repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateTestSupportMethodActionTest.kt
|
4
|
1538
|
// 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.codeInsight.generate
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateTestSupportActionBase
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
abstract class AbstractGenerateTestSupportMethodActionTest : AbstractCodeInsightActionTest() {
override fun createAction(fileText: String) = (super.createAction(fileText) as KotlinGenerateTestSupportActionBase).apply {
testFrameworkToUse = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// TEST_FRAMEWORK:")
}
override fun getProjectDescriptor(): LightProjectDescriptor = TEST_ROOT_PROJECT_DESCRIPTOR
companion object {
val TEST_ROOT_PROJECT_DESCRIPTOR = object : LightProjectDescriptor() {
override fun getModuleTypeId(): String = ModuleTypeId.JAVA_MODULE
override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk18()
override fun getSourceRootType(): JpsModuleSourceRootType<*> = JavaSourceRootType.TEST_SOURCE
}
}
}
|
apache-2.0
|
6b80cc23c0669e9175d0d2417a7ed849
| 52.068966 | 158 | 0.797789 | 5.126667 | false | true | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/gallery/MediaGallerySelectedItem.kt
|
2
|
1989
|
package org.thoughtcrime.securesms.mediasend.v2.gallery
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader
import org.thoughtcrime.securesms.util.MediaUtil
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
typealias OnSelectedMediaClicked = (Media) -> Unit
object MediaGallerySelectedItem {
fun register(mappingAdapter: MappingAdapter, onSelectedMediaClicked: OnSelectedMediaClicked) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory({ ViewHolder(it, onSelectedMediaClicked) }, R.layout.v2_media_selection_item))
}
class Model(val media: Media) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean {
return media.uri == newItem.media.uri
}
override fun areContentsTheSame(newItem: Model): Boolean {
return media.uri == newItem.media.uri
}
}
class ViewHolder(itemView: View, private val onSelectedMediaClicked: OnSelectedMediaClicked) : MappingViewHolder<Model>(itemView) {
private val imageView: ImageView = itemView.findViewById(R.id.media_selection_image)
private val videoOverlay: ImageView = itemView.findViewById(R.id.media_selection_play_overlay)
override fun bind(model: Model) {
Glide.with(imageView)
.load(DecryptableStreamUriLoader.DecryptableUri(model.media.uri))
.centerCrop()
.into(imageView)
videoOverlay.visible = MediaUtil.isVideo(model.media.mimeType) && !model.media.isVideoGif
itemView.setOnClickListener { onSelectedMediaClicked(model.media) }
}
}
}
|
gpl-3.0
|
6c1e5bf084688e03f58aaa319439e89d
| 39.591837 | 146 | 0.78733 | 4.286638 | false | false | false | false |
yongce/AndroidLib
|
baseLib/src/main/java/me/ycdev/android/lib/common/packets/PacketsWorker.kt
|
1
|
1680
|
package me.ycdev.android.lib.common.packets
import androidx.annotation.VisibleForTesting
import timber.log.Timber
import java.nio.ByteBuffer
import java.nio.ByteOrder
abstract class PacketsWorker(
private val ownerTag: String,
protected val callback: ParserCallback
) {
var maxPacketSize: Int = 0
set(value) {
if (value < MAX_PACKET_SIZE_MIN) {
throw PacketsException("The value ($value) for maxPacketSize is too small.")
}
if (debugLog) {
Timber.tag(ownerTag).d("setMaxPacketSize: %d", value)
}
field = value
}
var debugLog = false
@VisibleForTesting
internal var parserState = ParserState.HEADER_MAGIC
protected var readBuffer: ByteBuffer
init {
readBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE).order(ByteOrder.LITTLE_ENDIAN)
}
fun reset() {
parserState = ParserState.HEADER_MAGIC
readBuffer.clear()
}
abstract fun packetData(data: ByteArray): List<ByteArray>
abstract fun parsePackets(data: ByteArray)
interface ParserCallback {
fun onDataParsed(data: ByteArray)
}
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal enum class ParserState {
HEADER_MAGIC,
VERSION,
NUMBER,
DATA_CRC,
DATA_SIZE,
DATA
}
object Version {
const val UNKNOWN: Byte = 0
const val V1: Byte = 1
const val V2: Byte = 2
const val V3: Byte = 3
}
companion object {
const val MAX_PACKET_SIZE_MIN = 20
private const val DEFAULT_BUFFER_SIZE = 1024
}
}
|
apache-2.0
|
0dc51cddc09afd8db43d3eeac57f9aa5
| 24.454545 | 92 | 0.625595 | 4.421053 | false | true | false | false |
ktorio/ktor
|
ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/ProxySupportCommon.kt
|
1
|
1016
|
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.darwin
import io.ktor.http.*
import platform.Foundation.*
private const val HTTP_ENABLE_KEY = "HTTPEnable"
private const val HTTP_PROXY_KEY = "HTTPProxy"
private const val HTTP_PORT_KEY = "HTTPPort"
internal fun NSURLSessionConfiguration.setupProxy(config: DarwinClientEngineConfig) {
val proxy = config.proxy ?: return
val url = proxy.url
when (url.protocol) {
URLProtocol.HTTP -> setupHttpProxy(url)
URLProtocol.HTTPS -> setupHttpProxy(url)
// URLProtocol.SOCKS -> setupSocksProxy(url)
else -> error("Proxy type ${url.protocol.name} is unsupported by Darwin client engine.")
}
}
internal fun NSURLSessionConfiguration.setupHttpProxy(url: Url) {
connectionProxyDictionary = mapOf<Any?, Any?>(
HTTP_ENABLE_KEY to 1,
HTTP_PROXY_KEY to url.host,
HTTP_PORT_KEY to url.port
)
}
|
apache-2.0
|
cc1695b37008bb4d3fe858aae59e96b3
| 30.75 | 119 | 0.704724 | 3.762963 | false | true | false | false |
robnixon/ComputingTutorAndroidApp
|
app/src/main/java/net/computingtutor/robert/computingtutor/PostfixConverter.kt
|
1
|
3172
|
package net.computingtutor.robert.computingtutor
import java.util.*
import kotlin.collections.HashMap
class PostfixConverter(){
var inputString: String = ""
var postfix: Boolean = false
var postfixOutput: String = ""
var infixOutput: String = ""
val notOperands: Array<Char> = arrayOf('^', '*', '/', '~', '+', '-', '=', '(', ')')
fun editConverterInput(newInput: String, newPostfix: Boolean){
inputString = newInput
postfix = newPostfix
updateInfix()
updatePostfix()
}
private fun updateInfix(){
if (postfix) {
infixOutput = toInfix()
} else {
infixOutput = inputString
}
}
private fun updatePostfix() {
if (postfix) {
postfixOutput = inputString
} else {
postfixOutput = toPostfix()
}
}
private fun toInfix(): String {
val stack: Stack<String> = Stack()
for (character in inputString) {
if (character !in notOperands) {
stack.push(character.toString())
} else {
val tempExpressions: Array<String> = arrayOf(stack.pop(), stack.pop())
val expressionBuilder = StringBuilder()
expressionBuilder.append("(")
expressionBuilder.append(tempExpressions[1])
expressionBuilder.append(character.toString())
expressionBuilder.append(tempExpressions[0])
expressionBuilder.append(")")
stack.push(expressionBuilder.toString())
}
}
return stack.pop()
}
private fun getPrecedence(operator: Char, operators: HashMap<Char, Int>): Int {
var precedence = 3
if (operators.containsKey(operator)) {
precedence = operators.get(operator)!!.toInt()
}
return precedence
}
private fun toPostfix(): String {
/* An implementation Dijkstra's shunting-yard algorithm is used to convert infix to postfix */
val toPostfixOutput = StringBuilder()
val stack: Stack<Char> = Stack()
val operators: HashMap<Char, Int> = hashMapOf('^' to 1, '*' to 2, '/' to 2, '~' to 2, '+' to 3, '-' to 3, '=' to 5)
for (character in inputString) {
if (character !in notOperands){
toPostfixOutput.append(character)
} else if (operators.containsKey(character)) {
if (stack.isNotEmpty()){
while (getPrecedence(stack.peek(), operators) < getPrecedence(character, operators)) {
toPostfixOutput.append(stack.pop())
}
}
stack.push(character)
} else if (character == ')') {
while (stack.peek() != '(') {
toPostfixOutput.append(stack.pop())
}
stack.pop()
} else if (character == '(') {
stack.push(character)
}
}
while (!stack.isEmpty()) {
toPostfixOutput.append(stack.pop())
}
return toPostfixOutput.toString()
}
}
|
mit
|
93725c2865f001df505aa041df6f45ab
| 31.701031 | 123 | 0.535309 | 4.85758 | false | false | false | false |
roylanceMichael/yaclib
|
core/src/main/java/org/roylance/yaclib/core/services/java/server/JettyMainBuilder.kt
|
1
|
2788
|
package org.roylance.yaclib.core.services.java.server
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.JavaUtilities
class JettyMainBuilder(
private val projectInformation: YaclibModel.ProjectInformation) : IBuilder<YaclibModel.File> {
private val InitialTemplate = """${CommonTokens.AutoGeneratedAlteringOkay}
package ${projectInformation.mainDependency.group};
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import java.io.File;
public class Main {
public static void main(final String[] args) throws Exception {
// handle migrations when we start
final Server server = new Server(${buildPort()});
String fileLocation = "webapp";
if (!new File(fileLocation).exists()) {
fileLocation = "src/main/webapp";
}
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.setContextPath("/");
server.setHandler(context);
final ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/rest/*");
jerseyServlet.setInitOrder(1);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages","${projectInformation.mainDependency.group}");
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", "org.glassfish.jersey.media.multipart.MultiPartFeature");
final ServletHolder staticServlet = context.addServlet(DefaultServlet.class,"/*");
staticServlet.setInitParameter("resourceBase",fileLocation);
staticServlet.setInitParameter("pathInfoOnly","true");
try
{
server.start();
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}
"""
override fun build(): YaclibModel.File {
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(InitialTemplate)
.setFileName("Main")
.setFileExtension(YaclibModel.FileExtension.JAVA_EXT)
.setFileUpdateType(YaclibModel.FileUpdateType.WRITE_IF_NOT_EXISTS)
.setFullDirectoryLocation("src/main/java/" + JavaUtilities.convertGroupNameToFolders(
projectInformation.mainDependency.group))
return returnFile.build()
}
private fun buildPort(): String {
if (projectInformation.mainDependency.serverPort == 0) {
return "8080"
}
return projectInformation.mainDependency.serverPort.toString()
}
}
|
mit
|
7bf885cd6697314454ebaac61bb8b354
| 36.186667 | 140 | 0.719871 | 4.555556 | false | false | false | false |
airbnb/lottie-android
|
sample/src/main/kotlin/com/airbnb/lottie/samples/model/AnimationDataV2.kt
|
1
|
578
|
package com.airbnb.lottie.samples.model
import android.os.Parcelable
import com.airbnb.lottie.samples.utils.toColorIntSafe
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class AnimationDataV2(
@SerializedName("bg_color") val bgColor: String = "",
@SerializedName("file") val file: String = "",
@SerializedName("id") val id: Int,
@SerializedName("preview") val preview: String? = "",
@SerializedName("title") val title: String = "",
) : Parcelable {
val bgColorInt get() = bgColor.toColorIntSafe()
}
|
apache-2.0
|
581c1a46b0e377baa9dc233873a21c03
| 33.058824 | 57 | 0.731834 | 4.041958 | false | false | false | false |
acm-ndsu/ndacm-app
|
app/src/main/java/org/ndacm/ndacmapp/MenuActivity.kt
|
1
|
2569
|
package org.ndacm.ndacmapp
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.WindowCompat
class MenuActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
WindowCompat.setDecorFitsSystemWindows(window,false) //for edge-to-edge display
val menuButtonPreferences = findViewById<View>(R.id.menu_textview_preferences) as TextView
menuButtonPreferences.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"Preferences :)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonRoster = findViewById<View>(R.id.menu_textview_roster) as TextView
menuButtonRoster.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"Roster :)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonEvents = findViewById<View>(R.id.menu_textview_events) as TextView
menuButtonEvents.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"Events :)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonAbout = findViewById<View>(R.id.menu_textview_about) as TextView
menuButtonAbout.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"About Us :)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonCredit = findViewById<View>(R.id.menu_textview_credit) as TextView
menuButtonCredit.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"Credit System :)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonCamera = findViewById<View>(R.id.menu_textview_camera) as TextView
menuButtonCamera.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"ACM Camera:)",
Toast.LENGTH_SHORT
).show()
}
val menuButtonExtra = findViewById<View>(R.id.menu_textview_extra) as TextView
menuButtonExtra.setOnClickListener {
Toast.makeText(
this@MenuActivity,
"Extra button :o",
Toast.LENGTH_SHORT
).show()
}
}
}
|
gpl-2.0
|
8a5fc3a956c251a2788d563285f34138
| 32.376623 | 98 | 0.579603 | 5.027397 | false | false | false | false |
WilliamHester/Breadit-2
|
app/app/src/main/java/me/williamhester/reddit/apis/RedditClient.kt
|
1
|
3751
|
package me.williamhester.reddit.apis
import android.util.Log
import com.google.gson.JsonElement
import me.williamhester.reddit.BuildConfig
import me.williamhester.reddit.convert.RedditGsonConverter
import me.williamhester.reddit.messages.FailedRedditRequestMessage
import me.williamhester.reddit.messages.LogInFinishedMessage
import me.williamhester.reddit.messages.PostMessage
import me.williamhester.reddit.messages.VotableListMessage
import me.williamhester.reddit.models.Account
import me.williamhester.reddit.models.Submission
import me.williamhester.reddit.models.Subreddit
import org.greenrobot.eventbus.EventBus
import java.util.*
import kotlin.collections.ArrayList
/** Contains methods to communicate with Reddit */
class RedditClient(
private val redditGsonConverter: RedditGsonConverter,
private val requestBuilderFactory: RedditHttpRequest.Builder.Factory,
private val bus: EventBus
) {
fun getSubmissions(place: String, query: String?, after: String?) {
val queries = HashMap<String, String>()
if (after != null) {
queries["after"] = after
}
val callback = PostingCallback {
VotableListMessage(redditGsonConverter.toList<Submission>(it))
}
requestBuilderFactory.create(place, callback)
.queries(queries)
.build()
.execute()
}
fun getComments(permalink: String) {
val callback = PostingCallback { PostMessage(redditGsonConverter.toPost(it)) }
requestBuilderFactory.create(permalink, callback)
.build()
.execute()
}
fun getMySubreddits() {
getMySubreddits(null, ArrayList())
}
private fun getMySubreddits(after: String?, subreddits: List<Subreddit>) {
var subredditsList = subreddits
val innerCallback = object : RedditHttpRequestExecutor.JsonResponseCallback {
override fun onFailure(e: Exception) {
bus.post(FailedRedditRequestMessage())
Log.e("RedditClient", "Failed to communicate to Reddit", e)
}
override fun onResponse(element: JsonElement) {
val subList = redditGsonConverter.toList<Subreddit>(element)
subredditsList += subList
if (subList.size == 25) {
getMySubreddits(subList.last().name, subredditsList)
} else {
bus.post(subredditsList)
}
}
}
val queries = if (after != null) {
mapOf("after" to after)
} else {
null
}
requestBuilderFactory.create("subreddits/mine", innerCallback)
.queries(queries)
.build()
.execute()
}
fun logIn(code: String) {
val callback = PostingCallback { redditGsonConverter.toAccessTokenJson(it) }
requestBuilderFactory.create("api/v1/access_token", callback)
.params(mapOf(
"grant_type" to "authorization_code",
"code" to code,
"redirect_uri" to BuildConfig.REDDIT_REDIRECT_URI))
.build()
.execute()
}
fun getMe(account: Account) {
val callback = PostingCallback {
val meResponse = redditGsonConverter.toMeResponse(it)
account.username = meResponse.name
LogInFinishedMessage(account)
}
requestBuilderFactory.create("api/v1/me", callback)
.accessToken(account.accessToken)
.build()
.execute()
}
private inner class PostingCallback(
private val converter: (JsonElement) -> Any
) : RedditHttpRequestExecutor.JsonResponseCallback {
override fun onFailure(e: Exception) {
// Tell the user we had an error communicating with the network
bus.post(FailedRedditRequestMessage())
Log.e("RedditClient", "Failed to communicate to Reddit", e)
}
override fun onResponse(element: JsonElement) {
bus.post(converter.invoke(element))
}
}
}
|
apache-2.0
|
761e3372f34ec6ebb9e4f22840686be4
| 30.788136 | 82 | 0.696614 | 4.433806 | false | false | false | false |
wcaokaze/JapaneCraft
|
japanecraft-core/src/main/kotlin/com/wcaokaze/japanecraft/VariableExpander.kt
|
1
|
2617
|
package com.wcaokaze.japanecraft
class VariableExpander(strWithVars: String) {
private val tokenExpanderList = parse(strWithVars)
fun expand(variableMap: Map<String, String>): String {
return tokenExpanderList
.map { it.expand(variableMap) }
.fold(StringBuffer()) { buffer, token -> buffer.append(token) }
.toString()
}
private fun parse(str: String): List<TokenExpander> {
val identifierStartCharList = ('a'..'z') + ('A'..'Z') + '_'
val identifierPartCharList = identifierStartCharList + ('0'..'9')
fun Char.isIdentifierStart() = this in identifierStartCharList
fun Char.isIdentifierPart() = this in identifierPartCharList
return sequence {
val buffer = StringBuffer(str)
yieldToken@ while (buffer.isNotEmpty()) {
searchDollar@ for (i in 0 until buffer.lastIndex) {
if (buffer[i] != '$') continue@searchDollar
if (buffer[i + 1] == '{') {
val closeBraceIdx = buffer.indexOf("}")
if (closeBraceIdx == -1) continue@searchDollar
val constantStr = buffer.substring(0, i)
val variableName = buffer.substring(i + 2, closeBraceIdx)
.dropWhile { it == ' ' }
.dropLastWhile { it == ' ' }
yield(TokenExpander.ConstantString(constantStr))
yield(TokenExpander.VariableExpander(variableName))
buffer.delete(0, closeBraceIdx + 1)
continue@yieldToken
} else if (buffer[i + 1].isIdentifierStart()) {
yield(TokenExpander.ConstantString(buffer.substring(0, i)))
buffer.delete(0, i + 1)
val variableName
= buffer.takeWhile { it.isIdentifierPart() } .toString()
yield(TokenExpander.VariableExpander(variableName))
buffer.delete(0, variableName.length)
continue@yieldToken
}
}
yield(TokenExpander.ConstantString(buffer.toString()))
buffer.delete(0, buffer.length)
}
} .toList()
}
private sealed class TokenExpander {
abstract fun expand(variableMap: Map<String, String>): String
class ConstantString(private val str: String) : TokenExpander() {
override fun expand(variableMap: Map<String, String>): String {
return str
}
}
class VariableExpander(private val variableName: String) : TokenExpander() {
override fun expand(variableMap: Map<String, String>): String {
return variableMap.getOrDefault(variableName, "\${$variableName}")
}
}
}
}
|
mit
|
05704e23c185a91679d87a77d0fc2be0
| 32.987013 | 80 | 0.610241 | 4.473504 | false | false | false | false |
simplifycom/simplify-android-sdk-sample
|
simplify-android/src/main/kotlin/com/simplify/android/sdk/SimplifyMap.kt
|
2
|
12920
|
package com.simplify.android.sdk
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.ArrayList
class SimplifyMap : LinkedHashMap<String, Any> {
companion object {
private val arrayIndexPattern = "(.*)\\[(.*)\\]".toRegex()
/**
* Returns an identical copy of the map
*
* @param m The map to copy
* @return A copy of the original map
*/
@JvmStatic
fun normalize(m: MutableMap<String, Any>): MutableMap<String, Any> {
val pm = SimplifyMap()
m.keys.forEach { k ->
when (val v = m[k]) {
is List<*> -> pm.set(k, normalize(v as MutableList<Any>))
is Map<*, *> -> pm.set(k, normalize(v as MutableMap<String, Any>))
is String, is Double, is Float, is Number, is Boolean -> pm.set(k, v)
else -> pm.set(k, v.toString())
}
}
return pm
}
@JvmStatic
private fun normalize(l: MutableList<Any>): MutableList<Any> {
val pl = ArrayList<Any>()
l.forEach {v ->
when (v) {
is List<*> -> pl.add(normalize(v as MutableList<Any>))
is Map<*, *> -> pl.add(normalize(v as MutableMap<String, Any>))
is String, is Double, is Float, is Number, is Boolean -> pl.add(v)
else -> pl.add(v.toString())
}
}
return pl
}
}
/**
* Constructs an empty map with the default capacity and load factor.
*/
constructor() : super()
/**
* Constructs an empty map with the specified capacity and default load factor.
*
* @param initialCapacity the initial capacity
*/
constructor(initialCapacity: Int) : super(initialCapacity)
/**
* Constructs an empty map with the specified capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
*/
constructor(initialCapacity: Int, loadFactor: Float) : super(initialCapacity, loadFactor)
/**
* Constructs a map with the same mappings as in the specifed map.
*
* @param map the map whose mappings are to be placed in this map
*/
constructor(map: Map<String, Any>) : super(map)
/**
* Constructs a map based of the speficied JSON string.
*
* @param jsonMapString the JSON string used to construct the map
*/
constructor(jsonMapString: String?) : super() {
val map = Gson().fromJson<Map<out String, Any>>(jsonMapString, object : TypeToken<Map<out String, Any>>() {}.type)
putAll(map)
}
/**
* Constructs a map with an initial mapping of keyPath to value.
*
* @param keyPath key path with which the specified value is to be associated.
* @param value value to be associated with the specified key path.
*/
constructor(keyPath: String, value: Any) {
put(keyPath, value)
}
/**
* Associates the specified value to the specified key path.
*
* @param key key path to which the specified value is to be associated.
* @param value the value which is to be associated with the specified key path.
* @throws IllegalArgumentException if part of the key path does not match the expected type.
* @throws IndexOutOfBoundsException if using an array index in the key path is out of bounds.
*/
override fun put(key: String, value: Any): Any? {
val properties = key.split("\\.".toRegex())
var destinationObject: MutableMap<String, Any> = this
if (properties.size > 1) {
for (i in 0 until properties.size - 1) {
val property = properties[i]
destinationObject = when {
property.contains("[") -> getDestinationMap(property, destinationObject, i == properties.size - 1)
else -> getPropertyMapFrom(property, destinationObject)
}
}
} else if (key.contains("[")) {
destinationObject = getDestinationMap(key, this, true)
}
// TODO: need to take care of the case where we are inserting a value into an array rather than
// map ( eg map.put("a[2]", 123);
return when {
destinationObject === this -> super.put(key, value!!)
value is Map<*, *> -> { // if putting a map, call put all
destinationObject.clear()
val m = SimplifyMap()
m.putAll(value as Map<out String, Any>)
destinationObject[properties[properties.size - 1]] = m
destinationObject
}
else -> destinationObject.put(properties[properties.size - 1], value!!)
}
}
/**
* Associates the specified value to the specified key path and returns a reference to
* this map.
*
* @param keyPath key path to which the specified value is to be associated.
* @param value the value which is to be associated with the specified key path.
* @return this map
* @throws IllegalArgumentException if part of the key path does not match the expected type.
* @throws IndexOutOfBoundsException if using an array index in the key path is out of bounds.
*/
fun set(keyPath: String, value: Any): SimplifyMap {
put(keyPath, value)
return this
}
/**
* Returns the value associated with the specified key path or null if there is no associated value.
*
* @param keyPath key path whose associated value is to be returned
* @return the value to which the specified key is mapped
* @throws IllegalArgumentException if part of the key path does not match the expected type.
* @throws IndexOutOfBoundsException if using an array index in the key path is out of bounds.
*/
override fun get(key: String): Any? {
val keys = key.split("\\.".toRegex())
if (keys.size <= 1) {
return arrayIndexPattern.find(keys[0])?.groupValues?.let { groups ->
val k = groups[1]
val o = super.get(k) as? List<*>
?: throw IllegalArgumentException("Property '$k' is not an array")
val l = o as List<Map<String, Any>>
//get last item if none specified
val index = if (groups[2].isNotEmpty()) {
Integer.parseInt(groups[2])
} else l.size - 1
return l[index]
} ?: super.get(keys[0])
}
val map = findLastMapInKeyPath(key) // handles keyPaths beyond 'root' keyPath. i.e. "x.y OR x.y[].z, etc."
// retrieve the value at the end of the object path i.e. x.y.z, this retrieves whatever is in 'z'
return map!!.get(keys[keys.size - 1])
}
/**
* Returns true if there is a value associated with the specified key path.
*
* @param key key path whose associated value is to be tested
* @return true if this map contains an value associated with the specified key path
* @throws IllegalArgumentException if part of the key path does not match the expected type.
* @throws IndexOutOfBoundsException if using an array index in the key path is out of bounds.
*/
override fun containsKey(key: String): Boolean {
val keys = key.split("\\.".toRegex())
if (keys.size <= 1) {
return arrayIndexPattern.find(keys[0])?.groupValues?.let { groups ->
val k = groups[1]
val o = super.get(k) as? MutableList<*>
?: throw IllegalArgumentException("Property '$k' is not an array") // get the list from the map
val l = o as MutableList<MutableMap<String, Any>> // get the list from the map
val index: Int = if (groups[2].isNotEmpty()) Integer.parseInt(groups[2]) else l.size - 1
index >= 0 && index < l.size
} ?: super.containsKey(keys[0])
}
val map = findLastMapInKeyPath(key) ?: return false
return map.containsKey(keys[keys.size - 1])
}
/**
* Removes the value associated with the specified key path from the map.
*
* @param key key path whose associated value is to be removed
* @throws IllegalArgumentException if part of the key path does not match the expected type.
* @throws IndexOutOfBoundsException if using an array index in the key path is out of bounds.
*/
override fun remove(key: String): Any? {
val keys = key.split("\\.".toRegex())
if (keys.size <= 1) {
return arrayIndexPattern.find(keys[0])?.groupValues?.let { groups ->
val k = groups[1]
val o = super.get(k) as? MutableList<*>
?: throw IllegalArgumentException("Property '$k' is not an array") // get the list from the map
val l = o as MutableList<MutableMap<String, Any>> // get the list from the map
val index: Int = if (groups[2].isNotEmpty()) Integer.parseInt(groups[2]) else l.size - 1
l.removeAt(index)
} ?: super.remove(keys[0])
}
val map = findLastMapInKeyPath(key)
return map!!.remove(keys[keys.size - 1])
}
private fun findLastMapInKeyPath(keyPath: String): MutableMap<String, Any>? {
val keys = keyPath.split("\\.".toRegex())
var map: MutableMap<String, Any>? = null
for (i in 0..keys.size - 2) {
var thisKey = keys[i]
map = arrayIndexPattern.find(keys[i])?.groupValues?.let { groups ->
thisKey = groups[1]
val o: Any? = (if (null == map) super.get(thisKey) else map!![thisKey]) as? List<*>
?: throw IllegalArgumentException("Property '$thisKey' is not an array")
val l = o as MutableList<MutableMap<String, Any>>?
var index: Int? = l!!.size - 1 //get last item if none specified
if ("" != groups[2]) {
index = Integer.parseInt(groups[2])
}
l[index!!]
} ?: if (map == null) {
super.get(thisKey) as MutableMap<String, Any>?
} else {
map[thisKey] as MutableMap<String, Any>?
}
}
return map
}
private fun getDestinationMap(property: String, destinationObject: MutableMap<String, Any>, createMap: Boolean): MutableMap<String, Any> {
return arrayIndexPattern.find(property)?.groupValues?.let { groups ->
val propName = groups[1]
val index: Int? = if (groups[2].isNotEmpty()) {
Integer.parseInt(groups[2])
} else null
findOrAddToList(destinationObject, propName, index, createMap)
} ?: destinationObject
}
private fun findOrAddToList(destinationObject: MutableMap<String, Any>, propName: String, index: Int?, createMap: Boolean): MutableMap<String, Any> {
var destObject = destinationObject
var list = ArrayList<MutableMap<String, Any>>()
// find existing list or put the new list
if (destObject.containsKey(propName)) {
val o = destObject[propName] as? List<*>
?: throw IllegalArgumentException("Property '$propName' is not an array")
list = o as ArrayList<MutableMap<String, Any>>
} else {
destObject[propName] = list
}
// get the existing object in the list at the index
var propertyValue: MutableMap<String, Any>? = null
if (index != null && list.size > index) {
propertyValue = list[index]
}
// no object at the index, create a new map and add it
if (null == propertyValue) {
propertyValue = java.util.LinkedHashMap()
if (null == index) {
list.add(propertyValue)
} else {
list.add(index, propertyValue)
}
}
// return the map retrieved from or added to the list
destObject = propertyValue
return destObject
}
private fun getPropertyMapFrom(property: String, obj: MutableMap<String, Any>): MutableMap<String, Any> {
// create a new map at the key specified if it doesn't already exist
if (!obj.containsKey(property)) {
val value = LinkedHashMap<String, Any>()
obj[property] = value
}
val o = obj[property]
return if (o is Map<*, *>) {
o as MutableMap<String, Any>
} else {
throw IllegalArgumentException("cannot change nested property to map")
}
}
}
|
mit
|
3735f192a82a83a7096f12e4f1be0cbe
| 37.455357 | 153 | 0.572988 | 4.536517 | false | false | false | false |
saffih/ElmDroid
|
app/src/main/java/elmdroid/elmdroid/example3/MapsActivity.kt
|
1
|
8096
|
package elmdroid.elmdroid.example3
import android.Manifest
import android.location.Location
import android.os.Bundle
import android.os.Message
import android.support.v4.app.FragmentActivity
import android.widget.Toast
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import elmdroid.elmdroid.R
import saffih.elmdroid.ElmBase
import saffih.elmdroid.gps.GpsElmServiceClient
import saffih.elmdroid.gps.GpsLocalService
import saffih.elmdroid.permissionGranted
import saffih.elmdroid.post
import saffih.elmdroid.service.LocalServiceClient
import saffih.elmdroid.service.client.MService
import saffih.elmdroid.gps.child.Msg as GpsMsg
import saffih.elmdroid.gps.child.Msg.Api as GpsMsgApi
import saffih.elmdroid.service.client.Msg as ClientServiceMsg
class MapsActivity : FragmentActivity() {
val app = ElmApp(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
app.onCreate()
}
override fun onStart() {
super.onStart()
app.onCreate()
}
override fun onStop() {
super.onStop()
app.onDestroy()
}
}
sealed class Msg {
object Init : Msg()
sealed class Activity : Msg() {
sealed class Map : Activity() {
class Ready(val googleMap: GoogleMap) : Map()
class AddMarker(val markerOptions: MarkerOptions) : Map()
class MoveCamera(val cameraUpdate: CameraUpdate) : Map()
}
class GotLocation(val location: Location) : Activity()
}
}
/**
* Model representing the state of the system
* All Model types are Prefixed with M
*/
data class Model(val activity: MActivity = MActivity())
data class MActivity(val mMap: MMap = MMap())
data class MMap(val googleMap: GoogleMap? = null,
val markers: Set<MarkerOptions> = setOf<MarkerOptions>(),
val camera: CameraUpdate? = null)
class ElmApp(override val me: FragmentActivity) : ElmBase<Model, Msg>(me), OnMapReadyCallback {
fun toast(txt: String, duration: Int = Toast.LENGTH_SHORT) {
me.post({ Toast.makeText(me, txt, duration).show() })
}
fun getPerm(): Boolean {
val perm = Manifest.permission.ACCESS_FINE_LOCATION
return me.permissionGranted(perm)
}
// example using local service
val localServiceGps = object :
LocalServiceClient<GpsLocalService>(me, localserviceJavaClass = GpsLocalService::class.java) {
override fun onReceive(payload: Message?) {
val location = payload?.obj as Location
post { dispatch(Msg.Activity.GotLocation(location)) }
}
override fun onConnected() {
super.onConnected()
post {
toast("Using local service")
fun must_succeed() {
val sbound = bound!!
if (getPerm()) {
sbound.request()
} else {
post { must_succeed() }
}
}
must_succeed()
}
}
}
// example using service
val serviceGps = object : GpsElmServiceClient(me) {
override fun onAPI(msg: GpsMsgApi) {
when (msg) {
is saffih.elmdroid.gps.child.Msg.Api.Reply.NotifyLocation ->
post { dispatch(Msg.Activity.GotLocation(msg.location)) }
}
}
override fun onConnected(msg: MService) {
post {
toast("Using service")
fun must_succeed() {
if (getPerm()) {
request(saffih.elmdroid.gps.child.Msg.Api.Request.Location())
} else {
post { must_succeed() }
}
}
must_succeed()
}
}
}
val useLocal by lazy {
val action = me.intent.action
action == "localService"
}
override fun onCreate() {
super.onCreate()
// Bind to the service
if (useLocal) localServiceGps.onCreate()
else serviceGps.onCreate()
}
override fun onDestroy() {
// Unbind from the service
if (useLocal) localServiceGps.onDestroy()
else serviceGps.onDestroy()
super.onDestroy()
}
override fun init(): Model {
dispatch(Msg.Init)
return Model()
}
override fun update(msg: Msg, model: Model): Model {
return when (msg) {
is Msg.Init -> {
model
}
is Msg.Activity -> {
val activityModel =
update(msg, model.activity)
model.copy(activity = activityModel)
}
}
}
fun update(msg: Msg.Activity, model: MActivity): MActivity {
return when (msg) {
is Msg.Activity.Map -> {
val mapModel = update(msg, model.mMap)
model.copy(mMap = mapModel)
}
is Msg.Activity.GotLocation -> {
val m = update(msg, model.mMap)
model.copy(mMap = m)
}
}
}
private fun update(msg: Msg.Activity.GotLocation, model: MMap): MMap {
val here = LatLng(msg.location.latitude, msg.location.longitude)
return model.copy(markers = model.markers + MarkerOptions().position(here).title("you are here"),
camera = (CameraUpdateFactory.newLatLng(here)))
}
fun update(msg: Msg.Activity.Map, model: MMap): MMap {
return when (msg) {
is Msg.Activity.Map.Ready -> {
model.copy(googleMap = msg.googleMap)
}
is Msg.Activity.Map.AddMarker -> {
model.copy(markers = model.markers + msg.markerOptions)
}
is Msg.Activity.Map.MoveCamera -> {
model.copy(camera = msg.cameraUpdate)
}
}
}
override fun view(model: Model, pre: Model?) {
checkView({}, model, pre) {
view(model.activity, pre?.activity)
}
}
private fun view(model: MActivity, pre: MActivity?) {
val setup = {
me.setContentView(R.layout.activity_maps)
}
checkView(setup, model, pre) {
view(model.mMap, pre?.mMap)
}
}
private fun view(model: MMap, pre: MMap?) {
val setup = {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = me.supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
checkView(setup, model, pre) {
checkView({}, model.markers, pre?.markers) {
model.markers.forEach {
model.googleMap!!.addMarker(it)
}
}
checkView({}, model.camera, pre?.camera) {
model.googleMap!!.moveCamera(model.camera)
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
dispatch(Msg.Activity.Map.Ready(googleMap))
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
dispatch(Msg.Activity.Map.AddMarker(MarkerOptions().position(sydney).title("Marker in Sydney")))
dispatch(Msg.Activity.Map.MoveCamera(CameraUpdateFactory.newLatLng(sydney)))
}
}
|
apache-2.0
|
dad606c00a15287d9b84af4425bc1d62
| 30.874016 | 106 | 0.581645 | 4.485319 | false | false | false | false |
dkandalov/katas
|
kotlin/src/katas/kotlin/leetcode/combinations/CombinationsTests.kt
|
1
|
1606
|
package katas.kotlin.leetcode.combinations
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// https://leetcode.com/problems/combinations ✅
//
// Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
// You may return the answer in any order.
// Constraints:
// 1 <= n <= 20
// 1 <= k <= n
//
// Example 1:
// Input: n = 4, k = 2
// Output:
// [
// [2,4],
// [3,4],
// [2,3],
// [1,2],
// [1,3],
// [1,4],
// ]
//
// Example 2:
// Input: n = 1, k = 1
// Output: [[1]]
//
fun combine(n: Int, k: Int): List<List<Int>> {
require(n in 1..20 && k in 1..n)
return subsetsOf(1..n, maxSize = k)
}
private fun subsetsOf(range: IntRange, maxSize: Int): List<List<Int>> {
if (maxSize == 0) return listOf(emptyList())
if (range.size == maxSize) return listOf(range.toList())
return subsetsOf(range.shiftStart(), maxSize) +
subsetsOf(range.shiftStart(), maxSize - 1).map { listOf(range.first) + it }
}
private fun IntRange.shiftStart() = IntRange(start + 1, endInclusive)
private val IntRange.size: Int get() = endInclusive + 1 - start
class CombinationsTests {
@Test fun `some examples`() {
combine(n = 1, k = 1) shouldEqual listOf(listOf(1))
combine(n = 2, k = 1) shouldEqual listOf(listOf(2), listOf(1))
combine(n = 2, k = 2) shouldEqual listOf(listOf(1, 2))
combine(n = 4, k = 2) shouldEqual listOf(
listOf(3, 4),
listOf(2, 4),
listOf(2, 3),
listOf(1, 4),
listOf(1, 3),
listOf(1, 2)
)
}
}
|
unlicense
|
4e99f657b86ff1700db454340d42f337
| 24.887097 | 92 | 0.571696 | 3.114563 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardActions.kt
|
1
|
27977
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.DvcsUtil.disableActionIfAnyRepositoryIsFresh
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.dvcs.diverged
import com.intellij.dvcs.getCommonCurrentBranch
import com.intellij.dvcs.repo.Repository
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.vcs.log.VcsLogProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.actions.BooleanPropertyToggleAction
import com.intellij.vcs.log.util.VcsLogUtil.HEAD
import git4idea.GitUtil
import git4idea.actions.GitFetch
import git4idea.actions.branch.GitBranchActionsUtil.calculateNewBranchInitialName
import git4idea.branch.GitBranchType
import git4idea.branch.GitBrancher
import git4idea.config.GitVcsSettings
import git4idea.fetch.GitFetchResult
import git4idea.fetch.GitFetchSupport
import git4idea.i18n.GitBundle.message
import git4idea.i18n.GitBundleExtensions.messagePointer
import git4idea.isRemoteBranchProtected
import git4idea.remote.editRemote
import git4idea.remote.removeRemotes
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.branch.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.util.function.Supplier
import javax.swing.Icon
internal object BranchesDashboardActions {
class BranchesTreeActionGroup(private val project: Project, private val tree: FilteringBranchesTree) : ActionGroup(), DumbAware {
init {
templatePresentation.isPopupGroup = true
templatePresentation.isHideGroupIfEmpty = true
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
BranchActionsBuilder(project, tree).build()?.getChildren(e) ?: AnAction.EMPTY_ARRAY
}
class MultipleLocalBranchActions : ActionGroup(), DumbAware {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayOf(ShowArbitraryBranchesDiffAction(), UpdateSelectedBranchAction(), DeleteBranchAction())
}
class CurrentBranchActions(project: Project,
repositories: List<GitRepository>,
branchName: String,
selectedRepository: GitRepository)
: GitBranchPopupActions.CurrentBranchActions(project, repositories, branchName, selectedRepository) {
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
val children = arrayListOf<AnAction>(*super.getChildren(e))
if (myRepositories.diverged()) {
children.add(1, CheckoutAction(myProject, myRepositories, myBranchName))
}
return children.toTypedArray()
}
}
class LocalBranchActions(project: Project,
repositories: List<GitRepository>,
branchName: String,
selectedRepository: GitRepository)
: GitBranchPopupActions.LocalBranchActions(project, repositories, branchName, selectedRepository) {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayListOf<AnAction>(*super.getChildren(e)).toTypedArray()
}
class RemoteBranchActions(project: Project,
repositories: List<GitRepository>,
@NonNls branchName: String,
selectedRepository: GitRepository)
: GitBranchPopupActions.RemoteBranchActions(project, repositories, branchName, selectedRepository) {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayListOf<AnAction>(*super.getChildren(e)).toTypedArray()
}
class GroupActions : ActionGroup(), DumbAware {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayListOf<AnAction>(EditRemoteAction(), RemoveRemoteAction()).toTypedArray()
}
class MultipleGroupActions : ActionGroup(), DumbAware {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayListOf<AnAction>(RemoveRemoteAction()).toTypedArray()
}
class RemoteGlobalActions : ActionGroup(), DumbAware {
override fun getChildren(e: AnActionEvent?): Array<AnAction> =
arrayListOf<AnAction>(ActionManager.getInstance().getAction("Git.Configure.Remotes")).toTypedArray()
}
class BranchActionsBuilder(private val project: Project, private val tree: FilteringBranchesTree) {
fun build(): ActionGroup? {
val selectedBranches = tree.getSelectedBranches()
val multipleBranchSelection = selectedBranches.size > 1
val guessRepo = DvcsUtil.guessCurrentRepositoryQuick(project, GitUtil.getRepositoryManager(project),
GitVcsSettings.getInstance(project).recentRootPath) ?: return null
if (multipleBranchSelection) {
return MultipleLocalBranchActions()
}
val branchInfo = selectedBranches.singleOrNull()
val headSelected = tree.getSelectedBranchFilters().contains(HEAD)
if (branchInfo != null && !headSelected) {
val selectedRepositories = tree.getSelectedRepositories(branchInfo)
val selectedRepository = selectedRepositories.singleOrNull() ?: guessRepo
return when {
branchInfo.isCurrent -> CurrentBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository)
branchInfo.isLocal -> LocalBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository)
else -> RemoteBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository)
}
}
val selectedRemotes = tree.getSelectedRemotes()
if (selectedRemotes.size == 1) {
return GroupActions()
}
else if (selectedRemotes.isNotEmpty()) {
return MultipleGroupActions()
}
val selectedBranchNodes = tree.getSelectedBranchNodes()
if (selectedBranchNodes.size == 1 && selectedBranchNodes.first().type == NodeType.REMOTE_ROOT) {
return RemoteGlobalActions()
}
val currentBranchName = guessRepo.currentBranchName
if (currentBranchName != null && headSelected) {
return CurrentBranchActions(project, listOf(guessRepo), currentBranchName, guessRepo)
}
return null
}
}
class NewBranchAction : BranchesActionBase({ DvcsBundle.message("new.branch.action.text") },
{ DvcsBundle.message("new.branch.action.text") },
com.intellij.dvcs.ui.NewBranchAction.icon) {
override fun update(e: AnActionEvent) {
val branchFilters = e.getData(GIT_BRANCH_FILTERS)
if (branchFilters != null && branchFilters.contains(HEAD)) {
e.presentation.isEnabled = true
}
else {
super.update(e)
}
}
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
if (branches.size > 1) {
e.presentation.isEnabled = false
e.presentation.description = message("action.Git.New.Branch.description")
return
}
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = branches.flatMap(controller::getSelectedRepositories).distinct()
disableActionIfAnyRepositoryIsFresh(e, repositories, DvcsBundle.message("action.not.possible.in.fresh.repo.new.branch"))
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val branchFilters = e.getData(GIT_BRANCH_FILTERS)
if (branchFilters != null && branchFilters.contains(HEAD)) {
val repositories = GitRepositoryManager.getInstance(project).repositories
createOrCheckoutNewBranch(project, repositories, HEAD, initialName = repositories.getCommonCurrentBranch())
}
else {
val branches = e.getData(GIT_BRANCHES)!!
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = branches.flatMap(controller::getSelectedRepositories).distinct()
val branchInfo = branches.first()
val branchName = branchInfo.branchName
createOrCheckoutNewBranch(project, repositories, "$branchName^0",
message("action.Git.New.Branch.dialog.title", branchName),
calculateNewBranchInitialName(branchName, !branchInfo.isLocal))
}
}
}
class UpdateSelectedBranchAction : BranchesActionBase(text = messagePointer("action.Git.Update.Selected.text"),
icon = AllIcons.Actions.CheckOut) {
override fun update(e: AnActionEvent) {
val enabledAndVisible = e.project?.let(::hasRemotes) ?: false
e.presentation.isEnabledAndVisible = enabledAndVisible
if (enabledAndVisible) {
super.update(e)
}
}
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
val presentation = e.presentation
if (GitFetchSupport.fetchSupport(project).isFetchRunning) {
presentation.isEnabled = false
presentation.description = message("action.Git.Update.Selected.description.already.running")
return
}
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = branches.flatMap(controller::getSelectedRepositories).distinct()
val branchNames = branches.map(BranchInfo::branchName)
val updateMethodName = GitVcsSettings.getInstance(project).updateMethod.name.toLowerCase()
presentation.description = message("action.Git.Update.Selected.description", branches.size, updateMethodName)
val trackingInfosExist = isTrackingInfosExist(branchNames, repositories)
presentation.isEnabled = trackingInfosExist
if (!trackingInfosExist) {
presentation.description = message("action.Git.Update.Selected.description.tracking.not.configured", branches.size)
}
}
override fun actionPerformed(e: AnActionEvent) {
val branches = e.getData(GIT_BRANCHES)!!
val project = e.project!!
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = branches.flatMap(controller::getSelectedRepositories).distinct()
val branchNames = branches.map(BranchInfo::branchName)
updateBranches(project, repositories, branchNames)
}
}
class DeleteBranchAction : BranchesActionBase(icon = AllIcons.Actions.GC) {
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
e.presentation.text = message("action.Git.Delete.Branch.title", branches.size)
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val disabled =
branches.any { it.isCurrent || (!it.isLocal && isRemoteBranchProtected(controller.getSelectedRepositories(it), it.branchName)) }
e.presentation.isEnabled = !disabled
}
override fun actionPerformed(e: AnActionEvent) {
val branches = e.getData(GIT_BRANCHES)!!
val project = e.project!!
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
delete(project, branches, controller)
}
private fun delete(project: Project, branches: Collection<BranchInfo>, controller: BranchesDashboardController) {
val gitBrancher = GitBrancher.getInstance(project)
val (localBranches, remoteBranches) = branches.partition { it.isLocal && !it.isCurrent }
with(gitBrancher) {
val branchesToContainingRepositories: Map<String, List<GitRepository>> =
localBranches.associate { it.branchName to controller.getSelectedRepositories(it) }
val deleteRemoteBranches = {
deleteRemoteBranches(remoteBranches.map(BranchInfo::branchName), remoteBranches.flatMap(BranchInfo::repositories).distinct())
}
val localBranchNames = branchesToContainingRepositories.keys
if (localBranchNames.isNotEmpty()) { //delete local (possible tracked) branches first if any
deleteBranches(branchesToContainingRepositories, deleteRemoteBranches)
}
else {
deleteRemoteBranches()
}
}
}
}
class ShowBranchDiffAction : BranchesActionBase(text = messagePointer("action.Git.Compare.With.Current.title"),
icon = AllIcons.Actions.Diff) {
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
if (branches.none { !it.isCurrent }) {
e.presentation.isEnabled = false
e.presentation.description = message("action.Git.Update.Selected.description.select.non.current")
}
}
override fun actionPerformed(e: AnActionEvent) {
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val branches = e.getData(GIT_BRANCHES)!!
val project = e.project!!
val gitBrancher = GitBrancher.getInstance(project)
for (branch in branches.filterNot(BranchInfo::isCurrent)) {
gitBrancher.compare(branch.branchName, controller.getSelectedRepositories(branch))
}
}
}
class ShowArbitraryBranchesDiffAction : BranchesActionBase(text = messagePointer("action.Git.Compare.Selected.title"),
icon = AllIcons.Actions.Diff) {
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
if (branches.size != 2) {
e.presentation.isEnabledAndVisible = false
e.presentation.description = ""
}
else {
e.presentation.description = message("action.Git.Compare.Selected.description")
val branchOne = branches.elementAt(0)
val branchTwo = branches.elementAt(1)
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
if (branchOne.branchName == branchTwo.branchName || controller.commonRepositories(branchOne, branchTwo).isEmpty()) {
e.presentation.isEnabled = false
e.presentation.description = message("action.Git.Compare.Selected.description.disabled")
}
}
}
override fun actionPerformed(e: AnActionEvent) {
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val branches = e.getData(GIT_BRANCHES)!!
val branchOne = branches.elementAt(0)
val branchTwo = branches.elementAt(1)
val commonRepositories = controller.commonRepositories(branchOne, branchTwo)
GitBrancher.getInstance(e.project!!).compareAny(branchOne.branchName, branchTwo.branchName, commonRepositories.toList())
}
private fun BranchesDashboardController.commonRepositories(branchOne: BranchInfo, branchTwo: BranchInfo): Collection<GitRepository>{
return getSelectedRepositories(branchOne) intersect getSelectedRepositories(branchTwo)
}
}
class ShowMyBranchesAction(private val uiController: BranchesDashboardController)
: ToggleAction(messagePointer("action.Git.Show.My.Branches.title"), AllIcons.Actions.Find), DumbAware {
override fun isSelected(e: AnActionEvent) = uiController.showOnlyMy
override fun setSelected(e: AnActionEvent, state: Boolean) {
uiController.showOnlyMy = state
}
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.getData(CommonDataKeys.PROJECT)
if (project == null) {
e.presentation.isEnabled = false
return
}
val log = VcsProjectLog.getInstance(project)
val supportsIndexing = log.dataManager?.logProviders?.all {
VcsLogProperties.SUPPORTS_INDEXING.getOrDefault(it.value)
} ?: false
val isGraphReady = log.dataManager?.dataPack?.isFull ?: false
val allRootsIndexed = GitRepositoryManager.getInstance(project).repositories.all {
log.dataManager?.index?.isIndexed(it.root) ?: false
}
e.presentation.isEnabled = supportsIndexing && isGraphReady && allRootsIndexed
e.presentation.description = when {
!supportsIndexing -> {
message("action.Git.Show.My.Branches.description.not.support.indexing")
}
!allRootsIndexed -> {
message("action.Git.Show.My.Branches.description.not.all.roots.indexed")
}
!isGraphReady -> {
message("action.Git.Show.My.Branches.description.not.graph.ready")
}
else -> {
message("action.Git.Show.My.Branches.description.is.my.branch")
}
}
}
}
class FetchAction(private val ui: BranchesDashboardUi) : GitFetch() {
override fun update(e: AnActionEvent) {
super.update(e)
with(e.presentation) {
text = message("action.Git.Fetch.title")
icon = AllIcons.Vcs.Fetch
description = ""
val project = e.project ?: return@with
if (GitFetchSupport.fetchSupport(project).isFetchRunning) {
isEnabled = false
description = message("action.Git.Fetch.description.fetch.in.progress")
}
}
}
override fun actionPerformed(e: AnActionEvent) {
ui.startLoadingBranches()
super.actionPerformed(e)
}
override fun onFetchFinished(result: GitFetchResult) {
ui.stopLoadingBranches()
}
}
class ToggleFavoriteAction : BranchesActionBase(text = messagePointer("action.Git.Toggle.Favorite.title"), icon = AllIcons.Nodes.Favorite) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val branches = e.getData(GIT_BRANCHES)!!
val gitBranchManager = project.service<GitBranchManager>()
for (branch in branches) {
val type = if (branch.isLocal) GitBranchType.LOCAL else GitBranchType.REMOTE
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = controller.getSelectedRepositories(branch)
for (repository in repositories) {
gitBranchManager.setFavorite(type, repository, branch.branchName, !branch.isFavorite)
}
}
}
}
class ChangeBranchFilterAction : BooleanPropertyToggleAction() {
override fun setSelected(e: AnActionEvent, state: Boolean) {
super.setSelected(e, state)
e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY] = false
}
override fun getProperty(): VcsLogUiProperties.VcsLogUiProperty<Boolean> = CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY
}
class NavigateLogToBranchAction : BooleanPropertyToggleAction() {
override fun isSelected(e: AnActionEvent): Boolean {
return super.isSelected(e) &&
!e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
super.setSelected(e, state)
e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY] = false
}
override fun getProperty(): VcsLogUiProperties.VcsLogUiProperty<Boolean> = NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY
}
class GroupingSettingsGroup: DefaultActionGroup(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.isPopupGroup = GroupBranchByRepositoryAction.isEnabledAndVisible(e)
}
}
class GroupBranchByDirectoryAction : GroupBranchAction(GroupingKey.GROUPING_BY_DIRECTORY) {
override fun update(e: AnActionEvent) {
super.update(e)
val groupByDirectory: Supplier<String> = DvcsBundle.messagePointer("action.text.branch.group.by.directory")
val groupingSeparator: () -> String = messagePointer("group.Git.Log.Branches.Grouping.Settings.text")
e.presentation.text =
if (GroupBranchByRepositoryAction.isEnabledAndVisible(e)) groupByDirectory.get() //NON-NLS
else groupingSeparator() + " " + groupByDirectory.get() //NON-NLS
}
}
class GroupBranchByRepositoryAction : GroupBranchAction(GroupingKey.GROUPING_BY_REPOSITORY) {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = isEnabledAndVisible(e)
}
companion object {
fun isEnabledAndVisible(e: AnActionEvent): Boolean =
e.project?.let(RepositoryChangesBrowserNode.Companion::getColorManager)?.hasMultiplePaths() ?: false
}
}
abstract class GroupBranchAction(key: GroupingKey) : BranchGroupingAction(key) {
override fun setSelected(e: AnActionEvent, key: GroupingKey, state: Boolean) {
e.getData(BRANCHES_UI_CONTROLLER)?.toggleGrouping(key, state)
}
}
class HideBranchesAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val properties = e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)
e.presentation.isEnabledAndVisible = properties != null && properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)
super.update(e)
}
override fun actionPerformed(e: AnActionEvent) {
val properties = e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)
if (properties != null && properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) {
properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, false)
}
}
}
class RemoveRemoteAction : RemoteActionBase() {
override fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {
e.presentation.text = message("action.Git.Log.Remove.Remote.text", selectedRemotes.size)
}
override fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {
for ((repository, remotes) in selectedRemotes) {
removeRemotes(service(), repository, remotes)
}
}
}
class EditRemoteAction : RemoteActionBase(messagePointer("action.Git.Log.Edit.Remote.text")) {
override fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {
if (selectedRemotes.size != 1) {
e.presentation.isEnabledAndVisible = false
}
}
override fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {
val (repository, remotes) = selectedRemotes.entries.first()
editRemote(service(), repository, remotes.first())
}
}
abstract class RemoteActionBase(@Nls(capitalization = Nls.Capitalization.Title) text: () -> String = { "" },
@Nls(capitalization = Nls.Capitalization.Sentence) private val description: () -> String = { "" },
icon: Icon? = null) :
DumbAwareAction(text, description, icon) {
open fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {}
abstract fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>)
override fun update(e: AnActionEvent) {
val project = e.project
val controller = e.getData(BRANCHES_UI_CONTROLLER)
val selectedRemotes = controller?.getSelectedRemotes() ?: emptyMap()
val enabled = project != null && selectedRemotes.isNotEmpty()
e.presentation.isEnabled = enabled
e.presentation.description = description()
if (enabled) {
update(e, project!!, selectedRemotes)
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val selectedRemotes = controller.getSelectedRemotes()
doAction(e, project, selectedRemotes)
}
}
abstract class BranchesActionBase(@Nls(capitalization = Nls.Capitalization.Title) text: () -> String = { "" },
@Nls(capitalization = Nls.Capitalization.Sentence) private val description: () -> String = { "" },
icon: Icon? = null) :
DumbAwareAction(text, description, icon) {
open fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {}
override fun update(e: AnActionEvent) {
val controller = e.getData(BRANCHES_UI_CONTROLLER)
val branches = e.getData(GIT_BRANCHES)
val project = e.project
val enabled = project != null && controller != null && !branches.isNullOrEmpty()
e.presentation.isEnabled = enabled
e.presentation.description = description()
if (enabled) {
update(e, project!!, branches!!)
}
}
}
class CheckoutSelectedBranchAction : BranchesActionBase() {
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
if (branches.size > 1) {
e.presentation.isEnabled = false
return
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val branch = e.getData(GIT_BRANCHES)!!.firstOrNull() ?: return
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = controller.getSelectedRepositories(branch)
if (branch.isLocal) {
GitBranchPopupActions.LocalBranchActions.CheckoutAction
.checkoutBranch(project, repositories, branch.branchName)
}
else {
GitBranchPopupActions.RemoteBranchActions.CheckoutRemoteBranchAction
.checkoutRemoteBranch(project, repositories, branch.branchName)
}
}
}
class UpdateBranchFilterInLogAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val branchFilters = e.getData(GIT_BRANCH_FILTERS)
val uiController = e.getData(BRANCHES_UI_CONTROLLER)
val project = e.project
val enabled = project != null && uiController != null && !branchFilters.isNullOrEmpty()
&& e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) is BranchesTreeComponent
e.presentation.isEnabled = enabled
}
override fun actionPerformed(e: AnActionEvent) {
e.getRequiredData(BRANCHES_UI_CONTROLLER).updateLogBranchFilter()
}
}
class NavigateLogToSelectedBranchAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val branchFilters = e.getData(GIT_BRANCH_FILTERS)
val uiController = e.getData(BRANCHES_UI_CONTROLLER)
val project = e.project
val visible = project != null && uiController != null
if (!visible) {
e.presentation.isEnabledAndVisible = visible
return
}
val enabled = branchFilters != null && branchFilters.size == 1
e.presentation.isEnabled = enabled
}
override fun actionPerformed(e: AnActionEvent) {
e.getRequiredData(BRANCHES_UI_CONTROLLER).navigateLogToSelectedBranch()
}
}
class RenameLocalBranch : BranchesActionBase() {
override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {
if (branches.size > 1) {
e.presentation.isEnabled = false
return
}
val branch = branches.first()
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = controller.getSelectedRepositories(branch)
if (!branch.isLocal || repositories.any(Repository::isFresh)) {
e.presentation.isEnabled = false
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val branch = e.getData(GIT_BRANCHES)!!.firstOrNull() ?: return
val controller = e.getData(BRANCHES_UI_CONTROLLER)!!
val repositories = controller.getSelectedRepositories(branch)
GitBranchPopupActions.LocalBranchActions.RenameBranchAction.rename(project, repositories, branch.branchName)
}
}
}
|
apache-2.0
|
b2da774e556289d7b78803313f26c59b
| 40.324963 | 142 | 0.698145 | 4.798799 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/watcher/FileContainerDescription.kt
|
8
|
4824
|
// 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.workspaceModel.ide.impl.legacyBridge.watcher
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.util.ArrayUtilRt.EMPTY_STRING_ARRAY
import com.intellij.util.containers.toArray
import com.intellij.util.io.URLUtil
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
class FileContainerDescription(val urls: List<VirtualFileUrl>, val jarDirectories: List<JarDirectoryDescription>) {
private val virtualFilePointersList = mutableSetOf<VirtualFilePointer>()
private val virtualFilePointerManager = VirtualFilePointerManager.getInstance()
@Volatile
private var timestampOfCachedFiles = -1L
@Volatile
private var cachedFilesList = arrayOf<VirtualFile>()
@Volatile
private var cachedUrlsList: Array<String>? = null
init {
urls.forEach { virtualFilePointersList.add(it as VirtualFilePointer) }
jarDirectories.forEach { virtualFilePointersList.add(it.directoryUrl as VirtualFilePointer) }
}
fun isJarDirectory(url: String): Boolean = jarDirectories.any { it.directoryUrl.url == url }
fun findByUrl(url: String): VirtualFilePointer? = virtualFilePointersList.find { it.url == url }
fun getList(): List<VirtualFilePointer> = Collections.unmodifiableList(virtualFilePointersList.toList())
fun getUrls(): Array<String> {
if (cachedUrlsList == null) {
cachedUrlsList = virtualFilePointersList.map { it.url }.toArray(EMPTY_STRING_ARRAY)
}
return cachedUrlsList!!
}
fun getFiles(): Array<VirtualFile> {
val timestamp = timestampOfCachedFiles
val cachedResults = cachedFilesList
return if (timestamp == virtualFilePointerManager.modificationCount) cachedResults else cacheVirtualFilePointersData()
}
private fun cacheVirtualFilePointersData(): Array<VirtualFile> {
val cachedFiles: MutableList<VirtualFile> = ArrayList(virtualFilePointersList.size)
val cachedDirectories: MutableList<VirtualFile> = ArrayList(virtualFilePointersList.size / 3)
var allFilesAreDirs = true
for (pointer in virtualFilePointersList) {
if (!pointer.isValid) continue
val file = pointer.file
if (file != null) {
cachedFiles.add(file)
if (file.isDirectory) {
cachedDirectories.add(file)
}
else {
allFilesAreDirs = false
}
}
}
for (jarDirectory in jarDirectories) {
val virtualFilePointer = jarDirectory.directoryUrl as VirtualFilePointer
if (!virtualFilePointer.isValid) continue
val directoryFile = virtualFilePointer.file
if (directoryFile != null) {
cachedDirectories.remove(directoryFile)
if (jarDirectory.recursive) {
VfsUtilCore.visitChildrenRecursively(directoryFile, object : VirtualFileVisitor<Void?>() {
override fun visitFile(file: VirtualFile): Boolean {
if (!file.isDirectory && FileTypeRegistry.getInstance().getFileTypeByFileName(
file.nameSequence) === ArchiveFileType.INSTANCE) {
val jarRoot = StandardFileSystems.jar().findFileByPath(file.path + URLUtil.JAR_SEPARATOR)
if (jarRoot != null) {
cachedFiles.add(jarRoot)
cachedDirectories.add(jarRoot)
return false
}
}
return true
}
})
}
else {
if (!directoryFile.isValid) continue
val children = directoryFile.children
for (file in children) {
if (!file.isDirectory && FileTypeRegistry.getInstance().getFileTypeByFileName(file.nameSequence) === ArchiveFileType.INSTANCE) {
val jarRoot = StandardFileSystems.jar().findFileByPath(file.path + URLUtil.JAR_SEPARATOR)
if (jarRoot != null) {
cachedFiles.add(jarRoot)
cachedDirectories.add(jarRoot)
}
}
}
}
}
}
val files = if (allFilesAreDirs) VfsUtilCore.toVirtualFileArray(cachedDirectories) else VfsUtilCore.toVirtualFileArray(cachedFiles)
cachedFilesList = files
timestampOfCachedFiles = virtualFilePointerManager.modificationCount
return files
}
}
data class JarDirectoryDescription(val directoryUrl: VirtualFileUrl, val recursive: Boolean)
|
apache-2.0
|
bae07335e268b0a1c9eb842904b5e132
| 41.324561 | 140 | 0.711235 | 4.937564 | false | false | false | false |
tobyhs/WeatherWeight
|
app/src/main/java/io/github/tobyhs/weatherweight/forecast/ForecastCardItem.kt
|
1
|
1381
|
package io.github.tobyhs.weatherweight.forecast
import java.util.Locale
import android.view.LayoutInflater
import android.view.ViewGroup
import com.mikepenz.fastadapter.binding.AbstractBindingItem
import io.github.tobyhs.weatherweight.data.model.DailyForecast
import io.github.tobyhs.weatherweight.databinding.ForecastCardBinding
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
/**
* FastAdapter item for a [DailyForecast]
*
* @property forecast the [DailyForecast] to show data for
*/
class ForecastCardItem(val forecast: DailyForecast) : AbstractBindingItem<ForecastCardBinding>() {
override val type: Int
get() = 0
override fun bindView(binding: ForecastCardBinding, payloads: List<Any>) {
val locale = Locale.getDefault()
binding.day.text = forecast.date.dayOfWeek.getDisplayName(TextStyle.SHORT, locale)
binding.date.text = forecast.date.format(DATE_FORMATTER)
binding.temperatureLow.text = forecast.low.toString()
binding.temperatureHigh.text = forecast.high.toString()
binding.description.text = forecast.text
}
override fun createBinding(inflater: LayoutInflater, parent: ViewGroup?): ForecastCardBinding {
return ForecastCardBinding.inflate(inflater, parent, false)
}
}
val DATE_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("MMM d")
|
mit
|
e2c4df2011ac702fe479c6c5156622ef
| 34.410256 | 99 | 0.765387 | 4.454839 | false | false | false | false |
paplorinc/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt
|
2
|
5712
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, JvmDeclarationUElement {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUElement(givenParent)", ReplaceWith("JavaAbstractUElement(givenParent)"))
constructor() : this(null)
override fun equals(other: Any?): Boolean {
if (other !is UElement || other.javaClass != this.javaClass) return false
return if (this.psi != null) this.psi == other.psi else this === other
}
override fun hashCode(): Int = psi?.hashCode() ?: System.identityHashCode(this)
override fun asSourceString(): String {
return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString()
}
override fun toString(): String = asRenderString()
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
protected open fun convertParent(): UElement? =
getPsiParentForLazyConversion()
?.let { JavaConverter.unwrapElements(it).toUElement() }
?.let { unwrapSwitch(it) }
?.also {
if (it === this) throw IllegalStateException("lazy parent loop for $this")
if (it.psi != null && it.psi === this.psi)
throw IllegalStateException("lazy parent loop: psi ${this.psi}(${this.psi?.javaClass}) for $this of ${this.javaClass}")
}
protected open fun getPsiParentForLazyConversion(): PsiElement? = this.psi?.parent
//explicitly overridden in abstract class to be binary compatible with Kotlin
override val comments: List<UComment>
get() = super<JavaUElementWithComments>.comments
override val sourcePsi: PsiElement?
get() = super<JavaUElementWithComments>.sourcePsi
override val javaPsi: PsiElement?
get() = super<JavaUElementWithComments>.javaPsi
}
private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement {
when (uParent) {
is UBlockExpression -> {
val codeBlockParent = uParent.uastParent
when (codeBlockParent) {
is JavaUBlockExpression -> {
val sourcePsi = codeBlockParent.sourcePsi
if (sourcePsi is PsiBlockStatement && sourcePsi.parent is PsiSwitchLabeledRuleStatement)
(codeBlockParent.uastParent as? JavaUSwitchEntry)?.let { return it.body }
}
is JavaUSwitchEntryList -> {
if (branchHasElement(psi, codeBlockParent.psi) { it is PsiSwitchLabelStatementBase }) {
return codeBlockParent
}
val psiElement = psi ?: return uParent
return codeBlockParent.findUSwitchEntryForBodyStatementMember(psiElement)?.body ?: return codeBlockParent
}
is JavaUSwitchExpression -> return unwrapSwitch(codeBlockParent)
}
return uParent
}
is JavaUSwitchEntry -> {
val parentSourcePsi = uParent.sourcePsi
if (parentSourcePsi is PsiSwitchLabeledRuleStatement && parentSourcePsi.body?.children?.contains(psi) == true) {
val psi = psi
return if (psi is PsiExpression && uParent.body.expressions.size == 1)
DummyUBreakExpression(psi, uParent.body)
else uParent.body
}
else
return uParent
}
is USwitchExpression -> {
val parentPsi = uParent.psi as PsiSwitchBlock
return if (this === uParent.body || branchHasElement(psi, parentPsi) { it === parentPsi.expression })
uParent
else
uParent.body
}
else -> return uParent
}
}
private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean {
var current: PsiElement? = child;
while (current != null && current != parent) {
if (predicate(current)) return true
current = current.parent
}
return false
}
abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUExpression(givenParent)", ReplaceWith("JavaAbstractUExpression(givenParent)"))
constructor() : this(null)
override fun evaluate(): Any? {
val project = psi?.project ?: return null
return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi)
}
override val annotations: List<UAnnotation>
get() = emptyList()
override fun getExpressionType(): PsiType? {
val expression = psi as? PsiExpression ?: return null
return expression.type
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceExpression -> it.parent
is PsiReferenceExpression -> (it.parent as? PsiMethodCallExpression) ?: it
else -> it
}
}
override fun convertParent(): UElement? = super.convertParent().let { uParent ->
when (uParent) {
is UAnonymousClass -> uParent.uastParent
else -> uParent
}
}.let(this::unwrapCompositeQualifiedReference)
}
|
apache-2.0
|
d9512b6fc9ee4535bba315b7a4745768
| 35.382166 | 129 | 0.703081 | 4.894602 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/platform/bukkit/BukkitModuleType.kt
|
1
|
1505
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel
import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object BukkitModuleType : AbstractModuleType<BukkitModule<BukkitModuleType>>("org.bukkit", "bukkit") {
private const val ID = "BUKKIT_MODULE_TYPE"
val IGNORED_ANNOTATIONS = listOf(BukkitConstants.HANDLER_ANNOTATION)
val LISTENER_ANNOTATIONS = listOf(BukkitConstants.HANDLER_ANNOTATION)
init {
CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.BUKKIT
override val icon = PlatformAssets.BUKKIT_ICON
override val id = ID
override val ignoredAnnotations = IGNORED_ANNOTATIONS
override val listenerAnnotations = LISTENER_ANNOTATIONS
override val isEventGenAvailable = true
override fun generateModule(facet: MinecraftFacet): BukkitModule<BukkitModuleType> = BukkitModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass)
}
|
mit
|
1feec57a13ecbf5872c4e0cee9f6c18e
| 34.833333 | 114 | 0.794684 | 4.465875 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/MethodCallSideOnlyInspection.kt
|
1
|
9317
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class MethodCallSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() =
"Invalid usage of a @SideOnly method call"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription() =
"Methods which are declared with a @SideOnly annotation can only be " +
"used in matching @SideOnly classes and methods."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val method = infos[3] as PsiMethod
return if (method.isWritable) {
RemoveAnnotationInspectionGadgetsFix(method, "Remove @SideOnly annotation from method declaration")
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitMethodCallExpression(expression: PsiMethodCallExpression) {
if (!SideOnlyUtil.beginningCheck(expression)) {
return
}
val referenceExpression = expression.methodExpression
val qualifierExpression = referenceExpression.qualifierExpression
// If this field is a @SidedProxy field, don't check. This is because people often are naughty and use the server impl as
// the base class for their @SidedProxy class, and client extends it. this messes up our checks, so we will just assume the
// right class is loaded for @SidedProxy's
run skip@{
if (qualifierExpression is PsiReferenceExpression) {
val resolve = qualifierExpression.resolve() as? PsiField ?: return@skip
val resolveFieldModifierList = resolve.modifierList ?: return@skip
if (resolveFieldModifierList.findAnnotation(ForgeConstants.SIDED_PROXY_ANNOTATION) == null) {
return@skip
}
return
}
}
val declaration = referenceExpression.resolve() as? PsiMethod ?: return
var elementSide = SideOnlyUtil.checkMethod(declaration)
// Check the class(es) the element is declared in
val declarationContainingClass = declaration.containingClass ?: return
val declarationClassHierarchySides = SideOnlyUtil.checkClassHierarchy(declarationContainingClass)
val declarationClassSide = SideOnlyUtil.getFirstSide(declarationClassHierarchySides)
// The element inherits the @SideOnly from it's parent class if it doesn't explicitly set it itself
var inherited = false
if (declarationClassSide !== Side.NONE && (elementSide === Side.INVALID || elementSide === Side.NONE)) {
inherited = true
elementSide = declarationClassSide
}
if (elementSide === Side.INVALID || elementSide === Side.NONE) {
return
}
// Check the class(es) the element is in
val containingClass = expression.findContainingClass() ?: return
val classSide = SideOnlyUtil.getSideForClass(containingClass)
var classAnnotated = false
if (classSide !== Side.NONE && classSide !== Side.INVALID) {
if (classSide !== elementSide) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementSide.annotation,
classSide.annotation,
declaration
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementSide.annotation,
classSide.annotation,
declaration
)
}
}
classAnnotated = true
}
// Check the method the element is in
val methodSide = SideOnlyUtil.checkElementInMethod(expression)
// Put error on for method
if (elementSide !== methodSide && methodSide !== Side.INVALID) {
if (methodSide === Side.NONE) {
// If the class is properly annotated the method doesn't need to also be annotated
if (!classAnnotated) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD,
elementSide.annotation, null,
declaration
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_UNANNOTATED_METHOD,
elementSide.annotation, null,
declaration
)
}
}
} else {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementSide.annotation,
methodSide.annotation,
declaration
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementSide.annotation,
methodSide.annotation,
declaration
)
}
}
}
}
}
}
enum class Error {
ANNOTATED_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] + " cannot be referenced in an un-annotated method."
}
},
ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in an un-annotated method."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
|
mit
|
1907de46fbad836698dc6eeab40effaa
| 42.334884 | 139 | 0.520125 | 6.248826 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirNamedArgumentCompletionContributor.kt
|
1
|
5512
|
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.completion.contributors
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.analysis.api.signatures.KtVariableLikeSignature
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.idea.base.analysis.api.utils.CallParameterInfoProvider
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirNameReferencePositionContext
import org.jetbrains.kotlin.idea.completion.findValueArgument
import org.jetbrains.kotlin.idea.parameterInfo.collectCallCandidates
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
internal class FirNamedArgumentCompletionContributor(basicContext: FirBasicCompletionContext, priority: Int) :
FirCompletionContributorBase<FirNameReferencePositionContext>(basicContext, priority) {
override fun KtAnalysisSession.complete(positionContext: FirNameReferencePositionContext) {
if (positionContext.explicitReceiver != null) return
val valueArgument = findValueArgument(positionContext.nameExpression) ?: return
val valueArgumentList = valueArgument.parent as? KtValueArgumentList ?: return
val callElement = valueArgumentList.parent as? KtCallElement ?: return
if (valueArgument.getArgumentName() != null) return
val candidates = collectCallCandidates(callElement)
.mapNotNull { it.candidate as? KtFunctionCall<*> }
.filter { it.partiallyAppliedSymbol.symbol.hasStableParameterNames }
val namedArgumentInfos = buildList {
val currentArgumentIndex = valueArgumentList.arguments.indexOf(valueArgument)
val (candidatesWithTypeMismatches, candidatesWithNoTypeMismatches) = candidates.partition {
CallParameterInfoProvider.hasTypeMismatchBeforeCurrent(callElement, it.argumentMapping, currentArgumentIndex)
}
addAll(collectNamedArgumentInfos(callElement, candidatesWithNoTypeMismatches, currentArgumentIndex))
// if no candidates without type mismatches have any candidate parameters, try searching among remaining candidates
if (isEmpty()) {
addAll(collectNamedArgumentInfos(callElement, candidatesWithTypeMismatches, currentArgumentIndex))
}
}
for ((name, types) in namedArgumentInfos) {
with(lookupElementFactory) {
sink.addElement(createNamedArgumentLookupElement(name, types))
if (types.any { it.isBoolean }) {
sink.addElement(createNamedArgumentWithValueLookupElement(name, KtTokens.TRUE_KEYWORD.value))
sink.addElement(createNamedArgumentWithValueLookupElement(name, KtTokens.FALSE_KEYWORD.value))
}
if (types.any { it.isMarkedNullable }) {
sink.addElement(createNamedArgumentWithValueLookupElement(name, KtTokens.NULL_KEYWORD.value))
}
}
}
}
/**
* @property types types of all parameter candidates that match [name]
*/
private data class NamedArgumentInfo(
val name: Name,
val types: List<KtType>
)
private fun KtAnalysisSession.collectNamedArgumentInfos(
callElement: KtCallElement,
candidates: List<KtFunctionCall<*>>,
currentArgumentIndex: Int
): List<NamedArgumentInfo> {
val argumentsBeforeCurrent = callElement.valueArgumentList?.arguments?.take(currentArgumentIndex) ?: return emptyList()
val nameToTypes = mutableMapOf<Name, MutableSet<KtType>>()
for (candidate in candidates) {
val parameterCandidates = collectNotUsedParameterCandidates(callElement, candidate, argumentsBeforeCurrent)
parameterCandidates.forEach { parameter ->
nameToTypes.getOrPut(parameter.name) { HashSet() }.add(parameter.symbol.returnType)
}
}
return nameToTypes.map { (name, types) -> NamedArgumentInfo(name, types.toList()) }
}
private fun KtAnalysisSession.collectNotUsedParameterCandidates(
callElement: KtCallElement,
candidate: KtFunctionCall<*>,
argumentsBeforeCurrent: List<KtValueArgument>
): List<KtVariableLikeSignature<KtValueParameterSymbol>> {
val signature = candidate.partiallyAppliedSymbol.signature
val argumentMapping = candidate.argumentMapping
val argumentToParameterIndex = CallParameterInfoProvider.mapArgumentsToParameterIndices(callElement, signature, argumentMapping)
if (argumentsBeforeCurrent.any { it.getArgumentExpression() !in argumentToParameterIndex }) return emptyList()
val alreadyPassedParameters = argumentsBeforeCurrent.mapNotNull { argumentMapping[it.getArgumentExpression()] }.toSet()
return signature.valueParameters.filterNot { it in alreadyPassedParameters }
}
}
|
apache-2.0
|
eff83711eff065f3e9b30c5ec2e3b80d
| 50.523364 | 136 | 0.741473 | 5.425197 | false | false | false | false |
JetBrains/intellij-community
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCacheDownloader.kt
|
1
|
6050
|
// 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 org.jetbrains.intellij.build.impl.compilation
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.util.io.Decompressor
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory
import org.jetbrains.intellij.build.impl.compilation.cache.SourcesStateProcessor
import org.jetbrains.intellij.build.io.retryWithExponentialBackOff
import org.jetbrains.jps.cache.model.BuildTargetState
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
private const val COMMITS_COUNT = 1_000
internal class PortableCompilationCacheDownloader(
private val context: CompilationContext,
private val git: Git,
private val remoteCache: PortableCompilationCache.RemoteCache,
private val gitUrl: String,
private val availableForHeadCommitForced: Boolean,
private val downloadCompilationOutputsOnly: Boolean,
) {
private val remoteCacheUrl = remoteCache.url.trimEnd('/')
private val sourcesStateProcessor = SourcesStateProcessor(context.compilationData.dataStorageRoot, context.classesOutputDirectory)
/**
* If true then latest commit in current repository will be used to download caches.
*/
val availableForHeadCommit by lazy { availableCommitDepth == 0 }
private val lastCommits by lazy { git.log(COMMITS_COUNT) }
private fun downloadString(url: String): String = retryWithExponentialBackOff {
if (url.isS3()) {
awsS3Cli("cp", url, "-")
}
else {
httpClient.get(url, remoteCache.authHeader).useSuccessful { it.body.string() }
}
}
private fun downloadToFile(url: String, file: Path, spanName: String) {
TraceManager.spanBuilder(spanName).setAttribute("url", url).setAttribute("path", "$file").useWithScope {
Files.createDirectories(file.parent)
retryWithExponentialBackOff {
if (url.isS3()) {
awsS3Cli("cp", url, "$file")
} else {
httpClient.get(url, remoteCache.authHeader).useSuccessful { response ->
Files.newOutputStream(file).use {
response.body.byteStream().transferTo(it)
}
}
}
}
}
}
private val availableCommitDepth by lazy {
if (availableForHeadCommitForced) 0 else lastCommits.indexOfFirst {
availableCachesKeys.contains(it)
}
}
private val availableCachesKeys by lazy {
val commitHistory = "$remoteCacheUrl/${CommitsHistory.JSON_FILE}"
if (isExist(commitHistory)) {
val json = downloadString(commitHistory)
CommitsHistory(json).commitsForRemote(gitUrl)
}
else {
emptyList()
}
}
private fun isExist(path: String): Boolean =
TraceManager.spanBuilder("head").setAttribute("url", remoteCacheUrl).use {
retryWithExponentialBackOff {
httpClient.head(path, remoteCache.authHeader).use {
check(it.code == 200 || it.code == 404) {
"HEAD $path responded with unexpected ${it.code}"
}
it.code
}
} == 200
}
fun download() {
if (availableCommitDepth in 0 until lastCommits.count()) {
val lastCachedCommit = lastCommits.get(availableCommitDepth)
context.messages.info("Using cache for commit $lastCachedCommit ($availableCommitDepth behind last commit).")
val tasks = mutableListOf<ForkJoinTask<*>>()
if (!downloadCompilationOutputsOnly) {
tasks.add(ForkJoinTask.adapt { saveJpsCache(lastCachedCommit) })
}
val sourcesState = getSourcesState(lastCachedCommit)
val outputs = sourcesStateProcessor.getAllCompilationOutputs(sourcesState)
context.messages.info("Going to download ${outputs.size} compilation output parts.")
outputs.forEach { output ->
tasks.add(ForkJoinTask.adapt { saveOutput(output) })
}
ForkJoinTask.invokeAll(tasks)
}
else {
context.messages.warning("Unable to find cache for any of last $COMMITS_COUNT commits.")
}
}
private fun getSourcesState(commitHash: String): Map<String, Map<String, BuildTargetState>> {
return sourcesStateProcessor.parseSourcesStateFile(downloadString("$remoteCacheUrl/metadata/$commitHash"))
}
private fun saveJpsCache(commitHash: String) {
var cacheArchive: Path? = null
try {
cacheArchive = downloadJpsCache(commitHash)
val cacheDestination = context.compilationData.dataStorageRoot
val start = System.currentTimeMillis()
Decompressor.Zip(cacheArchive).overwrite(true).extract(cacheDestination)
context.messages.info("Jps Cache was uncompressed to $cacheDestination in ${System.currentTimeMillis() - start}ms.")
}
finally {
if (cacheArchive != null) {
Files.deleteIfExists(cacheArchive)
}
}
}
private fun downloadJpsCache(commitHash: String): Path {
val cacheArchive = Files.createTempFile("cache", ".zip")
downloadToFile("$remoteCacheUrl/caches/$commitHash", cacheArchive, spanName = "download jps cache")
return cacheArchive
}
private fun saveOutput(compilationOutput: CompilationOutput) {
var outputArchive: Path? = null
try {
outputArchive = downloadOutput(compilationOutput)
Decompressor.Zip(outputArchive).overwrite(true).extract(Path.of(compilationOutput.path))
}
catch (e: Exception) {
throw Exception("Unable to decompress $remoteCacheUrl/${compilationOutput.remotePath} to $compilationOutput.path", e)
}
finally {
if (outputArchive != null) {
Files.deleteIfExists(outputArchive)
}
}
}
private fun downloadOutput(compilationOutput: CompilationOutput): Path {
val outputArchive = Path.of(compilationOutput.path, "tmp-output.zip")
downloadToFile("$remoteCacheUrl/${compilationOutput.remotePath}", outputArchive, spanName = "download output")
return outputArchive
}
}
|
apache-2.0
|
3d72614f1ffbf56c3690dbffc2a0862b
| 35.672727 | 132 | 0.715207 | 4.461652 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/weighers/ExpectedTypeWeigher.kt
|
1
|
1850
|
// 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.weighers
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementWeigher
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.psi.UserDataProperty
internal object ExpectedTypeWeigher {
object Weigher : LookupElementWeigher(WEIGHER_ID) {
override fun weigh(element: LookupElement): MatchesExpectedType =
element.matchesExpectedType ?: MatchesExpectedType.NON_TYPABLE
}
fun KtAnalysisSession.addWeight(context: WeighingContext, lookupElement: LookupElement, symbol: KtSymbol) {
lookupElement.matchesExpectedType = matchesExpectedType(symbol, context.expectedType)
}
private fun KtAnalysisSession.matchesExpectedType(
symbol: KtSymbol,
expectedType: KtType?
) = when {
expectedType == null -> MatchesExpectedType.NON_TYPABLE
symbol !is KtCallableSymbol -> MatchesExpectedType.NON_TYPABLE
else -> MatchesExpectedType.matches(symbol.returnType isSubTypeOf expectedType)
}
var LookupElement.matchesExpectedType by UserDataProperty(Key<MatchesExpectedType>("MATCHES_EXPECTED_TYPE"))
enum class MatchesExpectedType {
MATCHES, NON_TYPABLE, NOT_MATCHES, ;
companion object {
fun matches(matches: Boolean) = if (matches) MATCHES else NOT_MATCHES
}
}
const val WEIGHER_ID = "kotlin.expected.type"
}
|
apache-2.0
|
91572f1751b57a831ace1ee1c1734346
| 37.541667 | 158 | 0.759459 | 4.65995 | false | false | false | false |
allotria/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/query/SearchQueryCompletionProvider.kt
|
5
|
3650
|
package com.jetbrains.packagesearch.intellij.plugin.api.query
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
abstract class SearchQueryCompletionProvider(private val handleSpace: Boolean) {
fun buildCompletionModel(query: String, caretPosition: Int): SearchQueryCompletionModel? {
val length = query.length
if (length == 0) return null
if (caretPosition < length) {
if (query[caretPosition] == ' ' && (caretPosition == 0 || query[caretPosition - 1] == ' ')) {
return if (handleSpace) buildAttributesCompletionModel(null, caretPosition) else null
}
} else if (caretPosition >= 1 && query[caretPosition - 1] == ' ') {
return if (handleSpace) buildAttributesCompletionModel(null, caretPosition) else null
}
val startPosition = Ref<Int>()
val attribute = parseAttributeInQuery(query, caretPosition, startPosition)
return if (attribute.second == null) {
buildAttributesCompletionModel(attribute.first, startPosition.get())
} else {
buildAttributeValuesCompletionModel(attribute.first, attribute.second, startPosition.get())
}
}
@Suppress("NestedBlockDepth") // Adopted code
private fun parseAttributeInQuery(query: String, endPosition: Int, startPosition: Ref<in Int>): Pair<String, String> {
var end = endPosition
var index = end - 1
var value: String? = null
while (index >= 0) {
val ch = query[index]
if (ch == ':') {
value = query.substring(index + 1, end)
startPosition.set(index + 1)
end = index + 1
index--
while (index >= 0) {
if (query[index] == ' ') {
break
}
index--
}
break
}
if (ch == ' ') {
break
}
index--
}
val name = StringUtil.trimStart(query.substring(index + 1, end), "-")
if (startPosition.isNull) {
startPosition.set(index + if (query[index + 1] == '-') 2 else 1)
}
return Pair.create(name, value)
}
private fun buildAttributesCompletionModel(prefix: String?, caretPosition: Int): SearchQueryCompletionModel? {
val shouldFilter = !prefix.isNullOrBlank()
val attributes = getAttributes().filter {
!shouldFilter || it.startsWith(prefix!!, true)
}.toList()
if (attributes.isEmpty()) return null
return SearchQueryCompletionModel(
caretPosition,
if (prefix != null) caretPosition + prefix.length else caretPosition,
prefix,
attributes,
null
)
}
private fun buildAttributeValuesCompletionModel(attribute: String, prefix: String?, caretPosition: Int): SearchQueryCompletionModel? {
val shouldFilter = !prefix.isNullOrBlank()
val values = getValuesFor(attribute).filter {
!shouldFilter || it.startsWith(prefix!!, true)
}.toList()
if (values.isEmpty()) return null
return SearchQueryCompletionModel(
caretPosition,
if (prefix != null) caretPosition + prefix.length else caretPosition,
prefix,
null,
values
)
}
protected abstract fun getAttributes(): List<String>
protected abstract fun getValuesFor(attribute: String): List<String>
}
|
apache-2.0
|
ae63fa7e388d6651ea2f93653bde30a0
| 33.11215 | 138 | 0.583562 | 5.076495 | false | false | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/diagnostic/hprof/navigator/ObjectNavigator.kt
|
2
|
4171
|
/*
* Copyright (C) 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 com.intellij.diagnostic.hprof.navigator
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.classstore.ClassStore
import com.intellij.diagnostic.hprof.classstore.HProfMetadata
import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser
import com.intellij.diagnostic.hprof.visitors.CreateAuxiliaryFilesVisitor
import it.unimi.dsi.fastutil.longs.LongList
import org.jetbrains.annotations.NonNls
import java.nio.channels.FileChannel
abstract class ObjectNavigator(val classStore: ClassStore, val instanceCount: Long) {
enum class ReferenceResolution {
ALL_REFERENCES,
ONLY_STRONG_REFERENCES,
NO_REFERENCES
}
data class RootObject(val id: Long, val reason: RootReason)
abstract val id: Long
abstract fun createRootsIterator(): Iterator<RootObject>
abstract fun goTo(id: Long, referenceResolution: ReferenceResolution = ReferenceResolution.ONLY_STRONG_REFERENCES)
abstract fun getClass(): ClassDefinition
abstract fun getReferencesCopy(): LongList
abstract fun copyReferencesTo(outReferences: LongList)
abstract fun getClassForObjectId(id: Long): ClassDefinition
abstract fun getRootReasonForObjectId(id: Long): RootReason?
abstract fun getObjectSize(): Int
abstract fun getSoftReferenceId(): Long
abstract fun getWeakReferenceId(): Long
abstract fun getSoftWeakReferenceIndex(): Int
fun goToInstanceField(@NonNls className: String?, @NonNls fieldName: String) {
val objectId = getInstanceFieldObjectId(className, fieldName)
goTo(objectId, ReferenceResolution.ALL_REFERENCES)
}
fun getInstanceFieldObjectId(@NonNls className: String?, @NonNls name: String): Long {
val refs = getReferencesCopy()
className?.let {
assert(className == getClass().name.substringBeforeLast('!')) { "Expected $className, got ${getClass().name}" }
}
val indexOfField = getClass().allRefFieldNames(classStore).indexOfFirst { it == name }
return refs.getLong(indexOfField)
}
fun goToStaticField(@NonNls className: String, @NonNls fieldName: String) {
val objectId = getStaticFieldObjectId(className, fieldName)
goTo(objectId, ReferenceResolution.ALL_REFERENCES)
}
private fun getStaticFieldObjectId(className: String, fieldName: String) =
classStore[className].objectStaticFields.first { it.name == fieldName }.value
companion object {
fun createOnAuxiliaryFiles(parser: HProfEventBasedParser,
auxOffsetsChannel: FileChannel,
auxChannel: FileChannel,
hprofMetadata: HProfMetadata,
instanceCount: Long): ObjectNavigator {
val createAuxiliaryFilesVisitor = CreateAuxiliaryFilesVisitor(auxOffsetsChannel, auxChannel, hprofMetadata.classStore, parser)
parser.accept(createAuxiliaryFilesVisitor, "auxFiles")
val auxBuffer = auxChannel.map(FileChannel.MapMode.READ_ONLY, 0, auxChannel.size())
val auxOffsetsBuffer =
auxOffsetsChannel.map(FileChannel.MapMode.READ_ONLY, 0, auxOffsetsChannel.size())
return ObjectNavigatorOnAuxFiles(hprofMetadata.roots, auxOffsetsBuffer, auxBuffer, hprofMetadata.classStore, instanceCount,
parser.idSize)
}
}
abstract fun isNull(): Boolean
// Some objects may have additional data (varies by type). Only available when referenceResolution != NO_REFERENCES.
abstract fun getExtraData(): Int
abstract fun getStringInstanceFieldValue(): String?
}
|
apache-2.0
|
94201541ba69e50703d43e1b36b4a557
| 38.72381 | 132 | 0.745625 | 4.655134 | false | false | false | false |
DmytroTroynikov/aemtools
|
aem-intellij-core/src/main/kotlin/com/aemtools/action/MarkAsHtlRootDirectoryAction.kt
|
1
|
2463
|
package com.aemtools.action
import com.aemtools.index.HtlTemplateIndex
import com.aemtools.lang.htl.icons.HtlIcons
import com.aemtools.service.detection.HtlDetectionService
import com.aemtools.lang.settings.HtlRootDirectories
import com.aemtools.common.util.psiManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.FileContentUtil.reparseOpenedFiles
/**
* Action that allows to mark/unmark directory as Htl Root.
*
* `Mark As -> HTL Root`
* `Mark As -> Unmark as HTL Root`
*
* @author Dmytro Troynikov
*/
class MarkAsHtlRootDirectoryAction : DumbAwareAction() {
override fun update(event: AnActionEvent) {
val file = event.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
?.firstOrNull()
val project = event.project
if (file == null
|| project == null
|| shouldDisable(file, project, event)) {
event.presentation.isEnabledAndVisible = false
return
}
if (HtlDetectionService.isHtlRootDirectory(file.path, project)) {
event.presentation.text = "Unmark as HTL Root"
return
}
event.presentation.icon = HtlIcons.HTL_ROOT
}
override fun actionPerformed(event: AnActionEvent) {
val file = event.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
?.firstOrNull() ?: return
val project = event.project
if (!event.presentation.isEnabledAndVisible || project == null) {
return
}
val path = file.path
val htlRootDirectories = HtlRootDirectories.getInstance(project)
?: return
if (shouldAdd(event)) {
htlRootDirectories.addRoot(path)
} else {
htlRootDirectories.removeRoot(path)
}
// attempt to flush cached files
event.project?.psiManager()?.apply {
reparseOpenedFiles()
HtlTemplateIndex.rebuildIndex()
}
}
private fun shouldAdd(event: AnActionEvent) = event.presentation.text == "HTL Root"
private fun shouldDisable(file: VirtualFile,
project: Project,
event: AnActionEvent): Boolean {
return (!file.isDirectory
&& event.place != ActionPlaces.PROJECT_VIEW_POPUP
|| !HtlDetectionService.mayBeMarked(file.path, project))
}
}
|
gpl-3.0
|
7a8d1e471bb6db7eb6ee576a261cb386
| 29.036585 | 85 | 0.707674 | 4.374778 | false | false | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/PluginChunkDataSource.kt
|
3
|
5399
|
// 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.ide.plugins.marketplace
import com.intellij.ide.IdeBundle
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.io.HttpRequests
import com.jetbrains.plugin.blockmap.core.BlockMap
import com.jetbrains.plugin.blockmap.core.Chunk
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.charset.Charset
private const val MAX_HTTP_HEADERS_LENGTH: Int = 19000
private const val MAX_RANGE_BYTES: Int = 10_000_000
private const val MAX_STRING_LENGTH: Int = 1024
private val LOG = logger<PluginChunkDataSource>()
class PluginChunkDataSource(
oldBlockMap: BlockMap,
newBlockMap: BlockMap,
private val newPluginUrl: String
) : Iterator<ByteArray> {
private val oldSet = oldBlockMap.chunks.toSet()
private val chunks = newBlockMap.chunks.filter { chunk -> !oldSet.contains(chunk) }
private var pos = 0
private var chunkSequences = ArrayList<MutableList<Chunk>>()
private var curChunkData = getRange(nextRange())
private var pointer: Int = 0
override fun hasNext() = curChunkData.size != 0
override fun next(): ByteArray {
return if (curChunkData.size != 0) {
if (pointer < curChunkData.size) {
curChunkData[pointer++]
}
else {
curChunkData = getRange(nextRange())
pointer = 0
next()
}
}
else throw NoSuchElementException()
}
private fun nextRange(): String {
val range = StringBuilder()
chunkSequences.clear()
var bytes = 0
while (pos < chunks.size
&& range.length < MAX_HTTP_HEADERS_LENGTH
&& bytes < MAX_RANGE_BYTES) {
val chunkSequence = nextChunkSequence(bytes)
chunkSequences.add(chunkSequence)
bytes += chunkSequence.last().offset + chunkSequence.last().length - chunkSequence[0].offset
range.append("${chunkSequence[0].offset}-${chunkSequence.last().offset + chunkSequence.last().length - 1},")
}
return range.removeSuffix(",").toString()
}
private fun nextChunkSequence(bytes: Int): MutableList<Chunk> {
val result = ArrayList<Chunk>()
result.add(chunks[pos])
pos++
var sum = result[0].length
while (pos < chunks.size - 1
&& chunks[pos].offset == chunks[pos - 1].offset + chunks[pos - 1].length
&& sum + bytes < MAX_RANGE_BYTES) {
result.add(chunks[pos])
sum += chunks[pos].length
pos++
}
return result
}
private fun getRange(range: String): MutableList<ByteArray> {
val result = ArrayList<ByteArray>()
HttpRequests.requestWithRange(newPluginUrl, range).productNameAsUserAgent().connect { request ->
val boundary = request.connection.contentType.removePrefix("multipart/byteranges; boundary=")
request.inputStream.buffered().use { input ->
when {
chunkSequences.size > 1 -> {
for (sequence in chunkSequences) {
parseHttpMultirangeHeaders(input, boundary)
parseHttpRangeBody(input, sequence, result)
}
}
chunkSequences.size == 1 -> parseHttpRangeBody(input, chunkSequences[0], result)
else -> LOG.error("Zero chunks", "request '$newPluginUrl'", "range '$range'")
}
}
}
return result
}
private fun parseHttpMultirangeHeaders(input: BufferedInputStream, boundary: String) {
val openingEmptyLine = nextLine(input)
if (openingEmptyLine.trim().isNotEmpty()) {
throw IOException(IdeBundle.message("http.multirange.response.doesnt.include.line.separator"))
}
val boundaryLine = nextLine(input)
if (!boundaryLine.contains(boundary)) {
throw IOException(IdeBundle.message("http.multirange.response.doesnt.contain.boundary", boundaryLine, boundary))
}
val contentTypeLine = nextLine(input)
if (!contentTypeLine.startsWith("Content-Type")) {
throw IOException(IdeBundle.message("http.multirange.response.includes.incorrect.header", contentTypeLine, "Content-Type"))
}
val contentRangeLine = nextLine(input)
if (!contentRangeLine.startsWith("Content-Range")) {
throw IOException(IdeBundle.message("http.multirange.response.includes.incorrect.header", contentRangeLine, "Content-Range"))
}
val closingEmptyLine = nextLine(input)
if (closingEmptyLine.trim().isNotEmpty()) {
throw IOException(IdeBundle.message("http.multirange.response.doesnt.include.line.separator"))
}
}
private fun parseHttpRangeBody(
input: BufferedInputStream,
sequence: MutableList<Chunk>,
result: MutableList<ByteArray>
) {
for (chunk in sequence) {
val data = ByteArray(chunk.length)
for (i in 0 until chunk.length) data[i] = input.read().toByte()
result.add(data)
}
}
private fun nextLine(input: BufferedInputStream): String {
ByteArrayOutputStream().use { baos ->
do {
val byte = input.read()
baos.write(byte)
if (baos.size() >= MAX_STRING_LENGTH) {
throw IOException(IdeBundle.message("wrong.http.range.response", String(baos.toByteArray(), Charset.defaultCharset())))
}
}
while (byte.toChar() != '\n')
return String(baos.toByteArray(), Charset.defaultCharset())
}
}
}
|
apache-2.0
|
4a8f36158b93f00d9d309d1b975a7f2e
| 35.734694 | 140 | 0.6792 | 4.195027 | false | false | false | false |
zdary/intellij-community
|
platform/projectModel-impl/src/com/intellij/openapi/module/impl/moduleGroupers.kt
|
13
|
5004
|
// 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.module.impl
import com.intellij.openapi.module.*
import com.intellij.openapi.project.Project
import com.intellij.util.SystemProperties
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.util.*
@ApiStatus.Internal
fun createGrouper(project: Project, moduleModel: ModifiableModuleModel? = null): ModuleGrouper {
val hasGroups = moduleModel?.hasModuleGroups() ?: ModuleManager.getInstance(project).hasModuleGroups()
if (!isQualifiedModuleNamesEnabled(project) || hasGroups) {
return ExplicitModuleGrouper(project, moduleModel)
}
return QualifiedNameGrouper(project, moduleModel)
}
private abstract class ModuleGrouperBase(protected val project: Project, protected val model: ModifiableModuleModel?) : ModuleGrouper() {
override fun getAllModules(): Array<Module> = model?.modules ?: ModuleManager.getInstance(project).modules
protected fun getModuleName(module: Module) = model?.getActualName(module) ?: module.name
override fun getShortenedName(module: Module) = getShortenedNameByFullModuleName(getModuleName(module))
override fun getShortenedName(module: Module, parentGroupName: String?) =
getShortenedNameByFullModuleName(getModuleName(module), parentGroupName)
}
private class QualifiedNameGrouper(project: Project, model: ModifiableModuleModel?) : ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module) = getGroupPathByModuleName(getModuleName(module))
override fun getGroupPath(description: ModuleDescription) = getGroupPathByModuleName(description.name)
override fun getShortenedNameByFullModuleName(name: String) = name.substringAfterLastDotNotFollowedByIncorrectChar()
override fun getShortenedNameByFullModuleName(name: String, parentGroupName: String?): String {
return if (parentGroupName != null) name.removePrefix("$parentGroupName.") else name
}
override fun getGroupPathByModuleName(name: String) = name.splitByDotsJoiningIncorrectIdentifiers().dropLast(1)
override fun getModuleAsGroupPath(module: Module) = getModuleName(module).splitByDotsJoiningIncorrectIdentifiers()
override fun getModuleAsGroupPath(description: ModuleDescription) = description.name.splitByDotsJoiningIncorrectIdentifiers()
override val compactGroupNodes: Boolean
get() = compactImplicitGroupNodes
companion object {
private val compactImplicitGroupNodes = SystemProperties.getBooleanProperty("project.compact.module.group.nodes", true)
}
}
private class ExplicitModuleGrouper(project: Project, model: ModifiableModuleModel?): ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
val path = if (model != null) model.getModuleGroupPath(module) else ModuleManager.getInstance(project).getModuleGroupPath(module)
return if (path != null) Arrays.asList(*path) else emptyList()
}
override fun getGroupPath(description: ModuleDescription) = when (description) {
is LoadedModuleDescription -> getGroupPath(description.module)
is UnloadedModuleDescription -> description.groupPath
else -> throw IllegalArgumentException(description.javaClass.name)
}
override fun getShortenedNameByFullModuleName(name: String) = name
override fun getShortenedNameByFullModuleName(name: String, parentGroupName: String?) = name
override fun getGroupPathByModuleName(name: String): List<String> = emptyList()
override fun getModuleAsGroupPath(module: Module) = null
override fun getModuleAsGroupPath(description: ModuleDescription) = null
override val compactGroupNodes: Boolean
get() = false
}
/**
* Split by dots where it doesn't lead to incorrect identifiers (i.e. "a.b-1.1" will be split to "a" and "b-1.1", not to "a", "b-1" and "1")
*/
private fun String.splitByDotsJoiningIncorrectIdentifiers(): List<String> {
var start = 0
var next = 1
val names = ArrayList<String>()
while (next < length) {
val end = indexOf('.', next)
if (end == -1 || end == length - 1) {
break
}
next = end + 1
if (this[end + 1].isJavaIdentifierStart()) {
names.add(substring(start, end))
start = end + 1
}
}
names.add(substring(start))
return names
}
/**
* Returns the same value as `splitByDotsNotFollowedByIncorrectChars().last()` but works more efficiently
*/
private fun String.substringAfterLastDotNotFollowedByIncorrectChar(): String {
if (length <= 1) return this
var i = lastIndexOf('.', length - 2)
while (i != -1 && !this[i + 1].isJavaIdentifierStart()) {
i = lastIndexOf('.', i-1)
}
if (i <= 0) return this
return substring(i+1)
}
@TestOnly
public fun splitStringByDotsJoiningIncorrectIdentifiers(string: String): Pair<List<String>, String> {
return Pair(string.splitByDotsJoiningIncorrectIdentifiers(), string.substringAfterLastDotNotFollowedByIncorrectChar())
}
|
apache-2.0
|
13b25045acd0b3dd50b80b726c31d8f5
| 40.7 | 140 | 0.768785 | 4.64624 | false | false | false | false |
zdary/intellij-community
|
community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateGradleProjectAndConfigureExactKotlinGuiTest.kt
|
6
|
2411
|
// 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.ide.projectWizard.kotlin.createProject
import com.intellij.ide.projectWizard.kotlin.model.*
import com.intellij.testGuiFramework.framework.param.GuiTestSuiteParam
import com.intellij.testGuiFramework.util.scenarios.NewProjectDialogModel
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.Serializable
@RunWith(GuiTestSuiteParam::class)
class CreateGradleProjectAndConfigureExactKotlinGuiTest(private val testParameters: TestParameters) : KotlinGuiTestCase() {
data class TestParameters(
val projectName: String,
val kotlinVersion: String,
val project: ProjectProperties = kotlinProjects.getValue(Projects.GradleGProjectJvm),
val expectedFacet: FacetStructure) : Serializable {
override fun toString() = projectName
}
@Test
fun createGradleAndConfigureKotlinJvmExactVersion() {
KotlinTestProperties.kotlin_artifact_version = testParameters.kotlinVersion
testCreateGradleAndConfigureKotlin(
kotlinVersion = KotlinTestProperties.kotlin_artifact_version,
project = testParameters.project,
expectedFacet = testParameters.expectedFacet,
gradleOptions = NewProjectDialogModel.GradleProjectOptions(
artifact = testMethod.methodName
)
)
}
companion object {
private val expectedFacet11 = FacetStructure(
targetPlatform = TargetPlatform.JVM18,
languageVersion = LanguageVersion.L11,
apiVersion = LanguageVersion.L11,
jvmOptions = FacetStructureJVM()
)
private val expectedFacet12 =
expectedFacet11.copy(apiVersion = LanguageVersion.L12, languageVersion = LanguageVersion.L12)
private val expectedFacet13 =
expectedFacet11.copy(apiVersion = LanguageVersion.L13, languageVersion = LanguageVersion.L13)
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data(): Collection<TestParameters> {
return listOf(
TestParameters(
projectName = "gradle_cfg_jvm_1271",
expectedFacet = expectedFacet12,
kotlinVersion = "1.2.71"
),
TestParameters(
projectName = "gradle_cfg_jvm_130",
expectedFacet = expectedFacet13,
kotlinVersion = "1.3.0"
)
)
}
}
}
|
apache-2.0
|
b74a12311b5dba801b76f2a762f1a2c3
| 35.545455 | 140 | 0.738698 | 4.78373 | false | true | false | false |
grover-ws-1/http4k
|
src/docs/cookbook/typesafe_http_contracts/example.kt
|
1
|
3500
|
package cookbook.typesafe_http_contracts
import org.http4k.contract.ApiInfo
import org.http4k.contract.ApiKey
import org.http4k.contract.RouteMeta
import org.http4k.contract.Swagger
import org.http4k.contract.bind
import org.http4k.contract.bindContract
import org.http4k.contract.contract
import org.http4k.contract.div
import org.http4k.contract.meta
import org.http4k.contract.query
import org.http4k.core.Body
import org.http4k.core.ContentType.Companion.TEXT_PLAIN
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.core.with
import org.http4k.filter.CachingFilters.Response.NoCache
import org.http4k.filter.CorsPolicy
import org.http4k.filter.ReportRouteLatency
import org.http4k.filter.ResponseFilters
import org.http4k.filter.ServerFilters
import org.http4k.format.Argo
import org.http4k.lens.Path
import org.http4k.lens.Query
import org.http4k.lens.int
import org.http4k.lens.string
import org.http4k.routing.ResourceLoader.Companion.Classpath
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.routing.static
import org.http4k.server.Jetty
import org.http4k.server.asServer
import java.time.Clock
fun main(args: Array<String>) {
fun add(value1: Int, value2: Int): HttpHandler = {
Response(OK).with(
Body.string(TEXT_PLAIN).toLens() of (value1 + value2).toString()
)
}
val ageQuery = Query.int().required("age")
fun echo(name: String): HttpHandler = {
Response(OK).with(
Body.string(TEXT_PLAIN).toLens() of "hello $name you are ${ageQuery(it)}"
)
}
val filter: Filter = ResponseFilters.ReportRouteLatency(Clock.systemUTC(), { name, latency ->
println(name + " took " + latency)
})
val security = ApiKey(Query.int().required("apiKey"), {
println("foo" + (it == 42))
it == 42
})
val contract = contract(Swagger(ApiInfo("my great api", "v1.0"), Argo), "/docs/swagger.json", security,
"/add" / Path.int().of("value1") / Path.int().of("value2")
bindContract GET
to ::add
meta RouteMeta("add", "Adds 2 numbers together").returning("The result" to OK),
"/echo" / Path.of("name")
query ageQuery
bindContract GET to ::echo
meta RouteMeta("echo")
)
val handler = routes(
"/context" bind filter.then(contract),
"/static" bind NoCache().then(static(Classpath("cookbook"))),
"/" bind contract(Swagger(ApiInfo("my great super api", "v1.0"), Argo),
"/echo" / Path.of("name")
query ageQuery
bindContract GET to ::echo
meta RouteMeta("echo")
)
)
ServerFilters.Cors(CorsPolicy.UnsafeGlobalPermissive).then(handler).asServer(Jetty(8000)).start()
}
// Adding 2 numbers: curl -v "http://localhost:8000/context/add/123/564?apiKey=42"
// Echo (fail): curl -v "http://localhost:8000/context/echo/myName?age=notANumber&apiKey=42"
// API Key enforcement: curl -v "http://localhost:8000/context/add/123/564?apiKey=444"
// Static content: curl -v "http://localhost:8000/static/someStaticFile.txt"
// Swagger documentation: curl -v "http://localhost:8000/context/docs/swagger.json"
// Echo endpoint (at root): curl -v "http://localhost:8000/echo/hello?age=123"
|
apache-2.0
|
ba36dd5200b032a2726bd3f7cc10a089
| 36.244681 | 107 | 0.688286 | 3.451677 | false | false | false | false |
blokadaorg/blokada
|
android5/app/src/main/java/service/BackupService.kt
|
1
|
2761
|
/*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import android.app.backup.*
import android.os.ParcelFileDescriptor
import model.LocalConfig
import utils.Logger
private val log = Logger("Backup")
object BackupService {
var onBackupRestored = {}
fun requestBackup() {
log.v("Requesting backup")
val ctx = ContextService.requireAppContext()
val manager = BackupManager(ctx)
manager.dataChanged()
}
}
/**
* This will back up the following things:
* - All settings saved in the default shared preferences namespace
* - Blocklist files (merged blocklist, allowed list and denied list)
*
* What is saved to the default shared preferences namespace is controlled by PersistenceService, and
* depends on the useBackup flag. Same flag is used here to decide whether to backup the blocklist
* files or not.
*/
class BackupAgent : BackupAgentHelper() {
override fun onCreate() {
ContextService.setAppContext(this.applicationContext)
log.v("Registering backup agent")
// This is taken from the SharedPreferences source code, there's no api for this
val sharedPreferencesFileName = packageName + "_preferences"
addHelper(sharedPreferencesFileName,
SharedPreferencesBackupHelper(this, sharedPreferencesFileName)
)
val useBackup = PersistenceService.load(LocalConfig::class).backup
if (useBackup) {
log.v("Registering blocklist file backup")
addHelper(
BlocklistService.MERGED_BLOCKLIST,
FileBackupHelper(this, BlocklistService.MERGED_BLOCKLIST)
)
addHelper(
BlocklistService.USER_ALLOWED,
FileBackupHelper(this, BlocklistService.USER_ALLOWED)
)
addHelper(
BlocklistService.USER_DENIED,
FileBackupHelper(this, BlocklistService.USER_DENIED)
)
}
}
override fun onBackup(oldState: ParcelFileDescriptor?, data: BackupDataOutput?,
newState: ParcelFileDescriptor?) {
log.v("Backing up")
super.onBackup(oldState, data, newState)
}
override fun onRestore(data: BackupDataInput?, appVersionCode: Int, newState: ParcelFileDescriptor?) {
super.onRestore(data, appVersionCode, newState)
log.v("Restoring backup")
BackupService.onBackupRestored()
}
}
|
mpl-2.0
|
88adec5b0b828af7e746750278cf459c
| 29.340659 | 106 | 0.666304 | 4.693878 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/gradle/java/src/execution/build/GradleApplicationEnvironmentProvider.kt
|
10
|
9515
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.build
import com.intellij.execution.ShortenCommandLine
import com.intellij.execution.application.ApplicationConfiguration
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.util.ProgramParametersUtil
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiClass
import com.intellij.task.ExecuteRunConfigurationTask
/**
* @author Vladislav.Soroka
*/
internal class GradleApplicationEnvironmentProvider : GradleBaseApplicationEnvironmentProvider<ApplicationConfiguration>() {
override fun isApplicable(task: ExecuteRunConfigurationTask): Boolean = task.runProfile is ApplicationConfiguration
override fun generateInitScript(applicationConfiguration: ApplicationConfiguration,
module: Module,
params: JavaParameters,
gradleTaskPath: String,
runAppTaskName: String,
mainClass: PsiClass,
javaExePath: String,
sourceSetName: String,
javaModuleName: String?): String {
val workingDir = ProgramParametersUtil.getWorkingDir(applicationConfiguration, module.project, module)?.let {
FileUtil.toSystemIndependentName(it)
}
val argsString = createEscapedParameters(params.programParametersList.parameters, "args") +
createEscapedParameters(params.vmParametersList.parameters, "jvmArgs")
val useManifestJar = applicationConfiguration.shortenCommandLine === ShortenCommandLine.MANIFEST
val useArgsFile = applicationConfiguration.shortenCommandLine === ShortenCommandLine.ARGS_FILE
var useClasspathFile = applicationConfiguration.shortenCommandLine === ShortenCommandLine.CLASSPATH_FILE
var intelliJRtPath: String? = null
if (useClasspathFile) {
try {
intelliJRtPath = FileUtil.toCanonicalPath(
PathManager.getJarPathForClass(Class.forName("com.intellij.rt.execution.CommandLineWrapper")))
}
catch (t: Throwable) {
LOG.warn("Unable to use classpath file", t)
useClasspathFile = false
}
}
// @formatter:off
@Suppress("UnnecessaryVariable")
// @Language("Groovy")
val initScript = """
def gradlePath = '$gradleTaskPath'
def runAppTaskName = '$runAppTaskName'
def mainClass = '${mainClass.qualifiedName}'
def javaExePath = mapPath('$javaExePath')
def _workingDir = ${if (workingDir.isNullOrEmpty()) "null\n" else "mapPath('$workingDir')\n"}
def sourceSetName = '$sourceSetName'
def javaModuleName = ${if (javaModuleName == null) "null\n" else "'$javaModuleName'\n"}
${if (useManifestJar) "gradle.addListener(new ManifestTaskActionListener(runAppTaskName))\n" else ""}
${if (useArgsFile) "gradle.addListener(new ArgFileTaskActionListener(runAppTaskName))\n" else ""}
${if (useClasspathFile && intelliJRtPath != null) "gradle.addListener(new ClasspathFileTaskActionListener(runAppTaskName, mainClass, mapPath('$intelliJRtPath')))\n " else ""}
import org.gradle.util.GradleVersion
allprojects {
afterEvaluate { project ->
if(project.path == gradlePath && project?.convention?.findPlugin(JavaPluginConvention)) {
def overwrite = project.tasks.findByName(runAppTaskName) != null
project.tasks.create(name: runAppTaskName, overwrite: overwrite, type: JavaExec) {
if (javaExePath) executable = javaExePath
main = mainClass
$argsString
if (_workingDir) workingDir = _workingDir
standardInput = System.in
if (javaModuleName) {
classpath = tasks[sourceSets[sourceSetName].jarTaskName].outputs.files + project.sourceSets[sourceSetName].runtimeClasspath;
if (GradleVersion.current().baseVersion < GradleVersion.version("6.4")) {
doFirst {
jvmArgs += [
'--module-path', classpath.asPath,
'--module', javaModuleName + '/' + mainClass
]
classpath = files()
}
} else {
mainModule = javaModuleName
}
} else {
classpath = project.sourceSets[sourceSetName].runtimeClasspath
}
}
}
}
}
""" + (if (useManifestJar || useArgsFile || useClasspathFile) """
import org.gradle.api.execution.TaskActionListener
import org.gradle.api.Task
import org.gradle.api.tasks.JavaExec
abstract class RunAppTaskActionListener implements TaskActionListener {
String myTaskName
File myClasspathFile
RunAppTaskActionListener(String taskName) {
myTaskName = taskName
}
void beforeActions(Task task) {
if(!(task instanceof JavaExec) || task.name != myTaskName) return
myClasspathFile = patchTaskClasspath(task)
}
void afterActions(Task task) {
if(myClasspathFile != null) { myClasspathFile.delete() }
}
abstract File patchTaskClasspath(JavaExec task)
}
""" else "") + (if (useManifestJar) """
import org.gradle.api.tasks.JavaExec
import java.util.jar.Attributes
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
import java.util.zip.ZipEntry
class ManifestTaskActionListener extends RunAppTaskActionListener {
ManifestTaskActionListener(String taskName) {
super(taskName)
}
File patchTaskClasspath(JavaExec task) {
Manifest manifest = new Manifest()
Attributes attributes = manifest.getMainAttributes()
attributes.put(Attributes.Name.MANIFEST_VERSION, '1.0')
attributes.putValue('Class-Path', task.classpath.files.collect {it.toURI().toURL().toString()}.join(' '))
File file = File.createTempFile('generated-', '-manifest')
def oStream = new JarOutputStream(new FileOutputStream(file), manifest)
oStream.putNextEntry(new ZipEntry('META-INF/'))
oStream.close()
task.classpath = task.project.files(file.getAbsolutePath())
return file
}
}
""" else "") + (if (useArgsFile) """
import org.gradle.api.tasks.JavaExec
import org.gradle.process.CommandLineArgumentProvider
class ArgFileTaskActionListener extends RunAppTaskActionListener {
ArgFileTaskActionListener(String taskName) {
super(taskName)
}
File patchTaskClasspath(JavaExec task) {
File file = File.createTempFile('generated-', '-argFile')
def writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), 'UTF-8'))
def lineSep = System.getProperty('line.separator')
writer.print('-classpath' + lineSep)
writer.print(quoteArg(task.classpath.asPath))
writer.print(lineSep)
writer.close()
task.jvmArgs('@' + file.absolutePath)
task.classpath = task.project.files([])
return file
}
private static String quoteArg(String arg) {
String specials = ' #\'\"\n\r\t\f'
if (specials.find { arg.indexOf(it) != -1 } == null) return arg
StringBuilder sb = new StringBuilder(arg.length() * 2)
for (int i = 0; i < arg.length(); i++) {
char c = arg.charAt(i)
if (c == ' ' as char || c == '#' as char || c == '\'' as char) sb.append('"').append(c).append('"')
else if (c == '"' as char) sb.append("\"\\\"\"")
else if (c == '\n' as char) sb.append("\"\\n\"")
else if (c == '\r' as char) sb.append("\"\\r\"")
else if (c == '\t' as char) sb.append("\"\\t\"")
else if (c == '\f' as char) sb.append("\"\\f\"")
else sb.append(c)
}
return sb.toString()
}}
""" else "") + if (useClasspathFile) """
import org.gradle.api.tasks.JavaExec
import org.gradle.process.CommandLineArgumentProvider
class ClasspathFileTaskActionListener extends RunAppTaskActionListener {
String myMainClass
String myIntelliJRtPath
ClasspathFileTaskActionListener(String taskName, String mainClass, String intelliJRtPath) {
super(taskName)
myMainClass = mainClass
myIntelliJRtPath = intelliJRtPath
}
File patchTaskClasspath(JavaExec task) {
File file = File.createTempFile('generated-', '-classpathFile')
def writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), 'UTF-8'))
task.classpath.files.each { writer.println(it.path) }
writer.close()
List args = [file.absolutePath, myMainClass] as List
args.addAll(task.args)
task.args = []
task.argumentProviders.add({ return args } as CommandLineArgumentProvider)
task.main = 'com.intellij.rt.execution.CommandLineWrapper'
task.classpath = task.project.files([myIntelliJRtPath])
return file
}
}
""" else ""
// @formatter:on
return initScript
}
companion object {
private val LOG = logger<GradleApplicationEnvironmentProvider>()
}
}
|
apache-2.0
|
ab1b9dafcae14d6ccc0ba878d7bc0369
| 43.882075 | 178 | 0.650972 | 4.703411 | false | true | false | false |
smmribeiro/intellij-community
|
platform/credential-store/src/linuxKWalletLibrary.kt
|
10
|
5151
|
// 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.credentialStore
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.text.nullize
import org.freedesktop.dbus.annotations.DBusInterfaceName
import org.freedesktop.dbus.connections.impl.DBusConnection
import org.freedesktop.dbus.errors.NoReply
import org.freedesktop.dbus.errors.ServiceUnknown
import org.freedesktop.dbus.exceptions.DBusException
import org.freedesktop.dbus.interfaces.DBusInterface
import org.freedesktop.dbus.types.Variant
import java.io.Closeable
internal class KWalletCredentialStore private constructor(private val connection: DBusConnection, private val kWallet: KWallet) : CredentialStore, Closeable {
companion object {
private fun appName(): String {
val app = ApplicationManager.getApplication()
val appName = if (app == null || app.isUnitTestMode) null else ApplicationInfo.getInstance().fullApplicationName
return appName ?: "IDEA tests"
}
fun create(): KWalletCredentialStore? {
try {
val connection = DBusConnection.getConnection(DBusConnection.DBusBusType.SESSION)
try {
val wallet = connection.getRemoteObject("org.kde.kwalletd5", "/modules/kwalletd5", KWallet::class.java, true)
wallet.localWallet() //ping
return KWalletCredentialStore(connection, wallet)
}
catch (e: ServiceUnknown) {
LOG.info("No KWallet service", e)
}
catch (e: DBusException) {
LOG.warn("Failed to connect to KWallet", e)
}
catch (e: RuntimeException) {
LOG.warn("Failed to connect to KWallet", e)
}
connection.close()
}
catch (e: DBusException) {
LOG.warn("Failed to connect to D-Bus", e)
}
catch (e: RuntimeException) {
LOG.warn("Failed to connect to D-Bus", e)
}
return null
}
}
private val appId = appName()
private var cachedWalletId = -1
private var cachedWalletName: String? = null
private var suggestedCreation: String? = null
private fun getWalletId(): Int {
if (cachedWalletId != -1 && kWallet.isOpen(cachedWalletId) && cachedWalletName?.let { appId in kWallet.users(it) } == true) {
return cachedWalletId
}
val walletName = kWallet.localWallet()
cachedWalletName = walletName
val wallets = kWallet.wallets()
val isNew = walletName !in wallets
if (walletName == null || isNew && suggestedCreation == walletName) {
return -1
}
cachedWalletId = kWallet.open(walletName, 0L, appId)
if (isNew) suggestedCreation = walletName
return cachedWalletId
}
private inline fun handleError(run: () -> Unit, handle: () -> Unit) {
try {
run()
}
catch (e: NoReply) {
handle()
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
handleError({
val walletId = getWalletId()
if (walletId == -1) return ACCESS_TO_KEY_CHAIN_DENIED
val userName = attributes.userName.nullize()
val passwords = kWallet.readPasswordList(walletId, attributes.serviceName, userName ?: "*", appId)
val e = passwords.entries.firstOrNull() ?: return null
return Credentials(e.key, e.value.value)
}) { return CANNOT_UNLOCK_KEYCHAIN }
return null
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
handleError({
val walletId = getWalletId()
if (walletId == -1) return
val accountName = attributes.userName.nullize() ?: credentials?.userName
if (credentials.isEmpty()) {
kWallet.removeFolder(walletId, attributes.serviceName, appId)
}
else {
kWallet.writePassword(walletId, attributes.serviceName, accountName ?: "", credentials?.password?.toString() ?: "", appId)
}
}){}
}
override fun close() {
connection.use {
if (cachedWalletId != -1) {
kWallet.close(cachedWalletId, false, appId)
}
}
}
}
@DBusInterfaceName("org.kde.KWallet")
interface KWallet : DBusInterface {
fun localWallet(): String?
fun wallets(): List<String>
fun users(wallet: String): List<String>
fun isOpen(walletId: Int): Boolean
fun open(wallet: String, wId: Long, appId: String): Int
fun close(walletId: Int, force: Boolean, appId: String): Int
fun readPassword(walletId: Int, folder: String, key: String, appId: String): String?
fun readPasswordList(walletId: Int, folder: String, key: String, appId: String): Map<String, Variant<String>>
fun removeEntry(walletId: Int, folder: String, key: String, appId: String): Int
fun removeFolder(walletId: Int, folder: String, appId: String): Boolean
fun writePassword(walletId: Int, folder: String, key: String, value: String, appId: String): Int
}
|
apache-2.0
|
1c31f97064977f9c911b99c70a5de0ea
| 38.022727 | 158 | 0.659872 | 4.232539 | false | false | false | false |
smmribeiro/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/TargetPresentationBuilderImpl.kt
|
9
|
2277
|
// 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.codeInsight.navigation.impl
import com.intellij.navigation.TargetPresentation
import com.intellij.navigation.TargetPresentationBuilder
import com.intellij.openapi.editor.markup.TextAttributes
import org.jetbrains.annotations.Nls
import java.awt.Color
import javax.swing.Icon
/**
* `data` class for `#copy` method
*/
internal data class TargetPresentationBuilderImpl(
override val backgroundColor: Color? = null,
override val icon: Icon? = null,
override val presentableText: @Nls String,
override val presentableTextAttributes: TextAttributes? = null,
override val containerText: @Nls String? = null,
override val containerTextAttributes: TextAttributes? = null,
override val locationText: @Nls String? = null,
override val locationIcon: Icon? = null,
) : TargetPresentationBuilder, TargetPresentation {
override fun presentation(): TargetPresentation = this
override fun backgroundColor(color: Color?): TargetPresentationBuilder {
return copy(backgroundColor = color)
}
override fun icon(icon: Icon?): TargetPresentationBuilder {
return copy(icon = icon)
}
override fun presentableText(text: String): TargetPresentationBuilder {
return copy(presentableText = text)
}
override fun presentableTextAttributes(attributes: TextAttributes?): TargetPresentationBuilder {
return copy(presentableTextAttributes = attributes)
}
override fun containerText(text: String?): TargetPresentationBuilder {
return copy(containerText = text)
}
override fun containerText(text: String?, attributes: TextAttributes?): TargetPresentationBuilder {
return copy(containerText = text, containerTextAttributes = attributes)
}
override fun containerTextAttributes(attributes: TextAttributes?): TargetPresentationBuilder {
return copy(containerTextAttributes = attributes)
}
override fun locationText(text: String?): TargetPresentationBuilder {
return copy(locationText = text)
}
override fun locationText(text: String?, icon: Icon?): TargetPresentationBuilder {
return copy(locationText = text, locationIcon = icon)
}
}
|
apache-2.0
|
188237f99976b54c66aa1048feb785a5
| 35.725806 | 158 | 0.775582 | 5.004396 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/viewmodels/SetPasswordViewModel.kt
|
1
|
7984
|
package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.CurrentUserType
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.extensions.isNotEmptyAndAtLeast6Chars
import com.kickstarter.libs.utils.extensions.maskEmail
import com.kickstarter.libs.utils.extensions.newPasswordValidationWarnings
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.SetPasswordActivity
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface SetPasswordViewModel {
interface Inputs {
/** Call when the user clicks the change password button. */
fun changePasswordClicked()
/** Call when the current password field changes. */
fun confirmPassword(confirmPassword: String)
/** Call when the new password field changes. */
fun newPassword(newPassword: String)
}
interface Outputs {
/** Emits when the password update was unsuccessful. */
fun error(): Observable<String>
/** Emits a string resource to display when the user's new password entries are invalid. */
fun passwordWarning(): Observable<Int>
/** Emits when the progress bar should be visible. */
fun progressBarIsVisible(): Observable<Boolean>
/** Emits when the save button should be enabled. */
fun saveButtonIsEnabled(): Observable<Boolean>
/** Emits when the password update was successful. */
fun success(): Observable<String>
/** Emits a boolean that determines if the form is in the progress of being submitted. */
fun isFormSubmitting(): Observable<Boolean>
/** Emits when with user email to set password */
fun setUserEmail(): Observable<String>
}
class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<SetPasswordActivity>(environment), Inputs, Outputs {
private val changePasswordClicked = PublishSubject.create<Void>()
private val confirmPassword = PublishSubject.create<String>()
private val newPassword = PublishSubject.create<String>()
private val isFormSubmitting = PublishSubject.create<Boolean>()
private val error = BehaviorSubject.create<String>()
private val passwordWarning = BehaviorSubject.create<Int>()
private val progressBarIsVisible = BehaviorSubject.create<Boolean>()
private val saveButtonIsEnabled = BehaviorSubject.create<Boolean>()
private val success = BehaviorSubject.create<String>()
private val setUserEmail = BehaviorSubject.create<String>()
val inputs: Inputs = this
val outputs: Outputs = this
private val apolloClient = requireNotNull(this.environment.apolloClient())
private val currentUser: CurrentUserType = requireNotNull(environment.currentUser())
init {
intent()
.filter { it.hasExtra(IntentKey.EMAIL) }
.map {
it.getStringExtra(IntentKey.EMAIL)
}
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.map { it.maskEmail() }
.compose(bindToLifecycle())
.subscribe {
this.setUserEmail.onNext(it)
}
val setNewPassword = Observable.combineLatest(
this.newPassword.startWith(""),
this.confirmPassword.startWith("")
) { new, confirm -> SetNewPassword(new, confirm) }
setNewPassword
.map { it.warning() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.passwordWarning)
setNewPassword
.map { it.isValid() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.saveButtonIsEnabled)
val setNewPasswordNotification = setNewPassword
.compose(Transformers.takeWhen(this.changePasswordClicked))
.switchMap { cp -> submit(cp).materialize() }
.compose(bindToLifecycle())
.share()
val apiError = setNewPasswordNotification
.compose(Transformers.errors())
.filter { ObjectUtils.isNotNull(it.localizedMessage) }
.map {
requireNotNull(it.localizedMessage)
}
val error = setNewPasswordNotification
.compose(Transformers.errors())
.map { ErrorEnvelope.fromThrowable(it) }
.map { it?.errorMessage() }
.filter { ObjectUtils.isNotNull(it) }
.map {
requireNotNull(it)
}
Observable.merge(apiError, error)
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.error.onNext(it)
}
val userHasPassword = setNewPasswordNotification
.compose(Transformers.values())
.filter { it.updateUserAccount()?.user()?.hasPassword() }
this.currentUser.loggedInUser()
.compose(Transformers.takePairWhen(userHasPassword))
.distinctUntilChanged()
.subscribe {
currentUser.accessToken?.let { it1 ->
currentUser.login(
it.first.toBuilder().needsPassword(false).build(),
it1
)
}
this.success.onNext(it.second.updateUserAccount()?.user()?.email())
}
}
private fun submit(setNewPassword: SetNewPassword): Observable<UpdateUserPasswordMutation.Data> {
return this.apolloClient.updateUserPassword("", setNewPassword.newPassword, setNewPassword.confirmPassword)
.doOnSubscribe {
this.progressBarIsVisible.onNext(true)
this.isFormSubmitting.onNext(true)
}
.doAfterTerminate {
this.progressBarIsVisible.onNext(false)
this.isFormSubmitting.onNext(false)
}
}
override fun changePasswordClicked() {
this.changePasswordClicked.onNext(null)
}
override fun confirmPassword(confirmPassword: String) {
this.confirmPassword.onNext(confirmPassword)
}
override fun newPassword(newPassword: String) {
this.newPassword.onNext(newPassword)
}
override fun error(): Observable<String> = this.error
override fun passwordWarning(): Observable<Int> = this.passwordWarning
override fun progressBarIsVisible(): Observable<Boolean> = this.progressBarIsVisible
override fun saveButtonIsEnabled(): Observable<Boolean> = this.saveButtonIsEnabled
override fun isFormSubmitting(): Observable<Boolean> = this.isFormSubmitting
override fun success(): Observable<String> = this.success
override fun setUserEmail(): Observable<String> = this.setUserEmail
data class SetNewPassword(val newPassword: String, val confirmPassword: String) {
fun isValid(): Boolean {
return this.newPassword.isNotEmptyAndAtLeast6Chars() &&
this.confirmPassword.isNotEmptyAndAtLeast6Chars() &&
this.confirmPassword == this.newPassword
}
fun warning(): Int? =
newPassword.newPasswordValidationWarnings(confirmPassword)
}
}
}
|
apache-2.0
|
3646b3e3e70d5ca08c28d47d0e42eb53
| 39.734694 | 131 | 0.615982 | 5.690663 | false | false | false | false |
kivensolo/UiUsingListView
|
app/src/main/kotlin/com/zeke/ktx/modules/aac/ViewModelDemoActivity.kt
|
1
|
3171
|
package com.zeke.ktx.modules.aac
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.kingz.customdemo.R
import com.kingz.module.common.BaseActivity
import com.zeke.kangaroo.utils.ZLog
import com.zeke.ktx.modules.aac.viewmodels.User
import com.zeke.ktx.modules.aac.viewmodels.UserInfoViewModel
import kotlinx.android.synthetic.main.activity_crossfade.*
/**
* author: King.Z <br></br>
* date: 2020/4/20 23:37 <br></br>
* 一个简单的展示ViewModel和LiveData的
*/
class ViewModelDemoActivity : BaseActivity() {
private var mShortAnimationDuration = 800
private var testViewModel: UserInfoViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crossfade)
content!!.visibility = View.GONE
crossFade()
// 创建与当前activity相关的LiveData 对象
testViewModel = ViewModelProviders.of(this).get(UserInfoViewModel::class.java)
// Create the observer which updates the UI.
val nameObserver: Observer<User> = Observer {
// 当数据变化时回调onChange方法
ZLog.d("onChanged ", "it: $it")
lorem_ipsum_view?.text = it.toString()
}
/**
* 将 Observer 对象附加到 LiveData 对象, observe() 方法会采用 LifecycleOwner 对象。
* 这样会使 Observer 对象订阅 LiveData 对象,以使其收到有关更改的通知。
* 通常情况下,可以在界面控制器(如 Activity 或 Fragment)中附加 Observer 对象。
*
* 若要注册未关联 LifecycleOwner 对象可以使用 observeForever(Observer) 方法
*/
testViewModel?.run{
testStringLiveData.observe(this@ViewModelDemoActivity, nameObserver)
// 更新存储在 LiveData 对象中的值时,
// 它会触发所有已注册的观察者(只要附加的 LifecycleOwner 处于活跃状态)
testStringLiveData.value = User("KingZ","27","Boy")
}
lorem_ipsum_view.setOnClickListener {
testViewModel?.let {
it.testStringLiveData.value = User("KingZZZZZ","27777","Boyyyy")
}
}
}
private fun crossFade() { // Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
content?.alpha = 0f
content?.visibility = View.VISIBLE
content?.animate()?.apply {
alpha(1f)
duration = mShortAnimationDuration.toLong()
setListener(null)
}
loading_spinner?.animate()?.apply {
alpha(0f)
duration = mShortAnimationDuration.toLong()
setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
loading_spinner!!.visibility = View.GONE
}
})
}
}
}
|
gpl-2.0
|
c0c3e5b8a671c786fd0e654dd3536335
| 34.555556 | 102 | 0.649184 | 4.221408 | false | true | false | false |
feelfreelinux/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mywykop/observedtags/MyWykopObservedTagsFragment.kt
|
1
|
3273
|
package io.github.feelfreelinux.wykopmobilny.ui.modules.mywykop.observedtags
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.base.BaseFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.ObservedTagResponse
import io.github.feelfreelinux.wykopmobilny.ui.adapters.ObservedTagsAdapter
import io.github.feelfreelinux.wykopmobilny.ui.modules.mywykop.MyWykopNotifier
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import kotlinx.android.synthetic.main.activity_conversations_list.*
import javax.inject.Inject
class MyWykopObservedTagsFragment : BaseFragment(), MyWykopObservedTagsView, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener,
MyWykopNotifier {
companion object {
const val DATA_FRAGMENT_TAG = "MYWYKOP_OBSERVED_TAGS_FRAGMENT_TAG"
fun newInstance() = MyWykopObservedTagsFragment()
}
@Inject lateinit var adapter: ObservedTagsAdapter
@Inject lateinit var presenter: MyWykopObservedTagsPresenter
lateinit var dataFragment: DataFragment<List<ObservedTagResponse>>
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.activity_conversations_list, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
presenter.subscribe(this)
dataFragment = childFragmentManager.getDataFragmentInstance(DATA_FRAGMENT_TAG)
presenter.subscribe(this)
swiperefresh.setOnRefreshListener(this)
recyclerView?.prepare()
recyclerView?.adapter = adapter
if (dataFragment.data != null) {
adapter.items.clear()
adapter.items.addAll(dataFragment.data!!)
adapter.notifyDataSetChanged()
} else {
loadingView?.isVisible = true
presenter.loadTags()
}
}
override fun onRefresh() {
if (!swiperefresh.isRefreshing) swiperefresh?.isRefreshing = true
presenter.loadTags()
}
override fun showTags(tags: List<ObservedTagResponse>) {
loadingView?.isVisible = false
swiperefresh?.isRefreshing = false
adapter.items.clear()
adapter.items.addAll(tags)
adapter.notifyDataSetChanged()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
dataFragment.data = adapter.items
}
override fun onDetach() {
presenter.unsubscribe()
super.onDetach()
}
override fun onPause() {
if (isRemoving) childFragmentManager.removeDataFragment(dataFragment)
super.onPause()
}
override fun removeDataFragment() = childFragmentManager.removeDataFragment(dataFragment)
}
|
mit
|
2069fe69f56675f4c1197550a6cb89fe
| 37.517647 | 149 | 0.751604 | 5.004587 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/framework/KotlinSdkType.kt
|
1
|
3566
|
// 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.framework
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.util.Consumer
import org.jdom.Element
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import javax.swing.JComponent
class KotlinSdkType : SdkType("KotlinSDK") {
companion object {
@JvmField
val INSTANCE = KotlinSdkType()
val defaultHomePath: String
get() = KotlinArtifacts.instance.kotlincDirectory.absolutePath
@JvmOverloads
fun setUpIfNeeded(disposable: Disposable? = null, checkIfNeeded: () -> Boolean = { true }) {
val projectSdks: Array<Sdk> = ProjectJdkTable.getInstance().allJdks
if (projectSdks.any { it.sdkType is KotlinSdkType }) return
if (!checkIfNeeded()) return // do not create Kotlin SDK
val newSdkName = SdkConfigurationUtil.createUniqueSdkName(INSTANCE, defaultHomePath, projectSdks.toList())
val newJdk = ProjectJdkImpl(newSdkName, INSTANCE)
newJdk.homePath = defaultHomePath
INSTANCE.setupSdkPaths(newJdk)
ApplicationManager.getApplication().invokeAndWait {
runWriteAction {
if (ProjectJdkTable.getInstance().allJdks.any { it.sdkType is KotlinSdkType }) return@runWriteAction
if (disposable != null) {
ProjectJdkTable.getInstance().addJdk(newJdk, disposable)
} else {
ProjectJdkTable.getInstance().addJdk(newJdk)
}
}
}
}
}
override fun getPresentableName() = KotlinIdeaAnalysisBundle.message("framework.name.kotlin.sdk")
override fun getIcon() = KotlinIcons.SMALL_LOGO
override fun isValidSdkHome(path: String) = true
override fun suggestSdkName(currentSdkName: String?, sdkHome: String) = "Kotlin SDK"
override fun suggestHomePath() = null
override fun sdkHasValidPath(sdk: Sdk) = true
override fun getVersionString(sdk: Sdk): String = KotlinCompilerVersion.VERSION
override fun supportsCustomCreateUI() = true
override fun showCustomCreateUI(sdkModel: SdkModel, parentComponent: JComponent, selectedSdk: Sdk?, sdkCreatedCallback: Consumer<in Sdk>) {
sdkCreatedCallback.consume(createSdkWithUniqueName(sdkModel.sdks.toList()))
}
fun createSdkWithUniqueName(existingSdks: Collection<Sdk>): ProjectJdkImpl {
val sdkName = suggestSdkName(SdkConfigurationUtil.createUniqueSdkName(this, "", existingSdks), "")
return ProjectJdkImpl(sdkName, this).apply {
homePath = defaultHomePath
}
}
override fun createAdditionalDataConfigurable(sdkModel: SdkModel, sdkModificator: SdkModificator) = null
override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) {
}
override fun allowCreationByUser(): Boolean {
return false
}
}
|
apache-2.0
|
53b43ea19d251f8d8e2d5271a35cc9be
| 40 | 158 | 0.71032 | 5.079772 | false | true | false | false |
SimpleMobileTools/Simple-Calendar
|
app/src/main/kotlin/com/simplemobiletools/calendar/pro/interfaces/TasksDao.kt
|
1
|
622
|
package com.simplemobiletools.calendar.pro.interfaces
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.simplemobiletools.calendar.pro.models.Task
@Dao
interface TasksDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(task: Task): Long
@Query("SELECT * FROM tasks WHERE task_id = :id AND start_ts = :startTs")
fun getTaskWithIdAndTs(id: Long, startTs: Long): Task?
@Query("DELETE FROM tasks WHERE task_id = :id AND start_ts = :startTs")
fun deleteTaskWithIdAndTs(id: Long, startTs: Long)
}
|
gpl-3.0
|
a71597a71e0f4292d674e6f83fdc67a0
| 31.736842 | 77 | 0.758842 | 3.792683 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/security/generate/GenerateSshKeyFactory.kt
|
2
|
755
|
package com.github.kerubistan.kerub.planner.steps.host.security.generate
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import kotlin.reflect.KClass
object GenerateSshKeyFactory : AbstractOperationalStepFactory<GenerateSshKey>() {
override val problemHints = setOf<KClass<out Problem>>()
override val expectationHints = setOf<KClass<out Expectation>>()
override fun produce(state: OperationalState): List<GenerateSshKey> = state.index.runningHosts
.filter { it.config?.publicKey == null }
.map { GenerateSshKey(host = it.stat) }
}
|
apache-2.0
|
a7b40b668a3c850425f96759621eac1e
| 46.25 | 95 | 0.817219 | 4.217877 | false | true | false | false |
JetBrains/kotlin-native
|
klib/src/main/kotlin/org/jetbrains/kotlin/cli/klib/DeclarationPrinter.kt
|
3
|
4817
|
package org.jetbrains.kotlin.cli.klib
import org.jetbrains.kotlin.backend.konan.descriptors.getPackageFragments
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.DeclarationDescriptorVisitorEmptyBodies
import org.jetbrains.kotlin.utils.Printer
class DeclarationPrinter(
out: Appendable,
private val headerRenderer: DeclarationHeaderRenderer,
private val signatureRenderer: IdSignatureRenderer
) {
private val printer = Printer(out, 1, " ")
private val DeclarationDescriptorWithVisibility.isPublicOrProtected: Boolean
get() = visibility == DescriptorVisibilities.PUBLIC || visibility == DescriptorVisibilities.PROTECTED
private val CallableMemberDescriptor.isFakeOverride: Boolean
get() = kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE
private val DeclarationDescriptor.shouldBePrinted: Boolean
get() = this is ClassifierDescriptorWithTypeParameters && isPublicOrProtected
|| this is CallableMemberDescriptor && isPublicOrProtected && !isFakeOverride
fun print(module: ModuleDescriptor) {
module.accept(PrinterVisitor(), Unit)
}
private fun Printer.printWithBody(header: String, signature: String? = null, body: () -> Unit) {
println()
printPlain(header, signature, suffix = " {")
pushIndent()
body()
popIndent()
println("}")
println()
}
private fun Printer.printPlain(header: String, signature: String? = null, suffix: String? = null) {
if (signature != null) println(signature)
println(if (suffix != null ) header + suffix else header)
}
private inner class PrinterVisitor : DeclarationDescriptorVisitorEmptyBodies<Unit, Unit>() {
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, data: Unit) {
descriptor.getPackageFragments().forEach { it.accept(this, data) }
}
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, data: Unit) {
val children = descriptor.getMemberScope().getContributedDescriptors()
.filter { it.shouldBePrinted }
.sortedBy { it.name }
if (children.isNotEmpty()) {
printer.printWithBody(header = headerRenderer.render(descriptor)) {
children.forEach { it.accept(this, data) }
}
}
}
override fun visitClassDescriptor(descriptor: ClassDescriptor, data: Unit) {
val header = headerRenderer.render(descriptor)
val signature = signatureRenderer.render(descriptor)
val children = descriptor.unsubstitutedMemberScope.getContributedDescriptors().filter { it.shouldBePrinted }
val constructors = descriptor.constructors.filter { !it.isPrimary && it.shouldBePrinted }
if (children.isNotEmpty() || constructors.isNotEmpty()) {
printer.printWithBody(header, signature) {
constructors.forEach { it.accept(this, data) }
children.forEach { it.accept(this, data) }
}
} else {
printer.printPlain(header, signature)
}
}
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: Unit) {
printer.printPlain(header = headerRenderer.render(descriptor), signature = signatureRenderer.render(descriptor))
}
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: Unit) {
printer.printPlain(header = headerRenderer.render(descriptor), signature = signatureRenderer.render(descriptor))
descriptor.getter?.takeIf { !it.annotations.isEmpty() }?.let { getter ->
printer.pushIndent()
printer.printPlain(header = headerRenderer.render(getter), signature = signatureRenderer.render(getter))
printer.popIndent()
}
descriptor.setter?.takeIf { !it.annotations.isEmpty() || it.visibility != descriptor.visibility }?.let { setter ->
printer.pushIndent()
printer.printPlain(header = headerRenderer.render(setter), signature = signatureRenderer.render(setter))
printer.popIndent()
}
}
override fun visitConstructorDescriptor(descriptor: ConstructorDescriptor, data: Unit) {
printer.printPlain(header = headerRenderer.render(descriptor), signature = signatureRenderer.render(descriptor))
}
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, data: Unit) {
printer.printPlain(header = headerRenderer.render(descriptor), signature = signatureRenderer.render(descriptor))
}
}
}
|
apache-2.0
|
a26d3e362954e42030962e50f878ae0a
| 46.22549 | 126 | 0.666597 | 5.358176 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SimplifyComparisonFix.kt
|
1
|
2550
|
// 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters2
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.inspections.ConstantConditionIfInspection
import org.jetbrains.kotlin.idea.intentions.SimplifyBooleanWithConstantsIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class SimplifyComparisonFix(element: KtExpression, val value: Boolean) : KotlinQuickFixAction<KtExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("simplify.0.to.1", element.toString(), value)
override fun getText() = KotlinBundle.message("simplify.comparison")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replacement = KtPsiFactory(project).createExpression("$value")
val result = element.replaced(replacement)
val booleanExpression = result.getNonStrictParentOfType<KtBinaryExpression>()
val simplifyIntention = SimplifyBooleanWithConstantsIntention()
if (booleanExpression != null && simplifyIntention.isApplicableTo(booleanExpression)) {
simplifyIntention.applyTo(booleanExpression, editor)
} else {
simplifyIntention.removeRedundantAssertion(result)
}
val ifExpression = result.getStrictParentOfType<KtIfExpression>()?.takeIf { it.condition == result }
if (ifExpression != null) ConstantConditionIfInspection.applyFixIfSingle(ifExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val value = (diagnostic as? DiagnosticWithParameters2<*, *, *>)?.b as? Boolean ?: return null
return SimplifyComparisonFix(expression, value)
}
}
}
|
apache-2.0
|
03df56540b65b63bf31b8a3ff059ce1c
| 52.145833 | 158 | 0.769412 | 5.079681 | false | false | false | false |
OpenConference/DroidconBerlin2017
|
app/src/main/java/de/droidcon/berlin2018/ui/PicassoListener.kt
|
1
|
1320
|
package de.droidcon.berlin2018.ui
import android.support.v7.widget.RecyclerView
import com.squareup.picasso.Picasso
/**
* This is a scroll listener that listens for scroll events on recyclerviews
* to avoid picasso loading images while scrolling (avoid laggy scroll behavior)
*/
class PicassoScrollListener(private val picasso: Picasso) : RecyclerView.OnScrollListener() {
companion object {
val TAG = "PicassoScrollTag"
}
private var previousScrollState = RecyclerView.SCROLL_STATE_IDLE
private var scrollingFirstTime = true
init {
picasso.resumeTag(TAG)
}
override fun onScrollStateChanged(view: RecyclerView?, scrollState: Int) {
if (scrollingFirstTime) {
resume()
scrollingFirstTime = false
}
// TO the picasso staff
if (!isScrolling(scrollState) && isScrolling(previousScrollState)) {
resume()
}
if (isScrolling(scrollState) && !isScrolling(previousScrollState)) {
pause()
}
previousScrollState = scrollState
}
private inline fun isScrolling(scrollState: Int): Boolean {
return scrollState == RecyclerView.SCROLL_STATE_DRAGGING || scrollState == RecyclerView.SCROLL_STATE_SETTLING
}
private inline fun resume() {
picasso.resumeTag(TAG)
}
private inline fun pause() {
picasso.pauseTag(TAG)
}
}
|
apache-2.0
|
369b57f331c24718743ae3f70de89746
| 23 | 113 | 0.717424 | 4.599303 | false | false | false | false |
androidx/androidx
|
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/grid/LazyGridAnimateScrollScope.kt
|
3
|
4132
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.grid
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.lazy.layout.LazyAnimateScrollScope
import androidx.compose.ui.unit.Density
import androidx.compose.ui.util.fastFirstOrNull
import kotlin.math.max
internal class LazyGridAnimateScrollScope(
private val state: LazyGridState
) : LazyAnimateScrollScope {
override val density: Density get() = state.density
override val firstVisibleItemIndex: Int get() = state.firstVisibleItemIndex
override val firstVisibleItemScrollOffset: Int get() = state.firstVisibleItemScrollOffset
override val lastVisibleItemIndex: Int
get() = state.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
override val itemCount: Int get() = state.layoutInfo.totalItemsCount
override fun getTargetItemOffset(index: Int): Int? =
state.layoutInfo.visibleItemsInfo
.fastFirstOrNull {
it.index == index
}?.let { item ->
if (state.isVertical) {
item.offset.y
} else {
item.offset.x
}
}
override fun ScrollScope.snapToItem(index: Int, scrollOffset: Int) {
state.snapToItemIndexInternal(index, scrollOffset)
}
override fun expectedDistanceTo(index: Int, targetScrollOffset: Int): Float {
val visibleItems = state.layoutInfo.visibleItemsInfo
val slotsPerLine = state.slotsPerLine
val averageLineMainAxisSize = calculateLineAverageMainAxisSize(
visibleItems,
state.isVertical
)
val before = index < firstVisibleItemIndex
val linesDiff =
(index - firstVisibleItemIndex + (slotsPerLine - 1) * if (before) -1 else 1) /
slotsPerLine
return (averageLineMainAxisSize * linesDiff).toFloat() +
targetScrollOffset - firstVisibleItemScrollOffset
}
override val numOfItemsForTeleport: Int get() = 100 * state.slotsPerLine
private fun calculateLineAverageMainAxisSize(
visibleItems: List<LazyGridItemInfo>,
isVertical: Boolean
): Int {
val lineOf: (Int) -> Int = {
if (isVertical) visibleItems[it].row else visibleItems[it].column
}
var totalLinesMainAxisSize = 0
var linesCount = 0
var lineStartIndex = 0
while (lineStartIndex < visibleItems.size) {
val currentLine = lineOf(lineStartIndex)
if (currentLine == -1) {
// Filter out exiting items.
++lineStartIndex
continue
}
var lineMainAxisSize = 0
var lineEndIndex = lineStartIndex
while (lineEndIndex < visibleItems.size && lineOf(lineEndIndex) == currentLine) {
lineMainAxisSize = max(
lineMainAxisSize,
if (isVertical) {
visibleItems[lineEndIndex].size.height
} else {
visibleItems[lineEndIndex].size.width
}
)
++lineEndIndex
}
totalLinesMainAxisSize += lineMainAxisSize
++linesCount
lineStartIndex = lineEndIndex
}
return totalLinesMainAxisSize / linesCount
}
override suspend fun scroll(block: suspend ScrollScope.() -> Unit) {
state.scroll(block = block)
}
}
|
apache-2.0
|
0ffe164247119b1b42a587610da52c35
| 33.731092 | 93 | 0.63456 | 5.277139 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/expression/KotlinTryExpressionSurrounder.kt
|
4
|
1404
|
// 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.codeInsight.surroundWith.expression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.codeInsight.surroundWith.statement.KotlinTrySurrounderBase
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtTryExpression
sealed class KotlinTryExpressionSurrounder : KotlinControlFlowExpressionSurrounderBase() {
class TryCatch : KotlinTryExpressionSurrounder() {
@NlsSafe
override fun getTemplateDescription() = "try { expr } catch {}"
override fun getPattern() = "try { $0 } catch (e: Exception) { TODO(\"Not yet implemented\") }"
}
class TryCatchFinally : KotlinTryExpressionSurrounder() {
@NlsSafe
override fun getTemplateDescription() = "try { expr } catch {} finally {}"
override fun getPattern() = "try { $0 } catch (e: Exception) { TODO(\"Not yet implemented\") } finally {}"
}
override fun getRange(editor: Editor, replaced: KtExpression): TextRange? {
val tryExpression = replaced as KtTryExpression
return KotlinTrySurrounderBase.getCatchTypeParameterTextRange(tryExpression)
}
}
|
apache-2.0
|
7527f00b0ac21b538c1ffb37c95b1a74
| 44.290323 | 158 | 0.742165 | 4.695652 | false | false | false | false |
GunoH/intellij-community
|
java/java-tests/testSrc/com/intellij/java/refactoring/suggested/JavaSignatureChangePresentationTest.kt
|
8
|
25386
|
// 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.java.refactoring.suggested
import com.intellij.refactoring.suggested.BaseSignatureChangePresentationTest
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
class JavaSignatureChangePresentationTest : BaseSignatureChangePresentationTest() {
override val refactoringSupport = JavaSuggestedRefactoringSupport()
private fun signature(
name: String,
type: String?,
parameters: List<Parameter>,
additionalData: SuggestedRefactoringSupport.SignatureAdditionalData? = null
): Signature? {
return Signature.create(name, type, parameters, additionalData)
}
fun testAddParameters() {
val oldSignature = signature(
"foo",
"String",
listOf(Parameter(0, "p1", "Int"))
)!!
val newSignature = signature(
"foo",
"String",
listOf(
Parameter(Any(), "p0", "Any"),
Parameter(0, "p1", "Int"),
Parameter(Any(), "p2", "Long")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'String'
' '
'foo'
'('
LineBreak('', true)
Group:
'Int'
' '
'p1'
LineBreak('', false)
')'
New:
'String'
' '
'foo'
'('
LineBreak('', true)
Group (added):
'Any'
' '
'p0'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group (added):
'Long'
' '
'p2'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParameters() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int"),
Parameter(1, "p2", "Long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "Long"),
Parameter(0, "p1", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'Long'
' '
'p2'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Long'
' '
'p2'
','
LineBreak(' ', true)
Group (moved):
'Int'
' '
'p1'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParametersAndRenameFirst() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int"),
Parameter(1, "p2", "Long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "Long"),
Parameter(0, "p1New", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'Int'
' '
'p1' (modified)
','
LineBreak(' ', true)
Group:
'Long'
' '
'p2'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Long'
' '
'p2'
','
LineBreak(' ', true)
Group (moved):
'Int'
' '
'p1New' (modified)
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParametersAndRenameSecond() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int"),
Parameter(1, "p2", "Long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2New", "Long"),
Parameter(0, "p1", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group (moved):
'Long'
' '
'p2' (modified)
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'Long'
' '
'p2New' (modified)
','
LineBreak(' ', true)
Group:
'Int'
' '
'p1'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParametersAndAddNewOne() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int"),
Parameter(1, "p2", "Long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "Long"),
Parameter(0, "p1", "Int"),
Parameter(2, "pNew", "String")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (id = 0, moved):
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'Long'
' '
'p2'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Long'
' '
'p2'
','
LineBreak(' ', true)
Group (id = 0, moved):
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group (added):
'String'
' '
'pNew'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParametersAndRemoveParameter() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int"),
Parameter(1, "p2", "Long"),
Parameter(2, "p", "String")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "Long"),
Parameter(0, "p1", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (id = 0, moved):
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'Long'
' '
'p2'
','
LineBreak(' ', true)
Group (removed):
'String'
' '
'p'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Long'
' '
'p2'
','
LineBreak(' ', true)
Group (id = 0, moved):
'Int'
' '
'p1'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testSwapParametersAndAddRemoveAnnotations() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "Int", JavaParameterAdditionalData("@NotNull")),
Parameter(1, "p2", "Int"),
Parameter(2, "p3", "Int"),
Parameter(3, "p4", "Int", JavaParameterAdditionalData("@NotNull")),
Parameter(4, "p5", "Int"),
Parameter(5, "p6", "Int"),
Parameter(6, "p7", "Int"),
Parameter(7, "p8", "Int")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "Int"),
Parameter(0, "p1", "Int"),
Parameter(3, "p4", "Int"),
Parameter(2, "p3", "Int"),
Parameter(5, "p6", "Int"),
Parameter(4, "p5", "Int", JavaParameterAdditionalData("@Nullable")),
Parameter(7, "p8", "Int", JavaParameterAdditionalData("@Nullable")),
Parameter(6, "p7", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (id = 0, moved):
'@NotNull' (removed)
' '
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p2'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p3'
','
LineBreak(' ', true)
Group (id = 3, moved):
'@NotNull' (removed)
' '
'Int'
' '
'p4'
','
LineBreak(' ', true)
Group (id = 4, moved):
'Int'
' '
'p5'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p6'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p7'
','
LineBreak(' ', true)
Group (id = 7, moved):
'Int'
' '
'p8'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'Int'
' '
'p2'
','
LineBreak(' ', true)
Group (id = 0, moved):
'Int'
' '
'p1'
','
LineBreak(' ', true)
Group (id = 3, moved):
'Int'
' '
'p4'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p3'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p6'
','
LineBreak(' ', true)
Group (id = 4, moved):
'@Nullable' (added)
' '
'Int'
' '
'p5'
','
LineBreak(' ', true)
Group (id = 7, moved):
'@Nullable' (added)
' '
'Int'
' '
'p8'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p7'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testChangeFunctionName() {
val oldSignature = signature("foo", "void", emptyList())!!
val newSignature = signature("bar", "void", emptyList())!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo' (modified)
'('
LineBreak('', false)
')'
New:
'void'
' '
'bar' (modified)
'('
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testChangeReturnType() {
val oldSignature = signature("foo", "Object", emptyList())!!
val newSignature = signature("foo", "String", emptyList())!!
doTest(
oldSignature,
newSignature,
"""
Old:
'Object' (modified)
' '
'foo'
'('
LineBreak('', false)
')'
New:
'String' (modified)
' '
'foo'
'('
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testChangeParameterName() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1New", "int"),
Parameter(1, "p2", "long")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1' (modified)
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1New' (modified)
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testChangeTwoParameterNames() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1New", "int"),
Parameter(1, "p2New", "long")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1' (modified)
','
LineBreak(' ', true)
Group:
'long'
' '
'p2' (modified)
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1New' (modified)
','
LineBreak(' ', true)
Group:
'long'
' '
'p2New' (modified)
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testMoveAndRenameParameter() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long"),
Parameter(2, "p3", "Object")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "long"),
Parameter(2, "p3", "Object"),
Parameter(0, "p1New", "int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'int'
' '
'p1' (modified)
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
','
LineBreak(' ', true)
Group:
'Object'
' '
'p3'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'long'
' '
'p2'
','
LineBreak(' ', true)
Group:
'Object'
' '
'p3'
','
LineBreak(' ', true)
Group (moved):
'int'
' '
'p1New' (modified)
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testMoveParameterAndAddAnnotation() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long"),
Parameter(2, "p3", "Object")
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(2, "p3", "Object", JavaParameterAdditionalData("@NotNull")),
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
','
LineBreak(' ', true)
Group (moved):
'Object'
' '
'p3'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'@NotNull' (added)
' '
'Object'
' '
'p3'
','
LineBreak(' ', true)
Group:
'int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testMoveParameterAndRemoveAnnotation() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long"),
Parameter(2, "p3", "Object", JavaParameterAdditionalData("@NotNull"))
)
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(2, "p3", "Object"),
Parameter(0, "p1", "int"),
Parameter(1, "p2", "long")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
','
LineBreak(' ', true)
Group (moved):
'@NotNull' (removed)
' '
'Object'
' '
'p3'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (moved):
'Object'
' '
'p3'
','
LineBreak(' ', true)
Group:
'int'
' '
'p1'
','
LineBreak(' ', true)
Group:
'long'
' '
'p2'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testAddParameterToConstructor() {
val oldSignature = signature(
"Foo",
null,
listOf(Parameter(0, "p1", "Int"))
)!!
val newSignature = signature(
"Foo",
null,
listOf(
Parameter(Any(), "p0", "Any"),
Parameter(0, "p1", "Int")
)
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'Foo'
'('
LineBreak('', true)
Group:
'Int'
' '
'p1'
LineBreak('', false)
')'
New:
'Foo'
'('
LineBreak('', true)
Group (added):
'Any'
' '
'p0'
','
LineBreak(' ', true)
Group:
'Int'
' '
'p1'
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testAnnotations() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "String", JavaParameterAdditionalData("@Nullable")),
Parameter(1, "p2", "String"),
Parameter(2, "p3", "Object", JavaParameterAdditionalData("@Nullable"))
),
JavaDeclarationAdditionalData("public", "", emptyList())
)!!
val newSignature = signature(
"foo",
"Object",
listOf(
Parameter(1, "p2", "String", JavaParameterAdditionalData("@NotNull")),
Parameter(2, "p3", "Object"),
Parameter(0, "p1New", "String", JavaParameterAdditionalData("@NotNull"))
),
JavaDeclarationAdditionalData("public", "@NotNull", emptyList())
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void' (modified)
' '
'foo'
'('
LineBreak('', true)
Group (id = 0, moved):
'@Nullable' (modified)
' '
'String'
' '
'p1' (modified)
','
LineBreak(' ', true)
Group:
'String'
' '
'p2'
','
LineBreak(' ', true)
Group:
'@Nullable' (removed)
' '
'Object'
' '
'p3'
LineBreak('', false)
')'
New:
'@NotNull' (added)
' '
'Object' (modified)
' '
'foo'
'('
LineBreak('', true)
Group:
'@NotNull' (added)
' '
'String'
' '
'p2'
','
LineBreak(' ', true)
Group:
'Object'
' '
'p3'
','
LineBreak(' ', true)
Group (id = 0, moved):
'@NotNull' (modified)
' '
'String'
' '
'p1New' (modified)
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testReorderExceptions() {
val oldSignature = signature(
"foo",
"void",
emptyList(),
JavaDeclarationAdditionalData("public", "", listOf("IOException", "SQLException", "NumberFormatException"))
)!!
val newSignature = signature(
"foo",
"void",
emptyList(),
JavaDeclarationAdditionalData("public", "", listOf("NumberFormatException", "IOException", "SQLException"))
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException'
','
LineBreak(' ', true)
'SQLException'
','
LineBreak(' ', true)
'NumberFormatException' (moved)
New:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'NumberFormatException' (moved)
','
LineBreak(' ', true)
'IOException'
','
LineBreak(' ', true)
'SQLException'
""".trimIndent()
)
}
fun testSwapExceptionsAndParameters() {
val oldSignature = signature(
"foo",
"void",
listOf(
Parameter(0, "p1", "String"),
Parameter(1, "p2", "int")
),
JavaDeclarationAdditionalData("public", "", listOf("IOException", "SQLException"))
)!!
val newSignature = signature(
"foo",
"void",
listOf(
Parameter(1, "p2", "int"),
Parameter(0, "p1", "String")
),
JavaDeclarationAdditionalData("public", "", listOf("SQLException", "IOException"))
)!!
doTest(
oldSignature,
newSignature,
"""
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (id = 0, moved):
'String'
' '
'p1'
','
LineBreak(' ', true)
Group:
'int'
' '
'p2'
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException' (id = ExceptionConnectionId(oldIndex=0), moved)
','
LineBreak(' ', true)
'SQLException'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'int'
' '
'p2'
','
LineBreak(' ', true)
Group (id = 0, moved):
'String'
' '
'p1'
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'SQLException'
','
LineBreak(' ', true)
'IOException' (id = ExceptionConnectionId(oldIndex=0), moved)
""".trimIndent()
)
}
}
|
apache-2.0
|
236f7167afe9f12034efae4bdeb3a22c
| 19.809016 | 140 | 0.362601 | 4.555994 | false | false | false | false |
loxal/FreeEthereum
|
free-ethereum-core/src/main/java/org/ethereum/net/server/Channel.kt
|
1
|
12497
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.net.server
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPipeline
import io.netty.handler.timeout.ReadTimeoutHandler
import org.ethereum.config.SystemProperties
import org.ethereum.core.Block
import org.ethereum.core.BlockHeaderWrapper
import org.ethereum.core.Transaction
import org.ethereum.db.ByteArrayWrapper
import org.ethereum.net.MessageQueue
import org.ethereum.net.client.Capability
import org.ethereum.net.eth.EthVersion
import org.ethereum.net.eth.handler.Eth
import org.ethereum.net.eth.handler.EthAdapter
import org.ethereum.net.eth.handler.EthHandlerFactory
import org.ethereum.net.eth.message.Eth62MessageFactory
import org.ethereum.net.eth.message.Eth63MessageFactory
import org.ethereum.net.message.MessageFactory
import org.ethereum.net.message.ReasonCode
import org.ethereum.net.message.StaticMessages
import org.ethereum.net.p2p.HelloMessage
import org.ethereum.net.p2p.P2pHandler
import org.ethereum.net.p2p.P2pMessageFactory
import org.ethereum.net.rlpx.*
import org.ethereum.net.rlpx.discover.NodeManager
import org.ethereum.net.rlpx.discover.NodeStatistics
import org.ethereum.net.shh.ShhHandler
import org.ethereum.net.shh.ShhMessageFactory
import org.ethereum.net.swarm.bzz.BzzHandler
import org.ethereum.net.swarm.bzz.BzzMessageFactory
import org.ethereum.sync.SyncStatistics
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
import java.io.IOException
import java.math.BigInteger
import java.net.InetSocketAddress
import java.util.concurrent.TimeUnit
/**
* @author Roman Mandeleil
* *
* @since 01.11.2014
*/
@Component
@Scope("prototype")
open class Channel {
val peerStats = PeerStatistics()
@Autowired
private var config: SystemProperties? = null
@Autowired
private val msgQueue: MessageQueue? = null
@Autowired
private val p2pHandler: P2pHandler? = null
@Autowired
private val shhHandler: ShhHandler? = null
@Autowired
private val bzzHandler: BzzHandler? = null
@Autowired
private var messageCodec: MessageCodec? = null
@Autowired
private val handshakeHandler: HandshakeHandler? = null
@Autowired
private val nodeManager: NodeManager? = null
@Autowired
private val ethHandlerFactory: EthHandlerFactory? = null
@Autowired
private val staticMessages: StaticMessages? = null
@Autowired
private val stats: WireTrafficStats? = null
var channelManager: ChannelManager? = null
private set
var ethHandler: Eth = EthAdapter()
private set
var inetSocketAddress: InetSocketAddress? = null
var node: Node? = null
private set
var nodeStatistics: NodeStatistics? = null
private set
var isDiscoveryMode: Boolean = false
private set
/**
* Indicates whether this connection was initiated by our peer
*/
var isActive: Boolean = false
private set
var isDisconnected: Boolean = false
private set
private var remoteId: String? = null
fun init(pipeline: ChannelPipeline, remoteId: String?, discoveryMode: Boolean, channelManager: ChannelManager) {
this.channelManager = channelManager
this.remoteId = remoteId
isActive = remoteId != null && !remoteId.isEmpty()
pipeline.addLast("readTimeoutHandler",
ReadTimeoutHandler(config!!.peerChannelReadTimeout()!!.toLong(), TimeUnit.SECONDS))
pipeline.addLast(stats!!.tcp)
pipeline.addLast("handshakeHandler", handshakeHandler)
this.isDiscoveryMode = discoveryMode
if (discoveryMode) {
// temporary key/nodeId to not accidentally smear our reputation with
// unexpected disconnect
// handshakeHandler.generateTempKey();
}
handshakeHandler!!.setRemoteId(remoteId, this)
messageCodec!!.setChannel(this)
msgQueue!!.setChannel(this)
p2pHandler!!.setMsgQueue(msgQueue)
messageCodec!!.setP2pMessageFactory(P2pMessageFactory())
shhHandler!!.setMsgQueue(msgQueue)
messageCodec!!.setShhMessageFactory(ShhMessageFactory())
bzzHandler!!.setMsgQueue(msgQueue)
messageCodec!!.setBzzMessageFactory(BzzMessageFactory())
}
@Throws(IOException::class, InterruptedException::class)
fun publicRLPxHandshakeFinished(ctx: ChannelHandlerContext, frameCodec: FrameCodec,
helloRemote: HelloMessage) {
logger.debug("publicRLPxHandshakeFinished with " + ctx.channel().remoteAddress())
if (P2pHandler.isProtocolVersionSupported(helloRemote.p2PVersion)) {
if (helloRemote.p2PVersion < 5) {
messageCodec!!.setSupportChunkedFrames(false)
}
val frameCodecHandler = FrameCodecHandler(frameCodec, this)
ctx.pipeline().addLast("medianFrameCodec", frameCodecHandler)
ctx.pipeline().addLast("messageCodec", messageCodec)
ctx.pipeline().addLast(Capability.P2P, p2pHandler)
p2pHandler!!.setChannel(this)
p2pHandler.setHandshake(helloRemote, ctx)
nodeStatistics!!.rlpxHandshake.add()
}
}
@Throws(IOException::class, InterruptedException::class)
fun sendHelloMessage(ctx: ChannelHandlerContext, frameCodec: FrameCodec, nodeId: String,
inboundHelloMessage: HelloMessage?) {
val helloMessage = staticMessages!!.createHelloMessage(nodeId)
if (inboundHelloMessage != null && P2pHandler.isProtocolVersionSupported(inboundHelloMessage.p2PVersion)) {
// the p2p version can be downgraded if requested by peer and supported by us
helloMessage.setP2pVersion(inboundHelloMessage.p2PVersion)
}
val byteBufMsg = ctx.alloc().buffer()
frameCodec.writeFrame(FrameCodec.Frame(helloMessage.code.toInt(), helloMessage.encoded), byteBufMsg)
ctx.writeAndFlush(byteBufMsg).sync()
if (logger.isDebugEnabled)
logger.debug("To: {} Send: {}", ctx.channel().remoteAddress(), helloMessage)
nodeStatistics!!.rlpxOutHello.add()
}
fun activateEth(ctx: ChannelHandlerContext, version: EthVersion) {
val handler = ethHandlerFactory!!.create(version)
val messageFactory = createEthMessageFactory(version)
messageCodec!!.setEthVersion(version)
messageCodec!!.setEthMessageFactory(messageFactory)
logger.debug("Eth{} [ address = {} | id = {} ]", handler.version, inetSocketAddress, peerIdShort)
ctx.pipeline().addLast(Capability.ETH, handler)
handler.setMsgQueue(msgQueue)
handler.setChannel(this)
handler.setPeerDiscoveryMode(isDiscoveryMode)
handler.activate()
ethHandler = handler
}
private fun createEthMessageFactory(version: EthVersion): MessageFactory {
when (version) {
EthVersion.V62 -> return Eth62MessageFactory()
EthVersion.V63 -> return Eth63MessageFactory()
else -> throw IllegalArgumentException("Eth $version is not supported")
}
}
fun activateShh(ctx: ChannelHandlerContext) {
ctx.pipeline().addLast(Capability.SHH, shhHandler)
shhHandler!!.activate()
}
fun activateBzz(ctx: ChannelHandlerContext) {
ctx.pipeline().addLast(Capability.BZZ, bzzHandler)
bzzHandler!!.activate()
}
/**
* Set node and register it in NodeManager if it is not registered yet.
*/
@JvmOverloads fun initWithNode(nodeId: ByteArray, remotePort: Int = inetSocketAddress!!.port) {
node = Node(nodeId, inetSocketAddress!!.hostString, remotePort)
nodeStatistics = nodeManager!!.getNodeStatistics(node)
}
fun initMessageCodes(caps: List<Capability>) {
messageCodec!!.initMessageCodes(caps)
}
val isProtocolsInitialized: Boolean
get() = ethHandler.hasStatusPassed()
fun onDisconnect() {
isDisconnected = true
}
fun onSyncDone(done: Boolean) {
if (done) {
ethHandler.enableTransactions()
} else {
ethHandler.disableTransactions()
}
ethHandler.onSyncDone(done)
}
val peerId: String
get() = if (node == null) "<null>" else node!!.hexId
val peerIdShort: String
get() = if (node == null)
if (remoteId != null && remoteId!!.length >= 8) remoteId!!.substring(0, 8) else remoteId!!
else
node!!.hexIdShort
val nodeId: ByteArray?
get() = if (node == null) null else node!!.id
val nodeIdWrapper: ByteArrayWrapper?
get() = if (node == null) null else ByteArrayWrapper(node!!.id)
fun disconnect(reason: ReasonCode) {
msgQueue!!.disconnect(reason)
}
// ETH sub protocol
fun fetchBlockBodies(headers: List<BlockHeaderWrapper>) {
ethHandler.fetchBodies(headers)
}
fun isEthCompatible(peer: Channel?): Boolean {
return peer != null && peer.ethVersion.isCompatible(ethVersion)
}
fun hasEthStatusSucceeded(): Boolean {
return ethHandler.hasStatusSucceeded()
}
fun logSyncStats(): String {
return ethHandler.syncStats
}
val totalDifficulty: BigInteger
get() = ethHandler.totalDifficulty
val syncStats: SyncStatistics
get() = ethHandler.stats
val isHashRetrievingDone: Boolean
get() = ethHandler.isHashRetrievingDone
val isHashRetrieving: Boolean
get() = ethHandler.isHashRetrieving
val isMaster: Boolean
get() = ethHandler.isHashRetrieving || ethHandler.isHashRetrievingDone
val isIdle: Boolean
get() = ethHandler.isIdle
fun prohibitTransactionProcessing() {
ethHandler.disableTransactions()
}
fun sendTransaction(tx: List<Transaction>) {
ethHandler.sendTransaction(tx)
}
fun sendNewBlock(block: Block) {
ethHandler.sendNewBlock(block)
}
fun sendNewBlockHashes(block: Block) {
ethHandler.sendNewBlockHashes(block)
}
private val ethVersion: EthVersion
get() = ethHandler.version
fun dropConnection() {
ethHandler.dropConnection()
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val channel = o as Channel?
if (if (inetSocketAddress != null) inetSocketAddress != channel!!.inetSocketAddress else channel!!.inetSocketAddress != null) return false
if (if (node != null) node != channel.node else channel.node != null) return false
return this === channel
}
override fun hashCode(): Int {
var result = if (inetSocketAddress != null) inetSocketAddress!!.hashCode() else 0
result = 31 * result + if (node != null) node!!.hashCode() else 0
return result
}
override fun toString(): String {
return String.format("%s | %s", peerIdShort, inetSocketAddress)
}
companion object {
private val logger = LoggerFactory.getLogger("net")
}
}
|
mit
|
3599c3f8660cb58d60336945555e3703
| 32.959239 | 146 | 0.691606 | 4.417462 | false | false | false | false |
loxal/FreeEthereum
|
free-ethereum-core/src/test/java/org/ethereum/sync/ShortSyncTest.kt
|
1
|
31273
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.sync
import org.ethereum.config.NoAutoscan
import org.ethereum.config.SystemProperties
import org.ethereum.config.net.MainNetConfig
import org.ethereum.core.Block
import org.ethereum.core.BlockHeader
import org.ethereum.core.Blockchain
import org.ethereum.core.TransactionReceipt
import org.ethereum.facade.Ethereum
import org.ethereum.facade.EthereumFactory
import org.ethereum.listener.EthereumListenerAdapter
import org.ethereum.net.eth.handler.Eth62
import org.ethereum.net.eth.handler.EthHandler
import org.ethereum.net.eth.message.*
import org.ethereum.net.message.Message
import org.ethereum.net.p2p.DisconnectMessage
import org.ethereum.net.rlpx.Node
import org.ethereum.net.server.Channel
import org.ethereum.util.FileUtil.recursiveDelete
import org.ethereum.util.blockchain.StandaloneBlockchain
import org.junit.*
import org.junit.Assert.fail
import org.spongycastle.util.encoders.Hex.decode
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import java.io.File
import java.io.IOException
import java.math.BigInteger
import java.net.URISyntaxException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.SECONDS
/**
* @author Mikhail Kalinin
* *
* @since 14.12.2015
*/
@Ignore("Long network tests")
open class ShortSyncTest {
private var ethereumA: Ethereum? = null
private var ethereumB: Ethereum? = null
private var ethA: EthHandler? = null
private var testDbA: String? = null
private var testDbB: String? = null
@Before
@Throws(InterruptedException::class)
fun setupTest() {
testDbA = "test_db_" + BigInteger(32, Random())
testDbB = "test_db_" + BigInteger(32, Random())
SysPropConfigA.props.setDataBaseDir(testDbA)
SysPropConfigB.props.setDataBaseDir(testDbB)
}
@After
fun cleanupTest() {
recursiveDelete(testDbA)
recursiveDelete(testDbB)
SysPropConfigA.eth62 = null
}
// positive gap, A on main, B on main
// expected: B downloads missed blocks from A => B on main
@Test
@Throws(InterruptedException::class)
fun test1() {
setupPeers()
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10, B == genesis
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// positive gap, A on fork, B on main
// positive gap, A on fork, B on fork (same story)
// expected: B downloads missed blocks from A => B on A's fork
@Test
@Throws(InterruptedException::class)
fun test2() {
setupPeers()
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
// A == b8', B == genesis
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b8_)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlock(b8_)
semaphore.await(10, SECONDS)
// check if B == b8'
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// positive gap, A on main, B on fork
// expected: B finds common ancestor and downloads missed blocks from A => B on main
@Test
@Throws(InterruptedException::class)
fun test3() {
setupPeers()
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
for (b in forkB1B5B8_!!) {
blockchainB.tryToConnect(b)
}
// A == b10, B == b8'
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// negative gap, A on main, B on main
// expected: B skips A's block as already imported => B on main
@Test
@Throws(InterruptedException::class)
fun test4() {
setupPeers()
val b5 = mainB1B10!![4]
val b9 = mainB1B10!![8]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
if (b.isEqual(b5)) break
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b9)) break
}
// A == b5, B == b9
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b5)
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// negative gap, A on fork, B on main
// negative gap, A on fork, B on fork (same story)
// expected: B downloads A's fork and imports it as NOT_BEST => B on its chain
@Test
@Throws(InterruptedException::class)
fun test5() {
setupPeers()
val b9 = mainB1B10!![8]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b9)) break
}
// A == b8', B == b9
val semaphore = CountDownLatch(1)
val semaphoreB8_ = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
if (block.isEqual(b8_)) {
semaphoreB8_.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b8_)
semaphoreB8_.await(10, SECONDS)
if (semaphoreB8_.count > 0) {
fail("PeerB didn't import b8'")
}
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// negative gap, A on main, B on fork
// expected: B finds common ancestor and downloads A's blocks => B on main
@Test
@Throws(InterruptedException::class)
fun test6() {
setupPeers()
val b7 = mainB1B10!![6]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
if (b.isEqual(b7)) break
}
for (b in forkB1B5B8_!!) {
blockchainB.tryToConnect(b)
}
// A == b7, B == b8'
val semaphore = CountDownLatch(1)
val semaphoreB7 = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b7)) {
semaphoreB7.countDown()
}
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b7)
semaphoreB7.await(10, SECONDS)
// check if B == b7
if (semaphoreB7.count > 0) {
fail("PeerB didn't recover a gap")
}
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// positive gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads main blocks from A => B on main
@Test
@Throws(InterruptedException::class)
fun test7() {
setupPeers()
val b4 = mainB1B10!![3]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b4)) break
}
// A == b8', B == b4
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is NewBlockMessage) {
// it's time to do a re-branch
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
}
}
})
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlock(b8_)
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// negative gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads A's fork and imports it as NOT_BEST => B on main
@Test
@Throws(InterruptedException::class)
fun test8() {
setupPeers()
val b7_ = forkB1B5B8_!![6]
val b8 = mainB1B10!![7]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
if (b.isEqual(b7_)) break
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b8)) break
}
// A == b7', B == b8
val semaphore = CountDownLatch(1)
val semaphoreB7_ = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b7_)) {
// it's time to do a re-branch
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
semaphoreB7_.countDown()
}
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b7_)
semaphoreB7_.await(10, SECONDS)
if (semaphoreB7_.count > 0) {
fail("PeerB didn't import b7'")
}
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// positive gap, A on fork, B on main
// A doesn't send common ancestor
// expected: B drops A and all its blocks => B on main
@Test
@Throws(InterruptedException::class)
fun test9() {
// handler which don't send an ancestor
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
// process init header request correctly
if (msg.maxHeaders == 1) {
super.processGetBlockHeaders(msg)
return
}
val headers = (7..mainB1B10!!.size - 1).map { mainB1B10!![it].header }
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
val b6 = mainB1B10!![5]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b6)) break
}
// A == b8', B == b6
ethA!!.sendNewBlock(b8_)
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
// back to usual handler
SysPropConfigA.eth62 = null
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
val semaphoreConnect = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onPeerAddedToSyncPool(peer: Channel) {
semaphoreConnect.countDown()
}
})
ethereumB!!.connect(nodeA!!)
// await connection
semaphoreConnect.await(10, SECONDS)
if (semaphoreConnect.count > 0) {
fail("PeerB is not able to connect to PeerA")
}
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// negative gap, A on fork, B on main
// A doesn't send the gap block in ancestor response
// expected: B drops A and all its blocks => B on main
@Test
@Throws(InterruptedException::class)
fun test10() {
// handler which don't send a gap block
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (msg.maxHeaders == 1) {
super.processGetBlockHeaders(msg)
return
}
val headers = (0..forkB1B5B8_!!.size - 1 - 1).map { forkB1B5B8_!![it].header }
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
val b9 = mainB1B10!![8]
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b9)) break
}
// A == b8', B == b9
ethA!!.sendNewBlockHashes(b8_)
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
// back to usual handler
SysPropConfigA.eth62 = null
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
val semaphoreConnect = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onPeerAddedToSyncPool(peer: Channel) {
semaphoreConnect.countDown()
}
})
ethereumB!!.connect(nodeA!!)
// await connection
semaphoreConnect.await(10, SECONDS)
if (semaphoreConnect.count > 0) {
fail("PeerB is not able to connect to PeerA")
}
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10
ethA!!.sendNewBlock(b10)
semaphore.await(10, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// A sends block with low TD to B
// expected: B skips this block
@Test
@Throws(InterruptedException::class)
fun test11() {
val b5 = mainB1B10!![4]
val b6_ = forkB1B5B8_!![5]
setupPeers()
// A == B == genesis
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b5)) break
}
// A == b8', B == b5
val semaphore1 = CountDownLatch(1)
val semaphore2 = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b6_)) {
if (semaphore1.count > 0) {
semaphore1.countDown()
} else {
semaphore2.countDown()
}
}
}
})
ethA!!.sendNewBlock(b6_)
semaphore1.await(10, SECONDS)
if (semaphore1.count > 0) {
fail("PeerB doesn't accept block with higher TD")
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
}
// B == b10
ethA!!.sendNewBlock(b6_)
semaphore2.await(5, SECONDS)
// check if B skips b6'
if (semaphore2.count.equals(0)) {
fail("PeerB doesn't skip block with lower TD")
}
}
// bodies validation: A doesn't send bodies corresponding to headers which were sent previously
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test12() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockBodies(msg: GetBlockBodiesMessage) {
val bodies = Arrays.asList<ByteArray>(
mainB1B10!![0].encodedBody
)
val response = BlockBodiesMessage(bodies)
sendMessage(response)
}
}
setupPeers()
val blockchainA = ethereumA!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
ethA!!.sendNewBlock(b10)
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// bodies validation: headers order is incorrect in the response, reverse = true
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test13() {
val b9 = mainB1B10!![8]
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (msg.maxHeaders == 1) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
forkB1B5B8_!![7].header,
forkB1B5B8_!![6].header,
forkB1B5B8_!![4].header,
forkB1B5B8_!![5].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b9)) break
}
// A == b8', B == b10
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b8_)
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// bodies validation: ancestor's parent hash and header's hash does not match, reverse = true
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test14() {
val b9 = mainB1B10!![8]
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (msg.maxHeaders == 1) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
forkB1B5B8_!![7].header,
forkB1B5B8_!![6].header,
BlockHeader(ByteArray(32), ByteArray(32), ByteArray(32), ByteArray(32), ByteArray(32),
6, byteArrayOf(0), 0, 0, ByteArray(0), ByteArray(0), ByteArray(0)),
forkB1B5B8_!![4].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
val blockchainA = ethereumA!!.blockchain as Blockchain
val blockchainB = ethereumB!!.blockchain as Blockchain
for (b in forkB1B5B8_!!) {
blockchainA.tryToConnect(b)
}
for (b in mainB1B10!!) {
blockchainB.tryToConnect(b)
if (b.isEqual(b9)) break
}
// A == b8', B == b10
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
ethA!!.sendNewBlockHashes(b8_)
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
@Throws(InterruptedException::class)
private fun setupPeers() {
ethereumA = EthereumFactory.createEthereum(SysPropConfigA.props, SysPropConfigA::class.java)
ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB::class.java)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onEthStatusUpdated(channel: Channel, statusMessage: StatusMessage) {
ethA = channel.ethHandler as EthHandler
}
})
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onPeerAddedToSyncPool(peer: Channel) {
semaphore.countDown()
}
})
ethereumB!!.connect(nodeA!!)
semaphore.await(10, SECONDS)
if (semaphore.count > 0) {
fail("Failed to set up peers")
}
}
@Configuration
@NoAutoscan
open class SysPropConfigA {
@Bean
open fun systemProperties(): SystemProperties {
return props
}
@Bean
@Scope("prototype")
@Throws(IllegalAccessException::class, InstantiationException::class)
open fun eth62(): Eth62 {
if (eth62 != null) return eth62!!
return Eth62()
}
companion object {
internal val props = SystemProperties()
internal var eth62: Eth62? = null
}
}
@Configuration
@NoAutoscan
open class SysPropConfigB {
@Bean
open fun systemProperties(): SystemProperties {
return props
}
companion object {
internal val props = SystemProperties()
}
}
companion object {
private val minDifficultyBackup: BigInteger? = null
private var nodeA: Node? = null
private var mainB1B10: List<Block>? = null
private var forkB1B5B8_: List<Block>? = null
private var b10: Block? = null
private var b8_: Block? = null
@BeforeClass
@Throws(IOException::class, URISyntaxException::class)
fun setup() {
SystemProperties.getDefault()!!.blockchainConfig = StandaloneBlockchain.getEasyMiningConfig()
nodeA = Node("enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334")
SysPropConfigA.props.overrideParams(
"peer.listen.port", "30334",
"peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c",
// nodeId: 3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6
"genesis", "genesis-light.json"
)
SysPropConfigB.props.overrideParams(
"peer.listen.port", "30335",
"peer.privateKey", "6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec",
"genesis", "genesis-light.json",
"sync.enabled", "true"
)
mainB1B10 = loadBlocks("sync/main-b1-b10.dmp")
forkB1B5B8_ = loadBlocks("sync/fork-b1-b5-b8_.dmp")
b10 = mainB1B10!![mainB1B10!!.size - 1]
b8_ = forkB1B5B8_!![forkB1B5B8_!!.size - 1]
}
@Throws(URISyntaxException::class, IOException::class)
private fun loadBlocks(path: String): List<Block> {
val url = ClassLoader.getSystemResource(path)
val file = File(url.toURI())
val strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)
val blocks = ArrayList<Block>(strData.size)
strData.mapTo(blocks) { Block(decode(it)) }
return blocks
}
@AfterClass
fun cleanup() {
SystemProperties.getDefault()!!.blockchainConfig = MainNetConfig.INSTANCE
}
}
}
|
mit
|
0d3b16716f7a8bdbe47028f987d6d2f6
| 27.929695 | 180 | 0.560579 | 4.283973 | false | false | false | false |
jwren/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/CodeVisionListData.kt
|
4
|
1985
|
package com.intellij.codeInsight.codeVision.ui.model
import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.map
import com.jetbrains.rd.util.throttleLast
import java.time.Duration
class CodeVisionListData(
val lifetime: Lifetime,
val projectModel: ProjectCodeVisionModel,
val rangeCodeVisionModel: RangeCodeVisionModel,
val inlay: Inlay<*>,
val anchoredLens: List<CodeVisionEntry>,
val anchor: CodeVisionAnchorKind
) {
companion object {
@JvmField
val KEY = Key.create<CodeVisionListData>("CodeVisionListData")
}
var isPainted: Boolean = false
get() = field
set(value) {
if (field != value) {
field = value
if ((inlay.editor as? EditorImpl)?.isPurePaintingMode != true)
inlay.update()
}
}
val visibleLens = ArrayList<CodeVisionEntry>()
private var throttle = false
init {
projectModel.hoveredInlay.map {
it == inlay
}.throttleLast(Duration.ofMillis(300), SwingScheduler).advise(lifetime) {
throttle = it
inlay.repaint()
}
updateVisible()
}
private fun updateVisible() {
val count = projectModel.maxVisibleLensCount[anchor]
visibleLens.clear()
if (count == null) {
visibleLens.addAll(anchoredLens)
return
}
val visibleCount = minOf(count, anchoredLens.size)
visibleLens.addAll(anchoredLens.subList(0, visibleCount))
}
fun state() = rangeCodeVisionModel.state()
fun isMoreLensActive() = throttle && Registry.`is`("editor.codeVision.more.inlay")
fun isHoveredEntry(entry: CodeVisionEntry) = projectModel.hoveredEntry.value == entry && projectModel.hoveredInlay.value == inlay
}
|
apache-2.0
|
efabc770d724e1138f38efaafe041a12
| 27.357143 | 131 | 0.729975 | 4.287257 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/projectTemplates/ConfiguratorSettingsBuilder.kt
|
4
|
1326
|
// 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.tools.projectWizard.projectTemplates
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ModuleConfiguratorSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingType
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleBasedConfiguratorContext
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfiguratorContext
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
class ConfiguratorSettingsBuilder<C : ModuleConfigurator>(
val module: Module,
val configurator: C
) : ModuleConfiguratorContext by ModuleBasedConfiguratorContext(configurator, module) {
init {
assert(module.configurator === configurator)
}
private val settings = mutableListOf<SettingWithValue<*, *>>()
val setsSettings: List<SettingWithValue<*, *>>
get() = settings
infix fun <V : Any, T : SettingType<V>> ModuleConfiguratorSetting<V, T>.withValue(value: V) {
settings += SettingWithValue(reference, value)
}
}
|
apache-2.0
|
a2759861263d079347cf9eedc5be22d5
| 48.148148 | 158 | 0.79638 | 4.787004 | false | true | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/UselessCallOnNotNullInspection.kt
|
1
|
4185
|
// 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.collections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.quickfix.ReplaceWithDotCallFix
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
class UselessCallOnNotNullInspection : AbstractUselessCallInspection() {
override val uselessFqNames = mapOf(
"kotlin.collections.orEmpty" to deleteConversion,
"kotlin.sequences.orEmpty" to deleteConversion,
"kotlin.text.orEmpty" to deleteConversion,
"kotlin.text.isNullOrEmpty" to Conversion("isEmpty"),
"kotlin.text.isNullOrBlank" to Conversion("isBlank"),
"kotlin.collections.isNullOrEmpty" to Conversion("isEmpty")
)
override val uselessNames = uselessFqNames.keys.toShortNames()
override fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
context: BindingContext,
conversion: Conversion
) {
val newName = conversion.replacementName
val safeExpression = expression as? KtSafeQualifiedExpression
val notNullType = expression.receiverExpression.isNotNullType(context)
val defaultRange =
TextRange(expression.operationTokenNode.startOffset, calleeExpression.endOffset).shiftRight(-expression.startOffset)
if (newName != null && (notNullType || safeExpression != null)) {
val fixes = listOf(RenameUselessCallFix(newName)) + listOfNotNull(safeExpression?.let {
IntentionWrapper(ReplaceWithDotCallFix(safeExpression))
})
val descriptor = holder.manager.createProblemDescriptor(
expression,
defaultRange,
KotlinBundle.message("call.on.not.null.type.may.be.reduced"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
*fixes.toTypedArray()
)
holder.registerProblem(descriptor)
} else if (notNullType) {
val descriptor = holder.manager.createProblemDescriptor(
expression,
defaultRange,
KotlinBundle.message("useless.call.on.not.null.type"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
RemoveUselessCallFix()
)
holder.registerProblem(descriptor)
} else if (safeExpression != null) {
holder.registerProblem(
safeExpression.operationTokenNode.psi,
KotlinBundle.message("this.call.is.useless.with"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(ReplaceWithDotCallFix(safeExpression))
)
}
}
private fun KtExpression.isNotNullType(context: BindingContext): Boolean {
val type = getType(context) ?: return false
val dataFlowValueFactory = getResolutionFacade().getDataFlowValueFactory()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, findModuleDescriptor())
val stableNullability = context.getDataFlowInfoBefore(this).getStableNullability(dataFlowValue)
return !stableNullability.canBeNull()
}
}
|
apache-2.0
|
3481241a6605c9644af26e55856e8ff7
| 47.103448 | 158 | 0.71589 | 5.33121 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/class/classOptionalVars.kt
|
4
|
241
|
<warning descr="SSR">class Empty</warning>
<warning descr="SSR">class BoxOfVal {
val v1 = 0
}</warning>
<warning descr="SSR">class BoxOfVar {
var v1 = 0
}</warning>
<warning descr="SSR">class BoxOfFun {
fun f1() {}
}</warning>
|
apache-2.0
|
0c11c6bbef4fa01f4cda9350b08bfae1
| 17.615385 | 42 | 0.639004 | 3.0125 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/inspections/dynamic/test.kt
|
13
|
695
|
class A {
fun foo(i: Int) {}
}
fun bar(d: dynamic, s: String, a: Any, u: Unit) {}
fun main(args: Array<String>) {
val d: dynamic = Any()
var s: String = ""
var a: Any = ""
var u: Unit = Unit
s = d
a = d
u = d
s = d as String
a = d as Any
u = d as Unit
if (d is String) {
s = d
d.subSequence(1, 2)
}
if (d is A) {
d.foo(1)
}
if (a is String) {
s = a
a.length
}
if (d is Any) {
a = d
}
if (d is Unit) {
u = d
}
bar(d, d.boo, d, d)
bar(d, d as String, d as Any, d as Unit)
bar(d.aaa, d.bbb as String, d.ccc(), d.ddd {})
return d
}
|
apache-2.0
|
e8478a926bc50794f6010a06e861f31f
| 13.479167 | 50 | 0.418705 | 2.78 | false | false | false | false |
Tolriq/yatse-customcommandsplugin-api
|
api/src/main/java/tv/yatse/plugin/customcommands/api/CustomCommandsAppCompatActivity.kt
|
1
|
2352
|
/*
* Copyright 2015 Tolriq / Genimee.
* 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 tv.yatse.plugin.customcommands.api
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* The CustomCommandsActivity Activity that plugin must extend if they support adding / editing Custom Commands
*
*
* Activity should call : <br></br>
* - [CustomCommandsAppCompatActivity.cancelAndFinish] to cancel any change and return to Yatse.<br></br>
* - [CustomCommandsAppCompatActivity.saveAndFinish] to return the updated pluginCustomCommand for adding / saving in Yatse.
*/
abstract class CustomCommandsAppCompatActivity : AppCompatActivity() {
@JvmField
protected var pluginCustomCommand: PluginCustomCommand? = null
/**
* @return true if editing an existing custom command
*/
protected var isEditing = false
private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isEditing = intent?.hasExtra(CustomCommandsActivity.EXTRA_CUSTOM_COMMAND) ?: false
pluginCustomCommand = intent?.getParcelableExtra(CustomCommandsActivity.EXTRA_CUSTOM_COMMAND) ?: PluginCustomCommand()
setResult(RESULT_CANCELED, Intent())
}
/**
* Cancel adding / editing and finish the activity.
*/
protected fun cancelAndFinish() {
setResult(RESULT_CANCELED, Intent())
finish()
}
/**
* Finish the activity and return the added / updated custom command to Yatse.
*/
protected fun saveAndFinish() {
setResult(RESULT_OK, Intent().putExtra(EXTRA_CUSTOM_COMMAND, pluginCustomCommand))
finish()
}
companion object {
const val EXTRA_CUSTOM_COMMAND = "tv.yatse.plugin.customcommands.EXTRA_CUSTOM_COMMAND"
}
}
|
apache-2.0
|
36522a6c06124dacf1117c8b9732e969
| 34.651515 | 126 | 0.718963 | 4.514395 | false | false | false | false |
wn1/LNotes
|
app/src/main/java/ru/qdev/lnotes/mvp/QDVNotesListState.kt
|
1
|
796
|
package ru.qdev.lnotes.mvp
import android.support.annotation.AnyThread
import ru.qdev.lnotes.db.entity.QDVDbFolder
import java.io.Serializable
/**
* Created by Vladimir Kudashov on 29.09.18.
*/
@AnyThread
class QDVFilterByFolderState : Serializable {
enum class FilterType {ALL_FOLDER, FOLDER_NOT_SELECTED, FOLDER_ID, FOLDER}
var folder: QDVDbFolder? = null
var folderId: Long? = null
var filterType: FilterType = FilterType.ALL_FOLDER
}
class QDVSearchState: Serializable {
var isSearchActive: Boolean = false
var searchText: String? = null
}
class QDVNotesListState : Serializable {
val searchState: QDVSearchState = QDVSearchState()
var filterByFolderState: QDVFilterByFolderState = QDVFilterByFolderState()
var folderIdForNotesAdding: Long? = null
}
|
mit
|
050400b63336c010ad601038740083aa
| 27.464286 | 78 | 0.76005 | 4.020202 | false | false | false | false |
getsentry/raven-java
|
sentry-android-timber/src/main/java/io/sentry/android/timber/SentryTimberTree.kt
|
1
|
2667
|
package io.sentry.android.timber
import android.util.Log
import io.sentry.Breadcrumb
import io.sentry.IHub
import io.sentry.SentryEvent
import io.sentry.SentryLevel
import io.sentry.protocol.Message
import timber.log.Timber
/**
* Sentry Timber tree which is responsible to capture events via Timber
*/
class SentryTimberTree(
private val hub: IHub,
private val minEventLevel: SentryLevel,
private val minBreadcrumbLevel: SentryLevel
) : Timber.Tree() {
/**
* do not log if it's lower than min. required level.
*/
private fun isLoggable(level: SentryLevel, minLevel: SentryLevel): Boolean = level.ordinal >= minLevel.ordinal
/**
* Captures a Sentry Event if the min. level is equal or higher than the min. required level.
*/
override fun log(priority: Int, tag: String?, message: String, throwable: Throwable?) {
val level = getSentryLevel(priority)
captureEvent(level, tag, message, throwable)
addBreadcrumb(level, message)
}
/**
* Captures an event with the given attributes
*/
private fun captureEvent(sentryLevel: SentryLevel, tag: String?, msg: String, throwable: Throwable?) {
if (isLoggable(sentryLevel, minEventLevel)) {
val sentryEvent = SentryEvent().apply {
level = sentryLevel
throwable?.let {
setThrowable(it)
}
message = Message().apply {
formatted = msg
}
tag?.let {
setTag("TimberTag", it)
}
logger = "Timber"
}
hub.captureEvent(sentryEvent)
}
}
/**
* Adds a breadcrumb
*/
private fun addBreadcrumb(sentryLevel: SentryLevel, msg: String) {
// checks the breadcrumb level
if (isLoggable(sentryLevel, minBreadcrumbLevel)) {
val breadCrumb = Breadcrumb().apply {
level = sentryLevel
category = "Timber"
message = msg
}
hub.addBreadcrumb(breadCrumb)
}
}
/**
* Converts from Timber priority to SentryLevel.
* Fallback to SentryLevel.DEBUG.
*/
private fun getSentryLevel(priority: Int): SentryLevel {
return when (priority) {
Log.ASSERT -> SentryLevel.FATAL
Log.ERROR -> SentryLevel.ERROR
Log.WARN -> SentryLevel.WARNING
Log.INFO -> SentryLevel.INFO
Log.DEBUG -> SentryLevel.DEBUG
Log.VERBOSE -> SentryLevel.DEBUG
else -> SentryLevel.DEBUG
}
}
}
|
bsd-3-clause
|
32eea703fc465050e2bec8b4a88816f7
| 27.37234 | 114 | 0.586052 | 4.911602 | false | false | false | false |
wuan/bo-android
|
app/src/main/java/org/blitzortung/android/map/overlay/OwnLocationOverlay.kt
|
1
|
5195
|
/*
Copyright 2015 Andreas Würl
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.blitzortung.android.map.overlay
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Canvas
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.preference.PreferenceManager
import org.blitzortung.android.app.R
import org.blitzortung.android.app.helper.ViewHelper
import org.blitzortung.android.app.view.OnSharedPreferenceChangeListener
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.get
import org.blitzortung.android.app.view.getAndConvert
import org.blitzortung.android.location.LocationEvent
import org.blitzortung.android.map.components.LayerOverlayComponent
import org.blitzortung.android.util.TabletAwareView
import org.osmdroid.api.IMapView
import org.osmdroid.events.MapListener
import org.osmdroid.events.ScrollEvent
import org.osmdroid.events.ZoomEvent
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.ItemizedOverlay
class OwnLocationOverlay(
context: Context,
private val mapView: MapView
) : ItemizedOverlay<OwnLocationOverlayItem>(DEFAULT_DRAWABLE),
OnSharedPreferenceChangeListener,
LayerOverlay, MapListener {
private val layerOverlayComponent: LayerOverlayComponent = LayerOverlayComponent(context.resources.getString(R.string.own_location_layer))
private var item: OwnLocationOverlayItem? = null
private var symbolSize: Float = 1.0f
private val sizeFactor: Float
private var zoomLevel: Double
init {
zoomLevel = mapView.zoomLevelDouble
}
val locationEventConsumer: (LocationEvent) -> Unit = { event ->
val location = event.location
if (isEnabled) {
item = location?.run { OwnLocationOverlayItem(location) }
populate()
refresh()
mapView.postInvalidate()
}
}
init {
populate()
sizeFactor = ViewHelper.pxFromDp(context, 1.0f) * TabletAwareView.sizeFactor(context)
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
preferences.registerOnSharedPreferenceChangeListener(this)
onSharedPreferenceChanged(preferences, PreferenceKey.SHOW_LOCATION)
onSharedPreferenceChanged(preferences, PreferenceKey.OWN_LOCATION_SIZE)
refresh()
}
override fun draw(canvas: Canvas?, mapView: MapView?, shadow: Boolean) {
if (!shadow) {
super.draw(canvas, mapView, false)
}
}
private fun refresh() {
item?.run { setMarker(ShapeDrawable(OwnLocationShape((sizeFactor * zoomLevel * symbolSize).toFloat()))) }
}
override fun createItem(i: Int): OwnLocationOverlayItem {
return item!!
}
override fun size(): Int {
return if (item == null) 0 else 1
}
private fun enableOwnLocation() {
isEnabled = true
refresh()
}
private fun disableOwnLocation() {
item = null
isEnabled = false
refresh()
}
override fun onSnapToItem(x: Int, y: Int, snapPoint: Point?, mapView: IMapView?): Boolean {
return false
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) {
if (key == PreferenceKey.SHOW_LOCATION) {
val showLocation = sharedPreferences.get(key, false)
if (showLocation) {
enableOwnLocation()
} else {
disableOwnLocation()
}
} else if (key == PreferenceKey.OWN_LOCATION_SIZE) {
symbolSize = sharedPreferences.getAndConvert(PreferenceKey.OWN_LOCATION_SIZE, 100) {
it.toFloat() / 100
}
}
}
override fun onScroll(event: ScrollEvent?): Boolean {
return false
}
override fun onZoom(event: ZoomEvent?): Boolean {
if (event != null) {
val zoomLevel = event.zoomLevel
if (zoomLevel != this.zoomLevel) {
this.zoomLevel = zoomLevel
refresh()
}
}
return false
}
override val name: String
get() = layerOverlayComponent.name
override var visible: Boolean
get() = layerOverlayComponent.visible
set(value) {
layerOverlayComponent.visible = value
}
companion object {
private val DEFAULT_DRAWABLE: Drawable
init {
val shape = OwnLocationShape(1f)
DEFAULT_DRAWABLE = ShapeDrawable(shape)
}
}
}
|
apache-2.0
|
7c1706505878957ba8f11d26553e5695
| 29.197674 | 142 | 0.679438 | 4.795937 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS
|
2017.AndroidApplicationDevelopment/Rehtaew/app/src/main/java/com/myls/rehtaew/data/WeatherData.kt
|
1
|
9188
|
package com.myls.rehtaew.data
import java.util.Calendar
import com.myls.rehtaew.R
/**
* Created by myls on 10/12/17.
*/
// [Kotlin - Creating DTOs (POJOs/POCOs)]
// (http://kotlinlang.org/docs/reference/idioms.html#creating-dtos-pojospocos)
// [Kotlin - Data Classes]
// (http://kotlinlang.org/docs/reference/data-classes.html)
data class WeatherData
(
private var city_code : String = "101010100",
private var city_name : String = "",
private var time_sunrise : String = "",
private var time_sunset : String = "",
private var weather_day : String = "",
private var weather_night: String = "",
private var temp_now : Int? = null,
private var temp_low : Int? = null,
private var temp_high : Int? = null,
private var wind_dir : String = "",
private var wind_level : String = "",
private var humid_desc : String = "湿度",
private var humid_value : Int? = null,
private var pm25_desc : String = "PM 2.5",
private var pm25_value : Int? = null,
private var air_quality : String = "",
private var forecast : ArrayList<Forecast>? = null,
private var last_updated : Calendar = Calendar.getInstance()
) {
var cityCode: String
get() = city_code
set(value) { city_code = value }
val cityName: String
get() = city_name
val lastUpdated: String
get() {
val old = last_updated.timeInMillis
val new = Calendar.getInstance().timeInMillis
val min = (new - old) / (1000 * 60)
return when
{
(min < 5) -> "刚刚"
(min < 15) -> "十分钟前"
(min < 25) -> "二十分钟前"
(min < 45) -> "半小时前"
(min < 90) -> "一个小时前"
(min < 150) -> "两个小时前"
(min < 420) -> "几个小时前"
(min < 18*60) -> "半天前"
(min < 36*60) -> "一天前"
(min < 60*60) -> "两天前"
else -> "很久之前"
} + "更新"
}
val isNight: Boolean
get() {
val now = Calendar.getInstance().run {
get(Calendar.HOUR_OF_DAY) * 60 + get(Calendar.MINUTE)
}
// [Higher-Order Functions and Lambdas]
// (https://kotlinlang.org/docs/reference/lambdas.html)
// [Destructuring Declarations]
// (https://kotlinlang.org/docs/reference/multi-declarations.html)
// [Regex]
// (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/)
"\\D*(\\d{1,2})\\D+(\\d{1,2})\\D*".toRegex().run {
val toMinute = {
time: String, default: Int -> Int
matchEntire(time)?.run {
val (h, m) = destructured
h.toInt() * 60 + m.toInt()
}?:default
}
var beg = toMinute(time_sunrise, 6 * 60)
var end = toMinute(time_sunset, 18 * 60)
if (end <= beg) {
beg = 6 * 60
end = 18 * 60
}
return (end < now) or (now < beg)
}
}
val weatherDescription: String
get() = if (isNight) {
weather_night
} else {
weather_day
}
val weatherIconId: Int
get() = when (weatherDescription) {
"多云" -> WEATHER_PARTLY_CLOUDY
"阴" -> WEATHER_CLOUDY
"雾" -> WEATHER_FOG
"雷阵雨" -> WEATHER_LIGHTNING_RAINY
"雷阵雨冰雹" -> WEATHER_LIGHTNING_RAINY_HAIL
"小雨" -> WEATHER_RAINY_LV1
"中雨" -> WEATHER_RAINY_LV2
"大雨" -> WEATHER_RAINY_LV3
"暴雨" -> WEATHER_RAINY_LV4
"大暴雨" -> WEATHER_RAINY_LV5
"特大暴雨" -> WEATHER_RAINY_LV6
"阵雨" -> WEATHER_RAINY_SHOWER
"小雪" -> WEATHER_SNOWY_LV1
"中雪" -> WEATHER_SNOWY_LV2
"大雪" -> WEATHER_SNOWY_LV3
"暴雪" -> WEATHER_SNOWY_LV4
"阵雪" -> WEATHER_SNOWY_SHOWER
"雨夹雪" -> WEATHER_SNOWY_RAINY
"晴" -> if (isNight) WEATHER_SUNNY_NIGHT else WEATHER_SUNNY_DAY
"沙尘暴" -> WEATHER_SANDSTORM
else -> WEATHER_NONE
}
val temperatureNow: String
get() = if (temp_now != null) "$temp_now°" else ""
val temperatureToday: String
get() = if (temp_low != null && temp_high != null) "$temp_low° / $temp_high℃" else ""
val windDirection: String
get() = wind_dir
val windLevel: String
get() = wind_level
val humidDescription: String
get() = humid_desc
val humidValue: String
get() = if (humid_value != null) "$humid_value%" else ""
val pm25Description: String
get() = pm25_desc
val pm25Value: String
get() = if (pm25_value != null) "$pm25_value" else ""
val airQuality: String
get() = air_quality
val weatherFuture: ArrayList<Forecast>
get() = forecast ?: ArrayList<Forecast>()
data class Forecast
(
private val datetime: Calendar,
private val weather: String,
private val temp_low: Int,
private val temp_high: Int
) {
val date: String
get() = "${datetime.get(Calendar.MONTH)+1}/${datetime.get(Calendar.DAY_OF_MONTH)}"
val weekday: String
get() = with(datetime) {
Calendar.getInstance().let {
if (this.get(Calendar.YEAR) == it.get(Calendar.YEAR) &&
this.get(Calendar.DAY_OF_YEAR) == it.get(Calendar.DAY_OF_YEAR) ) {
"今天"
} else when(datetime.get(Calendar.DAY_OF_WEEK)) {
Calendar.MONDAY -> "星期一"
Calendar.TUESDAY -> "星期二"
Calendar.WEDNESDAY -> "星期三"
Calendar.THURSDAY -> "星期四"
Calendar.FRIDAY -> "星期五"
Calendar.SATURDAY -> "星期六"
Calendar.SUNDAY -> "星期日"
else -> "???"
}
}
}
val weatherIconId: Int
get() = when (weather) {
"多云" -> WEATHER_PARTLY_CLOUDY
"阴" -> WEATHER_CLOUDY
"雾" -> WEATHER_FOG
"雷阵雨" -> WEATHER_LIGHTNING_RAINY
"雷阵雨冰雹" -> WEATHER_LIGHTNING_RAINY_HAIL
"小雨" -> WEATHER_RAINY_LV1
"中雨" -> WEATHER_RAINY_LV2
"大雨" -> WEATHER_RAINY_LV3
"暴雨" -> WEATHER_RAINY_LV4
"大暴雨" -> WEATHER_RAINY_LV5
"特大暴雨" -> WEATHER_RAINY_LV6
"阵雨" -> WEATHER_RAINY_SHOWER
"小雪" -> WEATHER_SNOWY_LV1
"中雪" -> WEATHER_SNOWY_LV2
"大雪" -> WEATHER_SNOWY_LV3
"暴雪" -> WEATHER_SNOWY_LV4
"阵雪" -> WEATHER_SNOWY_SHOWER
"雨夹雪" -> WEATHER_SNOWY_RAINY
"晴" -> WEATHER_SUNNY_DAY
"沙尘暴" -> WEATHER_SANDSTORM
else -> WEATHER_NONE
}
val temperatureHigh: String
get() = "$temp_high°"
val temperatureLow: String
get() = "$temp_low°"
}
companion object {
val WEATHER_NONE = R.drawable.ic_warning
val WEATHER_CLOUDY = R.drawable.ic_weather_cloudy
val WEATHER_PARTLY_CLOUDY = R.drawable.ic_weather_partlycloudy
val WEATHER_FOG = R.drawable.ic_weather_fog
val WEATHER_LIGHTNING_RAINY = R.drawable.ic_weather_lightning_rainy
val WEATHER_LIGHTNING_RAINY_HAIL = R.drawable.ic_weather_lightning_rainy
val WEATHER_RAINY_LV1 = R.drawable.ic_weather_rainy
val WEATHER_RAINY_LV2 = R.drawable.ic_weather_rainy
val WEATHER_RAINY_LV3 = R.drawable.ic_weather_rainy
val WEATHER_RAINY_LV4 = R.drawable.ic_weather_pouring
val WEATHER_RAINY_LV5 = R.drawable.ic_weather_pouring
val WEATHER_RAINY_LV6 = R.drawable.ic_weather_pouring
val WEATHER_RAINY_SHOWER = R.drawable.ic_weather_rainy
val WEATHER_SNOWY_LV1 = R.drawable.ic_weather_snowy
val WEATHER_SNOWY_LV2 = R.drawable.ic_weather_snowy
val WEATHER_SNOWY_LV3 = R.drawable.ic_weather_snowy
val WEATHER_SNOWY_LV4 = R.drawable.ic_weather_snowy
val WEATHER_SNOWY_SHOWER = R.drawable.ic_weather_snowy
val WEATHER_SNOWY_RAINY = R.drawable.ic_weather_snowy_rainy
val WEATHER_SUNNY_DAY = R.drawable.ic_weather_sunny
val WEATHER_SUNNY_NIGHT = R.drawable.ic_weather_night
val WEATHER_SANDSTORM = R.drawable.ic_weather_windy
}
}
// R.drawable.ic_weather_night
// R.drawable.ic_weather_hail
// R.drawable.ic_weather_lightning
// R.drawable.ic_weather_sunset
// R.drawable.ic_weather_sunset_down
// R.drawable.ic_weather_sunset_up
// R.drawable.ic_weather_windy_variant
|
mit
|
e848e603bb1f6372cb0b82c1f0428db9
| 33.850394 | 90 | 0.525418 | 3.349224 | false | false | false | false |
marschall/pgjdbc
|
buildSrc/src/main/kotlin/org/postgresql/buildtools/JavaCommentPreprocessorTask.kt
|
6
|
2895
|
/*
* Copyright (c) 2020, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.buildtools
import com.igormaznitsa.jcp.JcpPreprocessor
import com.igormaznitsa.jcp.context.PreprocessorContext
import com.igormaznitsa.jcp.expression.Value
import com.igormaznitsa.jcp.logger.PreprocessorLogger
import org.gradle.api.DefaultTask
import org.gradle.api.file.FileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
import org.gradle.kotlin.dsl.setProperty
import java.io.File
import javax.inject.Inject
open class JavaCommentPreprocessorTask @Inject constructor(
objects: ObjectFactory
) : DefaultTask() {
@Internal
val baseDir = objects.fileProperty()
@Internal
val sourceFolders = objects.listProperty<String>()
@Internal
val excludedPatterns = objects.setProperty<String>()
@get:InputFiles
protected val inputDirectories: FileCollection get() =
project.files().apply {
val base = baseDir.get().asFile
val excludedPatterns = excludedPatterns.get()
for (folder in sourceFolders.get()) {
from(project.fileTree(File(base, folder)) {
exclude(excludedPatterns)
})
}
}
@OutputDirectory
val outputDirectory = objects.directoryProperty()
.convention(project.layout.buildDirectory.dir("jcp/$name"))
@Input
val variables = objects.mapProperty<String, String>()
@Input
val keepLines = objects.property<Boolean>().convention(true)
@Input
val keepComments = objects.property<Boolean>().convention(true)
@Input
val clearTarget = objects.property<Boolean>().convention(true)
@TaskAction
fun run() {
val logger = project.logger
val context = PreprocessorContext(baseDir.get().asFile).apply {
preprocessorLogger = object : PreprocessorLogger {
override fun warning(message: String?) = logger.warn(message)
override fun info(message: String?) = logger.info(message)
override fun error(message: String?) = logger.error(message)
override fun debug(message: String?) = logger.debug(message)
}
target = outputDirectory.get().asFile
setSources(sourceFolders.get())
isClearTarget = clearTarget.get()
isKeepLines = keepLines.get()
isKeepComments = keepComments.get()
excludeFolders = excludedPatterns.get().toList()
for ((k, v) in variables.get()) {
setGlobalVariable(k, Value.recognizeRawString(v))
}
}
JcpPreprocessor(context).execute()
}
}
|
bsd-2-clause
|
c5ae82470b8e50ad8dc069f619c85382
| 33.058824 | 77 | 0.670121 | 4.509346 | false | false | false | false |
kamgurgul/cpu-info
|
app/src/main/java/com/kgurgul/cpuinfo/features/ramwidget/RamUsageWidgetProvider.kt
|
1
|
6044
|
/*
* Copyright 2017 KG Soft
*
* 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.kgurgul.cpuinfo.features.ramwidget
import android.app.ActivityManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.widget.RemoteViews
import com.kgurgul.cpuinfo.R
import com.kgurgul.cpuinfo.features.HostActivity
import com.kgurgul.cpuinfo.utils.runOnApiBelow
import com.kgurgul.cpuinfo.widgets.arc.ArcProgress
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.io.RandomAccessFile
import java.util.regex.Pattern
/**
* Displays current usage of the RAM memory. Won't work on Android O!
* All refreshing logic can be migrated into foreground service but IMO it is not worth it.
*
* @author kgurgul
*/
class RamUsageWidgetProvider : AppWidgetProvider() {
companion object {
var previousRamState = -1
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
Timber.d("Update called")
val thisWidget = ComponentName(context, RamUsageWidgetProvider::class.java)
val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget)
// To ensure that RefreshService is running
if (!allWidgetIds.isEmpty()) {
val actualRamState = getUsedPercentageRam(context)
if (actualRamState != previousRamState) {
Timber.d("Ram state changed from $previousRamState to $actualRamState")
previousRamState = actualRamState
val remoteViews = RemoteViews(context.packageName, R.layout.widget)
remoteViews.setOnClickPendingIntent(R.id.arc_ram_status, buildButtonPendingIntent(context))
remoteViews.setImageViewBitmap(R.id.arc_ram_status, getArcBitmap(context))
pushWidgetUpdates(context.applicationContext, remoteViews)
}
// Won't work on Android O!
runOnApiBelow(Build.VERSION_CODES.O) {
val intent = Intent(context, RefreshService::class.java)
context.startService(intent)
}
}
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
override fun onEnabled(context: Context) {
super.onEnabled(context)
Timber.d("Widget enabled")
previousRamState = -1
}
override fun onDisabled(context: Context) {
Timber.d("Widget disabled")
EventBus.getDefault().post(RefreshService.KillRefreshServiceEvent())
previousRamState = -1
super.onDisabled(context)
}
private fun buildButtonPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, HostActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
return PendingIntent.getActivity(context, 0, intent, 0)
}
private fun pushWidgetUpdates(context: Context, remoteViews: RemoteViews) {
val ramCleanerWidget = ComponentName(context, RamUsageWidgetProvider::class.java)
val manager = AppWidgetManager.getInstance(context)
manager.updateAppWidget(ramCleanerWidget, remoteViews)
}
private fun getArcBitmap(context: Context): Bitmap {
val arcRamProgress = ArcProgress(context)
arcRamProgress.progress = previousRamState
arcRamProgress.bottomText = "RAM"
arcRamProgress.textSize = context.resources.getDimension(R.dimen.arc_text_size)
arcRamProgress.suffixTextSize = context.resources.getDimension(R.dimen.arc_suffix_text_size)
arcRamProgress.bottomTextSize = context.resources.getDimension(R.dimen.arc_bottom_text_size)
arcRamProgress.strokeWidth = context.resources.getDimension(R.dimen.arc_stroke_width)
arcRamProgress.measure(500, 500)
arcRamProgress.layout(0, 0, 500, 500)
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
arcRamProgress.draw(Canvas(bitmap))
return bitmap
}
@Synchronized
private fun getUsedPercentageRam(context: Context): Int {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val totalRam: Long
totalRam = if (Build.VERSION.SDK_INT >= 16) {
memoryInfo.totalMem
} else {
getTotalRamForOldApi()
}
return ((totalRam.toDouble() - memoryInfo.availMem.toDouble()) / totalRam.toDouble()
* 100.0).toInt()
}
private fun getTotalRamForOldApi(): Long {
var reader: RandomAccessFile? = null
var totRam: Long = -1
try {
reader = RandomAccessFile("/proc/meminfo", "r")
val load = reader.readLine()
// Get the Number value from the string
val p = Pattern.compile("(\\d+)")
val m = p.matcher(load)
var value = ""
while (m.find()) {
value = m.group(1)!!
}
reader.close()
totRam = value.toLong()
} catch (ex: Exception) {
Timber.e(ex)
} finally {
reader?.close()
}
return totRam * 1024
}
}
|
apache-2.0
|
4f8ea5550fc1cae7dacb1f5958d523b9
| 36.08589 | 107 | 0.680179 | 4.523952 | false | false | false | false |
Tomlezen/FragmentBuilder
|
lib/src/main/java/com/tlz/fragmentbuilder/FbFragmentManager.kt
|
1
|
6940
|
package com.tlz.fragmentbuilder
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import com.tlz.fragmentbuilder.FbActionType.BACK
import java.lang.ref.WeakReference
import kotlin.reflect.KClass
/**
*
* Created by Tomlezen.
* Date: 2017/7/13.
* Time: 15:11.
* manage fragment
*/
class FbFragmentManager private constructor(
private val context: Context,
private val TAG: String,
fragmentManager: FragmentManager,
@IdRes private val frameLayoutId: Int
) {
private val fragmentManagerWrapper: WeakReference<FragmentManager> = WeakReference(fragmentManager)
var enter = R.anim.empty
var exit = R.anim.empty
fun switch(kclass: KClass<out Fragment>, init: (FbActionEditor.() -> Unit)? = null) {
commit(FbActionEditor(kclass, FbActionType.SWITCH).apply {
init?.let { this.apply(init) }
})
}
fun add(kclass: KClass<out Fragment>, init: (FbActionEditor.() -> Unit)? = null) {
commit(FbActionEditor(kclass, FbActionType.ADD).apply {
init?.let { this.apply(init) }
})
}
fun addForResult(kclass: KClass<out Fragment>, requestCode: Int,
init: (FbActionEditor.() -> Unit)? = null) {
commit(FbActionEditor(kclass, FbActionType.ADD, requestCode).apply {
init?.let { this.apply(init) }
})
}
fun back() = commit(FbActionEditor(null, FbActionType.BACK))
fun backForResult(requestCode: Int, resultCode: Int, data: Bundle?) {
commit(FbActionEditor(null, FbActionType.BACK, requestCode).apply {
this.resultCode = resultCode
data?.let {
this.data = it
}
})
}
private fun commit(editor: FbActionEditor): Int {
if (editor.action != BACK) {
editor.data.putString(FbConst.KEY_FRAGMENT_MANAGER_TAG, TAG)
}
return when (editor.action) {
FbActionType.SWITCH -> {
doSwitch(editor)
}
FbActionType.ADD -> {
doAdd(editor)
}
FbActionType.BACK -> {
doBack(editor)
}
}
}
@SuppressLint("RestrictedApi")
private fun doSwitch(editor: FbActionEditor): Int {
return fragmentManger()?.beginTransaction()?.let {
it.setCustomAnimations(enter, exit)
try {
fragmentManger()?.fragments
?.filter { !(it == null || !it.isVisible || it.tag == null || it.tag == editor.TAG) }
?.forEach { value ->
it.remove(value)
}
} catch (e: Exception) {
e.printStackTrace()
}
val fragment = Fragment.instantiate(context, editor.kclass?.java?.name, editor.data)
fragment.check()
it.replace(frameLayoutId, fragment, editor.TAG)
val id = it.commitAllowingStateLoss()
try {
fragment.userVisibleHint = true
fragmentManger()?.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} catch (e: Exception) {
e.printStackTrace()
}
id
} ?: 0
}
private fun doAdd(editor: FbActionEditor): Int {
if (editor.requestCode != 0) {
editor.data.putInt(FbConst.KEY_FB_REQUEST_CODE, editor.requestCode)
}
val topFragment = topFragment()
val fragment = Fragment.instantiate(context, editor.kclass?.java?.name, editor.data)
fragment.check()
return fragmentManger()?.beginTransaction()?.let {
if (editor.isClearPrev) {
fragmentManger()?.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
it.setCustomAnimations(enter, exit, enter, exit)
it.add(frameLayoutId, fragment, editor.TAG)
it.addToBackStack(editor.TAG)
fragment?.userVisibleHint = true
try {
(topFragment as? FbFragment)?.onFbPause()
it.commitAllowingStateLoss()
} catch (e: Exception) {
-1
}
} ?: -1
}
private fun doBack(editor: FbActionEditor): Int {
try {
if (canBack() && fragmentManger()?.popBackStackImmediate() == true) {
(topFragment() as? FbFragment)?.let {
if (editor.requestCode != 0) {
it.onFragmentResult(editor.requestCode, editor.resultCode, editor.data)
}
it.onFbResume()
}
return 0
}
} catch (e: Exception) {
e.printStackTrace()
}
return -1
}
fun canBack(): Boolean {
try {
return (fragmentManger()?.backStackEntryCount ?: 0) > 0
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
@SuppressLint("RestrictedApi")
fun topFragment(): Fragment? {
val fm = fragmentManger()
if (fm != null) {
val count = fm.backStackEntryCount
if (count > 0) {
return getFragmentByTag(fm.getBackStackEntryAt(count - 1).name)
}
return fm.fragments.first { it != null && it.isVisible }
}
return null
}
fun getFragmentByTag(TAG: String) = fragmentManger()?.findFragmentByTag(TAG)
fun onBackPress(): Boolean {
try {
return topFragment()?.check()?.onBackPress() ?: false
} catch (e: Exception) {
}
return false
}
fun fragmentManger(): FragmentManager? = fragmentManagerWrapper.get()
companion object {
/** SuperFragmentManager collection. */
private val managerMap = mutableMapOf<String, FbFragmentManager>()
fun with(activity: FragmentActivity, @IdRes frameLayoutId: Int): FbFragmentManager {
return with(activity, activity.javaClass.canonicalName, activity.supportFragmentManager,
frameLayoutId)
}
fun with(fragment: Fragment, @IdRes frameLayoutId: Int): FbFragmentManager =
with(fragment.activity!!, fragment.javaClass.canonicalName, fragment.childFragmentManager, frameLayoutId)
private fun with(context: Context, TAG: String,
fragmentManager: FragmentManager, @IdRes frameLayoutId: Int): FbFragmentManager {
var manager = managerMap[TAG]
if (manager == null) {
manager = FbFragmentManager(context.applicationContext, TAG, fragmentManager,
frameLayoutId)
managerMap.put(TAG, manager)
}
return manager
}
fun getManager(fragment: Fragment): FbFragmentManager? =
managerMap[fragment.javaClass.canonicalName]
fun getManager(activity: FragmentActivity): FbFragmentManager? =
managerMap[activity.javaClass.canonicalName]
fun getManager(TAG: String): FbFragmentManager? = managerMap[TAG]
fun remove(fragment: Fragment) {
managerMap.remove(fragment.javaClass.canonicalName)
}
fun remove(activity: FragmentActivity) {
managerMap.remove(activity.javaClass.canonicalName)
}
}
}
internal fun Fragment.check(): FbFragment {
if (this !is FbFragment) {
throw IllegalAccessException("${this.javaClass.name} does not inherit FbFragment")
}
return this
}
|
apache-2.0
|
3dffdb59c50e76fd77e5c2973f487a17
| 28.662393 | 113 | 0.656196 | 4.268143 | false | false | false | false |
fython/shadowsocks-android
|
mobile/src/main/java/com/github/shadowsocks/widget/ServiceButton.kt
|
3
|
5475
|
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
package com.github.shadowsocks.widget
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.design.widget.FloatingActionButton
import android.support.graphics.drawable.Animatable2Compat
import android.support.graphics.drawable.AnimatedVectorDrawableCompat
import android.support.v7.widget.TooltipCompat
import android.util.AttributeSet
import android.view.View
import com.github.shadowsocks.R
import com.github.shadowsocks.bg.BaseService
import java.util.*
class ServiceButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FloatingActionButton(context, attrs, defStyleAttr) {
private val callback = object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable) {
super.onAnimationEnd(drawable)
var next = animationQueue.peek() ?: return
if (next.current == drawable) {
animationQueue.pop()
next = animationQueue.peek() ?: return
}
setImageDrawable(next)
next.start()
}
}
private fun createIcon(@DrawableRes resId: Int): AnimatedVectorDrawableCompat {
val result = AnimatedVectorDrawableCompat.create(context, resId)!!
result.registerAnimationCallback(callback)
return result
}
private val iconStopped by lazy { createIcon(R.drawable.ic_service_stopped) }
private val iconConnecting by lazy { createIcon(R.drawable.ic_service_connecting) }
private val iconConnected by lazy { createIcon(R.drawable.ic_service_connected) }
private val iconStopping by lazy { createIcon(R.drawable.ic_service_stopping) }
private val animationQueue = ArrayDeque<AnimatedVectorDrawableCompat>()
private var checked = false
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (checked) View.mergeDrawableStates(drawableState, intArrayOf(android.R.attr.state_checked))
return drawableState
}
fun changeState(state: Int, animate: Boolean) {
when (state) {
BaseService.CONNECTING -> changeState(iconConnecting, animate)
BaseService.CONNECTED -> changeState(iconConnected, animate)
BaseService.STOPPING -> changeState(iconStopping, animate)
else -> changeState(iconStopped, animate)
}
if (state == BaseService.CONNECTED) {
checked = true
TooltipCompat.setTooltipText(this, context.getString(R.string.stop))
} else {
checked = false
TooltipCompat.setTooltipText(this, context.getString(R.string.connect))
}
refreshDrawableState()
isEnabled = state == BaseService.CONNECTED || state == BaseService.STOPPED
}
private fun counters(a: AnimatedVectorDrawableCompat, b: AnimatedVectorDrawableCompat): Boolean =
a == iconStopped && b == iconConnecting ||
a == iconConnecting && b == iconStopped ||
a == iconConnected && b == iconStopping ||
a == iconStopping && b == iconConnected
private fun changeState(icon: AnimatedVectorDrawableCompat, animate: Boolean) {
if (animate) {
if (animationQueue.size < 2 || !counters(animationQueue.last, icon)) {
animationQueue.add(icon)
if (animationQueue.size == 1) {
setImageDrawable(icon)
icon.start()
}
} else animationQueue.removeLast()
} else {
animationQueue.peekFirst()?.stop()
animationQueue.clear()
setImageDrawable(icon)
icon.start() // force ensureAnimatorSet to be called so that stop() will work
icon.stop()
}
}
}
|
gpl-3.0
|
86746f6d079fdef3435a9110e2a369d6
| 47.883929 | 117 | 0.58484 | 5.300097 | false | false | false | false |
google-developer-training/android-basics-kotlin-inventory-app
|
app/src/main/java/com/example/inventory/ItemListFragment.kt
|
1
|
2750
|
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.inventory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.inventory.databinding.ItemListFragmentBinding
/**
* Main fragment displaying details for all items in the database.
*/
class ItemListFragment : Fragment() {
private val viewModel: InventoryViewModel by activityViewModels {
InventoryViewModelFactory(
(activity?.application as InventoryApplication).database.itemDao()
)
}
private var _binding: ItemListFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ItemListFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ItemListAdapter {
val action =
ItemListFragmentDirections.actionItemListFragmentToItemDetailFragment(it.id)
this.findNavController().navigate(action)
}
binding.recyclerView.layoutManager = LinearLayoutManager(this.context)
binding.recyclerView.adapter = adapter
// Attach an observer on the allItems list to update the UI automatically when the data
// changes.
viewModel.allItems.observe(this.viewLifecycleOwner) { items ->
items.let {
adapter.submitList(it)
}
}
binding.floatingActionButton.setOnClickListener {
val action = ItemListFragmentDirections.actionItemListFragmentToAddItemFragment(
getString(R.string.add_fragment_title)
)
this.findNavController().navigate(action)
}
}
}
|
apache-2.0
|
445b51fb863a2fb4ba25bfe7fcb259c1
| 35.184211 | 95 | 0.708364 | 5.064457 | false | false | false | false |
mizukami2005/StockQiita
|
app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/view/activity/ArticleActivity.kt
|
1
|
5948
|
package com.mizukami2005.mizukamitakamasa.qiitaclient.view.activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Vibrator
import android.support.v4.content.res.ResourcesCompat
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import com.joanzapata.iconify.IconDrawable
import com.joanzapata.iconify.fonts.MaterialIcons
import com.mizukami2005.mizukamitakamasa.qiitaclient.MainActivity
import com.mizukami2005.mizukamitakamasa.qiitaclient.QiitaClientApp
import com.mizukami2005.mizukamitakamasa.qiitaclient.R
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.ArticleClient
import com.mizukami2005.mizukamitakamasa.qiitaclient.model.Article
import com.mizukami2005.mizukamitakamasa.qiitaclient.toast
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import kotlinx.android.synthetic.main.activity_article.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import javax.inject.Inject
class ArticleActivity : AppCompatActivity() {
@Inject
lateinit var articleClient: ArticleClient
lateinit var article: Article
var checkStock = false
var isMenu = false
lateinit var data: SharedPreferences
lateinit var token: String
val TOKEN_PREFERENCES_NAME = "DataToken"
val TOKEN = "token"
companion object {
private const val ARTICLE_EXTRA: String = "article"
fun intent(context: Context, article: Article): Intent =
Intent(context, ArticleActivity::class.java)
.putExtra(ARTICLE_EXTRA, article)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as QiitaClientApp).component.inject(this)
setContentView(R.layout.activity_article)
article = intent.getParcelableExtra(ARTICLE_EXTRA)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
article_view.setArticle(article, true)
markdown_view.setMarkDownText(article.body)
app_bar.addOnOffsetChangedListener { appBarLayout, offset ->
collapsing_toolbar.title = ""
toolbar_text_view.text = ""
isMenu = false
invalidateOptionsMenu()
if (-offset + toolbar.height == collapsing_toolbar.height) {
isMenu = true
toolbar_text_view.text = article.title
invalidateOptionsMenu()
}
}
data = getSharedPreferences(TOKEN_PREFERENCES_NAME, Context.MODE_PRIVATE)
token = data.getString(TOKEN, "")
toolbar.setOnMenuItemClickListener(object: Toolbar.OnMenuItemClickListener {
override fun onMenuItemClick(item: MenuItem?): Boolean {
changeStockUnstock()
return true
}
})
processCheck(articleClient.checkStock("Bearer $token", article.id))
stock_button.setImageDrawable(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.colorQiita))
stock_button.setOnClickListener {
changeStockUnstock()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (isMenu) {
menuInflater.inflate(R.menu.menu_main, menu)
menu.findItem(R.id.action_stock).setIcon(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.fab_background).actionBarSize())
if (checkStock) {
menu.findItem(R.id.action_stock).setIcon(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.stocked_article).actionBarSize())
}
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
private fun processCheck(observable: Observable<String>) {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.bindToLifecycle(MainActivity())
.subscribe({
val stateList = ColorStateList(
arrayOf<IntArray>(intArrayOf()), intArrayOf(Color.parseColor("#C9302C"))
)
stock_button.backgroundTintList = stateList
stock_button.setImageDrawable(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.fab_background))
checkStock = true
}, {
checkStock = false
})
}
private fun processStock(observable: Observable<String>, isStock: Boolean) {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate { invalidateOptionsMenu() }
.bindToLifecycle(MainActivity())
.subscribe({
if (isStock) {
checkStock = true
val vib = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vib.vibrate(100)
} else {
checkStock = false
}
}, {
if (isStock) {
checkStock = false
} else {
checkStock = true
}
})
}
private fun changeStockUnstock() {
if (token.length != 0 && !checkStock) {
val stateList = ColorStateList(
arrayOf<IntArray>(intArrayOf()), intArrayOf(Color.parseColor("#C9302C"))
)
stock_button.backgroundTintList = stateList
stock_button.setImageDrawable(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.fab_background))
processStock(articleClient.stock("Bearer $token", article.id), true)
} else if (token.length != 0 && checkStock) {
val stateList = ColorStateList(
arrayOf<IntArray>(intArrayOf()), intArrayOf(Color.parseColor("#FFFFFF"))
)
stock_button.backgroundTintList = stateList
stock_button.setImageDrawable(IconDrawable(this, MaterialIcons.md_folder).colorRes(R.color.colorQiita))
processStock(articleClient.unStock("Bearer $token", article.id), false)
} else {
toast(getString(R.string.not_login_message))
}
}
}
|
mit
|
613761cf717db916005042f9f78d6ec3
| 33.381503 | 143 | 0.727303 | 4.316401 | false | false | false | false |
SoulBeaver/SpriteSheetProcessor
|
src/main/java/com/sbg/rpg/packing/unpacker/SpriteSheetUnpacker.kt
|
1
|
10719
|
/*
* Copyright 2016 Christian Broomfield
*
* 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.sbg.rpg.packing.unpacker
import com.sbg.rpg.packing.common.SpriteBounds
import com.sbg.rpg.packing.common.SpriteCutter
import com.sbg.rpg.packing.common.SpriteSheet
import com.sbg.rpg.packing.common.extensions.*
import org.apache.logging.log4j.LogManager
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import java.awt.image.BufferedImage
import java.util.*
/**
* Motivation: oftentimes a SpriteSheet is given without any further information. For example,
* a spritesheet with twenty sprites from the famous Megaman series. How do you integrate this into your game?
* Do you calculate the position and size of each sprite by hand? Of course not, apps like TexturePacker do a wonderful
* job of taking individual sprites, packing them, and handing you an atlas with all necessary information.
*
* However, to do that, you need the individual sprites first! This class, SpriteSheetUnpacker, cuts up a SpriteSheet
* and delivers the individual sprites.
*/
class SpriteSheetUnpacker(
private val spriteCutter: SpriteCutter,
// TODO: make value user-configurable
private val colorSimilarityThreshold: Int = 10,
// TODO: user-configurable variable to adjust the unpacking algorithm which may or may not help the general effort
private val maxPixelDistance: Int = 3) {
private val logger = LogManager.getLogger(SpriteSheetUnpacker::class.simpleName)
/**
* Given a valid sprite sheet, detects and returns every individual sprite. The method may not be perfect and
* return grouped sprites if they're not contiguous. Does not alter the source common in any way.
*
* @param spriteSheet the sprite sheet to unpack
* @return list of extracted sprite images
*/
fun unpack(spriteSheet: BufferedImage): List<BufferedImage> {
val backgroundColor = spriteSheet.probableBackgroundColor()
logger.debug("The background color (probably) is $backgroundColor")
return discoverSprites(spriteSheet).pmap {
spriteCutter.cut(spriteSheet, it, backgroundColor)
}
}
/**
* Given a valid sprite sheet, detects and returns the bounding rectangle of every individual sprite. The method may not be perfect and
* return grouped sprites if they're not contiguous. Does not alter the source common in any way.
*
* @param spriteSheet the sprite sheet to unpack
* @return list of extracted sprite bounds
*/
fun discoverSprites(spriteSheet: SpriteSheet): List<SpriteBounds> {
val spriteBoundsList = findSprites(spriteSheet, spriteSheet.probableBackgroundColor())
logger.info("Found ${spriteBoundsList.size} sprites.")
// any sprites completely inside other sprites? exclude 'em.
val filteredSpriteBoundsList = filterSpritesContainedCompletelyInOtherSprites(spriteBoundsList)
logger.debug("${spriteBoundsList.size} sprites remaining after filtering.")
// any sprites have one or more of their edges inside anothers? merge 'em.
val filteredAndMergedSpriteBoundsList = mergeSpritesWithOverlappingEdges(filteredSpriteBoundsList)
logger.debug("${spriteBoundsList.size} sprites remaining after merging sprites with overlapping edges.")
return filteredAndMergedSpriteBoundsList
}
/*
* Sometimes we have sprites that have components that aren't connected, but still part of the same sprite.
*
* See the `unpacker/Intersecting.png` image in the test/resources directly for an example of this. Goku's aura
* near the top forms a crown that isn't directly connected to the rest of his sprite, but should clearly not be treated
* as a separate sprite. Instead, we check if the edges of their corresponding boundaries are contained inside each other.
*
* It's very important that there is a distinction made between entire edges inside of other sprite bounds and not
* simply searching for an intersection. Densely packed sprite sheets may have many intersections among sprites, but
* should not be merged.
*
* As a consideration for the future, this option might become toggleable.
*/
private fun mergeSpritesWithOverlappingEdges(spriteBoundsList: List<SpriteBounds>): List<SpriteBounds> {
if (spriteBoundsList.size <= 1)
return spriteBoundsList
val mergedSpriteBoundsList = mutableListOf(*spriteBoundsList.toTypedArray())
for (a: Rectangle in spriteBoundsList) {
for (b in spriteBoundsList.reversed()) {
if (a == b) {
break
}
if (a.containsLine(b)) {
mergedSpriteBoundsList.remove(a)
mergedSpriteBoundsList.remove(b)
val c = a.union(b)
mergedSpriteBoundsList.add(c)
}
}
}
return mergedSpriteBoundsList
}
/*
* Some sprites are located entirely inside of other sprites. A sprite that is within another sprite completely
* is considered part of that sprite and its boundaries are discarded.
*/
private fun filterSpritesContainedCompletelyInOtherSprites(spriteBoundsList: List<SpriteBounds>): List<SpriteBounds> {
if (spriteBoundsList.size <= 1)
return spriteBoundsList
val filteredSpriteBoundsList = mutableListOf<SpriteBounds>()
val spriteBoundsListByAreaAsc = spriteBoundsList.sortedBy(SpriteBounds::area)
for (spriteBoundsAsc in spriteBoundsListByAreaAsc) {
for (spriteBoundsDesc in spriteBoundsListByAreaAsc.reversed()) {
if (spriteBoundsAsc.area() >= spriteBoundsDesc.area()) {
filteredSpriteBoundsList.add(spriteBoundsAsc)
break
}
if (spriteBoundsDesc.contains(spriteBoundsAsc)) {
break
}
}
}
return filteredSpriteBoundsList
}
private fun findSprites(spriteSheet: SpriteSheet,
backgroundColor: Color): List<SpriteBounds> {
val workingCopy = spriteSheet.copy()
val spriteBoundsList = ArrayList<Rectangle>()
for (pixel in workingCopy) {
val (point, color) = pixel
if (backgroundColor.distance(color) > colorSimilarityThreshold) {
logger.debug("Found a sprite starting at (${point.x}, ${point.y}) with color $color")
val spritePlot = plotSprite(workingCopy, point, backgroundColor)
val spriteBounds = constructSpriteBoundsFromPlot(spritePlot)
logger.debug("The identified sprite has an area of ${spriteBounds.width}x${spriteBounds.height}")
spriteBoundsList.add(spriteBounds)
workingCopy.erasePoints(spritePlot, backgroundColor)
}
}
return spriteBoundsList
}
private fun plotSprite(spriteSheet: SpriteSheet, point: Point, backgroundColor: Color): List<Point> {
val unvisited = LinkedList<Point>()
val visited = hashSetOf(point)
unvisited.addAll(neighbors(point, spriteSheet).filter { spriteSheet.getRGB(it.x, it.y) != backgroundColor.rgb })
while (unvisited.isNotEmpty()) {
val currentPoint = unvisited.pop()
val currentColor = Color(spriteSheet.getRGB(currentPoint.x, currentPoint.y), true)
if (backgroundColor.distance(currentColor) > colorSimilarityThreshold) {
unvisited.addAll(neighbors(currentPoint, spriteSheet).filter {
val neighborColor = Color(spriteSheet.getRGB(it.x, it.y))
!visited.contains(it) &&
!unvisited.contains(it) &&
backgroundColor.distance(neighborColor) > colorSimilarityThreshold
})
visited.add(currentPoint)
}
}
return visited.toList()
}
private fun neighbors(point: Point, spriteSheet: BufferedImage): List<Point> {
val neighbors = ArrayList<Point>(8)
val imageWidth = spriteSheet.getWidth(null) - 1
val imageHeight = spriteSheet.getHeight(null) - 1
// Left neighbor
if (point.x > 0)
neighbors.add(Point(point.x - 1, point.y))
// Right neighbor
if (point.x < imageWidth)
neighbors.add(Point(point.x + 1, point.y))
// Top neighbor
if (point.y > 0)
neighbors.add(Point(point.x, point.y - 1))
// Bottom neighbor
if (point.y < imageHeight)
neighbors.add(Point(point.x, point.y + 1))
// Top-left neighbor
if (point.x > 0 && point.y > 0)
neighbors.add(Point(point.x - 1, point.y - 1))
// Top-right neighbor
if (point.x < imageWidth && point.y > 0)
neighbors.add(Point(point.x + 1, point.y - 1))
// Bottom-left neighbor
if (point.x > 0 && point.y < imageHeight - 1)
neighbors.add(Point(point.x - 1, point.y + 1))
// Bottom-right neighbor
if (point.x < imageWidth && point.y < imageHeight)
neighbors.add(Point(point.x + 1, point.y + 1))
return neighbors
}
private fun constructSpriteBoundsFromPlot(points: List<Point>): Rectangle {
if (points.isEmpty())
throw IllegalArgumentException("No points to span Rectangle from.")
val left = points.reduce { current, next ->
if (current.x > next.x) next else current
}
val top = points.reduce { current, next ->
if (current.y > next.y) next else current
}
val right = points.reduce { current, next ->
if (current.x < next.x) next else current
}
val bottom = points.reduce { current, next ->
if (current.y < next.y) next else current
}
return Rectangle(left.x, top.y,
right.x - left.x + 1,
bottom.y - top.y + 1)
}
}
|
apache-2.0
|
f8b6869aa1e8fa0ecbd2c744030ce242
| 39.760456 | 139 | 0.65174 | 4.634241 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/MemeMakerExecutor.kt
|
1
|
2246
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.gabrielaimageserver.data.MemeMakerRequest
import net.perfectdreams.gabrielaimageserver.data.URLImageData
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.declarations.MemeMakerCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.gabrielaimageserver.handleExceptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
class MemeMakerExecutor(
loritta: LorittaBot,
val client: GabrielaImageServerClient
) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val line1 = string("line1", MemeMakerCommand.I18N_PREFIX.Options.Line1)
val line2 = optionalString("line2", MemeMakerCommand.I18N_PREFIX.Options.Line2)
val imageReference = imageReferenceOrAttachment("image")
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage() // Defer message because image manipulation is kinda heavy
val imageReference = args[options.imageReference].get(context)!!
val line1 = args[options.line1]
val line2 = args[options.line2]
val result = client.handleExceptions(context) {
client.images.memeMaker(
MemeMakerRequest(
URLImageData(imageReference.url),
line1,
line2
)
)
}
context.sendMessage {
addFile("meme_maker.png", result.inputStream())
}
}
}
|
agpl-3.0
|
137fa5fc3805661fbd49f493e9bb0656
| 43.94 | 114 | 0.760463 | 5.092971 | false | false | false | false |
MichaelRocks/lightsaber
|
processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/CollectionsExtensions.kt
|
1
|
1247
|
/*
* Copyright 2018 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.commons
import java.util.Collections
import java.util.SortedMap
import java.util.SortedSet
fun <T> Collection<T>.immutable(): Collection<T> = Collections.unmodifiableCollection(this)
fun <T> List<T>.immutable(): List<T> = Collections.unmodifiableList(this)
fun <K, V> Map<K, V>.immutable(): Map<K, V> = Collections.unmodifiableMap(this)
fun <T> Set<T>.immutable(): Set<T> = Collections.unmodifiableSet(this)
fun <K, V> SortedMap<K, V>.immutable(): SortedMap<K, V> = Collections.unmodifiableSortedMap(this)
fun <T> SortedSet<T>.immutable(): SortedSet<T> = Collections.unmodifiableSortedSet(this)
|
apache-2.0
|
25dca0f329c102f7d0d3be97f14f9241
| 43.535714 | 97 | 0.752205 | 3.872671 | false | false | false | false |
NoodleMage/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/data/database/queries/TrackQueries.kt
|
3
|
1351
|
package eu.kanade.tachiyomi.data.database.queries
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio.sqlite.queries.Query
import eu.kanade.tachiyomi.data.database.DbProvider
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.database.tables.TrackTable
import eu.kanade.tachiyomi.data.track.TrackService
interface TrackQueries : DbProvider {
fun getTracks(manga: Manga) = db.get()
.listOfObjects(Track::class.java)
.withQuery(Query.builder()
.table(TrackTable.TABLE)
.where("${TrackTable.COL_MANGA_ID} = ?")
.whereArgs(manga.id)
.build())
.prepare()
fun insertTrack(track: Track) = db.put().`object`(track).prepare()
fun insertTracks(tracks: List<Track>) = db.put().objects(tracks).prepare()
fun deleteTrackForManga(manga: Manga, sync: TrackService) = db.delete()
.byQuery(DeleteQuery.builder()
.table(TrackTable.TABLE)
.where("${TrackTable.COL_MANGA_ID} = ? AND ${TrackTable.COL_SYNC_ID} = ?")
.whereArgs(manga.id, sync.id)
.build())
.prepare()
}
|
apache-2.0
|
a0eb1e5929a24c13d75d6a438bb13380
| 37.794118 | 94 | 0.618801 | 4.118902 | false | false | false | false |
mua-uniandes/weekly-problems
|
codeforces/939/939a.kt
|
1
|
528
|
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val In = BufferedReader(InputStreamReader(System.`in`))
In.readLine()!!.toInt()
val planes = In.readLine()!!.split(" ").map {it.toInt() - 1}
triangle(planes, 0)
}
fun triangle(nodes : List<Int>, count : Int) {
if(count == nodes[nodes[nodes[count]]]) {
println("YES")
return
} else if(count == nodes.size -1){
println("NO")
return
} else {
return triangle(nodes, count+1)
}
}
|
gpl-3.0
|
e8e65fe1f0c2ceddc956d3db4ca4ec06
| 23.045455 | 64 | 0.587121 | 3.666667 | false | false | false | false |
alessio-b-zak/myRivers
|
android/app/src/main/java/com/epimorphics/android/myrivers/helpers/InputStreamHelper.kt
|
1
|
1016
|
package com.epimorphics.android.myrivers.helpers
import android.util.JsonReader
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
/**
* Helper class providing base functions used by most input stream converters
*/
abstract class InputStreamHelper {
/**
* Reads a value corresponding to a given key inside a next Json Object
*
* @param reader JsonReader
* @param key key
*
* @return value as a string corresponding to the given key
*/
fun readItemToString(reader: JsonReader, key: String = "label"): String {
var item = ""
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
if (name == key) {
item = reader.nextString()
} else {
reader.skipValue()
}
}
reader.endObject()
return item
}
}
|
mit
|
f44e1672beed8031f879d597455cfb0b
| 25.076923 | 77 | 0.628937 | 4.725581 | false | false | false | false |
emce/smog
|
app/src/main/java/mobi/cwiklinski/smog/database/SelectionBuilder.kt
|
1
|
3847
|
package mobi.cwiklinski.smog.database
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.text.TextUtils
import java.util.*
class SelectionBuilder {
private var mTable: String? = null
private val mProjectionMap = HashMap<String, String>()
private val mSelection = StringBuilder()
private val mSelectionArgs = ArrayList<String>()
/**
* Reset any internal state, allowing this builder to be recycled.
*/
fun reset(): SelectionBuilder {
mTable = null
mSelection.setLength(0)
mSelectionArgs.clear()
return this
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using `AND`.
*/
fun where(selection: String?, selectionArgs: Array<out String>?): SelectionBuilder {
if (selection == null || selection.isEmpty() || selectionArgs == null || selectionArgs.isEmpty()) {
return this
}
if (mSelection.length > 0) {
mSelection.append(" AND ")
}
mSelection.append("(").append(selection).append(")")
Collections.addAll(mSelectionArgs as Collection<*>?, *selectionArgs)
return this
}
fun table(table: String): SelectionBuilder {
mTable = table
return this
}
private fun assertTable() {
if (mTable == null) {
throw IllegalStateException("Table not specified")
}
}
fun mapToTable(column: String, table: String): SelectionBuilder {
mProjectionMap.put(column, table + "." + column)
return this
}
fun map(fromColumn: String, toClause: String): SelectionBuilder {
mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn)
return this
}
/**
* Return selection string for current internal state.
* @see .getSelectionArgs
*/
val selection: String
get() = mSelection.toString()
/**
* Return selection arguments for current internal state.
* @see .getSelection
*/
val selectionArgs: Array<String>
get() = mSelectionArgs.toArray<String>(arrayOfNulls<String>(mSelectionArgs.size))
private fun mapColumns(columns: Array<String>) {
for (i in columns.indices) {
val target = mProjectionMap[columns[i]]
if (target != null) {
columns[i] = target
}
}
}
override fun toString(): String {
return "SelectionBuilder[table=" + mTable + ", selection=" + selection + ", selectionArgs=" + Arrays.toString(selectionArgs) + "]"
}
/**
* Execute query using the current internal state as `WHERE` clause.
*/
fun query(db: SQLiteDatabase, columns: Array<String>?, orderBy: String?): Cursor {
return query(db, columns, null, null, orderBy, null)
}
/**
* Execute query using the current internal state as `WHERE` clause.
*/
fun query(db: SQLiteDatabase, columns: Array<String>?, groupBy: String?,
having: String?, orderBy: String?, limit: String?): Cursor {
assertTable()
if (columns != null) mapColumns(columns)
return db.query(mTable, columns, selection, selectionArgs, groupBy, having,
orderBy, limit)
}
/**
* Execute update using the current internal state as `WHERE` clause.
*/
fun update(db: SQLiteDatabase, values: ContentValues): Int {
assertTable()
return db.update(mTable, values, selection, selectionArgs)
}
/**
* Execute delete using the current internal state as `WHERE` clause.
*/
fun delete(db: SQLiteDatabase): Int {
assertTable()
return db.delete(mTable, selection, selectionArgs)
}
}
|
apache-2.0
|
259a7eadcfc61720ea2e0cf79f139024
| 28.829457 | 138 | 0.622823 | 4.702934 | false | false | false | false |
tehras/ActiveTouch
|
activetouchsample/src/main/java/com/github/tehras/activetouchsample/MainActivity.kt
|
1
|
3696
|
package com.github.tehras.activetouchsample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.HapticFeedbackConstants
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.github.tehras.activetouch.touchlisteners.ActiveTouchBehavior
import java.util.*
class MainActivity : AppCompatActivity(), ActiveTouchBehavior.OnActiveTouchPopupListener {
override fun onShow() {
idList.clear()
}
override fun onDismiss() {
Toast.makeText(this, "Hover over - $idList", Toast.LENGTH_SHORT).show()
}
private var recyclerView: RecyclerView? = null
private var blockedScroll = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recycler_view) as RecyclerView
recyclerView!!.layoutManager = object : LinearLayoutManager(this) {
override fun canScrollVertically(): Boolean {
return !blockedScroll
}
}
recyclerView!!.setHasFixedSize(true)
recyclerView!!.adapter = SampleAdapter(this)
}
class SampleAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder> {
val activity: MainActivity
constructor(activity: MainActivity) {
this.activity = activity
}
var lastInt = -1
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (position > lastInt)
activity.addLongHolder(holder!!.itemView)
lastInt = position
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
return ViewHolder(LayoutInflater.from(parent!!.context).inflate(R.layout.layout_sample_list_view, parent, false))
}
override fun getItemCount(): Int {
return 20
}
class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
}
}
var idList = ArrayList<Int>()
fun addLongHolder(v: View?) {
ActiveTouchBehavior.Builder(v!!, this.findViewById(R.id.container_view) as ViewGroup)
.setPopupCallback(this)
.setHoverCallback(object : ActiveTouchBehavior.OnViewHoverOverListener {
override fun onHover(v: View?, isInside: Boolean) {
Log.d("MainActivity", "view - ${v?.id} - inside - $isInside")
if (v != null && (v.id == R.id.add_button || v.id == R.id.remove_button || v.id == R.id.cancel_button)) {
if (isInside) {
if (!idList.contains(v.id)) {
idList.add(v.id)
v.background = [email protected](R.color.colorAccent)
v.isHapticFeedbackEnabled = true
v.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
}
} else {
idList.remove(v.id)
v.background = [email protected](android.R.color.white)
}
}
}
})
.setContentFragment(SampleFragment.getInstance())
.build(this)
}
}
|
apache-2.0
|
c5de1bc3611d5ffedaeec63c915529df
| 35.96 | 129 | 0.59605 | 5.035422 | false | false | false | false |
siempredelao/Distance-From-Me-Android
|
app/src/main/java/gc/david/dfm/distance/data/DistanceLocalDataSource.kt
|
1
|
1925
|
/*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.distance.data
import gc.david.dfm.database.DFMDatabase
import gc.david.dfm.database.Distance
import gc.david.dfm.database.Position
/**
* Created by david on 16.01.17.
*/
class DistanceLocalDataSource(private val database: DFMDatabase) : DistanceRepository {
override fun insert(distance: Distance, positionList: List<Position>, callback: DistanceRepository.Callback) {
val rowID = database.distanceDao().insert(distance)
if (rowID == -1L) {
callback.onFailure()
} else {
val positionListWithDistanceId = positionList.map { it.apply { distanceId = rowID } }
database.positionDao().insertMany(positionListWithDistanceId)
callback.onSuccess()
}
}
override fun loadDistances(callback: DistanceRepository.LoadDistancesCallback) {
callback.onSuccess(database.distanceDao().loadAll())
}
override fun clear(callback: DistanceRepository.Callback) {
with(database) {
distanceDao().deleteAll()
positionDao().deleteAll()
}
callback.onSuccess()
}
override fun getPositionListById(distanceId: Long, callback: DistanceRepository.LoadPositionsByIdCallback) {
callback.onSuccess(database.positionDao().loadAllById(distanceId))
}
}
|
apache-2.0
|
3629605857f4181336ce61f49d71320c
| 34.648148 | 114 | 0.705974 | 4.355204 | false | false | false | false |
emilybache/Racing-Car-Katas
|
kotlin/Leaderboard/src/main/kotlin/tddmicroexercises/leaderboard/Driver.kt
|
1
|
503
|
package tddmicroexercises.leaderboard
open class Driver(val name: String, val country: String) {
override fun hashCode(): Int {
return name.hashCode() * 31 + country.hashCode()
}
override fun equals(any: Any?): Boolean {
if (this === any) {
return true
}
if (any == null || any !is Driver) {
return false
}
val other = any as Driver?
return this.name == other!!.name && this.country == other.country
}
}
|
mit
|
711d7c17d20cb30543a3170193425ecf
| 25.473684 | 73 | 0.558648 | 4.262712 | false | false | false | false |
yschimke/oksocial
|
src/main/kotlin/com/baulsupp/okurl/services/facebook/facebook.kt
|
1
|
1910
|
package com.baulsupp.okurl.services.facebook
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.kotlin.edit
import com.baulsupp.okurl.kotlin.moshi
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.kotlin.queryForString
import com.baulsupp.okurl.kotlin.request
import com.baulsupp.okurl.kotlin.tokenSet
import com.baulsupp.okurl.services.facebook.model.Metadata
import com.baulsupp.okurl.services.facebook.model.MetadataResult
import com.baulsupp.okurl.services.facebook.model.PageableResult
import com.baulsupp.okurl.util.ClientException
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import kotlin.reflect.KClass
import kotlin.reflect.full.memberProperties
suspend inline fun <reified I, reified T : PageableResult<I>> OkHttpClient.fbQueryList(
path: String,
tokenSet: Token
): T {
val fields = fbFieldNames(I::class)
val stringResult = this.queryForString(
"https://graph.facebook.com/v2.11$path?fields=${fields.joinToString(",")}", tokenSet
)
return moshi.adapter<T>(T::class.java).fromJson(stringResult)!!
}
suspend inline fun <reified T> OkHttpClient.fbQuery(path: String, tokenSet: Token): T {
val fields = fbFieldNames(T::class)
return this.query(
"https://graph.facebook.com/v2.11$path?fields=${fields.joinToString(",")}",
tokenSet
)
}
fun fbFieldNames(kClass: KClass<*>): Collection<String> {
return kClass.memberProperties.map { it.name }.toSet().filterNot { it == "metadata" }
}
suspend fun getMetadata(client: OkHttpClient, requestUrl: HttpUrl, tokenSet: Token): Metadata? {
val request = request {
url(requestUrl.edit {
addQueryParameter("metadata", "1")
})
tokenSet(tokenSet)
}
return try {
val response = client.query<MetadataResult>(request)
response.metadata
} catch (ce: ClientException) {
if (ce.code != 404) {
throw ce
}
null
}
}
const val VERSION = "v3.0"
|
apache-2.0
|
e9ab534633b72559fcbd6b52bc282e4f
| 29.31746 | 96 | 0.74555 | 3.767258 | false | false | false | false |
alxnns1/MobHunter
|
src/main/kotlin/com/alxnns1/mobhunter/item/MHSword.kt
|
1
|
1995
|
package com.alxnns1.mobhunter.item
import com.alxnns1.mobhunter.init.SharpnessLevel
import com.google.common.collect.ImmutableMultimap
import com.google.common.collect.Multimap
import net.minecraft.entity.ai.attributes.Attribute
import net.minecraft.entity.ai.attributes.AttributeModifier
import net.minecraft.entity.ai.attributes.Attributes
import net.minecraft.inventory.EquipmentSlotType
import net.minecraft.item.IItemTier
import net.minecraft.item.ItemStack
import net.minecraft.item.SwordItem
class MHSword(
private val sharpness: List<Int>,
tier: IItemTier,
private val attackDamageIn: Int,
private val attackSpeedIn: Float,
builderIn: Properties
) : SwordItem(tier, 0, 0f, builderIn) {
override fun getRGBDurabilityForDisplay(stack: ItemStack): Int {
val damage = stack.maxDamage - stack.damage
val sharpnessLevel = sharpness.first { damage <= it }
return SharpnessLevel.values()[sharpness.indexOf(sharpnessLevel)].colour
}
override fun getAttributeModifiers(slot: EquipmentSlotType, stack: ItemStack): Multimap<Attribute, AttributeModifier> {
return if (slot == EquipmentSlotType.MAINHAND) {
ImmutableMultimap.builder<Attribute, AttributeModifier>()
.put(Attributes.ATTACK_DAMAGE, AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", attackDamageIn * getSharpnessAttackModifier(stack), AttributeModifier.Operation.ADDITION))
.put(Attributes.ATTACK_SPEED, AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", attackSpeedIn.toDouble(), AttributeModifier.Operation.ADDITION))
.build()
} else {
super.getAttributeModifiers(slot, stack)
}
}
override fun showDurabilityBar(stack: ItemStack?) = true
private fun getSharpnessAttackModifier(stack: ItemStack): Double {
val damage = stack.maxDamage - stack.damage
val sharpnessLevel = sharpness.first { damage <= it }
return SharpnessLevel.values()[sharpness.indexOf(sharpnessLevel)].multiplier
}
override fun getIsRepairable(toRepair: ItemStack, repair: ItemStack) = false
}
|
gpl-2.0
|
fcb3db57f48173a003d0bff49bc270d5
| 40.583333 | 186 | 0.798997 | 3.792776 | false | false | false | false |
snarks/RxProperty
|
src/main/kotlin/io/github/snarks/rxproperty/RxProperty.kt
|
1
|
1872
|
/*
* Copyright 2017 James Cruz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.snarks.rxproperty
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.subjects.PublishSubject
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* A mutable delegated property that is also an [Observable]
*
* **Example:**
* ```kotlin
* val fooProperty = RxProperty("initial")
* var foo by fooProperty
*
* fooProperty.subscribe(::println)
* foo = "hello"
* foo = "hello"
* foo = "world"
* // this will print 'hello', 'hello' and 'world'
* ```
*
* This class is an unbounded observable, so it will never emit `onError` or `onComplete`. It will emit `onNext`
* immediately after assigning a value to it.
*
* It's **not** safe to _assign_ values to `RxProperty` from multiple threads, but the usual RxJava operations are
* thread-safe.
*/
class RxProperty<T>(initialValue: T) : Observable<T>(), ReadWriteProperty<Any?, T> {
private val relay = PublishSubject.create<T>()
private var value = initialValue
override fun getValue(thisRef: Any?, property: KProperty<*>) = value
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
relay.onNext(value)
}
override fun subscribeActual(observer: Observer<in T>?) = relay.subscribe(observer)
}
|
apache-2.0
|
b3919fbe5a13b4b9ca4558584dd7d701
| 31.275862 | 114 | 0.724893 | 3.875776 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/test/kotlin/org/rust/ide/lineMarkers/RsLineMarkerProviderTestBase.kt
|
2
|
1510
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.lineMarkers
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
abstract class RsLineMarkerProviderTestBase : RsTestBase() {
protected fun doTestByText(@Language("Rust") source: String) {
myFixture.configureByText("lib.rs", source)
myFixture.doHighlighting()
val expected = markersFrom(source)
val actual = markersFrom(myFixture.editor, myFixture.project)
assertEquals(expected.joinToString(COMPARE_SEPARATOR), actual.joinToString(COMPARE_SEPARATOR))
}
private fun markersFrom(text: String) =
text.split('\n')
.withIndex()
.filter { it.value.contains(MARKER) }
.map { Pair(it.index, it.value.substring(it.value.indexOf(MARKER) + MARKER.length).trim()) }
private fun markersFrom(editor: Editor, project: Project) =
DaemonCodeAnalyzerImpl.getLineMarkers(editor.document, project)
.map {
Pair(editor.document.getLineNumber(it.element?.textRange?.startOffset as Int),
it.lineMarkerTooltip)
}
.sortedBy { it.first }
private companion object {
val MARKER = "// - "
val COMPARE_SEPARATOR = " | "
}
}
|
mit
|
c2814aa97a38a03b1fc3e27547d3ad46
| 35.829268 | 104 | 0.675497 | 4.454277 | false | true | false | false |
facebook/litho
|
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/DepsCollectionKComponent.kt
|
1
|
3097
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.kotlin.collection
import android.graphics.Color
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.core.padding
import com.facebook.litho.dp
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.sp
import com.facebook.litho.useState
import com.facebook.litho.view.alpha
import com.facebook.litho.widget.collection.LazyList
class DepsCollectionKComponent : KComponent() {
override fun ComponentScope.render(): Component? {
val color = useState { Color.RED }
val size = useState { 14 }
val alpha = useState { 1f }
return Column(style = Style.padding(16.dp)) {
child(
Row {
child(
Button("Toggle Color") {
color.update { prevColor ->
if (prevColor == Color.RED) Color.BLUE else Color.RED
}
})
child(
Button("Toggle Size") {
size.update { prevSize -> if (prevSize == 14) 28 else 14 }
})
child(
Button("Toggle Alpha") {
alpha.update { prevAlpha -> if (prevAlpha == 0.5f) 1f else 0.5f }
})
})
child(
LazyList {
child(
Text(
"deps = null (all props)",
textColor = color.value,
textSize = size.value.sp,
style = Style.alpha(alpha.value)))
child(deps = arrayOf(color.value)) {
Text(
"deps = arrayOf(color.value)",
textColor = color.value,
textSize = size.value.sp,
style = Style.alpha(alpha.value))
}
child(deps = arrayOf(size.value)) {
Text(
"deps = arrayOf(size.value)",
textColor = color.value,
textSize = size.value.sp,
style = Style.alpha(alpha.value))
}
child(deps = arrayOf()) {
Text(
"deps = arrayOf()",
textColor = color.value,
textSize = size.value.sp,
style = Style.alpha(alpha.value))
}
})
}
}
}
|
apache-2.0
|
4c656464f2f1abbdd4435c50fd9712ee
| 33.032967 | 83 | 0.561188 | 4.475434 | false | false | false | false |
google/horologist
|
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/PlayPauseButtonPreview.kt
|
1
|
2048
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@Preview(
"Enabled - Playing",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseButtonPreviewPlaying() {
PlayPauseButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = true
)
}
@Preview(
"Enabled - Not playing",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseButtonPreviewNotPlaying() {
PlayPauseButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = false
)
}
@Preview(
"Disabled - Playing",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseButtonPreviewDisabledPlaying() {
PlayPauseButton(
onPlayClick = {},
onPauseClick = {},
enabled = false,
playing = true
)
}
@Preview(
"Disabled - Not playing",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseButtonPreviewDisabledNotPlaying() {
PlayPauseButton(
onPlayClick = {},
onPauseClick = {},
enabled = false,
playing = false
)
}
|
apache-2.0
|
3a99cd9b2c6f655abbc3f79f0c3dfaee
| 23.674699 | 78 | 0.685547 | 4.423326 | false | false | false | false |
ajmirB/Messaging
|
app/src/main/java/com/xception/messaging/features/channels/items/MessageOtherModel.kt
|
1
|
1334
|
package com.xception.messaging.features.channels.items
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.EpoxyModelClass
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.xception.messaging.R
import com.xception.messaging.features.channels.presenters.MessageOtherItemData
@EpoxyModelClass(layout = R.layout.conversation_message_other_item)
abstract class MessageOtherModel : EpoxyModel<View>() {
@EpoxyAttribute
lateinit var message: MessageOtherItemData
override fun bind(view: View?) {
super.bind(view)
val senderTextView: TextView = view!!.findViewById(R.id.message_other_sender_name_text_view)
senderTextView.text = view.context.getString(R.string.conversation_sender_format_text, message.senderName)
val messageTextView: TextView = view.findViewById(R.id.message_other_text_view)
messageTextView.text = message.message
val mSenderImageView: ImageView = view.findViewById(R.id.conversation_message_sender_image_view)
Glide.with(view.context).load(message.senderImgUrl)
.apply(RequestOptions.circleCropTransform())
.into(mSenderImageView)
}
}
|
apache-2.0
|
85d39c89f45afc719ec13da18ac6a464
| 38.264706 | 114 | 0.767616 | 4.208202 | false | false | false | false |
mrkirby153/KirBot
|
src/main/kotlin/me/mrkirby153/KirBot/Bot.kt
|
1
|
12456
|
package me.mrkirby153.KirBot
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger
import com.mrkirby153.bfs.Pair
import com.mrkirby153.bfs.model.Model
import com.mrkirby153.bfs.model.SoftDeletingModel
import com.mrkirby153.bfs.query.QueryBuilder
import com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers
import io.sentry.Sentry
import me.mrkirby153.KirBot.botlists.BotListManager
import me.mrkirby153.KirBot.botlists.TopGGBotList
import me.mrkirby153.KirBot.command.CommandDocumentationGenerator
import me.mrkirby153.KirBot.database.models.guild.DiscordGuild
import me.mrkirby153.KirBot.error.UncaughtErrorReporter
import me.mrkirby153.KirBot.event.PriorityEventManager
import me.mrkirby153.KirBot.event.Subscribe
import me.mrkirby153.KirBot.infraction.Infractions
import me.mrkirby153.KirBot.inject.ApplicationContext
import me.mrkirby153.KirBot.listener.ShardListener
import me.mrkirby153.KirBot.listener.WaitUtilsListener
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.AdminControl
import me.mrkirby153.KirBot.rss.FeedTask
import me.mrkirby153.KirBot.server.KirBotGuild
import me.mrkirby153.KirBot.stats.Statistics
import me.mrkirby153.KirBot.utils.HttpUtils
import me.mrkirby153.KirBot.utils.readProperties
import me.mrkirby153.KirBot.utils.settings.SettingsRepository
import me.mrkirby153.kcutils.Time
import me.mrkirby153.kcutils.child
import me.mrkirby153.kcutils.readProperties
import me.mrkirby153.kcutils.utils.SnowflakeWorker
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.OnlineStatus
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Activity
import net.dv8tion.jda.api.events.ReadyEvent
import net.dv8tion.jda.api.requests.GatewayIntent
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder
import net.dv8tion.jda.api.sharding.ShardManager
import net.dv8tion.jda.api.utils.cache.CacheFlag
import okhttp3.Request
import org.json.JSONObject
import org.json.JSONTokener
import org.slf4j.LoggerFactory
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis
object Bot {
@JvmStatic
val LOG = LoggerFactory.getLogger("KirBot")
var initialized = false
var state = BotState.UNKNOWN
val startTime = System.currentTimeMillis()
val scheduler: ScheduledExecutorService = Executors.newScheduledThreadPool(5)
val files = BotFiles()
val properties = files.properties.readProperties()
var numShards: Int = 1
val constants = Bot.javaClass.getResourceAsStream("/constants.properties").readProperties()
val gitProperties = Bot.javaClass.getResourceAsStream("/git.properties")?.readProperties()
val playerManager: AudioPlayerManager = DefaultAudioPlayerManager().apply {
AudioSourceManagers.registerRemoteSources(this)
AudioSourceManagers.registerLocalSource(this)
}
val debug = properties.getProperty("debug", "false").toBoolean()
val idGenerator = SnowflakeWorker(1, 1)
val applicationContext = ApplicationContext()
private lateinit var shardManager: ShardManager
fun start(token: String) {
Statistics.export()
initializeSentry()
val startupTime = System.currentTimeMillis()
state = BotState.INITIALIZING
configureLogging()
Bot.LOG.info("Starting KirBot ${constants.getProperty("bot-version")}")
Bot.LOG.debug("\t + Base URL: ${constants.getProperty("bot-base-url")}")
Thread.setDefaultUncaughtExceptionHandler(UncaughtErrorReporter())
if (initialized)
throw IllegalStateException("Bot has already been initialized!")
initialized = true
// Register everything into the application context
ModuleManager.discoverModules()
applicationContext.scanForInjectables("me.mrkirby153.KirBot")
// Get the number of shards to start with
numShards = if (properties.getProperty("shards") == null || properties.getProperty(
"shards") == "auto") {
-1
} else {
properties.getProperty("shards").toInt()
}
LOG.info("Initializing Bot ($numShards shards)")
val startTime = System.currentTimeMillis()
state = BotState.CONNECTING
val gatewayIntents = listOf(GatewayIntent.GUILD_MEMBERS,
GatewayIntent.GUILD_BANS, GatewayIntent.GUILD_VOICE_STATES,
GatewayIntent.GUILD_MESSAGES, GatewayIntent.GUILD_MESSAGE_REACTIONS,
GatewayIntent.GUILD_EMOJIS)
shardManager = DefaultShardManagerBuilder.create(gatewayIntents).apply {
setToken(token)
setEventManagerProvider { PriorityEventManager() }
setStatus(OnlineStatus.IDLE)
setShardsTotal(numShards)
setAutoReconnect(true)
setBulkDeleteSplittingEnabled(false)
disableCache(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS)
setActivity(Activity.playing("Starting up..."))
if (!System.getProperty("os.name").contains("Mac"))
setAudioSendFactory(NativeAudioSendFactory())
}.build()
applicationContext.register(shardManager)
Bot.LOG.info("Waiting for shards to start..")
while (shardManager.shards.firstOrNull { it.status != JDA.Status.CONNECTED } != null) {
shardManager.shards.first { it.status != JDA.Status.CONNECTED }.awaitReady()
}
val endTime = System.currentTimeMillis()
LOG.info("\n\n\nSHARDS INITIALIZED! (${Time.format(1, endTime - startTime)})")
initializeBotLists()
val sl = applicationContext.newInstance(ShardListener::class.java)
val ac = applicationContext.newInstance(AdminControl::class.java)
shardManager.addEventListener(sl, ac)
state = BotState.LOADING
// Boot the modules
ModuleManager.load(true)
// Remove old guilds
purgeSoftDeletedGuilds()
val guilds = shardManager.shards.flatMap { it.guilds }
LOG.info("Started syncing of ${guilds.size} guilds")
val syncTime = measureTimeMillis {
guilds.forEach {
LOG.info("Syncing guild ${it.id} (${it.name})")
KirBotGuild[it].syncSeenUsers()
KirBotGuild[it].sync()
// KirBotGuild[it].dispatchBackfill()
}
}
LOG.info("Synced ${guilds.size} guilds ${Time.format(1,
syncTime)}")
HttpUtils.clearCache()
scheduler.scheduleAtFixedRate(applicationContext.newInstance(FeedTask::class.java), 0, 15,
TimeUnit.MINUTES)
ModuleManager.startScheduler()
applicationContext.get(Infractions::class.java).waitForInfraction()
// Register listener for nick changes
SettingsRepository.registerSettingsListener("bot_nick") { guild, value ->
if (guild.selfMember.hasPermission(Permission.NICKNAME_CHANGE))
guild.selfMember.modifyNickname(value).queue()
}
shardManager.setStatus(OnlineStatus.ONLINE)
shardManager.setActivity(null)
LOG.info("Startup completed in ${Time.format(0, System.currentTimeMillis() - startupTime)}")
val memberSet = mutableSetOf<String>()
Bot.shardManager.shards.flatMap { it.guilds }.flatMap { it.members }.forEach {
if (it.user.id !in memberSet)
memberSet.add(it.user.id)
}
val guildCount = shardManager.shards.flatMap { it.guilds }.count()
applicationContext.get(AdminControl::class.java).sendQueuedMessages()
applicationContext.get(AdminControl::class.java).log(
"Bot startup complete in ${Time.formatLong(
System.currentTimeMillis() - startTime).toLowerCase()}. On $guildCount guilds with ${memberSet.size} users")
CommandDocumentationGenerator.generate(files.data.child("commands.md"))
state = BotState.RUNNING
shardManager.addEventListener(object {
@Subscribe
fun onReady(event: ReadyEvent) {
Bot.LOG.info(
"Shard ${event.jda.shardInfo.shardId} is ready, syncing all guilds (${event.jda.guilds.size})")
event.jda.guilds.forEach {
KirBotGuild[it].syncSeenUsers()
KirBotGuild[it].sync()
}
}
})
shardManager.addEventListener(WaitUtilsListener())
}
private fun purgeSoftDeletedGuilds() {
LOG.info("Purging old guilds...")
// Remove guilds whose time has passed
val threshold = Instant.now().minus(Duration.ofDays(30))
LOG.info("Removing guilds that we left before ${SimpleDateFormat(
"MM-dd-yy HH:mm:ss").format(threshold.toEpochMilli())}")
val guilds = SoftDeletingModel.withTrashed(DiscordGuild::class.java).where("deleted_at",
"<",
Timestamp.from(threshold)).get()
LOG.info("${guilds.size} guilds being purged")
guilds.forEach { it.forceDelete() }
val guildList = shardManager.shards.flatMap { it.guilds }
Model.query(DiscordGuild::class.java).whereNotIn("id",
guildList.map { it.id }.toTypedArray()).whereNull("deleted_at").update(
listOf(Pair<String, Any>("deleted_at", Timestamp(System.currentTimeMillis()))))
}
private fun configureLogging() {
if (debug) {
(LOG as? Logger)?.let { logger ->
logger.level = Level.DEBUG
}
}
if (System.getProperty("kirbot.logQueries", "false")?.toBoolean() == true) {
LOG.warn("Setting log level for bfs to TRACE")
(LoggerFactory.getLogger(QueryBuilder::class.java) as? Logger)?.level = Level.TRACE
}
(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as? Logger)?.level = Level.valueOf(
System.getProperty("kirbot.global_log", "INFO"))
}
fun stop() {
state = BotState.SHUTTING_DOWN
applicationContext.get(AdminControl::class.java).log("Bot shutting down...")
shardManager.shutdown()
ModuleManager.unloadAll()
LOG.info("Bot is disconnecting from Discord")
state = BotState.SHUT_DOWN
System.exit(0)
}
private fun getNumShards(token: String): Int {
LOG.debug("Asking Discord for the number of shards to use...")
val request = Request.Builder().apply {
url("https://discordapp.com/api/v6/gateway/bot")
header("Authorization", "Bot $token")
}.build()
val response = HttpUtils.CLIENT.newCall(request).execute()
if (response.code() != 200)
throw RuntimeException(
"Received non-success code (${response.code()}) from Discord, aborting")
val body = response.body()?.string()
if (body.isNullOrEmpty()) {
throw RuntimeException(
"Could not determine the number of shards. Must be specified manually")
}
LOG.debug("Received body $body")
val json = JSONObject(JSONTokener(body))
val shards = json.getInt("shards")
LOG.debug("Discord returned $shards shards.")
return shards
}
private fun initializeBotLists() {
val manager = applicationContext.newInstance(BotListManager::class.java)
applicationContext.register(manager)
val topGGKey = properties.getProperty("botlist.topgg")
if (topGGKey != null) {
manager.registerBotList(TopGGBotList(topGGKey, shardManager.shards.first().selfUser.id))
}
manager.updateBotLists()
}
private fun initializeSentry() {
val sentryDsn = properties.getProperty("sentry-dsn")
if (sentryDsn != null) {
LOG.info("Initializing sentry")
Sentry.init(sentryDsn)
} else {
LOG.warn("Sentry dsn was not found. Skipping initialization")
}
}
}
|
mit
|
1ff714ca21874ce10cd04af693450f8c
| 39.054662 | 132 | 0.67622 | 4.495128 | false | false | false | false |
openMF/android-client
|
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/loanaccountsummary/LoanAccountSummaryFragment.kt
|
1
|
17873
|
/*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.loanaccountsummary
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Button
import android.widget.QuickContactBadge
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.ProgressableFragment
import com.mifos.mifosxdroid.online.datatable.DataTableFragment
import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment
import com.mifos.mifosxdroid.online.loanaccountapproval.LoanAccountApproval
import com.mifos.mifosxdroid.online.loanaccountdisbursement.LoanAccountDisbursementFragment
import com.mifos.mifosxdroid.online.loancharge.LoanChargeFragment
import com.mifos.objects.accounts.loan.LoanWithAssociations
import com.mifos.objects.client.Charges
import com.mifos.utils.Constants
import com.mifos.utils.DateHelper
import com.mifos.utils.FragmentConstants
import java.util.*
import javax.inject.Inject
/**
* Created by ishankhanna on 09/05/14.
*/
class LoanAccountSummaryFragment : ProgressableFragment(), LoanAccountSummaryMvpView {
var loanAccountNumber = 0
@kotlin.jvm.JvmField
@BindView(R.id.view_status_indicator)
var view_status_indicator: View? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_clientName)
var tv_clientName: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.quickContactBadge_client)
var quickContactBadge: QuickContactBadge? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_product_short_name)
var tv_loan_product_short_name: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loanAccountNumber)
var tv_loanAccountNumber: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_amount_disbursed)
var tv_amount_disbursed: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_disbursement_date)
var tv_disbursement_date: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_in_arrears)
var tv_in_arrears: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_officer)
var tv_loan_officer: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_principal)
var tv_principal: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_principal_due)
var tv_loan_principal_due: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_principal_paid)
var tv_loan_principal_paid: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_interest)
var tv_interest: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_interest_due)
var tv_loan_interest_due: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_interest_paid)
var tv_loan_interest_paid: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_fees)
var tv_fees: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_fees_due)
var tv_loan_fees_due: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_fees_paid)
var tv_loan_fees_paid: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_penalty)
var tv_penalty: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_penalty_due)
var tv_loan_penalty_due: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_loan_penalty_paid)
var tv_loan_penalty_paid: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_total)
var tv_total: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_total_due)
var tv_total_due: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_total_paid)
var tv_total_paid: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.bt_processLoanTransaction)
var bt_processLoanTransaction: Button? = null
@kotlin.jvm.JvmField
@Inject
var mLoanAccountSummaryPresenter: LoanAccountSummaryPresenter? = null
var chargesList: MutableList<Charges> = ArrayList()
private lateinit var rootView: View
// Action Identifier in the onProcessTransactionClicked Method
private var processLoanTransactionAction = -1
private var parentFragment = true
private var mListener: OnFragmentInteractionListener? = null
private var clientLoanWithAssociations: LoanWithAssociations? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
loanAccountNumber = requireArguments().getInt(Constants.LOAN_ACCOUNT_NUMBER)
parentFragment = requireArguments().getBoolean(Constants.IS_A_PARENT_FRAGMENT)
}
//Necessary Call to add and update the Menu in a Fragment
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_loan_account_summary, container, false)
//Injecting Presenter
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
ButterKnife.bind(this, rootView)
mLoanAccountSummaryPresenter!!.attachView(this)
inflateLoanAccountSummary()
return rootView
}
private fun inflateLoanAccountSummary() {
showProgress(true)
setToolbarTitle(resources.getString(R.string.loanAccountSummary))
//TODO Implement cases to enable/disable repayment button
bt_processLoanTransaction!!.isEnabled = false
mLoanAccountSummaryPresenter!!.loadLoanById(loanAccountNumber)
}
@OnClick(R.id.bt_processLoanTransaction)
fun onProcessTransactionClicked() {
if (processLoanTransactionAction == TRANSACTION_REPAYMENT) {
mListener!!.makeRepayment(clientLoanWithAssociations)
} else if (processLoanTransactionAction == ACTION_APPROVE_LOAN) {
approveLoan()
} else if (processLoanTransactionAction == ACTION_DISBURSE_LOAN) {
disburseLoan()
} else {
Log.i(requireActivity().localClassName, "TRANSACTION ACTION NOT SET")
}
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
mListener = try {
activity as OnFragmentInteractionListener
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + " must implement " +
"OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
if (!parentFragment) {
requireActivity().finish()
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.clear()
menu.add(Menu.NONE, MENU_ITEM_DATA_TABLES, Menu.NONE, Constants.DATA_TABLE_LOAN_NAME)
menu.add(Menu.NONE, MENU_ITEM_LOAN_TRANSACTIONS, Menu.NONE, resources.getString(R.string.transactions))
menu.add(Menu.NONE, MENU_ITEM_REPAYMENT_SCHEDULE, Menu.NONE, resources.getString(R.string.loan_repayment_schedule))
menu.add(Menu.NONE, MENU_ITEM_DOCUMENTS, Menu.NONE, resources.getString(R.string.documents))
menu.add(Menu.NONE, MENU_ITEM_CHARGES, Menu.NONE, resources.getString(R.string.charges))
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
MENU_ITEM_REPAYMENT_SCHEDULE -> mListener!!.loadRepaymentSchedule(loanAccountNumber)
MENU_ITEM_LOAN_TRANSACTIONS -> mListener!!.loadLoanTransactions(loanAccountNumber)
MENU_ITEM_DOCUMENTS -> loadDocuments()
MENU_ITEM_CHARGES -> loadloanCharges()
MENU_ITEM_DATA_TABLES -> loadLoanDataTables()
else -> {
}
}
return super.onOptionsItemSelected(item)
}
fun inflateLoanSummary(loanWithAssociations: LoanWithAssociations) {
tv_amount_disbursed!!.text = loanWithAssociations.summary
.principalDisbursed.toString()
try {
tv_disbursement_date!!.text = DateHelper.getDateAsString(loanWithAssociations
.timeline.actualDisbursementDate)
} catch (exception: IndexOutOfBoundsException) {
Toast.makeText(activity, resources.getString(R.string.loan_rejected_message), Toast.LENGTH_SHORT).show()
}
tv_in_arrears!!.text = loanWithAssociations.summary.totalOverdue.toString()
tv_principal!!.text = loanWithAssociations.summary
.principalDisbursed.toString()
tv_loan_principal_due!!.text = loanWithAssociations.summary
.principalOutstanding.toString()
tv_loan_principal_paid!!.text = loanWithAssociations.summary
.principalPaid.toString()
tv_interest!!.text = loanWithAssociations.summary.interestCharged.toString()
tv_loan_interest_due!!.text = loanWithAssociations.summary
.interestOutstanding.toString()
tv_loan_interest_paid!!.text = loanWithAssociations.summary
.interestPaid.toString()
tv_fees!!.text = loanWithAssociations.summary.feeChargesCharged.toString()
tv_loan_fees_due!!.text = loanWithAssociations.summary
.feeChargesOutstanding.toString()
tv_loan_fees_paid!!.text = loanWithAssociations.summary
.feeChargesPaid.toString()
tv_penalty!!.text = loanWithAssociations.summary
.penaltyChargesCharged.toString()
tv_loan_penalty_due!!.text = loanWithAssociations.summary
.penaltyChargesOutstanding.toString()
tv_loan_penalty_paid!!.text = loanWithAssociations.summary
.penaltyChargesPaid.toString()
tv_total!!.text = loanWithAssociations.summary
.totalExpectedRepayment.toString()
tv_total_due!!.text = loanWithAssociations.summary.totalOutstanding.toString()
tv_total_paid!!.text = loanWithAssociations.summary.totalRepayment.toString()
}
fun loadDocuments() {
val documentListFragment = DocumentListFragment.newInstance(Constants.ENTITY_TYPE_LOANS, loanAccountNumber)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_LOAN_ACCOUNT_SUMMARY)
fragmentTransaction.replace(R.id.container, documentListFragment)
fragmentTransaction.commit()
}
fun loadloanCharges() {
val loanChargeFragment: LoanChargeFragment = LoanChargeFragment.Companion.newInstance(loanAccountNumber,
chargesList)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_LOAN_ACCOUNT_SUMMARY)
fragmentTransaction.replace(R.id.container, loanChargeFragment)
fragmentTransaction.commit()
}
fun approveLoan() {
val loanAccountApproval: LoanAccountApproval = LoanAccountApproval.Companion.newInstance(loanAccountNumber, clientLoanWithAssociations)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_LOAN_ACCOUNT_SUMMARY)
fragmentTransaction.replace(R.id.container, loanAccountApproval)
fragmentTransaction.commit()
}
fun disburseLoan() {
val loanAccountDisbursement: LoanAccountDisbursementFragment = LoanAccountDisbursementFragment.Companion.newInstance(loanAccountNumber)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_LOAN_ACCOUNT_SUMMARY)
fragmentTransaction.replace(R.id.container, loanAccountDisbursement)
fragmentTransaction.commit()
}
fun loadLoanDataTables() {
val loanAccountFragment = DataTableFragment.newInstance(Constants.DATA_TABLE_NAME_LOANS, loanAccountNumber)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_LOAN_ACCOUNT_SUMMARY)
fragmentTransaction.replace(R.id.container, loanAccountFragment)
fragmentTransaction.commit()
}
override fun showLoanById(loanWithAssociations: LoanWithAssociations) {
/* Activity is null - Fragment has been detached; no need to do anything. */
if (activity == null) return
clientLoanWithAssociations = loanWithAssociations
tv_clientName!!.text = loanWithAssociations.clientName
tv_loan_product_short_name!!.text = loanWithAssociations.loanProductName
tv_loanAccountNumber!!.text = "#" + loanWithAssociations.accountNo
tv_loan_officer!!.text = loanWithAssociations.loanOfficerName
//TODO Implement QuickContactBadge
//quickContactBadge.setImageToDefault();
bt_processLoanTransaction!!.isEnabled = true
if (loanWithAssociations.status.active) {
inflateLoanSummary(loanWithAssociations)
// if Loan is already active
// the Transaction Would be Make Repayment
view_status_indicator!!.setBackgroundColor(
ContextCompat.getColor(requireActivity(), R.color.light_green))
bt_processLoanTransaction!!.text = "Make Repayment"
processLoanTransactionAction = TRANSACTION_REPAYMENT
} else if (loanWithAssociations.status.pendingApproval) {
// if Loan is Pending for Approval
// the Action would be Approve Loan
view_status_indicator!!.setBackgroundColor(
ContextCompat.getColor(requireActivity(), R.color.light_yellow))
bt_processLoanTransaction!!.text = "Approve Loan"
processLoanTransactionAction = ACTION_APPROVE_LOAN
} else if (loanWithAssociations.status.waitingForDisbursal) {
// if Loan is Waiting for Disbursal
// the Action would be Disburse Loan
view_status_indicator!!.setBackgroundColor(
ContextCompat.getColor(requireActivity(), R.color.blue))
bt_processLoanTransaction!!.text = "Disburse Loan"
processLoanTransactionAction = ACTION_DISBURSE_LOAN
} else if (loanWithAssociations.status.closedObligationsMet) {
inflateLoanSummary(loanWithAssociations)
// if Loan is Closed after the obligations are met
// the make payment will be disabled so that no more payment can be collected
view_status_indicator!!.setBackgroundColor(
ContextCompat.getColor(requireActivity(), R.color.black))
bt_processLoanTransaction!!.isEnabled = false
bt_processLoanTransaction!!.text = "Make Repayment"
} else {
inflateLoanSummary(loanWithAssociations)
view_status_indicator!!.setBackgroundColor(
ContextCompat.getColor(requireActivity(), R.color.black))
bt_processLoanTransaction!!.isEnabled = false
bt_processLoanTransaction!!.text = "Loan Closed"
}
}
override fun showFetchingError(s: String?) {
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show()
}
override fun showProgressbar(b: Boolean) {
showProgress(b)
}
override fun onDestroyView() {
super.onDestroyView()
mLoanAccountSummaryPresenter!!.detachView()
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putParcelable("LoanWithAssociation", clientLoanWithAssociations)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (savedInstanceState != null) {
// Restore last state for checked position.
clientLoanWithAssociations = savedInstanceState.getParcelable("LoanWithAssociation")
}
}
interface OnFragmentInteractionListener {
fun makeRepayment(loan: LoanWithAssociations?)
fun loadRepaymentSchedule(loanId: Int)
fun loadLoanTransactions(loanId: Int)
}
companion object {
const val MENU_ITEM_DATA_TABLES = 1001
const val MENU_ITEM_REPAYMENT_SCHEDULE = 1002
const val MENU_ITEM_LOAN_TRANSACTIONS = 1003
const val MENU_ITEM_DOCUMENTS = 1004
const val MENU_ITEM_CHARGES = 1005
/*
Set of Actions and Transactions that can be performed depending on the status of the Loan
Actions are performed to change the status of the loan
Transactions are performed to do repayments
*/
private const val ACTION_NOT_SET = -1
private const val ACTION_APPROVE_LOAN = 0
private const val ACTION_DISBURSE_LOAN = 1
private const val TRANSACTION_REPAYMENT = 2
@kotlin.jvm.JvmStatic
fun newInstance(loanAccountNumber: Int,
parentFragment: Boolean): LoanAccountSummaryFragment {
val fragment = LoanAccountSummaryFragment()
val args = Bundle()
args.putInt(Constants.LOAN_ACCOUNT_NUMBER, loanAccountNumber)
args.putBoolean(Constants.IS_A_PARENT_FRAGMENT, parentFragment)
fragment.arguments = args
return fragment
}
}
}
|
mpl-2.0
|
2d355bab18b0909134799b89c0c7d6ec
| 40.761682 | 143 | 0.695574 | 4.700947 | false | false | false | false |
cfig/Nexus_boot_image_editor
|
bbootimg/src/main/kotlin/bootimg/Signer.kt
|
1
|
4556
|
// Copyright 2021 [email protected]
//
// 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 cfig.bootimg
import avb.AVBInfo
import avb.alg.Algorithms
import cfig.Avb
import cfig.Avb.Companion.getJsonFileName
import cfig.helper.Helper
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.slf4j.LoggerFactory
import java.io.File
import cfig.EnvironmentVerifier
class Signer {
companion object {
private val log = LoggerFactory.getLogger(Signer::class.java)
fun signAVB(output: String, imageSize: Long, avbtool: String) {
log.info("Adding hash_footer with verified-boot 2.0 style")
val ai = ObjectMapper().readValue(File(getJsonFileName(output)), AVBInfo::class.java)
val alg = Algorithms.get(ai.header!!.algorithm_type)
val bootDesc = ai.auxBlob!!.hashDescriptors[0]
val newAvbInfo = ObjectMapper().readValue(File(getJsonFileName(output)), AVBInfo::class.java)
//our signer
File("$output.clear").copyTo(File("$output.signed"), overwrite = true)
Avb().addHashFooter("$output.signed",
imageSize,
partition_name = bootDesc.partition_name,
newAvbInfo = newAvbInfo)
//original signer
val cmdPrefix = if (EnvironmentVerifier().isWindows) "python " else ""
CommandLine.parse("$cmdPrefix$avbtool add_hash_footer").apply {
addArguments("--image ${output}.signed2")
addArguments("--flags ${ai.header!!.flags}")
addArguments("--partition_size ${imageSize}")
addArguments("--salt ${Helper.toHexString(bootDesc.salt)}")
addArguments("--partition_name ${bootDesc.partition_name}")
addArguments("--hash_algorithm ${bootDesc.hash_algorithm}")
addArguments("--algorithm ${alg!!.name}")
addArguments("--rollback_index ${ai.header!!.rollback_index}")
if (alg.defaultKey.isNotBlank()) {
addArguments("--key ${alg.defaultKey}")
}
newAvbInfo.auxBlob?.let { newAuxblob ->
newAuxblob.propertyDescriptors.forEach { newProp ->
addArguments(arrayOf("--prop", "${newProp.key}:${newProp.value}"))
}
}
addArgument("--internal_release_string")
addArgument(ai.header!!.release_string, false)
log.info(this.toString())
File("$output.clear").copyTo(File("$output.signed2"), overwrite = true)
DefaultExecutor().execute(this)
}
Common.assertFileEquals("$output.signed", "$output.signed2")
//TODO: decide what to verify
//Parser.verifyAVBIntegrity(cfg.info.output + ".signed", avbtool)
//Parser.verifyAVBIntegrity(cfg.info.output + ".signed2", avbtool)
}
fun signVB1(src: String, tgt: String) {
val bootSigner = Helper.prop("bootSigner")
log.info("Signing with verified-boot 1.0 style")
val sig = Common.VeritySignature(
verity_pk8 = Helper.prop("verity_pk8"),
verity_pem = Helper.prop("verity_pem"),
jarPath = Helper.prop("bootSigner")
)
val bootSignCmd = "java -jar $bootSigner " +
"${sig.path} $src " +
"${sig.verity_pk8} ${sig.verity_pem} " +
"$tgt"
log.info(bootSignCmd)
DefaultExecutor().execute(CommandLine.parse(bootSignCmd))
}
fun mapToJson(m: LinkedHashMap<*, *>): String {
val sb = StringBuilder()
m.forEach { k, v ->
if (sb.isNotEmpty()) sb.append(", ")
sb.append("\"$k\": \"$v\"")
}
return "{ $sb }"
}
}
}
|
apache-2.0
|
53e2ee1ce212102af96a10eaa92d05b2
| 43.23301 | 105 | 0.587577 | 4.537849 | false | false | false | false |
misaochan/apps-android-commons
|
app/src/main/java/fr/free/nrw/commons/explore/paging/FooterAdapter.kt
|
8
|
2081
|
package fr.free.nrw.commons.explore.paging
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import fr.free.nrw.commons.R
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.list_item_load_more.*
class FooterAdapter(private val onRefreshClicked: () -> Unit) :
ListAdapter<FooterItem, FooterViewHolder>(object :
DiffUtil.ItemCallback<FooterItem>() {
override fun areItemsTheSame(oldItem: FooterItem, newItem: FooterItem) = oldItem == newItem
override fun areContentsTheSame(oldItem: FooterItem, newItem: FooterItem) =
oldItem == newItem
}) {
override fun getItemViewType(position: Int): Int {
return getItem(position).ordinal
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
when (FooterItem.values()[viewType]) {
FooterItem.LoadingItem -> LoadingViewHolder(
parent.inflate(R.layout.list_item_progress)
)
FooterItem.RefreshItem -> RefreshViewHolder(
parent.inflate(R.layout.list_item_load_more),
onRefreshClicked
)
}
override fun onBindViewHolder(holder: FooterViewHolder, position: Int) {}
}
open class FooterViewHolder(override val containerView: View) :
RecyclerView.ViewHolder(containerView),
LayoutContainer
class LoadingViewHolder(containerView: View) : FooterViewHolder(containerView)
class RefreshViewHolder(containerView: View, onRefreshClicked: () -> Unit) :
FooterViewHolder(containerView) {
init {
listItemLoadMoreButton.setOnClickListener { onRefreshClicked() }
}
}
enum class FooterItem { LoadingItem, RefreshItem }
fun ViewGroup.inflate(@LayoutRes layoutId: Int, attachToRoot: Boolean = false): View =
LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
|
apache-2.0
|
1c71a56a9615a144990860cca908a5ce
| 36.160714 | 99 | 0.730899 | 4.772936 | false | false | false | false |
sys1yagi/mastodon4j
|
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/Status.kt
|
1
|
2055
|
package com.sys1yagi.mastodon4j.api.entity
import com.google.gson.annotations.SerializedName
/**
* see more https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#status
*/
class Status(
@SerializedName("id") val id: Long = 0L,
@SerializedName("uri") val uri: String = "",
@SerializedName("url") val url: String = "",
@SerializedName("account") val account: Account? = null,
@SerializedName("in_reply_to_id") val inReplyToId: Long? = null,
@SerializedName("in_reply_to_account_id") val inReplyToAccountId: Long? = null,
@SerializedName("reblog") val reblog: Status? = null,
@SerializedName("content") val content: String = "",
@SerializedName("created_at") val createdAt: String = "",
@SerializedName("emojis") val emojis: List<Emoji> = emptyList(),
@SerializedName("replies_count") val repliesCount: Int = 0,
@SerializedName("reblogs_count") val reblogsCount: Int = 0,
@SerializedName("favourites_count") val favouritesCount: Int = 0,
@SerializedName("reblogged") val isReblogged: Boolean = false,
@SerializedName("favourited") val isFavourited: Boolean = false,
@SerializedName("sensitive") val isSensitive: Boolean = false,
@SerializedName("spoiler_text") val spoilerText: String = "",
@SerializedName("visibility") val visibility: String = Visibility.Public.value,
@SerializedName("media_attachments") val mediaAttachments: List<Attachment> = emptyList(),
@SerializedName("mentions") val mentions: List<Mention> = emptyList(),
@SerializedName("tags") val tags: List<Tag> = emptyList(),
@SerializedName("application") val application: Application? = null,
@SerializedName("language") val language: String? = null,
@SerializedName("pinned") val pinned: Boolean? = null) {
enum class Visibility(val value: String) {
Public("public"),
Unlisted("unlisted"),
Private("private"),
Direct("direct")
}
}
|
mit
|
015da777423be20d21b94757e8376085
| 51.692308 | 98 | 0.659367 | 4.326316 | false | false | false | false |
cout970/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/OilHeater.kt
|
1
|
2316
|
package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.MagneticraftApi
import com.cout970.magneticraft.api.internal.registries.machines.oilheater.OilHeaterRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.liquid.ILiquidStack
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@ZenClass("mods.magneticraft.OilHeater")
@ZenRegister
object OilHeater {
@ZenMethod
@JvmStatic
fun addRecipe(input: ILiquidStack, output: ILiquidStack, duration: Float, minTemperature: Float) {
CraftTweakerPlugin.delayExecution {
val inFluid = input.toStack() ?: run {
ctLogError("[OilHeater] Invalid input value: $input")
return@delayExecution
}
val outFluid = output.toStack() ?: run {
ctLogError("[OilHeater] Invalid output value: $output")
return@delayExecution
}
if (minTemperature <= 0) {
ctLogError("[OilHeater] Invalid minTemperature value: $minTemperature")
return@delayExecution
}
if (duration <= 0) {
ctLogError("[OilHeater] Invalid duration value: $duration")
return@delayExecution
}
val recipe = OilHeaterRecipeManager.createRecipe(inFluid, outFluid, duration, minTemperature)
applyAction("Adding $recipe") {
OilHeaterRecipeManager.registerRecipe(recipe)
}
}
}
@ZenMethod
@JvmStatic
fun removeRecipe(input: ILiquidStack) {
CraftTweakerPlugin.delayExecution {
val a = input.toStack()
if (a == null) {
ctLogError("[OilHeater] Invalid input stack: $input")
return@delayExecution
}
val man = MagneticraftApi.getOilHeaterRecipeManager()
val recipe = man.findRecipe(a)
if (recipe != null) {
applyAction("Removing $recipe") {
man.removeRecipe(recipe)
}
} else {
ctLogError("[OilHeater] Error removing recipe: Unable to find recipe with input = $input")
}
}
}
}
|
gpl-2.0
|
e1acbdacad41d4b87b7e7ce51d19df8a
| 33.073529 | 106 | 0.60924 | 4.795031 | false | false | false | false |
rcgroot/open-gpstracker-ng
|
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/graphs/widgets/LineGraph.kt
|
1
|
13654
|
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: René de Groot
** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.graphs.widgets
import android.content.Context
import android.graphics.*
import androidx.annotation.Size
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import nl.sogeti.android.gpstracker.ng.base.common.ofMainThread
import nl.sogeti.android.gpstracker.ng.base.common.onMainThread
import nl.sogeti.android.gpstracker.ng.features.graphs.dataproviders.GraphDataCalculator
import nl.sogeti.android.gpstracker.ng.features.graphs.dataproviders.condense
import nl.sogeti.android.opengpstrack.ng.features.R
class LineGraph : View {
@Size(multiple = 2)
var data: List<GraphPoint> = listOf()
set(value) {
field = value
fillPointsCache(data)
}
var xUnit = ""
set(value) {
field = value
invalidate()
}
var yUnit = ""
set(value) {
field = value
invalidate()
}
var description: GraphDataCalculator = GraphDataCalculator.DefaultGraphValueDescriptor
set(value) {
field = value
invalidate()
}
var topGradientColor: Int = Color.DKGRAY
set(value) {
field = value
createLineShader()
invalidate()
}
var bottomGradientColor = Color.TRANSPARENT
set(value) {
field = value
createLineShader()
invalidate()
}
var lineColor
set(value) {
linePaint.color = value
axisPaint.color = value
gridPaint.color = value
textPaint.color = value
valueTextPaint.color = value
invalidate()
}
get() = linePaint.color
private var cachedPoints: List<PointF>? = null
private val axisPaint = Paint()
private val gridPaint = Paint()
private val textPaint = Paint()
private val valueTextPaint = Paint()
private val linePaint = Paint()
private val belowLinePaint = Paint()
private val linePath = Path()
private val drawLinePath = Path()
private var h = 0f
private var w = 0f
private var sectionHeight = 0f
private var sectionWidth = 0f
private var unitTextSideMargin = 0f
private val graphSideMargin = dp2px(8)
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
if (attrs != null) appyStyle(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
if (attrs != null) appyStyle(attrs)
}
init {
axisPaint.color = Color.WHITE
gridPaint.color = Color.WHITE
gridPaint.style = Paint.Style.STROKE
val dash = dp2px(2)
gridPaint.pathEffect = DashPathEffect(floatArrayOf(dash, dash), dash)
textPaint.textSize = dp2px(18)
textPaint.color = Color.WHITE
textPaint.isAntiAlias = true
valueTextPaint.textSize = dp2px(12)
valueTextPaint.color = Color.WHITE
valueTextPaint.isAntiAlias = true
linePaint.color = Color.BLACK
linePaint.isAntiAlias = true
linePaint.style = Paint.Style.STROKE
linePaint.setShadowLayer(3f, -2f, 1f, Color.BLACK)
belowLinePaint.isAntiAlias = true
unitTextSideMargin = textPaint.textHeight() + valueTextPaint.textHeight()
if (isInEditMode) {
xUnit = "timeSpan"
yUnit = "speed"
data = listOf(GraphPoint(1f, 12F), GraphPoint(2F, 24F), GraphPoint(3F, 36F), GraphPoint(4F, 23F), GraphPoint(5F, 65F), GraphPoint(6F, 10F),
GraphPoint(7F, 80F), GraphPoint(8F, 65F), GraphPoint(9F, 13F))
description = GraphDataCalculator.DefaultGraphValueDescriptor
}
}
fun appyStyle(attrs: AttributeSet) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.LineGraph, 0, 0)
try {
xUnit = ta.getString(R.styleable.LineGraph_x_unit) ?: xUnit
yUnit = ta.getString(R.styleable.LineGraph_y_unit) ?: yUnit
topGradientColor = ta.getColor(R.styleable.LineGraph_top_gradient, topGradientColor)
bottomGradientColor = ta.getColor(R.styleable.LineGraph_bottom_gradient, bottomGradientColor)
lineColor = ta.getColor(R.styleable.LineGraph_line_color, lineColor)
} finally {
ta.recycle()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
this.w = w.toFloat()
this.h = h.toFloat()
this.sectionHeight = (h - unitTextSideMargin - graphSideMargin) / 4f
this.sectionWidth = (w - unitTextSideMargin - graphSideMargin) / 4f
cachedPoints = null
createLineShader()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (cachedPoints == null) {
fillPointsCache(data)
}
drawGrid(canvas)
drawGraphLine(canvas)
drawAxis(canvas)
drawText(canvas)
}
private fun createLineShader() {
belowLinePaint.shader = LinearGradient(0f, 0f, 0f, h, topGradientColor, bottomGradientColor, Shader.TileMode.CLAMP)
}
private fun drawGraphLine(canvas: Canvas) {
// Gradient below
linePath.reset()
linePath.moveTo(unitTextSideMargin, h - unitTextSideMargin)
cachedPoints?.forEach { linePath.lineTo(it.x, it.y) }
linePath.lineTo(w - graphSideMargin - 1, h - unitTextSideMargin)
linePath.close()
canvas.drawPath(linePath, belowLinePaint)
// Top line
linePath.rewind()
linePath.moveTo(unitTextSideMargin, h - unitTextSideMargin)
cachedPoints?.forEach { linePath.lineTo(it.x, it.y) }
linePath.lineTo(w - graphSideMargin, h - unitTextSideMargin)
canvas.drawPath(linePath, linePaint)
}
private fun drawAxis(canvas: Canvas) {
// X-axis
canvas.drawLine(unitTextSideMargin, h - unitTextSideMargin, w - graphSideMargin, h - unitTextSideMargin, axisPaint)
// Y-axis
canvas.drawLine(unitTextSideMargin, h - unitTextSideMargin, unitTextSideMargin, graphSideMargin, axisPaint)
}
private fun drawGrid(canvas: Canvas) {
// Dotted X-axes
drawLine(canvas, unitTextSideMargin, h - unitTextSideMargin - 1 * sectionHeight, w - graphSideMargin, h - unitTextSideMargin - 1 * sectionHeight, gridPaint)
drawLine(canvas, unitTextSideMargin, h - unitTextSideMargin - 2 * sectionHeight, w - graphSideMargin, h - unitTextSideMargin - 2 * sectionHeight, gridPaint)
drawLine(canvas, unitTextSideMargin, h - unitTextSideMargin - 3 * sectionHeight, w - graphSideMargin, h - unitTextSideMargin - 3 * sectionHeight, gridPaint)
drawLine(canvas, unitTextSideMargin, h - unitTextSideMargin - 4 * sectionHeight, w - graphSideMargin, h - unitTextSideMargin - 4 * sectionHeight, gridPaint)
// Dotted Y-axes
drawLine(canvas, unitTextSideMargin + 1 * sectionWidth, h - unitTextSideMargin, unitTextSideMargin + 1 * sectionWidth, graphSideMargin, gridPaint)
drawLine(canvas, unitTextSideMargin + 2 * sectionWidth, h - unitTextSideMargin, unitTextSideMargin + 2 * sectionWidth, graphSideMargin, gridPaint)
drawLine(canvas, unitTextSideMargin + 3 * sectionWidth, h - unitTextSideMargin, unitTextSideMargin + 3 * sectionWidth, graphSideMargin, gridPaint)
drawLine(canvas, unitTextSideMargin + 4 * sectionWidth, h - unitTextSideMargin, unitTextSideMargin + 4 * sectionWidth, graphSideMargin, gridPaint)
}
private fun drawText(canvas: Canvas) {
val x1 = description.describeXvalue(context, minX)
val x2 = description.describeXvalue(context, (minX + maxX) / 2)
val x3 = description.describeXvalue(context, maxX)
val y1 = description.describeYvalue(context, minY)
val y2 = description.describeYvalue(context, (minY + maxY) / 2)
val y3 = description.describeYvalue(context, maxY)
canvas.rotate(-90f)
// Y unit
val verticalTextWidth = textPaint.measureText(yUnit)
canvas.drawText(yUnit, -verticalTextWidth / 2 - h / 2, -textPaint.fontMetrics.top, textPaint)
// Y values
canvas.drawText(y1, -graphSideMargin - 4 * sectionHeight, unitTextSideMargin - valueTextPaint.fontMetrics.descent, valueTextPaint)
val middleTextHeight = valueTextPaint.measureText(y2)
canvas.drawText(y2, -graphSideMargin - 2 * sectionHeight - middleTextHeight / 2, unitTextSideMargin - valueTextPaint.fontMetrics.descent, valueTextPaint)
val endTextHeight = valueTextPaint.measureText(y3)
canvas.drawText(y3, -graphSideMargin - endTextHeight, unitTextSideMargin - valueTextPaint.fontMetrics.descent, valueTextPaint)
canvas.rotate(90f)
// X unit
val horizontalTextWidth = textPaint.measureText(yUnit)
canvas.drawText(xUnit, w / 2 - horizontalTextWidth / 2, h - textPaint.fontMetrics.bottom, textPaint)
// X values
canvas.drawText(x1, unitTextSideMargin, h - textPaint.textHeight(), valueTextPaint)
val middleTextWidth = valueTextPaint.measureText(x2)
canvas.drawText(x2, unitTextSideMargin + 2 * sectionWidth - middleTextWidth / 2f, h - textPaint.textHeight(), valueTextPaint)
val endTextWidth = valueTextPaint.measureText(x3)
canvas.drawText(x3, unitTextSideMargin + 4 * sectionWidth - endTextWidth, h - textPaint.textHeight(), valueTextPaint)
}
private var minY: Float = 0f
private var maxY: Float = 1f
private var minX: Float = 0f
private var maxX: Float = 1f
private fun fillPointsCache(data: List<GraphPoint>) {
cachedPoints = listOf()
ofMainThread {
minX = data.firstOrNull()?.x ?: 0f
maxX = data.lastOrNull()?.x ?: 100f
val bucketSize = (maxX - minX) / (width / 3F)
val condensedData = data.condens(bucketSize)
minY = description.prettyMinYValue(context, condensedData.minBy { it.y }?.y ?: 0f)
maxY = description.prettyMaxYValue(context, condensedData.maxBy { it.y }?.y ?: 100f)
fun convertDataToPoint(point: GraphPoint): PointF {
val y = (point.y - minY) / (maxY - minY) * (sectionHeight * 4)
val x = (point.x - minX) / (maxX - minX) * (sectionWidth * 4)
return PointF(x + unitTextSideMargin, h - unitTextSideMargin - y)
}
val newDataPoints = condensedData.map { convertDataToPoint(it) }
onMainThread {
cachedPoints = newDataPoints
invalidate()
}
}
}
private fun List<GraphPoint>.condens(bucketSize: Float): List<GraphPoint> {
fun Collection<GraphPoint>.average(): GraphPoint {
val averageY = this.sumByDouble { it.y.toDouble() } / this.size
val averageX = this.sumByDouble { it.x.toDouble() } / this.size
return GraphPoint(averageX.toFloat(), averageY.toFloat())
}
fun GraphPoint.bucket(): Int = ((this.x - minX) / bucketSize).toInt()
return this.condense({ i, j -> i.bucket() == j.bucket() }, { it.average() })
}
private fun drawLine(canvas: Canvas, x: Float, y: Float, x2: Float, y2: Float, paint: Paint) {
drawLinePath.rewind()
drawLinePath.moveTo(x, y)
drawLinePath.lineTo(x2, y2)
canvas.drawPath(drawLinePath, paint)
}
private fun Paint.textHeight() = this.fontMetrics.descent - this.fontMetrics.ascent + this.fontMetrics.leading
private fun dp2px(dp: Int): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics)
}
private fun drawOutline(canvas: Canvas) {
canvas.drawLines(floatArrayOf(0f, 0f, w, h,
w, 0f, 0f, h,
0f, 0f, w, 0f,
0f, 0f, 0f, h,
w - 1, h - 1, 0f, h - 1,
w - 1, h - 1, w - 1, 0f), axisPaint)
}
}
|
gpl-3.0
|
c6255f1af53aa065d5e555d79e4edca2
| 42.619808 | 164 | 0.638394 | 4.139782 | false | false | false | false |
werelord/nullpod
|
nullpodApp/src/main/kotlin/com/cyrix/nullpod/ui/TrackItemAdapter.kt
|
1
|
3177
|
/**
* TrackItemAdapter
*
* Copyright 2017 Joel Braun
*
* This file is part of nullPod.
*
* nullPod 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.
*
* nullPod 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 nullPod. If not, see <http://www.gnu.org/licenses/>.
*/
package com.cyrix.nullpod.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cyrix.nullpod.data.FeedImageCache
import com.cyrix.nullpod.data.PodcastTrack
import com.cyrix.util.CxLogger
import com.cyrix.util.debug
import com.cyrix.util.function
import com.cyrix.util.warn
import com.woxthebox.draglistview.DragItemAdapter
import kotlinx.android.synthetic.main.draglist_item.view.*
class TrackItemAdapter(val trackList: List<PodcastTrack>, val layoutId: Int, val grabHandleId: Int,
val dragOnLongPress: Boolean, val bmpCache: FeedImageCache?)
: DragItemAdapter<PodcastTrack, TrackItemAdapter.ViewHolder>() {
private val log = CxLogger<TrackItemAdapter>()
init {
log.function()
super.setHasStableIds(true)
super.setItemList(trackList)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
//log.function()
val view: View = LayoutInflater.from(parent?.context).inflate(layoutId, parent, false)
// todo: set swipe direction stuff..
return ViewHolder(view)
}
override fun getItemId(position: Int): Long {
// stable id for each VH item
return trackList[position].id
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
//log.function()
super.onBindViewHolder(holder, position)
holder?.itemView?.item_layout?.track_text?.text = itemList[position].title
holder?.itemView?.tag = itemList[position]
//log.debug { smallBmpCache.values }
val ivFeedImage = holder?.itemView?.feed_image
if (ivFeedImage != null) {
if (bmpCache?.getBmp(itemList[position], FeedImageCache.ImageDP.FEED_IMAGE_40_DP) != null) {
ivFeedImage.setImageBitmap(bmpCache.getBmp(itemList[position], FeedImageCache.ImageDP.FEED_IMAGE_40_DP))
} else {
log.warn { "Unable to find bitmap for given file (will use default image)" }
}
}
holder?.itemView?.tvUndo?.setOnClickListener {
log.debug { "onclick hit" }
// todo: cancel removal from list
// todo: reslide back in
}
}
inner class ViewHolder(itemView: View) : DragItemAdapter.ViewHolder(itemView, grabHandleId, dragOnLongPress)
// no members; initial constructor parameters are only ones needed
}
|
gpl-3.0
|
6536eca0ede5c82099239ca8a37752f2
| 33.532609 | 120 | 0.690903 | 4.253012 | false | false | false | false |
vondear/RxTools
|
RxUI/src/main/java/com/tamsiree/rxui/view/progress/TOrangeJuice.kt
|
1
|
14923
|
package com.tamsiree.rxui.view.progress
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.View
import com.tamsiree.rxkit.RxImageTool.dp2px
import com.tamsiree.rxui.R
import java.util.*
class TOrangeJuice(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
private val mLeftMargin: Int
private val mRightMargin: Int
/**
* 获取中等振幅
*/
/**
* 设置中等振幅
*
* @param amplitude
*/
// 中等振幅大小
var middleAmplitude = MIDDLE_AMPLITUDE
/**
* 获取振幅差
*/
/**
* 设置振幅差
*
* @param disparity
*/
// 振幅差
var mplitudeDisparity = AMPLITUDE_DISPARITY
// 叶子飘动一个周期所花的时间
private var mLeafFloatTime = LEAF_FLOAT_TIME
// 叶子旋转一周需要的时间
private var mLeafRotateTime = LEAF_ROTATE_TIME
private val mResources: Resources
private var mLeafBitmap: Bitmap? = null
private var mLeafWidth = 0
private var mLeafHeight = 0
private var mOuterBitmap: Bitmap? = null
private var mOuterSrcRect: Rect? = null
private var mOuterDestRect: Rect? = null
private var mOuterWidth = 0
private var mOuterHeight = 0
private var mTotalWidth = 0
private var mTotalHeight = 0
private var mBitmapPaint: Paint? = null
private var mWhitePaint: Paint? = null
private var mOrangePaint: Paint? = null
private var mWhiteRectF: RectF? = null
private var mOrangeRectF: RectF? = null
private var mArcRectF: RectF? = null
// 当前进度
private var mProgress = 0
// 所绘制的进度条部分的宽度
private var mProgressWidth = 0
// 当前所在的绘制的进度条的位置
private var mCurrentProgressPosition = 0
// 弧形的半径
private var mArcRadius = 0
// arc的右上角的x坐标,也是矩形x坐标的起始点
private var mArcRightLocation = 0
// 用于产生叶子信息
private val mLeafFactory: LeafFactory
// 产生出的叶子信息
private val mLeafInfos: List<Leaf>
// 用于控制随机增加的时间不抱团
private var mAddTime = 0
private fun initPaint() {
mBitmapPaint = Paint()
mBitmapPaint!!.isAntiAlias = true
mBitmapPaint!!.isDither = true
mBitmapPaint!!.isFilterBitmap = true
mWhitePaint = Paint()
mWhitePaint!!.isAntiAlias = true
mWhitePaint!!.color = WHITE_COLOR
mOrangePaint = Paint()
mOrangePaint!!.isAntiAlias = true
mOrangePaint!!.color = ORANGE_COLOR
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 绘制进度条和叶子
// 之所以把叶子放在进度条里绘制,主要是层级原因
drawProgressAndLeafs(canvas)
// drawLeafs(canvas);
canvas.drawBitmap(mOuterBitmap!!, mOuterSrcRect, mOuterDestRect!!, mBitmapPaint)
postInvalidate()
}
private fun drawProgressAndLeafs(canvas: Canvas) {
if (mProgress >= TOTAL_PROGRESS) {
mProgress = 0
}
// mProgressWidth为进度条的宽度,根据当前进度算出进度条的位置
mCurrentProgressPosition = mProgressWidth * mProgress / TOTAL_PROGRESS
// 即当前位置在图中所示1范围内
if (mCurrentProgressPosition < mArcRadius) {
// RxLogTool.i(TAG, "mProgress = " + mProgress + "---mCurrentProgressPosition = " + mCurrentProgressPosition + "--mArcProgressWidth" + mArcRadius);
// 1.绘制白色ARC,绘制orange ARC
// 2.绘制白色矩形
// 1.绘制白色ARC
canvas.drawArc(mArcRectF!!, 90f, 180f, false, mWhitePaint!!)
// 2.绘制白色矩形
mWhiteRectF!!.left = mArcRightLocation.toFloat()
canvas.drawRect(mWhiteRectF!!, mWhitePaint!!)
// 绘制叶子
drawLeafs(canvas)
// 3.绘制棕色 ARC
// 单边角度
val angle = Math.toDegrees(Math.acos(((mArcRadius - mCurrentProgressPosition)
/ mArcRadius.toFloat()).toDouble())).toInt()
// 起始的位置
val startAngle = 180 - angle
// 扫过的角度
val sweepAngle = 2 * angle
// RxLogTool.i(TAG, "startAngle = " + startAngle);
canvas.drawArc(mArcRectF!!, startAngle.toFloat(), sweepAngle.toFloat(), false, mOrangePaint!!)
} else {
// RxLogTool.i(TAG, "mProgress = " + mProgress + "---transfer-----mCurrentProgressPosition = " + mCurrentProgressPosition + "--mArcProgressWidth" + mArcRadius);
// 1.绘制white RECT
// 2.绘制Orange ARC
// 3.绘制orange RECT
// 这个层级进行绘制能让叶子感觉是融入棕色进度条中
// 1.绘制white RECT
mWhiteRectF!!.left = mCurrentProgressPosition.toFloat()
canvas.drawRect(mWhiteRectF!!, mWhitePaint!!)
// 绘制叶子
drawLeafs(canvas)
// 2.绘制Orange ARC
canvas.drawArc(mArcRectF!!, 90f, 180f, false, mOrangePaint!!)
// 3.绘制orange RECT
mOrangeRectF!!.left = mArcRightLocation.toFloat()
mOrangeRectF!!.right = mCurrentProgressPosition.toFloat()
canvas.drawRect(mOrangeRectF!!, mOrangePaint!!)
}
}
/**
* 绘制叶子
*
* @param canvas
*/
private fun drawLeafs(canvas: Canvas) {
mLeafRotateTime = if (mLeafRotateTime <= 0) LEAF_ROTATE_TIME else mLeafRotateTime
val currentTime = System.currentTimeMillis()
for (i in mLeafInfos.indices) {
val orange_pulp = mLeafInfos[i]
if (currentTime > orange_pulp.startTime && orange_pulp.startTime != 0L) {
// 绘制叶子--根据叶子的类型和当前时间得出叶子的(x,y)
getLeafLocation(orange_pulp, currentTime)
// 根据时间计算旋转角度
canvas.save()
// 通过Matrix控制叶子旋转
val matrix = Matrix()
val transX = mLeftMargin + orange_pulp.x
val transY = mLeftMargin + orange_pulp.y
// RxLogTool.i(TAG, "left.x = " + orange_pulp.x + "--orange_pulp.y=" + orange_pulp.y);
matrix.postTranslate(transX, transY)
// 通过时间关联旋转角度,则可以直接通过修改LEAF_ROTATE_TIME调节叶子旋转快慢
val rotateFraction = ((currentTime - orange_pulp.startTime) % mLeafRotateTime
/ mLeafRotateTime.toFloat())
val angle = (rotateFraction * 360).toInt()
// 根据叶子旋转方向确定叶子旋转角度
val rotate = if (orange_pulp.rotateDirection == 0) angle + orange_pulp.rotateAngle else -angle
+orange_pulp.rotateAngle
matrix.postRotate(rotate.toFloat(), transX
+ mLeafWidth / 2, transY + mLeafHeight / 2)
canvas.drawBitmap(mLeafBitmap!!, matrix, mBitmapPaint)
canvas.restore()
} else {
continue
}
}
}
private fun getLeafLocation(orange_pulp: Leaf, currentTime: Long) {
val intervalTime = currentTime - orange_pulp.startTime
mLeafFloatTime = if (mLeafFloatTime <= 0) LEAF_FLOAT_TIME else mLeafFloatTime
if (intervalTime < 0) {
return
} else if (intervalTime > mLeafFloatTime) {
orange_pulp.startTime = (System.currentTimeMillis()
+ Random().nextInt(mLeafFloatTime.toInt()))
}
val fraction = intervalTime.toFloat() / mLeafFloatTime
orange_pulp.x = (mProgressWidth - mProgressWidth * fraction)
orange_pulp.y = getLocationY(orange_pulp).toFloat()
}
// 通过叶子信息获取当前叶子的Y值
private fun getLocationY(orange_pulp: Leaf): Int {
// y = A(wx+Q)+h
val w = (2.toFloat() * Math.PI / mProgressWidth).toFloat()
var a = middleAmplitude.toFloat()
when (orange_pulp.type) {
StartType.LITTLE -> // 小振幅 = 中等振幅 - 振幅差
a = middleAmplitude - mplitudeDisparity.toFloat()
StartType.MIDDLE -> a = middleAmplitude.toFloat()
StartType.BIG -> // 小振幅 = 中等振幅 + 振幅差
a = middleAmplitude + mplitudeDisparity.toFloat()
else -> {
}
}
// RxLogTool.i(TAG, "---a = " + a + "---w = " + w + "--orange_pulp.x = " + orange_pulp.x);
return (a * Math.sin(w * orange_pulp.x.toDouble())).toInt() + mArcRadius * 2 / 3
}
private fun initBitmap() {
mLeafBitmap = (mResources.getDrawable(R.drawable.orange_pulp) as BitmapDrawable).bitmap
mLeafWidth = mLeafBitmap?.width!!
mLeafHeight = mLeafBitmap?.height!!
mOuterBitmap = (mResources.getDrawable(R.drawable.orange_pulp_frame) as BitmapDrawable).bitmap
mOuterWidth = mOuterBitmap?.width!!
mOuterHeight = mOuterBitmap?.height!!
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mTotalWidth = w
mTotalHeight = h
mProgressWidth = mTotalWidth - mLeftMargin - mRightMargin
mArcRadius = (mTotalHeight - 2 * mLeftMargin) / 2
mOuterSrcRect = Rect(0, 0, mOuterWidth, mOuterHeight)
mOuterDestRect = Rect(0, 0, mTotalWidth, mTotalHeight)
mWhiteRectF = RectF((mLeftMargin + mCurrentProgressPosition).toFloat(), mLeftMargin.toFloat(), (mTotalWidth
- mRightMargin).toFloat(),
(mTotalHeight - mLeftMargin).toFloat())
mOrangeRectF = RectF((mLeftMargin + mArcRadius).toFloat(), mLeftMargin.toFloat(),
mCurrentProgressPosition.toFloat()
, (mTotalHeight - mLeftMargin).toFloat())
mArcRectF = RectF(mLeftMargin.toFloat(), mLeftMargin.toFloat(), (mLeftMargin + 2 * mArcRadius).toFloat(),
(mTotalHeight - mLeftMargin).toFloat())
mArcRightLocation = mLeftMargin + mArcRadius
}
/**
* 设置进度
*
* @param progress
*/
fun setProgress(progress: Int) {
mProgress = progress
postInvalidate()
}
/**
* 获取叶子飘完一个周期所花的时间
*/
/**
* 设置叶子飘完一个周期所花的时间
*
* @param time
*/
var leafFloatTime: Long
get() {
mLeafFloatTime = if (mLeafFloatTime == 0L) LEAF_FLOAT_TIME else mLeafFloatTime
return mLeafFloatTime
}
set(time) {
mLeafFloatTime = time
}
/**
* 获取叶子旋转一周所花的时间
*/
/**
* 设置叶子旋转一周所花的时间
*
* @param time
*/
var leafRotateTime: Long
get() {
mLeafRotateTime = if (mLeafRotateTime == 0L) LEAF_ROTATE_TIME else mLeafRotateTime
return mLeafRotateTime
}
set(time) {
mLeafRotateTime = time
}
private enum class StartType {
LITTLE, MIDDLE, BIG
}
/**
* 叶子对象,用来记录叶子主要数据
*
* @author Ajian_Studio
*/
private inner class Leaf {
// 在绘制部分的位置
var x = 0f
var y = 0f
// 控制叶子飘动的幅度
var type: StartType? = null
// 旋转角度
var rotateAngle = 0
// 旋转方向--0代表顺时针,1代表逆时针
var rotateDirection = 0
// 起始时间(ms)
var startTime: Long = 0
}
private inner class LeafFactory {
var random = Random()
private val MAX_LEAFS = 8
// 生成一个叶子信息
fun generateLeaf(): Leaf {
val orange_pulp = Leaf()
val randomType = random.nextInt(3)
// 随时类型- 随机振幅
var type = StartType.MIDDLE
when (randomType) {
0 -> {
}
1 -> type = StartType.LITTLE
2 -> type = StartType.BIG
else -> {
}
}
orange_pulp.type = type
// 随机起始的旋转角度
orange_pulp.rotateAngle = random.nextInt(360)
// 随机旋转方向(顺时针或逆时针)
orange_pulp.rotateDirection = random.nextInt(2)
// 为了产生交错的感觉,让开始的时间有一定的随机性
mLeafFloatTime = if (mLeafFloatTime <= 0) LEAF_FLOAT_TIME else mLeafFloatTime
mAddTime += random.nextInt((mLeafFloatTime * 2).toInt())
orange_pulp.startTime = System.currentTimeMillis() + mAddTime
return orange_pulp
}
// 根据传入的叶子数量产生叶子信息
// 根据最大叶子数产生叶子信息
@JvmOverloads
fun generateLeafs(orange_pulpSize: Int = MAX_LEAFS): List<Leaf> {
val orange_pulps: MutableList<Leaf> = LinkedList()
for (i in 0 until orange_pulpSize) {
orange_pulps.add(generateLeaf())
}
return orange_pulps
}
}
companion object {
private const val TAG = "TOrangeJuice"
// 淡白色
private const val WHITE_COLOR = -0x21c67
// 橙色
private const val ORANGE_COLOR = -0x5800
// 中等振幅大小
private const val MIDDLE_AMPLITUDE = 13
// 不同类型之间的振幅差距
private const val AMPLITUDE_DISPARITY = 5
// 总进度
private const val TOTAL_PROGRESS = 100
// 叶子飘动一个周期所花的时间
private const val LEAF_FLOAT_TIME: Long = 3000
// 叶子旋转一周需要的时间
private const val LEAF_ROTATE_TIME: Long = 2000
// 用于控制绘制的进度条距离左/上/下的距离
private const val LEFT_MARGIN = 9
// 用于控制绘制的进度条距离右的距离
private const val RIGHT_MARGIN = 25
}
init {
mResources = resources
mLeftMargin = dp2px(context!!, LEFT_MARGIN.toFloat())
mRightMargin = dp2px(context, RIGHT_MARGIN.toFloat())
mLeafFloatTime = LEAF_FLOAT_TIME
mLeafRotateTime = LEAF_ROTATE_TIME
initBitmap()
initPaint()
mLeafFactory = LeafFactory()
mLeafInfos = mLeafFactory.generateLeafs()
}
}
|
apache-2.0
|
34bac64129a5bde9d6bc6165765c4e80
| 31.471154 | 171 | 0.57659 | 3.732246 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/edit/WikiTextKeyboardHeadingsView.kt
|
1
|
2424
|
package org.wikipedia.edit
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import org.wikipedia.R
import org.wikipedia.databinding.ViewWikitextKeyboardHeadingsBinding
import org.wikipedia.util.FeedbackUtil
class WikiTextKeyboardHeadingsView : FrameLayout {
private val binding = ViewWikitextKeyboardHeadingsBinding.inflate(LayoutInflater.from(context), this)
var callback: WikiTextKeyboardView.Callback? = null
var editText: SyntaxHighlightableEditText? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
init {
binding.closeButton.setOnClickListener {
callback?.onSyntaxOverlayCollapse()
}
binding.wikitextButtonH2.contentDescription = context.getString(R.string.wikitext_heading_n, 2)
binding.wikitextButtonH2.setOnClickListener {
editText?.inputConnection?.let {
WikiTextKeyboardView.toggleSyntaxAroundCurrentSelection(editText, it, "==", "==")
}
}
binding.wikitextButtonH3.contentDescription = context.getString(R.string.wikitext_heading_n, 3)
binding.wikitextButtonH3.setOnClickListener {
editText?.inputConnection?.let {
WikiTextKeyboardView.toggleSyntaxAroundCurrentSelection(editText, it, "===", "===")
}
}
binding.wikitextButtonH4.contentDescription = context.getString(R.string.wikitext_heading_n, 4)
binding.wikitextButtonH4.setOnClickListener {
editText?.inputConnection?.let {
WikiTextKeyboardView.toggleSyntaxAroundCurrentSelection(editText, it, "====", "====")
}
}
binding.wikitextButtonH5.contentDescription = context.getString(R.string.wikitext_heading_n, 5)
binding.wikitextButtonH5.setOnClickListener {
editText?.inputConnection?.let {
WikiTextKeyboardView.toggleSyntaxAroundCurrentSelection(editText, it, "=====", "=====")
}
}
FeedbackUtil.setButtonLongPressToast(binding.closeButton, binding.wikitextButtonH2, binding.wikitextButtonH3,
binding.wikitextButtonH4, binding.wikitextButtonH5)
}
}
|
apache-2.0
|
4c9fec8f97b8845be211c66594bd4241
| 44.735849 | 117 | 0.706271 | 4.781065 | false | false | false | false |
runjia1987/crawler-client-kt
|
src/main/java/org/jackJew/biz/engine/client/MessagePushService.kt
|
1
|
1084
|
package org.jackJew.biz.engine.client
import com.rabbitmq.client.MessageProperties
import org.jackJew.biz.engine.util.GsonUtils
import org.jackJew.biz.engine.util.PropertyReader
import org.jackJew.biz.task.Reply
import java.util.concurrent.LinkedBlockingQueue
class MessagePushService {
companion object {
val exchangeName = PropertyReader.getProperty("exchangeName")
val queueNameReply = PropertyReader.getProperty("queueNameReply")
val INSTANCE by lazy { MessagePushService() }
}
val connection = EngineClient.CONN_FACTORY.newConnection()!!
private val replyQueue = LinkedBlockingQueue<Reply>()
init {
val channel = connection.createChannel()
Thread(Runnable {
while (true) {
replyQueue.take().also {
channel.basicPublish(exchangeName, queueNameReply, MessageProperties.BASIC, GsonUtils.toJson(it).toByteArray())
}
}
}, "publishThread").also {
it.isDaemon = true
it.start()
}
}
/**
* Asynchronously submit reply message.
*/
fun submit(reply: Reply) = replyQueue.offer(reply)
}
|
apache-2.0
|
aeb564ae6f251284dce6c147ab319c6d
| 27.552632 | 121 | 0.719557 | 4.25098 | false | false | false | false |
AndroidX/androidx
|
compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/Color.kt
|
3
|
23418
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.colorspace.ColorModel
import androidx.compose.ui.graphics.colorspace.ColorSpace
import androidx.compose.ui.graphics.colorspace.ColorSpaces
import androidx.compose.ui.graphics.colorspace.Rgb
import androidx.compose.ui.graphics.colorspace.connect
import androidx.compose.ui.util.lerp
import kotlin.math.max
import kotlin.math.min
/**
* The `Color` class contains color information to be used while painting
* in [Canvas]. `Color` supports [ColorSpace]s with 3 [components][ColorSpace.componentCount],
* plus one for [alpha].
*
* ### Creating
*
* `Color` can be created with one of these methods:
*
* // from 4 separate [Float] components. Alpha and ColorSpace are optional
* val rgbaWhiteFloat = Color(red = 1f, green = 1f, blue = 1f, alpha = 1f,
* ColorSpace.get(ColorSpaces.Srgb))
*
* // from a 32-bit SRGB color integer
* val fromIntWhite = Color(android.graphics.Color.WHITE)
* val fromLongBlue = Color(0xFF0000FF)
*
* // from SRGB integer component values. Alpha is optional
* val rgbaWhiteInt = Color(red = 0xFF, green = 0xFF, blue = 0xFF, alpha = 0xFF)
*
* ### Representation
*
* A `Color` always defines a color using 4 components packed in a single
* 64 bit long value. One of these components is always alpha while the other
* three components depend on the color space's [color model][ColorModel].
* The most common color model is the [RGB][ColorModel.Rgb] model in
* which the components represent red, green, and blue values.
*
* **Component ranges:** the ranges defined in the tables
* below indicate the ranges that can be encoded in a color long. They do not
* represent the actual ranges as they may differ per color space. For instance,
* the RGB components of a color in the [Display P3][ColorSpaces.DisplayP3]
* color space use the `[0..1]` range. Please refer to the documentation of the
* various [color spaces][ColorSpaces] to find their respective ranges.
*
* **Alpha range:** while alpha is encoded in a color long using
* a 10 bit integer (thus using a range of `[0..1023]`), it is converted to and
* from `[0..1]` float values when decoding and encoding color longs.
*
* **sRGB color space:** for compatibility reasons and ease of
* use, `Color` encoded [sRGB][ColorSpaces.Srgb] colors do not
* use the same encoding as other color longs.
* ```
* | Component | Name | Size | Range |
* |-----------|-------------|---------|-----------------------|
* | [RGB][ColorSpace.Model.Rgb] color model |
* | R | Red | 16 bits | `[-65504.0, 65504.0]` |
* | G | Green | 16 bits | `[-65504.0, 65504.0]` |
* | B | Blue | 16 bits | `[-65504.0, 65504.0]` |
* | A | Alpha | 10 bits | `[0..1023]` |
* | | Color space | 6 bits | `[0..63]` |
* | [SRGB][ColorSpaces.Srgb] color space |
* | R | Red | 8 bits | `[0..255]` |
* | G | Green | 8 bits | `[0..255]` |
* | B | Blue | 8 bits | `[0..255]` |
* | A | Alpha | 8 bits | `[0..255]` |
* | X | Unused | 32 bits | `[0]` |
* | [XYZ][ColorSpace.Model.Xyz] color model |
* | X | X | 16 bits | `[-65504.0, 65504.0]` |
* | Y | Y | 16 bits | `[-65504.0, 65504.0]` |
* | Z | Z | 16 bits | `[-65504.0, 65504.0]` |
* | A | Alpha | 10 bits | `[0..1023]` |
* | | Color space | 6 bits | `[0..63]` |
* | [Lab][ColorSpace.Model.Lab] color model |
* | L | L | 16 bits | `[-65504.0, 65504.0]` |
* | a | a | 16 bits | `[-65504.0, 65504.0]` |
* | b | b | 16 bits | `[-65504.0, 65504.0]` |
* | A | Alpha | 10 bits | `[0..1023]` |
* | | Color space | 6 bits | `[0..63]` |
* ```
* The components in this table are listed in encoding order (see below),
* which is why color longs in the RGB model are called RGBA colors (even if
* this doesn't quite hold for the special case of sRGB colors).
*
* The color encoding relies on half-precision float values (fp16). If you
* wish to know more about the limitations of half-precision float values, please
* refer to the documentation of the [Float16] class.
*
* The values returned by these methods depend on the color space encoded
* in the color long. The values are however typically in the `[0..1]` range
* for RGB colors. Please refer to the documentation of the various
* [color spaces][ColorSpaces] for the exact ranges.
*/
@Immutable
@kotlin.jvm.JvmInline
value class Color(val value: ULong) {
/**
* Returns this color's color space.
*
* @return A non-null instance of [ColorSpace]
*/
@Stable
val colorSpace: ColorSpace
get() = ColorSpaces.getColorSpace((value and 0x3fUL).toInt())
/**
* Converts this color from its color space to the specified color space.
* The conversion is done using the default rendering intent as specified
* by [ColorSpace.connect].
*
* @param colorSpace The destination color space, cannot be null
*
* @return A non-null color instance in the specified color space
*/
fun convert(colorSpace: ColorSpace): Color {
if (colorSpace == this.colorSpace) {
return this // nothing to convert
}
val connector = this.colorSpace.connect(colorSpace)
val color = getComponents()
connector.transform(color)
return Color(
red = color[0],
green = color[1],
blue = color[2],
alpha = color[3],
colorSpace = colorSpace
)
}
/**
* Returns the value of the red component in the range defined by this
* color's color space (see [ColorSpace.getMinValue] and
* [ColorSpace.getMaxValue]).
*
* If this color's color model is not [RGB][ColorModel.Rgb],
* calling this is the first component of the ColorSpace.
*
* @see alpha
* @see blue
* @see green
*/
@Stable
val red: Float
get() {
return if ((value and 0x3fUL) == 0UL) {
((value shr 48) and 0xffUL).toFloat() / 255.0f
} else {
Float16(((value shr 48) and 0xffffUL).toShort())
.toFloat()
}
}
/**
* Returns the value of the green component in the range defined by this
* color's color space (see [ColorSpace.getMinValue] and
* [ColorSpace.getMaxValue]).
*
* If this color's color model is not [RGB][ColorModel.Rgb],
* calling this is the second component of the ColorSpace.
*
* @see alpha
* @see red
* @see blue
*/
@Stable
val green: Float
get() {
return if ((value and 0x3fUL) == 0UL) {
((value shr 40) and 0xffUL).toFloat() / 255.0f
} else {
Float16(((value shr 32) and 0xffffUL).toShort())
.toFloat()
}
}
/**
* Returns the value of the blue component in the range defined by this
* color's color space (see [ColorSpace.getMinValue] and
* [ColorSpace.getMaxValue]).
*
* If this color's color model is not [RGB][ColorModel.Rgb],
* calling this is the third component of the ColorSpace.
*
* @see alpha
* @see red
* @see green
*/
@Stable
val blue: Float
get() {
return if ((value and 0x3fUL) == 0UL) {
((value shr 32) and 0xffUL).toFloat() / 255.0f
} else {
Float16(((value shr 16) and 0xffffUL).toShort())
.toFloat()
}
}
/**
* Returns the value of the alpha component in the range `[0..1]`.
*
* @see red
* @see green
* @see blue
*/
@Stable
val alpha: Float
get() {
return if ((value and 0x3fUL) == 0UL) {
((value shr 56) and 0xffUL).toFloat() / 255.0f
} else {
((value shr 6) and 0x3ffUL).toFloat() / 1023.0f
}
}
@Stable
operator fun component1(): Float = red
@Stable
operator fun component2(): Float = green
@Stable
operator fun component3(): Float = blue
@Stable
operator fun component4(): Float = alpha
@Stable
operator fun component5(): ColorSpace = colorSpace
/**
* Copies the existing color, changing only the provided values. The [ColorSpace][colorSpace]
* of the returned [Color] is the same as this [colorSpace].
*/
@Stable
fun copy(
alpha: Float = this.alpha,
red: Float = this.red,
green: Float = this.green,
blue: Float = this.blue
): Color = Color(
red = red,
green = green,
blue = blue,
alpha = alpha,
colorSpace = this.colorSpace
)
/**
* Returns a string representation of the object. This method returns
* a string equal to the value of:
*
* "Color($r, $g, $b, $a, ${colorSpace.name})"
*
* For instance, the string representation of opaque black in the sRGB
* color space is equal to the following value:
*
* Color(0.0, 0.0, 0.0, 1.0, sRGB IEC61966-2.1)
*
* @return A non-null string representation of the object
*/
override fun toString(): String {
return "Color($red, $green, $blue, $alpha, ${colorSpace.name})"
}
companion object {
@Stable
val Black = Color(0xFF000000)
@Stable
val DarkGray = Color(0xFF444444)
@Stable
val Gray = Color(0xFF888888)
@Stable
val LightGray = Color(0xFFCCCCCC)
@Stable
val White = Color(0xFFFFFFFF)
@Stable
val Red = Color(0xFFFF0000)
@Stable
val Green = Color(0xFF00FF00)
@Stable
val Blue = Color(0xFF0000FF)
@Stable
val Yellow = Color(0xFFFFFF00)
@Stable
val Cyan = Color(0xFF00FFFF)
@Stable
val Magenta = Color(0xFFFF00FF)
@Stable
val Transparent = Color(0x00000000)
/**
* Because Color is an inline class, this represents an unset value
* without having to box the Color. It will be treated as [Transparent]
* when drawn. A Color can compare with [Unspecified] for equality or use
* [isUnspecified] to check for the unset value or [isSpecified] for any color that isn't
* [Unspecified].
*/
@Stable
val Unspecified = Color(0f, 0f, 0f, 0f, ColorSpaces.Unspecified)
/**
* Return a [Color] from [hue], [saturation], and [value] (HSV representation).
*
* @param hue The color value in the range (0..360), where 0 is red, 120 is green, and
* 240 is blue
* @param saturation The amount of [hue] represented in the color in the range (0..1),
* where 0 has no color and 1 is fully saturated.
* @param value The strength of the color, where 0 is black.
* @param colorSpace The RGB color space used to calculate the Color from the HSV values.
*/
fun hsv(
hue: Float,
saturation: Float,
value: Float,
alpha: Float = 1f,
colorSpace: Rgb = ColorSpaces.Srgb
): Color {
require(hue in 0f..360f && saturation in 0f..1f && value in 0f..1f) {
"HSV ($hue, $saturation, $value) must be in range (0..360, 0..1, 0..1)"
}
val red = hsvToRgbComponent(5, hue, saturation, value)
val green = hsvToRgbComponent(3, hue, saturation, value)
val blue = hsvToRgbComponent(1, hue, saturation, value)
return Color(red, green, blue, alpha, colorSpace)
}
private fun hsvToRgbComponent(n: Int, h: Float, s: Float, v: Float): Float {
val k = (n.toFloat() + h / 60f) % 6f
return v - (v * s * max(0f, minOf(k, 4 - k, 1f)))
}
/**
* Return a [Color] from [hue], [saturation], and [lightness] (HSL representation).
*
* @param hue The color value in the range (0..360), where 0 is red, 120 is green, and
* 240 is blue
* @param saturation The amount of [hue] represented in the color in the range (0..1),
* where 0 has no color and 1 is fully saturated.
* @param lightness A range of (0..1) where 0 is black, 0.5 is fully colored, and 1 is
* white.
* @param colorSpace The RGB color space used to calculate the Color from the HSL values.
*/
fun hsl(
hue: Float,
saturation: Float,
lightness: Float,
alpha: Float = 1f,
colorSpace: Rgb = ColorSpaces.Srgb
): Color {
require(hue in 0f..360f && saturation in 0f..1f && lightness in 0f..1f) {
"HSL ($hue, $saturation, $lightness) must be in range (0..360, 0..1, 0..1)"
}
val red = hslToRgbComponent(0, hue, saturation, lightness)
val green = hslToRgbComponent(8, hue, saturation, lightness)
val blue = hslToRgbComponent(4, hue, saturation, lightness)
return Color(red, green, blue, alpha, colorSpace)
}
private fun hslToRgbComponent(n: Int, h: Float, s: Float, l: Float): Float {
val k = (n.toFloat() + h / 30f) % 12f
val a = s * min(l, 1f - l)
return l - a * max(-1f, minOf(k - 3, 9 - k, 1f))
}
}
}
/**
* Create a [Color] by passing individual [red], [green], [blue], [alpha], and [colorSpace]
* components. The default [color space][ColorSpace] is [SRGB][ColorSpaces.Srgb] and
* the default [alpha] is `1.0` (opaque). [colorSpace] must have a [ColorSpace.componentCount] of
* 3.
*/
@Stable
fun Color(
red: Float,
green: Float,
blue: Float,
alpha: Float = 1f,
colorSpace: ColorSpace = ColorSpaces.Srgb
): Color {
require(
red in colorSpace.getMinValue(0)..colorSpace.getMaxValue(0) &&
green in colorSpace.getMinValue(1)..colorSpace.getMaxValue(1) &&
blue in colorSpace.getMinValue(2)..colorSpace.getMaxValue(2) &&
alpha in 0f..1f
) {
"red = $red, green = $green, blue = $blue, alpha = $alpha outside the range for $colorSpace"
}
if (colorSpace.isSrgb) {
val argb = (
((alpha * 255.0f + 0.5f).toInt() shl 24) or
((red * 255.0f + 0.5f).toInt() shl 16) or
((green * 255.0f + 0.5f).toInt() shl 8) or
(blue * 255.0f + 0.5f).toInt()
)
return Color(value = (argb.toULong() and 0xffffffffUL) shl 32)
}
require(colorSpace.componentCount == 3) {
"Color only works with ColorSpaces with 3 components"
}
val id = colorSpace.id
require(id != ColorSpace.MinId) {
"Unknown color space, please use a color space in ColorSpaces"
}
val r = Float16(red)
val g = Float16(green)
val b = Float16(blue)
val a = (max(0.0f, min(alpha, 1.0f)) * 1023.0f + 0.5f).toInt()
// Suppress sign extension
return Color(
value = (
((r.halfValue.toULong() and 0xffffUL) shl 48) or (
(g.halfValue.toULong() and 0xffffUL) shl 32
) or (
(b.halfValue.toULong() and 0xffffUL) shl 16
) or (
(a.toULong() and 0x3ffUL) shl 6
) or (
id.toULong() and 0x3fUL
)
)
)
}
/**
* Creates a new [Color] instance from an ARGB color int.
* The resulting color is in the [sRGB][ColorSpaces.Srgb]
* color space.
*
* @param color The ARGB color int to create a <code>Color</code> from.
* @return A non-null instance of {@link Color}
*/
@Stable
fun Color(/*@ColorInt*/ color: Int): Color {
return Color(value = color.toULong() shl 32)
}
/**
* Creates a new [Color] instance from an ARGB color int.
* The resulting color is in the [sRGB][ColorSpaces.Srgb]
* color space. This is useful for specifying colors with alpha
* greater than 0x80 in numeric form without using [Long.toInt]:
*
* val color = Color(0xFF000080)
*
* @param color The 32-bit ARGB color int to create a <code>Color</code>
* from
* @return A non-null instance of {@link Color}
*/
@Stable
fun Color(color: Long): Color {
return Color(value = (color.toULong() and 0xffffffffUL) shl 32)
}
/**
* Creates a new [Color] instance from an ARGB color components.
* The resulting color is in the [sRGB][ColorSpaces.Srgb]
* color space. The default alpha value is `0xFF` (opaque).
*
* @param red The red component of the color, between 0 and 255.
* @param green The green component of the color, between 0 and 255.
* @param blue The blue component of the color, between 0 and 255.
* @param alpha The alpha component of the color, between 0 and 255.
*
* @return A non-null instance of {@link Color}
*/
@Stable
fun Color(
/*@IntRange(from = 0, to = 0xFF)*/
red: Int,
/*@IntRange(from = 0, to = 0xFF)*/
green: Int,
/*@IntRange(from = 0, to = 0xFF)*/
blue: Int,
/*@IntRange(from = 0, to = 0xFF)*/
alpha: Int = 0xFF
): Color {
val color = ((alpha and 0xFF) shl 24) or
((red and 0xFF) shl 16) or
((green and 0xFF) shl 8) or
(blue and 0xFF)
return Color(color)
}
/**
* Linear interpolate between two [Colors][Color], [start] and [stop] with [fraction] fraction
* between the two. The [ColorSpace] of the result is always the [ColorSpace][Color.colorSpace]
* of [stop]. [fraction] should be between 0 and 1, inclusive. Interpolation is done
* in the [ColorSpaces.Oklab] color space.
*/
@Stable
fun lerp(start: Color, stop: Color, /*@FloatRange(from = 0.0, to = 1.0)*/ fraction: Float): Color {
val colorSpace = ColorSpaces.Oklab
val startColor = start.convert(colorSpace)
val endColor = stop.convert(colorSpace)
val startAlpha = startColor.alpha
val startL = startColor.red
val startA = startColor.green
val startB = startColor.blue
val endAlpha = endColor.alpha
val endL = endColor.red
val endA = endColor.green
val endB = endColor.blue
val interpolated = Color(
alpha = lerp(startAlpha, endAlpha, fraction),
red = lerp(startL, endL, fraction),
green = lerp(startA, endA, fraction),
blue = lerp(startB, endB, fraction),
colorSpace = colorSpace
)
return interpolated.convert(stop.colorSpace)
}
/**
* Composites [this] color on top of [background] using the Porter-Duff 'source over' mode.
*
* Both [this] and [background] must not be pre-multiplied, and the resulting color will also
* not be pre-multiplied.
*
* The [ColorSpace] of the result is always the [ColorSpace][Color.colorSpace] of [background].
*
* @return the [Color] representing [this] composited on top of [background], converted to the
* color space of [background].
*/
@Stable
fun Color.compositeOver(background: Color): Color {
val fg = this.convert(background.colorSpace)
val bgA = background.alpha
val fgA = fg.alpha
val a = fgA + (bgA * (1f - fgA))
val r = compositeComponent(fg.red, background.red, fgA, bgA, a)
val g = compositeComponent(fg.green, background.green, fgA, bgA, a)
val b = compositeComponent(fg.blue, background.blue, fgA, bgA, a)
return Color(r, g, b, a, background.colorSpace)
}
/**
* Composites the given [foreground component][fgC] over the [background component][bgC], with
* foreground and background alphas of [fgA] and [bgA] respectively.
*
* This uses a pre-calculated composite destination alpha of [a] for efficiency.
*/
@Suppress("NOTHING_TO_INLINE")
private inline fun compositeComponent(
fgC: Float,
bgC: Float,
fgA: Float,
bgA: Float,
a: Float
) = if (a == 0f) 0f else ((fgC * fgA) + ((bgC * bgA) * (1f - fgA))) / a
/**
* Returns this color's components as a new array. The last element of the
* array is always the alpha component.
*
* @return A new, non-null array whose size is 4
*/
/*@Size(value = 4)*/
private fun Color.getComponents(): FloatArray = floatArrayOf(red, green, blue, alpha)
/**
* Returns the relative luminance of this color.
*
* Based on the formula for relative luminance defined in WCAG 2.0,
* W3C Recommendation 11 December 2008.
*
* @return A value between 0 (darkest black) and 1 (lightest white)
*
* @throws IllegalArgumentException If the this color's color space
* does not use the [RGB][ColorModel.Rgb] color model
*/
@Stable
fun Color.luminance(): Float {
val colorSpace = colorSpace
require(colorSpace.model == ColorModel.Rgb) {
"The specified color must be encoded in an RGB color space. " +
"The supplied color space is ${colorSpace.model}"
}
val eotf = (colorSpace as Rgb).eotf
val r = eotf(red.toDouble())
val g = eotf(green.toDouble())
val b = eotf(blue.toDouble())
return saturate(((0.2126 * r) + (0.7152 * g) + (0.0722 * b)).toFloat())
}
private fun saturate(v: Float): Float {
return if (v <= 0.0f) 0.0f else (if (v >= 1.0f) 1.0f else v)
}
/**
* Converts this color to an ARGB color int. A color int is always in
* the [sRGB][ColorSpaces.Srgb] color space. This implies
* a color space conversion is applied if needed.
*
* @return An ARGB color in the sRGB color space
*/
@Stable
/*@ColorInt*/
fun Color.toArgb(): Int {
val colorSpace = colorSpace
if (colorSpace.isSrgb) {
return (this.value shr 32).toInt()
}
val color = getComponents()
// The transformation saturates the output
colorSpace.connect().transform(color)
return (color[3] * 255.0f + 0.5f).toInt() shl 24 or
((color[0] * 255.0f + 0.5f).toInt() shl 16) or
((color[1] * 255.0f + 0.5f).toInt() shl 8) or
(color[2] * 255.0f + 0.5f).toInt()
}
/**
* `false` when this is [Color.Unspecified].
*/
@Stable
inline val Color.isSpecified: Boolean get() = value != Color.Unspecified.value
/**
* `true` when this is [Color.Unspecified].
*/
@Stable
inline val Color.isUnspecified: Boolean get() = value == Color.Unspecified.value
/**
* If this [Color] [isSpecified] then this is returned, otherwise [block] is executed and its result
* is returned.
*/
inline fun Color.takeOrElse(block: () -> Color): Color = if (isSpecified) this else block()
|
apache-2.0
|
d87d950a4dfcf5e7a2a713fcec123244
| 34.162162 | 100 | 0.596251 | 3.7272 | false | false | false | false |
salRoid/Filmy
|
app/src/main/java/tech/salroid/filmy/utility/EndlessScrollListener.kt
|
1
|
3825
|
package tech.salroid.filmy.utility
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
abstract class EndlessScrollListener : RecyclerView.OnScrollListener {
private var visibleThreshold = 5
private var currentPage = 0
private var previousTotalItemCount = 0
private var loading = true
private val startingPageIndex = 0
private var mLayoutManager: RecyclerView.LayoutManager
constructor(layoutManager: LinearLayoutManager) {
mLayoutManager = layoutManager
}
constructor(layoutManager: GridLayoutManager) {
mLayoutManager = layoutManager
visibleThreshold = 2
}
protected constructor(layoutManager: StaggeredGridLayoutManager) {
mLayoutManager = layoutManager
visibleThreshold *= layoutManager.spanCount
}
private fun getLastVisibleItem(lastVisibleItemPositions: IntArray): Int {
var maxSize = 0
for (i in lastVisibleItemPositions.indices) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i]
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i]
}
}
return maxSize
}
// 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) {
//Log.d("", "onScrolled: "+dx+" "+dy);
var lastVisibleItemPosition = 0
val totalItemCount = mLayoutManager.itemCount
if (mLayoutManager is StaggeredGridLayoutManager) {
val lastVisibleItemPositions =
(mLayoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions(null)
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions)
} else if (mLayoutManager is GridLayoutManager) {
lastVisibleItemPosition =
(mLayoutManager as GridLayoutManager).findLastVisibleItemPosition()
} else if (mLayoutManager is LinearLayoutManager) {
lastVisibleItemPosition =
(mLayoutManager as LinearLayoutManager).findLastVisibleItemPosition()
}
// 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) {
currentPage = startingPageIndex
previousTotalItemCount = totalItemCount
if (totalItemCount == 0) {
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 (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) {
currentPage++
onLoadMore(currentPage, totalItemCount, view)
loading = true
}
}
fun resetState() {
currentPage = startingPageIndex
previousTotalItemCount = 0
loading = true
}
fun setCurrentPage(page: Int) {
currentPage = page
}
abstract fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?)
}
|
apache-2.0
|
78472cd0ace24b2ab4b33511bd0d5456
| 37.24 | 98 | 0.66937 | 5.954829 | false | false | false | false |
jorjoluiso/QuijoteLui
|
src/main/kotlin/com/quijotelui/repository/ElectronicoDaoImpl.kt
|
1
|
1693
|
package com.quijotelui.repository
import com.quijotelui.model.Electronico
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
@Transactional
@Repository
class ElectronicoDaoImpl : IElectronicoDao {
@PersistenceContext
lateinit var entityMAnager : EntityManager
@Override
override fun findAll(): MutableList<Electronico> {
return entityMAnager.createQuery("from Electronico").resultList as MutableList<Electronico>
}
@Override
override fun saveElectronico(electronico: Electronico) {
entityMAnager.persist(electronico)
}
@Override
override fun updateElectronico(electronico: Electronico) {
val e = findById(electronico.id!!)
e.codigo = electronico.codigo
e.numero = electronico.numero
e.numeroAutorizacion = electronico.numeroAutorizacion
e.fechaAutorizacion = electronico.fechaAutorizacion
e.observacion = electronico.observacion
e.estado = electronico.estado
entityMAnager.flush()
}
@Override
override fun findById(id : Long): Electronico {
return entityMAnager.find(Electronico::class.java, id)
}
@Override
override fun findByComprobante(codigo: String, numero: String): MutableList<Electronico> {
return entityMAnager.createQuery("from Electronico " +
"where codigo = :codigo " +
"and numero = :numero")
.setParameter("codigo", codigo)
.setParameter("numero", numero).resultList as MutableList<Electronico>
}
}
|
gpl-3.0
|
3bd2db04cbd274ae4ef9f4a59d418f76
| 32.215686 | 99 | 0.710573 | 4.702778 | false | false | false | false |
ligi/SurvivalManual
|
android/src/main/kotlin/org/ligi/survivalmanual/ui/MainActivity.kt
|
1
|
14295
|
package org.ligi.survivalmanual.ui
import android.annotation.TargetApi
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintManager
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat.getColor
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.ligi.compat.WebViewCompat
import org.ligi.kaxt.*
import org.ligi.snackengage.SnackEngage
import org.ligi.snackengage.snacks.DefaultRateSnack
import org.ligi.snackengage.snacks.RateSnack
import org.ligi.survivalmanual.R
import org.ligi.survivalmanual.R.*
import org.ligi.survivalmanual.R.id.*
import org.ligi.survivalmanual.adapter.EditingRecyclerAdapter
import org.ligi.survivalmanual.adapter.MarkdownRecyclerAdapter
import org.ligi.survivalmanual.adapter.SearchResultRecyclerAdapter
import org.ligi.survivalmanual.databinding.ActivityMainBinding
import org.ligi.survivalmanual.databinding.BookmarkBinding
import org.ligi.survivalmanual.functions.CaseInsensitiveSearch
import org.ligi.survivalmanual.functions.convertMarkdownToHtml
import org.ligi.survivalmanual.functions.isImage
import org.ligi.survivalmanual.functions.splitText
import org.ligi.survivalmanual.model.*
import timber.log.Timber
import kotlin.math.max
import kotlin.math.min
import kotlin.properties.Delegates.observable
class MainActivity : BaseActivity() {
private val drawerToggle by lazy {
ActionBarDrawerToggle(this, mainBinding.mainDrawerLayout, string.drawer_open, string.drawer_close)
}
private val survivalContent by lazy { SurvivalContent(assets) }
private lateinit var mainBinding: ActivityMainBinding
private lateinit var currentUrl: String
private lateinit var currentTopicName: String
private lateinit var textInput: MutableList<String>
private var lastFontSize = State.getFontSize()
private var lastNightMode = State.nightModeString()
private var lastAllowSelect = State.allowSelect()
private val linearLayoutManager by lazy { LinearLayoutManager(this) }
private var isInEditMode by observable(false, onChange = { _, _, newMode ->
if (newMode) {
mainBinding.mainFab.setImageResource(drawable.ic_remove_red_eye)
mainBinding.mainContentRecycler.adapter = EditingRecyclerAdapter(textInput)
} else {
mainBinding.mainFab.setImageResource(drawable.ic_edit)
mainBinding.mainContentRecycler.adapter = MarkdownRecyclerAdapter(textInput, imageWidth(), onURLClick)
}
mainBinding.mainContentRecycler.scrollToPosition(State.lastScrollPos)
})
private fun imageWidth(): Int {
val totalWidthPadding = (resources.getDimension(dimen.content_padding) * 2).toInt()
return min(mainBinding.mainContentRecycler.width - totalWidthPadding, mainBinding.mainContentRecycler.height)
}
val onURLClick: (String) -> Unit = {
if (it.startsWith("http")) {
startActivityFromURL(it)
} else if (!processProductLinks(it, this)) {
if (isImage(it)) {
startActivity(Intent(this, ImageViewActivity::class.java).apply {
putExtra("URL", it)
})
} else {
processURL(it)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainBinding.root)
mainBinding.mainDrawerLayout.addDrawerListener(drawerToggle)
setSupportActionBar(mainBinding.mainToolbar.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
mainBinding.mainNavigationView.setNavigationItemSelectedListener { item ->
mainBinding.mainDrawerLayout.closeDrawers()
processURL(navigationEntryMap[item.itemId].entry.url)
true
}
mainBinding.mainContentRecycler.layoutManager = linearLayoutManager
class RememberPositionOnScroll : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
State.lastScrollPos = (mainBinding.mainContentRecycler.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
super.onScrolled(recyclerView, dx, dy)
}
}
mainBinding.mainContentRecycler.addOnScrollListener(RememberPositionOnScroll())
val rateSnack = DefaultRateSnack().apply {
setActionColor(getColor(baseContext, color.colorAccentLight))
}
SnackEngage.from(mainBinding.mainFab).withSnack(rateSnack).build().engageWhenAppropriate()
mainBinding.mainContentRecycler.post {
val data = intent.data?.path
if (data == null || !processURL(data.replace("/", ""))) {
if (!processURL(State.lastVisitedURL)) {
processURL(State.FALLBACK_URL)
}
}
isInEditMode = false
}
if (State.isInitialOpening) {
mainBinding.mainDrawerLayout.openDrawer(GravityCompat.START)
State.isInitialOpening = false
}
mainBinding.mainFab.setOnClickListener {
isInEditMode = !isInEditMode
}
}
override fun onPrepareOptionsMenu(menu: Menu) = super.onPrepareOptionsMenu(menu.apply {
findItem(action_search)?.let {
it.isVisible = State.allowSearch()
}
})
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
if (Build.VERSION.SDK_INT >= 19) {
menuInflater.inflate(R.menu.print, menu)
}
val searchView = menu.findItem(action_search).actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(searchTerm: String): Boolean {
State.searchTerm = searchTerm
val adapter = mainBinding.mainContentRecycler.adapter
if (adapter is MarkdownRecyclerAdapter) {
val positionForWord = adapter.getPositionForWord(searchTerm)
if (positionForWord != null) {
mainBinding.mainContentRecycler.smoothScrollToPosition(positionForWord)
} else {
mainBinding.mainContentRecycler.adapter = SearchResultRecyclerAdapter(searchTerm, survivalContent) {
processURL(it)
closeKeyboard()
}.apply { showToastWhenListIsEmpty() }
}
adapter.notifyDataSetChanged()
} else if (adapter is SearchResultRecyclerAdapter) {
adapter.changeTerm(searchTerm)
adapter.showToastWhenListIsEmpty()
if (survivalContent.getMarkdown(currentUrl)!!.contains(searchTerm)) {
mainBinding.mainContentRecycler.adapter = MarkdownRecyclerAdapter(textInput, imageWidth(), onURLClick)
State.searchTerm = searchTerm
}
}
return true
}
override fun onQueryTextSubmit(query: String?) = true
})
return super.onCreateOptionsMenu(menu)
}
fun SearchResultRecyclerAdapter.showToastWhenListIsEmpty() {
if (list.isEmpty()) {
Toast.makeText(this@MainActivity, State.searchTerm + " not found", Toast.LENGTH_LONG).show()
}
}
private fun MarkdownRecyclerAdapter.getPositionForWord(searchTerm: String): Int? {
val first = max(linearLayoutManager.findFirstVisibleItemPosition(), 0)
val search = CaseInsensitiveSearch(searchTerm)
return (first..list.lastIndex).firstOrNull {
search.isInContent(list[it])
}
}
private val optionsMap = mapOf(
menu_settings to { startActivityFromClass(PreferenceActivity::class.java) },
menu_share to {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_TEXT, RateSnack().getUri(this).toString())
intent.type = "text/plain"
startActivity(Intent.createChooser(intent, null))
},
menu_rate to {
startActivityFromURL(RateSnack().getUri(this))
},
menu_print to {
AlertDialog.Builder(this)
.setSingleChoiceItems(arrayOf("This chapter", "Everything"), 0, null)
.setTitle("Print")
.setPositiveButton(android.R.string.ok) { dialog, _ ->
val text = when ((dialog as AlertDialog).listView.checkedItemPosition) {
0 -> convertMarkdownToHtml(survivalContent.getMarkdown(currentUrl)!!)
else -> navigationEntryMap.joinToString("<hr/>") {
convertMarkdownToHtml(survivalContent.getMarkdown(it.entry.url)!!)
}
}
val newWebView = if (Build.VERSION.SDK_INT >= 17) {
WebView(createConfigurationContext(Configuration()))
} else {
WebView(this@MainActivity)
}
newWebView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?) = false
override fun onPageFinished(view: WebView, url: String) = createWebPrintJob(view)
}
newWebView.loadDataWithBaseURL("file:///android_asset/md/", text, "text/HTML", "UTF-8", null)
}
.setNegativeButton(android.R.string.cancel, null)
.show()
},
menu_bookmark to {
val bookmarkBinding: BookmarkBinding = BookmarkBinding.inflate(layoutInflater)
val view = inflate(R.layout.bookmark)
bookmarkBinding.bookmarkTopicText.text = currentTopicName
AlertDialog.Builder(this)
.setView(view)
.setTitle(string.add_bookmark)
.setPositiveButton(string.bookmark) { _: DialogInterface, _: Int ->
Bookmarks.persist(Bookmark(currentUrl, bookmarkBinding.bookmarkCommentEdit.text.toString(), ""))
}
.setNegativeButton(string.cancel) { _: DialogInterface, _: Int -> }
.show()
}
)
override fun onOptionsItemSelected(item: MenuItem) = if (optionsMap.containsKey(item.itemId)) {
(optionsMap[item.itemId] ?: error("selected item ${item.itemId} not in optionsMap")).invoke()
true
} else {
drawerToggle.onOptionsItemSelected(item)
}
@TargetApi(19)
private fun createWebPrintJob(webView: WebView) {
val printManager = getSystemService(Context.PRINT_SERVICE) as PrintManager
val jobName = getString(string.app_name) + " Document"
val printAdapter = WebViewCompat.createPrintDocumentAdapter(webView, jobName)
try {
printManager.print(jobName, printAdapter, PrintAttributes.Builder().build())
} catch (iae: IllegalArgumentException) {
AlertDialog.Builder(this)
.setMessage("Problem printing: " + iae.message)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
private fun processURL(url: String): Boolean {
mainBinding.mainAppbar.setExpanded(true)
Timber.i("processing url $url")
VisitedURLStore.add(url)
val titleResByURL = getTitleResByURL(url) ?: return false
currentUrl = url
currentTopicName = getString(titleResByURL)
supportActionBar?.subtitle = currentTopicName
State.lastVisitedURL = url
survivalContent.getMarkdown(currentUrl)?.let { markdown ->
textInput = splitText(markdown)
val newAdapter = MarkdownRecyclerAdapter(textInput, imageWidth(), onURLClick)
mainBinding.mainContentRecycler.adapter = newAdapter
if (!State.searchTerm.isNullOrBlank()) {
newAdapter.notifyDataSetChanged()
newAdapter.getPositionForWord(State.searchTerm!!)?.let {
mainBinding.mainContentRecycler.scrollToPosition(it)
}
}
mainBinding.mainNavigationView.refresh()
return true
}
return false
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
drawerToggle.syncState()
}
override fun onResume() {
super.onResume()
mainBinding.mainNavigationView.refresh()
mainBinding.mainFab.setVisibility(State.allowEdit())
if (lastFontSize != State.getFontSize()) {
mainBinding.mainContentRecycler.adapter?.notifyDataSetChanged()
lastFontSize = State.getFontSize()
}
if (lastAllowSelect != State.allowSelect()) {
recreate()
lastAllowSelect = State.allowSelect()
}
if (lastNightMode != State.nightModeString()) {
recreate()
lastNightMode = State.nightModeString()
}
invalidateOptionsMenu()
}
}
|
gpl-3.0
|
e988eec66832f11dda89e201e0f5fb61
| 38.164384 | 139 | 0.634558 | 5.32204 | false | false | false | false |
jean79/yested
|
src/main/docsite/effects/slide.kt
|
2
|
2121
|
package effects
import net.yested.div
import net.yested.bootstrap.btsButton
import net.yested.Div
import net.yested.bootstrap.panel
import net.yested.bootstrap.Panel
import net.yested.with
import net.yested.SlideUp
import net.yested.SlideDown
import net.yested.bootstrap.row
import net.yested.bootstrap.Medium
import net.yested.bootstrap.pageHeader
/**
* Created by jean79 on 21/01/15.
*/
fun createEffectsSection(): Div {
var visible: Boolean = true
val target = Panel() with {
heading { +"Sample component" }
content {
+"Sample Text"
br()
emph { +"Some bolded text" }
br()
a() { +"Some link" }
}
}
return div {
row {
col(Medium(12)) {
pageHeader { h3 { +"Slide Up/Down" } }
}
}
row {
col(Medium(6)) {
+"Effects are applied directly on components:"
code(lang="kotlin", content = "SlideUp().apply(component)")
h4 { +"Demo" }
btsButton(label = { +"Toogle it" }) {
if (visible) {
SlideUp().apply(target)
} else {
SlideDown().apply(target)
}
visible = !visible
}
//+" Press button to slide up/down panel. "
br()
br()
+target
}
col(Medium(6)) {
h4 { +"Source code"}
code(lang = "kotlin", content =
"""var visible: Boolean = true
val target = Panel() with {
heading { +"Sample component" }
content {
+"Sample Text"
br()
emph { +"Some bolded text" }
br()
br()
a() { +"Some text" }
}
}
...
div {
btsButton(label = { +"Toogle it" }) {
if (visible) {
SlideUp().apply(target)
} else {
SlideDown().apply(target)
}
visible = !visible
}
br()
+target
}""")
}
}
}
}
|
mit
|
5a7626c43ed804b4fc698a8808479153
| 22.065217 | 75 | 0.460632 | 4.208333 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/translations/lang/colors/LangSyntaxHighlighter.kt
|
1
|
1715
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.lang.colors
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
class LangSyntaxHighlighter(private val lexer: Lexer) : SyntaxHighlighterBase() {
override fun getHighlightingLexer() = lexer
override fun getTokenHighlights(tokenType: IElementType?) =
when (tokenType) {
LangTypes.KEY, LangTypes.DUMMY -> KEY_KEYS
LangTypes.EQUALS -> EQUALS_KEYS
LangTypes.VALUE -> VALUE_KEYS
LangTypes.COMMENT -> COMMENT_KEYS
else -> EMPTY_KEYS
}
companion object {
val KEY = TextAttributesKey.createTextAttributesKey("I18N_KEY", DefaultLanguageHighlighterColors.KEYWORD)
val EQUALS =
TextAttributesKey.createTextAttributesKey("I18N_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN)
val VALUE = TextAttributesKey.createTextAttributesKey("I18N_VALUE", DefaultLanguageHighlighterColors.STRING)
val COMMENT =
TextAttributesKey.createTextAttributesKey("I18N_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val KEY_KEYS = arrayOf(KEY)
val EQUALS_KEYS = arrayOf(EQUALS)
val VALUE_KEYS = arrayOf(VALUE)
val COMMENT_KEYS = arrayOf(COMMENT)
val EMPTY_KEYS = emptyArray<TextAttributesKey>()
}
}
|
mit
|
223f663a0b4817bb8d903b07547926de
| 36.282609 | 117 | 0.724781 | 4.91404 | false | false | false | false |
arkon/LISTEN.moe-Unofficial-Android-App
|
app/src/main/java/me/echeung/moemoekyun/client/api/APIClient.kt
|
1
|
7918
|
package me.echeung.moemoekyun.client.api
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.Input
import com.apollographql.apollo.api.cache.http.HttpCachePolicy
import com.apollographql.apollo.cache.http.ApolloHttpCache
import com.apollographql.apollo.coroutines.toDeferred
import com.apollographql.apollo.coroutines.toFlow
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import me.echeung.moemoekyun.CheckFavoriteQuery
import me.echeung.moemoekyun.FavoriteMutation
import me.echeung.moemoekyun.FavoritesQuery
import me.echeung.moemoekyun.LoginMfaMutation
import me.echeung.moemoekyun.LoginMutation
import me.echeung.moemoekyun.QueueQuery
import me.echeung.moemoekyun.QueueSubscription
import me.echeung.moemoekyun.RegisterMutation
import me.echeung.moemoekyun.RequestSongMutation
import me.echeung.moemoekyun.SongQuery
import me.echeung.moemoekyun.SongsQuery
import me.echeung.moemoekyun.UserQuery
import me.echeung.moemoekyun.UserQueueSubscription
import me.echeung.moemoekyun.client.RadioClient
import me.echeung.moemoekyun.client.api.data.SongsCache
import me.echeung.moemoekyun.client.api.data.transform
import me.echeung.moemoekyun.client.api.library.Library
import me.echeung.moemoekyun.client.auth.AuthUtil
import me.echeung.moemoekyun.client.model.Song
import me.echeung.moemoekyun.client.model.User
import me.echeung.moemoekyun.client.model.search
import okhttp3.OkHttpClient
class APIClient(
okHttpClient: OkHttpClient,
apolloCache: ApolloHttpCache,
private val authUtil: AuthUtil
) {
private val scope = CoroutineScope(Job() + Dispatchers.Main)
private val client: ApolloClient
private val songsCache: SongsCache
init {
// val transportFactory = WebSocketSubscriptionTransport.Factory(webSocketUrl, okHttpClient)
client = ApolloClient.builder()
.serverUrl(Library.API_BASE)
.httpCache(apolloCache)
.defaultHttpCachePolicy(DEFAULT_CACHE_POLICY)
.okHttpClient(okHttpClient)
// .subscriptionTransportFactory(transportFactory)
.build()
songsCache = SongsCache(this)
}
/**
* Authenticates to the radio.
*
* @param username User's username.
* @param password User's password.
*/
suspend fun authenticate(username: String, password: String): Pair<LoginState, String> {
val response = client.mutate(LoginMutation(username, password))
.toDeferred()
.await()
val userToken = response.data?.login?.token!!
if (response.data?.login?.mfa!!) {
authUtil.mfaToken = userToken
return Pair(LoginState.REQUIRE_OTP, userToken)
}
authUtil.authToken = userToken
return Pair(LoginState.COMPLETE, userToken)
}
/**
* Second step for MFA authentication.
*
* @param otpToken User's one-time password token.
*/
suspend fun authenticateMfa(otpToken: String): String {
val response = client.mutate(LoginMfaMutation(otpToken))
.toDeferred()
.await()
val userToken = response.data?.loginMFA?.token!!
authUtil.authToken = userToken
authUtil.clearMfaAuthToken()
return userToken
}
/**
* Register a new user.
*/
suspend fun register(email: String, username: String, password: String) {
client.mutate(RegisterMutation(email, username, password))
.toDeferred()
.await()
}
/**
* Gets the user information (id and username).
*/
suspend fun getUserInfo(): User {
val response = client.query(UserQuery("@me"))
.toDeferred()
.await()
return response.data?.user!!.transform()
}
/**
* Gets a list of all the user's favorited songs.
*/
suspend fun getUserFavorites(): List<Song> {
// TODO: do actual pagination
val response = client.query(FavoritesQuery("@me", 0, 2500, Input.optional(RadioClient.isKpop())))
.toDeferred()
.await()
return response.data?.user?.favorites?.favorites
?.mapNotNull { it?.song }
?.map { it.transform() }
?: emptyList()
}
/**
* Gets the favorited status of a list of songs.
*
* @param songIds IDs of songs to check status of.
*/
suspend fun isFavorite(songIds: List<Int>): List<Int> {
val response = client.query(CheckFavoriteQuery(songIds))
.toDeferred()
.await()
return response.data?.checkFavorite?.filterNotNull() ?: emptyList()
}
/**
* Toggles a song's favorite status
*
* @param songId Song to update favorite status of.
*/
suspend fun toggleFavorite(songId: Int) {
client.mutate(FavoriteMutation(songId))
.toDeferred()
.await()
}
/**
* Sends a song request to the queue.
*
* @param songId Song to request.
*/
suspend fun requestSong(songId: Int) {
val response = client.mutate(RequestSongMutation(songId, Input.optional(RadioClient.isKpop())))
.toDeferred()
.await()
if (response.hasErrors()) {
throw Exception(response.errors?.get(0)?.message)
}
}
/**
* Searches for songs.
*
* @param query Search query string.
*/
suspend fun search(query: String?): List<Song> {
val songs = songsCache.getSongs()
return songs!!.search(query)
}
/**
* Gets details for a song.
*
* @param songId Song to get details for.
*/
suspend fun getSongDetails(songId: Int): Song {
val response = client.query(SongQuery(songId))
.httpCachePolicy(SONG_CACHE_POLICY)
.toDeferred()
.await()
return response.data?.song!!.transform()
}
/**
* Gets all songs.
*/
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun getAllSongs(): List<Song> {
// TODO: do actual pagination
// TODO: maintain an actual DB of song info so we don't need to query as much stuff
val response = client.query(SongsQuery(0, 50000, Input.optional(RadioClient.isKpop())))
.httpCachePolicy(SONG_CACHE_POLICY)
.toDeferred()
.await()
return response.data?.songs?.songs?.map { it.transform() } ?: emptyList()
}
/**
* Gets and subscribes to song queue info.
*/
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun getQueue(user: User) {
val queue = client.query(QueueQuery())
.toDeferred()
.await()
// callback.onQueueSuccess(response.data?.queue ?: 0)
client.subscribe(QueueSubscription(RadioClient.library.name))
.toFlow()
.onEach {
// callback.onQueueSuccess(response.data?.queue?.amount ?: 0)
}
.launchIn(scope)
// TODO: handle user change
client.subscribe(UserQueueSubscription(RadioClient.library.name, user.uuid))
.toFlow()
.onEach {
// callback.onUserQueueSuccess(
// response.data?.userQueue?.amount ?: 0,
// response.data?.userQueue?.before ?: 0
// )
}
.launchIn(scope)
}
enum class LoginState {
REQUIRE_OTP,
COMPLETE,
}
companion object {
private val DEFAULT_CACHE_POLICY = HttpCachePolicy.NETWORK_FIRST
private val SONG_CACHE_POLICY = HttpCachePolicy.CACHE_FIRST.expireAfter(1, TimeUnit.DAYS)
}
}
|
mit
|
4245cc9d7f5a959e8c0113281f0ce9a1
| 29.809339 | 105 | 0.640187 | 4.443322 | false | false | false | false |
inorichi/tachiyomi-extensions
|
multisrc/overrides/eromuse/erofus/src/Erofus.kt
|
1
|
9948
|
package eu.kanade.tachiyomi.extension.en.erofus
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.multisrc.eromuse.EroMuse
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.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Response
import rx.Observable
@ExperimentalStdlibApi
@Nsfw
class Erofus : EroMuse("Erofus", "https://www.erofus.com") {
override val albumSelector = "a.a-click"
override val topLevelPathSegment = "comics"
override fun fetchPopularManga(page: Int): Observable<MangasPage> = fetchManga("$baseUrl/comics/various-authors?sort=viewed&page=1", page, "viewed")
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> = fetchManga("$baseUrl/comics/various-authors?sort=recent&page=1", page, "recent")
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
if (page == 1) {
pageStack.clear()
val filterList = if (filters.isEmpty()) getFilterList() else filters
currentSortingMode = filterList.filterIsInstance<SortFilter>().first().toQueryValue()
if (query.isNotBlank()) {
// TODO possibly add genre search if a decent list of them can be built
pageStack.addLast(StackItem("$baseUrl/?search=$query&sort=$currentSortingMode&page=1", SEARCH_RESULTS_OR_BASE))
} else {
val albumFilter = filterList.filterIsInstance<AlbumFilter>().first().selection()
val url = (baseUrl + albumFilter.pathSegments).toHttpUrl().newBuilder()
.addQueryParameter("sort", currentSortingMode)
.addQueryParameter("page", "1")
pageStack.addLast(StackItem(url.toString(), albumFilter.pageType))
}
}
return client.newCall(stackRequest())
.asObservableSuccess()
.map { response -> parseManga(response.asJsoup()) }
}
override fun mangaDetailsParse(response: Response): SManga {
return SManga.create().apply {
with(response.asJsoup()) {
setUrlWithoutDomain(response.request.url.toString())
thumbnail_url = select("$albumSelector img").firstOrNull()?.imgAttr()
author = when (getAlbumType(url)) {
AUTHOR -> {
// eg. https://www.erofus.com/comics/witchking00-comics/adventure-time
// eg. https://www.erofus.com/comics/mcc-comics/bearing-gifts/bearing-gifts-issue-1
select("div.navigation-breadcrumb li:nth-child(3)").text()
}
VARIOUS_AUTHORS -> {
// eg. https://www.erofus.com/comics/various-authors/artdude41/bat-vore
select("div.navigation-breadcrumb li:nth-child(5)").text()
}
else -> null
}
genre = select("div.album-tag-container a").joinToString { it.text() }
}
}
}
override val linkedChapterSelector = "a.a-click:has(img)[href^=/comics/]"
override val pageThumbnailSelector = "a.a-click:has(img)[href*=/pic/] img"
override val pageThumbnailPathSegment = "/thumb/"
override val pageFullSizePathSegment = "/medium/"
override fun getAlbumList() = arrayOf(
Triple("All Authors", "", SEARCH_RESULTS_OR_BASE),
Triple("Various Authors", "/comics/various-authors", VARIOUS_AUTHORS),
Triple("Hentai and Manga English", "/comics/hentai-and-manga-english", VARIOUS_AUTHORS),
Triple("TabooLicious.xxx Comics", "/comics/taboolicious_xxx-comics", AUTHOR),
Triple("IllustratedInterracial.com Comics", "/comics/illustratedinterracial_com-comics", AUTHOR),
Triple("ZZZ Comics", "/comics/zzz-comics", AUTHOR),
Triple("JohnPersons.com Comics", "/comics/johnpersons_com-comics", AUTHOR),
Triple("For members only", "/", AUTHOR),
Triple("PalComix Comics", "/comics/palcomix-comics", AUTHOR),
Triple("Melkormancin.com Comics", "/comics/melkormancin_com-comics", AUTHOR),
Triple("TG Comics", "/comics/tg-comics", AUTHOR),
Triple("ShadBase Comics", "/comics/shadbase-comics", AUTHOR),
Triple("Filthy Figments Comics", "/comics/filthy-figments-comics", AUTHOR),
Triple("Witchking00 Comics", "/comics/witchking00-comics", AUTHOR),
Triple("Tease Comix", "/comics/tease-comix", AUTHOR),
Triple("PrismGirls Comics", "/comics/prismgirls-comics", AUTHOR),
Triple("Croc Comics", "/comics/croc-comics", AUTHOR),
Triple("CRAZYXXX3DWORLD Comics", "/comics/crazyxxx3dworld-comics", AUTHOR),
Triple("Moiarte Comics", "/comics/moiarte-comics", AUTHOR),
Triple("Nicole Heat Comics", "/comics/nicole-heat-comics", AUTHOR),
Triple("Expansion Comics", "/comics/expansion-comics", AUTHOR),
Triple("DizzyDills Comics", "/comics/dizzydills-comics", AUTHOR),
Triple("Hustler Cartoons", "/comics/hustler-cartoons", AUTHOR),
Triple("ArtOfJaguar Comics", "/comics/artofjaguar-comics", AUTHOR),
Triple("Grow Comics", "/comics/grow-comics", AUTHOR),
Triple("Bimbo Story Club Comics", "/comics/bimbo-story-club-comics", AUTHOR),
Triple("HentaiTNA.com Comics", "/comics/hentaitna_com-comics", AUTHOR),
Triple("ZZomp Comics", "/comics/zzomp-comics", AUTHOR),
Triple("Seiren.com.br Comics", "/comics/seiren_com_br-comics", AUTHOR),
Triple("DukesHardcoreHoneys.com Comics", "/comics/dukeshardcorehoneys_com-comics", AUTHOR),
Triple("Frozen Parody Comics", "/comics/frozen-parody-comics", AUTHOR),
Triple("Giantess Club Comics", "/comics/giantess-club-comics", AUTHOR),
Triple("Ultimate3DPorn Comics", "/comics/ultimate3dporn-comics", AUTHOR),
Triple("Sean Harrington Comics", "/comics/sean-harrington-comics", AUTHOR),
Triple("Central Comics", "/comics/central-comics", AUTHOR),
Triple("Mana World Comics", "/comics/mana-world-comics", AUTHOR),
Triple("The Foxxx Comics", "/comics/the-foxxx-comics", AUTHOR),
Triple("Bloody Sugar Comics", "/comics/bloody-sugar-comics", AUTHOR),
Triple("Deuce Comics", "/comics/deuce-comics", AUTHOR),
Triple("Adult Empire Comics", "/comics/adult-empire-comics", AUTHOR),
Triple("SuperHeroineComixxx", "/comics/superheroinecomixxx", AUTHOR),
Triple("Sluttish Comics", "/comics/sluttish-comics", AUTHOR),
Triple("Damn3D Comics", "/comics/damn3d-comics", AUTHOR),
Triple("Fake Celebrities Sex Pictures", "/comics/fake-celebrities-sex-pictures", AUTHOR),
Triple("Secret Chest Comics", "/comics/secret-chest-comics", AUTHOR),
Triple("Project Bellerophon Comics", "/comics/project-bellerophon-comics", AUTHOR),
Triple("Smudge Comics", "/comics/smudge-comics", AUTHOR),
Triple("Superheroine Central Comics", "/comics/superheroine-central-comics", AUTHOR),
Triple("Jay Marvel Comics", "/comics/jay-marvel-comics", AUTHOR),
Triple("Fred Perry Comics", "/comics/fred-perry-comics", AUTHOR),
Triple("Seduced Amanda Comics", "/comics/seduced-amanda-comics", AUTHOR),
Triple("VGBabes Comics", "/comics/vgbabes-comics", AUTHOR),
Triple("SodomSluts.com Comics", "/comics/sodomsluts_com-comics", AUTHOR),
Triple("AKABUR Comics", "/comics/akabur-comics", AUTHOR),
Triple("eBluberry Comics", "/comics/ebluberry-comics", AUTHOR),
Triple("InterracialComicPorn.com Comics", "/comics/interracialcomicporn_com-comics", AUTHOR),
Triple("Dubh3d-Dubhgilla Comics", "/comics/dubh3d-dubhgilla-comics", AUTHOR),
Triple("Gush Bomb Comix", "/comics/gush-bomb-comix", AUTHOR),
Triple("Chiyoji Tomo Comics", "/comics/chiyoji-tomo-comics", AUTHOR),
Triple("Mangrowing Comics", "/comics/mangrowing-comics", AUTHOR),
Triple("eAdultComics Collection", "/comics/eadultcomics-collection", AUTHOR),
Triple("Skulltitti Comics", "/comics/skulltitti-comics", AUTHOR),
Triple("James Lemay Comics", "/comics/james-lemay-comics", AUTHOR),
Triple("TalesOfPleasure.com Comics", "/comics/talesofpleasure_com-comics", AUTHOR),
Triple("Eden Comics", "/comics/eden-comics", AUTHOR),
Triple("WorldOfPeach Comics", "/comics/worldofpeach-comics", AUTHOR),
Triple("Daniel40 Comics", "/comics/daniel40-comics", AUTHOR),
Triple("DontFapGirl Comics", "/comics/dontfapgirl-comics", AUTHOR),
Triple("Wingbird Comics", "/comics/wingbird-comics", AUTHOR),
Triple("Intrigue3d.com Comics", "/comics/intrigue3d_com-comics", AUTHOR),
Triple("Hentaikey Comics", "/comics/hentaikey-comics", AUTHOR),
Triple("Kamina1978 Comics", "/comics/kamina1978-comics", AUTHOR),
Triple("3DPerils Comics", "/comics/3dperils-comics", AUTHOR),
Triple("Tracy Scops Comics", "/comics/tracy-scops-comics", AUTHOR),
Triple("Shemale3D Comics", "/comics/shemale3d-comics", AUTHOR),
Triple("InterracialSex3D.com Comics", "/comics/Interracialsex3d-Com-Comix", AUTHOR),
Triple("MyHentaiGrid Comics", "/comics/myhentaigrid-comics", AUTHOR),
Triple("Magnifire Comics", "/comics/magnifire-comics", AUTHOR),
Triple("Reptileye Comics", "/comics/reptileye-comics", AUTHOR),
Triple("ProjectPinkXXX.com Comics", "/comics/projectpinkxxx_com-comics", AUTHOR),
Triple("CallMePlisskin Comics", "/comics/callmeplisskin-comics", AUTHOR)
)
override fun getSortList() = arrayOf(
Pair("Viewed", "viewed"),
Pair("Liked", "liked"),
Pair("Date", "recent"),
Pair("A-Z", "az")
)
}
|
apache-2.0
|
20decbb9e4e1b06a2c55489f6a1aefca
| 58.568862 | 153 | 0.656313 | 3.756798 | false | false | false | false |
felipebz/sonar-plsql
|
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/CommitRollbackCheck.kt
|
1
|
2157
|
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.typeIs
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlKeyword
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MAJOR)
@ConstantRemediation("30min")
@RuleInfo(scope = RuleInfo.Scope.MAIN)
@ActivatedByDefault
class CommitRollbackCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.COMMIT_STATEMENT, PlSqlGrammar.ROLLBACK_STATEMENT)
}
override fun visitNode(node: AstNode) {
val scope = context.currentScope
var outerScope = scope
while (outerScope?.outer() != null) {
outerScope = outerScope.outer()
}
val isRollbackToSavepoint = node.typeIs(PlSqlGrammar.ROLLBACK_STATEMENT) && node.hasDirectChildren(PlSqlKeyword.TO)
val currentScopeIsAutonomousTransaction = scope?.isAutonomousTransaction ?: false
val isInsideABlockStatement = outerScope?.tree()?.typeIs(PlSqlGrammar.BLOCK_STATEMENT) ?: false
if (!isRollbackToSavepoint && !currentScopeIsAutonomousTransaction && !isInsideABlockStatement) {
addLineIssue(getLocalizedMessage(), node.tokenLine, node.tokenValue)
}
}
}
|
lgpl-3.0
|
5d26e2f3af0b13ed589a73d51576da43
| 37.517857 | 123 | 0.738526 | 4.411043 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.