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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cashapp/sqldelight | test-util/src/main/kotlin/app/cash/sqldelight/test/util/FixtureCompiler.kt | 1 | 6733 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.test.util
import app.cash.sqldelight.core.compiler.SqlDelightCompiler
import app.cash.sqldelight.core.lang.MigrationFile
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.dialect.api.SqlDelightDialect
import app.cash.sqldelight.dialects.sqlite_3_18.SqliteDialect
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.junit.rules.TemporaryFolder
import java.io.File
private typealias CompilationMethod = (Module, SqlDelightDialect, SqlDelightQueriesFile, (String) -> Appendable) -> Unit
object FixtureCompiler {
fun compileSql(
sql: String,
temporaryFolder: TemporaryFolder,
overrideDialect: SqlDelightDialect = SqliteDialect(),
compilationMethod: CompilationMethod = SqlDelightCompiler::writeInterfaces,
fileName: String = "Test.sq",
treatNullAsUnknownForEquality: Boolean = false,
generateAsync: Boolean = false,
): CompilationResult {
writeSql(sql, temporaryFolder, fileName)
return compileFixture(
temporaryFolder.fixtureRoot().path,
compilationMethod,
overrideDialect = overrideDialect,
treatNullAsUnknownForEquality = treatNullAsUnknownForEquality,
generateAsync = generateAsync,
)
}
fun writeSql(
sql: String,
temporaryFolder: TemporaryFolder,
fileName: String,
) {
val srcRootDir = temporaryFolder.fixtureRoot().apply { mkdirs() }
val fixtureSrcDir = File(srcRootDir, "com/example").apply { mkdirs() }
File(fixtureSrcDir, fileName).apply {
createNewFile()
writeText(sql)
}
}
fun parseSql(
sql: String,
temporaryFolder: TemporaryFolder,
fileName: String = "Test.sq",
dialect: SqlDelightDialect = SqliteDialect(),
treatNullAsUnknownForEquality: Boolean = false,
generateAsync: Boolean = false,
): SqlDelightQueriesFile {
writeSql(sql, temporaryFolder, fileName)
val errors = mutableListOf<String>()
val parser = TestEnvironment(dialect = dialect, treatNullAsUnknownForEquality = treatNullAsUnknownForEquality, generateAsync = generateAsync)
val environment = parser.build(
temporaryFolder.fixtureRoot().path,
createAnnotationHolder(errors),
)
if (errors.isNotEmpty()) {
throw AssertionError("Got unexpected errors\n\n$errors")
}
var file: SqlDelightQueriesFile? = null
environment.forSourceFiles {
if (it.name == fileName) file = it as SqlDelightQueriesFile
}
return file!!
}
fun compileFixture(
fixtureRoot: String,
compilationMethod: CompilationMethod = SqlDelightCompiler::writeInterfaces,
overrideDialect: SqlDelightDialect = SqliteDialect(),
generateDb: Boolean = true,
writer: ((String) -> Appendable)? = null,
outputDirectory: File = File(fixtureRoot, "output"),
deriveSchemaFromMigrations: Boolean = false,
treatNullAsUnknownForEquality: Boolean = false,
generateAsync: Boolean = false,
): CompilationResult {
val compilerOutput = mutableMapOf<File, StringBuilder>()
val errors = mutableListOf<String>()
val sourceFiles = StringBuilder()
val parser = TestEnvironment(outputDirectory, deriveSchemaFromMigrations, treatNullAsUnknownForEquality, overrideDialect, generateAsync)
val fixtureRootDir = File(fixtureRoot)
require(fixtureRootDir.exists()) { "$fixtureRoot does not exist" }
val environment = parser.build(fixtureRootDir.path, createAnnotationHolder(errors))
val fileWriter = writer ?: fileWriter@{ fileName: String ->
val builder = StringBuilder()
compilerOutput += File(fileName) to builder
return@fileWriter builder
}
var file: SqlDelightQueriesFile? = null
var topMigration: MigrationFile? = null
environment.forSourceFiles { psiFile ->
psiFile.log(sourceFiles)
if (psiFile is SqlDelightQueriesFile) {
if (errors.isEmpty()) {
compilationMethod(environment.module, environment.dialect, psiFile, fileWriter)
}
file = psiFile
} else if (psiFile is MigrationFile) {
if (topMigration == null || psiFile.order > topMigration!!.order) {
topMigration = psiFile
}
}
}
if (topMigration != null) {
SqlDelightCompiler.writeInterfaces(
file = topMigration!!,
output = fileWriter,
includeAll = true,
)
}
if (generateDb) {
SqlDelightCompiler.writeDatabaseInterface(environment.module, file!!, "testmodule", fileWriter)
SqlDelightCompiler.writeImplementations(
environment.module,
file!!,
"testmodule",
fileWriter,
)
}
return CompilationResult(outputDirectory, compilerOutput, errors, sourceFiles.toString(), file!!)
}
private fun createAnnotationHolder(
errors: MutableList<String>,
) = object : SqlAnnotationHolder {
override fun createErrorAnnotation(element: PsiElement, s: String) {
val documentManager = PsiDocumentManager.getInstance(element.project)
val name = element.containingFile.name
val document = documentManager.getDocument(element.containingFile)!!
val lineNum = document.getLineNumber(element.textOffset)
val offsetInLine = element.textOffset - document.getLineStartOffset(lineNum)
errors += "$name: (${lineNum + 1}, $offsetInLine): $s"
}
}
private fun PsiFile.log(sourceFiles: StringBuilder) {
sourceFiles.append("$name:\n")
printTree {
sourceFiles.append(" ")
sourceFiles.append(this)
}
}
private fun PsiElement.printTree(printer: (String) -> Unit) {
printer("$this\n")
children.forEach { child ->
child.printTree { printer(" $it") }
}
}
data class CompilationResult(
val outputDirectory: File,
val compilerOutput: Map<File, StringBuilder>,
val errors: List<String>,
val sourceFiles: String,
val compiledFile: SqlDelightQueriesFile,
)
}
fun TemporaryFolder.fixtureRoot() = File(root, "src/test/test-fixture")
| apache-2.0 | 8c30439ceb06392729064e3443e6292c | 33.528205 | 145 | 0.71454 | 4.643448 | false | false | false | false |
shlusiak/Freebloks-Android | server/src/main/java/de/saschahlusiak/freebloks/server/JNIServer.kt | 1 | 2138 | package de.saschahlusiak.freebloks.server
import android.util.Log
import de.saschahlusiak.freebloks.model.Game
import de.saschahlusiak.freebloks.model.GameMode
import de.saschahlusiak.freebloks.model.Shape
object JNIServer {
private val tag = JNIServer::class.java.simpleName
@Suppress("FunctionName")
private external fun get_number_of_processors(): Int
@Suppress("FunctionName")
private external fun native_run_server(
game_mode: Int,
field_size_x: Int,
field_size_y: Int,
stones: IntArray?,
ki_mode: Int,
ki_threads: Int
): Int
@Suppress("FunctionName")
private external fun native_resume_server(
field_size_x: Int,
field_size_y: Int,
current_player: Int,
spieler: IntArray,
field_data: IntArray,
player_stone_data: IntArray,
game_mode: Int,
ki_mode: Int,
ki_threads: Int
): Int
fun runServerForNewGame(gameMode: GameMode, size: Int, stones: IntArray?, kiMode: Int): Int {
val threads = get_number_of_processors()
Log.d(tag, "spawning server with $threads threads")
return native_run_server(gameMode.ordinal, size, size, stones, kiMode, threads)
}
fun runServerForExistingGame(game: Game, kiMode: Int): Int {
val threads = get_number_of_processors()
Log.d(tag, "spawning server with $threads threads")
val board = game.board
val playerStonesAvailable = IntArray(Shape.COUNT * 4)
for (player in 0..3) {
for (shape in 0 until Shape.COUNT) {
playerStonesAvailable[player * Shape.COUNT + shape] = board.getPlayer(player).getStone(shape).available
}
}
return native_resume_server(
board.width,
board.height,
game.currentPlayer,
game.playerTypes,
board.fields,
playerStonesAvailable,
game.gameMode.ordinal,
kiMode,
threads
)
}
init {
Log.d(tag, "loading server.so")
System.loadLibrary("server")
}
} | gpl-2.0 | 55f98971131ba3625fb03a090dfcda18 | 28.30137 | 119 | 0.611319 | 4.003745 | false | false | false | false |
digammas/damas | solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/model/JcrPathFinder.kt | 1 | 1332 | package solutions.digamma.damas.jcr.model
import solutions.digamma.damas.common.MisuseException
import solutions.digamma.damas.common.WorkspaceException
import solutions.digamma.damas.content.PathFinder
import solutions.digamma.damas.entity.Entity
import solutions.digamma.damas.jcr.common.Exceptions
import solutions.digamma.damas.jcr.session.JcrSessionConsumer
import java.nio.file.Paths
import javax.jcr.RepositoryException
/**
* An interface that provide path finding functionality.
*
* @author Ahmad Shahwan
*/
internal interface JcrPathFinder<T : Entity> : JcrSessionConsumer, PathFinder<T> {
/**
* This method converts a thrown exception into a [WorkspaceException].
* It also normalizes the path to a JCR compatible one.
*/
@Throws(WorkspaceException::class)
override fun find(path: String): T = Exceptions.check {
var p = Paths.get(path).normalize().toString()
if (p.startsWith("../")) {
throw MisuseException("Invalid relative path.")
}
if (p == "") p = "."
this.doFind(p)
}
/**
* Perform path look-up.
*
* @param path
* @return
* @throws RepositoryException
* @throws WorkspaceException
*/
@Throws(RepositoryException::class, WorkspaceException::class)
fun doFind(path: String): T
}
| mit | 8e767cde86acf4f4ca8661b51508b73d | 29.976744 | 82 | 0.695946 | 4.136646 | false | false | false | false |
ToxicBakery/ViewPagerTransforms | library/src/main/java/com/ToxicBakery/viewpager/transforms/ABaseTransformer.kt | 1 | 5390 | /*
* Copyright 2014 Toxic Bakery
*
* 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.ToxicBakery.viewpager.transforms
import android.support.v4.view.ViewPager.PageTransformer
import android.view.View
abstract class ABaseTransformer : PageTransformer {
/**
* Indicates if the default animations of the view pager should be used.
*
* @return
*/
protected open val isPagingEnabled: Boolean
get() = false
/**
* Called each [.transformPage].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected abstract fun onTransform(page: View, position: Float)
/**
* Apply a property transformation to the given page. For most use cases, this method should not be overridden.
* Instead use [.transformPage] to perform typical transformations.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
override fun transformPage(page: View, position: Float) {
val clampedPosition = clampPosition(position)
onPreTransform(page, clampedPosition)
onTransform(page, clampedPosition)
onPostTransform(page, clampedPosition)
}
/**
* Clamp the position. This step is required for some Android 4 devices.
* <p>
* The position is dependant on the range of the ViewPager and whether it supports infinite scrolling in both
* directions.
*
* On some devices it returns the position as NaN, so we set 0 as the fallback value
*
* @param position Position of page relative to the current front-and-center position of the pager.
* @return A value between -1 and 1
*/
private fun clampPosition(position: Float): Float {
return when {
position < -1f -> -1f
position > 1f -> 1f
position.isNaN() -> 0f
else -> position
}
}
/**
* If the position offset of a fragment is less than negative one or greater than one, returning true will set the
* fragment alpha to 0f. Otherwise fragment alpha is always defaulted to 1f.
*
* @return
*/
protected open fun hideOffscreenPages(): Boolean {
return true
}
/**
* Called each [.transformPage] before {[.onTransform].
*
*
* The default implementation attempts to reset all view properties. This is useful when toggling transforms that do
* not modify the same page properties. For instance changing from a transformation that applies rotation to a
* transformation that fades can inadvertently leave a fragment stuck with a rotation or with some degree of applied
* alpha.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected open fun onPreTransform(page: View, position: Float) {
val width = page.width.toFloat()
page.rotationX = 0f
page.rotationY = 0f
page.rotation = 0f
page.scaleX = 1f
page.scaleY = 1f
page.pivotX = 0f
page.pivotY = 0f
page.translationY = 0f
page.translationX = if (isPagingEnabled) 0f else -width * position
if (hideOffscreenPages()) {
page.alpha = if (position <= -1f || position >= 1f) 0f else 1f
page.isEnabled = false
} else {
page.isEnabled = true
page.alpha = 1f
}
}
/**
* Called each [.transformPage] after [.onTransform].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected open fun onPostTransform(page: View, position: Float) {}
companion object {
/**
* Same as [Math.min] without double casting, zero closest to infinity handling, or NaN support.
*
* @param value
* @param min
* @return
*/
@JvmStatic
protected fun min(value: Float, min: Float): Float {
return if (value < min) min else value
}
}
}
| apache-2.0 | 1d92c9a9ac6cdf3d437442c647f2d51d | 34.228758 | 120 | 0.646011 | 4.454545 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/DummyItemAdapter.kt | 1 | 7757 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.adapter
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.text.BidiFormatter
import android.support.v7.widget.RecyclerView
import android.util.SparseBooleanArray
import com.bumptech.glide.RequestManager
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.iface.IGapSupportedAdapter
import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter
import de.vanita5.twittnuker.adapter.iface.IUserListsAdapter
import de.vanita5.twittnuker.adapter.iface.IUsersAdapter
import de.vanita5.twittnuker.constant.*
import de.vanita5.twittnuker.model.*
import de.vanita5.twittnuker.extension.model.activityStatus
import de.vanita5.twittnuker.util.AsyncTwitterWrapper
import de.vanita5.twittnuker.util.TwidereLinkify
import de.vanita5.twittnuker.util.UserColorNameManager
import de.vanita5.twittnuker.util.dagger.GeneralComponent
import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder
import javax.inject.Inject
class DummyItemAdapter(
val context: Context,
override val twidereLinkify: TwidereLinkify = TwidereLinkify(null),
private val adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>? = null,
override val requestManager: RequestManager
) : IStatusesAdapter<Any>, IUsersAdapter<Any>, IUserListsAdapter<Any> {
@Inject
lateinit var preferences: SharedPreferences
@Inject
override lateinit var twitterWrapper: AsyncTwitterWrapper
@Inject
override lateinit var userColorNameManager: UserColorNameManager
@Inject
override lateinit var bidiFormatter: BidiFormatter
override var profileImageSize: String = context.getString(R.string.profile_image_size)
override var profileImageStyle: Int = 0
override var mediaPreviewStyle: Int = 0
override var textSize: Float = 0f
override var linkHighlightingStyle: Int = 0
override var nameFirst: Boolean = false
override var lightFont: Boolean = false
override var profileImageEnabled: Boolean = false
override var sensitiveContentEnabled: Boolean = false
override var mediaPreviewEnabled: Boolean = false
override var showAbsoluteTime: Boolean = false
override var friendshipClickListener: IUsersAdapter.FriendshipClickListener? = null
override var requestClickListener: IUsersAdapter.RequestClickListener? = null
override var statusClickListener: IStatusViewHolder.StatusClickListener? = null
override var userClickListener: IUsersAdapter.UserClickListener? = null
override var showAccountsColor: Boolean = false
override var useStarsForLikes: Boolean = false
override var simpleLayout: Boolean = false
override var showFollow: Boolean = true
var showCardActions: Boolean = false
private var showingActionCardPosition = RecyclerView.NO_POSITION
private val showingFullTextStates = SparseBooleanArray()
init {
GeneralComponent.get(context).inject(this)
updateOptions()
}
override fun getItemCount(): Int {
return 0
}
override fun getStatus(position: Int, raw: Boolean): ParcelableStatus {
if (adapter is ParcelableStatusesAdapter) {
return adapter.getStatus(position, raw)
} else if (adapter is VariousItemsAdapter) {
return adapter.getItem(position) as ParcelableStatus
} else if (adapter is ParcelableActivitiesAdapter) {
return adapter.getActivity(position).activityStatus!!
}
throw IndexOutOfBoundsException()
}
override fun getStatusCount(raw: Boolean) = 0
override fun getStatusId(position: Int, raw: Boolean) = ""
override fun getStatusTimestamp(position: Int, raw: Boolean) = -1L
override fun getStatusPositionKey(position: Int, raw: Boolean) = -1L
override fun getAccountKey(position: Int, raw: Boolean) = UserKey.INVALID
override fun findStatusById(accountKey: UserKey, statusId: String) = null
override fun isCardActionsShown(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return showCardActions
return showCardActions || showingActionCardPosition == position
}
override fun showCardActions(position: Int) {
if (showingActionCardPosition != RecyclerView.NO_POSITION && adapter != null) {
adapter.notifyItemChanged(showingActionCardPosition)
}
showingActionCardPosition = position
if (position != RecyclerView.NO_POSITION && adapter != null) {
adapter.notifyItemChanged(position)
}
}
override fun isFullTextVisible(position: Int): Boolean {
return showingFullTextStates.get(position)
}
override fun setFullTextVisible(position: Int, visible: Boolean) {
showingFullTextStates.put(position, visible)
if (position != RecyclerView.NO_POSITION && adapter != null) {
adapter.notifyItemChanged(position)
}
}
override fun getUser(position: Int): ParcelableUser? {
if (adapter is ParcelableUsersAdapter) {
return adapter.getUser(position)
} else if (adapter is VariousItemsAdapter) {
return adapter.getItem(position) as ParcelableUser
}
return null
}
override val userCount: Int
get() = 0
override val userListsCount: Int
get() = 0
override val gapClickListener: IGapSupportedAdapter.GapClickListener?
get() = null
override val userListClickListener: IUserListsAdapter.UserListClickListener?
get() = null
override fun getUserId(position: Int): String? {
return null
}
override fun getUserList(position: Int): ParcelableUserList? {
return null
}
override fun getUserListId(position: Int): String? {
return null
}
override fun setData(data: Any?): Boolean {
return false
}
override fun isGapItem(position: Int): Boolean {
return false
}
override fun addGapLoadingId(id: ObjectId) {
}
override fun removeGapLoadingId(id: ObjectId) {
}
fun updateOptions() {
profileImageStyle = preferences[profileImageStyleKey]
mediaPreviewStyle = preferences[mediaPreviewStyleKey]
textSize = preferences[textSizeKey].toFloat()
nameFirst = preferences[nameFirstKey]
profileImageEnabled = preferences[displayProfileImageKey]
mediaPreviewEnabled = preferences[mediaPreviewKey]
sensitiveContentEnabled = preferences[displaySensitiveContentsKey]
showCardActions = !preferences[hideCardActionsKey]
linkHighlightingStyle = preferences[linkHighlightOptionKey]
lightFont = preferences[lightFontKey]
useStarsForLikes = preferences[iWantMyStarsBackKey]
showAbsoluteTime = preferences[showAbsoluteTimeKey]
}
} | gpl-3.0 | bcee25382b25ea26eac7cb0860d0abb8 | 36.119617 | 90 | 0.732113 | 4.821007 | false | false | false | false |
slartus/4pdaClient-plus | http/src/main/java/ru/slartus/http/Translit.kt | 1 | 3314 | package ru.slartus.http
/**
* User: slinkin
* Date: 02.08.12
* Time: 14:18
*/
import java.util.Hashtable
@Suppress("unused")
object Translit {
private const val NEUTRAL = 0
private const val UPPER = 1
private const val LOWER = 2
internal val map: Hashtable<Char, String> = makeTranslitMap()
private fun makeTranslitMap(): Hashtable<Char, String> {
val map = Hashtable<Char, String>()
map['а'] = "a"
map['б'] = "b"
map['в'] = "v"
map['г'] = "g"
map['д'] = "d"
map['е'] = "e"
map['ё'] = "yo"
map['ж'] = "zh"
map['з'] = "z"
map['и'] = "i"
map['й'] = "j"
map['к'] = "k"
map['л'] = "l"
map['м'] = "m"
map['н'] = "n"
map['о'] = "o"
map['п'] = "p"
map['р'] = "r"
map['с'] = "s"
map['т'] = "t"
map['у'] = "u"
map['ф'] = "f"
map['х'] = "h"
map['ц'] = "ts"
map['ч'] = "ch"
map['ш'] = "sh"
map['щ'] = "sh'"
map['ъ'] = "`"
map['ы'] = "y"
map['ь'] = "'"
map['э'] = "e"
map['ю'] = "yu"
map['я'] = "ya"
map['«'] = "\""
map['»'] = "\""
map['№'] = "No"
return map
}
private fun charClass(c: Char): Int {
if (Character.isLowerCase(c))
return LOWER
return if (Character.isUpperCase(c)) UPPER else NEUTRAL
}
fun translit(text: String): String {
val len = text.length
if (len == 0)
return text
val sb = StringBuffer()
var pc = NEUTRAL
var c = text[0]
var cc = charClass(c)
for (i in 1..len) {
val nextChar = if (i < len) text[i] else ' '
val nc = charClass(nextChar)
val co = Character.toLowerCase(c)
val tr = map[co]
if (tr == null) sb.append(c)
else
when (cc) {
LOWER, NEUTRAL -> sb.append(tr)
UPPER -> if (nc == LOWER || nc == NEUTRAL && pc != UPPER) {
sb.append(Character.toUpperCase(tr[0]))
if (tr.isNotEmpty()) {
sb.append(tr.substring(1))
}
} else {
sb.append(tr.toUpperCase())
}
}
c = nextChar
pc = cc
cc = nc
}
return sb.toString()
}
fun makeFileName(text: String): String {
val len = text.length
if (len == 0)
return text
val sb = StringBuffer()
var lastAppended: Char = 0.toChar()
var count = 0
for (i in 0 until len) {
var c = text[i]
if (c.toInt() and 0xFFFF > 0x7F) {
// keep non-ASCII as is
} else if (c <= ' ' || c == '/' || c == '\\' || c == ':' || c == '~' || c == '"') {
c = '_'
}//|| c == '.'
if (c == '_' && lastAppended == '_')
continue
sb.append(c)
if (++count > 50)
break
lastAppended = c
}
return sb.toString()
}
}
| apache-2.0 | 164ccb48aec0d4f53839bd79b6755bf1 | 25.427419 | 95 | 0.382057 | 3.63707 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/wallet/WalletScreen.kt | 1 | 20138 | package com.stripe.android.link.ui.wallet
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AlertDialog
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.link.R
import com.stripe.android.link.model.LinkAccount
import com.stripe.android.link.theme.DefaultLinkTheme
import com.stripe.android.link.theme.HorizontalPadding
import com.stripe.android.link.theme.PaymentsThemeForLink
import com.stripe.android.link.theme.linkColors
import com.stripe.android.link.theme.linkShapes
import com.stripe.android.link.ui.BottomSheetContent
import com.stripe.android.link.ui.ErrorMessage
import com.stripe.android.link.ui.ErrorText
import com.stripe.android.link.ui.PrimaryButton
import com.stripe.android.link.ui.ScrollableTopLevelColumn
import com.stripe.android.link.ui.SecondaryButton
import com.stripe.android.link.ui.completePaymentButtonLabel
import com.stripe.android.link.ui.paymentmethod.SupportedPaymentMethod
import com.stripe.android.model.CardBrand
import com.stripe.android.model.ConsumerPaymentDetails
import com.stripe.android.model.CvcCheck
import com.stripe.android.ui.core.elements.CvcController
import com.stripe.android.ui.core.elements.CvcElement
import com.stripe.android.ui.core.elements.DateConfig
import com.stripe.android.ui.core.elements.IdentifierSpec
import com.stripe.android.ui.core.elements.RowController
import com.stripe.android.ui.core.elements.RowElement
import com.stripe.android.ui.core.elements.SectionElement
import com.stripe.android.ui.core.elements.SectionElementUI
import com.stripe.android.ui.core.elements.SectionSingleFieldElement
import com.stripe.android.ui.core.elements.SimpleTextElement
import com.stripe.android.ui.core.elements.SimpleTextFieldController
import com.stripe.android.ui.core.elements.TextFieldController
import com.stripe.android.uicore.text.Html
import kotlinx.coroutines.flow.flowOf
import java.util.UUID
@Preview
@Composable
private fun WalletBodyPreview() {
val paymentDetailsList = listOf(
ConsumerPaymentDetails.Card(
id = "id1",
isDefault = false,
expiryYear = 2030,
expiryMonth = 12,
brand = CardBrand.Visa,
last4 = "4242",
cvcCheck = CvcCheck.Fail
),
ConsumerPaymentDetails.Card(
id = "id2",
isDefault = false,
expiryYear = 2022,
expiryMonth = 1,
brand = CardBrand.MasterCard,
last4 = "4444",
cvcCheck = CvcCheck.Pass
),
ConsumerPaymentDetails.BankAccount(
id = "id2",
isDefault = true,
bankIconCode = "icon",
bankName = "Stripe Bank With Long Name",
last4 = "6789"
)
)
DefaultLinkTheme {
Surface {
WalletBody(
uiState = WalletUiState(
paymentDetailsList = paymentDetailsList,
supportedTypes = SupportedPaymentMethod.allTypes,
selectedItem = paymentDetailsList[2],
isExpanded = true,
errorMessage = ErrorMessage.Raw("Something went wrong")
),
primaryButtonLabel = "Pay $10.99",
expiryDateController = SimpleTextFieldController(textFieldConfig = DateConfig()),
cvcController = CvcController(cardBrandFlow = flowOf(CardBrand.Visa)),
setExpanded = {},
onItemSelected = {},
onAddNewPaymentMethodClick = {},
onEditPaymentMethod = {},
onSetDefault = {},
onDeletePaymentMethod = {},
onPrimaryButtonClick = {},
onPayAnotherWayClick = {},
showBottomSheetContent = {}
)
}
}
}
@Composable
internal fun WalletBody(
linkAccount: LinkAccount,
injector: NonFallbackInjector,
showBottomSheetContent: (BottomSheetContent?) -> Unit
) {
val viewModel: WalletViewModel = viewModel(
factory = WalletViewModel.Factory(
linkAccount,
injector
)
)
val uiState by viewModel.uiState.collectAsState()
uiState.alertMessage?.let { alertMessage ->
AlertDialog(
text = { Text(alertMessage.getMessage(LocalContext.current.resources)) },
onDismissRequest = viewModel::onAlertDismissed,
confirmButton = {
TextButton(onClick = viewModel::onAlertDismissed) {
Text(
text = stringResource(android.R.string.ok),
color = MaterialTheme.linkColors.actionLabel
)
}
}
)
}
if (uiState.paymentDetailsList.isEmpty()) {
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
} else {
WalletBody(
uiState = uiState,
primaryButtonLabel = completePaymentButtonLabel(
viewModel.args.stripeIntent,
LocalContext.current.resources
),
expiryDateController = viewModel.expiryDateController,
cvcController = viewModel.cvcController,
setExpanded = viewModel::setExpanded,
onItemSelected = viewModel::onItemSelected,
onAddNewPaymentMethodClick = viewModel::addNewPaymentMethod,
onEditPaymentMethod = viewModel::editPaymentMethod,
onSetDefault = viewModel::setDefault,
onDeletePaymentMethod = viewModel::deletePaymentMethod,
onPrimaryButtonClick = viewModel::onConfirmPayment,
onPayAnotherWayClick = viewModel::payAnotherWay,
showBottomSheetContent = showBottomSheetContent
)
}
}
@Composable
internal fun WalletBody(
uiState: WalletUiState,
primaryButtonLabel: String,
expiryDateController: TextFieldController,
cvcController: CvcController,
setExpanded: (Boolean) -> Unit,
onItemSelected: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onAddNewPaymentMethodClick: () -> Unit,
onEditPaymentMethod: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onSetDefault: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onDeletePaymentMethod: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onPrimaryButtonClick: () -> Unit,
onPayAnotherWayClick: () -> Unit,
showBottomSheetContent: (BottomSheetContent?) -> Unit
) {
var itemBeingRemoved by remember {
mutableStateOf<ConsumerPaymentDetails.PaymentDetails?>(null)
}
var openDialog by remember { mutableStateOf(false) }
itemBeingRemoved?.let {
// Launch confirmation dialog at the first recomposition after marking item for deletion
LaunchedEffect(it) {
openDialog = true
}
ConfirmRemoveDialog(
paymentDetails = it,
showDialog = openDialog
) { confirmed ->
if (confirmed) {
onDeletePaymentMethod(it)
}
openDialog = false
itemBeingRemoved = null
}
}
val focusManager = LocalFocusManager.current
LaunchedEffect(uiState.isProcessing) {
if (uiState.isProcessing) {
focusManager.clearFocus()
}
}
ScrollableTopLevelColumn {
Spacer(modifier = Modifier.height(12.dp))
Box(modifier = Modifier.animateContentSize()) {
if (uiState.isExpanded || uiState.selectedItem == null) {
ExpandedPaymentDetails(
uiState = uiState,
onItemSelected = {
onItemSelected(it)
setExpanded(false)
},
onMenuButtonClick = {
showBottomSheetContent {
WalletPaymentMethodMenu(
paymentDetails = it,
onEditClick = {
showBottomSheetContent(null)
onEditPaymentMethod(it)
},
onSetDefaultClick = {
showBottomSheetContent(null)
onSetDefault(it)
},
onRemoveClick = {
showBottomSheetContent(null)
itemBeingRemoved = it
},
onCancelClick = {
showBottomSheetContent(null)
}
)
}
},
onAddNewPaymentMethodClick = onAddNewPaymentMethodClick,
onCollapse = {
setExpanded(false)
}
)
} else {
CollapsedPaymentDetails(
selectedPaymentMethod = uiState.selectedItem,
enabled = !uiState.primaryButtonState.isBlocking,
onClick = {
setExpanded(true)
}
)
}
}
if (uiState.selectedItem is ConsumerPaymentDetails.BankAccount) {
Html(
html = stringResource(R.string.wallet_bank_account_terms).replaceHyperlinks(),
color = MaterialTheme.colors.onSecondary,
style = MaterialTheme.typography.caption,
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
urlSpanStyle = SpanStyle(
color = MaterialTheme.colors.primary
)
)
}
AnimatedVisibility(visible = uiState.errorMessage != null) {
ErrorText(
text = uiState.errorMessage?.getMessage(LocalContext.current.resources).orEmpty(),
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp)
)
}
uiState.selectedCard?.let { selectedCard ->
if (selectedCard.requiresCardDetailsRecollection) {
CardDetailsRecollectionForm(
expiryDateController = expiryDateController,
cvcController = cvcController,
isCardExpired = selectedCard.isExpired,
modifier = Modifier.padding(top = 16.dp)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
PrimaryButton(
label = primaryButtonLabel,
state = uiState.primaryButtonState,
onButtonClick = onPrimaryButtonClick,
iconEnd = R.drawable.stripe_ic_lock
)
SecondaryButton(
enabled = !uiState.primaryButtonState.isBlocking,
label = stringResource(id = R.string.wallet_pay_another_way),
onClick = onPayAnotherWayClick
)
}
}
@Composable
internal fun CardDetailsRecollectionForm(
expiryDateController: TextFieldController,
cvcController: CvcController,
isCardExpired: Boolean,
modifier: Modifier = Modifier
) {
val rowElement = remember(expiryDateController, cvcController) {
val rowFields: List<SectionSingleFieldElement> = buildList {
if (isCardExpired) {
this += SimpleTextElement(
identifier = IdentifierSpec.Generic("date"),
controller = expiryDateController
)
}
this += CvcElement(
_identifier = IdentifierSpec.CardCvc,
controller = cvcController
)
}
RowElement(
_identifier = IdentifierSpec.Generic("row_" + UUID.randomUUID().leastSignificantBits),
fields = rowFields,
controller = RowController(rowFields)
)
}
val errorTextResId = if (isCardExpired) {
R.string.wallet_update_expired_card_error
} else {
R.string.wallet_recollect_cvc_error
}
PaymentsThemeForLink {
Column(modifier) {
ErrorText(
text = stringResource(errorTextResId),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
SectionElementUI(
enabled = true,
element = SectionElement.wrap(rowElement),
hiddenIdentifiers = emptySet(),
lastTextFieldIdentifier = rowElement.fields.last().identifier
)
}
}
}
@Composable
internal fun CollapsedPaymentDetails(
selectedPaymentMethod: ConsumerPaymentDetails.PaymentDetails,
enabled: Boolean,
onClick: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(64.dp)
.border(
width = 1.dp,
color = MaterialTheme.linkColors.componentBorder,
shape = MaterialTheme.linkShapes.large
)
.clip(MaterialTheme.linkShapes.large)
.background(
color = MaterialTheme.linkColors.componentBackground,
shape = MaterialTheme.linkShapes.large
)
.clickable(
enabled = enabled,
onClick = onClick
),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(id = R.string.wallet_collapsed_payment),
modifier = Modifier.padding(
start = HorizontalPadding,
end = 8.dp
),
color = MaterialTheme.linkColors.disabledText
)
PaymentDetails(paymentDetails = selectedPaymentMethod, enabled = true)
Icon(
painter = painterResource(id = R.drawable.ic_link_chevron),
contentDescription = stringResource(id = R.string.wallet_expand_accessibility),
modifier = Modifier
.padding(end = 22.dp)
.semantics {
testTag = "ChevronIcon"
},
tint = MaterialTheme.linkColors.disabledText
)
}
}
@Composable
private fun ExpandedPaymentDetails(
uiState: WalletUiState,
onItemSelected: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onMenuButtonClick: (ConsumerPaymentDetails.PaymentDetails) -> Unit,
onAddNewPaymentMethodClick: () -> Unit,
onCollapse: () -> Unit
) {
val isEnabled = !uiState.primaryButtonState.isBlocking
Column(
modifier = Modifier
.fillMaxWidth()
.border(
width = 1.dp,
color = MaterialTheme.linkColors.componentBorder,
shape = MaterialTheme.linkShapes.large
)
.clip(MaterialTheme.linkShapes.large)
.background(
color = MaterialTheme.linkColors.componentBackground,
shape = MaterialTheme.linkShapes.large
)
) {
Row(
modifier = Modifier
.height(44.dp)
.clickable(enabled = isEnabled, onClick = onCollapse),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(id = R.string.wallet_expanded_title),
modifier = Modifier
.padding(start = HorizontalPadding, top = 20.dp),
color = MaterialTheme.colors.onPrimary,
style = MaterialTheme.typography.button
)
Spacer(modifier = Modifier.weight(1f))
Icon(
painter = painterResource(id = R.drawable.ic_link_chevron),
contentDescription = stringResource(id = R.string.wallet_expand_accessibility),
modifier = Modifier
.padding(top = 20.dp, end = 22.dp)
.rotate(180f)
.semantics {
testTag = "ChevronIcon"
},
tint = MaterialTheme.colors.onPrimary
)
}
// TODO(brnunes-stripe): Use LazyColumn, will need to write custom shape for the border
// https://juliensalvi.medium.com/custom-shape-with-jetpack-compose-1cb48a991d42
uiState.paymentDetailsList.forEach { item ->
PaymentDetailsListItem(
paymentDetails = item,
enabled = isEnabled,
isSupported = uiState.supportedTypes.contains(item.type),
isSelected = uiState.selectedItem?.id == item.id,
isUpdating = uiState.paymentMethodIdBeingUpdated == item.id,
onClick = {
onItemSelected(item)
},
onMenuButtonClick = {
onMenuButtonClick(item)
}
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.height(60.dp)
.clickable(enabled = isEnabled, onClick = onAddNewPaymentMethodClick),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_link_add_green),
contentDescription = null,
modifier = Modifier.padding(start = HorizontalPadding, end = 12.dp),
tint = Color.Unspecified
)
Text(
text = stringResource(id = R.string.add_payment_method),
modifier = Modifier.padding(end = HorizontalPadding, bottom = 4.dp),
color = MaterialTheme.linkColors.actionLabel,
style = MaterialTheme.typography.button
)
}
}
}
private fun String.replaceHyperlinks() = this.replace(
"<terms>",
"<a href=\"https://stripe.com/legal/ach-payments/authorization\">"
).replace("</terms>", "</a>")
| mit | c5a9ed39c8d2bd56bede8b716463fc57 | 36.018382 | 98 | 0.59713 | 5.368702 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/music/lyric/Lyric.kt | 1 | 1170 | package com.xenoage.zong.core.music.lyric
import com.xenoage.zong.core.music.TextElement
import com.xenoage.zong.core.music.VoiceElement
import com.xenoage.zong.core.music.lyric.SyllableType.Extend
import com.xenoage.zong.core.text.Text
/**
* This class represents a single syllable of lyrics.
*/
class Lyric(
/** The text. Usually a single syllable. Null, if type is [Extend]. */
override val text: Text?,
/** The position of the syllable within the lyrics. */
val syllableType: SyllableType,
/** The verse number. 0 is the first one. */
val verse: Int = 0
) : TextElement {
/** Back reference: The parent element, or null, if not attached to an element. */
var parent: VoiceElement? = null
override fun toString() = "Lyric (${if (text != null) "\"$text\"" else "extend"})"
companion object {
/** Creates a new lyric. */
operator fun invoke(text: Text?, syllableType: SyllableType, verse: Int): Lyric {
check(syllableType != Extend || text != null, { "text must be null for extend"})
return Lyric(text, syllableType, verse)
}
/** Creates a new extend lyric. */
fun lyricExtend(verse: Int) = Lyric(null, Extend, verse)
}
}
| agpl-3.0 | a32ea731919a25ac10fe784e6d8721d0 | 29 | 83 | 0.692308 | 3.305085 | false | false | false | false |
AndroidX/androidx | benchmark/integration-tests/macrobenchmark/src/androidTest/java/androidx/benchmark/integration/macrobenchmark/AudioUnderrunBenchmark.kt | 3 | 2557 | /*
* 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.benchmark.integration.macrobenchmark
import android.content.Intent
import androidx.benchmark.macro.AudioUnderrunMetric
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.ExperimentalMetricApi
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 23)
@OptIn(ExperimentalMetricApi::class)
class AudioUnderrunBenchmark() {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
private lateinit var device: UiDevice
@Before
fun setUp() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
device = UiDevice.getInstance(instrumentation)
}
@Test
fun start() {
benchmarkRule.measureRepeated(
packageName = PACKAGE_NAME,
metrics = listOf(AudioUnderrunMetric()),
compilationMode = CompilationMode.Full(),
startupMode = StartupMode.WARM,
iterations = 1,
setupBlock = {
val intent = Intent()
intent.action = ACTION
startActivityAndWait(intent)
}
) {
// audio is played for a half of duration, ~50% of the frames would be zero
Thread.sleep(DURATION_MS.toLong())
}
}
companion object {
private const val PACKAGE_NAME = "androidx.benchmark.integration.macrobenchmark.target"
private const val ACTION = "$PACKAGE_NAME.AUDIO_ACTIVITY"
private const val DURATION_MS = 2000
}
} | apache-2.0 | 2ed234566fcced21cd624832cceb403b | 33.106667 | 95 | 0.716465 | 4.709024 | false | true | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/welcome/WelcomeLayout.kt | 1 | 2552 | package au.com.codeka.warworlds.client.game.welcome
import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.ctrl.TransparentWebView
import au.com.codeka.warworlds.client.game.world.ImageHelper
import au.com.codeka.warworlds.client.util.ViewBackgroundGenerator.setBackground
import au.com.codeka.warworlds.common.proto.Empire
import com.google.common.base.Preconditions
import com.squareup.picasso.Picasso
/**
* Layout for the [WelcomeScreen].
*/
class WelcomeLayout(context: Context?, private val callbacks: Callbacks)
: RelativeLayout(context, null) {
interface Callbacks {
fun onStartClick()
fun onHelpClick()
fun onWebsiteClick()
fun onSignInClick()
}
private val startButton: Button
private val signInButton: Button
private val connectionStatus: TextView
private val empireName: TextView
private val empireIcon: ImageView
private val motdView: TransparentWebView
fun refreshEmpireDetails(empire: Empire) {
empireName.text = empire.display_name
Picasso.get()
.load(ImageHelper.getEmpireImageUrl(context, empire, 20, 20))
.into(empireIcon)
}
fun updateWelcomeMessage(html: String) {
motdView.loadHtml("html/skeleton.html", html)
}
fun setConnectionStatus(connected: Boolean, message: String) {
startButton.isEnabled = connected
connectionStatus.text = message
}
fun setSignInText(resId: Int) {
signInButton.setText(resId)
}
init {
View.inflate(context, R.layout.welcome, this)
setBackground(this)
startButton = Preconditions.checkNotNull(findViewById(R.id.start_btn))
signInButton = findViewById(R.id.signin_btn)
motdView = Preconditions.checkNotNull(findViewById(R.id.motd))
empireName = Preconditions.checkNotNull(findViewById(R.id.empire_name))
empireIcon = Preconditions.checkNotNull(findViewById(R.id.empire_icon))
connectionStatus = Preconditions.checkNotNull(findViewById(R.id.connection_status))
// val optionsButton = Preconditions.checkNotNull(findViewById<Button>(R.id.options_btn))
startButton.setOnClickListener { callbacks.onStartClick() }
findViewById<View>(R.id.help_btn).setOnClickListener { callbacks.onHelpClick() }
findViewById<View>(R.id.website_btn).setOnClickListener { callbacks.onWebsiteClick() }
signInButton.setOnClickListener { callbacks.onSignInClick() }
}
}
| mit | d4a7238ea8135794669a65761f8c2639 | 34.943662 | 92 | 0.770768 | 4.12945 | false | false | false | false |
AndroidX/androidx | core/core-ktx/src/main/java/androidx/core/util/Pair.kt | 3 | 3357 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE") // Aliases to public API.
package androidx.core.util
import android.annotation.SuppressLint
import android.util.Pair as AndroidPair
import kotlin.Pair as KotlinPair
/**
* Returns the first component of the pair.
*
* This method allows to use destructuring declarations when working with pairs, for example:
* ```
* val (first, second) = myPair
* ```
*/
@SuppressLint("UnknownNullness")
@Suppress("HasPlatformType") // Intentionally propagating platform type with unknown nullability.
public inline operator fun <F, S> Pair<F, S>.component1(): F = first
/**
* Returns the second component of the pair.
*
* This method allows to use destructuring declarations when working with pairs, for example:
* ```
* val (first, second) = myPair
* ```
*/
@SuppressLint("UnknownNullness")
@Suppress("HasPlatformType") // Intentionally propagating platform type with unknown nullability.
public inline operator fun <F, S> Pair<F, S>.component2(): S = second
/** Returns this [AndroidX `Pair`][Pair] as a [Kotlin `Pair`][KotlinPair]. */
public inline fun <F, S> Pair<F, S>.toKotlinPair(): kotlin.Pair<F, S> = KotlinPair(first, second)
/** Returns this [Kotlin `Pair`][KotlinPair] as an [AndroidX `Pair`][Pair]. */
// Note: the return type is explicitly specified here to prevent always seeing platform types.
public inline fun <F, S> KotlinPair<F, S>.toAndroidXPair(): Pair<F, S> = Pair(first, second)
/**
* Returns the first component of the pair.
*
* This method allows to use destructuring declarations when working with pairs, for example:
* ```
* val (first, second) = myPair
* ```
*/
@SuppressLint("UnknownNullness")
@Suppress("HasPlatformType") // Intentionally propagating platform type with unknown nullability.
public inline operator fun <F, S> AndroidPair<F, S>.component1(): F = first
/**
* Returns the second component of the pair.
*
* This method allows to use destructuring declarations when working with pairs, for example:
* ```
* val (first, second) = myPair
* ```
*/
@SuppressLint("UnknownNullness")
@Suppress("HasPlatformType") // Intentionally propagating platform type with unknown nullability.
public inline operator fun <F, S> AndroidPair<F, S>.component2(): S = second
/** Returns this [Android `Pair`][AndroidPair] as a [Kotlin `Pair`][KotlinPair]. */
public inline fun <F, S> AndroidPair<F, S>.toKotlinPair(): kotlin.Pair<F, S> =
KotlinPair(first, second)
/** Returns this [Kotlin `Pair`][KotlinPair] as an [Android `Pair`][AndroidPair]. */
// Note: the return type is explicitly specified here to prevent always seeing platform types.
public inline fun <F, S> KotlinPair<F, S>.toAndroidPair(): AndroidPair<F, S> =
AndroidPair(first, second)
| apache-2.0 | cf36de24ceb903dd4a66794e6fba1a44 | 37.586207 | 97 | 0.722669 | 3.840961 | false | false | false | false |
riaektiv/fdp | fdp-common/src/main/java/com/riaektiv/fdp/common/kafka/MessageProperties.kt | 1 | 788 | package com.riaektiv.fdp.common.kafka
/**
* Created: 3/11/2018, 9:33 AM Eastern Time
*
* @author Sergey Chuykov
*/
class MessageProperties {
var objectType: String? = null
private var replyTo: String? = null
private var contentType: String? = null
private var correlationId: String? = null
fun setReplyTo(replyTo: String) {
this.replyTo = replyTo
}
fun getReplyTo(): String? {
return replyTo
}
fun getContentType(): String? {
return contentType
}
fun setContentType(contentType: String) {
this.contentType = contentType
}
fun getCorrelationId(): String? {
return correlationId
}
fun setCorrelationId(correlationId: String) {
this.correlationId = correlationId
}
} | apache-2.0 | f8380729b51d481669063a233cb8f7f7 | 19.230769 | 49 | 0.640863 | 4.528736 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt | 2 | 31227 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.presentation
import org.rust.ide.utils.import.ImportCandidate
import org.rust.ide.utils.import.ImportCandidatesCollector
import org.rust.ide.utils.import.ImportContext
import org.rust.lang.core.crate.impl.FakeCrate
import org.rust.lang.core.parser.RustParserUtil
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.*
import org.rust.lang.core.stubs.RsStubLiteralKind
import org.rust.lang.core.types.*
import org.rust.lang.core.types.consts.CtConstParameter
import org.rust.lang.core.types.consts.CtValue
import org.rust.lang.core.types.infer.resolve
import org.rust.lang.core.types.infer.substitute
import org.rust.lang.core.types.regions.ReEarlyBound
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyInteger
import org.rust.lang.core.types.ty.TyPrimitive
import org.rust.lang.core.types.ty.TyTypeParameter
import org.rust.lang.utils.escapeRust
import org.rust.lang.utils.evaluation.evaluate
import org.rust.stdext.exhaustive
import org.rust.stdext.joinToWithBuffer
/** Return text of the element without switching to AST (loses non-stubbed parts of PSI) */
fun RsTypeReference.getStubOnlyText(
subst: Substitution = emptySubstitution,
renderLifetimes: Boolean = true,
shortPaths: Boolean = true,
): String {
val options = PsiRenderingOptions(renderLifetimes, shortPaths = shortPaths)
return TypeSubstitutingPsiRenderer(options, subst).renderTypeReference(this)
}
/** Return text of the element without switching to AST (loses non-stubbed parts of PSI) */
fun RsValueParameterList.getStubOnlyText(
subst: Substitution = emptySubstitution,
renderLifetimes: Boolean = true
): String = TypeSubstitutingPsiRenderer(PsiRenderingOptions(renderLifetimes), subst).renderValueParameterList(this)
/** Return text of the element without switching to AST (loses non-stubbed parts of PSI) */
fun RsTraitRef.getStubOnlyText(subst: Substitution = emptySubstitution, renderLifetimes: Boolean = true): String =
buildString { TypeSubstitutingPsiRenderer(PsiRenderingOptions(renderLifetimes), subst).appendPath(this, path) }
fun RsPsiRenderer.renderTypeReference(ref: RsTypeReference): String =
buildString { appendTypeReference(this, ref) }
fun RsPsiRenderer.renderTraitRef(ref: RsTraitRef): String =
buildString { appendPath(this, ref.path) }
fun RsPsiRenderer.renderValueParameterList(list: RsValueParameterList): String =
buildString { appendValueParameterList(this, list) }
fun RsPsiRenderer.renderFunctionSignature(fn: RsFunction): String =
buildString { appendFunctionSignature(this, fn) }
fun RsPsiRenderer.renderTypeAliasSignature(ta: RsTypeAlias, renderBounds: Boolean): String =
buildString { appendTypeAliasSignature(this, ta, renderBounds) }
data class PsiRenderingOptions(
val renderLifetimes: Boolean = true,
/** Related to [RsPsiRenderer.appendFunctionSignature] */
val renderGenericsAndWhere: Boolean = true,
/** if `true`, renders `Bar` instead of `foo::Bar` */
val shortPaths: Boolean = true,
)
@Suppress("MemberVisibilityCanBePrivate", "DuplicatedCode")
open class RsPsiRenderer(
protected val options: PsiRenderingOptions
) {
protected val renderLifetimes: Boolean get() = options.renderLifetimes
protected val renderGenericsAndWhere: Boolean get() = options.renderGenericsAndWhere
protected val shortPaths: Boolean get() = options.shortPaths
open fun appendFunctionSignature(sb: StringBuilder, fn: RsFunction) {
if (fn.isAsync) {
sb.append("async ")
}
if (fn.isConst) {
sb.append("const ")
}
if (fn.isUnsafe) {
sb.append("unsafe ")
}
if (fn.isActuallyExtern) {
sb.append("extern ")
val abiName = fn.abiName
if (abiName != null) {
sb.append("\"")
sb.append(abiName)
sb.append("\" ")
}
}
sb.append("fn ")
sb.append(fn.escapedName ?: "")
val typeParameterList = fn.typeParameterList
if (typeParameterList != null && renderGenericsAndWhere) {
appendTypeParameterList(sb, typeParameterList)
}
val valueParameterList = fn.valueParameterList
if (valueParameterList != null) {
appendValueParameterList(sb, valueParameterList)
}
val retType = fn.retType
if (retType != null) {
sb.append(" -> ")
val retTypeReference = retType.typeReference
if (retTypeReference != null) {
appendTypeReference(sb, retTypeReference)
}
}
val whereClause = fn.whereClause
if (whereClause != null && renderGenericsAndWhere) {
appendWhereClause(sb, whereClause)
}
}
open fun appendTypeAliasSignature(sb: StringBuilder, ta: RsTypeAlias, renderBounds: Boolean) {
sb.append("type ")
sb.append(ta.escapedName ?: "")
val typeParameterList = ta.typeParameterList
if (typeParameterList != null && renderGenericsAndWhere) {
appendTypeParameterList(sb, typeParameterList)
}
val whereClause = ta.whereClause
if (whereClause != null && renderGenericsAndWhere) {
appendWhereClause(sb, whereClause)
}
val typeParamBounds = ta.typeParamBounds
if (typeParamBounds != null && renderBounds) {
appendTypeParamBounds(sb, typeParamBounds)
}
}
private fun appendWherePred(sb: StringBuilder, pred: RsWherePred) {
val lifetime = pred.lifetime
val type = pred.typeReference
if (lifetime != null) {
sb.append(lifetime.name)
val bounds = pred.lifetimeParamBounds
if (bounds != null) {
appendLifetimeBounds(sb, bounds)
}
} else if (type != null) {
val forLifetimes = pred.forLifetimes
if (renderLifetimes && forLifetimes != null) {
appendForLifetimes(sb, forLifetimes)
}
appendTypeReference(sb, type)
val typeParamBounds = pred.typeParamBounds
if (typeParamBounds != null) {
appendTypeParamBounds(sb, typeParamBounds)
}
}
}
private fun appendWhereClause(sb: StringBuilder, whereClause: RsWhereClause) {
sb.append(" where ")
whereClause.wherePredList.joinToWithBuffer(sb, separator = ", ") {
appendWherePred(sb, this)
}
}
private fun appendTypeParamBounds(sb: StringBuilder, bounds: RsTypeParamBounds) {
sb.append(": ")
bounds.polyboundList.joinToWithBuffer(sb, " + ") {
appendPolybound(sb, this)
}
}
open fun appendTypeParameterList(sb: StringBuilder, list: RsTypeParameterList) {
sb.append("<")
list.stubChildrenOfType<RsElement>().joinToWithBuffer(sb, separator = ", ") {
when (this) {
is RsLifetimeParameter -> {
sb.append(name)
val bounds = lifetimeParamBounds
if (bounds != null) {
appendLifetimeBounds(sb, bounds)
}
}
is RsTypeParameter -> {
sb.append(name)
val bounds = typeParamBounds
if (bounds != null) {
sb.append(": ")
bounds.polyboundList.joinToWithBuffer(sb, " + ") {
appendPolybound(sb, this)
}
}
val defaultValue = typeReference
if (defaultValue != null) {
sb.append(" = ")
appendTypeReference(sb, defaultValue)
}
}
is RsConstParameter -> {
sb.append("const ")
sb.append(name ?: "_")
val type = typeReference
if (type != null) {
sb.append(": ")
appendTypeReference(sb, type)
}
}
}
}
sb.append(">")
}
private fun appendLifetimeBounds(sb: StringBuilder, bounds: RsLifetimeParamBounds) {
sb.append(": ")
bounds.lifetimeList.joinToWithBuffer(sb, separator = " + ") { it.append(name) }
}
open fun appendValueParameterList(
sb: StringBuilder,
list: RsValueParameterList
) {
sb.append("(")
val selfParameter = list.selfParameter
val valueParameterList = list.valueParameterList
if (selfParameter != null) {
appendSelfParameter(sb, selfParameter)
if (valueParameterList.isNotEmpty()) {
sb.append(", ")
}
}
valueParameterList.joinToWithBuffer(sb, separator = ", ") { sb1 ->
sb1.append(patText ?: "_")
sb1.append(": ")
val typeReference = typeReference
if (typeReference != null) {
appendTypeReference(sb1, typeReference)
} else {
sb1.append("()")
}
}
sb.append(")")
}
open fun appendSelfParameter(
sb: StringBuilder,
selfParameter: RsSelfParameter
) {
val typeReference = selfParameter.typeReference
if (typeReference != null) {
sb.append("self: ")
appendTypeReference(sb, typeReference)
} else {
if (selfParameter.isRef) {
sb.append("&")
val lifetime = selfParameter.lifetime
if (renderLifetimes && lifetime != null) {
appendLifetime(sb, lifetime)
sb.append(" ")
}
sb.append(if (selfParameter.mutability.isMut) "mut " else "")
}
sb.append("self")
}
}
open fun appendTypeReference(sb: StringBuilder, type: RsTypeReference) {
when (type) {
is RsParenType -> {
sb.append("(")
type.typeReference?.let { appendTypeReference(sb, it) }
sb.append(")")
}
is RsTupleType -> {
val types = type.typeReferenceList
if (types.size == 1) {
sb.append("(")
appendTypeReference(sb, types.single())
sb.append(",)")
} else {
types.joinToWithBuffer(sb, ", ", "(", ")") { appendTypeReference(it, this) }
}
}
is RsUnitType -> sb.append("()")
is RsNeverType -> sb.append("!")
is RsInferType -> sb.append("_")
is RsPathType -> appendPath(sb, type.path)
is RsRefLikeType -> {
if (type.isPointer) {
sb.append(if (type.mutability.isMut) "*mut " else "*const ")
} else if (type.isRef) {
sb.append("&")
val lifetime = type.lifetime
if (renderLifetimes && lifetime != null) {
appendLifetime(sb, lifetime)
sb.append(" ")
}
if (type.mutability.isMut) sb.append("mut ")
}
type.typeReference?.let { appendTypeReference(sb, it) }
}
is RsArrayType -> {
sb.append("[")
type.typeReference?.let { appendTypeReference(sb, it) }
if (!type.isSlice) {
val arraySizeExpr = type.expr
sb.append("; ")
if (arraySizeExpr != null) {
appendConstExpr(sb, arraySizeExpr, TyInteger.USize.INSTANCE)
} else {
sb.append("{}")
}
}
sb.append("]")
}
is RsFnPointerType -> {
if (type.isUnsafe) {
sb.append("unsafe ")
}
if (type.isExtern) {
sb.append("extern ")
val abiName = type.abiName
if (abiName != null) {
sb.append("\"")
sb.append(abiName)
sb.append("\" ")
}
}
sb.append("fn")
appendValueParameterListTypes(sb, type.valueParameters)
appendRetType(sb, type.retType)
}
is RsTraitType -> {
sb.append(if (type.isImpl) "impl " else "dyn ")
type.polyboundList.joinToWithBuffer(sb, " + ") {
appendPolybound(sb, this)
}
}
is RsMacroType -> {
appendPath(sb, type.macroCall.path)
sb.append("!(")
type.macroCall.macroBody?.let { sb.append(it) }
sb.append(")")
}
}
}
private fun appendPolybound(sb: StringBuilder, polyBound: RsPolybound) {
val forLifetimes = polyBound.forLifetimes
if (renderLifetimes && forLifetimes != null) {
appendForLifetimes(sb, forLifetimes)
}
if (polyBound.hasQ) {
sb.append("?")
}
val bound = polyBound.bound
val lifetime = bound.lifetime
if (renderLifetimes && lifetime != null) {
sb.append(lifetime.referenceName)
} else {
bound.traitRef?.path?.let { appendPath(sb, it) }
}
}
private fun appendForLifetimes(sb: StringBuilder, forLifetimes: RsForLifetimes) {
sb.append("for<")
forLifetimes.lifetimeParameterList.joinTo(sb, ", ") {
it.name ?: "'_"
}
sb.append("> ")
}
open fun appendLifetime(sb: StringBuilder, lifetime: RsLifetime) {
sb.append(lifetime.referenceName)
}
open fun appendPath(
sb: StringBuilder,
path: RsPath
) {
appendPathWithoutArgs(sb, path)
appendPathArgs(sb, path)
}
protected open fun appendPathWithoutArgs(sb: StringBuilder, path: RsPath) {
val qualifier = path.path
if (!shortPaths && qualifier != null) {
appendPath(sb, qualifier)
}
val typeQual = path.typeQual
if (typeQual != null) {
appendTypeQual(sb, typeQual)
}
if (path.hasColonColon) {
sb.append("::")
}
sb.append(path.referenceName.orEmpty())
}
protected open fun appendTypeQual(sb: StringBuilder, typeQual: RsTypeQual) {
sb.append("<")
appendTypeReference(sb, typeQual.typeReference)
val traitRef = typeQual.traitRef
if (traitRef != null) {
sb.append(" as ")
appendPath(sb, traitRef.path)
}
sb.append(">")
sb.append("::")
}
private fun appendPathArgs(sb: StringBuilder, path: RsPath) {
val inAngles = path.typeArgumentList // Foo<...>
val fnSugar = path.valueParameterList // &dyn FnOnce(...) -> i32
if (inAngles != null) {
val lifetimeArguments = inAngles.lifetimeList
val typeArguments = inAngles.typeReferenceList
val constArguments = inAngles.exprList
val assocTypeBindings = inAngles.assocTypeBindingList
val hasLifetimes = renderLifetimes && lifetimeArguments.isNotEmpty()
val hasTypeReferences = typeArguments.isNotEmpty()
val hasConstArguments = constArguments.isNotEmpty()
val hasAssocTypeBindings = assocTypeBindings.isNotEmpty()
if (hasLifetimes || hasTypeReferences || hasConstArguments || hasAssocTypeBindings) {
sb.append("<")
if (hasLifetimes) {
lifetimeArguments.joinToWithBuffer(sb, ", ") { appendLifetime(it, this) }
if (hasTypeReferences || hasConstArguments || hasAssocTypeBindings) {
sb.append(", ")
}
}
if (hasTypeReferences) {
typeArguments.joinToWithBuffer(sb, ", ") { appendTypeReference(it, this) }
if (hasConstArguments || hasAssocTypeBindings) {
sb.append(", ")
}
}
if (hasConstArguments) {
constArguments.joinToWithBuffer(sb, ", ") { appendConstExpr(it, this) }
if (hasAssocTypeBindings) {
sb.append(", ")
}
}
@Suppress("NAME_SHADOWING")
assocTypeBindings.joinToWithBuffer(sb, ", ") { sb ->
appendPath(sb, this.path)
sb.append("=")
typeReference?.let { appendTypeReference(sb, it) }
}
sb.append(">")
}
} else if (fnSugar != null) {
appendValueParameterListTypes(sb, fnSugar.valueParameterList)
appendRetType(sb, path.retType)
}
}
protected open fun appendRetType(sb: StringBuilder, retType: RsRetType?) {
val retTypeRef = retType?.typeReference
if (retTypeRef != null) {
sb.append(" -> ")
appendTypeReference(sb, retTypeRef)
}
}
protected open fun appendValueParameterListTypes(
sb: StringBuilder,
list: List<RsValueParameter>
) {
@Suppress("NAME_SHADOWING")
list.joinToWithBuffer(sb, separator = ", ", prefix = "(", postfix = ")") { sb ->
typeReference?.let { appendTypeReference(sb, it) }
}
}
protected open fun appendConstExpr(
sb: StringBuilder,
expr: RsExpr,
expectedTy: Ty = expr.type
) {
when (expr) {
is RsPathExpr -> appendPath(sb, expr.path)
is RsLitExpr -> appendLitExpr(sb, expr)
is RsBlockExpr -> appendBlockExpr(sb, expr)
is RsUnaryExpr -> appendUnaryExpr(sb, expr)
is RsBinaryExpr -> appendBinaryExpr(sb, expr)
else -> sb.append("{}")
}
}
protected open fun appendLitExpr(sb: StringBuilder, expr: RsLitExpr) {
when (val kind = expr.stubKind) {
is RsStubLiteralKind.Boolean -> sb.append(kind.value.toString())
is RsStubLiteralKind.Integer -> sb.append(kind.value?.toString() ?: "")
is RsStubLiteralKind.Float -> sb.append(kind.value?.toString() ?: "")
is RsStubLiteralKind.Char -> {
if (kind.isByte) {
sb.append("b")
}
sb.append("'")
sb.append(kind.value.orEmpty().escapeRust())
sb.append("'")
}
is RsStubLiteralKind.String -> {
if (kind.isByte) {
sb.append("b")
}
sb.append('"')
sb.append(kind.value.orEmpty().escapeRust())
sb.append('"')
}
null -> "{}"
}.exhaustive
}
protected open fun appendBlockExpr(sb: StringBuilder, expr: RsBlockExpr) {
val isTry = expr.isTry
val isUnsafe = expr.isUnsafe
val isAsync = expr.isAsync
val isConst = expr.isConst
val tailExpr = expr.block.expandedTailExpr
if (isTry) {
sb.append("try ")
}
if (isUnsafe) {
sb.append("unsafe ")
}
if (isAsync) {
sb.append("async ")
}
if (isConst) {
sb.append("const ")
}
if (tailExpr == null) {
sb.append("{}")
} else {
sb.append("{ ")
appendConstExpr(sb, tailExpr)
sb.append(" }")
}
}
protected open fun appendUnaryExpr(sb: StringBuilder, expr: RsUnaryExpr) {
val sign = when (expr.operatorType) {
UnaryOperator.REF -> "&"
UnaryOperator.REF_MUT -> "&mut "
UnaryOperator.DEREF -> "*"
UnaryOperator.MINUS -> "-"
UnaryOperator.NOT -> "!"
UnaryOperator.BOX -> "box "
UnaryOperator.RAW_REF_CONST -> "&raw const "
UnaryOperator.RAW_REF_MUT -> "&raw mut "
}
sb.append(sign)
val innerExpr = expr.expr
if (innerExpr != null) {
appendConstExpr(sb, innerExpr)
}
}
protected open fun appendBinaryExpr(sb: StringBuilder, expr: RsBinaryExpr) {
val sign = when (val op = expr.operatorType) {
is ArithmeticOp -> op.sign
is ArithmeticAssignmentOp -> op.sign
AssignmentOp.EQ -> "="
is ComparisonOp -> op.sign
is EqualityOp -> op.sign
LogicOp.AND -> "&&"
LogicOp.OR -> "||"
}
appendConstExpr(sb, expr.left)
sb.append(" ")
sb.append(sign)
sb.append(" ")
val right = expr.right
if (right != null) {
appendConstExpr(sb, right)
}
}
}
open class TypeSubstitutingPsiRenderer(
options: PsiRenderingOptions,
private val subst: Substitution
) : RsPsiRenderer(options) {
override fun appendTypeReference(sb: StringBuilder, type: RsTypeReference) {
val ty = type.rawType
if (ty is TyTypeParameter && subst[ty] != null) {
sb.append(ty.substAndGetText(subst))
} else {
super.appendTypeReference(sb, type)
}
}
override fun appendLifetime(sb: StringBuilder, lifetime: RsLifetime) {
val resolvedLifetime = lifetime.resolve()
val substitutedLifetime = if (resolvedLifetime is ReEarlyBound) subst[resolvedLifetime] else null
if (substitutedLifetime is ReEarlyBound) {
sb.append(substitutedLifetime.parameter.name)
} else {
sb.append(lifetime.referenceName)
}
}
override fun appendConstExpr(
sb: StringBuilder,
expr: RsExpr,
expectedTy: Ty
) {
when (val const = expr.evaluate(expectedTy).substitute(subst)) { // may trigger resolve
is CtValue -> sb.append(const)
is CtConstParameter -> {
val wrapParameterInBraces = expr.stubParent is RsTypeArgumentList
if (wrapParameterInBraces) {
sb.append("{ ")
}
sb.append(const.toString())
if (wrapParameterInBraces) {
sb.append(" }")
}
}
else -> sb.append("{}")
}
}
}
open class PsiSubstitutingPsiRenderer(
options: PsiRenderingOptions,
private val substitutions: List<RsPsiSubstitution>
) : RsPsiRenderer(options) {
override fun appendPathWithoutArgs(sb: StringBuilder, path: RsPath) {
val replaced = when (val resolved = path.reference?.resolve()) {
is RsTypeParameter -> when (val s = typeSubst(resolved)) {
is RsPsiSubstitution.Value.Present -> when (s.value) {
is RsPsiSubstitution.TypeValue.InAngles -> {
super.appendTypeReference(sb, s.value.value)
true
}
is RsPsiSubstitution.TypeValue.FnSugar -> false
}
is RsPsiSubstitution.Value.DefaultValue -> {
super.appendTypeReference(sb, s.value.value)
true
}
else -> false
}
is RsConstParameter -> when (val s = constSubst(resolved)) {
is RsPsiSubstitution.Value.Present -> {
when (s.value) {
is RsExpr -> appendConstExpr(sb, s.value)
is RsTypeReference -> appendTypeReference(sb, s.value)
}
true
}
is RsPsiSubstitution.Value.DefaultValue -> {
appendConstExpr(sb, s.value)
true
}
else -> false
}
else -> false
}
if (!replaced) {
super.appendPathWithoutArgs(sb, path)
}
}
override fun appendLifetime(sb: StringBuilder, lifetime: RsLifetime) {
val resolvedLifetime = lifetime.reference.resolve()
val substitutedLifetime = if (resolvedLifetime is RsLifetimeParameter) {
regionSubst(resolvedLifetime)
} else {
null
}
when (substitutedLifetime) {
is RsPsiSubstitution.Value.Present -> sb.append(substitutedLifetime.value.name)
else -> sb.append(lifetime.referenceName)
}
}
private fun regionSubst(lifetime: RsLifetimeParameter?): RsPsiSubstitution.Value<RsLifetime, Nothing>? {
return substitutions.firstNotNullOfOrNull { it.regionSubst[lifetime] }
}
private fun constSubst(const: RsConstParameter?): RsPsiSubstitution.Value<RsElement, RsExpr>? {
return substitutions.firstNotNullOfOrNull { it.constSubst[const] }
}
private fun typeSubst(type: RsTypeParameter?): RsPsiSubstitution.Value<RsPsiSubstitution.TypeValue, RsPsiSubstitution.TypeDefault>? {
return substitutions.firstNotNullOfOrNull { it.typeSubst[type] }
}
}
class ImportingPsiRenderer(
options: PsiRenderingOptions,
substitutions: List<RsPsiSubstitution>,
private val context: RsElement
) : PsiSubstitutingPsiRenderer(options, substitutions) {
private val importContext = ImportContext.from(context, ImportContext.Type.OTHER)
private val visibleNames: Pair<MutableMap<Pair<String, Namespace>, RsElement>, MutableMap<RsElement, String>> by lazy(LazyThreadSafetyMode.PUBLICATION) {
val nameToElement = mutableMapOf<Pair<String, Namespace>, RsElement>()
val elementToName = mutableMapOf<RsElement, String>()
processNestedScopesUpwards(context, TYPES_N_VALUES, createProcessor {
val element = it.element as? RsNamedElement ?: return@createProcessor false
for (namespace in element.namespaces) {
nameToElement[it.name to namespace] = element
if (it.name != "_" && element !in elementToName) {
elementToName[element] = it.name
}
}
false
})
nameToElement to elementToName
}
private val visibleNameToElement: MutableMap<Pair<String, Namespace>, RsElement> get() = visibleNames.first
private val visibleElementToName: MutableMap<RsElement, String> get() = visibleNames.second
private val itemsToImportMut: MutableSet<ImportCandidate> = mutableSetOf()
val itemsToImport: Set<ImportCandidate> get() = itemsToImportMut
override fun appendPathWithoutArgs(sb: StringBuilder, path: RsPath) {
val pathReferenceName = path.referenceName
val tryImportPath1 = path.parent !is RsPath &&
path.parent !is RsAssocTypeBinding &&
TyPrimitive.fromPath(path) == null &&
path.basePath().referenceName != "Self" &&
path.basePath().typeQual == null
if (tryImportPath1 && pathReferenceName != null) {
val resolved = path.reference?.resolve()
val tryImportPath2 = resolved !is RsTypeParameter
&& resolved !is RsConstParameter
&& resolved !is RsMacroDefinitionBase
&& resolved !is RsMod
if (tryImportPath2 && resolved is RsQualifiedNamedElement) {
val visibleElementName = visibleElementToName[resolved]
if (visibleElementName != null) {
sb.append(visibleElementName)
} else {
val importCandidate = importContext?.let {
ImportCandidatesCollector.findImportCandidate(it, resolved)
}
if (importCandidate == null) {
val resolvedCrate = resolved.containingCrate
if (resolvedCrate is FakeCrate || resolvedCrate == context.containingCrate) {
sb.append("crate")
} else {
sb.append(resolvedCrate.normName)
}
sb.append(resolved.crateRelativePath)
} else {
val ns = if (path.parent is RsExpr) {
Namespace.Values
} else {
Namespace.Types
}
val elementInScopeWithSameName = visibleNameToElement[pathReferenceName to ns]
val isNameConflict = elementInScopeWithSameName != null && elementInScopeWithSameName != resolved
if (isNameConflict) {
val qualifiedPath = importCandidate.info.usePath
sb.append(trySimplifyPath(path, qualifiedPath) ?: qualifiedPath)
} else {
itemsToImportMut += importCandidate
visibleElementToName[resolved] = pathReferenceName
for (namespace in resolved.namespaces) {
visibleNameToElement[pathReferenceName to namespace] = resolved
}
sb.append(pathReferenceName)
}
}
}
return
}
}
super.appendPathWithoutArgs(sb, path)
}
private fun trySimplifyPath(originPath: RsPath, qualifiedPath: String): String? {
val newPath = RsCodeFragmentFactory(originPath.project).createPath(
qualifiedPath,
context,
RustParserUtil.PathParsingMode.TYPE,
originPath.allowedNamespaces()
) ?: return null
val segmentsReversed = generateSequence(newPath) { it.path }.toList()
var simplifiedSegmentCount = 1
var firstSegmentName: String? = null
for (s in segmentsReversed.asSequence().drop(1)) {
val resolved = s.reference?.resolve() ?: return null
simplifiedSegmentCount++
firstSegmentName = visibleElementToName[resolved]
if (firstSegmentName != null) break
}
return if (firstSegmentName == null || simplifiedSegmentCount >= segmentsReversed.size) {
null
} else {
"$firstSegmentName::" + segmentsReversed
.take(simplifiedSegmentCount - 1)
.asReversed()
.joinToString(separator = "::") { it.referenceName.orEmpty() }
}
}
}
| mit | 81617488a2f8d3d620d78b5b77cc3764 | 36.850909 | 157 | 0.553271 | 4.938637 | false | false | false | false |
bibaev/stream-debugger-plugin | src/test/java/com/intellij/debugger/streams/exec/streamex/DistinctOperationsTest.kt | 1 | 1097 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.exec.streamex
/**
* @author Vitaliy.Bibaev
*/
class DistinctOperationsTest : StreamExTestCase() {
override val packageName: String = "distinct"
fun testDistinctAtLeast() = doStreamExWithResultTest()
fun testDistinctWithKeyExtractor() = doStreamExWithResultTest()
fun testDistinctWithStatefulExtractor() = doStreamExWithResultTest()
fun testDistinctKeys() = doStreamExWithResultTest()
fun testDistinctValues() = doStreamExWithResultTest()
}
| apache-2.0 | b93f92ed03347a8a99c4e4e9138c42c1 | 34.387097 | 75 | 0.76299 | 4.353175 | false | true | false | false |
googlecodelabs/wear-tiles | start/src/main/java/com/example/wear/tiles/messaging/tile/MessagingTileService.kt | 2 | 3755 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.wear.tiles.messaging.tile
import androidx.lifecycle.lifecycleScope
import androidx.wear.tiles.RequestBuilders.ResourcesRequest
import androidx.wear.tiles.RequestBuilders.TileRequest
import androidx.wear.tiles.ResourceBuilders.Resources
import androidx.wear.tiles.TileBuilders.Tile
import coil.imageLoader
import com.example.wear.tiles.messaging.MessagingRepo
import com.google.android.horologist.tiles.CoroutinesTileService
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class MessagingTileService : CoroutinesTileService() {
private lateinit var repo: MessagingRepo
private lateinit var renderer: MessagingTileRenderer
private lateinit var tileStateFlow: StateFlow<MessagingTileState?>
override fun onCreate() {
super.onCreate()
repo = MessagingRepo(this)
renderer = MessagingTileRenderer(this)
tileStateFlow = repo.getFavoriteContacts()
.map { contacts -> MessagingTileState(contacts) }
.stateIn(
lifecycleScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = null
)
}
override suspend fun tileRequest(requestParams: TileRequest): Tile {
val tileState = latestTileState()
return renderer.renderTimeline(tileState, requestParams)
}
/**
* Reads the latest state from the flow, and updates the data if there isn't any.
*/
private suspend fun latestTileState(): MessagingTileState {
var tileState = tileStateFlow.filterNotNull().first()
// see `refreshData()` docs for more information
if (tileState.contacts.isEmpty()) {
refreshData()
tileState = tileStateFlow.filterNotNull().first()
}
return tileState
}
/**
* If our data source (the repository) is empty/has stale data, this is where we could perform
* an update. For this sample, we're updating the repository with fake data
* ([MessagingRepo.knownContacts]).
*
* In a more complete example, tiles, complications and the main app (/overlay) would
* share a common data source so it's less likely that an initial data refresh triggered by the
* tile would be necessary.
*/
private suspend fun refreshData() {
repo.updateContacts(MessagingRepo.knownContacts)
}
override suspend fun resourcesRequest(requestParams: ResourcesRequest): Resources {
// Since we know there's only 2 very small avatars, we'll fetch them
// as part of this resource request.
val avatars = imageLoader.fetchAvatarsFromNetwork(
context = this@MessagingTileService,
requestParams = requestParams,
tileState = latestTileState()
)
// then pass the bitmaps to the renderer to transform them to ImageResources
return renderer.produceRequestedResources(avatars, requestParams)
}
}
| apache-2.0 | 45e334a8af36921e2d13157f07e087b4 | 38.526316 | 99 | 0.71478 | 4.966931 | false | false | false | false |
mauriciocoelho/upcomingmovies | infrastructure/src/test/kotlin/com/mauscoelho/upcomingmovies/infrastructure/UpcomingMoviesRepositoryTest.kt | 1 | 3257 | package com.mauscoelho.upcomingmovies.infrastructure
import br.ufs.github.rxassertions.RxAssertions
import com.mauscoelho.upcomingmovies.infrastructure.boundary.UpcomingMoviesRepository
import com.mauscoelho.upcomingmovies.model.Genre
import com.mauscoelho.upcomingmovies.model.Movie
import com.mauscoelho.upcomingmovies.model.UpcomingMovies
import com.nhaarman.mockito_kotlin.any
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import rx.Observable
@RunWith(JUnitPlatform::class)
class UpcomingMoviesRepositoryTest : Spek({
val apiKey = "1f54bd990f1cdfb230adb312546d765d"
val language = "en-US"
fun createUpcomingMovies(): Observable<UpcomingMovies> {
val movies = mutableListOf<Movie>()
(1..20).mapTo(movies) { Movie(20, 1, 1, "title", "poster_path", "overview", "release_date", "", "", 0.1, listOf(Genre(1,"Horror")), listOf(1),"a","a","a","a","a") }
return Observable.just(UpcomingMovies(1, movies.toTypedArray(), 4, 80))
}
fun createMovie(): Observable<Movie> {
return Observable.just(Movie(20, 1, 1, "title", "poster_path", "overview", "release_date", "", "", 0.1, listOf(Genre(1,"Horror")), listOf(1),"a","a","a","a","a"))
}
describe("UpcomingMoviesRepositoryTest") {
context("Get upcoming movies") {
it("should return upcoming movies from network") {
val page = 1
val upcomingMoviesRepositoryMock = mock(UpcomingMoviesRepository::class.java)
`when`(upcomingMoviesRepositoryMock.getUpcomingMovies(any(), any(), any())).thenReturn(createUpcomingMovies())
RxAssertions.assertThat(upcomingMoviesRepositoryMock.getUpcomingMovies(apiKey, language, page))
.completes()
.withoutErrors()
.emissionsCount(1)
}
}
context("Get movie detail") {
it("should return movie detail from network") {
val movieId = 1
val upcomingMoviesRepositoryMock = mock(UpcomingMoviesRepository::class.java)
`when`(upcomingMoviesRepositoryMock.getMovie(movieId, apiKey, language)).thenReturn(createMovie())
RxAssertions.assertThat(upcomingMoviesRepositoryMock.getMovie(movieId, apiKey, language))
.completes()
.withoutErrors()
.emissionsCount(1)
}
it("should not return movie detail from network") {
val movieId = 2
val upcomingMoviesRepositoryMock = mock(UpcomingMoviesRepository::class.java)
`when`(upcomingMoviesRepositoryMock.getMovie(2, apiKey, language)).thenReturn(Observable.empty())
RxAssertions.assertThat(upcomingMoviesRepositoryMock.getMovie(movieId, apiKey, language))
.emitsNothing()
.completes()
.withoutErrors()
}
}
}
})
| apache-2.0 | dc78f92375f84ddd4cb5e29cdc910aea | 40.75641 | 172 | 0.644765 | 4.693084 | false | false | false | false |
robohorse/RoboPOJOGenerator | generator/src/main/kotlin/com/robohorse/robopojogenerator/postrocessing/common/CommonJavaPostProcessor.kt | 1 | 3501 | package com.robohorse.robopojogenerator.postrocessing.common
import com.robohorse.robopojogenerator.properties.ClassItem
import com.robohorse.robopojogenerator.properties.templates.ClassTemplate
import com.robohorse.robopojogenerator.utils.ClassGenerateHelper
import com.robohorse.robopojogenerator.utils.ClassTemplateHelper
import com.robohorse.robopojogenerator.models.FieldModel
import com.robohorse.robopojogenerator.models.GenerationModel
import com.robohorse.robopojogenerator.models.Visibility
internal class CommonJavaPostProcessor(
generateHelper: ClassGenerateHelper,
classTemplateHelper: ClassTemplateHelper
) : JavaPostProcessor(generateHelper, classTemplateHelper) {
override fun proceedClassBody(
classItem: ClassItem,
generationModel: GenerationModel
): String {
val classBodyBuilder = StringBuilder()
val classMethodBuilder = StringBuilder()
val classFields = classItem.classFields
with(classBodyBuilder) {
for (objectName in classFields.keys) {
val classItemValue = classFields[objectName]?.getJavaItem(
primitive = generationModel.javaPrimitives
)
val itemNameFormatted = generateHelper.formatClassField(objectName)
append(
classTemplateHelper.createField(
FieldModel(
classType = classItemValue,
fieldNameFormatted = itemNameFormatted,
fieldName = objectName,
annotation = classItem.annotation,
visibility = if (generationModel.useLombokValue) {
Visibility.NONE
} else {
Visibility.PRIVATE
}
)
)
)
}
for (objectName in classFields.keys) {
val classItemValue = classFields[objectName]?.getJavaItem(
primitive = generationModel.javaPrimitives
)
val itemNameFormatted = generateHelper.formatClassField(objectName)
if (generationModel.useSetters) {
append(ClassTemplate.NEW_LINE)
append(
classTemplateHelper.createSetter(
itemNameFormatted,
classItemValue
)
)
}
if (generationModel.useGetters) {
append(ClassTemplate.NEW_LINE)
append(
classTemplateHelper.createGetter(
itemNameFormatted,
classItemValue
)
)
}
}
if (generationModel.useStrings) {
append(ClassTemplate.NEW_LINE)
append(
classTemplateHelper.createToString(
classItem
)
)
}
append(classMethodBuilder)
return toString()
}
}
override fun createClassTemplate(
classItem: ClassItem,
classBody: String?,
generationModel: GenerationModel
) = classTemplateHelper.createClassBody(classItem, classBody)
}
| mit | fadf05fe3c5affe3bbdfbcf94ab5d51f | 39.241379 | 83 | 0.547843 | 6.60566 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/LuaElementTypes.kt | 2 | 2611 | /*
* Copyright (c) 2017. tangzx([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 com.tang.intellij.lua.psi
import com.tang.intellij.lua.psi.impl.*
import com.tang.intellij.lua.stubs.*
object LuaElementTypes {
val BINARY_OPS by lazy { arrayOf(
LuaTypes.CONCAT,
LuaTypes.LE, LuaTypes.EQ, LuaTypes.LT, LuaTypes.NE, LuaTypes.GE, LuaTypes.GT,
LuaTypes.AND, LuaTypes.OR,
LuaTypes.BIT_AND, LuaTypes.BIT_LTLT, LuaTypes.BIT_OR, LuaTypes.BIT_RTRT, LuaTypes.BIT_TILDE, LuaTypes.EXP,
LuaTypes.PLUS, LuaTypes.MINUS, LuaTypes.MULT, LuaTypes.DIV, LuaTypes.DOUBLE_DIV, LuaTypes.MOD
)}
val UNARY_OPS by lazy { arrayOf(
LuaTypes.MINUS, LuaTypes.GETN
)}
val LOCAL_DEF = LuaPlaceholderStub.Type("LOCAL_DEF", ::LuaLocalDefImpl)
val SINGLE_ARG = LuaPlaceholderStub.Type("SINGLE_ARG", ::LuaSingleArgImpl)
val LIST_ARGS = LuaPlaceholderStub.Type("LIST_ARGS", ::LuaListArgsImpl)
val EXPR_LIST = LuaPlaceholderStub.Type("EXPR_LIST", ::LuaExprListImpl)
val NAME_LIST = LuaPlaceholderStub.Type("NAME_LIST", ::LuaNameListImpl)
val ASSIGN_STAT = LuaPlaceholderStub.Type("ASSIGN_STAT", ::LuaAssignStatImpl)
val VAR_LIST = LuaPlaceholderStub.Type("VAR_LIST", ::LuaVarListImpl)
val LOCAL_FUNC_DEF = LuaLocalFuncDefElementType()
val FUNC_BODY = LuaPlaceholderStub.Type("FUNC_BODY", ::LuaFuncBodyImpl)
val CLASS_METHOD_NAME = LuaPlaceholderStub.Type("CLASS_METHOD_NAME", ::LuaClassMethodNameImpl)
val CLOSURE_EXPR = LuaClosureExprType()
val PAREN_EXPR = LuaExprPlaceStub.Type("PAREN_EXPR", ::LuaParenExprImpl)
val CALL_EXPR = LuaExprPlaceStub.Type("CALL_EXPR", ::LuaCallExprImpl)
val UNARY_EXPR = LuaUnaryExprType()
val BINARY_EXPR = LuaBinaryExprType()
val RETURN_STAT = LuaPlaceholderStub.Type("RETURN_STAT", ::LuaReturnStatImpl)
val DO_STAT = LuaPlaceholderStub.Type("DO_STAT", ::LuaDoStatImpl)
val IF_STAT = LuaPlaceholderStub.Type("IF_STAT", ::LuaIfStatImpl)
val EXPR_STAT = LuaPlaceholderStub.Type("CALL_STAT", ::LuaExprStatImpl)
} | apache-2.0 | 66541f0e447334c8a62296fc8eddab91 | 45.642857 | 118 | 0.720031 | 3.756835 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/EditionContentParentViewHolder.kt | 2 | 1219 | package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.edition_content_parent_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.EditionContentParent
import ru.fantlab.android.ui.widgets.htmlview.HTMLTextView
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder
class EditionContentParentViewHolder : TreeViewBinder<EditionContentParentViewHolder.ViewHolder>() {
override val layoutId: Int = R.layout.edition_content_parent_row_item
override fun provideViewHolder(itemView: View) = ViewHolder(itemView)
override fun bindView(
holder: RecyclerView.ViewHolder, position: Int, node: TreeNode<*>, onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener?
) {
(holder as EditionContentParentViewHolder.ViewHolder)
val parentNode = node.content as EditionContentParent?
holder.title.html = "• " + parentNode!!.title
}
class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) {
var title: HTMLTextView = rootView.title
}
}
| gpl-3.0 | 34a5a43ade7a00014441ad605137e355 | 39.566667 | 125 | 0.815941 | 3.900641 | false | false | false | false |
googlearchive/android-ContentProviderPaging | kotlinApp/app/src/main/kotlin/com.example.android.contentproviderpaging/ImageClientFragment.kt | 3 | 6171 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.contentproviderpaging
import android.app.LoaderManager
import android.content.ContentResolver
import android.content.CursorLoader
import android.content.Loader
import android.database.Cursor
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import java.util.concurrent.atomic.AtomicInteger
/**
* Fragment that works as a client for accessing the DocumentsProvider
* ([ImageProvider].
*/
class ImageClientFragment : Fragment() {
private var mAdapter: ImageAdapter? = null
private var mLayoutManager: LinearLayoutManager? = null
private val mLoaderCallback = LoaderCallback()
/**
* The offset position for the ContentProvider to be used as a starting position to fetch
* the images from.
*/
private val mOffset = AtomicInteger(0)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_image_client, container, false)
}
override fun onViewCreated(rootView: View?, savedInstanceState: Bundle?) {
super.onViewCreated(rootView, savedInstanceState)
val activity = activity
val recyclerView = activity.findViewById<RecyclerView>(R.id.recyclerview)
if (mLayoutManager == null) {
mLayoutManager = LinearLayoutManager(activity)
}
recyclerView.layoutManager = mLayoutManager
if (mAdapter == null) {
mAdapter = ImageAdapter(activity)
}
recyclerView.adapter = mAdapter
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
val lastVisiblePosition = mLayoutManager!!.findLastVisibleItemPosition()
if (lastVisiblePosition >= mAdapter!!.fetchedItemCount) {
Log.d(TAG,
"Fetch new images. LastVisiblePosition: " + lastVisiblePosition
+ ", NonEmptyItemCount: " + mAdapter!!.fetchedItemCount)
val pageId = lastVisiblePosition / LIMIT
// Fetch new images once the last fetched item becomes visible
activity.loaderManager
.restartLoader(pageId, null, mLoaderCallback)
}
}
})
val showButton = rootView!!.findViewById<Button>(R.id.button_show)
showButton.setOnClickListener {
activity.loaderManager.restartLoader(0, null, mLoaderCallback)
showButton.visibility = View.GONE
}
}
private inner class LoaderCallback : LoaderManager.LoaderCallbacks<Cursor> {
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
val activity = [email protected]
return object : CursorLoader(activity) {
override fun loadInBackground(): Cursor {
val bundle = Bundle()
bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, mOffset.toInt())
bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, LIMIT)
return activity.contentResolver
.query(ImageContract.CONTENT_URI, null, bundle, null)
}
}
}
override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor) {
val extras = cursor.extras
val totalSize = extras.getInt(ContentResolver.EXTRA_TOTAL_SIZE)
mAdapter!!.setTotalSize(totalSize)
val beforeCount = mAdapter!!.fetchedItemCount
while (cursor.moveToNext()) {
val displayName = cursor.getString(cursor.getColumnIndex(
ImageContract.Columns.DISPLAY_NAME))
val absolutePath = cursor.getString(cursor.getColumnIndex(
ImageContract.Columns.ABSOLUTE_PATH))
val imageDocument = ImageAdapter.ImageDocument(absolutePath, displayName)
mAdapter!!.add(imageDocument)
}
val cursorCount = cursor.count
if (cursorCount == 0) {
return
}
val activity = [email protected]
mAdapter!!.notifyItemRangeChanged(beforeCount, cursorCount)
val offsetSnapShot = mOffset.get()
val message = activity.resources
.getString(R.string.fetched_images_out_of, offsetSnapShot + 1,
offsetSnapShot + cursorCount, totalSize)
mOffset.addAndGet(cursorCount)
Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
}
override fun onLoaderReset(loader: Loader<Cursor>) {
}
}
companion object {
private val TAG = "ImageClientFragment"
/** The number of fetched images in a single query to the DocumentsProvider. */
private val LIMIT = 10
fun newInstance(): ImageClientFragment {
val args = Bundle()
val fragment = ImageClientFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 85130acd25f7cbd6d858363d9974a0a4 | 37.811321 | 93 | 0.641873 | 5.296996 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/lanes/AddLanesForm.kt | 1 | 10377 | package de.westnordost.streetcomplete.quests.lanes
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.annotation.AnyThread
import androidx.core.view.isGone
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.OtherAnswer
import de.westnordost.streetcomplete.quests.StreetSideRotater
import de.westnordost.streetcomplete.quests.lanes.LanesType.*
import de.westnordost.streetcomplete.view.dialogs.ValuePickerDialog
import kotlinx.android.synthetic.main.quest_lanes_select_type.view.*
import kotlinx.android.synthetic.main.quest_street_lanes_puzzle.view.*
import kotlinx.android.synthetic.main.view_little_compass.view.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class AddLanesForm : AbstractQuestFormAnswerFragment<LanesAnswer>(),
CoroutineScope by CoroutineScope(Dispatchers.Main) {
private var selectedLanesType: LanesType? = null
private var leftSide: Int = 0
private var rightSide: Int = 0
private var hasCenterLeftTurnLane: Boolean = false
private var lastRotation: Float = 0f
private var lastTilt: Float = 0f
override val contentPadding get() = selectedLanesType == null
private var puzzleView: LanesSelectPuzzle? = null
private var streetSideRotater: StreetSideRotater? = null
// just some shortcuts
private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic
private val isOneway get() = isForwardOneway || isReversedOneway
private val isForwardOneway get() = osmElement!!.tags["oneway"] == "yes" || osmElement!!.tags["junction"] == "roundabout"
private val isReversedOneway get() = osmElement!!.tags["oneway"] == "-1"
override val otherAnswers: List<OtherAnswer> get() {
val answers = mutableListOf<OtherAnswer>()
if (!isOneway && countryInfo.isCenterLeftTurnLaneKnown) {
answers.add(OtherAnswer(R.string.quest_lanes_answer_lanes_center_left_turn_lane) {
selectedLanesType = MARKED_SIDES
hasCenterLeftTurnLane = true
setStreetSideLayout()
})
}
return answers
}
//region Lifecycle
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (savedInstanceState != null) {
selectedLanesType = savedInstanceState.getString(LANES_TYPE)?.let { LanesType.valueOf(it) }
leftSide = savedInstanceState.getInt(LANES_LEFT, 0)
rightSide = savedInstanceState.getInt(LANES_RIGHT, 0)
hasCenterLeftTurnLane = savedInstanceState.getBoolean(CENTER_LEFT_TURN_LANE)
}
if (selectedLanesType == null || selectedLanesType == UNMARKED) {
setSelectLanesTypeLayout()
} else {
setStreetSideLayout()
}
}
@AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) {
streetSideRotater?.onMapOrientation(rotation, tilt)
lastRotation = rotation
lastTilt = tilt
}
override fun isFormComplete(): Boolean = when (selectedLanesType) {
null -> false
UNMARKED -> true
MARKED_SIDES -> leftSide > 0 && rightSide > 0
else -> leftSide > 0 || rightSide > 0
}
override fun isRejectingClose() = leftSide > 0 || rightSide > 0
override fun onClickOk() {
val totalLanes = leftSide + rightSide
when(selectedLanesType) {
MARKED -> applyAnswer(MarkedLanes(totalLanes))
UNMARKED -> applyAnswer(UnmarkedLanes)
MARKED_SIDES -> {
val forwardLanes = if (isLeftHandTraffic) leftSide else rightSide
val backwardLanes = if (isLeftHandTraffic) rightSide else leftSide
applyAnswer(MarkedLanesSides(forwardLanes, backwardLanes, hasCenterLeftTurnLane))
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(LANES_TYPE, selectedLanesType?.name)
outState.putInt(LANES_LEFT, leftSide)
outState.putInt(LANES_RIGHT, rightSide)
outState.putBoolean(CENTER_LEFT_TURN_LANE, hasCenterLeftTurnLane)
}
override fun onDestroy() {
super.onDestroy()
coroutineContext.cancel()
}
//endregion
//region Select lanes type
private fun setSelectLanesTypeLayout() {
val view = setContentView(R.layout.quest_lanes_select_type)
val unmarkedLanesButton = view.unmarkedLanesButton
unmarkedLanesButton.isSelected = selectedLanesType == UNMARKED
unmarkedLanesButton.setOnClickListener {
val wasSelected = unmarkedLanesButton.isSelected
unmarkedLanesButton.isSelected = !wasSelected
selectedLanesType = if (wasSelected) null else UNMARKED
checkIsFormComplete()
}
view.markedLanesButton.setOnClickListener {
selectedLanesType = MARKED
unmarkedLanesButton.isSelected = false
checkIsFormComplete()
askLanesAndSwitchToStreetSideLayout()
}
view.markedLanesOddButton.isGone = isOneway
view.markedLanesOddButton.setOnClickListener {
selectedLanesType = MARKED_SIDES
unmarkedLanesButton.isSelected = false
setStreetSideLayout()
}
}
private fun askLanesAndSwitchToStreetSideLayout() { launch {
val lanes = askForTotalNumberOfLanes()
setTotalLanesCount(lanes)
setStreetSideLayout()
}}
//endregion
//region Street side layout
private fun setStreetSideLayout() {
puzzleView?.let {
it.pause()
lifecycle.removeObserver(it)
}
val view = setContentView(R.layout.quest_street_lanes_puzzle)
puzzleView = view.puzzleView
lifecycle.addObserver(view.puzzleView)
when(selectedLanesType) {
MARKED -> {
view.puzzleView.onClickListener = this::selectTotalNumberOfLanes
view.puzzleView.onClickSideListener = null
}
MARKED_SIDES -> {
view.puzzleView.onClickListener = null
view.puzzleView.onClickSideListener = this::selectNumberOfLanesOnOneSide
}
}
view.puzzleView.isShowingLaneMarkings = selectedLanesType in listOf(MARKED, MARKED_SIDES)
view.puzzleView.isShowingBothSides = !isOneway
view.puzzleView.isForwardTraffic = if (isOneway) isForwardOneway else !isLeftHandTraffic
val shoulderLine = countryInfo.shoulderLine
view.puzzleView.shoulderLineColor =
if(shoulderLine.contains("yellow")) Color.YELLOW else Color.WHITE
view.puzzleView.shoulderLineStyle =
if(shoulderLine.contains("dashes"))
if (shoulderLine.contains("short")) LineStyle.SHORT_DASHES else LineStyle.DASHES
else
LineStyle.CONTINUOUS
view.puzzleView.centerLineColor = if(countryInfo.centerLine.contains("yellow")) Color.YELLOW else Color.WHITE
streetSideRotater = StreetSideRotater(view.puzzleViewRotateContainer, view.compassNeedleView, elementGeometry as ElementPolylinesGeometry)
streetSideRotater?.onMapOrientation(lastRotation, lastTilt)
updatePuzzleView()
}
private fun updatePuzzleView() {
puzzleView?.setLaneCounts(leftSide, rightSide, hasCenterLeftTurnLane)
checkIsFormComplete()
}
//endregion
//region Lane selection dialog
private fun selectNumberOfLanesOnOneSide(isRight: Boolean) { launch {
setLanesCount(askForNumberOfLanesOnOneSide(isRight), isRight)
}}
private suspend fun askForNumberOfLanesOnOneSide(isRight: Boolean): Int {
val currentLaneCount = if (isRight) rightSide else leftSide
return showSelectMarkedLanesDialogForOneSide(currentLaneCount)
}
private fun setLanesCount(lanes: Int, isRightSide: Boolean) {
if (isRightSide) rightSide = lanes
else leftSide = lanes
updatePuzzleView()
}
private fun selectTotalNumberOfLanes() {launch {
setTotalLanesCount(askForTotalNumberOfLanes())
}}
private suspend fun askForTotalNumberOfLanes(): Int {
val currentLaneCount = rightSide + leftSide
return if (selectedLanesType == MARKED) {
if (isOneway) {
showSelectMarkedLanesDialogForOneSide(currentLaneCount.takeIf { it > 0 })
} else {
showSelectMarkedLanesDialogForBothSides(currentLaneCount.takeIf { it > 0 })
}
} else {
throw IllegalStateException()
}
}
private fun setTotalLanesCount(lanes: Int) {
if (isOneway) {
leftSide = 0
rightSide = lanes
} else {
leftSide = lanes / 2
rightSide = lanes - lanes / 2
}
updatePuzzleView()
}
private suspend fun showSelectMarkedLanesDialogForBothSides(selectedValue: Int?) = suspendCoroutine<Int> { cont ->
ValuePickerDialog(requireContext(),
listOf(2,4,6,8,10,12,14),
selectedValue, null,
R.layout.quest_lanes_select_lanes,
{ cont.resume(it) }
).show()
}
private suspend fun showSelectMarkedLanesDialogForOneSide(selectedValue: Int?) = suspendCoroutine<Int> { cont ->
ValuePickerDialog(requireContext(),
listOf(1,2,3,4,5,6,7,8),
selectedValue, null,
R.layout.quest_lanes_select_lanes_one_side_only,
{ cont.resume(it) }
).show()
}
// endregion
companion object {
private const val LANES_TYPE = "lanes_type"
private const val LANES_LEFT = "lanes_left"
private const val LANES_RIGHT = "lanes_right"
private const val CENTER_LEFT_TURN_LANE = "center_left_turn_lane"
}
}
private enum class LanesType {
MARKED, MARKED_SIDES, UNMARKED
}
| gpl-3.0 | db788b13b0f492f8bedd35de1490c7db | 34.659794 | 146 | 0.672641 | 4.760092 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/runtime/collections/hash_map0.kt | 1 | 8220 | fun assertTrue(cond: Boolean) {
if (!cond)
println("FAIL")
}
fun assertFalse(cond: Boolean) {
if (cond)
println("FAIL")
}
fun assertEquals(value1: Any?, value2: Any?) {
if (value1 != value2)
println("FAIL")
}
fun assertNotEquals(value1: Any?, value2: Any?) {
if (value1 == value2)
println("FAIL")
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
println("FAIL")
}
fun testBasic() {
val m = HashMap<String, String>()
assertTrue(m.isEmpty())
assertEquals(0, m.size)
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertEquals(null, m.put("1", "a"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertFalse(m.isEmpty())
assertEquals(1, m.size)
assertFalse(m.containsKey("2"))
assertFalse(m.containsValue("b"))
assertEquals(null, m.get("2"))
assertEquals(null, m.put("2", "b"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("b"))
assertEquals("b", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(2, m.size)
assertEquals("b", m.put("2", "bb"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("a"))
assertTrue(m.containsValue("bb"))
assertEquals("bb", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(2, m.size)
assertEquals("a", m.remove("1"))
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("bb"))
assertEquals("bb", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(1, m.size)
assertEquals("bb", m.remove("2"))
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertFalse(m.containsKey("2"))
assertFalse(m.containsValue("bb"))
assertEquals(null, m.get("2"))
assertTrue(m.isEmpty())
assertEquals(0, m.size)
}
fun testRehashAndCompact() {
val m = HashMap<String, String>()
for (repeat in 1..10) {
val n = when (repeat) {
1 -> 1000
2 -> 10000
3 -> 10
else -> 100000
}
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
assertEquals(null, m.put(i.toString(), "val$i"))
assertTrue(m.containsKey(i.toString()))
assertEquals(i, m.size)
}
for (i in 1..n) {
assertTrue(m.containsKey(i.toString()))
}
for (i in 1..n) {
assertEquals("val$i", m.remove(i.toString()))
assertFalse(m.containsKey(i.toString()))
assertEquals(n - i, m.size)
}
assertTrue(m.isEmpty())
}
}
fun testClear() {
val m = HashMap<String, String>()
for (repeat in 1..10) {
val n = when (repeat) {
1 -> 1000
2 -> 10000
3 -> 10
else -> 100000
}
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
assertEquals(null, m.put(i.toString(), "val$i"))
assertTrue(m.containsKey(i.toString()))
assertEquals(i, m.size)
}
for (i in 1..n) {
assertTrue(m.containsKey(i.toString()))
}
m.clear()
assertEquals(0, m.size)
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
}
}
}
fun testEquals() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertTrue(m == expected)
assertTrue(m == mapOf("b" to "2", "c" to "3", "a" to "1")) // order does not matter
assertFalse(m == mapOf("a" to "1", "b" to "2", "c" to "4"))
assertFalse(m == mapOf("a" to "1", "b" to "2", "c" to "5"))
assertFalse(m == mapOf("a" to "1", "b" to "2"))
assertEquals(m.keys, expected.keys)
assertEquals(m.values, expected.values)
assertEquals(m.entries, expected.entries)
}
fun testHashCode() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertEquals(expected.hashCode(), m.hashCode())
assertEquals(expected.entries.hashCode(), m.entries.hashCode())
assertEquals(expected.keys.hashCode(), m.keys.hashCode())
assertEquals(listOf("1", "2", "3").hashCode(), m.values.hashCode())
}
fun testToString() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertEquals(expected.toString(), m.toString())
assertEquals(expected.entries.toString(), m.entries.toString())
assertEquals(expected.keys.toString(), m.keys.toString())
assertEquals(expected.values.toString(), m.values.toString())
}
fun testPutEntry() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
val e = expected.entries.iterator().next() as MutableMap.MutableEntry<String, String>
assertTrue(m.entries.contains(e))
assertTrue(m.entries.remove(e))
assertTrue(mapOf("b" to "2", "c" to "3") == m)
assertTrue(m.entries.add(e))
assertTrue(expected == m)
assertFalse(m.entries.add(e))
assertTrue(expected == m)
}
fun testRemoveAllEntries() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.entries.removeAll(mapOf("a" to "2", "b" to "3", "c" to "4").entries))
assertEquals(expected, m)
assertTrue(m.entries.removeAll(mapOf("b" to "22", "c" to "3", "d" to "4").entries))
assertNotEquals(expected, m)
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testRetainAllEntries() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.entries.retainAll(expected.entries))
assertEquals(expected, m)
assertTrue(m.entries.retainAll(mapOf("b" to "22", "c" to "3", "d" to "4").entries))
assertEquals(mapOf("c" to "3"), m)
}
fun testContainsAllValues() {
val m = HashMap(mapOf("a" to "1", "b" to "2", "c" to "3"))
assertTrue(m.values.containsAll(listOf("1", "2")))
assertTrue(m.values.containsAll(listOf("1", "2", "3")))
assertFalse(m.values.containsAll(listOf("1", "2", "3", "4")))
assertFalse(m.values.containsAll(listOf("2", "3", "4")))
}
fun testRemoveValue() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.remove("b"))
assertEquals(expected, m)
assertTrue(m.values.remove("2"))
assertEquals(mapOf("a" to "1", "c" to "3"), m)
}
fun testRemoveAllValues() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.removeAll(listOf("b", "c")))
assertEquals(expected, m)
assertTrue(m.values.removeAll(listOf("b", "3")))
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testRetainAllValues() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.retainAll(listOf("1", "2", "3")))
assertEquals(expected, m)
assertTrue(m.values.retainAll(listOf("1", "2", "c")))
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testEntriesIteratorSet() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
val it = m.iterator()
while (it.hasNext()) {
val entry = it.next()
entry.setValue(entry.value + "!")
}
assertNotEquals(expected, m)
assertEquals(mapOf("a" to "1!", "b" to "2!", "c" to "3!"), m)
}
fun main(args : Array<String>) {
testBasic()
testRehashAndCompact()
testClear()
testEquals()
testHashCode()
testToString()
testPutEntry()
testRemoveAllEntries()
testRetainAllEntries()
testContainsAllValues()
testRemoveValue()
testRemoveAllValues()
testRetainAllValues()
testEntriesIteratorSet()
//testDegenerateKeys()
println("OK")
} | apache-2.0 | 14f57ac37a54c30807dd43b07cabefd4 | 29.790262 | 89 | 0.584793 | 3.385502 | false | true | false | false |
soulnothing/HarmonyGen | src/main/kotlin/HarmonyGen/Util/configuration.kt | 1 | 2460 | package HarmonyGen.Util
import org.ini4j.Ini
import java.io.File
/**
* Method to read the configuration file.
*
* This reads the configuration file. The *param* noted below
* is optional. It defaults to the relative path **./config/settings.dev.ini**.
* This will be expanded for better environment support.
*
* The file is simply read, if log level is at debug it will be printed to the logs.
*
* @author soulnothing
* @since 0.1.0
* @param java.io.File A file object pointing at the target configuration file.
* @return org.ini4j.Ini The parse ini file.
*/
fun readConfig(config_file: File = File("./config/settings.dev.ini")): Ini {
val config: Ini = Ini(config_file)
// logger.debug("Reading config, received a value of $config")
return config
}
/**
* Read the configuration file and return the Config data class.
*
* See the read config function noted below. This function is largely a wrapper
* that does type handling and conversion. Mapping to the data class for Config.
*
* @see HarmonyGen.Util.readConfig
* @see HarmonyGen.Util.Config
* @author soulnothing
* @since 0.1.0
* @return HarmonyGen.Util.Config A config data class.
*/
fun getConfig(): Config {
val config = readConfig()
return Config(
LastFMAPIKey = config.get("LastFM", "api_key"),
LastFMAPISecret = config.get("LastFM", "api_secret"),
SpotifyClientID = config.get("Spotify", "client_id"),
SpotifyClientSecret = config.get("Spotify", "client_secret"),
SpotifyScopes = config.get("Spotify", "scopes").split(","),
SpotifyPlaylist = config.get("Spotify", "playlist"),
Secret = config.get("HarmonyGen", "secret"),
MaxTracks = config.get("HarmonyGen", "playlist_length").toInt(),
Applications = config.get("HarmonyGen", "applications").split(",").toList(),
Database = config.get("Database", "database"),
DatabaseHost = config.get("Database", "host"),
DatabaseUser = config.get("Database", "user"),
DatabasePassword = config.get("Database", "password"),
DatabasePort = config.get("Database", "port").toInt(),
MusicBrainzDatabase = config.get("MusicBrainzDatabase", "database"),
MusicBrainzHost = config.get("MusicBrainzDatabase", "host"),
MusicBrainzPort = config.get("MusicBrainzDatabase", "port").toInt(),
MusicBrainzUser = config.get("MusicBrainzDatabase", "user"),
MusicBrainzPassword = config.get("MusicBrainzDatabase", "password")
)
} | bsd-3-clause | 479c70133f9420fbe9fa442e50dfea13 | 38.693548 | 84 | 0.69065 | 3.682635 | false | true | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt | 1 | 4009 | package eu.kanade.tachiyomi.data.database
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.db.SupportSQLiteOpenHelper
import eu.kanade.tachiyomi.data.database.tables.*
import exh.metadata.sql.tables.SearchMetadataTable
import exh.metadata.sql.tables.SearchTagTable
import exh.metadata.sql.tables.SearchTitleTable
class DbOpenCallback : SupportSQLiteOpenHelper.Callback(DATABASE_VERSION) {
companion object {
/**
* Name of the database file.
*/
const val DATABASE_NAME = "tachiyomi.db"
/**
* Version of the database.
*/
const val DATABASE_VERSION = 9 // [EXH]
}
override fun onCreate(db: SupportSQLiteDatabase) = with(db) {
execSQL(MangaTable.createTableQuery)
execSQL(ChapterTable.createTableQuery)
execSQL(TrackTable.createTableQuery)
execSQL(CategoryTable.createTableQuery)
execSQL(MangaCategoryTable.createTableQuery)
execSQL(HistoryTable.createTableQuery)
// EXH -->
execSQL(SearchMetadataTable.createTableQuery)
execSQL(SearchTagTable.createTableQuery)
execSQL(SearchTitleTable.createTableQuery)
// EXH <--
// DB indexes
execSQL(MangaTable.createUrlIndexQuery)
execSQL(MangaTable.createLibraryIndexQuery)
execSQL(ChapterTable.createMangaIdIndexQuery)
execSQL(ChapterTable.createUnreadChaptersIndexQuery)
execSQL(HistoryTable.createChapterIdIndexQuery)
// EXH -->
db.execSQL(SearchMetadataTable.createUploaderIndexQuery)
db.execSQL(SearchMetadataTable.createIndexedExtraIndexQuery)
db.execSQL(SearchTagTable.createMangaIdIndexQuery)
db.execSQL(SearchTagTable.createNamespaceNameIndexQuery)
db.execSQL(SearchTitleTable.createMangaIdIndexQuery)
db.execSQL(SearchTitleTable.createTitleIndexQuery)
// EXH <--
}
override fun onUpgrade(db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 2) {
db.execSQL(ChapterTable.sourceOrderUpdateQuery)
// Fix kissmanga covers after supporting cloudflare
db.execSQL("""UPDATE mangas SET thumbnail_url =
REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""")
}
if (oldVersion < 3) {
// Initialize history tables
db.execSQL(HistoryTable.createTableQuery)
db.execSQL(HistoryTable.createChapterIdIndexQuery)
}
if (oldVersion < 4) {
db.execSQL(ChapterTable.bookmarkUpdateQuery)
}
if (oldVersion < 5) {
db.execSQL(ChapterTable.addScanlator)
}
if (oldVersion < 6) {
db.execSQL(TrackTable.addTrackingUrl)
}
if (oldVersion < 7) {
db.execSQL(TrackTable.addLibraryId)
}
if (oldVersion < 8) {
db.execSQL("DROP INDEX IF EXISTS mangas_favorite_index")
db.execSQL(MangaTable.createLibraryIndexQuery)
db.execSQL(ChapterTable.createUnreadChaptersIndexQuery)
}
// EXH -->
if (oldVersion < 9) {
db.execSQL(SearchMetadataTable.createTableQuery)
db.execSQL(SearchTagTable.createTableQuery)
db.execSQL(SearchTitleTable.createTableQuery)
db.execSQL(SearchMetadataTable.createUploaderIndexQuery)
db.execSQL(SearchMetadataTable.createIndexedExtraIndexQuery)
db.execSQL(SearchTagTable.createMangaIdIndexQuery)
db.execSQL(SearchTagTable.createNamespaceNameIndexQuery)
db.execSQL(SearchTitleTable.createMangaIdIndexQuery)
db.execSQL(SearchTitleTable.createTitleIndexQuery)
}
// Remember to increment any Tachiyomi database upgrades after this
// EXH <--
}
override fun onConfigure(db: SupportSQLiteDatabase) {
db.setForeignKeyConstraintsEnabled(true)
}
}
| apache-2.0 | c05cca6bb851c4ff43f62de6ccadf99a | 37.548077 | 97 | 0.672237 | 4.853511 | false | false | false | false |
haozileung/test | src/main/kotlin/com/haozileung/web/domain/logging/OperateLog.kt | 1 | 626 | /*
* Powered By [rapid-framework]
* Web Site: http://www.rapid-framework.org.cn
* Google Code: http://code.google.com/p/rapid-framework/
* Since 2008 - 2016
*/
package com.haozileung.web.domain.logging
import java.io.Serializable
/**
* @author Haozi
* *
* @version 1.0
* *
* @since 1.0
*/
data class OperateLog(var operateLogId: Long? = null,
var operationId: Long? = null,
var params: String? = null,
var userId: Long? = null,
var ipAddress: String? = null,
var remarks: String? = null) : Serializable | mit | 8076313775f34da704cffb43708688eb | 25.125 | 65 | 0.5623 | 3.597701 | false | false | false | false |
quarck/SmartNotify | app/src/main/java/com/github/quarck/smartnotify/NotificationReceiverService.kt | 1 | 10031 | /*
* Copyright (c) 2014, Sergey Parshin, [email protected]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of developer (Sergey Parshin) nor the
* names of other project contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.quarck.smartnotify
import java.util.ArrayList
import java.util.HashMap
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
class NotificationReceiverService : NotificationListenerService(), Handler.Callback
{
private var alarm: Alarm? = null
private val messenger = Messenger(Handler(this))
private var settings: Settings? = null
private var pkgSettings: PackageSettings? = null
override fun handleMessage(msg: Message): Boolean
{
var ret = true
Lw.d(TAG, "handleMessage, msg=" + msg.what)
when (msg.what)
{
MSG_CHECK_PERMISSIONS -> ret = handleCheckPermissions(msg)
MSG_LIST_NOTIFICATIONS -> ret = handleListNotifications(msg)
MSG_RELOAD_SETTINGS ->
{
Lw.d(TAG, "Explicit request to reload config")
update(null)
}
MSG_LIST_RECENT_NOTIFICATIONS ->
{
Lw.d(TAG, "Req for recent notifications")
sendRecent(msg)
}
MSG_TOGGLE_MUTE ->
{
Lw.d(TAG, "Toggling mute")
GlobalState.setIsMuted(this, !GlobalState.getIsMuted(this))
update(null)
}
}
return ret
}
private fun handleCheckPermissions(msg: Message): Boolean
{
Lw.d(TAG, "handleCheckPermissions")
try
{
activeNotifications
}
catch (ex: NullPointerException)
{
Lw.e(TAG, "Got exception, have no permissions!")
reply(msg, Message.obtain(null, MSG_NO_PERMISSIONS, 0, 0))
}
return true
}
private fun handleListNotifications(msg: Message): Boolean
{
Lw.d(TAG, "handleListNotifications")
try
{
val notifications = activeNotifications
val `val` = arrayOfNulls<String>(notifications.size())
var idx = 0
for (notification in notifications)
{
Lw.d(TAG, "Sending info about notification " + notification)
`val`[idx++] = notification.packageName
}
reply(msg, Message.obtain(null, MSG_LIST_NOTIFICATIONS, 0, 0, `val`))
}
catch (ex: NullPointerException)
{
Lw.e(TAG, "Got exception, have no permissions!")
reply(msg, Message.obtain(null, MSG_NO_PERMISSIONS, 0, 0))
}
return true
}
private fun sendRecent(msg: Message): Boolean
{
Lw.d(TAG, "sendRecent")
val notifications = getRecentNotifications()
if (notifications != null)
reply(msg, Message.obtain(null, MSG_LIST_RECENT_NOTIFICATIONS, 0, 0, notifications))
return true
}
private fun reply(msgIn: Message, msgOut: Message)
{
try
{
msgIn.replyTo.send(msgOut)
}
catch (e: RemoteException)
{
e.printStackTrace()
}
}
override fun onCreate()
{
super.onCreate()
Lw.d(TAG, "onCreate()")
Lw.d(TAG, "AlarmReceiver")
alarm = Alarm()
Lw.d(TAG, "Settings")
settings = Settings(this)
Lw.d(TAG, "PackageSettings")
pkgSettings = PackageSettings(this)
CallStateTracker.start(this)
}
override fun onDestroy()
{
Lw.d(TAG, "onDestroy (??)")
super.onDestroy()
}
override fun onBind(intent: Intent): IBinder?
{
if (intent.getBooleanExtra(configServiceExtra, false))
return messenger.binder
return super.onBind(intent)
}
private fun update(addedOrRemoved: StatusBarNotification?)
{
Lw.d(TAG, "update")
if (addedOrRemoved != null && addedOrRemoved.packageName != Consts.packageName)
{
synchronized (NotificationReceiverService::class.java) {
recentNotifications.put(
addedOrRemoved.packageName,
System.currentTimeMillis())
if (recentNotifications.size > 100)
cleanupRecentNotifications()
}
}
if (!settings!!.isServiceEnabled)
{
Lw.d(TAG, "Service is disabled, cancelling all the alarms and returning")
alarm!!.cancelAlarm(this)
if (GlobalState.getLastCountHandledNotifications(this) != 0)
{
OngoingNotificationManager.cancelOngoingNotification(this)
GlobalState.setLastCountHandledNotifications(this, 0)
}
return
}
var notifications: Array<StatusBarNotification>? = null
try
{
notifications = activeNotifications
}
catch (ex: NullPointerException)
{
Lw.e(TAG, "Got exception while obtaining list of notifications, have no permissions!")
}
var cntHandledNotifications = 0
var minReminderInterval = Integer.MAX_VALUE
if (notifications != null)
{
Lw.d(TAG, "Total number of notifications currently active: " + notifications.size())
for (notification in notifications)
{
Lw.d(TAG, "Checking notification" + notification)
val packageName = notification.packageName
if (packageName == Consts.packageName)
{
Lw.d(TAG, "That's ours, ignoring")
continue
}
Lw.d(TAG, "Package name is " + packageName)
val pkg = pkgSettings!!.getPackage(packageName)
if (pkg != null && pkg.isHandlingThis)
{
Lw.d(TAG, "We are handling this!")
++cntHandledNotifications
if (pkg.remindIntervalSeconds < minReminderInterval)
{
minReminderInterval = pkg.remindIntervalSeconds
Lw.d(TAG, "remind interval updated to $minReminderInterval seconds")
}
}
else
{
if (pkg == null)
Lw.d(TAG, "No settings for package " + packageName)
else
Lw.d(TAG, "There are settings for packageName: $pkg, but it is not currently handled")
}
}
Lw.d(TAG, "Currently known packages: ")
for (pkg in pkgSettings!!.allPackages)
{
Lw.d(TAG, ">> " + pkg)
}
}
else
{
Lw.e(TAG, "Can't get list of notifications. WE HAVE NO PERMISSION!! ")
}
if (cntHandledNotifications != 0)
{
Lw.d(TAG, "(Re)Setting alarm with interval $minReminderInterval seconds")
alarm!!.setAlarmMillis(this, minReminderInterval * 1000)
if ((GlobalState.getLastCountHandledNotifications(this) != cntHandledNotifications) && settings!!.isOngoingNotificationEnabled)
{
GlobalState.setLastCountHandledNotifications(this, cntHandledNotifications)
OngoingNotificationManager.showUpdateOngoingNotification(this)
}
}
else if (GlobalState.getIsMuted(this))
// if we are muted - always show the notification also
{
Lw.d(TAG, "Nothing to notify about, cancelling alarm, if any, but setting notification since we are muted")
alarm!!.cancelAlarm(this)
if ((GlobalState.getLastCountHandledNotifications(this) != cntHandledNotifications) && settings!!.isOngoingNotificationEnabled)
{
GlobalState.setLastCountHandledNotifications(this, 0)
OngoingNotificationManager.showUpdateOngoingNotification(this)
}
}
else
{
Lw.d(TAG, "Nothing to notify about, cancelling alarm, if any")
alarm!!.cancelAlarm(this)
if (GlobalState.getLastCountHandledNotifications(this) != 0)
{
GlobalState.setLastCountHandledNotifications(this, 0)
OngoingNotificationManager.cancelOngoingNotification(this)
}
}
}
override fun onNotificationPosted(arg0: StatusBarNotification)
{
Lw.d(TAG, "Notification posted: " + arg0)
update(arg0)
}
override fun onNotificationRemoved(arg0: StatusBarNotification)
{
Lw.d(TAG, "Notification removed: " + arg0)
update(arg0)
}
companion object
{
val TAG = "Service"
val configServiceExtra = "configService"
val MSG_CHECK_PERMISSIONS = 1
val MSG_NO_PERMISSIONS = 2
val MSG_LIST_NOTIFICATIONS = 3
val MSG_RELOAD_SETTINGS = 4
val MSG_LIST_RECENT_NOTIFICATIONS = 5
val MSG_TOGGLE_MUTE = 6
private val recentNotifications = HashMap<String, Long>()
private fun cleanupRecentNotifications()
{
val timeNow = System.currentTimeMillis()
val listToCleanup = ArrayList<String>()
for (entry in recentNotifications.entries)
{
val key = entry.key
val value = entry.value
if (timeNow - value.toLong() > 1000 * 3600 * 24)
// older than 1 day
{
listToCleanup.add(key)
recentNotifications.remove(key)
}
}
for (key in listToCleanup)
recentNotifications.remove(key)
}
fun getRecentNotifications(): Array<String>
{
Lw.d(TAG, "getRecentNotifications")
var notifications: Array<String?>? = null
synchronized (NotificationReceiverService::class.java) {
cleanupRecentNotifications()
notifications = arrayOfNulls<String>(recentNotifications.size)
var idx = 0
for (key in recentNotifications.keys)
{
notifications!![idx++] = key
}
}
return notifications!!
.filter {it != null}
.map {it!!}
.toTypedArray()
}
}
}
| bsd-3-clause | ac76e724e7fc9fd14185a112f0174670 | 24.786632 | 130 | 0.707606 | 3.633104 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/glance/UpdatesGridGlanceWidget.kt | 1 | 10996 | package eu.kanade.tachiyomi.glance
import android.app.Application
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import androidx.glance.GlanceModifier
import androidx.glance.Image
import androidx.glance.ImageProvider
import androidx.glance.LocalContext
import androidx.glance.LocalSize
import androidx.glance.action.clickable
import androidx.glance.appwidget.CircularProgressIndicator
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.action.actionStartActivity
import androidx.glance.appwidget.appWidgetBackground
import androidx.glance.appwidget.updateAll
import androidx.glance.background
import androidx.glance.layout.Alignment
import androidx.glance.layout.Box
import androidx.glance.layout.Column
import androidx.glance.layout.ContentScale
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.padding
import androidx.glance.layout.size
import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
import coil.executeBlocking
import coil.imageLoader
import coil.request.CachePolicy
import coil.request.ImageRequest
import coil.size.Precision
import coil.size.Scale
import coil.transform.RoundedCornersTransformation
import eu.kanade.data.DatabaseHandler
import eu.kanade.domain.manga.model.MangaCover
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.core.security.SecurityPreferences
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.system.dpToPx
import kotlinx.coroutines.MainScope
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import view.UpdatesView
import java.util.Calendar
import java.util.Date
class UpdatesGridGlanceWidget : GlanceAppWidget() {
private val app: Application by injectLazy()
private val preferences: SecurityPreferences by injectLazy()
private val coroutineScope = MainScope()
var data: List<Pair<Long, Bitmap?>>? = null
override val sizeMode = SizeMode.Exact
@Composable
override fun Content() {
// App lock enabled, don't do anything
if (preferences.useAuthenticator().get()) {
WidgetNotAvailable()
} else {
UpdatesWidget()
}
}
@Composable
private fun WidgetNotAvailable() {
val intent = Intent(LocalContext.current, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
Box(
modifier = GlanceModifier
.clickable(actionStartActivity(intent))
.then(ContainerModifier)
.padding(8.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = stringResource(R.string.appwidget_unavailable_locked),
style = TextStyle(
color = ColorProvider(R.color.appwidget_on_secondary_container),
fontSize = 12.sp,
textAlign = TextAlign.Center,
),
)
}
}
@Composable
private fun UpdatesWidget() {
val (rowCount, columnCount) = LocalSize.current.calculateRowAndColumnCount()
Column(
modifier = ContainerModifier,
verticalAlignment = Alignment.CenterVertically,
horizontalAlignment = Alignment.CenterHorizontally,
) {
val inData = data
if (inData == null) {
CircularProgressIndicator()
} else if (inData.isEmpty()) {
Text(text = stringResource(R.string.information_no_recent))
} else {
(0 until rowCount).forEach { i ->
val coverRow = (0 until columnCount).mapNotNull { j ->
inData.getOrNull(j + (i * columnCount))
}
if (coverRow.isNotEmpty()) {
Row(
modifier = GlanceModifier
.padding(vertical = 4.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically,
) {
coverRow.forEach { (mangaId, cover) ->
Box(
modifier = GlanceModifier
.padding(horizontal = 3.dp),
contentAlignment = Alignment.Center,
) {
val intent = Intent(LocalContext.current, MainActivity::class.java).apply {
action = MainActivity.SHORTCUT_MANGA
putExtra(MangaController.MANGA_EXTRA, mangaId)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
// https://issuetracker.google.com/issues/238793260
addCategory(mangaId.toString())
}
Cover(
modifier = GlanceModifier.clickable(actionStartActivity(intent)),
cover = cover,
)
}
}
}
}
}
}
}
}
@Composable
private fun Cover(
modifier: GlanceModifier = GlanceModifier,
cover: Bitmap?,
) {
Box(
modifier = modifier
.size(width = CoverWidth, height = CoverHeight)
.appWidgetInnerRadius(),
) {
if (cover != null) {
Image(
provider = ImageProvider(cover),
contentDescription = null,
modifier = GlanceModifier
.fillMaxSize()
.appWidgetInnerRadius(),
contentScale = ContentScale.Crop,
)
} else {
// Enjoy placeholder
Image(
provider = ImageProvider(R.drawable.appwidget_cover_error),
contentDescription = null,
modifier = GlanceModifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
}
}
}
fun loadData(list: List<UpdatesView>? = null) {
coroutineScope.launchIO {
// Don't show anything when lock is active
if (preferences.useAuthenticator().get()) {
updateAll(app)
return@launchIO
}
val manager = GlanceAppWidgetManager(app)
val ids = manager.getGlanceIds(this@UpdatesGridGlanceWidget::class.java)
if (ids.isEmpty()) return@launchIO
val processList = list
?: Injekt.get<DatabaseHandler>()
.awaitList { updatesViewQueries.updates(after = DateLimit.timeInMillis) }
val (rowCount, columnCount) = ids
.flatMap { manager.getAppWidgetSizes(it) }
.maxBy { it.height.value * it.width.value }
.calculateRowAndColumnCount()
data = prepareList(processList, rowCount * columnCount)
ids.forEach { update(app, it) }
}
}
private fun prepareList(processList: List<UpdatesView>, take: Int): List<Pair<Long, Bitmap?>> {
// Resize to cover size
val widthPx = CoverWidth.value.toInt().dpToPx
val heightPx = CoverHeight.value.toInt().dpToPx
val roundPx = app.resources.getDimension(R.dimen.appwidget_inner_radius)
return processList
.distinctBy { it.mangaId }
.take(take)
.map { updatesView ->
val request = ImageRequest.Builder(app)
.data(
MangaCover(
mangaId = updatesView.mangaId,
sourceId = updatesView.source,
isMangaFavorite = updatesView.favorite,
url = updatesView.thumbnailUrl,
lastModified = updatesView.coverLastModified,
),
)
.memoryCachePolicy(CachePolicy.DISABLED)
.precision(Precision.EXACT)
.size(widthPx, heightPx)
.scale(Scale.FILL)
.let {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
it.transformations(RoundedCornersTransformation(roundPx))
} else {
it // Handled by system
}
}
.build()
Pair(updatesView.mangaId, app.imageLoader.executeBlocking(request).drawable?.toBitmap())
}
}
companion object {
val DateLimit: Calendar
get() = Calendar.getInstance().apply {
time = Date()
add(Calendar.MONTH, -3)
}
}
}
private val CoverWidth = 58.dp
private val CoverHeight = 87.dp
private val ContainerModifier = GlanceModifier
.fillMaxSize()
.background(ImageProvider(R.drawable.appwidget_background))
.appWidgetBackground()
.appWidgetBackgroundRadius()
/**
* Calculates row-column count.
*
* Row
* Numerator: Container height - container vertical padding
* Denominator: Cover height + cover vertical padding
*
* Column
* Numerator: Container width - container horizontal padding
* Denominator: Cover width + cover horizontal padding
*
* @return pair of row and column count
*/
private fun DpSize.calculateRowAndColumnCount(): Pair<Int, Int> {
// Hack: Size provided by Glance manager is not reliable so take at least 1 row and 1 column
// Set max to 10 children each direction because of Glance limitation
val rowCount = (height.value / 95).toInt().coerceIn(1, 10)
val columnCount = (width.value / 64).toInt().coerceIn(1, 10)
return Pair(rowCount, columnCount)
}
| apache-2.0 | 1a1c0feb9bb593fd5b13800da59ec31d | 37.313589 | 111 | 0.575573 | 5.361287 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/di/module/NetworkModule.kt | 1 | 4632 | package com.rolandvitezhu.todocloud.di.module
import com.google.gson.GsonBuilder
import com.rolandvitezhu.todocloud.app.AppController
import com.rolandvitezhu.todocloud.database.TodoCloudDatabase
import com.rolandvitezhu.todocloud.helper.BooleanTypeAdapter
import com.rolandvitezhu.todocloud.network.ApiService
import dagger.Module
import dagger.Provides
import kotlinx.coroutines.runBlocking
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import javax.inject.Singleton
/**
* It defines that for the Dagger 2, how to create instances of these objects
* as we inject them into other classes.
*/
@Module
class NetworkModule {
// val BASE_URL = "http://192.168.1.100/"; // LAN IP
// val BASE_URL = "http://192.168.56.1/"; // Genymotion IP
// val BASE_URL = "http://169.254.50.78/"; // Genymotion IP - Current
// val BASE_URL = "http://10.0.2.2/"; // AVD IP
// val BASE_URL = "http://192.168.173.1/"; // ad hoc network IP
val BASE_URL = "http://todocloud.000webhostapp.com/" // 000webhost IP
@Provides
@Singleton
fun provideRetrofit(): Retrofit {
val clientBuilder = OkHttpClient.Builder()
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
clientBuilder.addInterceptor(loggingInterceptor)
clientBuilder.addInterceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
var apiKey: String?
runBlocking {
apiKey = TodoCloudDatabase.
getInstance(AppController.appContext.applicationContext).
todoCloudDatabaseDao.getCurrentApiKey()
}
val headersBuilder = Headers.Builder()
// Add Authorization header
if (apiKey != null) {
headersBuilder.add("authorization", apiKey)
// Remove every headers to prevent issues and add new headers only after that
requestBuilder.headers(headersBuilder.build())
}
val request = requestBuilder.build()
chain.proceed(request)
}
val gsonBuilder = GsonBuilder()
.setLenient()
.serializeNulls()
.disableHtmlEscaping()
.registerTypeAdapter(Boolean::class.javaObjectType, BooleanTypeAdapter())
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(clientBuilder.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.build()
}
@Provides
@Singleton
fun provideApiService(): ApiService {
val clientBuilder = OkHttpClient.Builder()
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
clientBuilder.addInterceptor(loggingInterceptor)
clientBuilder.addInterceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
var apiKey: String?
runBlocking {
apiKey = TodoCloudDatabase.getInstance(AppController.appContext.applicationContext).
todoCloudDatabaseDao.getCurrentApiKey()
}
val headersBuilder = Headers.Builder()
// Add the authorization header
if (apiKey != null) {
headersBuilder.add("authorization", apiKey)
// Remove every headers to prevent issues and add new headers only after that
requestBuilder.headers(headersBuilder.build())
}
val request = requestBuilder.build()
chain.proceed(request)
}
val gsonBuilder = GsonBuilder()
.setLenient()
.serializeNulls()
.disableHtmlEscaping()
.registerTypeAdapter(Boolean::class.javaObjectType, BooleanTypeAdapter())
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(clientBuilder.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
.build()
return retrofit.create(ApiService::class.java)
}
} | mit | 9badeea801e252165b0a0eb0137590e6 | 36.666667 | 100 | 0.642703 | 5.379791 | false | false | false | false |
Hexworks/zircon | zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/animations/ZirconLogoExample.kt | 1 | 3932 | package org.hexworks.zircon.examples.animations
import org.hexworks.zircon.api.CP437TilesetResources
import org.hexworks.zircon.api.ColorThemes
import org.hexworks.zircon.api.DrawSurfaces
import org.hexworks.zircon.api.SwingApplications
import org.hexworks.zircon.api.animation.Animation
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.extensions.toScreen
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.api.resource.REXPaintResources
import org.hexworks.zircon.internal.animation.impl.DefaultAnimationFrame
import kotlin.jvm.JvmStatic
object ZirconLogoExample {
val size = Size.create(59, 27)
@JvmStatic
fun main(args: Array<String>) {
val rex =
REXPaintResources.loadREXFile(ZirconLogoExample::class.java.getResourceAsStream("/rex_files/zircon_logo.xp")!!)
val screen = SwingApplications.startTileGrid(
AppConfig.newBuilder()
.withDefaultTileset(CP437TilesetResources.rexPaint20x20())
.withSize(size)
.build()
).toScreen()
val img = DrawSurfaces.tileGraphicsBuilder().withSize(size).build()
rex.toLayerList().forEach {
img.draw(it)
}
val builder = Animation.newBuilder()
(20 downTo 1).forEach { idx ->
val repeat = if (idx == 1) 40 else 1
builder.addFrame(
DefaultAnimationFrame(
size = size,
layers = listOf(
Layer.newBuilder()
.withTileGraphics(
img.toTileImage()
.transform { tc ->
tc.withBackgroundColor(
tc.backgroundColor
.darkenByPercent(idx.toDouble().div(20))
)
.withForegroundColor(
tc.foregroundColor
.darkenByPercent(idx.toDouble().div(20))
)
}.toTileGraphics()
)
.build().asInternalLayer()
),
repeatCount = repeat
)
)
}
(0..20).forEach { idx ->
val repeat = if (idx == 20) 20 else 1
builder.addFrame(
DefaultAnimationFrame(
size = size,
layers = listOf(
Layer.newBuilder()
.withTileGraphics(
img.toTileImage().transform { tc ->
tc.withBackgroundColor(
tc.backgroundColor
.darkenByPercent(idx.toDouble().div(20))
)
.withForegroundColor(
tc.foregroundColor
.darkenByPercent(idx.toDouble().div(20))
)
}.toTileGraphics()
)
.build().asInternalLayer()
),
repeatCount = repeat
)
)
}
val anim = builder
.withLoopCount(0)
.setPositionForAll(Position.zero())
.build()
screen.theme = ColorThemes.empty()
screen.display()
screen.start(anim)
}
}
| apache-2.0 | 5f607f9bfc8f2a91217228b4f8712a14 | 36.807692 | 123 | 0.459308 | 5.895052 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/ActivityViewHolder.kt | 1 | 4905 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.wordpress.android.R
import org.wordpress.android.databinding.StatsBlockActivityItemBinding
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ActivityItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ActivityItem.Box
import org.wordpress.android.util.ContentDescriptionListAnnouncer
import org.wordpress.android.util.extensions.viewBinding
private const val SIZE_PADDING = 32
private const val GAP = 8
private const val BLOCK_WIDTH = 104
private const val SPAN_COUNT = 7
class ActivityViewHolder(
parent: ViewGroup,
val binding: StatsBlockActivityItemBinding = parent.viewBinding(StatsBlockActivityItemBinding::inflate)
) : BlockListItemViewHolder(
binding.root
) {
private val coroutineScope = CoroutineScope(Dispatchers.Main)
fun bind(
item: ActivityItem
) = with(binding) {
drawBlock(firstActivity.activity, item.blocks[0].boxes)
firstActivity.label.text = item.blocks[0].label
if (item.blocks.size > 1) {
drawBlock(secondActivity.activity, item.blocks[1].boxes)
secondActivity.label.text = item.blocks[1].label
}
if (item.blocks.size > 2) {
drawBlock(thirdActivity.activity, item.blocks[2].boxes)
thirdActivity.label.text = item.blocks[2].label
}
val widthInDp = root.width / root.context.resources.displayMetrics.density
if (widthInDp > BLOCK_WIDTH + 2 * GAP) {
updateVisibility(item, widthInDp)
} else {
coroutineScope.launch {
delay(50)
updateVisibility(item, root.width / root.context.resources.displayMetrics.density)
}
}
setupBlocksForAccessibility(item)
}
private fun StatsBlockActivityItemBinding.setupBlocksForAccessibility(item: ActivityItem) {
val blocks = listOf(firstActivity, secondActivity, thirdActivity)
blocks.forEachIndexed { index, block ->
block.label.contentDescription = item.blocks[index].contentDescription
val announcer = ContentDescriptionListAnnouncer()
announcer.setupAnnouncer(
R.string.stats_posting_activity_empty_description,
R.string.stats_posting_activity_end_description,
R.string.stats_posting_activity_action,
requireNotNull(item.blocks[index].activityContentDescriptions), block.root
)
}
}
private fun StatsBlockActivityItemBinding.updateVisibility(
item: ActivityItem,
widthInDp: Float
) {
val canFitTwoBlocks = widthInDp > 2 * BLOCK_WIDTH + GAP + SIZE_PADDING
if (canFitTwoBlocks && item.blocks.size > 1) {
secondActivity.root.visibility = View.VISIBLE
} else {
secondActivity.root.visibility = View.GONE
}
val canFitThreeBlocks = widthInDp > 3 * BLOCK_WIDTH + 2 * GAP + SIZE_PADDING
if (canFitThreeBlocks && item.blocks.size > 2) {
firstActivity.root.visibility = View.VISIBLE
} else {
firstActivity.root.visibility = View.GONE
}
}
private fun drawBlock(recyclerView: RecyclerView, boxes: List<Box>) {
if (recyclerView.adapter == null) {
recyclerView.adapter = MonthActivityAdapter()
}
if (recyclerView.layoutManager == null) {
recyclerView.layoutManager = GridLayoutManager(
recyclerView.context,
SPAN_COUNT,
GridLayoutManager.HORIZONTAL,
false
)
}
if (recyclerView.itemDecorationCount == 0) {
val offsets = recyclerView.resources.getDimensionPixelSize(R.dimen.stats_activity_spacing)
recyclerView.addItemDecoration(
object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
outRect.set(offsets, offsets, offsets, offsets)
}
}
)
}
(recyclerView.adapter as MonthActivityAdapter).update(boxes)
}
}
| gpl-2.0 | fe75d0a5e68a2830dd46e4f549b1ea04 | 39.204918 | 107 | 0.638532 | 4.832512 | false | false | false | false |
felipefpx/utility-util-android-extensions | android-exts/src/main/kotlin/com/felipeporge/utility/ContextExt.kt | 1 | 3505 | @file:JvmName("ContextUtils")
package com.felipeporge.utility
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
/**
* Starts an activity.
* @param clazz Activity class.
*/
fun Context.startActivity(clazz: Class<*>): Boolean = fireIntent(Intent(this, clazz))
/**
* Fires an intent.
* @param intent The [Intent] to fire.
* @return [Boolean] True (successfully fired) or false (otherwise).
*/
fun Context.fireIntent(intent: Intent): Boolean {
intent.resolveActivity(packageManager)?.let {
startActivity(intent)
return true
}
return false
}
/**
* Opens an URL.
* @param url Url to open.
* @return False if there is no intent to resolve it.
*/
fun Context.openUrl(url: String): Boolean = openUrl(Uri.parse(url))
/**
* Opens an URL.
* @param uri Url to open.
* @return False if there is no intent to resolve it.
*/
fun Context.openUrl(uri: Uri): Boolean = fireIntent(Intent(Intent.ACTION_VIEW, uri))
/**
* Opens app in Google Play.
* @return False if there is no intent to resolve it.
*/
fun Context.openAppInGooglePlay(): Boolean = openUrl("https://play.google.com/store/apps/details?id=" + applicationInfo.packageName)
/**
* Opens publisher page in Google Play.
* @param pubName Publisher name.
* @return False if there is no intent to resolve it.
*/
fun Context.openPubAppsInGooglePlay(pubName: String): Boolean {
val uri = Uri.parse("https://play.google.com/store/search")
.buildUpon()
.appendQueryParameter("q", "pub:" + pubName)
.appendQueryParameter("c", "apps")
.build()
return openUrl(uri)
}
/**
* Opens an intent to send an ic_email.
* @param destinationEmail The destination ic_email.
* @param subject Email subject.
* @param body Email body.
* @return False if there is no intent to resolve it.
*/
fun Context.sendEmail(
destinationEmail: String,
subject: String,
body: String): Boolean {
val intent = Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", destinationEmail, null))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, body)
return fireIntent(intent)
}
/**
* Opens an intent to make a call.
* @param phone Phone number.
* @return False if there is no intent to resolve it.
*/
fun Context.openDialer(phone: String): Boolean {
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:" + phone)
return fireIntent(intent)
}
/**
* Copies a text to clipboard.
* @param textToCopy The text to copy.
* @return False if there is no clipboard manager ready.
*/
fun Context.copyToClipboard(textToCopy: String): Boolean {
val clipboard = (getSystemService(Activity.CLIPBOARD_SERVICE) as? ClipboardManager)
val clip = ClipData.newPlainText(packageName, textToCopy)
clipboard?.let {
clipboard.primaryClip = clip
return true
}
return false
}
/**
* Directions to an specific location.
* @param latitude - Destination latitude.
* @param longitude - Destination longitude.
* @return - False if there is no intent to resolve it.
*/
fun Context.directionsTo(
latitude: Double,
longitude: Double): Boolean {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?daddr=$latitude,$longitude"))
return fireIntent(intent)
} | apache-2.0 | c933eb2936b08d6f21576c30a1831310 | 27.504065 | 132 | 0.687589 | 3.830601 | false | false | false | false |
DanielGrech/anko | preview/robowrapper/src/org/jetbrains/kotlin/android/robowrapper/androidUtils/SpecialArgumentConverters.kt | 3 | 1914 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.robowrapper
import android.widget.ImageView
import android.widget.ImageView.ScaleType
import android.text.TextUtils.TruncateAt
import android.view.View
fun convertScaleType(value: ImageView.ScaleType) = when (value) {
ScaleType.CENTER -> "center"
ScaleType.CENTER_CROP -> "centerCrop"
ScaleType.CENTER_INSIDE -> "fitInside"
ScaleType.FIT_CENTER -> "fitCenter"
ScaleType.FIT_END -> "fitEnd"
ScaleType.FIT_START -> "fitStart"
ScaleType.FIT_XY -> "fitXY"
ScaleType.MATRIX -> "matrix"
else -> null
}
fun convertEllipsize(value: TruncateAt) = when (value) {
TruncateAt.END -> "end"
TruncateAt.MARQUEE -> "marquee"
TruncateAt.MIDDLE -> "middle"
TruncateAt.START -> "start"
TruncateAt.END_SMALL -> "end"
else -> "none"
}
/*
Value is a raw px value got from property getter.
Convert it to sp if a text-related parameter (following the Android developer guidelines), all other to dp
*/
fun resolveDimension(view: View, key: String, value: String): String {
val intValue = value.toDouble().toInt() //0.0
val useSp = (key == "textSize")
if (useSp) {
return "${intValue}sp"
} else {
val dpValue = view.getContext().px2dip(intValue).prettifyNumber()
return "${dpValue}dp"
}
} | apache-2.0 | e4898603d4099ed159c57032678908ce | 31.457627 | 110 | 0.69697 | 3.820359 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusTextModeAction.kt | 1 | 1175 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.status
import com.intellij.ide.ui.NavBarLocation
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.ui.ExperimentalUI
class StatusTextModeAction : ToggleAction(), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
val settings = UISettings.getInstance()
return !settings.showNavigationBar || settings.navBarLocation != NavBarLocation.BOTTOM
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
val settings = UISettings.getInstance()
settings.showNavigationBar = !state
settings.fireUISettingsChanged()
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = ExperimentalUI.isNewUI()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
| apache-2.0 | 6a522da3188f13d2790aeefb3cdb8b91 | 35.71875 | 120 | 0.788936 | 4.7 | false | false | false | false |
mdaniel/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/importing/MavenImportFlow.kt | 2 | 17920 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.project.importing
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ExternalStorageConfigurationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.idea.maven.MavenDisposable
import org.jetbrains.idea.maven.execution.BTWMavenConsole
import org.jetbrains.idea.maven.importing.MavenImportUtil
import org.jetbrains.idea.maven.importing.MavenProjectImporter
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenExplicitProfiles
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.project.actions.LookForNestedToggleAction
import org.jetbrains.idea.maven.server.MavenWrapperDownloader
import org.jetbrains.idea.maven.server.MavenWrapperSupport
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder
import org.jetbrains.idea.maven.utils.FileFinder
import org.jetbrains.idea.maven.utils.MavenProgressIndicator
import org.jetbrains.idea.maven.utils.MavenUtil
import java.util.*
@IntellijInternalApi
@ApiStatus.Internal
@ApiStatus.Experimental
class MavenImportFlow {
fun prepareNewImport(project: Project,
importPaths: ImportPaths,
generalSettings: MavenGeneralSettings,
importingSettings: MavenImportingSettings,
enabledProfiles: Collection<String>,
disabledProfiles: Collection<String>): MavenInitialImportContext {
val isVeryNewProject = project.getUserData<Boolean>(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == true
&& ModuleManager.getInstance(project).modules.size == 0
if (isVeryNewProject) {
ExternalStorageConfigurationManager.getInstance(project).isEnabled = true
}
val dummyModule = if (isVeryNewProject) createDummyModule(importPaths, project) else null
val manager = MavenProjectsManager.getInstance(project)
val profiles = MavenExplicitProfiles(enabledProfiles, disabledProfiles)
val ignorePaths = manager.ignoredFilesPaths
val ignorePatterns = manager.ignoredFilesPatterns
val importDisposable = Disposer.newDisposable("MavenImportFlow:importDisposable" + System.currentTimeMillis())
Disposer.register(MavenDisposable.getInstance(project), importDisposable)
return MavenInitialImportContext(project, importPaths, profiles, generalSettings, importingSettings, ignorePaths, ignorePatterns,
importDisposable,
dummyModule, Exception())
}
private fun createDummyModule(importPaths: ImportPaths, project: Project): Module? {
if (Registry.`is`("maven.create.dummy.module.on.first.import")) {
val contentRoot = when (importPaths) {
is FilesList -> ContainerUtil.getFirstItem(importPaths.poms).parent
is RootPath -> importPaths.path
}
return MavenImportUtil.createDummyModule(project, contentRoot)
}
return null
}
fun readMavenFiles(context: MavenInitialImportContext, indicator: MavenProgressIndicator): MavenReadContext {
val projectManager = MavenProjectsManager.getInstance(context.project)
ApplicationManager.getApplication().assertIsNonDispatchThread()
val ignorePaths: List<String> = context.ignorePaths
val ignorePatterns: List<String> = context.ignorePatterns
val projectsTree = loadOrCreateProjectTree(projectManager)
MavenProjectsManager.applyStateToTree(projectsTree, projectManager)
val rootFiles = MavenProjectsManager.getInstance(context.project).projectsTree.rootProjectsFiles
val pomFiles = LinkedHashSet<VirtualFile>()
rootFiles?.let { pomFiles.addAll(it.filterNotNull()) }
val newPomFiles = when (context.paths) {
is FilesList -> context.paths.poms
is RootPath -> searchForMavenFiles(context.paths.path, context.indicator)
}
pomFiles.addAll(newPomFiles)
projectsTree.addManagedFilesWithProfiles(pomFiles.filter { it.exists() }.toList(), context.profiles)
val toResolve = LinkedHashSet<MavenProject>()
val errorsSet = LinkedHashSet<MavenProject>()
val d = Disposer.newDisposable("MavenImportFlow:readMavenFiles:treeListener")
Disposer.register(context.importDisposable, d)
projectsTree.addListener(projectManager.treeListenerEventDispatcher.multicaster, context.importDisposable)
projectsTree.addListener(object : MavenProjectsTree.Listener {
override fun projectsUpdated(updated: MutableList<Pair<MavenProject, MavenProjectChanges>>, deleted: MutableList<MavenProject>) {
val allUpdated = MavenUtil.collectFirsts(
updated) // import only updated projects and dependents of them (we need to update faced-deps, packaging etc);
toResolve.addAll(allUpdated)
for (eachDependent in projectsTree.getDependentProjects(allUpdated)) {
toResolve.add(eachDependent)
}
// resolve updated, theirs dependents, and dependents of deleted
toResolve.addAll(projectsTree.getDependentProjects(ContainerUtil.concat(allUpdated, deleted)))
errorsSet.addAll(toResolve.filter { it.hasReadingProblems() })
toResolve.removeIf { it.hasReadingProblems() }
runLegacyListeners(context) { projectsScheduled() }
}
}, d)
if (ignorePaths.isNotEmpty()) {
projectsTree.ignoredFilesPaths = ignorePaths
}
if (ignorePatterns.isNotEmpty()) {
projectsTree.ignoredFilesPatterns = ignorePatterns
}
projectsTree.updateAll(true, context.generalSettings, indicator)
Disposer.dispose(d)
val workingDir = getWorkingBaseDir(context)
val wrapperData = MavenWrapperSupport.getWrapperDistributionUrl(workingDir)?.let { WrapperData(it, workingDir!!) }
readDoubleUpdateToWorkaroundIssueWhenProjectToBeReadTwice(context, projectsTree, indicator)
return MavenReadContext(context.project, projectsTree, toResolve, errorsSet, context, wrapperData, indicator)
}
//TODO: Remove this. See StructureImportingTest.testProjectWithMavenConfigCustomUserSettingsXml
private fun readDoubleUpdateToWorkaroundIssueWhenProjectToBeReadTwice(context: MavenInitialImportContext,
projectsTree: MavenProjectsTree,
indicator: MavenProgressIndicator) {
context.generalSettings.updateFromMavenConfig(projectsTree.rootProjectsFiles)
projectsTree.updateAll(true, context.generalSettings, indicator)
}
fun setupMavenWrapper(readContext: MavenReadContext): MavenReadContext {
if (readContext.wrapperData == null) return readContext
if (!MavenUtil.isWrapper(readContext.initialContext.generalSettings)) return readContext
MavenWrapperDownloader.checkOrInstallForSync(readContext.project, readContext.wrapperData.baseDir.path)
return readContext
}
private fun getWorkingBaseDir(context: MavenInitialImportContext): VirtualFile? {
val guessedDir = context.project.guessProjectDir()
if (guessedDir != null) return guessedDir
when (context.paths) {
is FilesList -> return context.paths.poms[0].parent
is RootPath -> return context.paths.path
}
}
private fun searchForMavenFiles(path: VirtualFile, indicator: MavenProgressIndicator): MutableList<VirtualFile> {
indicator.setText(MavenProjectBundle.message("maven.locating.files"))
return FileFinder.findPomFiles(path.children, LookForNestedToggleAction.isSelected(), indicator)
}
private fun loadOrCreateProjectTree(projectManager: MavenProjectsManager): MavenProjectsTree {
return projectManager.projectsTree.copyForReimport
}
fun resolveDependencies(context: MavenReadContext): MavenResolvedContext {
runLegacyListeners(context) { importAndResolveScheduled() }
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
val resolveContext = ResolveContext()
val d = Disposer.newDisposable("MavenImportFlow:resolveDependencies:treeListener")
Disposer.register(context.initialContext.importDisposable, d)
val projectsToImport = ArrayList(context.toResolve)
val nativeProjectStorage = ArrayList<kotlin.Pair<MavenProject, NativeMavenProjectHolder>>()
context.projectsTree.addListener(object : MavenProjectsTree.Listener {
override fun projectResolved(projectWithChanges: Pair<MavenProject, MavenProjectChanges>,
nativeMavenProject: NativeMavenProjectHolder?) {
if (nativeMavenProject != null) {
if (shouldScheduleProject(projectWithChanges.first, projectWithChanges.second)) {
projectsToImport.add(projectWithChanges.first)
}
nativeProjectStorage.add(projectWithChanges.first to nativeMavenProject)
}
}
}, d)
resolver.resolve(context.project, context.toResolve, context.initialContext.generalSettings, embeddersManager, consoleToBeRemoved,
resolveContext, context.initialContext.indicator)
Disposer.dispose(d)
return MavenResolvedContext(context.project, resolveContext.getUserData(MavenProjectResolver.UNRESOLVED_ARTIFACTS) ?: emptySet(),
projectsToImport, nativeProjectStorage, context)
}
fun resolvePlugins(context: MavenResolvedContext): MavenPluginResolvedContext {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.readContext.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
val unresolvedPlugins = Collections.synchronizedSet(LinkedHashSet<MavenPlugin>())
context.nativeProjectHolder.foreachParallel {
unresolvedPlugins.addAll(
resolver.resolvePlugins(it.first, it.second, embeddersManager, consoleToBeRemoved, context.initialContext.indicator, false,
projectManager.forceUpdateSnapshots))
}
return MavenPluginResolvedContext(context.project, unresolvedPlugins, context)
}
fun downloadArtifacts(context: MavenResolvedContext, sources: Boolean, javadocs: Boolean): MavenArtifactDownloader.DownloadResult {
assertNonDispatchThread()
if (!(sources || javadocs)) return MavenArtifactDownloader.DownloadResult()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.readContext.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
return resolver.downloadSourcesAndJavadocs(context.project, context.projectsToImport, null, sources, javadocs, embeddersManager,
consoleToBeRemoved, context.initialContext.indicator)
}
fun downloadSpecificArtifacts(project: Project,
mavenProjects: Collection<MavenProject>,
mavenArtifacts: Collection<MavenArtifact>?,
sources: Boolean,
javadocs: Boolean,
indicator: MavenProgressIndicator): MavenArtifactDownloader.DownloadResult {
assertNonDispatchThread()
if (!(sources || javadocs)) return MavenArtifactDownloader.DownloadResult()
val projectManager = MavenProjectsManager.getInstance(project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(projectManager.projectsTree)
val settings = MavenWorkspaceSettingsComponent.getInstance(project).settings.getGeneralSettings()
val consoleToBeRemoved = BTWMavenConsole(project, settings.outputLevel, settings.isPrintErrorStackTraces)
return resolver.downloadSourcesAndJavadocs(project, mavenProjects, mavenArtifacts, sources, javadocs, embeddersManager,
consoleToBeRemoved, indicator)
}
fun resolveFolders(projects: Collection<MavenProject>, project: Project, indicator: MavenProgressIndicator): Collection<MavenProject> {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(project)
val embeddersManager = projectManager.embeddersManager
val projectTree = loadOrCreateProjectTree(projectManager)
val resolver = MavenProjectResolver(loadOrCreateProjectTree(projectManager))
val generalSettings = MavenWorkspaceSettingsComponent.getInstance(project).settings.getGeneralSettings()
val importingSettings = MavenWorkspaceSettingsComponent.getInstance(project).settings.getImportingSettings()
val consoleToBeRemoved = BTWMavenConsole(project, generalSettings.outputLevel,
generalSettings.isPrintErrorStackTraces)
val d = Disposer.newDisposable("MavenImportFlow:resolveFolders:treeListener")
val projectsFoldersResolved = Collections.synchronizedList(ArrayList<MavenProject>())
Disposer.register(MavenDisposable.getInstance(project), d)
projectTree.addListener(object : MavenProjectsTree.Listener {
override fun foldersResolved(projectWithChanges: Pair<MavenProject, MavenProjectChanges>) {
if (projectWithChanges.second.hasChanges()) {
projectsFoldersResolved.add(projectWithChanges.first)
}
}
}, d)
projects.foreachParallel {
resolver.resolveFolders(it, importingSettings, embeddersManager, consoleToBeRemoved, indicator)
}
Disposer.dispose(d)
return projectsFoldersResolved
}
fun commitToWorkspaceModel(context: MavenResolvedContext, importingActivity: StructuredIdeActivity): MavenImportedContext {
val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(context.project)
assertNonDispatchThread()
val projectImporter = MavenProjectImporter.createImporter(context.project, context.readContext.projectsTree,
context.projectsToImport.map {
it to MavenProjectChanges.ALL
}.toMap(), false, modelsProvider, context.initialContext.importingSettings,
context.initialContext.dummyModule, importingActivity)
val postImportTasks = projectImporter.importProject()
val modulesCreated = projectImporter.createdModules()
return MavenImportedContext(context.project, modulesCreated, postImportTasks, context.readContext, context)
}
fun updateProjectManager(context: MavenReadContext) {
val projectManager = MavenProjectsManager.getInstance(context.project)
projectManager.projectsTree = context.projectsTree
runLegacyListeners(context) { projectImportCompleted() }
}
fun runPostImportTasks(context: MavenImportedContext) {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val consoleToBeRemoved = BTWMavenConsole(context.project, context.readContext.initialContext.generalSettings.outputLevel,
context.readContext.initialContext.generalSettings.isPrintErrorStackTraces)
context.postImportTasks?.forEach {
it.perform(context.project, embeddersManager, consoleToBeRemoved, context.readContext.indicator)
}
}
private fun shouldScheduleProject(project: MavenProject, changes: MavenProjectChanges): Boolean {
return !project.hasReadingProblems() && changes.hasChanges()
}
private fun <A> Collection<A>.foreachParallel(f: suspend (A) -> Unit) {
runBlocking {
forEach { launch { f(it) } }
}
}
}
internal fun assertNonDispatchThread() {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode && app.isDispatchThread) {
throw RuntimeException("Access from event dispatch thread is not allowed")
}
ApplicationManager.getApplication().assertIsNonDispatchThread()
}
internal fun runLegacyListeners(context: MavenImportContext, method: MavenProjectsManager.Listener.() -> Unit) {
try {
method(context.project.messageBus.syncPublisher(MavenImportingManager.LEGACY_PROJECT_MANAGER_LISTENER))
}
catch (ignore: Exception) {
}
}
| apache-2.0 | 0f549d65ab7e1c446d3d8af4f86b01ce | 51.705882 | 137 | 0.7524 | 5.229063 | false | false | false | false |
SkyTreasure/Kotlin-Firebase-Group-Chat | app/src/main/java/io/skytreasure/kotlingroupchat/chat/model/ChatModels.kt | 1 | 1962 | package io.skytreasure.kotlingroupchat.chat.model
import java.util.*
/**
* Created by akash on 23/10/17.
*/
data class UserModel(var uid: String? = null,
var name: String? = null,
var image_url: String? = null,
var email: String? = null,
var group: HashMap<String, Boolean> = hashMapOf(),
var deviceIds: HashMap<String, String> = hashMapOf(),
var online: Boolean? = null,
var unread_group_count: Int? = null,
var last_seen_online: String? = null,
var last_seen_message_timestamp: String? = null,
var admin: Boolean? = null,
var delete_till: String? = null,
var active: Boolean? = null)
data class GroupModel(var name: String? = null,
var image_url: String? = null,
var groupId: String? = null,
var group_deleted: Boolean? = null,
var group: Boolean? = null,
var lastMessage: MessageModel? = MessageModel(),
var members: HashMap<String, UserModel> = hashMapOf())
data class FileModel(var type: String? = "",
var url_file: String? = "",
var name_file: String? = "",
var size_file: String? = "")
data class LocationModel(var latitude: String? = "",
var longitude: String? = "")
data class MessageModel(var message: String? = "",
var sender_id: String? = "",
var timestamp: String? = "",
var message_id: String? = "",
var read_status: HashMap<String, Boolean> = hashMapOf(),
var file: FileModel? = null,
var location: LocationModel? = null) | mit | 7331bf3bc688999bf8ae4fda3182bc81 | 41.673913 | 80 | 0.478084 | 4.892768 | false | false | false | false |
benjamin-bader/thrifty | thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/FieldNamingPolicy.kt | 1 | 5075 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.schema
import com.google.common.base.CaseFormat
import java.util.regex.Pattern
/**
* Controls the style of names generated for fields.
*/
abstract class FieldNamingPolicy {
/**
* Apply this policy to the given [name].
*/
abstract fun apply(name: String): String
companion object {
private val LOWER_CAMEL_REGEX = Pattern.compile("([a-z]+[A-Z]+\\w+)+")
private val UPPER_CAMEL_REGEX = Pattern.compile("([A-Z]+[a-z]+\\w+)+")
/**
* The default policy is to leave names unaltered from their definition in Thrift IDL.
*/
val DEFAULT: FieldNamingPolicy = object : FieldNamingPolicy() {
override fun apply(name: String): String {
return name
}
}
/**
* The Java policy generates camelCase names, unless the initial part of the field name
* appears to be an acronym, in which case the casing is preserved.
*
* "Acronym" here is defined to be two or more consecutive upper-case characters
* at the beginning of the name. Thus, this policy will preserve `.SSLFlag` over
* `.sSLFlag`.
*/
val JAVA: FieldNamingPolicy = object : FieldNamingPolicy() {
override fun apply(name: String): String {
val caseFormat = caseFormatOf(name)
if (caseFormat != null) {
val formattedName = caseFormat.to(CaseFormat.LOWER_CAMEL, name)
// Handle acronym as camel case made it lower case.
return if (name.length > 1
&& formattedName.length > 1
&& Character.isUpperCase(name[0])
&& Character.isUpperCase(name[1])
&& caseFormat !== CaseFormat.UPPER_UNDERSCORE) {
name[0] + formattedName.substring(1)
} else {
formattedName
}
}
// Unknown case format. Handle the acronym.
if (Character.isUpperCase(name[0])) {
if (name.length == 1 || !Character.isUpperCase(name[1])) {
return Character.toLowerCase(name[0]) + name.substring(1)
}
}
return name
}
}
/**
* The Pascal-case policy generates PascalCase names.
*/
val PASCAL: FieldNamingPolicy = object : FieldNamingPolicy() {
override fun apply(name: String): String {
val caseFormat = caseFormatOf(name)
if (caseFormat != null) {
return caseFormat.to(CaseFormat.UPPER_CAMEL, name)
}
// Unknown format. We'll bulldoze the name by uppercasing the
// first char, then just removing any subsequent non-identifier chars.
return buildString {
append(Character.toUpperCase(name[0]))
name.substring(1)
.filter { it.isJavaIdentifierPart() }
.forEach { append(it) }
}
}
}
/**
* Find case format from string.
* @param s the input String
* @return CaseFormat the case format of the string.
*/
private fun caseFormatOf(s: String): CaseFormat? {
if (s.contains("_")) {
if (s.uppercase() == s) {
return CaseFormat.UPPER_UNDERSCORE
}
if (s.lowercase() == s) {
return CaseFormat.LOWER_UNDERSCORE
}
} else if (s.contains("-")) {
if (s.lowercase() == s) {
return CaseFormat.LOWER_HYPHEN
}
} else {
if (Character.isLowerCase(s[0])) {
if (LOWER_CAMEL_REGEX.matcher(s).matches()) {
return null
}
} else {
if (UPPER_CAMEL_REGEX.matcher(s).matches()) {
return CaseFormat.UPPER_CAMEL
}
}
}
return null
}
}
}
| apache-2.0 | 734f287b8ba77315655880a1c9c1eade | 35.775362 | 116 | 0.521182 | 4.898649 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-kotlin/mobile-ui/src/main/java/org/buffer/android/boilerplate/ui/injection/ApplicationComponent.kt | 2 | 818 | package <%= appPackage %>.ui.injection
import android.app.Application
import dagger.BindsInstance
import dagger.Component
import dagger.android.support.AndroidSupportInjectionModule
import <%= appPackage %>.ui.BufferooApplication
import <%= appPackage %>.ui.injection.module.ActivityBindingModule
import <%= appPackage %>.ui.injection.module.ApplicationModule
import <%= appPackage %>.ui.injection.scopes.PerApplication
@PerApplication
@Component(modules = arrayOf(ActivityBindingModule::class, ApplicationModule::class,
AndroidSupportInjectionModule::class))
interface ApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance fun application(application: Application): Builder
fun build(): ApplicationComponent
}
fun inject(app: BufferooApplication)
}
| mit | c3f9f49ed98e9b4f810347442d88ae04 | 31.72 | 84 | 0.781174 | 5.417219 | false | false | false | false |
caarmen/FRCAndroidWidget | app/src/main/kotlin/ca/rmen/android/frccommon/compat/Api26Helper.kt | 1 | 2818 | /*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2017 Carmen Alvarez
*
* 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 ca.rmen.android.frccommon.compat
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Icon
import android.support.annotation.ColorInt
import ca.rmen.android.frccommon.Action
import ca.rmen.android.frenchcalendar.R
object Api26Helper {
private const val NOTIFICATION_CHANNEL_ID = "FRC_NOTIFICATION_CHANNEL"
fun createNotification(context: Context,
iconId: Int,
@ColorInt color: Int,
tickerText: String,
contentText: String,
bigText: String,
defaultIntent: PendingIntent,
actions: Array<Action>): Notification {
val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
val builder = Notification.Builder(context, notificationChannel.id)
.setAutoCancel(true)
.setColor(color)
.setContentTitle(tickerText)
.setContentText(contentText)
.setStyle(Notification.BigTextStyle().bigText(bigText))
.setSmallIcon(iconId)
.setContentIntent(defaultIntent)
actions.forEach { action ->
val icon = Icon.createWithResource(context, action.iconId)
builder.addAction(Notification.Action.Builder(icon, action.title, action.pendingIntent).build())
}
val extender = Notification.WearableExtender()
.setBackground(Bitmap.createBitmap(intArrayOf(color), 1, 1, Bitmap.Config.ARGB_8888))
builder.extend(extender)
return builder.build()
}
}
| gpl-3.0 | 4555eef148c2e1afcad1c1ee1ad6ac21 | 43.730159 | 156 | 0.685947 | 5.041145 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/model/Entities.kt | 1 | 1782 | package csumissu.weatherforecast.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
import java.text.DecimalFormat
/**
* @author yxsun
* @since 02/06/2017
*/
data class Coordinate(private val _latitude: Double? = 34.275,
private val _longitude: Double? = 108.953) {
private val format = DecimalFormat("#.###")
val latitude: Double
get() = format.format(_latitude).toDouble()
val longitude: Double
get() = format.format(_longitude).toDouble()
}
data class Temperature(val day: Float,
val min: Float,
val max: Float) : Serializable
data class Weather(val description: String,
@SerializedName("icon") val iconCode: String) : Serializable {
val iconUrl: String
get() = "http://openweathermap.org/img/w/$iconCode.png"
}
data class Forecast(val dt: Long,
@SerializedName("temp") val temperature: Temperature,
@SerializedName("weather") val weathers: List<Weather>,
val humidity: Int,
val pressure: Float,
val windSpeed: Float,
@SerializedName("deg") val windDegrees: Int,
val clouds: Int) : Serializable {
val date: Long
get() = dt * 1000
}
data class City(val id: Long,
val name: String,
val country: String)
data class ForecastList(val city: City,
@SerializedName("list") val dailyForecast: List<Forecast>) {
val size: Int
get() = dailyForecast.size
operator fun get(position: Int) =
if (position < 0 || position > dailyForecast.size - 1) null else dailyForecast[position]
} | mit | a7cb55620d5a2b020ca7b406e508f8a6 | 29.741379 | 100 | 0.589226 | 4.477387 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/scripting/LastModifiedFiles.kt | 4 | 4482 | // 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.gradle.scripting
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.FileAttribute
import org.jetbrains.kotlin.idea.core.script.scriptingErrorLog
import org.jetbrains.kotlin.idea.core.util.readNullable
import org.jetbrains.kotlin.idea.core.util.readStringList
import org.jetbrains.kotlin.idea.core.util.writeNullable
import org.jetbrains.kotlin.idea.core.util.writeStringList
import java.io.DataInputStream
import java.io.DataOutput
import java.io.DataOutputStream
/**
* Optimized collection for storing last modified files with ability to
* get time of last modified file expect given one ([lastModifiedTimeStampExcept]).
*
* This is required since Gradle scripts configurations should be updated on
* each other script changes (but not on the given script changes itself).
*
* Actually works by storing two last timestamps with the set of files modified at this times.
*/
class LastModifiedFiles(
private var last: SimultaneouslyChangedFiles = SimultaneouslyChangedFiles(),
private var previous: SimultaneouslyChangedFiles = SimultaneouslyChangedFiles()
) {
init {
previous.fileIds.removeAll(last.fileIds)
if (previous.fileIds.isEmpty()) previous = SimultaneouslyChangedFiles()
}
class SimultaneouslyChangedFiles(
val ts: Long = Long.MIN_VALUE,
val fileIds: MutableSet<String> = mutableSetOf()
) {
override fun toString(): String {
return "SimultaneouslyChangedFiles(ts=$ts, fileIds=$fileIds)"
}
}
@Synchronized
fun fileChanged(ts: Long, fileId: String) {
when {
ts > last.ts -> {
val prevPrev = previous
previous = last
previous.fileIds.remove(fileId)
if (previous.fileIds.isEmpty()) previous = prevPrev
last = SimultaneouslyChangedFiles(ts, hashSetOf(fileId))
}
ts == last.ts -> last.fileIds.add(fileId)
ts == previous.ts -> previous.fileIds.add(fileId)
}
}
@Synchronized
fun lastModifiedTimeStampExcept(fileId: String): Long = when {
last.fileIds.size == 1 && last.fileIds.contains(fileId) -> previous.ts
else -> last.ts
}
override fun toString(): String {
return "LastModifiedFiles(last=$last, previous=$previous)"
}
companion object {
private val fileAttribute = FileAttribute("last-modified-files", 1, false)
fun read(buildRoot: VirtualFile): LastModifiedFiles? {
try {
return fileAttribute.readFileAttribute(buildRoot)?.use {
readLastModifiedFiles(it)
}
} catch (e: Exception) {
scriptingErrorLog("Cannot read data for buildRoot=$buildRoot from file attributes", e)
return null
}
}
@IntellijInternalApi
fun readLastModifiedFiles(it: DataInputStream) = it.readNullable {
LastModifiedFiles(readSCF(it), readSCF(it))
}
fun write(buildRoot: VirtualFile, data: LastModifiedFiles?) {
try {
fileAttribute.writeFileAttribute(buildRoot).use {
writeLastModifiedFiles(it, data)
}
} catch (e: Exception) {
scriptingErrorLog("Cannot store data=$data for buildRoot=$buildRoot to file attributes", e)
fileAttribute.writeFileAttribute(buildRoot).use {
writeLastModifiedFiles(it, null)
}
}
}
@IntellijInternalApi
fun writeLastModifiedFiles(it: DataOutputStream, data: LastModifiedFiles?) {
it.writeNullable(data) { data ->
writeSCF(data.last)
writeSCF(data.previous)
}
}
fun remove(buildRoot: VirtualFile) {
write(buildRoot, null)
}
private fun readSCF(it: DataInputStream) = SimultaneouslyChangedFiles(it.readLong(), it.readStringList().toMutableSet())
private fun DataOutput.writeSCF(last: SimultaneouslyChangedFiles) {
writeLong(last.ts)
writeStringList(last.fileIds.toList())
}
}
} | apache-2.0 | 3cda7de9fdfc23d18a7d26f69815adce | 36.049587 | 158 | 0.647033 | 4.688285 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/FeatureReader.kt | 3 | 4883 | /*
* Copyright 2000-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.completion.feature.impl
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
typealias DoubleFeatureInfo = Map<String, Double>
typealias CategoricalFeatureInfo = Map<String, Set<String>>
typealias BinaryFeatureInfo = Map<String, Map<String, Double>>
typealias IgnoredFeatureInfo = Set<String>
object FeatureUtils {
const val UNDEFINED: String = "UNDEFINED"
const val INVALID_CACHE: String = "INVALID_CACHE"
const val OTHER: String = "OTHER"
const val NONE: String = "NONE"
const val ML_RANK: String = "ml_rank"
const val BEFORE_ORDER: String = "before_rerank_order"
const val DEFAULT: String = "default"
fun getOtherCategoryFeatureName(name: String): String = "$name=$OTHER"
fun getUndefinedFeatureName(name: String): String = "$name=$UNDEFINED"
fun prepareRevelanceMap(relevance: List<Pair<String, Any?>>, position: Int, prefixLength: Int, elementLength: Int)
: Map<String, Any> {
val relevanceMap = mutableMapOf<String, Any>()
for ((name, value) in relevance) {
if(value == null) continue
if (name == "proximity") {
val proximityMap = value.toString().toProximityMap()
relevanceMap.putAll(proximityMap)
} else {
relevanceMap[name] = value
}
}
relevanceMap["position"] = position
relevanceMap["query_length"] = prefixLength
relevanceMap["result_length"] = elementLength
return relevanceMap
}
/**
* Proximity features now came like [samePsiFile=true, openedInEditor=false], need to convert to proper map
*/
private fun String.toProximityMap(): Map<String, Any> {
val items = replace("[", "").replace("]", "").split(",")
return items.map {
val (key, value) = it.trim().split("=")
"prox_$key" to value
}.toMap()
}
}
object FeatureReader {
private val gson = Gson()
fun completionFactors(): CompletionFactors {
val text = fileContent("features/all_features.json")
val typeToken = object : TypeToken<Map<String, Set<String>>>() {}
val map = gson.fromJson<Map<String, Set<String>>>(text, typeToken.type)
val relevance: Set<String> = map["javaRelevance"] ?: emptySet()
val proximity: Set<String> = map["javaProximity"] ?: emptySet()
return CompletionFactors(proximity, relevance)
}
fun binaryFactors(): BinaryFeatureInfo {
val text = fileContent("features/binary.json")
val typeToken = object : TypeToken<BinaryFeatureInfo>() {}
return gson.fromJson<BinaryFeatureInfo>(text, typeToken.type)
}
fun categoricalFactors(): CategoricalFeatureInfo {
val text = fileContent("features/categorical.json")
val typeToken = object : TypeToken<CategoricalFeatureInfo>() {}
return gson.fromJson<CategoricalFeatureInfo>(text, typeToken.type)
}
fun ignoredFactors(): IgnoredFeatureInfo {
val text = fileContent("features/ignored.json")
val typeToken = object : TypeToken<IgnoredFeatureInfo>() {}
return gson.fromJson<IgnoredFeatureInfo>(text, typeToken.type)
}
fun doubleFactors(): DoubleFeatureInfo {
val text = fileContent("features/float.json")
val typeToken = object : TypeToken<DoubleFeatureInfo>() {}
return gson.fromJson<DoubleFeatureInfo>(text, typeToken.type)
}
fun featuresOrder(): Map<String, Int> {
val text = fileContent("features/final_features_order.txt")
var index = 0
val map = mutableMapOf<String, Int>()
text.split("\n").forEach {
val featureName = it.trim()
map[featureName] = index++
}
return map
}
private fun fileContent(fileName: String): String {
val fileStream = FeatureReader.javaClass.classLoader.getResourceAsStream(fileName)
return fileStream.reader().readText()
}
fun jsonMap(fileName: String): List<MutableMap<String, Any>> {
val text = fileContent(fileName)
val typeToken = object : TypeToken<List<Map<String, Any>>>() {}
return gson.fromJson<List<MutableMap<String, Any>>>(text, typeToken.type)
}
} | apache-2.0 | fa20fb350ef441059fb9d6aae95b04e4 | 33.394366 | 118 | 0.656564 | 4.455292 | false | false | false | false |
jk1/intellij-community | platform/credential-store/src/credentialStore.kt | 3 | 3078 | // 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.credentialStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EncryptionSupport
import com.intellij.util.generateAesKey
import com.intellij.util.io.toByteArray
import java.nio.CharBuffer
import java.security.MessageDigest
import java.util.*
import javax.crypto.spec.SecretKeySpec
internal val LOG = Logger.getInstance(CredentialStore::class.java)
private fun toOldKey(hash: ByteArray) = "old-hashed-key|" + Base64.getEncoder().encodeToString(hash)
internal fun toOldKeyAsIdentity(hash: ByteArray) = CredentialAttributes(SERVICE_NAME_PREFIX, toOldKey(hash))
fun toOldKey(requestor: Class<*>, userName: String): CredentialAttributes {
return CredentialAttributes(SERVICE_NAME_PREFIX, toOldKey(MessageDigest.getInstance("SHA-256").digest("${requestor.name}/$userName".toByteArray())))
}
fun joinData(user: String?, password: OneTimeString?): ByteArray? {
if (user == null && password == null) {
return null
}
val builder = StringBuilder(user.orEmpty())
StringUtil.escapeChar(builder, '\\')
StringUtil.escapeChar(builder, '@')
if (password != null) {
builder.append('@')
password.appendTo(builder)
}
val buffer = Charsets.UTF_8.encode(CharBuffer.wrap(builder))
// clear password
builder.setLength(0)
return buffer.toByteArray()
}
fun splitData(data: String?): Credentials? {
if (data.isNullOrEmpty()) {
return null
}
val list = parseString(data!!, '@')
return Credentials(list.getOrNull(0), list.getOrNull(1))
}
private const val ESCAPING_CHAR = '\\'
private fun parseString(data: String, delimiter: Char): List<String> {
val part = StringBuilder()
val result = ArrayList<String>(2)
var i = 0
var c: Char?
do {
c = data.getOrNull(i++)
if (c != null && c != delimiter) {
if (c == ESCAPING_CHAR) {
c = data.getOrNull(i++)
}
if (c != null) {
part.append(c)
continue
}
}
result.add(part.toString())
part.setLength(0)
if (i < data.length) {
result.add(data.substring(i))
break
}
}
while (c != null)
return result
}
// check isEmpty before
@JvmOverloads
fun Credentials.serialize(storePassword: Boolean = true): ByteArray = joinData(userName, if (storePassword) password else null)!!
@Suppress("FunctionName")
internal fun SecureString(value: CharSequence): SecureString = SecureString(Charsets.UTF_8.encode(CharBuffer.wrap(value)).toByteArray())
internal class SecureString(value: ByteArray) {
companion object {
private val encryptionSupport = EncryptionSupport(SecretKeySpec(generateAesKey(), "AES"))
}
private val data = encryptionSupport.encrypt(value)
fun get(clearable: Boolean = true): OneTimeString = OneTimeString(encryptionSupport.decrypt(data), clearable = clearable)
}
internal val ACCESS_TO_KEY_CHAIN_DENIED = Credentials(null, null as OneTimeString?)
| apache-2.0 | 31ff46fe355256c092557cd0b7ff7b26 | 29.176471 | 150 | 0.718648 | 3.906091 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/plugins/server/TypeScriptClientServerBuilder.kt | 1 | 1682 | package org.roylance.yaclib.core.plugins.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.FileProcessUtilities
import org.roylance.yaclib.core.utilities.InitUtilities
import org.roylance.yaclib.core.utilities.TypeScriptUtilities
import java.nio.file.Paths
class TypeScriptClientServerBuilder(private val location: String,
private val apiProjectName: String) : IBuilder<Boolean> {
override fun build(): Boolean {
val javascriptDirectory = Paths.get(location,
"$apiProjectName${CommonTokens.ServerSuffix}",
"src", "main", "javascript").toFile()
println(InitUtilities.buildPhaseMessage("typescript server begin"))
val projectModel = TypeScriptUtilities.buildNpmModel(
javascriptDirectory.toString()) ?: return false
val shouldInstallAnon = projectModel.dependencies.values.any {
it.startsWith("https:") && it.endsWith(".tar.gz")
}
println(InitUtilities.buildPhaseMessage("restoring: (installing anon: $shouldInstallAnon)"))
val restoreDependenciesReport = TypeScriptUtilities.restoreDependencies(
javascriptDirectory.toString(), shouldInstallAnon)
println(restoreDependenciesReport.normalOutput)
println(restoreDependenciesReport.errorOutput)
println(InitUtilities.buildPhaseMessage("gulping"))
val gulpReport = FileProcessUtilities.executeProcess(javascriptDirectory.toString(), "gulp", "")
println(gulpReport.normalOutput)
println(gulpReport.errorOutput)
println(InitUtilities.buildPhaseMessage("typescript server end"))
return true
}
} | mit | 3d110d1455fbfeba1d57520d8829182b | 41.075 | 100 | 0.779429 | 4.672222 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoParentWithoutPidEntityImpl.kt | 3 | 8378 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OoParentWithoutPidEntityImpl: OoParentWithoutPidEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDONE_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithoutPidEntity::class.java, OoChildWithPidEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CHILDONE_CONNECTION_ID,
)
}
@JvmField var _parentProperty: String? = null
override val parentProperty: String
get() = _parentProperty!!
override val childOne: OoChildWithPidEntity?
get() = snapshot.extractOneToOneChild(CHILDONE_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: OoParentWithoutPidEntityData?): ModifiableWorkspaceEntityBase<OoParentWithoutPidEntity>(), OoParentWithoutPidEntity.Builder {
constructor(): this(OoParentWithoutPidEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OoParentWithoutPidEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isParentPropertyInitialized()) {
error("Field OoParentWithoutPidEntity#parentProperty should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field OoParentWithoutPidEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentProperty: String
get() = getEntityData().parentProperty
set(value) {
checkModificationAllowed()
getEntityData().parentProperty = value
changedProperty.add("parentProperty")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var childOne: OoChildWithPidEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILDONE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] as? OoChildWithPidEntity
} else {
this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] as? OoChildWithPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILDONE_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] = value
}
changedProperty.add("childOne")
}
override fun getEntityData(): OoParentWithoutPidEntityData = result ?: super.getEntityData() as OoParentWithoutPidEntityData
override fun getEntityClass(): Class<OoParentWithoutPidEntity> = OoParentWithoutPidEntity::class.java
}
}
class OoParentWithoutPidEntityData : WorkspaceEntityData<OoParentWithoutPidEntity>() {
lateinit var parentProperty: String
fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoParentWithoutPidEntity> {
val modifiable = OoParentWithoutPidEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OoParentWithoutPidEntity {
val entity = OoParentWithoutPidEntityImpl()
entity._parentProperty = parentProperty
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OoParentWithoutPidEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoParentWithoutPidEntityData
if (this.parentProperty != other.parentProperty) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoParentWithoutPidEntityData
if (this.parentProperty != other.parentProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentProperty.hashCode()
return result
}
} | apache-2.0 | ec634ad7f3d444428390fc678bdf547d | 40.275862 | 198 | 0.644307 | 5.814018 | false | false | false | false |
paplorinc/intellij-community | plugins/github/test/org/jetbrains/plugins/github/GithubCreatePullRequestTest.kt | 2 | 3542 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.service
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.testFramework.VfsTestUtil
import com.intellij.util.ThreeState
import git4idea.actions.GitInit
import git4idea.test.TestDialogHandler
import git4idea.test.git
import org.jetbrains.plugins.github.api.data.GithubRepo
import org.jetbrains.plugins.github.test.GithubGitRepoTest
import org.jetbrains.plugins.github.ui.GithubCreatePullRequestDialog
import org.jetbrains.plugins.github.util.GithubSettings
class GithubCreatePullRequestTest : GithubGitRepoTest() {
private lateinit var mainRepo: GithubRepo
override fun setUp() {
super.setUp()
mainRepo = createUserRepo(mainAccount, true)
registerDefaultCreatePullRequestDialogHandler()
}
private fun registerDefaultCreatePullRequestDialogHandler() {
dialogManager.registerDialogHandler(GithubCreatePullRequestDialog::class.java, TestDialogHandler { dialog ->
dialog.testSetRequestTitle("TestPR")
dialog.testSetFork(mainRepo.fullPath)
dialog.testSetBranch("master")
dialog.testCreatePullRequest()
DialogWrapper.OK_EXIT_CODE
})
}
fun testBranch() {
cloneRepo(mainRepo)
createBranch()
createChanges()
repository.update()
val coordinatesSet = gitHelper.getPossibleRemoteUrlCoordinates(myProject)
assertSize(1, coordinatesSet)
val coordinates = coordinatesSet.first()
GithubCreatePullRequestAction.createPullRequest(myProject, repository, coordinates.remote, coordinates.url, mainAccount.account)
checkNotification(NotificationType.INFORMATION, "Successfully created pull request", null)
checkRemoteConfigured()
checkLastCommitPushed()
}
private fun createBranch() {
git("branch prBranch")
git("checkout prBranch")
}
fun testFork() {
val fork = forkRepo(secondaryAccount, mainRepo)
cloneRepo(fork)
createChanges()
val coordinatesSet = gitHelper.getPossibleRemoteUrlCoordinates(myProject)
assertSize(1, coordinatesSet)
val coordinates = coordinatesSet.first()
service<GithubSettings>().createPullRequestCreateRemote = ThreeState.YES
GithubCreatePullRequestAction.createPullRequest(myProject, repository, coordinates.remote, coordinates.url, secondaryAccount.account)
checkNotification(NotificationType.INFORMATION, "Successfully created pull request", null)
checkRemoteConfigured()
checkLastCommitPushed()
}
private fun cloneRepo(repo: GithubRepo) {
cd(projectRoot)
git("init")
setGitIdentity(projectRoot)
GitInit.refreshAndConfigureVcsMappings(myProject, projectRoot, projectRoot.path)
findGitRepo()
repository.apply {
git("remote add origin ${repo.cloneUrl}")
// fork is initialized in background and there's nothing to poll
for (i in 1..10) {
try {
git("fetch")
break
}
catch (ise: IllegalStateException) {
if (i == 5) throw ise
Thread.sleep(50L)
}
}
git("checkout -t origin/master")
update()
}
}
private fun createChanges() {
VfsTestUtil.createFile(projectRoot, "file.txt", "file.txt content")
repository.apply {
git("add file.txt")
git("commit -m changes")
}
}
}
| apache-2.0 | 648e8a11785c778d8a605a46bc8f2401 | 31.2 | 140 | 0.741954 | 4.535211 | false | true | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/completion/AtCompletionContributor.kt | 1 | 13618 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at.completion
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.at.AtElementFactory
import com.demonwav.mcdev.platform.mcp.at.AtLanguage
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtEntry
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFieldName
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFunction
import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtTypes
import com.demonwav.mcdev.util.anonymousElements
import com.demonwav.mcdev.util.fullQualifiedName
import com.demonwav.mcdev.util.getSimilarity
import com.demonwav.mcdev.util.nameAndParameterTypes
import com.demonwav.mcdev.util.qualifiedMemberReference
import com.demonwav.mcdev.util.simpleQualifiedMemberReference
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.completion.CompletionUtil
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.patterns.PlatformPatterns.elementType
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.PlatformIcons
class AtCompletionContributor : CompletionContributor() {
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (parameters.completionType != CompletionType.BASIC) {
return
}
val position = parameters.position
if (!PsiUtilCore.findLanguageFromElement(position).isKindOf(AtLanguage)) {
return
}
val parent = position.parent
val parentText = parent.text ?: return
if (parentText.length < CompletionUtil.DUMMY_IDENTIFIER.length) {
return
}
val text = parentText.substring(0, parentText.length - CompletionUtil.DUMMY_IDENTIFIER.length)
when {
AFTER_KEYWORD.accepts(parent) -> handleAtClassName(text, parent, result)
AFTER_CLASS_NAME.accepts(parent) -> handleAtName(text, parent, result)
AFTER_NEWLINE.accepts(parent) -> handleNewLine(text, result)
}
}
private fun handleAtClassName(text: String, element: PsiElement, result: CompletionResultSet) {
if (text.isEmpty()) {
return
}
val currentPackage = text.substringBeforeLast('.', "")
val beginning = text.substringAfterLast('.', "")
if (currentPackage == "" || beginning == "") {
return
}
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)
val project = module.project
// Short name completion
if (!text.contains('.')) {
val kindResult = result.withPrefixMatcher(KindPrefixMatcher(text))
val cache = PsiShortNamesCache.getInstance(project)
var counter = 0
for (className in cache.allClassNames) {
if (!className.contains(beginning, ignoreCase = true)) {
continue
}
if (counter++ > 1000) {
break // Prevent insane CPU usage
}
val classesByName = cache.getClassesByName(className, scope)
for (classByName in classesByName) {
val name = classByName.fullQualifiedName ?: continue
kindResult.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(name).withIcon(PlatformIcons.CLASS_ICON),
1.0 + name.getValue(beginning)
)
)
}
}
}
// Anonymous and inner class completion
if (text.contains('$')) {
val currentClass =
JavaPsiFacade.getInstance(project).findClass(text.substringBeforeLast('$'), scope) ?: return
for (innerClass in currentClass.allInnerClasses) {
if (innerClass.name?.contains(beginning.substringAfterLast('$'), ignoreCase = true) != true) {
continue
}
val name = innerClass.fullQualifiedName ?: continue
result.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(name).withIcon(PlatformIcons.CLASS_ICON),
1.0
)
)
}
for (anonymousElement in currentClass.anonymousElements) {
val anonClass = anonymousElement as? PsiClass ?: continue
val name = anonClass.fullQualifiedName ?: continue
result.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(name).withIcon(PlatformIcons.CLASS_ICON),
1.0
)
)
}
return
}
val psiPackage = JavaPsiFacade.getInstance(project).findPackage(currentPackage) ?: return
// Classes in package completion
val used = mutableSetOf<String>()
for (psiClass in psiPackage.classes) {
if (psiClass.name == null) {
continue
}
if (!psiClass.name!!.contains(beginning, ignoreCase = true) || psiClass.name == "package-info") {
continue
}
if (!used.add(psiClass.name!!)) {
continue
}
val name = psiClass.fullQualifiedName ?: continue
result.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(name).withIcon(PlatformIcons.CLASS_ICON),
1.0
)
)
}
used.clear() // help GC
// Packages in package completion
for (subPackage in psiPackage.subPackages) {
if (subPackage.name == null) {
continue
}
if (!subPackage.name!!.contains(beginning, ignoreCase = true)) {
continue
}
val name = subPackage.qualifiedName
result.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(name).withIcon(PlatformIcons.PACKAGE_ICON),
0.0
)
)
}
}
private fun handleAtName(text: String, memberName: PsiElement, result: CompletionResultSet) {
if (memberName !is AtFieldName) {
return
}
val entry = memberName.parent as? AtEntry ?: return
val entryClass = entry.className.classNameValue ?: return
val module = ModuleUtilCore.findModuleForPsiElement(memberName) ?: return
val project = module.project
val mcpModule = MinecraftFacet.getInstance(module)?.getModuleOfType(McpModuleType) ?: return
val srgMap = mcpModule.srgManager?.srgMapNow ?: return
val srgResult = result.withPrefixMatcher(SrgPrefixMatcher(text))
for (field in entryClass.fields) {
if (!field.name.contains(text, ignoreCase = true)) {
continue
}
val memberReference = srgMap.getSrgField(field) ?: field.simpleQualifiedMemberReference
srgResult.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder
.create(field.name)
.withIcon(PlatformIcons.FIELD_ICON)
.withTailText(" (${memberReference.name})", true)
.withInsertHandler handler@{ context, _ ->
val currentElement = context.file.findElementAt(context.startOffset) ?: return@handler
currentElement.replace(
AtElementFactory.createFieldName(
context.project,
memberReference.name
)
)
// TODO: Fix visibility decrease
PsiDocumentManager.getInstance(context.project)
.doPostponedOperationsAndUnblockDocument(context.document)
val comment = " # ${field.name}"
context.document.insertString(context.editor.caretModel.offset, comment)
context.editor.caretModel.moveCaretRelatively(comment.length, 0, false, false, false)
},
1.0
)
)
}
for (method in entryClass.methods) {
if (!method.name.contains(text, ignoreCase = true)) {
continue
}
val memberReference = srgMap.getSrgMethod(method) ?: method.qualifiedMemberReference
srgResult.addElement(
PrioritizedLookupElement.withPriority(
LookupElementBuilder.create(method.nameAndParameterTypes)
.withIcon(PlatformIcons.METHOD_ICON)
.withTailText(" (${memberReference.name})", true)
.withInsertHandler handler@{ context, _ ->
var currentElement = context.file.findElementAt(context.startOffset) ?: return@handler
var counter = 0
while (currentElement !is AtFieldName && currentElement !is AtFunction) {
currentElement = currentElement.parent
if (counter++ > 3) {
break
}
}
// Hopefully this won't happen lol
if (currentElement !is AtFieldName && currentElement !is AtFunction) {
return@handler
}
if (currentElement is AtFieldName) {
// get rid of the bad parameters
val parent = currentElement.parent
val children =
parent.node.getChildren(TokenSet.create(AtTypes.OPEN_PAREN, AtTypes.CLOSE_PAREN))
if (children.size == 2) {
parent.node.removeRange(children[0], children[1].treeNext)
}
}
currentElement.replace(
AtElementFactory.createFunction(
project,
memberReference.name + memberReference.descriptor
)
)
// TODO: Fix visibility decreases
PsiDocumentManager.getInstance(context.project)
.doPostponedOperationsAndUnblockDocument(context.document)
val comment = " # ${method.name}"
context.document.insertString(context.editor.caretModel.offset, comment)
context.editor.caretModel.moveCaretRelatively(comment.length, 0, false, false, false)
},
0.0
)
)
}
}
private fun handleNewLine(text: String, result: CompletionResultSet) {
for (keyword in AtElementFactory.Keyword.softMatch(text)) {
result.addElement(LookupElementBuilder.create(keyword.text))
}
}
/**
* This helps order the (hopefully) most relevant entries in the short name completion
*/
private fun String?.getValue(text: String): Int {
if (this == null) {
return 0
}
// Push net.minecraft{forge} classes up to the top
val packageBonus = if (this.startsWith("net.minecraft")) 10_000 else 0
val thisName = this.substringAfterLast('.')
return thisName.getSimilarity(text, packageBonus)
}
companion object {
fun after(type: IElementType): PsiElementPattern.Capture<PsiElement> =
psiElement().afterSibling(psiElement().withElementType(elementType().oneOf(type)))
val AFTER_KEYWORD = after(AtTypes.KEYWORD)
val AFTER_CLASS_NAME = after(AtTypes.CLASS_NAME)
val AFTER_NEWLINE = after(AtTypes.CRLF)
}
}
| mit | bbf55b8cfcd6e9633eda9fbcd7c1b6a5 | 39.409496 | 117 | 0.573432 | 5.733895 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/referenceFixes.kt | 1 | 6643 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.SyntheticElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil
import org.jetbrains.plugins.groovy.codeInspection.GroovyQuickFixFactory
import org.jetbrains.plugins.groovy.lang.GrCreateClassKind
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrInterfaceDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.canBeClassOrPackage
fun generateCreateClassActions(ref: GrReferenceElement<*>): Collection<IntentionAction> {
if (ref.parentOfType<GrPackageDefinition>() != null) {
return emptyList()
}
val factory = GroovyQuickFixFactory.getInstance()
val parent = ref.parent
if (parent is GrNewExpression && parent.referenceElement === ref) {
return listOf(factory.createClassFromNewAction(parent))
}
if (ref is GrReferenceExpression && !canBeClassOrPackage(ref)) {
return emptyList()
}
return when {
classExpected(parent) -> listOf(
factory.createClassFixAction(ref, GrCreateClassKind.CLASS),
factory.createClassFixAction(ref, GrCreateClassKind.ENUM)
)
interfaceExpected(parent) -> listOf(
factory.createClassFixAction(ref, GrCreateClassKind.INTERFACE),
factory.createClassFixAction(ref, GrCreateClassKind.TRAIT)
)
annotationExpected(parent) -> listOf(
factory.createClassFixAction(ref, GrCreateClassKind.ANNOTATION)
)
else -> {
val result = mutableListOf(
factory.createClassFixAction(ref, GrCreateClassKind.CLASS),
factory.createClassFixAction(ref, GrCreateClassKind.INTERFACE)
)
if (!ref.isQualified || resolvesToGroovy(ref.qualifier)) {
result += factory.createClassFixAction(ref, GrCreateClassKind.TRAIT)
}
result += factory.createClassFixAction(ref, GrCreateClassKind.ENUM)
result += factory.createClassFixAction(ref, GrCreateClassKind.ANNOTATION)
result
}
}
}
private fun classExpected(parent: PsiElement?): Boolean {
return parent is GrExtendsClause && parent.parent !is GrInterfaceDefinition
}
private fun interfaceExpected(parent: PsiElement?): Boolean {
return parent is GrImplementsClause || parent is GrExtendsClause && parent.parent is GrInterfaceDefinition
}
private fun annotationExpected(parent: PsiElement?): Boolean {
return parent is GrAnnotation
}
private fun resolvesToGroovy(qualifier: PsiElement?): Boolean {
return when (qualifier) {
is GrReferenceElement<*> -> qualifier.resolve() is GroovyPsiElement
is GrExpression -> {
val type = qualifier.type as? PsiClassType
type?.resolve() is GroovyPsiElement
}
else -> false
}
}
fun generateAddImportActions(ref: GrReferenceElement<*>): Collection<IntentionAction> {
return generateAddImportAction(ref)?.let(::listOf) ?: emptyList()
}
private fun generateAddImportAction(ref: GrReferenceElement<*>): IntentionAction? {
if (ref.isQualified) return null
val referenceName = ref.referenceName ?: return null
if (referenceName.isEmpty()) return null
if (ref !is GrCodeReferenceElement && Character.isLowerCase(referenceName[0])) return null
return GroovyQuickFixFactory.getInstance().createGroovyAddImportAction(ref)
}
fun generateReferenceExpressionFixes(ref: GrReferenceExpression): Collection<IntentionAction> {
val targetClass = QuickfixUtil.findTargetClass(ref) ?: return emptyList()
val factory = GroovyQuickFixFactory.getInstance()
val actions = ArrayList<IntentionAction>()
generateAddDynamicMemberAction(ref)?.let(actions::add)
if (targetClass !is SyntheticElement || targetClass is GroovyScriptClass) {
actions += factory.createCreateFieldFromUsageFix(ref)
if (PsiUtil.isAccessedForReading(ref)) {
actions += factory.createCreateGetterFromUsageFix(ref, targetClass)
}
if (PsiUtil.isLValue(ref)) {
actions += factory.createCreateSetterFromUsageFix(ref)
}
if (ref.parent is GrCall && ref.parent is GrExpression) {
actions += factory.createCreateMethodFromUsageFix(ref)
}
}
if (!ref.isQualified) {
val owner = ref.parentOfType<GrVariableDeclarationOwner>()
if (owner !is GroovyFileBase || owner.isScript) {
actions += factory.createCreateLocalVariableFromUsageFix(ref, owner)
}
if (PsiTreeUtil.getParentOfType(ref, GrMethod::class.java) != null) {
actions += factory.createCreateParameterFromUsageFix(ref)
}
}
return actions
}
private fun generateAddDynamicMemberAction(referenceExpression: GrReferenceExpression): IntentionAction? {
if (referenceExpression.containingFile?.virtualFile == null) {
return null
}
if (PsiUtil.isCall(referenceExpression)) {
val argumentTypes = PsiUtil.getArgumentTypes(referenceExpression, false) ?: return null
return GroovyQuickFixFactory.getInstance().createDynamicMethodFix(referenceExpression, argumentTypes)
}
else {
return GroovyQuickFixFactory.getInstance().createDynamicPropertyFix(referenceExpression)
}
}
| apache-2.0 | f8c10976761222a6c738b8e7be5e5004 | 42.136364 | 140 | 0.784284 | 4.503729 | false | false | false | false |
google/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/generate/JavaUastCodeGenerationPlugin.kt | 3 | 22803 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.java.generate
import com.intellij.codeInsight.BlockUtils
import com.intellij.codeInsight.intention.impl.AddOnDemandStaticImportAction
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.impl.PsiDiamondTypeUtil
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.util.*
import com.intellij.util.castSafelyTo
import com.siyeh.ig.psiutils.ParenthesesUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.java.*
internal class JavaUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override fun getElementFactory(project: Project): UastElementFactory = JavaUastElementFactory(project)
override val language: Language
get() = JavaLanguage.INSTANCE
private fun cleanupMethodCall(methodCall: PsiMethodCallExpression): PsiMethodCallExpression {
if (methodCall.typeArguments.isNotEmpty()) {
val resolved = methodCall.resolveMethod() ?: return methodCall
if (methodCall.typeArguments.size == resolved.typeParameters.size &&
PsiDiamondTypeUtil.areTypeArgumentsRedundant(
methodCall.typeArguments,
methodCall,
false,
resolved,
resolved.typeParameters
)
) {
val emptyTypeArgumentsMethodCall = JavaPsiFacade.getElementFactory(methodCall.project)
.createExpressionFromText("foo()", null) as PsiMethodCallExpression
methodCall.typeArgumentList.replace(emptyTypeArgumentsMethodCall.typeArgumentList)
}
}
return JavaCodeStyleManager.getInstance(methodCall.project).shortenClassReferences(methodCall) as PsiMethodCallExpression
}
private fun adjustChainStyleToMethodCalls(oldPsi: PsiElement, newPsi: PsiElement) {
if (oldPsi is PsiMethodCallExpression && newPsi is PsiMethodCallExpression &&
oldPsi.methodExpression.qualifierExpression != null && newPsi.methodExpression.qualifier != null) {
if (oldPsi.methodExpression.children.getOrNull(1) is PsiWhiteSpace &&
newPsi.methodExpression.children.getOrNull(1) !is PsiWhiteSpace
) {
newPsi.methodExpression.addAfter(oldPsi.methodExpression.children[1], newPsi.methodExpression.children[0])
}
}
}
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.sourcePsi ?: return null
val newPsi = newElement.sourcePsi ?: return null
adjustChainStyleToMethodCalls(oldPsi, newPsi)
val factory = JavaPsiFacade.getElementFactory(oldPsi.project)
val updOldPsi = when {
(newPsi is PsiBlockStatement || newPsi is PsiCodeBlock) && oldPsi.parent is PsiExpressionStatement -> oldPsi.parent
else -> oldPsi
}
val updNewPsi = when {
updOldPsi is PsiStatement && newPsi is PsiExpression -> factory.createExpressionStatement(newPsi) ?: return null
updOldPsi is PsiCodeBlock && newPsi is PsiBlockStatement -> newPsi.codeBlock
else -> newPsi
}
return when (val replaced = updOldPsi.replace(updNewPsi)) {
is PsiExpressionStatement -> replaced.expression.toUElementOfExpectedTypes(elementType)
is PsiMethodCallExpression -> cleanupMethodCall(replaced).toUElementOfExpectedTypes(elementType)
is PsiMethodReferenceExpression -> {
JavaCodeStyleManager.getInstance(replaced.project).shortenClassReferences(replaced).toUElementOfExpectedTypes(elementType)
}
else -> replaced.toUElementOfExpectedTypes(elementType)
}
}
override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? {
val sourceReference = reference.sourcePsi ?: return null
if (sourceReference !is PsiReference) return null
return sourceReference.bindToElement(element)
}
override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? {
val sourceReference = reference.sourcePsi ?: return null
val styleManager = JavaCodeStyleManager.getInstance(sourceReference.project)
return styleManager.shortenClassReferences(sourceReference).toUElementOfType()
}
override fun importMemberOnDemand(reference: UQualifiedReferenceExpression): UExpression? {
val source = reference.sourcePsi ?: return null
val (qualifier, selector) = when (source) {
is PsiMethodCallExpression -> source.methodExpression.qualifierExpression to source.methodExpression
is PsiReferenceExpression -> source.qualifier to source.referenceNameElement
else -> return null
}
if (qualifier == null || selector == null) return null
val ptr = SmartPointerManager.createPointer(selector)
val qualifierIdentifier = qualifier.childrenOfType<PsiIdentifier>().firstOrNull() ?: return null
AddOnDemandStaticImportAction.invoke(source.project, source.containingFile, null, qualifierIdentifier)
return ptr.element?.parent.toUElementOfType()
}
}
private fun PsiElementFactory.createExpressionStatement(expression: PsiExpression): PsiStatement? {
val statement = createStatementFromText("x;", null) as? PsiExpressionStatement ?: return null
statement.expression.replace(expression)
return statement
}
class JavaUastElementFactory(private val project: Project) : UastElementFactory {
private val psiFactory: PsiElementFactory = JavaPsiFacade.getElementFactory(project)
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory.createExpressionFromText(qualifiedName, context)
.castSafelyTo<PsiReferenceExpression>()
?.let { JavaUQualifiedReferenceExpression(it, null) }
}
override fun createIfExpression(condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?): UIfExpression? {
val conditionPsi = condition.sourcePsi ?: return null
val thenBranchPsi = thenBranch.sourcePsi ?: return null
val ifStatement = psiFactory.createStatementFromText("if (a) b else c", null) as? PsiIfStatement ?: return null
ifStatement.condition?.replace(conditionPsi)
ifStatement.thenBranch?.replace(thenBranchPsi.branchStatement ?: return null)
elseBranch?.sourcePsi?.branchStatement?.let { ifStatement.elseBranch?.replace(it) } ?: ifStatement.elseBranch?.delete()
return JavaUIfExpression(ifStatement, null)
}
override fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val methodCall = psiFactory.createExpressionFromText(
createCallExpressionTemplateRespectingChainStyle(receiver), context
) as? PsiMethodCallExpression ?: return null
val methodIdentifier = psiFactory.createIdentifier(methodName)
if (receiver != null) {
methodCall.methodExpression.qualifierExpression?.replace(receiver.sourcePsi!!)
}
methodCall.methodExpression.referenceNameElement?.replace(methodIdentifier)
for (parameter in parameters) {
methodCall.argumentList.add(parameter.sourcePsi!!)
}
return if (expectedReturnType == null)
methodCall.toUElementOfType()
else
MethodCallUpgradeHelper(project, methodCall, expectedReturnType).tryUpgradeToExpectedType()
?.let { JavaUCallExpression(it, null) }
}
private fun createCallExpressionTemplateRespectingChainStyle(receiver: UExpression?): String {
if (receiver == null) return "a()"
val siblings = receiver.sourcePsi?.siblings(withSelf = false) ?: return "a.b()"
(siblings.firstOrNull() as? PsiWhiteSpace)?.let { whitespace ->
return "a${whitespace.text}.b()"
}
if (siblings.firstOrNull()?.elementType == ElementType.DOT) {
(siblings.elementAt(2) as? PsiWhiteSpace)?.let { whitespace ->
return "a.${whitespace.text}b()"
}
}
return "a.b()"
}
override fun createCallableReferenceExpression(
receiver: UExpression?,
methodName: String,
context: PsiElement?
): UCallableReferenceExpression? {
val receiverSource = receiver?.sourcePsi
requireNotNull(receiverSource) { "Receiver should not be null for Java callable references." }
val callableExpression = psiFactory.createExpressionFromText("${receiverSource.text}::$methodName", context)
if (callableExpression !is PsiMethodReferenceExpression) return null
return JavaUCallableReferenceExpression(callableExpression, null)
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText(StringUtil.wrapWithDoubleQuote(text), context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? {
return when (val literalExpr = psiFactory.createExpressionFromText(long.toString() + "L", context)) {
is PsiLiteralExpressionImpl -> JavaULiteralExpression(literalExpr, null)
is PsiPrefixExpression -> JavaUPrefixExpression(literalExpr, null)
else -> null
}
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText("null", context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
private class MethodCallUpgradeHelper(val project: Project, val methodCall: PsiMethodCallExpression, val expectedReturnType: PsiType) {
lateinit var resultType: PsiType
fun tryUpgradeToExpectedType(): PsiMethodCallExpression? {
resultType = methodCall.type ?: return null
if (expectedReturnType.isAssignableFrom(resultType)) return methodCall
if (!(resultType eqResolved expectedReturnType))
return null
return methodCall.methodExpression.qualifierExpression?.let { tryPickUpTypeParameters() }
}
private fun tryPickUpTypeParameters(): PsiMethodCallExpression? {
val expectedTypeTypeParameters = expectedReturnType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val resultTypeTypeParameters = resultType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val notEqualTypeParametersIndices = expectedTypeTypeParameters
.zip(resultTypeTypeParameters)
.withIndex()
.filterNot { (_, pair) -> PsiTypesUtil.compareTypes(pair.first, pair.second, false) }
.map { (i, _) -> i }
val resolvedMethod = methodCall.resolveMethod() ?: return null
val methodReturnTypeTypeParameters = (resolvedMethod.returnType.castSafelyTo<PsiClassType>())?.parameters ?: return null
val methodDefinitionTypeParameters = resolvedMethod.typeParameters
val methodDefinitionToReturnTypeParametersMapping = methodDefinitionTypeParameters.map {
it to methodReturnTypeTypeParameters.indexOfFirst { param -> it.name == param.canonicalText }
}
.filter { it.second != -1 }
.toMap()
val notMatchedTypesParametersNames = notEqualTypeParametersIndices
.map { methodReturnTypeTypeParameters[it].canonicalText }
.toSet()
val callTypeParametersSubstitutor = methodCall.resolveMethodGenerics().substitutor
val newParametersList = mutableListOf<PsiType>()
for (parameter in methodDefinitionTypeParameters) {
if (parameter.name in notMatchedTypesParametersNames) {
newParametersList += expectedTypeTypeParameters[methodDefinitionToReturnTypeParametersMapping[parameter] ?: return null]
}
else {
newParametersList += callTypeParametersSubstitutor.substitute(parameter) ?: return null
}
}
return buildMethodCallFromNewTypeParameters(newParametersList)
}
private fun buildMethodCallFromNewTypeParameters(newParametersList: List<PsiType>): PsiMethodCallExpression? {
val factory = JavaPsiFacade.getElementFactory(project)
val expr = factory.createExpressionFromText(buildString {
append("a.<")
newParametersList.joinTo(this) { "T" }
append(">b()")
}, null) as? PsiMethodCallExpression ?: return null
for ((i, param) in newParametersList.withIndex()) {
val typeElement = factory.createTypeElement(param)
expr.typeArgumentList.typeParameterElements[i].replace(typeElement)
}
methodCall.typeArgumentList.replace(expr.typeArgumentList)
if (methodCall.type?.let { expectedReturnType.isAssignableFrom(it) } != true)
return null
return methodCall
}
infix fun PsiType.eqResolved(other: PsiType): Boolean {
val resolvedThis = this.castSafelyTo<PsiClassType>()?.resolve() ?: return false
val resolvedOther = other.castSafelyTo<PsiClassType>()?.resolve() ?: return false
return PsiManager.getInstance(project).areElementsEquivalent(resolvedThis, resolvedOther)
}
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression {
return JavaUDeclarationsExpression(null, declarations)
}
override fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean,
context: PsiElement?): UReturnExpression? {
val returnStatement = psiFactory.createStatementFromText("return ;", null) as? PsiReturnStatement ?: return null
expression?.sourcePsi?.node?.let { (returnStatement as CompositeElement).addChild(it, returnStatement.lastChild.node) }
return JavaUReturnExpression(returnStatement, null)
}
private fun PsiVariable.setMutability(immutable: Boolean) {
if (immutable && !this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, true)
}
if (!immutable && this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, false)
}
}
override fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?): ULocalVariable? {
val initializerPsi = initializer.sourcePsi as? PsiExpression ?: return null
val name = createNameFromSuggested(
suggestedName,
VariableKind.LOCAL_VARIABLE,
type,
initializer = initializerPsi,
context = initializerPsi
) ?: return null
val variable = (type ?: initializer.getExpressionType())?.let { variableType ->
psiFactory.createVariableDeclarationStatement(
name,
variableType,
initializerPsi,
initializerPsi.context
).declaredElements.firstOrNull() as? PsiLocalVariable
} ?: return null
variable.setMutability(immutable)
return JavaULocalVariable(variable, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression? {
val blockStatement = BlockUtils.createBlockStatement(project)
for (expression in expressions) {
if (expression is JavaUDeclarationsExpression) {
for (declaration in expression.declarations) {
if (declaration.sourcePsi is PsiLocalVariable) {
blockStatement.codeBlock.add(declaration.sourcePsi?.parent as? PsiDeclarationStatement ?: return null)
}
}
continue
}
expression.sourcePsi?.let { psi ->
psi as? PsiStatement ?: (psi as? PsiExpression)?.let { psiFactory.createExpressionStatement(it) }
}?.let { blockStatement.codeBlock.add(it) } ?: return null
}
return JavaUBlockExpression(blockStatement, null)
}
override fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression? {
//TODO: smart handling cases, when parameters types should exist in code
val lambda = psiFactory.createExpressionFromText(
buildString {
parameters.joinTo(this, separator = ",", prefix = "(", postfix = ")") { "x x" }
append("->{}")
},
null
) as? PsiLambdaExpression ?: return null
val needsType = parameters.all { it.type != null }
lambda.parameterList.parameters.forEachIndexed { i, parameter ->
parameters[i].also { parameterInfo ->
val name = createNameFromSuggested(
parameterInfo.suggestedName,
VariableKind.PARAMETER,
parameterInfo.type,
context = body.sourcePsi
) ?: return null
parameter.nameIdentifier?.replace(psiFactory.createIdentifier(name))
if (needsType) {
parameter.typeElement?.replace(psiFactory.createTypeElement(parameterInfo.type!!))
}
else {
parameter.removeTypeElement()
}
}
}
if (lambda.parameterList.parametersCount == 1) {
lambda.parameterList.parameters[0].removeTypeElement()
lambda.parameterList.firstChild.delete()
lambda.parameterList.lastChild.delete()
}
val normalizedBody = when (val bodyPsi = body.sourcePsi) {
is PsiExpression -> bodyPsi
is PsiCodeBlock -> normalizeBlockForLambda(bodyPsi)
is PsiBlockStatement -> normalizeBlockForLambda(bodyPsi.codeBlock)
else -> return null
}
lambda.body?.replace(normalizedBody) ?: return null
return JavaULambdaExpression(lambda, null)
}
private fun normalizeBlockForLambda(block: PsiCodeBlock): PsiElement =
block
.takeIf { block.statementCount == 1 }
?.let { block.statements[0] as? PsiReturnStatement }
?.returnValue
?: block
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val parenthesizedExpression = psiFactory.createExpressionFromText("()", null) as? PsiParenthesizedExpression ?: return null
parenthesizedExpression.children.getOrNull(1)?.replace(expression.sourcePsi ?: return null) ?: return null
return JavaUParenthesizedExpression(parenthesizedExpression, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression {
val reference = psiFactory.createExpressionFromText(name, null)
return JavaUSimpleNameReferenceExpression(reference, name, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
override fun createBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val operatorSymbol = when (operator) {
UastBinaryOperator.LOGICAL_AND -> "&&"
UastBinaryOperator.PLUS -> "+"
else -> return null
}
val psiBinaryExpression = psiFactory.createExpressionFromText("a $operatorSymbol b", null) as? PsiBinaryExpression
?: return null
psiBinaryExpression.lOperand.replace(leftPsi)
psiBinaryExpression.rOperand?.replace(rightPsi)
return JavaUBinaryExpression(psiBinaryExpression, null)
}
override fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? {
val binaryExpression = createBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
val binarySourcePsi = binaryExpression.sourcePsi as? PsiBinaryExpression ?: return null
val dummyParent = psiFactory.createStatementFromText("a;", null)
dummyParent.firstChild.replace(binarySourcePsi)
ParenthesesUtils.removeParentheses(dummyParent.firstChild as PsiExpression, false)
return when (val result = dummyParent.firstChild) {
is PsiBinaryExpression -> JavaUBinaryExpression(result, null)
is PsiPolyadicExpression -> JavaUPolyadicExpression(result, null)
else -> error("Unexpected type " + result.javaClass)
}
}
private val PsiElement.branchStatement: PsiStatement?
get() = when (this) {
is PsiExpression -> JavaPsiFacade.getElementFactory(project).createExpressionStatement(this)
is PsiCodeBlock -> BlockUtils.createBlockStatement(project).also { it.codeBlock.replace(this) }
is PsiStatement -> this
else -> null
}
private fun PsiVariable.removeTypeElement() {
this.typeElement?.delete()
if (this.children.getOrNull(1) !is PsiIdentifier) {
this.children.getOrNull(1)?.delete()
}
}
private fun createNameFromSuggested(suggestedName: String?,
variableKind: VariableKind,
type: PsiType? = null,
initializer: PsiExpression? = null,
context: PsiElement? = null): String? {
val codeStyleManager = JavaCodeStyleManager.getInstance(project)
val name = suggestedName ?: codeStyleManager.generateVariableName(type, initializer, variableKind) ?: return null
return codeStyleManager.suggestUniqueVariableName(name, context, false)
}
private fun JavaCodeStyleManager.generateVariableName(type: PsiType?, initializer: PsiExpression?, kind: VariableKind) =
suggestVariableName(kind, null, initializer, type).names.firstOrNull()
} | apache-2.0 | ea00cedfc7f6db39fa05f1a918bb6ec0 | 43.279612 | 137 | 0.715608 | 5.602703 | false | false | false | false |
JetBrains/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/GrammarCheckingStrategy.kt | 1 | 9337 | // 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.
@file:Suppress("DEPRECATION")
package com.intellij.grazie.grammar.strategy
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.grammar.Typo
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.ElementBehavior.*
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain.*
import com.intellij.grazie.grammar.strategy.impl.ReplaceCharRule
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.grazie.utils.LinkedSet
import com.intellij.grazie.utils.orTrue
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
/**
* Strategy extracting elements for grammar checking used by Grazie plugin
*
* You need to implement [isMyContextRoot] and add com.intellij.grazie.grammar.strategy extension in your .xml config
*/
@Deprecated("Use TextExtractor and ProblemFilter instead")
@JvmDefaultWithCompatibility
interface GrammarCheckingStrategy {
/**
* Possible PsiElement behavior during grammar check
*
* [TEXT] - element contains text
* [STEALTH] - element's text is ignored
* [ABSORB] - element's text is ignored, as well as the typos that contain this element
*
* [ABSORB] and [STEALTH] behavior also prevents visiting children of these elements.
*
* Examples:
* Text: This is a <bold>error</bold> sample.
* PsiElements: ["This is a ", "<bold>", "error", "</bold>", " sample"]
*
* If this text pass as is to the grammar checker, then there are no errors.
* The reason are tags framing word 'error', these tags are not part of the sentence and used only for formatting.
* So you can add [STEALTH] behavior to these tags PsiElements, which made text passed to grammar checker 'This is a error sample.'
* and checker will find an error - 'Use "an" instead of 'a' if the following word starts with a vowel sound'
*
*
* Text: There is raining <br> Days passing by
* PsiElements: ["There is raining ", "<br>", "Days passing by"]
*
* There is <br> tag. Like in previous example this tag not used in the result text.
* But if we make tag <br> [STEALTH] there will be an error - 'There *are* raining days'
* By the way, 'Days passing by' is a new sentence that doesn't applies to previous one.
* In that case you can use [ABSORB] behavior, then this kind of errors will be filtered.
*/
enum class ElementBehavior {
TEXT,
STEALTH,
ABSORB
}
/**
* Possible domains for grammar check.
*
* [NON_TEXT] - domain for elements accepted as context root, but not containing reasonable text for check (IDs, file paths, etc.)
* [LITERALS] - domain for string literals of programming language
* [COMMENTS] - domain for general comments of programming languages (excluding doc comments)
* [DOCS] - domain for in-code documentation (JavaDocs, Python DocStrings, etc.)
* [PLAIN_TEXT] - domain for plain text (Markdown, HTML or LaTeX) and UI strings
*/
enum class TextDomain {
NON_TEXT,
LITERALS,
COMMENTS,
DOCS,
PLAIN_TEXT
}
/**
* Visible name of strategy for settings window.
*
* @return name of this strategy
*/
@NlsSafe
fun getName(): String {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
return Language.findLanguageByID(extension.language)?.displayName ?: extension.language
}
/**
* Return unique ID for grammar strategy. Used to distinguish strategies for user settings.
*
* NOTE: you need to override this method if you intend to use several strategies for one language.
*
* @return unique ID
*/
fun getID(): String {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
return "${extension.pluginDescriptor.pluginId}:${extension.language}"
}
/**
* Determine text block root, for example a paragraph of text.
*
* @param element visited element
* @return true if context root
*/
fun isMyContextRoot(element: PsiElement): Boolean
/**
* Determine tokens which should be treated as whitespaces for the current [Language].
* Default implementation considers that these tokens are the same as [ParserDefinition.getWhitespaceTokens].
*
* @return [TokenSet] of whitespace tokens
*/
fun getWhiteSpaceTokens(): TokenSet {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
val language = Language.findLanguageByID(extension.language) ?: return TokenSet.WHITE_SPACE
return LanguageParserDefinitions.INSTANCE.forLanguage(language).whitespaceTokens
}
/**
* Determine PsiElement roots that should be considered as a continuous text including [root].
* [root] element MUST be present in chain.
* Passing any sub-element in chain must return the same list of all the elements in the chain.
* Chain roots must be in the same [TextDomain] and have the same [GrammarCheckingStrategy]
* or be one of [getWhiteSpaceTokens].
* For example, this method can be used to combine single-line comments into
* a single block of text for grammar check.
*
* @param root root element previously selected in [isMyContextRoot]
* @return list of root elements that should be considered as a continuous text with [getWhiteSpaceTokens] elements
*/
fun getRootsChain(root: PsiElement): List<PsiElement> = listOf(root)
/**
* Determine if this strategy enabled by default.
*
* @return true if enabled else false
*/
fun isEnabledByDefault(): Boolean = !GraziePlugin.isBundled || ApplicationManager.getApplication()?.isUnitTestMode.orTrue()
/**
* Determine root PsiElement domain @see [TextDomain].
*
* @param root root element previously selected in [isMyContextRoot]
* @return [TextDomain] for [root] element
*/
fun getContextRootTextDomain(root: PsiElement) = StrategyUtils.getTextDomainOrDefault(this, root, default = PLAIN_TEXT)
/**
* Determine PsiElement behavior @see [ElementBehavior].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which behavior is specified
* @return [ElementBehavior] for [child] element
*/
fun getElementBehavior(root: PsiElement, child: PsiElement) = TEXT
/**
* Specify ranges, which will be removed from text before checking (like STEALTH behavior).
* You can use [StrategyUtils.indentIndexes] to hide the indentation of each line of text.
*
* @param root root element previously selected in [isMyContextRoot]
* @param text extracted text from root element without [ABSORB] and [STEALTH] ones
* in which you need to specify the ranges to remove from the grammar checking
* @return set of ranges in the [text] to be ignored
*/
fun getStealthyRanges(root: PsiElement, text: CharSequence): LinkedSet<IntRange> = StrategyUtils.emptyLinkedSet()
/**
* Determine if typo will be shown to user. The final check before add typo to [ProblemsHolder].
*
* @param root root element previously selected in [isMyContextRoot]
* @param typoRange range of the typo inside [root] element
* @param ruleRange range of elements needed for rule to find typo
* @return true if typo should be accepted
*/
fun isTypoAccepted(root: PsiElement, typoRange: IntRange, ruleRange: IntRange) = true
/**
* Determine if typo will be shown to user. The final check before add typo to [ProblemsHolder].
*
* @param parent common parent of [roots]
* @param roots roots from [getRootsChain] method
* @param typoRange range of the typo inside [parent] element
* @param ruleRange range of elements needed for rule to find typo
* @return true if typo should be accepted
*/
fun isTypoAccepted(parent: PsiElement, roots: List<PsiElement>, typoRange: IntRange, ruleRange: IntRange) = true
/**
* Get ignored typo categories for [child] element @see [Typo.Category].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which ignored categories are specified
* @return set of the ignored categories for [child]
*/
fun getIgnoredTypoCategories(root: PsiElement, child: PsiElement): Set<Typo.Category>? = null
/**
* Get ignored rules for [child] element @see [RuleGroup].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which ignored rules are specified
* @return RuleGroup with ignored rules for [child]
*/
fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement): RuleGroup? = null
/**
* Get rules for char replacement in PSI elements text @see [ReplaceCharRule].
* (In most cases you don't want to change this)
*
* @param root root element previously selected in [isMyContextRoot]
* @return list of char replacement rules for whole root context
*/
fun getReplaceCharRules(root: PsiElement): List<ReplaceCharRule> = emptyList()
}
| apache-2.0 | 51a99c9509e9f694e092de9b03db30a7 | 41.058559 | 140 | 0.729892 | 4.300783 | false | false | false | false |
exercism/xkotlin | exercises/practice/sieve/.meta/src/reference/kotlin/Sieve.kt | 1 | 408 | object Sieve {
fun primesUpTo(upperBound: Int): List<Int> {
val primes = mutableListOf<Int>()
var candidates = (2..upperBound).toList()
while (candidates.isNotEmpty()) {
val prime = candidates[0]
primes += prime
candidates = candidates.filterIndexed { index, value -> index != 0 && value % prime != 0 }
}
return primes
}
}
| mit | 5dc95dc4b2ab4197b942f9d0dd3531a5 | 30.384615 | 102 | 0.553922 | 4.636364 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/datas/FeeData.kt | 1 | 1685 | package com.masahirosaito.spigot.homes.datas
import com.google.gson.annotations.SerializedName
data class FeeData(
@SerializedName("Home Command Fee")
var HOME: Double = 0.0,
@SerializedName("Home Name Command Fee")
var HOME_NAME: Double = 0.0,
@SerializedName("Home Player Command Fee")
var HOME_PLAYER: Double = 0.0,
@SerializedName("Home Name Player Command Fee")
var HOME_NAME_PLAYER: Double = 0.0,
@SerializedName("Set Command Fee")
var SET: Double = 0.0,
@SerializedName("Set Name Command Fee")
var SET_NAME: Double = 0.0,
@SerializedName("Delete Command Fee")
var DELETE: Double = 0.0,
@SerializedName("Delete Name Command Fee")
var DELETE_NAME: Double = 0.0,
@SerializedName("List Command Fee")
var LIST: Double = 0.0,
@SerializedName("List Player Command Fee")
var LIST_PLAYER: Double = 0.0,
@SerializedName("Help Command Fee")
var HELP: Double = 0.0,
@SerializedName("Help Usage Command Fee")
var HELP_USAGE: Double = 0.0,
@SerializedName("Private Command Fee")
var PRIVATE: Double = 0.0,
@SerializedName("Private Name Command Fee")
var PRIVATE_NAME: Double = 0.0,
@SerializedName("Invite Accept Command Fee")
var INVITE: Double = 0.0,
@SerializedName("Invite Player Command Fee")
var INVITE_PLAYER: Double = 0.0,
@SerializedName("Invite Player Name Command Fee")
var INVITE_PLAYER_NAME: Double = 0.0,
@SerializedName("Reload Command Fee")
var RELOAD: Double = 0.0
)
| apache-2.0 | 0e9b4c981e829a6b367efede11b9917c | 27.083333 | 57 | 0.610682 | 4.060241 | false | false | false | false |
googlemaps/android-places-demos | snippets/app/src/main/java/com/google/places/kotlin/PlaceDetailsActivity.kt | 1 | 1922 | package com.google.places.kotlin
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.common.api.ApiException
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FetchPlaceRequest
import com.google.android.libraries.places.api.net.FetchPlaceResponse
import com.google.android.libraries.places.api.net.PlacesClient
class PlaceDetailsActivity : AppCompatActivity() {
private fun simpleExamples(place: Place) {
// [START maps_places_place_details_simple]
val name = place.name
val address = place.address
val location = place.latLng
// [END maps_places_place_details_simple]
}
private lateinit var placesClient: PlacesClient
private fun getPlaceById() {
// [START maps_places_get_place_by_id]
// Define a Place ID.
val placeId = "INSERT_PLACE_ID_HERE"
// Specify the fields to return.
val placeFields = listOf(Place.Field.ID, Place.Field.NAME)
// Construct a request object, passing the place ID and fields array.
val request = FetchPlaceRequest.newInstance(placeId, placeFields)
placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
Log.i(PlaceDetailsActivity.TAG, "Place found: ${place.name}")
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e(TAG, "Place not found: ${exception.message}")
val statusCode = exception.statusCode
TODO("Handle error with given status code")
}
}
// [END maps_places_get_place_by_id]
}
companion object {
private val TAG = PlaceDetailsActivity::class.java.simpleName
}
}
| apache-2.0 | 4b6de4edf3a036b36bdfdee015e9bae9 | 37.44 | 77 | 0.662851 | 4.438799 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/datas/strings/commands/SetCommandStringData.kt | 1 | 489 | package com.masahirosaito.spigot.homes.datas.strings.commands
data class SetCommandStringData(
val DESCRIPTION: String = "Set your home or named home",
val USAGE_SET: String = "Set your location to your default home",
val USAGE_SET_NAME: String = "Set your location to your named home",
val SET_DEFAULT_HOME: String = "&bSuccessfully set as &6default home&r",
val SET_NAMED_HOME: String = "&bSuccessfully set as &6home named <&r[home-name]&6>&r"
)
| apache-2.0 | 328b208352a00849a95adf00810a4b79 | 53.333333 | 93 | 0.693252 | 3.820313 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/SlyUseCompletionProvider.kt | 1 | 5472 | package com.aemtools.completion.htl.provider
import com.aemtools.completion.htl.CompletionPriority.CLOSE_CLASS
import com.aemtools.completion.htl.CompletionPriority.CLOSE_TEMPLATE
import com.aemtools.completion.htl.CompletionPriority.FAR_CLASS
import com.aemtools.completion.htl.CompletionPriority.FAR_TEMPLATE
import com.aemtools.common.util.normalizeToJcrRoot
import com.aemtools.common.util.relativeTo
import com.aemtools.index.HtlIndexFacade.getTemplates
import com.aemtools.index.model.TemplateDefinition
import com.aemtools.lang.java.JavaSearch
import com.aemtools.common.util.withPriority
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.psi.PsiClass
import com.intellij.util.ProcessingContext
import org.apache.commons.lang.StringUtils
/**
* Code completion for __data-sly-use.*__ attribute. (e.g. <div data-sly-use.bean="<caret>")
*
* @author Dmytro Troynikov.
*/
object SlyUseCompletionProvider : CompletionProvider<CompletionParameters>() {
private const val ONE_HUNDRED: Double = 100.0
override fun addCompletions(parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
result.addAllElements(useSuggestions(parameters))
}
/**
* Collect lookup elements suitable for `data-sly-use`.
*
* @param parameters completion parameters
* @return list of lookup elements for `data-sly-use`
*/
fun useSuggestions(parameters: CompletionParameters): List<LookupElement> {
val project = parameters.position.project
val currentFileName = normalizedFileName(parameters)
val useClasses = JavaSearch.findWcmUseClasses(project)
val slingModelClasses = JavaSearch.findSlingModels(project)
val useClassesVariants = extractCompletions(useClasses, currentFileName, "Use Class")
val slingModelVariants = extractCompletions(slingModelClasses, currentFileName, "Sling Model")
val allClasses = if (parameters.completionType == CompletionType.BASIC) {
useClassesVariants + slingModelVariants
} else {
(useClassesVariants + slingModelVariants)
.filter {
closeName(normalizedClassName(it.lookupString), currentFileName)
}
}
val templates = extractTemplates(parameters)
return allClasses + templates
}
private fun closeName(normalizedClassName: String, currentFileName: String): Boolean {
return StringUtils.getLevenshteinDistance(
normalizedClassName,
currentFileName) < (currentFileName.length / 2).inc()
}
private fun normalizedClassName(fqn: String): String =
fqn.substringAfterLast(".").toLowerCase()
private fun normalizedFileName(parameters: CompletionParameters): String =
parameters.originalFile.parent?.name?.toLowerCase()
?: parameters.originalFile.name.toLowerCase()
.let { it.replace("-", "") }
private fun extractCompletions(
classes: List<PsiClass>,
currentFileName: String,
type: String): List<LookupElement> {
return classes.flatMap {
val qualifiedName = it.qualifiedName
val name = it.name
if (qualifiedName == null || name == null) {
return@flatMap listOf<LookupElement>()
}
val result = LookupElementBuilder.create(qualifiedName)
.withLookupString(name)
.withPresentableText(name)
.withIcon(it.getIcon(0))
.withTypeText(type)
.withTailText(
"(${qualifiedName.substringAfterLast(".")})", true)
.withPriority(classCompletionPriority(currentFileName, name))
return@flatMap listOf(result)
}
}
private fun classCompletionPriority(fileName: String, className: String): Double =
base(fileName, className) - StringUtils.getLevenshteinDistance(fileName, className) / ONE_HUNDRED
private fun base(name1: String, name2: String): Double = if (closeName(name1, name2)) {
CLOSE_CLASS
} else {
FAR_CLASS
}
private fun extractTemplates(parameters: CompletionParameters): List<LookupElement> {
val dir = parameters.originalFile.containingDirectory.virtualFile
val dirPath = dir.path
val result: List<TemplateDefinition> = if (parameters.completionType == CompletionType.BASIC) {
getTemplates(parameters.position.project)
} else {
val allTemplates = getTemplates(parameters.position.project)
allTemplates.filter { "${it.containingDirectory}/".startsWith("${dir.path}/") }
}.groupBy { it.normalizedPath }
.flatMap { it.value }
.filter {
it.fullName != parameters.originalFile.virtualFile.path
}
return result.map {
LookupElementBuilder.create(it.normalizedPath.relativeTo(dirPath.normalizeToJcrRoot()))
.withTypeText("HTL Template")
.withTailText("(${it.normalizedPath})", true)
.withPresentableText(it.fileName)
.withIcon(AllIcons.FileTypes.Html)
.withPriority(if ("${it.containingDirectory}/".startsWith("${dir.path}/")) {
CLOSE_TEMPLATE
} else {
FAR_TEMPLATE
})
}
}
}
| gpl-3.0 | 8d9e2cc3b8cff12adb4dc30f0d33e6ce | 37 | 103 | 0.719481 | 4.725389 | false | false | false | false |
aporter/coursera-android | ExamplesKotlin/MapLocation/app/src/main/java/course/examples/maplocation/MapLocation.kt | 1 | 2776 | package course.examples.maplocation
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
// Several Activity lifecycle methods are instrumented to emit LogCat output
// so you can follow this class' lifecycle
class MapLocation : Activity() {
companion object {
const val TAG = "MapLocation"
}
// UI elements
private lateinit var addrText: EditText
private lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
/*
Required call through to Activity.onCreate()
Restore any saved instance state, if necessary
*/
super.onCreate(savedInstanceState)
// Set content view
setContentView(R.layout.main)
// Initialize UI elements
addrText = findViewById(R.id.location)
button = findViewById(R.id.mapButton)
// Link UI elements to actions in code
button.setOnClickListener { processClick() }
}
// Called when user clicks the Show Map button
private fun processClick() {
try {
// Process text for network transmission
var address = addrText.text.toString()
address = address.replace(' ', '+')
// Create Intent object for starting Google Maps application
val geoIntent = Intent(
Intent.ACTION_VIEW, Uri
.parse("geo:0,0?q=$address"))
if (packageManager.resolveActivity(geoIntent, 0) != null) {
// Use the Intent to start Google Maps application using Activity.startActivity()
startActivity(geoIntent)
}
} catch (e: Exception) {
// Log any error messages to LogCat using Log.e()
Log.e(TAG, e.toString())
}
}
override fun onStart() {
super.onStart()
Log.i(TAG, "The activity is visible and about to be started.")
}
override fun onRestart() {
super.onRestart()
Log.i(TAG, "The activity is visible and about to be restarted.")
}
override fun onResume() {
super.onResume()
Log.i(TAG, "The activity is visible and has focus (it is now \"resumed\")")
}
override fun onPause() {
super.onPause()
Log.i(TAG,
"Another activity is taking focus (this activity is about to be \"paused\")")
}
override fun onStop() {
super.onStop()
Log.i(TAG, "The activity is no longer visible (it is now \"stopped\")")
}
override fun onDestroy() {
super.onDestroy()
Log.i(TAG, "The activity is about to be destroyed.")
}
}
| mit | d356d25731e51d9b3065ce77c106aa50 | 26.215686 | 97 | 0.610591 | 4.713073 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/utils/Image.kt | 1 | 6784 | package graphics.scenery.utils
import cleargl.TGAReader
import graphics.scenery.volumes.Colormap
import org.lwjgl.system.MemoryUtil
import java.awt.Color
import java.awt.color.ColorSpace
import java.awt.geom.AffineTransform
import java.awt.image.*
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
import javax.imageio.ImageIO
/**
* Utility class for reading RGBA images via [BufferedImage].
* Image can store the image's RGBA content in [contents], and also stores image [width] and [height].
*
* @author Ulrik Guenther <[email protected]>
*/
open class Image(val contents: ByteBuffer, val width: Int, val height: Int, val depth: Int = 1) {
companion object {
protected val logger by LazyLogger()
private val StandardAlphaColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 8),
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE)
private val StandardColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 0),
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE)
/**
* Creates a new [Image] from a [stream], with the [extension] given. The image
* can be [flip]ped to accomodate Vulkan and OpenGL coordinate systems.
*/
@JvmStatic @JvmOverloads fun fromStream(stream: InputStream, extension: String, flip: Boolean = true): Image {
var bi: BufferedImage
val flippedImage: BufferedImage
val imageData: ByteBuffer
val pixels: IntArray
val buffer: ByteArray
if (extension.lowercase().endsWith("tga")) {
try {
val reader = BufferedInputStream(stream)
buffer = ByteArray(stream.available())
reader.read(buffer)
reader.close()
pixels = TGAReader.read(buffer, TGAReader.ARGB)
val width = TGAReader.getWidth(buffer)
val height = TGAReader.getHeight(buffer)
bi = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
bi.setRGB(0, 0, width, height, pixels, 0, width)
} catch (e: IOException) {
Colormap.logger.error("Could not read image from TGA. ${e.message}")
bi = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
bi.setRGB(0, 0, 1, 1, intArrayOf(255, 0, 0), 0, 1)
}
} else {
try {
val reader = BufferedInputStream(stream)
bi = ImageIO.read(stream)
reader.close()
} catch (e: IOException) {
Colormap.logger.error("Could not read image: ${e.message}")
bi = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
bi.setRGB(0, 0, 1, 1, intArrayOf(255, 0, 0), 0, 1)
}
}
stream.close()
if(flip) {
// convert to OpenGL UV space
flippedImage = createFlipped(bi)
imageData = bufferedImageToRGBABuffer(flippedImage)
} else {
imageData = bufferedImageToRGBABuffer(bi)
}
return Image(imageData, bi.width, bi.height)
}
/**
* Creates an Image from a resource given in [path], with [baseClass] as basis for the search path.
* [path] is expected to end in an extension (e.g., ".png"), such that the file type can be determined.
*/
@JvmStatic fun fromResource(path: String, baseClass: Class<*>): Image {
return fromStream(baseClass.getResourceAsStream(path), path.substringAfterLast(".").lowercase())
}
/**
* Converts a buffered image to an RGBA byte buffer.
*/
fun bufferedImageToRGBABuffer(bufferedImage: BufferedImage): ByteBuffer {
val imageBuffer: ByteBuffer
val raster: WritableRaster
val texImage: BufferedImage
var texWidth = bufferedImage.width
var texHeight = bufferedImage.height
// while (texWidth < bufferedImage.width) {
// texWidth *= 2
// }
// while (texHeight < bufferedImage.height) {
// texHeight *= 2
// }
if (bufferedImage.colorModel.hasAlpha()) {
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 4, null)
texImage = BufferedImage(StandardAlphaColorModel, raster, false, Hashtable<Any, Any>())
} else {
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 3, null)
texImage = BufferedImage(StandardColorModel, raster, false, Hashtable<Any, Any>())
}
val g = texImage.graphics
g.color = Color(0.0f, 0.0f, 0.0f, 1.0f)
g.fillRect(0, 0, texWidth, texHeight)
g.drawImage(bufferedImage, 0, 0, null)
g.dispose()
val data = (texImage.raster.dataBuffer as DataBufferByte).data
imageBuffer = MemoryUtil.memAlloc(data.size)
imageBuffer.order(ByteOrder.nativeOrder())
imageBuffer.put(data, 0, data.size)
imageBuffer.rewind()
return imageBuffer
}
/**
* Flips a given [BufferedImage] and returns it.
*/
// the following three routines are from
// http://stackoverflow.com/a/23458883/2129040,
// authored by MarcoG
fun createFlipped(image: BufferedImage): BufferedImage {
val at = AffineTransform()
at.concatenate(AffineTransform.getScaleInstance(1.0, -1.0))
at.concatenate(AffineTransform.getTranslateInstance(0.0, (-image.height).toDouble()))
return createTransformed(image, at)
}
/**
* Transforms a given [image] by [AffineTransform] [at].
*/
private fun createTransformed(
image: BufferedImage, at: AffineTransform): BufferedImage {
val newImage = BufferedImage(
image.width, image.height,
BufferedImage.TYPE_INT_ARGB)
val g = newImage.createGraphics()
g.transform(at)
g.drawImage(image, 0, 0, null)
g.dispose()
return newImage
}
}
}
| lgpl-3.0 | df8864c81bfc6c597ce80d4ac34b628c | 36.688889 | 119 | 0.574735 | 4.630717 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/config/AppConfig.kt | 1 | 2133 | /*
* Copyright (C) 2019 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.config
object AppConfig {
const val SERVER_PORT_WEBSHARE = 58732
const val DEFAULT_TIMEOUT_SOCKET = 5000
const val DELAY_DEFAULT_NOTIFICATION = 1000
const val EMAIL_DEVELOPER = "[email protected]"
const val URI_GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=org.monora.uprotocol.client.android"
const val URI_ORG_HOME = "https://monora.org"
const val URI_REPO_APP = "https://github.com/trebleshot"
const val URI_GITHUB_UPROTOCOL = "https://github.com/uprotocol"
const val URI_TRANSLATE = "https://hosted.weblate.org/engage/TrebleShot/"
const val URI_TELEGRAM_CHANNEL = "https://t.me/trebleshotNews"
const val PREFIX_ACCESS_POINT = "TS_"
const val EXT_FILE_PART = "tshare"
const val KEY_GOOGLE_PUBLIC = ("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk1peq7MhNms9ynhnoRtwxnb"
+ "izdEr3TKifUGlUPB3r33WkvPWjwowRvYeuY36+CkBmtjc46Xg/6/jrhPY+L0a+wd58lsNxLUMpo7"
+ "tN2std0TGrsMmmlihb4Bsxcu/6ThsY4CIQx0bdze2v8Zle3e4EoHuXcqQnpwkb+3wMx2rR2E9ih+"
+ "6utqrYAop9NdAbsRZ6BDXDUgJEuiHnRKwDZGDjU5PD4TCiR1jz2YJPYiRuI1QytJM6LirJu6YwE/"
+ "o6pfzSQ3xXlK4yGpGUhzLdTmSNQNIJTWRqZoM7qNgp+0ocmfQRJ32/6E+BxbJaVbHdTINhbVAvLR"
+ "+UFyQ2FldecfuQQIDAQAB")
val DEFAULT_DISABLED_INTERFACES = arrayOf("rmnet")
}
| gpl-2.0 | 38bec2d6a267f3ded2bd5248722d4e31 | 39.226415 | 115 | 0.739212 | 3.067626 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/component/UserEditor.kt | 1 | 6775 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component
import com.faendir.acra.i18n.Messages
import com.faendir.acra.model.User
import com.faendir.acra.service.UserService
import com.faendir.acra.ui.component.Translatable.ValidatedValue
import com.faendir.acra.ui.ext.setMaxWidthFull
import com.vaadin.flow.component.AbstractField.ComponentValueChangeEvent
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.Composite
import com.vaadin.flow.component.HasValidation
import com.vaadin.flow.component.HasValue
import com.vaadin.flow.component.orderedlayout.FlexLayout
import com.vaadin.flow.data.binder.Binder
import com.vaadin.flow.data.binder.Setter
import com.vaadin.flow.data.binder.ValidationResult
import com.vaadin.flow.data.binder.ValueContext
import com.vaadin.flow.data.validator.EmailValidator
import com.vaadin.flow.dom.ElementFactory
/**
* @author lukas
* @since 28.02.19
*/
class UserEditor(userService: UserService, private var user: User, isExistingUser: Boolean, onSuccess: () -> Unit) : Composite<FlexLayout>() {
init {
setId(EDITOR_ID)
val binder = Binder<User>()
val username = Translatable.createTextField(Messages.USERNAME)
exposeInput(username)
username.setWidthFull()
username.setId(USERNAME_ID)
val usernameBindingBuilder = binder.forField(username)
if (!isExistingUser) {
usernameBindingBuilder.asRequired(getTranslation(Messages.USERNAME_REQUIRED))
}
usernameBindingBuilder.withValidator({ it == user.username || userService.getUser(it) == null }, getTranslation(Messages.USERNAME_TAKEN))
.bind({ it.username }, if (!isExistingUser) Setter { u: User, value: String -> u.username = value.toLowerCase() } else null)
content.add(username)
val mail = Translatable.createTextField(Messages.EMAIL)
mail.setWidthFull()
mail.setId(MAIL_ID)
val emailValidator = EmailValidator(getTranslation(Messages.INVALID_MAIL))
binder.forField(mail).withValidator { m: String, c: ValueContext? -> if (m.isEmpty()) ValidationResult.ok() else emailValidator.apply(m, c) }
.bind({ it.mail ?: "" }) { u: User, value: String? -> u.mail = value }
content.add(mail)
val newPassword = Translatable.createPasswordField(Messages.NEW_PASSWORD)
exposeInput(newPassword)
newPassword.setWidthFull()
newPassword.setId(PASSWORD_ID)
val repeatPassword = Translatable.createPasswordField(Messages.REPEAT_PASSWORD)
exposeInput(repeatPassword)
repeatPassword.setWidthFull()
repeatPassword.setId(REPEAT_PASSWORD_ID)
if (isExistingUser) {
val oldPassword = Translatable.createPasswordField(Messages.OLD_PASSWORD)
exposeInput(oldPassword)
oldPassword.setWidthFull()
oldPassword.setId(OLD_PASSWORD_ID)
val oldPasswordBinding = binder.forField(oldPassword).withValidator({
if (newPassword.value.isNotEmpty() || oldPassword.value.isNotEmpty()) userService.checkPassword(user, it) else true
}, getTranslation(Messages.INCORRECT_PASSWORD)).bind({ "" }) { _: User?, _: String? -> }
content.add(oldPassword)
newPassword.addValueChangeListener { oldPasswordBinding.validate() }
repeatPassword.addValueChangeListener { oldPasswordBinding.validate() }
}
val newPasswordBindingBuilder = binder.forField(newPassword)
.withValidator { p, _ -> if (p.isNotBlank()) ValidationResult.ok() else ValidationResult.error(getTranslation(Messages.INVALID_PASSWORD)) }
val repeatPasswordBindingBuilder = binder.forField(repeatPassword)
if (!isExistingUser) {
newPasswordBindingBuilder.asRequired(getTranslation(Messages.PASSWORD_REQUIRED))
repeatPasswordBindingBuilder.asRequired(getTranslation(Messages.PASSWORD_REQUIRED))
}
newPasswordBindingBuilder.bind({ "" }) { u: User, plainTextPassword: String? ->
if (plainTextPassword != null && "" != plainTextPassword) {
u.setPlainTextPassword(plainTextPassword)
}
}
content.add(newPassword)
val repeatPasswordBinding = repeatPasswordBindingBuilder.withValidator({ it == newPassword.value }, getTranslation(Messages.PASSWORDS_NOT_MATCHING))
.bind({ "" }) { _: User?, _: String? -> }
newPassword.addValueChangeListener { if (repeatPassword.value.isNotEmpty()) repeatPasswordBinding.validate() }
content.add(repeatPassword)
binder.readBean(user)
val button = Translatable.createButton(Messages.CONFIRM) {
if (binder.writeBeanIfValid(user)) {
user = userService.store(user)
binder.readBean(user)
onSuccess()
}
}
button.setWidthFull()
button.setId(SUBMIT_ID)
button.content.isEnabled = false
binder.addStatusChangeListener { button.content.isEnabled = it.binder.hasChanges() }
content.add(button)
content.setFlexDirection(FlexLayout.FlexDirection.COLUMN)
content.setMaxWidthFull()
content.width = "calc(var(--lumo-size-m) * 10)"
}
/**
* password managers need an input outside the shadow dom, which we add here.
* @param field the field which should be visible to password managers
* @param <T> the type of the field
**/
private fun <T, V> exposeInput(field: ValidatedValue<T, *, V>) where T : Component, T : HasValue<ComponentValueChangeEvent<T, V>, V>, T : HasValidation {
val input = ElementFactory.createInput()
input.setAttribute("slot", "input")
field.element.appendChild(input)
}
companion object {
const val EDITOR_ID = "userEditor"
const val USERNAME_ID = "editorUsername"
const val MAIL_ID = "editorMail"
const val PASSWORD_ID = "editorPassword"
const val OLD_PASSWORD_ID = "editorOldPassword"
const val REPEAT_PASSWORD_ID = "editorRepeatPassword"
const val SUBMIT_ID = "editorSubmit"
}
} | apache-2.0 | 15f27bdfde75c814183059732fbebabd | 48.101449 | 157 | 0.690923 | 4.351317 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/scheduler/actors/ConcurrentStatefulActorBenchmark.kt | 1 | 7622 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.scheduler.actors
import benchmarks.*
import benchmarks.akka.*
import benchmarks.scheduler.actors.StatefulActorBenchmark.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
/*
* Noisy benchmarks useful to measure scheduling fairness and migration of affinity-sensitive tasks.
*
* Benchmark: single actor fans out requests to all (#cores count) computation actors and then ping pongs each in loop.
* Fair benchmark expects that every computation actor will receive exactly N messages, unfair expects N * cores messages received in total.
*
* Benchmark (dispatcher) (stateSize) Mode Cnt Score Error Units
* ConcurrentStatefulActorBenchmark.multipleComputationsFair fjp 1024 avgt 5 215.439 ± 29.685 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_1 1024 avgt 5 85.374 ± 4.477 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_8 1024 avgt 5 418.510 ± 46.906 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair experimental 1024 avgt 5 165.250 ± 20.309 ms/op
*
* ConcurrentStatefulActorBenchmark.multipleComputationsFair fjp 8192 avgt 5 220.576 ± 35.596 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_1 8192 avgt 5 298.276 ± 22.256 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_8 8192 avgt 5 426.105 ± 29.870 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair experimental 8192 avgt 5 288.546 ± 20.280 ms/op
*
* ConcurrentStatefulActorBenchmark.multipleComputationsFair fjp 262144 avgt 5 4146.057 ± 284.377 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_1 262144 avgt 5 10250.107 ± 1421.253 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair ftp_8 262144 avgt 5 6761.283 ± 4091.452 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsFair experimental 262144 avgt 5 6521.436 ± 346.726 ms/op
*
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair fjp 1024 avgt 5 289.875 ± 14.241 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_1 1024 avgt 5 87.336 ± 5.160 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_8 1024 avgt 5 430.718 ± 23.497 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair experimental 1024 avgt 5 153.704 ± 13.869 ms/op
*
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair fjp 8192 avgt 5 289.836 ± 9.719 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_1 8192 avgt 5 299.523 ± 17.357 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_8 8192 avgt 5 433.959 ± 27.669 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair experimental 8192 avgt 5 283.441 ± 22.740 ms/op
*
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair fjp 262144 avgt 5 7804.066 ± 1386.595 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_1 262144 avgt 5 11142.530 ± 381.401 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair ftp_8 262144 avgt 5 7739.136 ± 1317.885 ms/op
* ConcurrentStatefulActorBenchmark.multipleComputationsUnfair experimental 262144 avgt 5 7076.911 ± 1971.615 ms/op
*
*/
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class ConcurrentStatefulActorBenchmark : ParametrizedDispatcherBase() {
@Param("1024", "8192")
var stateSize: Int = -1
@Param("fjp", "scheduler")
override var dispatcher: String = "fjp"
@Benchmark
fun multipleComputationsUnfair() = runBlocking {
val resultChannel: Channel<Unit> = Channel(1)
val computations = (0 until CORES_COUNT).map { computationActor(stateSize) }
val requestor = requestorActorUnfair(computations, resultChannel)
requestor.send(Letter(Start(), requestor))
resultChannel.receive()
}
@Benchmark
fun multipleComputationsFair() = runBlocking {
val resultChannel: Channel<Unit> = Channel(1)
val computations = (0 until CORES_COUNT).map { computationActor(stateSize) }
val requestor = requestorActorFair(computations, resultChannel)
requestor.send(Letter(Start(), requestor))
resultChannel.receive()
}
fun requestorActorUnfair(
computations: List<SendChannel<Letter>>,
stopChannel: Channel<Unit>
) =
actor<Letter>(capacity = 1024) {
var received = 0
for (letter in channel) with(letter) {
when (message) {
is Start -> {
computations.shuffled()
.forEach { it.send(Letter(ThreadLocalRandom.current().nextLong(), channel)) }
}
is Long -> {
if (++received >= ROUNDS * 8) {
computations.forEach { it.close() }
stopChannel.send(Unit)
return@actor
} else {
sender.send(Letter(ThreadLocalRandom.current().nextLong(), channel))
}
}
else -> error("Cannot happen: $letter")
}
}
}
fun requestorActorFair(
computations: List<SendChannel<Letter>>,
stopChannel: Channel<Unit>
) =
actor<Letter>(capacity = 1024) {
val received = hashMapOf(*computations.map { it to 0 }.toTypedArray())
var receivedTotal = 0
for (letter in channel) with(letter) {
when (message) {
is Start -> {
computations.shuffled()
.forEach { it.send(Letter(ThreadLocalRandom.current().nextLong(), channel)) }
}
is Long -> {
if (++receivedTotal >= ROUNDS * computations.size) {
computations.forEach { it.close() }
stopChannel.send(Unit)
return@actor
} else {
val receivedFromSender = received[sender]!!
if (receivedFromSender <= ROUNDS) {
received[sender] = receivedFromSender + 1
sender.send(Letter(ThreadLocalRandom.current().nextLong(), channel))
}
}
}
else -> error("Cannot happen: $letter")
}
}
}
}
| apache-2.0 | 09acb980f285d70d99eb0cc79b6d41c6 | 52.507042 | 140 | 0.601211 | 4.427739 | false | false | false | false |
stevesea/RPGpad | adventuresmith-core/src/main/kotlin/org/stevesea/adventuresmith/core/Shuffler.kt | 2 | 3711 | /*
* Copyright (c) 2016 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 RPG-Pad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.KodeinAware
import com.github.salomonbrys.kodein.instance
import mu.KLoggable
import org.stevesea.adventuresmith.core.dice_roller.DiceParser
import java.util.Collections
import java.util.Random
class Shuffler(override val kodein: Kodein) : KodeinAware, KLoggable {
override val logger = logger()
val random: Random = instance()
val diceParser : DiceParser = instance()
fun <T> pick(items: Collection<T>) : T {
// use modulo because the randomizer might be a mock that's been setup to do something dumb
// and returns greater than the # of items in list
return items.elementAt(random.nextInt(items.size) % items.size)
}
fun pick(rmap: RangeMap) : String {
val itemsInds = rmap.keyRange().toList()
val sel = pick(itemsInds)
return rmap.select(sel)
}
fun pickN(rmap: RangeMap, num: Int) : List<String> {
if (num <= 0)
return listOf()
val itemsInds = rmap.keyRange().toList()
val selN = pickN(itemsInds, num)
return selN.map { rmap.select(it) }
}
fun <T> pickN(items: Collection<T>, num: Int) : Collection<T> {
if (num <= 0)
return listOf()
val localItems = items.toMutableList()
Collections.shuffle(localItems, random)
return localItems.take(num)
}
fun pickN(thing: Any, num: Int) : Collection<Any?> {
if (thing is RangeMap) {
return pickN(thing, num)
} else if (thing is Collection<*>) {
return pickN(thing, num)
} else {
throw IllegalArgumentException("don't know how to select thing of type " + thing.javaClass)
}
}
fun pickD(diceStr: String, thing: Any) : String {
if (thing is RangeMap) {
return pickD(diceStr, thing)
} else if (thing is Collection<*>) {
return pickD(diceStr, thing as Collection<String>)
} else {
throw IllegalArgumentException("don't know how to select thing of type " + thing.javaClass)
}
}
fun pickD(diceStr: String, items: RangeMap) : String {
try {
return items.select(roll(diceStr))
} catch (e: Exception) {
logger.warn("Error looking up $diceStr from rmap", e.message)
throw e
}
}
fun <T> pickD(diceStr: String, items: Collection<T>): T {
// dice are 1-based, list indexes are 0-based so subtract 1.
// then clamp the dice roll to the acceptable range
var ind = roll(diceStr) - 1
if (ind < 0)
ind = 0
else if (ind > items.size - 1)
ind = items.size - 1
return items.elementAt(ind)
}
fun roll(diceStr: String) : Int = diceParser.roll(diceStr)
fun rollN(diceStr: String, n: Int) : List<Int> = diceParser.rollN(diceStr, n)
}
| gpl-3.0 | cff453b772851dcea82641b756bf9854 | 34.342857 | 103 | 0.636756 | 3.825773 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/super/superConstructor/objectExtendsInner.kt | 4 | 310 | open class Foo(val value: String) {
open inner class Inner(val d: Double = -1.0, val s: String, vararg val y: Int) {
open fun result() = "Fail"
}
val obj = object : Inner(s = "O") {
override fun result() = s + value
}
}
fun box(): String {
return Foo("K").obj.result()
}
| apache-2.0 | d8d12355538347611eab44ad0c5fbf21 | 21.142857 | 84 | 0.548387 | 3.229167 | false | false | false | false |
AndroidX/androidx | compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/tasks/IconGenerationTask.kt | 3 | 8415 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator.tasks
import androidx.compose.material.icons.generator.Icon
import androidx.compose.material.icons.generator.IconProcessor
import com.android.build.gradle.LibraryExtension
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskProvider
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import java.io.File
import java.util.Locale
/**
* Base [org.gradle.api.Task] for tasks relating to icon generation.
*/
@CacheableTask
abstract class IconGenerationTask : DefaultTask() {
/**
* Directory containing raw drawables. These icons will be processed to generate programmatic
* representations.
*/
@PathSensitive(PathSensitivity.RELATIVE)
@InputDirectory
val allIconsDirectory =
project.rootProject.project(GeneratorProject).projectDir.resolve("raw-icons")
/**
* Specific theme to generate icons for, or null to generate all
*/
@Optional
@Input
var themeName: String? = null
/**
* Specific icon directories to use in this task
*/
@Internal
fun getIconDirectories(): List<File> {
val themeName = themeName
if (themeName != null) {
return listOf(allIconsDirectory.resolve(themeName))
} else {
return allIconsDirectory.listFiles()!!.filter { it.isDirectory }
}
}
/**
* Checked-in API file for the generator module, where we will track all the generated icons
*/
@PathSensitive(PathSensitivity.NONE)
@InputFile
val expectedApiFile =
project.rootProject.project(GeneratorProject).projectDir.resolve("api/icons.txt")
/**
* Root build directory for this task, where outputs will be placed into.
*/
@OutputDirectory
lateinit var buildDirectory: File
/**
* Generated API file that will be placed in the build directory. This can be copied manually
* to [expectedApiFile] to confirm that API changes were intended.
*/
@get:OutputFile
val generatedApiFile: File
get() = buildDirectory.resolve("api/icons.txt")
/**
* @return a list of all processed [Icon]s from [getIconDirectories].
*/
fun loadIcons(): List<Icon> {
// material-icons-core loads and verifies all of the icons from all of the themes:
// both that all icons are present in all themes, and also that no icons have been removed.
// So, when we're loading just one theme, we don't need to verify it
val verifyApi = themeName == null
return IconProcessor(
getIconDirectories(),
expectedApiFile,
generatedApiFile,
verifyApi
).process()
}
@get:OutputDirectory
val generatedSrcMainDirectory: File
get() = buildDirectory.resolve(GeneratedSrcMain)
@get:OutputDirectory
val generatedSrcAndroidTestDirectory: File
get() = buildDirectory.resolve(GeneratedSrcAndroidTest)
@get:OutputDirectory
val generatedResourceDirectory: File
get() = buildDirectory.resolve(GeneratedResource)
/**
* The action for this task
*/
@TaskAction
abstract fun run()
companion object {
/**
* Registers the core [project]. The core project contains only the icons defined in
* [androidx.compose.material.icons.generator.CoreIcons], and no tests.
*/
@JvmStatic
fun registerCoreIconProject(
project: Project,
libraryExtension: LibraryExtension,
isMpp: Boolean
) {
if (isMpp) {
CoreIconGenerationTask.register(project, null)
} else {
libraryExtension.libraryVariants.all { variant ->
CoreIconGenerationTask.register(project, variant)
}
}
}
/**
* Registers the extended [project]. The core project contains all icons except for the
* icons defined in [androidx.compose.material.icons.generator.CoreIcons], as well as a
* bitmap comparison test for every icon in both the core and extended project.
*/
@JvmStatic
fun registerExtendedIconThemeProject(
project: Project,
libraryExtension: LibraryExtension,
isMpp: Boolean
) {
if (isMpp) {
ExtendedIconGenerationTask.register(project, null)
} else {
libraryExtension.libraryVariants.all { variant ->
ExtendedIconGenerationTask.register(project, variant)
}
}
// b/175401659 - disable lint as it takes a long time, and most errors should
// be caught by lint on material-icons-core anyway
project.afterEvaluate {
project.tasks.named("lintAnalyzeDebug") { t ->
t.enabled = false
}
project.tasks.named("lintDebug") { t ->
t.enabled = false
}
}
}
@JvmStatic
fun registerExtendedIconMainProject(
project: Project,
libraryExtension: LibraryExtension
) {
libraryExtension.testVariants.all { variant ->
IconTestingGenerationTask.register(project, variant)
}
}
const val GeneratedSrcMain = "src/commonMain/kotlin"
const val GeneratedSrcAndroidTest = "src/androidAndroidTest/kotlin"
const val GeneratedResource = "generatedIcons/res"
}
}
// Path to the generator project
private const val GeneratorProject = ":compose:material:material:icons:generator"
/**
* Registers a new [T] in [this], and sets [IconGenerationTask.buildDirectory] depending on
* [variant].
*
* @param variant the [com.android.build.gradle.api.BaseVariant] to associate this task with, or
* `null` if this task does not change between variants.
* @return a [Pair] of the created [TaskProvider] of [T] of [IconGenerationTask], and the [File]
* for the directory that files will be generated to
*/
@Suppress("DEPRECATION") // BaseVariant
fun <T : IconGenerationTask> Project.registerGenerationTask(
taskName: String,
taskClass: Class<T>,
variant: com.android.build.gradle.api.BaseVariant? = null
): Pair<TaskProvider<T>, File> {
val variantName = variant?.name ?: "allVariants"
val themeName = if (project.name.contains("material-icons-extended-")) {
project.name.replace("material-icons-extended-", "")
} else {
null
}
val buildDirectory = project.buildDir.resolve("generatedIcons/$variantName")
return tasks.register("$taskName${variantName.capitalize(Locale.getDefault())}", taskClass) {
it.themeName = themeName
it.buildDirectory = buildDirectory
} to buildDirectory
}
fun Project.getMultiplatformSourceSet(name: String): KotlinSourceSet {
val sourceSet = project.multiplatformExtension!!.sourceSets.find { it.name == name }
return requireNotNull(sourceSet) {
"No source sets found matching $name"
}
}
private val Project.multiplatformExtension
get() = extensions.findByType(KotlinMultiplatformExtension::class.java)
| apache-2.0 | c0a0f0b7d48a1d71eeb932eb9f7e69f8 | 33.62963 | 99 | 0.667499 | 4.730185 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinMissingWhenBodyFixer.kt | 6 | 1360 | // 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.psi.KtWhenExpression
class KotlinMissingWhenBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
if (element !is KtWhenExpression) return
val doc = editor.document
val openBrace = element.openBrace
val closeBrace = element.closeBrace
if (openBrace == null && closeBrace == null && element.entries.isEmpty()) {
val openBraceAfter = element.insertOpenBraceAfter()
if (openBraceAfter != null) {
doc.insertString(openBraceAfter.range.end, "{}")
}
}
}
private fun KtWhenExpression.insertOpenBraceAfter(): PsiElement? = when {
rightParenthesis != null -> rightParenthesis
subjectExpression != null -> null
leftParenthesis != null -> null
else -> whenKeyword
}
}
| apache-2.0 | 34eec9149d7812b5073868bdc8e3b40d | 39 | 158 | 0.710294 | 4.839858 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt | 1 | 3462 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.config.LanguageFeature.ArrayLiteralsInAnnotations
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.isArrayOfMethod
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ReplaceArrayOfWithLiteralInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = callExpressionVisitor(fun(expression) {
if (!expression.languageVersionSettings.supportsFeature(ArrayLiteralsInAnnotations) &&
!isUnitTestMode()
) return
val calleeExpression = expression.calleeExpression as? KtNameReferenceExpression ?: return
when (val parent = expression.parent) {
is KtValueArgument -> {
if (parent.parent?.parent !is KtAnnotationEntry) return
if (parent.getSpreadElement() != null && !parent.isNamed()) return
}
is KtParameter -> {
val constructor = parent.parent?.parent as? KtPrimaryConstructor ?: return
val containingClass = constructor.getContainingClassOrObject()
if (!containingClass.isAnnotation()) return
}
else -> return
}
if (!expression.isArrayOfMethod()) return
val calleeName = calleeExpression.getReferencedName()
holder.registerProblem(
calleeExpression,
KotlinBundle.message("0.call.should.be.replaced.with.array.literal", calleeName),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithArrayLiteralFix()
)
})
private class ReplaceWithArrayLiteralFix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("replace.with.array.literal.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val calleeExpression = descriptor.psiElement as KtExpression
val callExpression = calleeExpression.parent as KtCallExpression
val valueArgument = callExpression.getParentOfType<KtValueArgument>(false)
valueArgument?.getSpreadElement()?.delete()
val arguments = callExpression.valueArguments
val arrayLiteral = KtPsiFactory(callExpression).buildExpression {
appendFixedText("[")
for ((index, argument) in arguments.withIndex()) {
appendExpression(argument.getArgumentExpression())
if (index != arguments.size - 1) {
appendFixedText(", ")
}
}
appendFixedText("]")
} as KtCollectionLiteralExpression
callExpression.replace(arrayLiteral)
}
}
} | apache-2.0 | f1eb988942c81c8d0067c7f2a2ed029c | 43.974026 | 158 | 0.692374 | 5.897785 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutRow.kt | 1 | 24443 | // 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.ui.layout.migLayout
import com.intellij.icons.AllIcons
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.HideableTitledSeparator
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.TitledSeparator
import com.intellij.ui.UIBundle
import com.intellij.ui.components.DialogPanel
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import net.miginfocom.layout.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.*
import javax.swing.border.LineBorder
import javax.swing.text.JTextComponent
import kotlin.math.max
import kotlin.reflect.KMutableProperty0
internal class MigLayoutRow(private val parent: MigLayoutRow?,
override val builder: MigLayoutBuilder,
val labeled: Boolean = false,
val noGrid: Boolean = false,
private val indent: Int /* level number (nested rows) */,
private val incrementsIndent: Boolean = parent != null) : Row() {
companion object {
private const val COMPONENT_ENABLED_STATE_KEY = "MigLayoutRow.enabled"
private const val COMPONENT_VISIBLE_STATE_KEY = "MigLayoutRow.visible"
// as static method to ensure that members of current row are not used
private fun createCommentRow(parent: MigLayoutRow,
component: JComponent,
indent: Int,
isParentRowLabeled: Boolean,
forComponent: Boolean,
columnIndex: Int,
anchorComponent: JComponent? = null) {
val cc = CC()
val commentRow = parent.createChildRow()
commentRow.isComment = true
commentRow.addComponent(component, cc)
if (forComponent) {
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
cc.skip = columnIndex
}
else if (isParentRowLabeled) {
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
cc.skip()
}
else if (anchorComponent == null || anchorComponent is JToggleButton) {
cc.horizontal.gapBefore = gapToBoundSize(indent + parent.spacing.indentLevel, true)
}
else {
cc.horizontal.gapBefore = gapToBoundSize(indent, true)
}
}
// as static method to ensure that members of current row are not used
private fun configureSeparatorRow(row: MigLayoutRow, @NlsContexts.Separator title: String?) {
val separatorComponent = if (title == null) SeparatorComponent(0, OnePixelDivider.BACKGROUND, null) else TitledSeparator(title)
row.addTitleComponent(separatorComponent, isEmpty = title == null)
}
}
val components: MutableList<JComponent> = SmartList()
var rightIndex = Int.MAX_VALUE
private var lastComponentConstraintsWithSplit: CC? = null
private var columnIndex = -1
internal var subRows: MutableList<MigLayoutRow>? = null
private set
var gapAfter: String? = null
set(value) {
field = value
rowConstraints?.gapAfter = if (value == null) null else ConstraintParser.parseBoundSize(value, true, false)
}
var rowConstraints: DimConstraint? = null
private var componentIndexWhenCellModeWasEnabled = -1
private val spacing: SpacingConfiguration
get() = builder.spacing
private var isTrailingSeparator = false
private var isComment = false
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
@Deprecated("Use Kotlin UI DSL Version 2")
override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) {
if (title != null) {
label(title)
gapAfter = "${spacing.radioGroupTitleVerticalGap}px!"
}
builder.withButtonGroup(buttonGroup, body)
}
override fun checkBoxGroup(title: String?, body: () -> Unit) {
if (title != null) {
label(title)
gapAfter = "${spacing.radioGroupTitleVerticalGap}px!"
}
body()
}
override var enabled = true
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
if (!value) {
if (!c.isEnabled) {
// current state of component differs from current row state - preserve current state to apply it when row state will be changed
c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, false)
}
}
else {
if (c.getClientProperty(COMPONENT_ENABLED_STATE_KEY) == false) {
// remove because for active row component state can be changed and we don't want to add listener to update value accordingly
c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, null)
// do not set to true, preserve old component state
continue
}
}
c.isEnabled = value
}
}
override var visible = true
set(value) {
if (field == value) {
return
}
field = value
for ((index, c) in components.withIndex()) {
builder.componentConstraints[c]?.hideMode = if (index == components.size - 1 && value) 2 else 3
if (!value) {
c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, if (c.isVisible) null else false)
}
else {
if (c.getClientProperty(COMPONENT_VISIBLE_STATE_KEY) == false) {
c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, null)
continue
}
}
c.isVisible = value
}
}
override var subRowsEnabled = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach {
it.enabled = value
it.subRowsEnabled = value
}
components.firstOrNull()?.parent?.repaint() // Repaint all dependent components in sync
}
override var subRowsVisible = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach {
it.visible = value
it.subRowsVisible = value
if (it != subRows!!.last()) {
it.gapAfter = if (value) null else "0px!"
}
}
}
override var subRowIndent: Int = -1
internal val isLabeledIncludingSubRows: Boolean
get() = labeled || (subRows?.any { it.isLabeledIncludingSubRows } ?: false)
internal val columnIndexIncludingSubRows: Int
get() = max(columnIndex, subRows?.asSequence()?.map { it.columnIndexIncludingSubRows }?.maxOrNull() ?: -1)
override fun createChildRow(label: JLabel?, isSeparated: Boolean, noGrid: Boolean, title: String?): MigLayoutRow {
return createChildRow(indent, label, isSeparated, noGrid, title)
}
private fun createChildRow(indent: Int,
label: JLabel? = null,
isSeparated: Boolean = false,
noGrid: Boolean = false,
@NlsContexts.Separator title: String? = null,
incrementsIndent: Boolean = true): MigLayoutRow {
val subRows = getOrCreateSubRowsList()
val newIndent = if (!this.incrementsIndent) indent else indent + spacing.indentLevel
val row = MigLayoutRow(this, builder,
labeled = label != null,
noGrid = noGrid,
indent = if (subRowIndent >= 0) subRowIndent * spacing.indentLevel else newIndent,
incrementsIndent = incrementsIndent)
if (isSeparated) {
val separatorRow = MigLayoutRow(this, builder, indent = newIndent, noGrid = true)
configureSeparatorRow(separatorRow, title)
separatorRow.enabled = subRowsEnabled
separatorRow.subRowsEnabled = subRowsEnabled
separatorRow.visible = subRowsVisible
separatorRow.subRowsVisible = subRowsVisible
row.getOrCreateSubRowsList().add(separatorRow)
}
var insertIndex = subRows.size
if (insertIndex > 0 && subRows[insertIndex-1].isTrailingSeparator) {
insertIndex--
}
if (insertIndex > 0 && subRows[insertIndex-1].isComment) {
insertIndex--
}
subRows.add(insertIndex, row)
row.enabled = subRowsEnabled
row.subRowsEnabled = subRowsEnabled
row.visible = subRowsVisible
row.subRowsVisible = subRowsVisible
if (label != null) {
row.addComponent(label)
}
return row
}
private fun <T : JComponent> addTitleComponent(titleComponent: T, isEmpty: Boolean) {
val cc = CC()
if (isEmpty) {
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false)
isTrailingSeparator = true
}
else {
// TitledSeparator doesn't grow by default opposite to SeparatorComponent
cc.growX()
}
addComponent(titleComponent, cc)
}
override fun titledRow(@NlsContexts.Separator title: String, init: Row.() -> Unit): Row {
return createBlockRow(title, true, init)
}
override fun blockRow(init: Row.() -> Unit): Row {
return createBlockRow(null, false, init)
}
private fun createBlockRow(@NlsContexts.Separator title: String?, isSeparated: Boolean, init: Row.() -> Unit): Row {
val parentRow = createChildRow(indent = indent, title = title, isSeparated = isSeparated, incrementsIndent = isSeparated)
parentRow.init()
val result = parentRow.createChildRow()
result.placeholder()
result.largeGapAfter()
return result
}
override fun hideableRow(title: String, incrementsIndent: Boolean, init: Row.() -> Unit): Row {
val titledSeparator = HideableTitledSeparator(title)
val separatorRow = createChildRow()
separatorRow.addTitleComponent(titledSeparator, isEmpty = false)
builder.hideableRowNestingLevel++
try {
val panelRow = createChildRow(indent, incrementsIndent = incrementsIndent)
panelRow.init()
titledSeparator.row = panelRow
titledSeparator.collapse()
return panelRow
}
finally {
builder.hideableRowNestingLevel--
}
}
override fun nestedPanel(title: String?, init: LayoutBuilder.() -> Unit): CellBuilder<DialogPanel> {
val nestedBuilder = createLayoutBuilder()
nestedBuilder.init()
val panel = DialogPanel(title, layout = null)
nestedBuilder.builder.build(panel, arrayOf())
builder.validateCallbacks.addAll(nestedBuilder.builder.validateCallbacks)
builder.componentValidateCallbacks.putAll(nestedBuilder.builder.componentValidateCallbacks)
mergeCallbacks(builder.customValidationRequestors, nestedBuilder.builder.customValidationRequestors)
mergeCallbacks(builder.applyCallbacks, nestedBuilder.builder.applyCallbacks)
mergeCallbacks(builder.resetCallbacks, nestedBuilder.builder.resetCallbacks)
mergeCallbacks(builder.isModifiedCallbacks, nestedBuilder.builder.isModifiedCallbacks)
lateinit var panelBuilder: CellBuilder<DialogPanel>
row {
panelBuilder = panel(CCFlags.growX)
}
return panelBuilder
}
private fun <K, V> mergeCallbacks(map: MutableMap<K, MutableList<V>>, nestedMap: Map<K, List<V>>) {
for ((requestor, callbacks) in nestedMap) {
map.getOrPut(requestor) { mutableListOf() }.addAll(callbacks)
}
}
private fun getOrCreateSubRowsList(): MutableList<MigLayoutRow> {
var subRows = subRows
if (subRows == null) {
// subRows in most cases > 1
subRows = ArrayList()
this.subRows = subRows
}
return subRows
}
// cell mode not tested with "gear" button, wait first user request
override fun setCellMode(value: Boolean, isVerticalFlow: Boolean, fullWidth: Boolean) {
if (value) {
assert(componentIndexWhenCellModeWasEnabled == -1)
componentIndexWhenCellModeWasEnabled = components.size
}
else {
val firstComponentIndex = componentIndexWhenCellModeWasEnabled
componentIndexWhenCellModeWasEnabled = -1
val componentCount = components.size - firstComponentIndex
if (componentCount == 0) return
val component = components.get(firstComponentIndex)
val cc = component.constraints
// do not add split if cell empty or contains the only component
if (componentCount > 1) {
cc.split(componentCount)
}
if (fullWidth) {
cc.spanX(LayoutUtil.INF)
}
if (isVerticalFlow) {
cc.flowY()
// because when vertical buttons placed near scroll pane, it wil be centered by baseline (and baseline not applicable for grow elements, so, will be centered)
cc.alignY("top")
}
}
}
override fun <T : JComponent> component(component: T): CellBuilder<T> {
addComponent(component)
return CellBuilderImpl(builder, this, component)
}
override fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> {
addComponent(viewComponent)
return CellBuilderImpl(builder, this, component, viewComponent)
}
internal fun addComponent(component: JComponent, cc: CC = CC()) {
components.add(component)
builder.componentConstraints.put(component, cc)
if (!visible) {
component.isVisible = false
}
if (!enabled) {
component.isEnabled = false
}
if (!shareCellWithPreviousComponentIfNeeded(component, cc)) {
// increase column index if cell mode not enabled or it is a first component of cell
if (componentIndexWhenCellModeWasEnabled == -1 || componentIndexWhenCellModeWasEnabled == (components.size - 1)) {
columnIndex++
}
}
if (labeled && components.size == 2 && component.border is LineBorder) {
builder.componentConstraints.get(components.first())?.vertical?.gapBefore = builder.defaultComponentConstraintCreator.vertical1pxGap
}
if (component is JRadioButton) {
builder.topButtonGroup?.add(component)
}
builder.defaultComponentConstraintCreator.addGrowIfNeeded(cc, component, spacing)
if (!noGrid && indent > 0 && components.size == 1) {
cc.horizontal.gapBefore = gapToBoundSize(indent, true)
}
if (builder.hideableRowNestingLevel > 0) {
cc.hideMode = 3
}
// if this row is not labeled and:
// a. previous row is labeled and first component is a "Remember" checkbox, skip one column (since this row doesn't have a label)
// b. some previous row is labeled and first component is a checkbox, span (since this checkbox should span across label and content cells)
if (!labeled && components.size == 1 && component is JCheckBox) {
val siblings = parent!!.subRows
if (siblings != null && siblings.size > 1) {
if (siblings.get(siblings.size - 2).labeled && component.text == UIBundle.message("auth.remember.cb")) {
cc.skip(1)
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
}
else if (siblings.any { it.labeled }) {
cc.spanX(2)
}
}
}
// MigLayout doesn't check baseline if component has grow
if (labeled && component is JScrollPane && component.viewport.view is JTextArea) {
val labelCC = components.get(0).constraints
labelCC.alignY("top")
val labelTop = component.border?.getBorderInsets(component)?.top ?: 0
if (labelTop != 0) {
labelCC.vertical.gapBefore = gapToBoundSize(labelTop, false)
}
}
}
private val JComponent.constraints: CC
get() = builder.componentConstraints.getOrPut(this) { CC() }
fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean) {
addCommentRow(comment, maxLineLength, forComponent, null)
}
// not using @JvmOverloads to maintain binary compatibility
fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean, anchorComponent: JComponent?) {
val commentComponent = ComponentPanelBuilder.createCommentComponent(comment, true, maxLineLength, true)
addCommentRow(commentComponent, forComponent, anchorComponent)
}
// not using @JvmOverloads to maintain binary compatibility
fun addCommentRow(component: JComponent, forComponent: Boolean) {
addCommentRow(component, forComponent, null)
}
fun addCommentRow(component: JComponent, forComponent: Boolean, anchorComponent: JComponent?) {
gapAfter = "${spacing.commentVerticalTopGap}px!"
val isParentRowLabeled = labeled
createCommentRow(this, component, indent, isParentRowLabeled, forComponent, columnIndex, anchorComponent)
}
private fun shareCellWithPreviousComponentIfNeeded(component: JComponent, componentCC: CC): Boolean {
if (components.size > 1 && component is JLabel && component.icon === AllIcons.General.GearPlain) {
componentCC.horizontal.gapBefore = builder.defaultComponentConstraintCreator.horizontalUnitSizeGap
if (lastComponentConstraintsWithSplit == null) {
val prevComponent = components.get(components.size - 2)
val prevCC = prevComponent.constraints
prevCC.split++
lastComponentConstraintsWithSplit = prevCC
}
else {
lastComponentConstraintsWithSplit!!.split++
}
return true
}
else {
lastComponentConstraintsWithSplit = null
return false
}
}
override fun alignRight() {
if (rightIndex != Int.MAX_VALUE) {
throw IllegalStateException("right allowed only once")
}
rightIndex = components.size
}
override fun largeGapAfter() {
gapAfter = "${spacing.largeVerticalGap}px!"
}
override fun createRow(label: String?): Row {
return createChildRow(label = label?.let { Label(it) })
}
override fun createNoteOrCommentRow(component: JComponent): Row {
val cc = CC()
cc.vertical.gapBefore = gapToBoundSize(if (subRows == null) spacing.verticalGap else spacing.largeVerticalGap, false)
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap, false)
val row = createChildRow(label = null, noGrid = true)
row.addComponent(component, cc)
return row
}
override fun radioButton(text: String, comment: String?): CellBuilder<JBRadioButton> {
val result = super.radioButton(text, comment)
attachSubRowsEnabled(result.component)
return result
}
override fun radioButton(text: String, prop: KMutableProperty0<Boolean>, comment: String?): CellBuilder<JBRadioButton> {
return super.radioButton(text, prop, comment).also { attachSubRowsEnabled(it.component) }
}
override fun onGlobalApply(callback: () -> Unit): Row {
builder.applyCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
override fun onGlobalReset(callback: () -> Unit): Row {
builder.resetCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
override fun onGlobalIsModified(callback: () -> Boolean): Row {
builder.isModifiedCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
private val labeledComponents = listOf(JTextComponent::class, JComboBox::class, JSpinner::class, JSlider::class)
/**
* Assigns next to label REASONABLE component with the label
*/
override fun row(label: JLabel?, separated: Boolean, init: Row.() -> Unit): Row {
val result = super.row(label, separated, init)
if (label != null && result is MigLayoutRow && result.components.size > 1) {
val component = result.components[1]
if (labeledComponents.any { clazz -> clazz.isInstance(component) }) {
label.labelFor = component
}
}
return result
}
}
private class CellBuilderImpl<T : JComponent>(
private val builder: MigLayoutBuilder,
private val row: MigLayoutRow,
override val component: T,
private val viewComponent: JComponent = component
) : CellBuilder<T>, CheckboxCellBuilder, ScrollPaneCellBuilder {
private var applyIfEnabled = false
private var property: GraphProperty<*>? = null
override fun withGraphProperty(property: GraphProperty<*>): CellBuilder<T> {
this.property = property
return this
}
override fun comment(text: String, maxLineLength: Int, forComponent: Boolean): CellBuilder<T> {
row.addCommentRow(text, maxLineLength, forComponent, viewComponent)
return this
}
override fun commentComponent(component: JComponent, forComponent: Boolean): CellBuilder<T> {
row.addCommentRow(component, forComponent, viewComponent)
return this
}
override fun focused(): CellBuilder<T> {
builder.preferredFocusedComponent = viewComponent
return this
}
override fun withValidationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> {
builder.validateCallbacks.add { callback(ValidationInfoBuilder(component.origin), component) }
return this
}
override fun withValidationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> {
builder.componentValidateCallbacks[component.origin] = { callback(ValidationInfoBuilder(component.origin), component) }
property?.let { builder.customValidationRequestors.getOrPut(component.origin, { SmartList() }).add(it::afterPropagation) }
return this
}
override fun onApply(callback: () -> Unit): CellBuilder<T> {
builder.applyCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun onReset(callback: () -> Unit): CellBuilder<T> {
builder.resetCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun onIsModified(callback: () -> Boolean): CellBuilder<T> {
builder.isModifiedCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun enabled(isEnabled: Boolean) {
viewComponent.isEnabled = isEnabled
}
override fun enableIf(predicate: ComponentPredicate): CellBuilder<T> {
viewComponent.isEnabled = predicate()
predicate.addListener { viewComponent.isEnabled = it }
return this
}
override fun visible(isVisible: Boolean) {
viewComponent.isVisible = isVisible
}
override fun visibleIf(predicate: ComponentPredicate): CellBuilder<T> {
viewComponent.isVisible = predicate()
predicate.addListener { viewComponent.isVisible = it }
return this
}
override fun applyIfEnabled(): CellBuilder<T> {
applyIfEnabled = true
return this
}
override fun shouldSaveOnApply(): Boolean {
return !(applyIfEnabled && !viewComponent.isEnabled)
}
override fun actsAsLabel() {
builder.updateComponentConstraints(viewComponent) { spanX = 1 }
}
override fun noGrowY() {
builder.updateComponentConstraints(viewComponent) {
growY(0.0f)
pushY(0.0f)
}
}
override fun sizeGroup(name: String): CellBuilderImpl<T> {
builder.updateComponentConstraints(viewComponent) {
sizeGroup(name)
}
return this
}
override fun growPolicy(growPolicy: GrowPolicy): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
builder.defaultComponentConstraintCreator.applyGrowPolicy(this, growPolicy)
}
return this
}
override fun constraints(vararg constraints: CCFlags): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
overrideFlags(this, constraints)
}
return this
}
override fun withLargeLeftGap(): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(builder.spacing.largeHorizontalGap, true)
}
return this
}
override fun withLeftGap(): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(builder.spacing.horizontalGap, true)
}
return this
}
override fun withLeftGap(gapLeft: Int): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(gapLeft, true)
}
return this
}
}
private val JComponent.origin: JComponent
get() {
return when (this) {
is TextFieldWithBrowseButton -> textField
else -> this
}
} | apache-2.0 | eefc0b90b729af2ee98860505d4fa670 | 33.67234 | 166 | 0.684327 | 4.792745 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFilePartClassIndex.kt | 2 | 1092 | // 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.stubindex
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.psi.KtFile
class KotlinFilePartClassIndex private constructor() : StringStubIndexExtension<KtFile>() {
override fun getKey(): StubIndexKey<String, KtFile> = KEY
override fun get(key: String, project: Project, scope: GlobalSearchScope) =
StubIndex.getElements(KEY, key, project, scope, KtFile::class.java)
companion object {
private val KEY = KotlinIndexUtil.createIndexKey(KotlinFilePartClassIndex::class.java)
@JvmField
val INSTANCE: KotlinFilePartClassIndex = KotlinFilePartClassIndex()
@JvmStatic
fun getInstance(): KotlinFilePartClassIndex = INSTANCE
}
} | apache-2.0 | 6f75f3a797a372473f9c0411c7944d43 | 38.035714 | 158 | 0.769231 | 4.55 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt | 1 | 16453 | // 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.j2k
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.psi.impl.source.DummyHolder
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.j2k.ast.Element
import org.jetbrains.kotlin.j2k.usageProcessing.ExternalCodeProcessor
import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessing
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.util.*
interface PostProcessor {
fun insertImport(file: KtFile, fqName: FqName)
val phasesCount: Int
fun doAdditionalProcessing(
target: JKPostProcessingTarget,
converterContext: ConverterContext?,
onPhaseChanged: ((Int, String) -> Unit)?
)
}
sealed class JKPostProcessingTarget
data class JKPieceOfCodePostProcessingTarget(
val file: KtFile,
val rangeMarker: RangeMarker
) : JKPostProcessingTarget()
data class JKMultipleFilesPostProcessingTarget(
val files: List<KtFile>
) : JKPostProcessingTarget()
fun JKPostProcessingTarget.elements() = when (this) {
is JKPieceOfCodePostProcessingTarget -> runReadAction {
val range = rangeMarker.range ?: return@runReadAction emptyList()
file.elementsInRange(range)
}
is JKMultipleFilesPostProcessingTarget -> files
}
fun JKPostProcessingTarget.files() = when (this) {
is JKPieceOfCodePostProcessingTarget -> listOf(file)
is JKMultipleFilesPostProcessingTarget -> files
}
enum class ParseContext {
TOP_LEVEL,
CODE_BLOCK
}
interface ExternalCodeProcessing {
fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit
}
data class ElementResult(val text: String, val importsToAdd: Set<FqName>, val parseContext: ParseContext)
data class Result(
val results: List<ElementResult?>,
val externalCodeProcessing: ExternalCodeProcessing?,
val converterContext: ConverterContext?
)
data class FilesResult(val results: List<String>, val externalCodeProcessing: ExternalCodeProcessing?)
interface ConverterContext
abstract class JavaToKotlinConverter {
protected abstract fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result
abstract fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator = EmptyProgressIndicator()
): FilesResult
abstract fun elementsToKotlin(inputElements: List<PsiElement>): Result
}
class OldJavaToKotlinConverter(
private val project: Project,
private val settings: ConverterSettings,
private val services: JavaToKotlinConverterServices
) : JavaToKotlinConverter() {
companion object {
private val LOG = Logger.getInstance(JavaToKotlinConverter::class.java)
}
override fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator
): FilesResult {
val withProgressProcessor = OldWithProgressProcessor(progress, files)
val (results, externalCodeProcessing) = ApplicationManager.getApplication().runReadAction(Computable {
elementsToKotlin(files, withProgressProcessor)
})
val texts = withProgressProcessor.processItems(0.5, results.withIndex()) { pair ->
val (i, result) = pair
try {
val kotlinFile = ApplicationManager.getApplication().runReadAction(Computable {
KtPsiFactory(project).createAnalyzableFile("dummy.kt", result!!.text, files[i])
})
result!!.importsToAdd.forEach { postProcessor.insertImport(kotlinFile, it) }
AfterConversionPass(project, postProcessor).run(kotlinFile, converterContext = null, range = null, onPhaseChanged = null)
kotlinFile.text
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) {
LOG.error(t)
result!!.text
}
}
return FilesResult(texts, externalCodeProcessing)
}
override fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result {
try {
val usageProcessings = LinkedHashMap<PsiElement, MutableCollection<UsageProcessing>>()
val usageProcessingCollector: (UsageProcessing) -> Unit = {
usageProcessings.getOrPut(it.targetElement) { ArrayList() }.add(it)
}
fun inConversionScope(element: PsiElement) = inputElements.any { it.isAncestor(element, strict = false) }
val intermediateResults = processor.processItems(0.25, inputElements) { inputElement ->
Converter.create(inputElement, settings, services, ::inConversionScope, usageProcessingCollector).convert()
}.toMutableList()
val results = processor.processItems(0.25, intermediateResults.withIndex()) { pair ->
val (i, result) = pair
intermediateResults[i] = null // to not hold unused objects in the heap
result?.let {
val (text, importsToAdd) = it.codeGenerator(usageProcessings)
ElementResult(text, importsToAdd, it.parseContext)
}
}
val externalCodeProcessing = buildExternalCodeProcessing(usageProcessings, ::inConversionScope)
return Result(results, externalCodeProcessing, null)
} catch (e: ElementCreationStackTraceRequiredException) {
// if we got this exception then we need to turn element creation stack traces on to get better diagnostic
Element.saveCreationStacktraces = true
try {
return elementsToKotlin(inputElements)
} finally {
Element.saveCreationStacktraces = false
}
}
}
override fun elementsToKotlin(inputElements: List<PsiElement>): Result {
return elementsToKotlin(inputElements, OldWithProgressProcessor.DEFAULT)
}
private data class ReferenceInfo(
val reference: PsiReference,
val target: PsiElement,
val file: PsiFile,
val processings: Collection<UsageProcessing>
) {
val depth: Int by lazy(LazyThreadSafetyMode.NONE) { target.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
val offset: Int by lazy(LazyThreadSafetyMode.NONE) { reference.element.textRange.startOffset }
}
private fun buildExternalCodeProcessing(
usageProcessings: Map<PsiElement, Collection<UsageProcessing>>,
inConversionScope: (PsiElement) -> Boolean
): ExternalCodeProcessing? {
if (usageProcessings.isEmpty()) return null
val map: Map<PsiElement, Collection<UsageProcessing>> = usageProcessings.values
.flatten()
.filter { it.javaCodeProcessors.isNotEmpty() || it.kotlinCodeProcessors.isNotEmpty() }
.groupBy { it.targetElement }
if (map.isEmpty()) return null
return object : ExternalCodeProcessing {
override fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit {
if (progress == null) error("Progress should not be null for old J2K")
val refs = ArrayList<ReferenceInfo>()
progress.text = KotlinJ2KBundle.message("text.searching.usages.to.update")
for ((i, entry) in map.entries.withIndex()) {
val psiElement = entry.key
val processings = entry.value
progress.text2 = (psiElement as? PsiNamedElement)?.name ?: ""
progress.checkCanceled()
ProgressManager.getInstance().runProcess(
{
val searchJava = processings.any { it.javaCodeProcessors.isNotEmpty() }
val searchKotlin = processings.any { it.kotlinCodeProcessors.isNotEmpty() }
services.referenceSearcher.findUsagesForExternalCodeProcessing(psiElement, searchJava, searchKotlin)
.filterNot { inConversionScope(it.element) }
.mapTo(refs) { ReferenceInfo(it, psiElement, it.element.containingFile, processings) }
},
ProgressPortionReporter(progress, i / map.size.toDouble(), 1.0 / map.size)
)
}
return { processUsages(refs) }
}
}
}
private fun processUsages(refs: Collection<ReferenceInfo>) {
for (fileRefs in refs.groupBy { it.file }.values) { // group by file for faster sorting
ReferenceLoop@
for ((reference, _, _, processings) in fileRefs.sortedWith(ReferenceComparator)) {
val processors = when (reference.element.language) {
JavaLanguage.INSTANCE -> processings.flatMap { it.javaCodeProcessors }
KotlinLanguage.INSTANCE -> processings.flatMap { it.kotlinCodeProcessors }
else -> continue@ReferenceLoop
}
checkReferenceValid(reference, null)
var references = listOf(reference)
for (processor in processors) {
references = references.flatMap { processor.processUsage(it)?.toList() ?: listOf(it) }
references.forEach { checkReferenceValid(it, processor) }
}
}
}
}
private fun checkReferenceValid(reference: PsiReference, afterProcessor: ExternalCodeProcessor?) {
val element = reference.element
assert(element.isValid && element.containingFile !is DummyHolder) {
"Reference $reference got invalidated" + (if (afterProcessor != null) " after processing with $afterProcessor" else "")
}
}
private object ReferenceComparator : Comparator<ReferenceInfo> {
override fun compare(info1: ReferenceInfo, info2: ReferenceInfo): Int {
val depth1 = info1.depth
val depth2 = info2.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left so that right-side of assignments is not invalidated by processing of the left one
return -info1.offset.compareTo(info2.offset)
}
}
}
interface WithProgressProcessor {
fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem>
fun updateState(fileIndex: Int?, phase: Int, description: String)
fun updateState(phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String)
fun <T> process(action: () -> T): T
}
class OldWithProgressProcessor(private val progress: ProgressIndicator?, private val files: List<PsiJavaFile>?) : WithProgressProcessor {
companion object {
val DEFAULT = OldWithProgressProcessor(null, null)
}
private val progressText
@Suppress("DialogTitleCapitalization")
@NlsContexts.ProgressText
get() = KotlinJ2KBundle.message("text.converting.java.to.kotlin")
private val fileCount = files?.size ?: 0
private val fileCountText
@Nls
get() = KotlinJ2KBundle.message("text.files.count.0", fileCount, if (fileCount == 1) 1 else 2)
private var fraction = 0.0
private var pass = 1
override fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem> {
val outputItems = ArrayList<TOutputItem>()
// we use special process with EmptyProgressIndicator to avoid changing text in our progress by inheritors search inside etc
ProgressManager.getInstance().runProcess(
{
progress?.text = "$progressText ($fileCountText) - ${KotlinJ2KBundle.message("text.pass.of.3", pass)}"
progress?.isIndeterminate = false
for ((i, item) in inputItems.withIndex()) {
progress?.checkCanceled()
progress?.fraction = fraction + fractionPortion * i / fileCount
progress?.text2 = files!![i].virtualFile.presentableUrl
outputItems.add(processItem(item))
}
pass++
fraction += fractionPortion
},
EmptyProgressIndicator()
)
return outputItems
}
override fun <T> process(action: () -> T): T {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(fileIndex: Int?, phase: Int, description: String) {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(
phase: Int,
subPhase: Int,
subPhaseCount: Int,
fileIndex: Int?,
description: String
) {
error("Should not be called for old J2K")
}
}
class ProgressPortionReporter(
indicator: ProgressIndicator,
private val start: Double,
private val portion: Double
) : DelegatingProgressIndicator(indicator) {
init {
fraction = 0.0
}
override fun start() {
fraction = 0.0
}
override fun stop() {
fraction = portion
}
override fun setFraction(fraction: Double) {
super.setFraction(start + (fraction * portion))
}
override fun getFraction(): Double {
return (super.getFraction() - start) / portion
}
override fun setText(text: String?) {
}
override fun setText2(text: String?) {
}
}
// Copied from com.intellij.ide.util.DelegatingProgressIndicator
open class DelegatingProgressIndicator(indicator: ProgressIndicator) : WrappedProgressIndicator, StandardProgressIndicator {
protected val delegate: ProgressIndicator = indicator
override fun start() = delegate.start()
override fun stop() = delegate.stop()
override fun isRunning() = delegate.isRunning
override fun cancel() = delegate.cancel()
override fun isCanceled() = delegate.isCanceled
override fun setText(text: String?) {
delegate.text = text
}
override fun getText() = delegate.text
override fun setText2(text: String?) {
delegate.text2 = text
}
override fun getText2() = delegate.text2
override fun getFraction() = delegate.fraction
override fun setFraction(fraction: Double) {
delegate.fraction = fraction
}
override fun pushState() = delegate.pushState()
override fun popState() = delegate.popState()
override fun isModal() = delegate.isModal
override fun getModalityState() = delegate.modalityState
override fun setModalityProgress(modalityProgress: ProgressIndicator?) {
delegate.setModalityProgress(modalityProgress)
}
override fun isIndeterminate() = delegate.isIndeterminate
override fun setIndeterminate(indeterminate: Boolean) {
delegate.isIndeterminate = indeterminate
}
override fun checkCanceled() = delegate.checkCanceled()
override fun getOriginalProgressIndicator() = delegate
override fun isPopupWasShown() = delegate.isPopupWasShown
override fun isShowing() = delegate.isShowing
} | apache-2.0 | a8836f7a313cde07b01b59da3b06ae70 | 36.56621 | 158 | 0.664985 | 5.147997 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/sdk/poetry/PyPoetryPackageManager.kt | 1 | 6111 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.poetry
import com.intellij.execution.ExecutionException
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.packaging.*
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.associatedModuleDir
/**
* @author vlan
*/
/**
* This source code is edited by @koxudaxi Koudai Aono <[email protected]>
*/
class PyPoetryPackageManager(val sdk: Sdk) : PyPackageManager() {
private val installedLines = listOf("Already installed", "Skipping", "Updating")
@Volatile
private var packages: List<PyPackage>? = null
private var requirements: List<PyRequirement>? = null
private var outdatedPackages: Map<String, PoetryOutdatedVersion> = emptyMap()
init {
PyPackageUtil.runOnChangeUnderInterpreterPaths(sdk, this, Runnable {
PythonSdkType.getInstance().setupSdkPaths(sdk)
})
}
override fun installManagement() {}
override fun hasManagement() = true
override fun install(requirementString: String) {
install(parseRequirements(requirementString), emptyList())
}
override fun install(requirements: List<PyRequirement>?, extraArgs: List<String>) {
val args = if (requirements == null || requirements.isEmpty()) {
listOfNotNull(listOf("install"),
extraArgs)
.flatten()
}
else {
listOfNotNull(listOf("add"),
requirements.map { it.name },
extraArgs)
.flatten()
}
try {
runPoetry(sdk, *args.toTypedArray())
}
finally {
sdk.associatedModuleDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun uninstall(packages: List<PyPackage>) {
val args = listOf("remove") +
packages.map { it.name }
try {
runPoetry(sdk, *args.toTypedArray())
}
finally {
sdk.associatedModuleDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun refresh() {
with(ApplicationManager.getApplication()) {
invokeLater {
runWriteAction {
val files = sdk.rootProvider.getFiles(OrderRootType.CLASSES)
VfsUtil.markDirtyAndRefresh(true, true, true, *files)
}
PythonSdkType.getInstance().setupSdkPaths(sdk)
}
}
}
override fun createVirtualEnv(destinationDir: String, useGlobalSite: Boolean): String {
throw ExecutionException("Creating virtual environments based on Poetry environments is not supported")
}
override fun getPackages() = packages
fun getOutdatedPackages() = outdatedPackages
override fun refreshAndGetPackages(alwaysRefresh: Boolean): List<PyPackage> {
if (alwaysRefresh || packages == null) {
packages = null
val outputInstallDryRun = try {
runPoetry(sdk, "install", "--dry-run", "--no-root")
}
catch (e: ExecutionException) {
packages = emptyList()
return packages ?: emptyList()
}
val allPackage = parsePoetryInstallDryRun(outputInstallDryRun)
packages = allPackage.first
requirements = allPackage.second
val outputOutdatedPackages = try {
runPoetry(sdk, "show", "--outdated")
}
catch (e: ExecutionException) {
outdatedPackages = emptyMap()
}
if (outputOutdatedPackages is String) {
outdatedPackages = parsePoetryShowOutdated(outputOutdatedPackages)
}
ApplicationManager.getApplication().messageBus.syncPublisher(PACKAGE_MANAGER_TOPIC).packagesRefreshed(sdk)
}
return packages ?: emptyList()
}
override fun getRequirements(module: Module): List<PyRequirement>? {
return requirements
}
override fun parseRequirements(text: String): List<PyRequirement> =
PyRequirementParser.fromText(text)
override fun parseRequirement(line: String): PyRequirement? =
PyRequirementParser.fromLine(line)
override fun parseRequirements(file: VirtualFile): List<PyRequirement> =
PyRequirementParser.fromFile(file)
override fun getDependents(pkg: PyPackage): Set<PyPackage> {
// TODO: Parse the dependency information from `pipenv graph`
return emptySet()
}
private fun getVersion(version: String): String {
return if (Regex("^[0-9]").containsMatchIn(version)) "==$version" else version
}
/**
* Parses the output of `poetry install --dry-run ` into a list of packages.
*/
private fun parsePoetryInstallDryRun(input: String): Pair<List<PyPackage>, List<PyRequirement>> {
fun getNameAndVersion(line: String): Triple<String, String, String> {
return line.split(" ").let {
val installedVersion = it[5].replace(Regex("[():]"), "")
val requiredVersion = when {
it.size > 7 && it[6] == "->" -> it[7].replace(Regex("[():]"), "")
else -> installedVersion
}
Triple(it[4], installedVersion, requiredVersion)
}
}
val pyPackages = mutableListOf<PyPackage>()
val pyRequirements = mutableListOf<PyRequirement>()
input
.lineSequence()
.filter { listOf(")", "Already installed").any { lastWords -> it.endsWith(lastWords) } }
.forEach { line ->
getNameAndVersion(line).also {
if (installedLines.any { installedLine -> line.contains(installedLine) }) {
pyPackages.add(PyPackage(it.first, it.second, null, emptyList()))
this.parseRequirement(it.first + getVersion(it.third))?.let { pyRequirement -> pyRequirements.add(pyRequirement) }
}
else if (line.contains("Installing")) {
this.parseRequirement(it.first + getVersion(it.third))?.let { pyRequirement -> pyRequirements.add(pyRequirement) }
}
}
}
return Pair(pyPackages.distinct().toList(), pyRequirements.distinct().toList())
}
} | apache-2.0 | 4633f4765e91f4b69f4ff9236d85f9c3 | 32.217391 | 140 | 0.680249 | 4.476923 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/joints/JointsDemo.kt | 1 | 23838 | package de.fabmax.kool.demo.physics.joints
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.demo.*
import de.fabmax.kool.demo.menu.DemoMenu
import de.fabmax.kool.math.*
import de.fabmax.kool.math.spatial.BoundingBox
import de.fabmax.kool.modules.ui2.*
import de.fabmax.kool.physics.*
import de.fabmax.kool.physics.geometry.BoxGeometry
import de.fabmax.kool.physics.geometry.ConvexMeshGeometry
import de.fabmax.kool.physics.geometry.CylinderGeometry
import de.fabmax.kool.physics.geometry.PlaneGeometry
import de.fabmax.kool.physics.joints.RevoluteJoint
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.RenderPass
import de.fabmax.kool.pipeline.Texture2d
import de.fabmax.kool.pipeline.ao.AoPipeline
import de.fabmax.kool.pipeline.ibl.EnvironmentHelper
import de.fabmax.kool.pipeline.ibl.EnvironmentMaps
import de.fabmax.kool.pipeline.shading.pbrShader
import de.fabmax.kool.pipeline.shading.unlitShader
import de.fabmax.kool.scene.*
import de.fabmax.kool.toString
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.ColorGradient
import de.fabmax.kool.util.MdColor
import de.fabmax.kool.util.SimpleShadowMap
import kotlin.math.abs
import kotlin.math.acos
import kotlin.math.max
import kotlin.math.roundToInt
class JointsDemo : DemoScene("Physics - Joints") {
private var physicsWorld: PhysicsWorld? = null
private val physicsStepper = ConstantPhysicsStepper(isAsync = false)
private val motorStrength = mutableStateOf(50f)
private val motorSpeed = mutableStateOf(1.5f)
private val motorDirection = mutableStateOf(1f)
private val numLinks = mutableStateOf(40)
private val drawNiceMeshes = mutableStateOf(true).onChange { niceMeshes.isVisible = it }
private val drawPhysMeshes = mutableStateOf(false).onChange { physMeshes.isVisible = it }
private val drawJointInfos = mutableStateOf(false).onChange { constraintInfo.isVisible = it }
private val physicsTimeTxt = mutableStateOf("0.00 ms")
private val numBodiesTxt = mutableStateOf("0")
private val numJointsTxt = mutableStateOf("0")
private val timeFactorTxt = mutableStateOf("1.00 x")
private var motorGearConstraint: RevoluteJoint? = null
private val joints = mutableListOf<RevoluteJoint>()
private val physMeshes = BodyMeshes(false).apply { isVisible = false }
private val niceMeshes = BodyMeshes(true).apply { isVisible = true }
private lateinit var constraintInfo: ConstraintsInfoMesh
private var resetPhysics = false
private val shadows = mutableListOf<SimpleShadowMap>()
private lateinit var aoPipeline: AoPipeline
private lateinit var ibl: EnvironmentMaps
private lateinit var groundAlbedo: Texture2d
private lateinit var groundNormal: Texture2d
private val staticCollGroup = 1
private val staticSimFilterData = FilterData {
setCollisionGroup(staticCollGroup)
clearCollidesWith(staticCollGroup)
}
private val material = Material(0.5f)
override suspend fun AssetManager.loadResources(ctx: KoolContext) {
ibl = EnvironmentHelper.hdriEnvironment(mainScene, "${DemoLoader.hdriPath}/colorful_studio_1k.rgbe.png", this)
Physics.awaitLoaded()
val world = PhysicsWorld()
world.simStepper = physicsStepper
physicsWorld = world
resetPhysics = true
constraintInfo = ConstraintsInfoMesh().apply { isVisible = false }
mainScene += constraintInfo
groundAlbedo = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine.png")
groundNormal = loadAndPrepareTexture("${DemoLoader.materialPath}/tile_flat/tiles_flat_fine_normal.png")
world.registerHandlers(mainScene)
}
override fun Scene.setupMainScene(ctx: KoolContext) {
defaultCamTransform().apply {
setMouseRotation(-20f, -20f)
setZoom(50.0, max = 200.0)
}
(camera as PerspectiveCamera).apply {
clipNear = 1f
clipFar = 1000f
}
// light setup
lightSetup()
// group containing physics bodies
+physMeshes
+niceMeshes
// ground plane
mainScene += textureMesh(isNormalMapped = true) {
isCastingShadow = false
generate {
rotate(-90f, Vec3f.X_AXIS)
rect {
size.set(250f, 250f)
origin.set(-size.x * 0.5f, -size.y * 0.5f, -20f)
generateTexCoords(15f)
}
}
shader = pbrShader {
useAlbedoMap(groundAlbedo)
useNormalMap(groundNormal)
useScreenSpaceAmbientOcclusion(aoPipeline.aoMap)
useImageBasedLighting(ibl)
shadowMaps += shadows
}
}
mainScene += Skybox.cube(ibl.reflectionMap, 1f)
onUpdate += {
if (resetPhysics) {
resetPhysics = false
makePhysicsScene()
}
physicsTimeTxt.set("${physicsStepper.perfCpuTime.toString(2)} ms")
timeFactorTxt.set("${physicsStepper.perfTimeFactor.toString(2)} x")
numBodiesTxt.set("${physicsWorld?.actors?.size ?: 0}")
numJointsTxt.set("${joints.size}")
}
}
private fun Scene.lightSetup() {
aoPipeline = AoPipeline.createForward(this)
lighting.apply {
lights.clear()
val l1 = Vec3f(80f, 120f, 100f)
val l2 = Vec3f(-30f, 100f, 100f)
lights += Light().apply {
setSpot(l1, MutableVec3f(l1).scale(-1f).norm(), 45f)
setColor(Color.WHITE.mix(MdColor.AMBER, 0.1f), 50000f)
}
lights += Light().apply {
setSpot(l2, MutableVec3f(l2).scale(-1f).norm(), 45f)
setColor(Color.WHITE.mix(MdColor.LIGHT_BLUE, 0.1f), 25000f)
}
}
shadows.add(SimpleShadowMap(this, 0).apply {
clipNear = 100f
clipFar = 500f
shaderDepthOffset = -0.2f
shadowBounds = BoundingBox(Vec3f(-75f, -20f, -75f), Vec3f(75f, 20f, 75f))
})
shadows.add(SimpleShadowMap(this, 1).apply {
clipNear = 100f
clipFar = 500f
shaderDepthOffset = -0.2f
shadowBounds = BoundingBox(Vec3f(-75f, -20f, -75f), Vec3f(75f, 20f, 75f))
})
}
private fun makePhysicsScene() {
physMeshes.clearBodies()
niceMeshes.clearBodies()
joints.forEach { it.release() }
joints.clear()
physicsWorld?.apply {
clear()
val groundPlane = RigidStatic()
groundPlane.simulationFilterData = staticSimFilterData
groundPlane.attachShape(Shape(PlaneGeometry(), material))
groundPlane.position = Vec3f(0f, -20f, 0f)
groundPlane.setRotation(Mat3f().rotate(90f, Vec3f.Z_AXIS))
addActor(groundPlane)
}
val frame = Mat4f().rotate(90f, Vec3f.Z_AXIS)
makeGearChain(numLinks.value, frame)
updateMotor()
}
override fun dispose(ctx: KoolContext) {
super.dispose(ctx)
joints.forEach { it.release() }
physicsWorld?.apply {
clear()
release()
}
material.release()
groundAlbedo.dispose()
groundNormal.dispose()
}
private fun drawNiceMeshes() {
drawNiceMeshes.set(true)
drawPhysMeshes.set(false)
}
private fun drawPhysMeshes() {
drawNiceMeshes.set(false)
drawPhysMeshes.set(true)
}
override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface {
MenuSlider2("Number of links", numLinks.use() / 2f, 10f, 50f, { "${it.roundToInt() * 2}" }) {
val links = it.roundToInt() * 2
if (links != numLinks.value) {
numLinks.set(links)
resetPhysics = true
}
}
MenuSlider2("Motor strength", motorStrength.use(), 0f, 100f, { "${it.toInt()}" }) {
motorStrength.set(it)
updateMotor()
}
MenuSlider2("Motor speed", motorSpeed.use(), 0f, 10f, { it.toString(1) }) {
motorSpeed.set(it)
updateMotor()
}
MenuRow {
Text("Reverse motor") {
labelStyle(Grow.Std)
modifier.onClick {
motorDirection.set(-motorDirection.value)
updateMotor()
}
}
Switch(motorDirection.use() < 0f) {
modifier
.alignY(AlignmentY.Center)
.onToggle {
motorDirection.set(-motorDirection.value)
updateMotor()
}
}
}
Text("Visualization") { sectionTitleStyle() }
MenuRow {
RadioButton(drawNiceMeshes.use()) {
modifier
.alignY(AlignmentY.Center)
.margin(end = sizes.gap)
.onToggle {
if (it) {
drawNiceMeshes()
}
}
}
Text("Draw nice meshes") {
labelStyle(Grow.Std)
modifier.onClick { drawNiceMeshes() }
}
}
MenuRow {
RadioButton(drawPhysMeshes.use()) {
modifier
.alignY(AlignmentY.Center)
.margin(end = sizes.gap)
.onToggle {
if (it) {
drawPhysMeshes()
}
}
}
Text("Draw physics meshes") {
labelStyle(Grow.Std)
modifier.onClick { drawPhysMeshes() }
}
}
MenuRow { LabeledSwitch("Draw joint infos", drawJointInfos) }
Text("Statistics") { sectionTitleStyle() }
MenuRow {
Text("Number of joints") { labelStyle(Grow.Std) }
Text(numJointsTxt.use()) { labelStyle() }
}
MenuRow {
Text("Number of bodies") { labelStyle(Grow.Std) }
Text(numBodiesTxt.use()) { labelStyle() }
}
MenuRow {
Text("Physics step CPU time") { labelStyle(Grow.Std) }
Text(physicsTimeTxt.use()) { labelStyle() }
}
MenuRow {
Text("Time factor") { labelStyle(Grow.Std) }
Text(timeFactorTxt.use()) { labelStyle() }
}
}
private fun updateMotor() {
motorGearConstraint?.apply {
enableAngularMotor(motorSpeed.value * -motorDirection.value, motorStrength.value)
}
}
private fun computeAxleDist(): Float {
val linkLen = 4f
return (numLinks.value - 12) / 2 * linkLen
}
private fun makeGearChain(numLinks: Int, frame: Mat4f) {
val world = physicsWorld ?: return
val linkMass = 1f
val gearMass = 10f
val gearR = 6.95f
val axleDist = computeAxleDist()
val tension = 0.05f
if (numLinks % 2 != 0) {
throw IllegalArgumentException("numLinks must be even")
}
makeGearAndAxle(gearR, Vec3f(0f, axleDist / 2f, 0f), gearMass, true, frame)
makeGearAndAxle(gearR, Vec3f(0f, -axleDist / 2f, 0f), gearMass, false, frame)
makeChain(linkMass, tension, gearR, axleDist, frame, world)
}
private fun makeChain(linkMass: Float, tension: Float, gearR: Float, axleDist: Float, frame: Mat4f, world: PhysicsWorld) {
val t = Mat4f().set(frame).translate(0f, axleDist / 2f + gearR + 0.6f, 0f)
val r = Mat3f()
val nLinks = numLinks.value
val rotLinks = mutableSetOf(1, 2, 3, nLinks - 2, nLinks - 1, nLinks)
for (i in (nLinks / 2 - 2)..(nLinks / 2 + 3)) {
rotLinks += i
}
val firstOuter = makeOuterChainLink(linkMass)
firstOuter.position = t.getOrigin(MutableVec3f())
firstOuter.setRotation(t.getRotation(r))
world.addActor(firstOuter)
var prevInner = makeInnerChainLink(linkMass)
t.translate(1.5f, 0f, 0f)
t.rotate(0f, 0f, -15f)
t.translate(0.5f, 0f, 0f)
prevInner.position = t.getOrigin(MutableVec3f())
prevInner.setRotation(t.getRotation(r))
world.addActor(prevInner)
connectLinksOuterInner(firstOuter, prevInner, tension)
physMeshes.linksO += firstOuter
niceMeshes.linksO += firstOuter
physMeshes.linksI += prevInner
niceMeshes.linksI += prevInner
for (i in 1 until nLinks) {
t.translate(0.5f, 0f, 0f)
if (i in rotLinks) {
t.rotate(0f, 0f, -15f)
}
t.translate(1.5f, 0f, 0f)
val outer = makeOuterChainLink(linkMass * 2)
outer.position = t.getOrigin(MutableVec3f())
outer.setRotation(t.getRotation(r))
world.addActor(outer)
connectLinksInnerOuter(prevInner, outer, tension)
prevInner = makeInnerChainLink(linkMass)
t.translate(1.5f, 0f, 0f)
if ((i + 1) in rotLinks) {
t.rotate(0f, 0f, -15f)
}
t.translate(0.5f, 0f, 0f)
prevInner.position = t.getOrigin(MutableVec3f())
prevInner.setRotation(t.getRotation(r))
world.addActor(prevInner)
connectLinksOuterInner(outer, prevInner, tension)
physMeshes.linksO += outer
niceMeshes.linksO += outer
physMeshes.linksI += prevInner
niceMeshes.linksI += prevInner
}
connectLinksInnerOuter(prevInner, firstOuter, tension)
}
private fun connectLinksOuterInner(outer: RigidDynamic, inner: RigidDynamic, t: Float) {
val hinge = RevoluteJoint(outer, inner,
Vec3f(1.5f - t, 0f, 0f), Vec3f(-0.5f, 0f, 0f),
Vec3f.Z_AXIS, Vec3f.Z_AXIS)
joints += hinge
}
private fun connectLinksInnerOuter(inner: RigidDynamic, outer: RigidDynamic, t: Float) {
val hinge = RevoluteJoint(outer, inner,
Vec3f(-1.5f + t, 0f, 0f), Vec3f(0.5f, 0f, 0f),
Vec3f.Z_AXIS, Vec3f.Z_AXIS)
joints += hinge
}
private fun makeGearAndAxle(gearR: Float, origin: Vec3f, gearMass: Float, isDriven: Boolean, frame: Mat4f) {
val world = physicsWorld ?: return
val axleGeom = CylinderGeometry(7f, 1f)
val axle = RigidStatic()
axle.simulationFilterData = staticSimFilterData
axle.attachShape(Shape(axleGeom, material))
axle.setRotation(frame.getRotation(Mat3f()).rotate(0f, -90f, 0f))
axle.position = frame.transform(MutableVec3f(origin))
world.addActor(axle)
physMeshes.axles += axle
niceMeshes.axles += axle
axleGeom.release()
val gear = makeGear(gearR, gearMass)
gear.setRotation(frame.getRotation(Mat3f()))
gear.position = frame.transform(MutableVec3f(origin))
world.addActor(gear)
physMeshes.gears += gear
niceMeshes.gears += gear
val motor = RevoluteJoint(axle, gear,
Vec3f(0f, 0f, 0f), Vec3f(0f, 0f, 0f),
Vec3f.X_AXIS, Vec3f.Z_AXIS)
joints += motor
if (isDriven) {
motorGearConstraint = motor
}
}
private fun makeGear(gearR: Float, mass: Float): RigidDynamic {
val s = 1f
val toothH = 1f * s
val toothBb = 0.55f * s
val toothBt = 0.4f * s
val toothWb = 1f * s
val toothWt = 0.7f * s
val gearShapes = mutableListOf<Shape>()
val toothPts = listOf(
Vec3f(toothWt, gearR + toothH, -toothBt), Vec3f(toothWt, gearR + toothH, toothBt),
Vec3f(-toothWt, gearR + toothH, -toothBt), Vec3f(-toothWt, gearR + toothH, toothBt),
Vec3f(toothWb, gearR - 0.1f, -toothBb), Vec3f(toothWb, gearR - 0.1f, toothBb),
Vec3f(-toothWb, gearR - 0.1f, -toothBb), Vec3f(-toothWb, gearR - 0.1f, toothBb)
)
val toothGeom = ConvexMeshGeometry(toothPts)
val cylGeom = CylinderGeometry(2.5f, gearR)
gearShapes += Shape(cylGeom, material, Mat4f().rotate(0f, 90f, 0f))
for (i in 0..11) {
gearShapes += Shape(toothGeom, material, Mat4f().rotate(0f, 0f, 30f * i))
}
val gearFilterData = FilterData {
setCollisionGroup(0)
clearCollidesWith(staticCollGroup)
}
val gear = RigidDynamic(mass)
gear.simulationFilterData = gearFilterData
gearShapes.forEach { shape ->
gear.attachShape(shape)
}
toothGeom.release()
cylGeom.release()
return gear
}
private fun makeOuterChainLink(mass: Float): RigidDynamic {
val boxA = BoxGeometry(Vec3f(3.4f, 0.8f, 0.3f))
val boxB = BoxGeometry(Vec3f(3.4f, 0.8f, 0.3f))
val shapes = mutableListOf<Shape>()
shapes += Shape(boxA, material, Mat4f().translate(0f, 0f, 0.75f))
shapes += Shape(boxB, material, Mat4f().translate(0f, 0f, -0.75f))
val link = RigidDynamic(mass)
shapes.forEach { shape ->
link.attachShape(shape)
}
boxA.release()
boxB.release()
return link
}
private fun makeInnerChainLink(mass: Float): RigidDynamic {
val w1 = 0.95f
val h1 = 0.2f
val w2 = 0.7f
val h2 = 0.6f
val d = 0.5f
val points = listOf(
Vec3f(-w1, -h1, -d), Vec3f(-w1, -h1, d),
Vec3f(-w1, h1, -d), Vec3f(-w1, h1, d),
Vec3f( w1, -h1, -d), Vec3f( w1, -h1, d),
Vec3f( w1, h1, -d), Vec3f( w1, h1, d),
Vec3f(-w2, -h2, -d), Vec3f(-w2, -h2, d),
Vec3f(-w2, h2, -d), Vec3f(-w2, h2, d),
Vec3f( w2, -h2, -d), Vec3f( w2, -h2, d),
Vec3f( w2, h2, -d), Vec3f( w2, h2, d),
)
val geom = ConvexMeshGeometry(points)
val link = RigidDynamic(mass)
link.attachShape(Shape(geom, material))
geom.release()
return link
}
private inner class BodyMesh(val color: Color, val onCreate: (Mesh) -> Unit) {
var mesh: Mesh? = null
var factory: (RigidActor) -> Mesh = { proto ->
colorMesh {
isFrustumChecked = false
instances = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT))
generate {
color = [email protected]
proto.shapes.forEach { shape ->
withTransform {
transform.mul(shape.localPose)
shape.geometry.generateMesh(this)
}
}
}
shader = pbrShader {
roughness = 1f
isInstanced = true
shadowMaps += shadows
useImageBasedLighting(ibl)
useScreenSpaceAmbientOcclusion(aoPipeline.aoMap)
}
}
}
fun getOrCreate(protoBody: RigidActor): Mesh {
if (mesh == null) {
mesh = factory(protoBody)
onCreate(mesh!!)
}
return mesh!!
}
fun updateInstances(bodies: List<RigidActor>) {
if (bodies.isNotEmpty()) {
getOrCreate(bodies[0]).instances!!.apply {
clear()
addInstances(bodies.size) { buf ->
for (i in bodies.indices) {
buf.put(bodies[i].transform.matrix)
}
}
}
}
}
}
private inner class BodyMeshes(isNice: Boolean): Group() {
var linkMeshO = BodyMesh(MdColor.BLUE_GREY.toLinear()) { addNode(it) }
var linkMeshI = BodyMesh(MdColor.BLUE_GREY toneLin 350) { addNode(it) }
var gearMesh = BodyMesh(MdColor.BLUE_GREY toneLin 200) { addNode(it) }
var axleMesh = BodyMesh(MdColor.BLUE_GREY toneLin 700) { addNode(it) }
val linksO = mutableListOf<RigidDynamic>()
val linksI = mutableListOf<RigidDynamic>()
val gears = mutableListOf<RigidDynamic>()
val axles = mutableListOf<RigidStatic>()
init {
isFrustumChecked = false
if (isNice) {
linkMeshO.factory = { GearChainMeshGen.makeNiceOuterLinkMesh(ibl, aoPipeline.aoMap, shadows) }
linkMeshI.factory = { GearChainMeshGen.makeNiceInnerLinkMesh(ibl, aoPipeline.aoMap, shadows) }
gearMesh.factory = { GearChainMeshGen.makeNiceGearMesh(ibl, aoPipeline.aoMap, shadows) }
axleMesh.factory = { GearChainMeshGen.makeNiceAxleMesh(ibl, aoPipeline.aoMap, shadows) }
}
onUpdate += {
linkMeshO.updateInstances(linksO)
linkMeshI.updateInstances(linksI)
gearMesh.updateInstances(gears)
axleMesh.updateInstances(axles)
}
}
fun clearBodies() {
linksO.clear()
linksI.clear()
gears.clear()
axles.clear()
}
}
private inner class ConstraintsInfoMesh : LineMesh() {
val gradient = ColorGradient.RED_YELLOW_GREEN.inverted()
// keep temp vectors as members to not re-allocate them all the time
val tmpAx = MutableVec3f()
val tmpP1 = MutableVec3f()
val tmpP2 = MutableVec3f()
val tmpA1 = MutableVec3f()
val tmpA2 = MutableVec3f()
val tmpL1 = MutableVec3f()
val tmpL2 = MutableVec3f()
init {
isCastingShadow = false
shader = unlitShader {
lineWidth = 3f
}
}
override fun update(updateEvent: RenderPass.UpdateEvent) {
if (isVisible) {
clear()
joints.forEach {
renderRevoluteConstraint(it)
}
}
super.update(updateEvent)
}
private fun renderRevoluteConstraint(rc: RevoluteJoint) {
val tA = rc.bodyA.transform
val tB = rc.bodyB.transform
rc.frameA.transform(tmpAx.set(Vec3f.X_AXIS), 0f)
rc.frameA.transform(tmpP1.set(Vec3f.ZERO), 1f)
tA.transform(tmpA1.set(tmpAx), 0f)
tA.transform(tmpP1)
val lenA = rc.bodyA.worldBounds.size * tmpAx * 0.5f + 1f
rc.frameB.transform(tmpAx.set(Vec3f.X_AXIS), 0f)
rc.frameB.transform(tmpP2.set(Vec3f.ZERO), 1f)
tB.transform(tmpA2.set(tmpAx), 0f)
tB.transform(tmpP2)
val lenB = rc.bodyB.worldBounds.size * tmpAx * 0.5f + 1f
val drawLen = max(lenA, lenB)
val diff = tmpP1.distance(tmpP2) + abs(acos(tmpA1 * tmpA2).toDeg()) / 20
val color = gradient.getColor(diff, 0f, 0.5f)
tmpL1.set(tmpA1).scale(drawLen).add(tmpP1)
tmpL2.set(tmpA1).scale(-drawLen).add(tmpP1)
addLine(tmpL1, tmpL2, color)
tmpL1.set(tmpA2).scale(drawLen).add(tmpP2)
tmpL2.set(tmpA2).scale(-drawLen).add(tmpP2)
addLine(tmpL1, tmpL2, color)
tmpL1.set(tmpA1).scale(drawLen).add(tmpP1)
tmpL2.set(tmpA2).scale(drawLen).add(tmpP2)
addLine(tmpL1, tmpL2, color)
tmpL1.set(tmpA1).scale(-drawLen).add(tmpP1)
tmpL2.set(tmpA2).scale(-drawLen).add(tmpP2)
addLine(tmpL1, tmpL2, color)
}
}
} | apache-2.0 | 963cd7f0de30fb5ab447dd765887601b | 34.421991 | 126 | 0.568462 | 3.85853 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfFile.kt | 1 | 29997 | package de.fabmax.kool.modules.gltf
import de.fabmax.kool.math.Mat4d
import de.fabmax.kool.math.Mat4dStack
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec4d
import de.fabmax.kool.pipeline.Texture2d
import de.fabmax.kool.pipeline.deferred.DeferredPbrShader
import de.fabmax.kool.pipeline.ibl.EnvironmentMaps
import de.fabmax.kool.pipeline.shading.*
import de.fabmax.kool.scene.Group
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.scene.Model
import de.fabmax.kool.scene.Node
import de.fabmax.kool.scene.animation.*
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.Log
import de.fabmax.kool.util.ShadowMap
import de.fabmax.kool.util.logW
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlin.math.min
/**
* The root object for a glTF asset.
*
* @param extensionsUsed Names of glTF extensions used somewhere in this asset.
* @param extensionsRequired Names of glTF extensions required to properly load this asset.
* @param accessors An array of accessors.
* @param animations An array of keyframe animations.
* @param asset Metadata about the glTF asset.
* @param buffers An array of buffers.
* @param bufferViews An array of bufferViews.
* @param images An array of images.
* @param materials An array of materials.
* @param meshes An array of meshes.
* @param nodes An array of nodes.
* @param scene The index of the default scene
* @param scenes An array of scenes.
* @param skins An array of skins.
* @param textures An array of textures.
*/
@Serializable
data class GltfFile(
val extensionsUsed: List<String> = emptyList(),
val extensionsRequired: List<String> = emptyList(),
val accessors: List<GltfAccessor> = emptyList(),
val animations: List<GltfAnimation> = emptyList(),
val asset: GltfAsset,
val buffers: List<GltfBuffer> = emptyList(),
val bufferViews: List<GltfBufferView> = emptyList(),
//val cameras List<Camera> = emptyList(),
val images: List<GltfImage> = emptyList(),
val materials: List<GltfMaterial> = emptyList(),
val meshes: List<GltfMesh> = emptyList(),
val nodes: List<GltfNode> = emptyList(),
//val samplers: List<Sampler> = emptyList(),
val scene: Int = 0,
val scenes: List<GltfScene> = emptyList(),
val skins: List<GltfSkin> = emptyList(),
val textures: List<GltfTexture> = emptyList()
) {
fun makeModel(modelCfg: ModelGenerateConfig = ModelGenerateConfig(), scene: Int = this.scene): Model {
return ModelGenerator(modelCfg).makeModel(scenes[scene])
}
internal fun updateReferences() {
accessors.forEach {
if (it.bufferView >= 0) {
it.bufferViewRef = bufferViews[it.bufferView]
}
it.sparse?.let { sparse ->
sparse.indices.bufferViewRef = bufferViews[sparse.indices.bufferView]
sparse.values.bufferViewRef = bufferViews[sparse.values.bufferView]
}
}
animations.forEach { anim ->
anim.samplers.forEach {
it.inputAccessorRef = accessors[it.input]
it.outputAccessorRef = accessors[it.output]
}
anim.channels.forEach {
it.samplerRef = anim.samplers[it.sampler]
if (it.target.node >= 0) {
it.target.nodeRef = nodes[it.target.node]
}
}
}
bufferViews.forEach { it.bufferRef = buffers[it.buffer] }
images.filter { it.bufferView >= 0 }.forEach { it.bufferViewRef = bufferViews[it.bufferView] }
meshes.forEach { mesh ->
mesh.primitives.forEach {
if (it.material >= 0) {
it.materialRef = materials[it.material]
}
}
}
nodes.forEach {
it.childRefs = it.children.map { iNd -> nodes[iNd] }
if (it.mesh >= 0) {
it.meshRef = meshes[it.mesh]
}
if (it.skin >= 0) {
it.skinRef = skins[it.skin]
}
}
scenes.forEach { it.nodeRefs = it.nodes.map { iNd -> nodes[iNd] } }
skins.forEach {
if (it.inverseBindMatrices >= 0) {
it.inverseBindMatrixAccessorRef = accessors[it.inverseBindMatrices]
}
it.jointRefs = it.joints.map { iJt -> nodes[iJt] }
}
textures.forEach { it.imageRef = images[it.source] }
}
class ModelGenerateConfig(
val generateNormals: Boolean = false,
val applyMaterials: Boolean = true,
val materialConfig: ModelMaterialConfig = ModelMaterialConfig(),
val setVertexAttribsFromMaterial: Boolean = false,
val loadAnimations: Boolean = true,
val applySkins: Boolean = true,
val applyMorphTargets: Boolean = true,
val applyTransforms: Boolean = false,
val removeEmptyNodes: Boolean = true,
val mergeMeshesByMaterial: Boolean = false,
val sortNodesByAlpha: Boolean = true,
val pbrBlock: (PbrMaterialConfig.(GltfMesh.Primitive) -> Unit)? = null
)
class ModelMaterialConfig(
val shadowMaps: List<ShadowMap> = emptyList(),
val scrSpcAmbientOcclusionMap: Texture2d? = null,
val environmentMaps: EnvironmentMaps? = null,
val isDeferredShading: Boolean = false,
val maxNumberOfJoints: Int = 64
)
private inner class ModelGenerator(val cfg: ModelGenerateConfig) {
val modelAnimations = mutableListOf<Animation>()
val modelNodes = mutableMapOf<GltfNode, Group>()
val meshesByMaterial = mutableMapOf<Int, MutableSet<Mesh>>()
val meshMaterials = mutableMapOf<Mesh, GltfMaterial?>()
fun makeModel(scene: GltfScene): Model {
val model = Model(scene.name ?: "model_scene")
scene.nodeRefs.forEach { nd -> model += nd.makeNode(model, cfg) }
if (cfg.loadAnimations) { makeTrsAnimations() }
if (cfg.loadAnimations) { makeSkins(model) }
modelNodes.forEach { (node, grp) -> node.createMeshes(model, grp, cfg) }
if (cfg.loadAnimations) { makeMorphAnimations() }
modelAnimations.filter { it.channels.isNotEmpty() }.forEach { modelAnim ->
modelAnim.prepareAnimation()
model.animations += modelAnim
}
model.disableAllAnimations()
if (cfg.applyTransforms && model.animations.isEmpty()) { applyTransforms(model) }
if (cfg.mergeMeshesByMaterial) { mergeMeshesByMaterial(model) }
if (cfg.sortNodesByAlpha) { model.sortNodesByAlpha() }
if (cfg.removeEmptyNodes) { model.removeEmpty() }
return model
}
private fun Group.removeEmpty() {
val tgChildren = children.filterIsInstance<Group>()
tgChildren.forEach {
it.removeEmpty()
if (it.children.isEmpty()) {
removeNode(it)
}
}
}
private fun makeTrsAnimations() {
animations.forEach { anim ->
val modelAnim = Animation(anim.name)
modelAnimations += modelAnim
val animNodes = mutableMapOf<Group, AnimationNode>()
anim.channels.forEach { channel ->
val nodeGrp = modelNodes[channel.target.nodeRef]
if (nodeGrp != null) {
val animationNd = animNodes.getOrPut(nodeGrp) { AnimatedTransformGroup(nodeGrp) }
when (channel.target.path) {
GltfAnimation.Target.PATH_TRANSLATION -> makeTranslationAnimation(channel, animationNd, modelAnim)
GltfAnimation.Target.PATH_ROTATION -> makeRotationAnimation(channel, animationNd, modelAnim)
GltfAnimation.Target.PATH_SCALE -> makeScaleAnimation(channel, animationNd, modelAnim)
}
}
}
}
}
private fun makeTranslationAnimation(animCh: GltfAnimation.Channel, animNd: AnimationNode, modelAnim: Animation) {
val inputAcc = animCh.samplerRef.inputAccessorRef
val outputAcc = animCh.samplerRef.outputAccessorRef
if (inputAcc.type != GltfAccessor.TYPE_SCALAR || inputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported translation animation input accessor: type = ${inputAcc.type}, component type = ${inputAcc.componentType}, should be SCALAR and 5126 (float)" }
return
}
if (outputAcc.type != GltfAccessor.TYPE_VEC3 || outputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported translation animation output accessor: type = ${outputAcc.type}, component type = ${outputAcc.componentType}, should be VEC3 and 5126 (float)" }
return
}
val transChannel = TranslationAnimationChannel("${modelAnim.name}_translation", animNd)
val interpolation = when (animCh.samplerRef.interpolation) {
GltfAnimation.Sampler.INTERPOLATION_STEP -> AnimationKey.Interpolation.STEP
GltfAnimation.Sampler.INTERPOLATION_CUBICSPLINE -> AnimationKey.Interpolation.CUBICSPLINE
else -> AnimationKey.Interpolation.LINEAR
}
modelAnim.channels += transChannel
val inTime = FloatAccessor(inputAcc)
val outTranslation = Vec3fAccessor(outputAcc)
for (i in 0 until min(inputAcc.count, outputAcc.count)) {
val t = inTime.next()
val transKey = if (interpolation == AnimationKey.Interpolation.CUBICSPLINE) {
val startTan = outTranslation.nextD()
val point = outTranslation.nextD()
val endTan = outTranslation.nextD()
CubicTranslationKey(t, point, startTan, endTan)
} else {
TranslationKey(t, outTranslation.nextD())
}
transKey.interpolation = interpolation
transChannel.keys[t] = transKey
}
}
private fun makeRotationAnimation(animCh: GltfAnimation.Channel, animNd: AnimationNode, modelAnim: Animation) {
val inputAcc = animCh.samplerRef.inputAccessorRef
val outputAcc = animCh.samplerRef.outputAccessorRef
if (inputAcc.type != GltfAccessor.TYPE_SCALAR || inputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported rotation animation input accessor: type = ${inputAcc.type}, component type = ${inputAcc.componentType}, should be SCALAR and 5126 (float)" }
return
}
if (outputAcc.type != GltfAccessor.TYPE_VEC4 || outputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported rotation animation output accessor: type = ${outputAcc.type}, component type = ${outputAcc.componentType}, should be VEC4 and 5126 (float)" }
return
}
val rotChannel = RotationAnimationChannel("${modelAnim.name}_rotation", animNd)
val interpolation = when (animCh.samplerRef.interpolation) {
GltfAnimation.Sampler.INTERPOLATION_STEP -> AnimationKey.Interpolation.STEP
GltfAnimation.Sampler.INTERPOLATION_CUBICSPLINE -> AnimationKey.Interpolation.CUBICSPLINE
else -> AnimationKey.Interpolation.LINEAR
}
modelAnim.channels += rotChannel
val inTime = FloatAccessor(inputAcc)
val outRotation = Vec4fAccessor(outputAcc)
for (i in 0 until min(inputAcc.count, outputAcc.count)) {
val t = inTime.next()
val rotKey = if (interpolation == AnimationKey.Interpolation.CUBICSPLINE) {
val startTan = outRotation.nextD()
val point = outRotation.nextD()
val endTan = outRotation.nextD()
CubicRotationKey(t, point, startTan, endTan)
} else {
RotationKey(t, outRotation.nextD())
}
rotKey.interpolation = interpolation
rotChannel.keys[t] = rotKey
}
}
private fun makeScaleAnimation(animCh: GltfAnimation.Channel, animNd: AnimationNode, modelAnim: Animation) {
val inputAcc = animCh.samplerRef.inputAccessorRef
val outputAcc = animCh.samplerRef.outputAccessorRef
if (inputAcc.type != GltfAccessor.TYPE_SCALAR || inputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported scale animation input accessor: type = ${inputAcc.type}, component type = ${inputAcc.componentType}, should be SCALAR and 5126 (float)" }
return
}
if (outputAcc.type != GltfAccessor.TYPE_VEC3 || outputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported scale animation output accessor: type = ${outputAcc.type}, component type = ${outputAcc.componentType}, should be VEC3 and 5126 (float)" }
return
}
val scaleChannel = ScaleAnimationChannel("${modelAnim.name}_scale", animNd)
val interpolation = when (animCh.samplerRef.interpolation) {
GltfAnimation.Sampler.INTERPOLATION_STEP -> AnimationKey.Interpolation.STEP
GltfAnimation.Sampler.INTERPOLATION_CUBICSPLINE -> AnimationKey.Interpolation.CUBICSPLINE
else -> AnimationKey.Interpolation.LINEAR
}
modelAnim.channels += scaleChannel
val inTime = FloatAccessor(inputAcc)
val outScale = Vec3fAccessor(outputAcc)
for (i in 0 until min(inputAcc.count, outputAcc.count)) {
val t = inTime.next()
val scaleKey = if (interpolation == AnimationKey.Interpolation.CUBICSPLINE) {
val startTan = outScale.nextD()
val point = outScale.nextD()
val endTan = outScale.nextD()
CubicScaleKey(t, point, startTan, endTan)
} else {
ScaleKey(t, outScale.nextD())
}
scaleKey.interpolation = interpolation
scaleChannel.keys[t] = scaleKey
}
}
private fun makeMorphAnimations() {
animations.forEachIndexed { iAnim, anim ->
anim.channels.forEach { channel ->
if (channel.target.path == GltfAnimation.Target.PATH_WEIGHTS) {
val modelAnim = modelAnimations[iAnim]
val gltfMesh = channel.target.nodeRef?.meshRef
val nodeGrp = modelNodes[channel.target.nodeRef]
nodeGrp?.children?.filterIsInstance<Mesh>()?.forEach {
makeWeightAnimation(gltfMesh!!, channel, MorphAnimatedMesh(it), modelAnim)
}
}
}
}
}
private fun makeWeightAnimation(gltfMesh: GltfMesh, animCh: GltfAnimation.Channel, animNd: MorphAnimatedMesh, modelAnim: Animation) {
val inputAcc = animCh.samplerRef.inputAccessorRef
val outputAcc = animCh.samplerRef.outputAccessorRef
if (inputAcc.type != GltfAccessor.TYPE_SCALAR || inputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported weight animation input accessor: type = ${inputAcc.type}, component type = ${inputAcc.componentType}, should be SCALAR and 5126 (float)" }
return
}
if (outputAcc.type != GltfAccessor.TYPE_SCALAR || outputAcc.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
logW { "Unsupported weight animation output accessor: type = ${outputAcc.type}, component type = ${inputAcc.componentType}, should be VEC3 and 5126 (float)" }
return
}
val weightChannel = WeightAnimationChannel("${modelAnim.name}_weight", animNd)
val interpolation = when (animCh.samplerRef.interpolation) {
GltfAnimation.Sampler.INTERPOLATION_STEP -> AnimationKey.Interpolation.STEP
GltfAnimation.Sampler.INTERPOLATION_CUBICSPLINE -> AnimationKey.Interpolation.CUBICSPLINE
else -> AnimationKey.Interpolation.LINEAR
}
modelAnim.channels += weightChannel
val morphTargets = gltfMesh.primitives[0].targets
val nAttribs = gltfMesh.primitives[0].targets.sumOf { it.size }
val inTimes = FloatAccessor(inputAcc)
val outWeight = FloatAccessor(outputAcc)
for (i in 0 until min(inputAcc.count, outputAcc.count)) {
val t = inTimes.next()
val weightKey = if (interpolation == AnimationKey.Interpolation.CUBICSPLINE) {
val startTan = FloatArray(nAttribs)
val point = FloatArray(nAttribs)
val endTan = FloatArray(nAttribs)
var iAttrib = 0
for (m in morphTargets.indices) {
val w = outWeight.next()
for (j in 0 until morphTargets[m].size) { startTan[iAttrib++] = w }
}
iAttrib = 0
for (m in morphTargets.indices) {
val w = outWeight.next()
for (j in 0 until morphTargets[m].size) { point[iAttrib++] = w }
}
iAttrib = 0
for (m in morphTargets.indices) {
val w = outWeight.next()
for (j in 0 until morphTargets[m].size) { endTan[iAttrib++] = w }
}
CubicWeightKey(t, point, startTan, endTan)
} else {
val attribWeights = FloatArray(nAttribs)
var iAttrib = 0
for (m in morphTargets.indices) {
val w = outWeight.next()
for (j in 0 until morphTargets[m].size) {
attribWeights[iAttrib++] = w
}
}
WeightKey(t, attribWeights)
}
weightKey.interpolation = interpolation
weightChannel.keys[t] = weightKey
}
}
private fun makeSkins(model: Model) {
skins.forEach { skin ->
val modelSkin = Skin()
val invBinMats = skin.inverseBindMatrixAccessorRef?.let { Mat4fAccessor(it) }
if (invBinMats != null) {
// 1st pass: make SkinNodes for specified nodes / TransformGroups
val skinNodes = mutableMapOf<GltfNode, Skin.SkinNode>()
skin.jointRefs.forEach { joint ->
val jointGrp = modelNodes[joint]!!
val invBindMat = invBinMats.next()
val skinNode = Skin.SkinNode(jointGrp, invBindMat)
modelSkin.nodes += skinNode
skinNodes[joint] = skinNode
}
// 2nd pass: build SkinNode hierarchy
skin.jointRefs.forEach { joint ->
val skinNode = skinNodes[joint]
if (skinNode != null) {
joint.childRefs.forEach { child ->
val childNode = skinNodes[child]
childNode?.let { skinNode.addChild(it) }
}
}
}
model.skins += modelSkin
}
}
}
private fun Group.sortNodesByAlpha(): Float {
val childAlphas = mutableMapOf<Node, Float>()
var avgAlpha = 0f
for (child in children) {
var a = 1f
if (child is Mesh && !child.isOpaque) {
a = 0f
} else if (child is Group) {
a = child.sortNodesByAlpha()
}
childAlphas[child] = a
avgAlpha += a
}
sortChildrenBy { -(childAlphas[it] ?: 1f) }
if (children.isNotEmpty()) {
avgAlpha /= children.size
}
return avgAlpha
}
private fun mergeMeshesByMaterial(model: Model) {
model.mergeMeshesByMaterial()
}
private fun Group.mergeMeshesByMaterial() {
children.filterIsInstance<Group>().forEach { it.mergeMeshesByMaterial() }
meshesByMaterial.values.forEach { sameMatMeshes ->
val mergeMeshes = children.filter { it in sameMatMeshes }.map { it as Mesh }
if (mergeMeshes.size > 1) {
val r = mergeMeshes[0]
for (i in 1 until mergeMeshes.size) {
val m = mergeMeshes[i]
if (m.geometry.attributeHash == r.geometry.attributeHash) {
r.geometry.addGeometry(m.geometry)
removeNode(m)
}
}
}
}
}
private fun applyTransforms(model: Model) {
val transform = Mat4dStack()
transform.setIdentity()
model.applyTransforms(transform, model)
}
private fun Group.applyTransforms(transform: Mat4dStack, rootGroup: Group) {
transform.push()
transform.mul(this.transform)
children.filterIsInstance<Mesh>().forEach {
it.geometry.batchUpdate(true) {
forEach { v ->
transform.transform(v.position, 1f)
transform.transform(v.normal, 0f)
val tan3 = v.tangent.getXyz(MutableVec3f())
transform.transform(tan3, 0f)
v.tangent.set(tan3, v.tangent.w)
}
}
if (rootGroup != this) {
rootGroup += it
}
}
val childGroups = children.filterIsInstance<Group>()
childGroups.forEach {
it.applyTransforms(transform, rootGroup)
removeNode(it)
}
transform.pop()
}
private fun GltfNode.makeNode(model: Model, cfg: ModelGenerateConfig): Group {
val modelNdName = name ?: "node_${model.nodes.size}"
val nodeGrp = Group(modelNdName)
modelNodes[this] = nodeGrp
model.nodes[modelNdName] = nodeGrp
if (matrix != null) {
nodeGrp.transform.set(matrix.map { it.toDouble() })
} else {
if (translation != null) {
nodeGrp.translate(translation[0], translation[1], translation[2])
}
if (rotation != null) {
val rotMat = Mat4d().setRotate(Vec4d(rotation[0].toDouble(), rotation[1].toDouble(), rotation[2].toDouble(), rotation[3].toDouble()))
nodeGrp.transform.mul(rotMat)
}
if (scale != null) {
nodeGrp.scale(scale[0], scale[1], scale[2])
}
}
childRefs.forEach {
nodeGrp += it.makeNode(model, cfg)
}
return nodeGrp
}
private fun GltfNode.createMeshes(model: Model, nodeGrp: Group, cfg: ModelGenerateConfig) {
meshRef?.primitives?.forEachIndexed { index, prim ->
val name = "${meshRef?.name ?: "${nodeGrp.name}.mesh"}_$index"
val geometry = prim.toGeometry(cfg, accessors)
if (!geometry.isEmpty()) {
val mesh = Mesh(geometry, name)
nodeGrp += mesh
meshesByMaterial.getOrPut(prim.material) { mutableSetOf() } += mesh
meshMaterials[mesh] = prim.materialRef
if (cfg.loadAnimations && cfg.applySkins && skin >= 0) {
mesh.skin = model.skins[skin]
val skeletonRoot = skins[skin].skeleton
if (skeletonRoot >= 0) {
nodeGrp -= mesh
modelNodes[nodes[skeletonRoot]]!! += mesh
}
mesh.isFrustumChecked = false
}
if (cfg.loadAnimations && cfg.applyMorphTargets && prim.targets.isNotEmpty()) {
mesh.morphWeights = FloatArray(prim.targets.sumOf { it.size })
mesh.isFrustumChecked = false
}
if (cfg.applyMaterials) {
var renderDeferred = cfg.materialConfig.isDeferredShading
val useVertexColor = prim.attributes.containsKey(GltfMesh.Primitive.ATTRIBUTE_COLOR_0)
val pbrConfig = PbrMaterialConfig().apply {
val material = prim.materialRef
if (material != null) {
material.applyTo(this, useVertexColor, this@GltfFile)
} else {
albedo = Color.GRAY
albedoSource = Albedo.STATIC_ALBEDO
}
if (mesh.skin != null) {
isSkinned = true
maxJoints = min(cfg.materialConfig.maxNumberOfJoints, mesh.skin!!.nodes.size)
if (cfg.materialConfig.maxNumberOfJoints < mesh.skin!!.nodes.size) {
Log.e("GltfFile") { "\"${model.name}\": Maximum number of joints exceeded (mesh has ${mesh.skin!!.nodes.size}, materialConfig.maxNumberOfJoints is ${cfg.materialConfig.maxNumberOfJoints})" }
}
}
if (mesh.morphWeights != null) {
morphAttributes += mesh.geometry.getMorphAttributes()
}
cfg.materialConfig.let { matCfg ->
shadowMaps += matCfg.shadowMaps
matCfg.scrSpcAmbientOcclusionMap?.let { useScreenSpaceAmbientOcclusion(it) }
useImageBasedLighting(matCfg.environmentMaps)
}
cfg.pbrBlock?.invoke(this, prim)
if (alphaMode is AlphaMode.Blend) {
mesh.isOpaque = false
// transparent / blended meshes must be rendered in forward pass
renderDeferred = false
}
albedoMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
emissiveMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
normalMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
roughnessMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
metallicMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
aoMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
displacementMap?.let { model.textures[it.name ?: "tex_${model.textures.size}"] = it }
}
if (renderDeferred) {
pbrConfig.isHdrOutput = true
mesh.shader = DeferredPbrShader(pbrConfig)
} else {
pbrConfig.isHdrOutput = false
mesh.shader = PbrShader(pbrConfig)
}
if (pbrConfig.alphaMode is AlphaMode.Mask) {
val depthShaderCfg = DepthShaderConfig().apply {
isInstanced = pbrConfig.isInstanced
isSkinned = pbrConfig.isSkinned
cullMethod = pbrConfig.cullMethod
alphaMode = pbrConfig.alphaMode
alphaMask = pbrConfig.albedoMap
}
mesh.depthShader = DepthShader(depthShaderCfg)
}
}
model.meshes[name] = mesh
}
}
}
}
companion object {
const val GLB_FILE_MAGIC = 0x46546c67
const val GLB_CHUNK_MAGIC_JSON = 0x4e4f534a
const val GLB_CHUNK_MAGIC_BIN = 0x004e4942
private val jsonFmt = Json {
isLenient = true
ignoreUnknownKeys = true
allowSpecialFloatingPointValues = true
useArrayPolymorphism = true
}
fun fromJson(json: String): GltfFile {
return jsonFmt.decodeFromString(json)
}
}
}
| apache-2.0 | 8859bd9d56a9bde9d9e9cb40f28b02d7 | 46.017241 | 226 | 0.540821 | 4.821119 | false | false | false | false |
zdary/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/importing/AbstractOpenProjectProvider.kt | 2 | 5266 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.importing
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.OpenUntrustedProjectChoice
import com.intellij.ide.impl.ProjectUtil.*
import com.intellij.ide.impl.setTrusted
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.externalSystem.ExternalSystemManager
import com.intellij.openapi.externalSystem.autolink.UnlinkedProjectNotificationAware
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil.confirmOpeningUntrustedProject
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.apache.commons.lang.StringUtils
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
@ApiStatus.Experimental
abstract class AbstractOpenProjectProvider : OpenProjectProvider {
protected open val systemId: ProjectSystemId by lazy {
/**
* Tries to resolve external system id
* Note: Implemented approach is super heuristics.
* Please, override [systemId] to avoid discrepancy with real id.
*/
LOG.warn("Class ${javaClass.name} have to override AbstractOpenProjectProvider.systemId. " +
"Resolving of systemId will be removed in future releases.")
val readableName = StringUtils.splitByCharacterTypeCamelCase(javaClass.simpleName).first()
val manager = ExternalSystemManager.EP_NAME.findFirstSafe {
StringUtils.equalsIgnoreCase(StringUtils.splitByCharacterTypeCamelCase(it.javaClass.simpleName).first(), readableName)
}
manager?.systemId ?: ProjectSystemId(readableName.toUpperCase())
}
protected abstract fun isProjectFile(file: VirtualFile): Boolean
protected abstract fun linkAndRefreshProject(projectDirectory: Path, project: Project)
override fun canOpenProject(file: VirtualFile): Boolean {
return if (file.isDirectory) file.children.any(::isProjectFile) else isProjectFile(file)
}
override fun openProject(projectFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
LOG.debug("Open project from $projectFile")
val projectDirectory = getProjectDirectory(projectFile)
if (focusOnOpenedSameProject(projectDirectory.toNioPath())) {
return null
}
val nioPath = projectDirectory.toNioPath()
val isValidIdeaProject = isValidProjectPath(nioPath)
val untrustedProjectChoice = confirmOpeningUntrustedProject(projectFile, systemId)
if (untrustedProjectChoice == OpenUntrustedProjectChoice.CANCEL) return null
val options = OpenProjectTask(
isNewProject = !isValidIdeaProject,
forceOpenInNewFrame = forceOpenInNewFrame,
projectToClose = projectToClose,
runConfigurators = false,
beforeOpen = { project ->
project.setTrusted(untrustedProjectChoice == OpenUntrustedProjectChoice.IMPORT)
if (isValidIdeaProject) {
UnlinkedProjectNotificationAware.enableNotifications(project, systemId)
}
else {
project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, true)
ApplicationManager.getApplication().invokeAndWait {
linkAndRefreshProject(nioPath, project)
}
updateLastProjectLocation(nioPath)
}
true
}
)
return ProjectManagerEx.getInstanceEx().openProject(nioPath, options)
}
override fun linkToExistingProject(projectFile: VirtualFile, project: Project) {
LOG.debug("Import project from $projectFile")
val projectDirectory = getProjectDirectory(projectFile)
linkAndRefreshProject(projectDirectory.toNioPath(), project)
}
fun linkToExistingProject(projectFilePath: String, project: Project) {
val localFileSystem = LocalFileSystem.getInstance()
val projectFile = localFileSystem.refreshAndFindFileByPath(projectFilePath)
if (projectFile == null) {
val shortPath = FileUtil.getLocationRelativeToUserHome(FileUtil.toSystemDependentName(projectFilePath), false)
throw IllegalArgumentException(ExternalSystemBundle.message("error.project.does.not.exist", systemId.readableName, shortPath))
}
linkToExistingProject(projectFile, project)
}
private fun focusOnOpenedSameProject(projectDirectory: Path): Boolean {
for (project in ProjectManager.getInstance().openProjects) {
if (isSameProject(projectDirectory, project)) {
focusProjectWindow(project, false)
return true
}
}
return false
}
private fun getProjectDirectory(file: VirtualFile): VirtualFile {
return if (file.isDirectory) file else file.parent
}
companion object {
protected val LOG = logger<AbstractOpenProjectProvider>()
}
} | apache-2.0 | b71af85bb7174c0944652dd90fefec15 | 42.528926 | 140 | 0.776491 | 5.147605 | false | false | false | false |
siosio/intellij-community | uast/uast-common/src/org/jetbrains/uast/generate/UastCodeGenerationPlugin.kt | 1 | 5205 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.generate
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import kotlin.streams.asSequence
@ApiStatus.Experimental
interface UastCodeGenerationPlugin {
companion object {
private val extensionPointName = ExtensionPointName<UastCodeGenerationPlugin>("org.jetbrains.uast.generate.uastCodeGenerationPlugin")
@JvmStatic
fun byLanguage(language: Language) = extensionPointName.extensions().asSequence().firstOrNull { it.language == language }
}
fun getElementFactory(project: Project): UastElementFactory
val language: Language
fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T?
}
@ApiStatus.Experimental
interface UastElementFactory {
fun createBinaryExpression(leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression?
/**
* Create binary expression, and possibly remove unnecessary parenthesis, so it could become [UPolyadicExpression], e.g
* [createFlatBinaryExpression] (1 + 2, 2, +) could produce 1 + 2 + 2, which is polyadic expression
*/
@JvmDefault
fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? =
createBinaryExpression(leftOperand, rightOperand, operator, context)
fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression?
fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression?
@Deprecated("Use PsiElement context variant")
fun createQualifiedReference(qualifiedName: String, context: UElement?): UQualifiedReferenceExpression?
fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression?
fun createParenthesizedExpression(expression: UExpression,
context: PsiElement?): UParenthesizedExpression?
fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean = false,
context: PsiElement?): UReturnExpression?
fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean = false,
context: PsiElement?): ULocalVariable?
fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression?
fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression?
fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression?
/**
* For providing additional information pass it via [context] only, otherwise it can be lost
*/
fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement? = null): UCallExpression?
fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?, context: PsiElement?): UIfExpression?
fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression?
fun createNullLiteral(context: PsiElement?): ULiteralExpression?
}
@ApiStatus.Experimental
data class UParameterInfo(val type: PsiType?, val suggestedName: String?)
@ApiStatus.Experimental
infix fun String?.ofType(type: PsiType?): UParameterInfo = UParameterInfo(type, this)
@ApiStatus.Experimental
inline fun <reified T : UElement> UElement.replace(newElement: T): T? =
UastCodeGenerationPlugin.byLanguage(this.lang)
?.replace(this, newElement, T::class.java).also {
if (it == null) {
logger<UastCodeGenerationPlugin>().warn("failed replacing the $this with $newElement")
}
}
@ApiStatus.Experimental
inline fun <reified T : UElement> T.refreshed() = sourcePsi?.also {
logger<UastCodeGenerationPlugin>().assertTrue(it.isValid,
"psi $it of class ${it.javaClass} should be valid, containing file = ${it.containingFile}")
}?.toUElementOfType<T>()
val UElement.generationPlugin: UastCodeGenerationPlugin?
@ApiStatus.Experimental
get() = UastCodeGenerationPlugin.byLanguage(this.lang)
@ApiStatus.Experimental
fun UElement.getUastElementFactory(project: Project): UastElementFactory? =
generationPlugin?.getElementFactory(project)
| apache-2.0 | a91a578bf8c3e7a691cacc18dd95ef89 | 42.739496 | 140 | 0.716619 | 5.554963 | false | false | false | false |
jwren/intellij-community | platform/vfs-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FsRootDataLoader.kt | 4 | 1382 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.newvfs.persistent
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem
import org.jetbrains.annotations.ApiStatus.Internal
import java.io.IOException
import java.nio.file.Path
@Internal
interface FsRootDataLoader {
val name: String
@Throws(IOException::class)
fun ensureLoaded(storage: Path)
@Throws(IOException::class)
fun deleteRootRecord(storage: Path, rootId: Int)
@Throws(IOException::class)
fun deleteDirectoryRecord(storage: Path, id: Int)
@Throws(IOException::class)
fun loadRootData(storage: Path, id: Int, path: String, fs: NewVirtualFileSystem)
@Throws(IOException::class)
fun loadDirectoryData(storage: Path, id: Int, path: String, fs: NewVirtualFileSystem)
}
class EmptyFsRootDataLoader : FsRootDataLoader {
override val name: String = "empty"
override fun ensureLoaded(storage: Path) = Unit
override fun deleteRootRecord(storage: Path, rootId: Int) = Unit
override fun deleteDirectoryRecord(storage: Path, id: Int) = Unit
override fun loadRootData(storage: Path, id: Int, path: String, fs: NewVirtualFileSystem) = Unit
override fun loadDirectoryData(storage: Path, id: Int, path: String, fs: NewVirtualFileSystem) = Unit
} | apache-2.0 | 2c95b7214d61e811e106bb72cfac5c06 | 32.731707 | 158 | 0.771346 | 3.915014 | false | false | false | false |
jwren/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/MavenBadConfigEventParser.kt | 3 | 5849 | // 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.idea.maven.externalSystemIntegration.output.quickfixes
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.BuildIssueEventImpl
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.build.issue.quickfix.OpenFileQuickFix
import com.intellij.build.output.BuildOutputInstantReader
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import org.jetbrains.idea.maven.externalSystemIntegration.output.LogMessageType
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLoggedEventParser
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenParsingContext
import org.jetbrains.idea.maven.externalSystemIntegration.output.importproject.MavenImportLoggedEventParser
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenUtil
import java.util.concurrent.CompletableFuture
import java.util.function.Consumer
class MavenBadConfigEventParser : MavenLoggedEventParser {
override fun supportsType(type: LogMessageType?): Boolean {
return type == null || type == LogMessageType.ERROR
}
override fun checkLogLine(parentId: Any,
parsingContext: MavenParsingContext,
logLine: MavenLogEntryReader.MavenLogEntry,
logEntryReader: MavenLogEntryReader,
messageConsumer: Consumer<in BuildEvent?>): Boolean {
val line = logLine.line
if (line.startsWith(MavenConfigBuildIssue.CONFIG_PARSE_ERROR) && logLine.type == null) {
val buildIssue = MavenConfigBuildIssue.getIssue(
line, line.substring(MavenConfigBuildIssue.CONFIG_PARSE_ERROR.length).trim(), parsingContext.ideaProject
) ?: return false
messageConsumer.accept(
BuildIssueEventImpl(parentId, buildIssue, MessageEvent.Kind.ERROR)
)
return true
}
if (line.startsWith(MavenConfigBuildIssue.CONFIG_VALUE_ERROR) && logLine.type == LogMessageType.ERROR) {
val buildIssue = MavenConfigBuildIssue.getIssue(line, line, parsingContext.ideaProject) ?: return false
messageConsumer.accept(
BuildIssueEventImpl(parentId, buildIssue, MessageEvent.Kind.ERROR)
)
return true
}
return false
}
}
class MavenImportBadConfigEventParser : MavenImportLoggedEventParser {
override fun processLogLine(project: Project,
logLine: String,
reader: BuildOutputInstantReader,
messageConsumer: Consumer<in BuildEvent>): Boolean {
if (logLine.startsWith(MavenConfigBuildIssue.CONFIG_PARSE_ERROR)) {
val buildIssue = MavenConfigBuildIssue.getIssue(
logLine, logLine.substring(MavenConfigBuildIssue.CONFIG_PARSE_ERROR.length).trim(), project
) ?: return false
messageConsumer.accept(
BuildIssueEventImpl(Any(), buildIssue, MessageEvent.Kind.ERROR)
)
return true
}
if (logLine.startsWith(MavenConfigBuildIssue.CONFIG_VALUE_ERROR)) {
val buildIssue = MavenConfigBuildIssue.getIssue(logLine, logLine, project) ?: return false
messageConsumer.accept(
BuildIssueEventImpl(Any(), buildIssue, MessageEvent.Kind.ERROR)
)
return true
}
return false
}
}
class MavenConfigOpenQuickFix(val mavenConfig: VirtualFile, val errorMessage: String) : BuildIssueQuickFix {
override val id: String = "open_maven_config_quick_fix"
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
var search: String? = null
if (errorMessage.contains(":")) {
search = errorMessage.substring(errorMessage.lastIndexOf(":"))
.replace(":", "")
.replace("\"", "")
.replace("'", "")
.trim()
}
OpenFileQuickFix.showFile(project, mavenConfig.toNioPath(), search)
return CompletableFuture.completedFuture<Any>(null)
}
}
object MavenConfigBuildIssue {
const val CONFIG_PARSE_ERROR: String = "Unable to parse maven.config:"
const val CONFIG_VALUE_ERROR: String = "For input string:"
fun getIssue(title: String, errorMessage: String, project: Project): BuildIssue? {
val mavenProject = MavenProjectsManager.getInstance(project).rootProjects.firstOrNull()
if (mavenProject == null) {
MavenLog.LOG.warn("Cannot find appropriate maven project,project = ${project.name}")
return null;
}
val configFile = MavenUtil.getConfigFile(mavenProject, MavenConstants.MAVEN_CONFIG_RELATIVE_PATH)
if (configFile == null) return null
val mavenConfigOpenQuickFix = MavenConfigOpenQuickFix(configFile, errorMessage)
val quickFixes = listOf<BuildIssueQuickFix>(mavenConfigOpenQuickFix)
val issueDescription = StringBuilder(errorMessage)
issueDescription.append("\n\n")
issueDescription.append(MavenProjectBundle.message("maven.quickfix.maven.config.file", mavenConfigOpenQuickFix.id))
return object : BuildIssue {
override val title: String = title
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
}
| apache-2.0 | a5dcd9ea31c0866be44e02deb7b40196 | 43.310606 | 158 | 0.741494 | 4.747565 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-tooling/tests/test/createKotlinMPPGradleModel.kt | 2 | 5594 | // 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.gradle
import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.gradleTooling.arguments.*
import org.jetbrains.kotlin.idea.projectModel.*
internal fun createKotlinMPPGradleModel(
dependencyMap: Map<KotlinDependencyId, KotlinDependency> = emptyMap(),
sourceSets: Set<KotlinSourceSet> = emptySet(),
targets: Iterable<KotlinTarget> = emptyList(),
extraFeatures: ExtraFeatures = createExtraFeatures(),
kotlinNativeHome: String = ""
): KotlinMPPGradleModelImpl {
return KotlinMPPGradleModelImpl(
dependencyMap = dependencyMap,
sourceSetsByName = sourceSets.associateBy { it.name },
targets = targets.toList(),
extraFeatures = extraFeatures,
kotlinNativeHome = kotlinNativeHome,
cacheAware = CompilerArgumentsCacheAwareImpl()
)
}
internal fun createExtraFeatures(
coroutinesState: String? = null,
isHmppEnabled: Boolean = false,
isNativeDependencyPropagationEnabled: Boolean = false
): ExtraFeaturesImpl {
return ExtraFeaturesImpl(
coroutinesState = coroutinesState,
isHMPPEnabled = isHmppEnabled,
isNativeDependencyPropagationEnabled = isNativeDependencyPropagationEnabled
)
}
internal fun createKotlinSourceSet(
name: String,
declaredDependsOnSourceSets: Set<String> = emptySet(),
allDependsOnSourceSets: Set<String> = declaredDependsOnSourceSets,
platforms: Set<KotlinPlatform> = emptySet(),
): KotlinSourceSetImpl = KotlinSourceSetImpl(
name = name,
languageSettings = KotlinLanguageSettingsImpl(
languageVersion = null,
apiVersion = null,
isProgressiveMode = false,
enabledLanguageFeatures = emptySet(),
optInAnnotationsInUse = emptySet(),
compilerPluginArguments = emptyArray(),
compilerPluginClasspath = emptySet(),
freeCompilerArgs = emptyArray()
),
sourceDirs = emptySet(),
resourceDirs = emptySet(),
regularDependencies = emptyArray(),
intransitiveDependencies = emptyArray(),
declaredDependsOnSourceSets = declaredDependsOnSourceSets,
allDependsOnSourceSets = allDependsOnSourceSets,
additionalVisibleSourceSets = emptySet(),
actualPlatforms = KotlinPlatformContainerImpl().apply { pushPlatforms(platforms) },
)
@Suppress("DEPRECATION_ERROR")
internal fun createKotlinCompilation(
name: String = "main",
defaultSourceSets: Set<KotlinSourceSet> = emptySet(),
allSourceSets: Set<KotlinSourceSet> = emptySet(),
dependencies: Iterable<KotlinDependencyId> = emptyList(),
output: KotlinCompilationOutput = createKotlinCompilationOutput(),
arguments: KotlinCompilationArguments = createKotlinCompilationArguments(),
dependencyClasspath: Iterable<String> = emptyList(),
cachedArgsInfo: CachedArgsInfo<*> = createCachedArgsInfo(),
kotlinTaskProperties: KotlinTaskProperties = createKotlinTaskProperties(),
nativeExtensions: KotlinNativeCompilationExtensions? = null
): KotlinCompilationImpl {
return KotlinCompilationImpl(
name = name,
declaredSourceSets = defaultSourceSets,
allSourceSets = allSourceSets,
dependencies = dependencies.toList().toTypedArray(),
output = output,
arguments = arguments,
dependencyClasspath = dependencyClasspath.toList().toTypedArray(),
cachedArgsInfo = cachedArgsInfo,
kotlinTaskProperties = kotlinTaskProperties,
nativeExtensions = nativeExtensions
)
}
internal fun createKotlinCompilationOutput(): KotlinCompilationOutputImpl {
return KotlinCompilationOutputImpl(
classesDirs = emptySet(),
effectiveClassesDir = null,
resourcesDir = null
)
}
@Suppress("DEPRECATION_ERROR")
internal fun createKotlinCompilationArguments(): KotlinCompilationArgumentsImpl {
return KotlinCompilationArgumentsImpl(
defaultArguments = emptyArray(),
currentArguments = emptyArray()
)
}
internal fun createCachedArgsBucket(): CachedCompilerArgumentsBucket = CachedCompilerArgumentsBucket(
compilerArgumentsClassName = KotlinCachedRegularCompilerArgument(0),
singleArguments = emptyMap(),
classpathParts = KotlinCachedMultipleCompilerArgument(emptyList()),
multipleArguments = emptyMap(),
flagArguments = emptyMap(),
internalArguments = emptyList(),
freeArgs = emptyList()
)
internal fun createCachedArgsInfo(): CachedArgsInfo<*> = CachedExtractedArgsInfo(
cacheOriginIdentifier = RandomUtils.nextLong(),
currentCompilerArguments = createCachedArgsBucket(),
defaultCompilerArguments = createCachedArgsBucket(),
dependencyClasspath = emptyList()
)
internal fun createKotlinTaskProperties(): KotlinTaskPropertiesImpl {
return KotlinTaskPropertiesImpl(
null, null, null, null
)
}
internal fun createKotlinTarget(
name: String,
platform: KotlinPlatform = KotlinPlatform.COMMON,
compilations: Iterable<KotlinCompilation> = emptyList()
): KotlinTargetImpl {
return KotlinTargetImpl(
name = name,
presetName = null,
disambiguationClassifier = null,
platform = platform,
compilations = compilations.toList(),
testRunTasks = emptyList(),
nativeMainRunTasks = emptyList(),
jar = null,
konanArtifacts = emptyList()
)
}
| apache-2.0 | 8b516d4aad34c6b2d8f1af8f1b62b71b | 36.543624 | 158 | 0.735967 | 5.932131 | false | false | false | false |
androidx/androidx | compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/vector/PathParser.kt | 3 | 21647 | /*
* 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.vector
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.vector.PathNode.ArcTo
import androidx.compose.ui.graphics.vector.PathNode.Close
import androidx.compose.ui.graphics.vector.PathNode.CurveTo
import androidx.compose.ui.graphics.vector.PathNode.HorizontalTo
import androidx.compose.ui.graphics.vector.PathNode.LineTo
import androidx.compose.ui.graphics.vector.PathNode.MoveTo
import androidx.compose.ui.graphics.vector.PathNode.QuadTo
import androidx.compose.ui.graphics.vector.PathNode.ReflectiveCurveTo
import androidx.compose.ui.graphics.vector.PathNode.ReflectiveQuadTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeArcTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeCurveTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeHorizontalTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeLineTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeMoveTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeQuadTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeReflectiveCurveTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeReflectiveQuadTo
import androidx.compose.ui.graphics.vector.PathNode.RelativeVerticalTo
import androidx.compose.ui.graphics.vector.PathNode.VerticalTo
import androidx.compose.ui.util.fastForEach
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.tan
class PathParser {
private data class PathPoint(var x: Float = 0.0f, var y: Float = 0.0f) {
fun reset() {
x = 0.0f
y = 0.0f
}
}
private val nodes = mutableListOf<PathNode>()
fun clear() {
nodes.clear()
}
private val currentPoint = PathPoint()
private val ctrlPoint = PathPoint()
private val segmentPoint = PathPoint()
private val reflectiveCtrlPoint = PathPoint()
/**
* Parses the path string to create a collection of PathNode instances with their corresponding
* arguments
* throws an IllegalArgumentException or NumberFormatException if the parameters are invalid
*/
fun parsePathString(pathData: String): PathParser {
nodes.clear()
var start = 0
var end = 1
while (end < pathData.length) {
end = nextStart(pathData, end)
val s = pathData.substring(start, end).trim { it <= ' ' }
if (s.isNotEmpty()) {
val args = getFloats(s)
addNode(s[0], args)
}
start = end
end++
}
if (end - start == 1 && start < pathData.length) {
addNode(pathData[start], FloatArray(0))
}
return this
}
fun addPathNodes(nodes: List<PathNode>): PathParser {
this.nodes.addAll(nodes)
return this
}
fun toNodes(): List<PathNode> = nodes
fun toPath(target: Path = Path()): Path {
target.reset()
currentPoint.reset()
ctrlPoint.reset()
segmentPoint.reset()
reflectiveCtrlPoint.reset()
var previousNode: PathNode? = null
nodes.fastForEach { node ->
if (previousNode == null) previousNode = node
when (node) {
is Close -> close(target)
is RelativeMoveTo -> node.relativeMoveTo(target)
is MoveTo -> node.moveTo(target)
is RelativeLineTo -> node.relativeLineTo(target)
is LineTo -> node.lineTo(target)
is RelativeHorizontalTo -> node.relativeHorizontalTo(target)
is HorizontalTo -> node.horizontalTo(target)
is RelativeVerticalTo -> node.relativeVerticalTo(target)
is VerticalTo -> node.verticalTo(target)
is RelativeCurveTo -> node.relativeCurveTo(target)
is CurveTo -> node.curveTo(target)
is RelativeReflectiveCurveTo ->
node.relativeReflectiveCurveTo(previousNode!!.isCurve, target)
is ReflectiveCurveTo -> node.reflectiveCurveTo(previousNode!!.isCurve, target)
is RelativeQuadTo -> node.relativeQuadTo(target)
is QuadTo -> node.quadTo(target)
is RelativeReflectiveQuadTo ->
node.relativeReflectiveQuadTo(previousNode!!.isQuad, target)
is ReflectiveQuadTo -> node.reflectiveQuadTo(previousNode!!.isQuad, target)
is RelativeArcTo -> node.relativeArcTo(target)
is ArcTo -> node.arcTo(target)
}
previousNode = node
}
return target
}
private fun close(target: Path) {
currentPoint.x = segmentPoint.x
currentPoint.y = segmentPoint.y
ctrlPoint.x = segmentPoint.x
ctrlPoint.y = segmentPoint.y
target.close()
target.moveTo(currentPoint.x, currentPoint.y)
}
private fun RelativeMoveTo.relativeMoveTo(target: Path) {
currentPoint.x += dx
currentPoint.y += dy
target.relativeMoveTo(dx, dy)
segmentPoint.x = currentPoint.x
segmentPoint.y = currentPoint.y
}
private fun MoveTo.moveTo(target: Path) {
currentPoint.x = x
currentPoint.y = y
target.moveTo(x, y)
segmentPoint.x = currentPoint.x
segmentPoint.y = currentPoint.y
}
private fun RelativeLineTo.relativeLineTo(target: Path) {
target.relativeLineTo(dx, dy)
currentPoint.x += dx
currentPoint.y += dy
}
private fun LineTo.lineTo(target: Path) {
target.lineTo(x, y)
currentPoint.x = x
currentPoint.y = y
}
private fun RelativeHorizontalTo.relativeHorizontalTo(target: Path) {
target.relativeLineTo(dx, 0.0f)
currentPoint.x += dx
}
private fun HorizontalTo.horizontalTo(target: Path) {
target.lineTo(x, currentPoint.y)
currentPoint.x = x
}
private fun RelativeVerticalTo.relativeVerticalTo(target: Path) {
target.relativeLineTo(0.0f, dy)
currentPoint.y += dy
}
private fun VerticalTo.verticalTo(target: Path) {
target.lineTo(currentPoint.x, y)
currentPoint.y = y
}
private fun RelativeCurveTo.relativeCurveTo(target: Path) {
target.relativeCubicTo(
dx1, dy1,
dx2, dy2,
dx3, dy3
)
ctrlPoint.x = currentPoint.x + dx2
ctrlPoint.y = currentPoint.y + dy2
currentPoint.x += dx3
currentPoint.y += dy3
}
private fun CurveTo.curveTo(target: Path) {
target.cubicTo(
x1, y1,
x2, y2,
x3, y3
)
ctrlPoint.x = x2
ctrlPoint.y = y2
currentPoint.x = x3
currentPoint.y = y3
}
private fun RelativeReflectiveCurveTo.relativeReflectiveCurveTo(
prevIsCurve: Boolean,
target: Path
) {
if (prevIsCurve) {
reflectiveCtrlPoint.x = currentPoint.x - ctrlPoint.x
reflectiveCtrlPoint.y = currentPoint.y - ctrlPoint.y
} else {
reflectiveCtrlPoint.reset()
}
target.relativeCubicTo(
reflectiveCtrlPoint.x, reflectiveCtrlPoint.y,
dx1, dy1,
dx2, dy2
)
ctrlPoint.x = currentPoint.x + dx1
ctrlPoint.y = currentPoint.y + dy1
currentPoint.x += dx2
currentPoint.y += dy2
}
private fun ReflectiveCurveTo.reflectiveCurveTo(prevIsCurve: Boolean, target: Path) {
if (prevIsCurve) {
reflectiveCtrlPoint.x = 2 * currentPoint.x - ctrlPoint.x
reflectiveCtrlPoint.y = 2 * currentPoint.y - ctrlPoint.y
} else {
reflectiveCtrlPoint.x = currentPoint.x
reflectiveCtrlPoint.y = currentPoint.y
}
target.cubicTo(
reflectiveCtrlPoint.x, reflectiveCtrlPoint.y,
x1, y1, x2, y2
)
ctrlPoint.x = x1
ctrlPoint.y = y1
currentPoint.x = x2
currentPoint.y = y2
}
private fun RelativeQuadTo.relativeQuadTo(target: Path) {
target.relativeQuadraticBezierTo(dx1, dy1, dx2, dy2)
ctrlPoint.x = currentPoint.x + dx1
ctrlPoint.y = currentPoint.y + dy1
currentPoint.x += dx2
currentPoint.y += dy2
}
private fun QuadTo.quadTo(target: Path) {
target.quadraticBezierTo(x1, y1, x2, y2)
ctrlPoint.x = x1
ctrlPoint.y = y1
currentPoint.x = x2
currentPoint.y = y2
}
private fun RelativeReflectiveQuadTo.relativeReflectiveQuadTo(
prevIsQuad: Boolean,
target: Path
) {
if (prevIsQuad) {
reflectiveCtrlPoint.x = currentPoint.x - ctrlPoint.x
reflectiveCtrlPoint.y = currentPoint.y - ctrlPoint.y
} else {
reflectiveCtrlPoint.reset()
}
target.relativeQuadraticBezierTo(
reflectiveCtrlPoint.x,
reflectiveCtrlPoint.y, dx, dy
)
ctrlPoint.x = currentPoint.x + reflectiveCtrlPoint.x
ctrlPoint.y = currentPoint.y + reflectiveCtrlPoint.y
currentPoint.x += dx
currentPoint.y += dy
}
private fun ReflectiveQuadTo.reflectiveQuadTo(prevIsQuad: Boolean, target: Path) {
if (prevIsQuad) {
reflectiveCtrlPoint.x = 2 * currentPoint.x - ctrlPoint.x
reflectiveCtrlPoint.y = 2 * currentPoint.y - ctrlPoint.y
} else {
reflectiveCtrlPoint.x = currentPoint.x
reflectiveCtrlPoint.y = currentPoint.y
}
target.quadraticBezierTo(
reflectiveCtrlPoint.x,
reflectiveCtrlPoint.y, x, y
)
ctrlPoint.x = reflectiveCtrlPoint.x
ctrlPoint.y = reflectiveCtrlPoint.y
currentPoint.x = x
currentPoint.y = y
}
private fun RelativeArcTo.relativeArcTo(target: Path) {
val arcStartX = arcStartDx + currentPoint.x
val arcStartY = arcStartDy + currentPoint.y
drawArc(
target,
currentPoint.x.toDouble(),
currentPoint.y.toDouble(),
arcStartX.toDouble(),
arcStartY.toDouble(),
horizontalEllipseRadius.toDouble(),
verticalEllipseRadius.toDouble(),
theta.toDouble(),
isMoreThanHalf,
isPositiveArc
)
currentPoint.x = arcStartX
currentPoint.y = arcStartY
ctrlPoint.x = currentPoint.x
ctrlPoint.y = currentPoint.y
}
private fun ArcTo.arcTo(target: Path) {
drawArc(
target,
currentPoint.x.toDouble(),
currentPoint.y.toDouble(),
arcStartX.toDouble(),
arcStartY.toDouble(),
horizontalEllipseRadius.toDouble(),
verticalEllipseRadius.toDouble(),
theta.toDouble(),
isMoreThanHalf,
isPositiveArc
)
currentPoint.x = arcStartX
currentPoint.y = arcStartY
ctrlPoint.x = currentPoint.x
ctrlPoint.y = currentPoint.y
}
private fun drawArc(
p: Path,
x0: Double,
y0: Double,
x1: Double,
y1: Double,
a: Double,
b: Double,
theta: Double,
isMoreThanHalf: Boolean,
isPositiveArc: Boolean
) {
/* Convert rotation angle from degrees to radians */
val thetaD = theta.toRadians()
/* Pre-compute rotation matrix entries */
val cosTheta = cos(thetaD)
val sinTheta = sin(thetaD)
/* Transform (x0, y0) and (x1, y1) into unit space */
/* using (inverse) rotation, followed by (inverse) scale */
val x0p = (x0 * cosTheta + y0 * sinTheta) / a
val y0p = (-x0 * sinTheta + y0 * cosTheta) / b
val x1p = (x1 * cosTheta + y1 * sinTheta) / a
val y1p = (-x1 * sinTheta + y1 * cosTheta) / b
/* Compute differences and averages */
val dx = x0p - x1p
val dy = y0p - y1p
val xm = (x0p + x1p) / 2
val ym = (y0p + y1p) / 2
/* Solve for intersecting unit circles */
val dsq = dx * dx + dy * dy
if (dsq == 0.0) {
return /* Points are coincident */
}
val disc = 1.0 / dsq - 1.0 / 4.0
if (disc < 0.0) {
val adjust = (sqrt(dsq) / 1.99999).toFloat()
drawArc(
p, x0, y0, x1, y1, a * adjust,
b * adjust, theta, isMoreThanHalf, isPositiveArc
)
return /* Points are too far apart */
}
val s = sqrt(disc)
val sdx = s * dx
val sdy = s * dy
var cx: Double
var cy: Double
if (isMoreThanHalf == isPositiveArc) {
cx = xm - sdy
cy = ym + sdx
} else {
cx = xm + sdy
cy = ym - sdx
}
val eta0 = atan2(y0p - cy, x0p - cx)
val eta1 = atan2(y1p - cy, x1p - cx)
var sweep = eta1 - eta0
if (isPositiveArc != (sweep >= 0)) {
if (sweep > 0) {
sweep -= 2 * PI
} else {
sweep += 2 * PI
}
}
cx *= a
cy *= b
val tcx = cx
cx = cx * cosTheta - cy * sinTheta
cy = tcx * sinTheta + cy * cosTheta
arcToBezier(
p, cx, cy, a, b, x0, y0, thetaD,
eta0, sweep
)
}
/**
* Converts an arc to cubic Bezier segments and records them in p.
*
* @param p The target for the cubic Bezier segments
* @param cx The x coordinate center of the ellipse
* @param cy The y coordinate center of the ellipse
* @param a The radius of the ellipse in the horizontal direction
* @param b The radius of the ellipse in the vertical direction
* @param e1x E(eta1) x coordinate of the starting point of the arc
* @param e1y E(eta2) y coordinate of the starting point of the arc
* @param theta The angle that the ellipse bounding rectangle makes with horizontal plane
* @param start The start angle of the arc on the ellipse
* @param sweep The angle (positive or negative) of the sweep of the arc on the ellipse
*/
private fun arcToBezier(
p: Path,
cx: Double,
cy: Double,
a: Double,
b: Double,
e1x: Double,
e1y: Double,
theta: Double,
start: Double,
sweep: Double
) {
var eta1x = e1x
var eta1y = e1y
// Taken from equations at: http://spaceroots.org/documents/ellipse/node8.html
// and http://www.spaceroots.org/documents/ellipse/node22.html
// Maximum of 45 degrees per cubic Bezier segment
val numSegments = ceil(abs(sweep * 4 / PI)).toInt()
var eta1 = start
val cosTheta = cos(theta)
val sinTheta = sin(theta)
val cosEta1 = cos(eta1)
val sinEta1 = sin(eta1)
var ep1x = (-a * cosTheta * sinEta1) - (b * sinTheta * cosEta1)
var ep1y = (-a * sinTheta * sinEta1) + (b * cosTheta * cosEta1)
val anglePerSegment = sweep / numSegments
for (i in 0 until numSegments) {
val eta2 = eta1 + anglePerSegment
val sinEta2 = sin(eta2)
val cosEta2 = cos(eta2)
val e2x = cx + (a * cosTheta * cosEta2) - (b * sinTheta * sinEta2)
val e2y = cy + (a * sinTheta * cosEta2) + (b * cosTheta * sinEta2)
val ep2x = (-a * cosTheta * sinEta2) - (b * sinTheta * cosEta2)
val ep2y = (-a * sinTheta * sinEta2) + (b * cosTheta * cosEta2)
val tanDiff2 = tan((eta2 - eta1) / 2)
val alpha = sin(eta2 - eta1) * (sqrt(4 + 3.0 * tanDiff2 * tanDiff2) - 1) / 3
val q1x = eta1x + alpha * ep1x
val q1y = eta1y + alpha * ep1y
val q2x = e2x - alpha * ep2x
val q2y = e2y - alpha * ep2y
// TODO (njawad) figure out if this is still necessary?
// Adding this no-op call to workaround a proguard related issue.
// p.relativeLineTo(0.0, 0.0)
p.cubicTo(
q1x.toFloat(),
q1y.toFloat(),
q2x.toFloat(),
q2y.toFloat(),
e2x.toFloat(),
e2y.toFloat()
)
eta1 = eta2
eta1x = e2x
eta1y = e2y
ep1x = ep2x
ep1y = ep2y
}
}
private fun addNode(cmd: Char, args: FloatArray) {
nodes.addAll(cmd.toPathNodes(args))
}
private fun nextStart(s: String, end: Int): Int {
var index = end
var c: Char
while (index < s.length) {
c = s[index]
// Note that 'e' or 'E' are not valid path commands, but could be
// used for floating point numbers' scientific notation.
// Therefore, when searching for next command, we should ignore 'e'
// and 'E'.
if (((c - 'A') * (c - 'Z') <= 0 || (c - 'a') * (c - 'z') <= 0) &&
c != 'e' && c != 'E'
) {
return index
}
index++
}
return index
}
private fun getFloats(s: String): FloatArray {
if (s[0] == 'z' || s[0] == 'Z') {
return FloatArray(0)
}
val results = FloatArray(s.length)
var count = 0
var startPosition = 1
var endPosition: Int
val result = ExtractFloatResult()
val totalLength = s.length
// The startPosition should always be the first character of the
// current number, and endPosition is the character after the current
// number.
while (startPosition < totalLength) {
extract(s, startPosition, result)
endPosition = result.endPosition
if (startPosition < endPosition) {
results[count++] =
s.substring(startPosition, endPosition).toFloat()
}
if (result.endWithNegativeOrDot) {
// Keep the '-' or '.' sign with next number.
startPosition = endPosition
} else {
startPosition = endPosition + 1
}
}
return copyOfRange(results, 0, count)
}
private fun copyOfRange(original: FloatArray, start: Int, end: Int): FloatArray {
if (start > end) {
throw IllegalArgumentException()
}
val originalLength = original.size
if (start < 0 || start > originalLength) {
throw IndexOutOfBoundsException()
}
val resultLength = end - start
val copyLength = minOf(resultLength, originalLength - start)
val result = FloatArray(resultLength)
original.copyInto(result, 0, start, start + copyLength)
return result
}
private fun extract(s: String, start: Int, result: ExtractFloatResult) {
// Now looking for ' ', ',', '.' or '-' from the start.
var currentIndex = start
var foundSeparator = false
result.endWithNegativeOrDot = false
var secondDot = false
var isExponential = false
while (currentIndex < s.length) {
val isPrevExponential = isExponential
isExponential = false
val currentChar = s[currentIndex]
when (currentChar) {
' ', ',' -> foundSeparator = true
'-' ->
// The negative sign following a 'e' or 'E' is not a separator.
if (currentIndex != start && !isPrevExponential) {
foundSeparator = true
result.endWithNegativeOrDot = true
}
'.' ->
if (!secondDot) {
secondDot = true
} else {
// This is the second dot, and it is considered as a separator.
foundSeparator = true
result.endWithNegativeOrDot = true
}
'e', 'E' -> isExponential = true
}
if (foundSeparator) {
break
}
currentIndex++
}
// When there is nothing found, then we put the end position to the end
// of the string.
result.endPosition = currentIndex
}
private data class ExtractFloatResult(
// We need to return the position of the next separator and whether the
// next float starts with a '-' or a '.'.
var endPosition: Int = 0,
var endWithNegativeOrDot: Boolean = false
)
private fun Float.toRadians(): Float = this / 180f * PI.toFloat()
private fun Double.toRadians(): Double = this / 180 * PI
} | apache-2.0 | 69e131ca006f1214b09c543fe58794f6 | 32.562791 | 99 | 0.572874 | 4.117748 | false | false | false | false |
androidx/androidx | fragment/fragment-lint/src/main/java/androidx/fragment/lint/LintUtils.kt | 3 | 2831 | /*
* 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.fragment.lint
import com.android.tools.lint.detector.api.JavaContext
import com.intellij.psi.PsiType
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UQualifiedReferenceExpression
/**
* Checks if the [PsiType] is a subclass of class with canonical name [superName].
*
* @param context The context of the lint request.
* @param superName The canonical name to check that the [PsiType] is a subclass of.
* @param strict Whether [superName] is inclusive.
*/
internal fun PsiType?.extends(
context: JavaContext,
superName: String,
strict: Boolean = false
): Boolean = context.evaluator.extendsClass(PsiTypesUtil.getPsiClass(this), superName, strict)
/**
* Walks up the uastParent hierarchy from this element.
*/
internal fun UElement.walkUp(): Sequence<UElement> = generateSequence(uastParent) { it.uastParent }
/**
* This is useful if you're in a nested call expression and want to find the nearest parent while ignoring this call.
*
* For example, if you have the following two cases of a `foo()` expression:
* - `checkNotNull(fragment.foo())`
* - `checkNotNull(foo())` // if foo() is a local function
*
* Calling this from `foo()` in both cases will drop you at the outer `checkNotNull()` expression.
*/
val UElement.nearestNonQualifiedReferenceParent: UElement?
get() = walkUp().first {
it !is UQualifiedReferenceExpression
}
/**
* @see [fullyQualifiedNearestParentOrNull]
*/
internal fun UElement.fullyQualifiedNearestParent(includeSelf: Boolean = true): UElement {
return fullyQualifiedNearestParentOrNull(includeSelf)!!
}
/**
* Given an element, returns the nearest fully qualified parent.
*
* Examples where [this] is a `UCallExpression` representing `bar()`:
* - `Foo.bar()` -> `Foo.bar()`
* - `bar()` -> `bar()`
*
* @param includeSelf Whether or not to include [this] element in the checks.
*/
internal fun UElement.fullyQualifiedNearestParentOrNull(includeSelf: Boolean = true): UElement? {
val node = if (includeSelf) this else uastParent ?: return null
return if (node is UQualifiedReferenceExpression) {
node.uastParent
} else {
node
}
} | apache-2.0 | dc0617b8bd99c12c9e4cf50f1d741009 | 34.4 | 117 | 0.729424 | 4.212798 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt | 4 | 4083 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.util.classMembers.MemberInfo
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class KotlinMemberInfo @JvmOverloads constructor(
member: KtNamedDeclaration,
val isSuperClass: Boolean = false,
val isCompanionMember: Boolean = false
) : MemberInfoBase<KtNamedDeclaration>(member) {
companion object {
private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
modifiers = setOf(DescriptorRendererModifier.INNER)
}
}
init {
val memberDescriptor = member.resolveToDescriptorWrapperAware()
isStatic = member.parent is KtFile
if ((member is KtClass || member is KtPsiClassWrapper) && isSuperClass) {
if (member.isInterfaceClass()) {
displayName = RefactoringBundle.message("member.info.implements.0", member.name)
overrides = false
} else {
displayName = RefactoringBundle.message("member.info.extends.0", member.name)
overrides = true
}
} else {
displayName = RENDERER.render(memberDescriptor)
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
displayName = KotlinBundle.message("member.info.abstract.0", displayName)
}
if (isCompanionMember) {
displayName = KotlinBundle.message("member.info.companion.0", displayName)
}
val overriddenDescriptors = (memberDescriptor as? CallableMemberDescriptor)?.overriddenDescriptors ?: emptySet()
if (overriddenDescriptors.isNotEmpty()) {
overrides = overriddenDescriptors.any { it.modality != Modality.ABSTRACT }
}
}
}
}
fun lightElementForMemberInfo(declaration: KtNamedDeclaration?): PsiMember? {
return when (declaration) {
is KtNamedFunction -> declaration.getRepresentativeLightMethod()
is KtProperty, is KtParameter -> declaration.toLightElements().let {
it.firstIsInstanceOrNull<PsiMethod>() ?: it.firstIsInstanceOrNull<PsiField>()
} as PsiMember?
is KtClassOrObject -> declaration.toLightClass()
is KtPsiClassWrapper -> declaration.psiClass
else -> null
}
}
fun MemberInfoBase<out KtNamedDeclaration>.toJavaMemberInfo(): MemberInfo? {
val declaration = member
val psiMember: PsiMember? = lightElementForMemberInfo(declaration)
val info = MemberInfo(psiMember ?: return null, psiMember is PsiClass && overrides != null, null)
info.isToAbstract = isToAbstract
info.isChecked = isChecked
return info
}
fun MemberInfo.toKotlinMemberInfo(): KotlinMemberInfo? {
val declaration = member.unwrapped as? KtNamedDeclaration ?: return null
return KotlinMemberInfo(declaration, declaration is KtClass && overrides != null).apply {
this.isToAbstract = [email protected]
}
}
| apache-2.0 | 1cbb9a60e4154449e58ff25182d87e58 | 43.380435 | 158 | 0.729121 | 5.268387 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/EntityStorage.kt | 2 | 12302 | // 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.storage
import com.intellij.workspaceModel.storage.impl.EntityStorageSnapshotImpl
import com.intellij.workspaceModel.storage.impl.MutableEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityExtensionDelegate
import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.deft.Obj
import org.jetbrains.deft.annotations.Abstract
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
/**
* A prototype of a storage system for the project model which stores data in typed entities. Entities are represented by interfaces
* implementing WorkspaceEntity interface.
*/
/**
* A base interface for entities. An entity may have properties of the following types:
* * primitive types;
* * String;
* * enum;
* * [VirtualFileUrl];
* * [WorkspaceEntity] or [SymbolicEntityId];
* * [List] of another allowed type;
* * [Map] of another allowed types where key is NOT a WorkspaceEntity;
* * another data class with properties of the allowed types (references to entities must be wrapped into [EntityReference]);
* * sealed abstract class where all implementations satisfy these requirements.
*
* Currently, the entities are representing by classes inheriting from WorkspaceEntityBase, and need to have a separate class with `Data`
* suffix extending WorkspaceEntityData to store the actual data.
*
* # Equality and identity
*
* Entities follow the java equality approach where by default objects are compared by identity. So, two different entities are never equal.
* However, even requesting the same entity multiple times may return different java objects, they are still considered as equal.
*
* Entities from independent snapshots are never equal.
*
* Requesting the same entity from two different snapshots will return two different java objects.
* However, they are equal if one snapshot is a modification of another, and this particular entity was not modified.
*
* This is the default behaviour of `equals` method that may be changed for any particular inheritor.
*
* ### Examples:
* ```kotlin
* val entityOne = builderOne.addEntity("data")
* val entityTwo = builderTwo.addEntity("data")
* entityOne != entityTwo
* ```
*
* ```kotlin
* val entityOne = snapshot.getEntity()
* val entityTwo = snapshot.getEntity()
* entityOne !== entityTwo
* entityOne == entityTwo
* ```
*
* ```kotlin
* val entityA = snapshot.getEntityA()
* val entityB = snapshot.getEntityB()
* entityA != entityB
* ```
*
* ```kotlin
* val entityAOne = snapshot1.getEntityA()
* val snapshot2 = snapshot1.toBuilder().modifyEntityB().toSnapshot()
* val entityATwo = snapshot2.getEntityA()
* entityAOne == entityATwo
* ```
*
* ```kotlin
* val entityAOne = snapshot1.getEntityA()
* val snapshot2 = snapshot1.toBuilder().modifyEntityA().toSnapshot()
* val entityATwo = snapshot2.getEntityA()
* entityAOne != entityATwo
* ```
*/
@Abstract
interface WorkspaceEntity : Obj {
val entitySource: EntitySource
fun <E : WorkspaceEntity> createReference(): EntityReference<E>
fun getEntityInterface(): Class<out WorkspaceEntity>
companion object {
inline fun <reified T> extension(): WorkspaceEntityExtensionDelegate<T> {
return WorkspaceEntityExtensionDelegate()
}
}
/**
* Base interface for modifiable variant of [Unmodifiable] entity. The implementation can be used to [create a new entity][MutableEntityStorage.addEntity]
* or [modify an existing value][MutableEntityStorage.modifyEntity].
*
* Currently, the class must inherit from ModifiableWorkspaceEntityBase.
*/
@Abstract
interface Builder<Unmodifiable : WorkspaceEntity> : WorkspaceEntity {
override var entitySource: EntitySource
}
}
/**
* Add this annotation to the field to mark this fields as a key field for replaceBySource operation.
* Entities will be compared based on these fields.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.TYPE)
annotation class EqualsBy
/**
* Declares a place from which an entity came.
* Usually contains enough information to identify a project location.
* An entity source must be serializable along with entities, so there are some limits to implementation.
* It must be a data class which contains read-only properties of the following types:
* * primitive types;
* * String;
* * enum;
* * [List] of another allowed type;
* * another data class with properties of the allowed types;
* * sealed abstract class where all implementations satisfy these requirements.
*/
interface EntitySource {
val virtualFileUrl: VirtualFileUrl?
get() = null
}
/**
* Marker interface to represent entities which properties aren't loaded and which were added to the storage because other entities requires
* them. Entities which sources implements this interface don't replace existing entities when [MutableEntityStorage.replaceBySource]
* is called.
*
* For example if we have `FacetEntity` which requires `ModuleEntity`, and need to load facet configuration from *.iml file and load the module
* configuration from some other source, we may use this interface to mark `entitySource` for `ModuleEntity`. This way when content of *.iml
* file is applied to the model via [MutableEntityStorage.replaceBySource], it won't overwrite actual configuration
* of `ModuleEntity`.
*/
interface DummyParentEntitySource : EntitySource
/**
* Represents a reference to an entity inside of [WorkspaceEntity].
*
* The reference can be obtained via [EntityStorage.createReference].
*
* The reference will return the same entity for the same storage, but the changes in storages should be tracked if the client want to
* use this reference between different storages. For example, if the referred entity was removed from the storage, this reference may
* return null, but it can also return a different (newly added) entity.
*/
abstract class EntityReference<out E : WorkspaceEntity> {
abstract fun resolve(storage: EntityStorage): E?
}
/**
* A base class for typed hierarchical entity IDs. An implementation must be a data class which contains read-only properties of the following types:
* * primitive types,
* * String,
* * enum,
* * another data class with properties of the allowed types;
* * sealed abstract class where all implementations satisfy these requirements.
*/
interface SymbolicEntityId<out E : WorkspaceEntityWithSymbolicId> {
/** Text which can be shown in an error message if id cannot be resolved */
val presentableName: String
fun resolve(storage: EntityStorage): E? = storage.resolve(this)
override fun toString(): String
}
@Abstract
interface WorkspaceEntityWithSymbolicId : WorkspaceEntity {
val symbolicId: SymbolicEntityId<WorkspaceEntityWithSymbolicId>
}
interface EntityStorage {
fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E>
fun <E : WorkspaceEntity> entitiesAmount(entityClass: Class<E>): Int
fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>, property: KProperty1<R, EntityReference<E>>): Sequence<R>
fun <E : WorkspaceEntityWithSymbolicId, R : WorkspaceEntity> referrers(id: SymbolicEntityId<E>, entityClass: Class<R>): Sequence<R>
fun <E : WorkspaceEntityWithSymbolicId> resolve(id: SymbolicEntityId<E>): E?
operator fun <E : WorkspaceEntityWithSymbolicId> contains(id: SymbolicEntityId<E>): Boolean
/**
* Please select a name for your mapping in a form `<product_id>.<mapping_name>`.
* E.g.:
* - intellij.modules.bridge
* - intellij.facets.bridge
* - rider.backend.id
*/
fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T>
fun getVirtualFileUrlIndex(): VirtualFileUrlIndex
fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>
fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E>
fun toSnapshot(): EntityStorageSnapshot
}
/**
* Read-only interface to a storage. Use [MutableEntityStorage] to modify it.
*/
interface EntityStorageSnapshot : EntityStorage {
companion object {
fun empty(): EntityStorageSnapshot = EntityStorageSnapshotImpl.EMPTY
}
}
/**
* Writeable interface to a storage. Use it if you need to build a storage from scratch or modify an existing storage in a way which requires
* reading its state after modifications.
*/
interface MutableEntityStorage : EntityStorage {
@Deprecated("The name may be misleading, use !hasChanges() instead", ReplaceWith("!hasChanges()"))
fun isEmpty(): Boolean
/**
* Returns `true` if there are changes recorded in this storage after its creation. Note, that this method may return `true` if these
* changes actually don't modify the resulting set of entities, you may use [hasSameEntities] to perform more sophisticated check.
*/
fun hasChanges(): Boolean
infix fun <T : WorkspaceEntity> addEntity(entity: T): T
fun <M : WorkspaceEntity.Builder<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T
/**
* Remove the entity from the builder.
* Returns true if the entity was removed, false if the entity was not in the storage
*/
fun removeEntity(e: WorkspaceEntity): Boolean
fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: EntityStorage)
/**
* Return changes in entities recorded in this instance. [original] parameter is used to get the old instances of modified
* and removed entities.
*/
fun collectChanges(original: EntityStorage): Map<Class<*>, List<EntityChange<*>>>
fun addDiff(diff: MutableEntityStorage)
/**
* Returns `true` if this instance contains entities with the same properties as [original] storage it was created from.
* The difference from [hasChanges] is that this method will return `true` in cases when an entity was removed, and then a new entity
* with the same properties was added.
*/
fun hasSameEntities(original: EntityStorage): Boolean
/**
* Please see [EntityStorage.getExternalMapping] for naming conventions
*/
fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T>
fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex
val modificationCount: Long
@ApiStatus.Internal
fun setUseNewRbs(value: Boolean)
companion object {
@JvmStatic
fun create(): MutableEntityStorage = MutableEntityStorageImpl.create()
@JvmStatic
fun from(storage: EntityStorage): MutableEntityStorage = MutableEntityStorageImpl.from(storage)
}
}
fun EntityStorage.toBuilder(): MutableEntityStorage {
return MutableEntityStorage.from(this)
}
sealed class EntityChange<T : WorkspaceEntity> {
/**
* Returns the entity which was removed or replaced in the change.
*/
abstract val oldEntity: T?
/**
* Returns the entity which was added or used as a replacement in the change.
*/
abstract val newEntity: T?
data class Added<T : WorkspaceEntity>(val entity: T) : EntityChange<T>() {
override val oldEntity: T?
get() = null
override val newEntity: T
get() = entity
}
data class Removed<T : WorkspaceEntity>(val entity: T) : EntityChange<T>() {
override val oldEntity: T
get() = entity
override val newEntity: T?
get() = null
}
data class Replaced<T : WorkspaceEntity>(override val oldEntity: T, override val newEntity: T) : EntityChange<T>()
}
open class NotGeneratedRuntimeException(message: String) : RuntimeException(message)
class NotGeneratedMethodRuntimeException(val methodName: String)
: NotGeneratedRuntimeException("Method `$methodName` uses default implementation. Please regenerate entities")
// Internal tools, not sure if we can open them
/**
* Return same entity, but in different entity storage. Fail if no entity
*/
internal fun <T: WorkspaceEntity> T.from(storage: EntityStorage): T {
return this.createReference<T>().resolve(storage)!!
}
| apache-2.0 | 035ce54ceadf3f486eef04a6e237f3a3 | 38.55627 | 156 | 0.750772 | 4.624812 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUClass.kt | 4 | 2716 | // 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.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForScript
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.uast.*
@ApiStatus.Internal
class KotlinUClass(
psi: KtLightClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
override val ktClass = psi.kotlinOrigin
override val javaPsi: KtLightClass = psi
override val sourcePsi: KtClassOrObject? = ktClass
override val psi = unwrap<UClass, PsiClass>(psi)
override fun getSourceElement() = sourcePsi ?: this
override fun getOriginalElement(): PsiElement? = super.getOriginalElement()
override fun getNameIdentifier(): PsiIdentifier = UastLightIdentifier(psi, ktClass)
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor: UIdentifier? by lz {
getIdentifierSourcePsi()?.let { KotlinUIdentifier(nameIdentifier, it, this) }
}
private fun getIdentifierSourcePsi(): PsiElement? {
ktClass?.nameIdentifier?.let { return it }
(ktClass as? KtObjectDeclaration)?.getObjectKeyword()?.let { return it }
return null
}
override fun getInnerClasses(): Array<UClass> {
// filter DefaultImpls to avoid processing same methods from original interface multiple times
// filter Enum entry classes to avoid duplication with PsiEnumConstant initializer class
return psi.innerClasses.filter {
it.name != JvmAbi.DEFAULT_IMPLS_CLASS_NAME && !it.isEnumEntryLightClass
}.mapNotNull {
languagePlugin?.convertOpt<UClass>(it, this)
}.toTypedArray()
}
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getMethods(): Array<UMethod> = computeMethods()
companion object {
fun create(psi: KtLightClass, containingElement: UElement?): UClass = when (psi) {
is PsiAnonymousClass -> KotlinUAnonymousClass(psi, containingElement)
is KtLightClassForScript -> KotlinScriptUClass(psi, containingElement)
else -> KotlinUClass(psi, containingElement)
}
}
}
| apache-2.0 | 69e3069b62621b9dbb656a726c15ec56 | 38.941176 | 158 | 0.730854 | 5.057728 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/AnnotationPresentationInfo.kt | 1 | 8395 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.IntentionActionWithOptions
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixUpdater
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.SuppressableProblemGroup
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.util.containers.MultiMap
import com.intellij.xml.util.XmlStringUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
class AnnotationPresentationInfo(
val ranges: List<TextRange>,
@Nls val nonDefaultMessage: String? = null,
val highlightType: ProblemHighlightType? = null,
val textAttributes: TextAttributesKey? = null
) {
companion object {
private const val KOTLIN_COMPILER_WARNING_ID = "KotlinCompilerWarningOptions"
}
fun processDiagnostics(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoBuilderByDiagnostic: MutableMap<Diagnostic, HighlightInfo>? = null,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
fixesMap: MultiMap<Diagnostic, IntentionAction>?,
calculatingInProgress: Boolean
) {
for (range in ranges) {
for (diagnostic in diagnostics) {
create(diagnostic, range) { info ->
holder.add(info)
highlightInfoBuilderByDiagnostic?.put(diagnostic, info)
if (fixesMap != null) {
applyFixes(fixesMap, diagnostic, info)
}
if (calculatingInProgress && highlightInfoByTextRange?.containsKey(range) == false) {
highlightInfoByTextRange[range] = info
QuickFixAction.registerQuickFixAction(info, CalculatingIntentionAction())
}
}
}
}
}
internal fun applyFixes(
quickFixes: MultiMap<Diagnostic, IntentionAction>,
diagnostic: Diagnostic,
info: HighlightInfo
) {
val isWarning = diagnostic.severity == Severity.WARNING
val isError = diagnostic.severity == Severity.ERROR
val element = diagnostic.psiElement
val fixes = quickFixes[diagnostic].takeIf { it.isNotEmpty() }
?: if (isWarning) listOf(CompilerWarningIntentionAction(diagnostic.factory.name)) else emptyList()
val keyForSuppressOptions = if (isWarning) {
HighlightDisplayKey.findOrRegister(
KOTLIN_COMPILER_WARNING_ID,
KotlinBaseFe10HighlightingBundle.message("kotlin.compiler.warning")
)
} else null
for (fix in fixes) {
if (fix !is IntentionAction) {
continue
}
if (fix == RegisterQuickFixesLaterIntentionAction) {
element.reference?.let {
UnresolvedReferenceQuickFixUpdater.getInstance(element.project).registerQuickFixesLater(it, info)
}
continue
}
val options = mutableListOf<IntentionAction>()
if (fix is IntentionActionWithOptions) {
options += fix.options
}
val problemGroup = info.problemGroup
if (problemGroup is SuppressableProblemGroup) {
options += problemGroup.getSuppressActions(element).mapNotNull { it as IntentionAction }
}
val message = KotlinBaseFe10HighlightingBundle.message(if (isError) "kotlin.compiler.error" else "kotlin.compiler.warning")
info.registerFix(fix, options, message, null, keyForSuppressOptions)
}
}
private fun create(diagnostic: Diagnostic, range: TextRange, consumer: (HighlightInfo) -> Unit) {
val message = nonDefaultMessage ?: getDefaultMessage(diagnostic)
HighlightInfo
.newHighlightInfo(toHighlightInfoType(highlightType, diagnostic.severity))
.range(range)
.description(message)
.escapedToolTip(getMessage(diagnostic))
.also { builder -> textAttributes?.let(builder::textAttributes) ?: convertSeverityTextAttributes(highlightType, diagnostic.severity)?.let(builder::textAttributes) }
.also {
if (diagnostic.severity == Severity.WARNING) {
it.problemGroup(KotlinSuppressableWarningProblemGroup(diagnostic.factory))
}
}
.createUnconditionally()
.also(consumer)
}
@NlsContexts.Tooltip
private fun getMessage(diagnostic: Diagnostic): String {
var message = IdeErrorMessages.render(diagnostic)
if (isApplicationInternalMode() || isUnitTestMode()) {
val factoryName = diagnostic.factory.name
message = if (message.startsWith("<html>")) {
@Suppress("HardCodedStringLiteral")
"<html>[$factoryName] ${message.substring("<html>".length)}"
} else {
"[$factoryName] $message"
}
}
if (!message.startsWith("<html>")) {
message = "<html><body>${XmlStringUtil.escapeString(message)}</body></html>"
}
return message
}
private fun getDefaultMessage(diagnostic: Diagnostic): String {
val message = DefaultErrorMessages.render(diagnostic)
return if (isApplicationInternalMode() || isUnitTestMode()) {
"[${diagnostic.factory.name}] $message"
} else {
message
}
}
private fun toHighlightInfoType(highlightType: ProblemHighlightType?, severity: Severity): HighlightInfoType =
when (highlightType) {
ProblemHighlightType.LIKE_UNUSED_SYMBOL -> HighlightInfoType.UNUSED_SYMBOL
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL -> HighlightInfoType.WRONG_REF
ProblemHighlightType.LIKE_DEPRECATED -> HighlightInfoType.DEPRECATED
ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL -> HighlightInfoType.MARKED_FOR_REMOVAL
else -> convertSeverity(highlightType, severity)
}
private fun convertSeverity(highlightType: ProblemHighlightType?, severity: Severity): HighlightInfoType =
when (severity) {
Severity.ERROR -> HighlightInfoType.ERROR
Severity.WARNING -> {
if (highlightType == ProblemHighlightType.WEAK_WARNING) {
HighlightInfoType.WEAK_WARNING
} else HighlightInfoType.WARNING
}
Severity.INFO -> HighlightInfoType.WEAK_WARNING
else -> HighlightInfoType.INFORMATION
}
private fun convertSeverityTextAttributes(highlightType: ProblemHighlightType?, severity: Severity): TextAttributesKey? =
when (highlightType) {
null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING ->
when (severity) {
Severity.ERROR -> CodeInsightColors.ERRORS_ATTRIBUTES
Severity.WARNING -> CodeInsightColors.WARNINGS_ATTRIBUTES
Severity.INFO -> CodeInsightColors.WARNINGS_ATTRIBUTES
else -> null
}
ProblemHighlightType.GENERIC_ERROR -> CodeInsightColors.ERRORS_ATTRIBUTES
else -> null
}
}
| apache-2.0 | ee283241f5cb0ccc505a1a5c82fe05f8 | 43.184211 | 176 | 0.664086 | 5.47619 | false | false | false | false |
GunoH/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkTreeConflictResolvedAction.kt | 5 | 4317 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.ChangesUtil.getAfterPath
import com.intellij.openapi.vcs.changes.ChangesUtil.getBeforePath
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import org.jetbrains.idea.svn.ConflictState
import org.jetbrains.idea.svn.ConflictedSvnChange
import org.jetbrains.idea.svn.SvnBundle.message
import org.jetbrains.idea.svn.SvnLocallyDeletedChange
import org.jetbrains.idea.svn.SvnVcs
import org.jetbrains.idea.svn.api.Depth
private fun getConflict(e: AnActionEvent): Conflict? {
val changes = e.getData(VcsDataKeys.CHANGE_LEAD_SELECTION)
val locallyDeletedChanges = e.getData(ChangesListView.LOCALLY_DELETED_CHANGES)
if (locallyDeletedChanges.isNullOrEmpty()) {
return (changes?.singleOrNull() as? ConflictedSvnChange)?.let { ChangeConflict(it) }
}
if (changes.isNullOrEmpty()) {
return (locallyDeletedChanges.singleOrNull() as? SvnLocallyDeletedChange)?.let { LocallyDeletedChangeConflict(it) }
}
return null
}
class MarkTreeConflictResolvedAction : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.project
val conflict = getConflict(e)
val enabled = project != null && conflict?.conflictState?.isTree == true
e.presentation.isEnabledAndVisible = enabled
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val conflict = getConflict(e)!!
val result = Messages.showYesNoDialog(
project,
message("dialog.message.mark.tree.conflict.resolved.confirmation"),
message("dialog.title.mark.tree.conflict.resolved"),
Messages.getQuestionIcon()
)
if (result == Messages.YES) {
object : Task.Backgroundable(project, message("progress.title.mark.tree.conflict.resolved"), true) {
private var exception: VcsException? = null
override fun run(indicator: ProgressIndicator) {
val path = conflict.path
val vcs = SvnVcs.getInstance(project)
try {
vcs.getFactory(path.ioFile).createConflictClient().resolve(path.ioFile, Depth.EMPTY, false, false, true)
}
catch (e: VcsException) {
exception = e
}
VcsDirtyScopeManager.getInstance(project).filePathsDirty(conflict.getPathsToRefresh(), null)
}
override fun onSuccess() {
if (exception != null) {
AbstractVcsHelper.getInstance(project).showError(exception, message("dialog.title.mark.tree.conflict.resolved"))
}
}
}.queue()
}
}
}
private interface Conflict {
val path: FilePath
val conflictState: ConflictState
fun getPathsToRefresh(): Collection<FilePath>
}
private class ChangeConflict(val change: ConflictedSvnChange) : Conflict {
override val path: FilePath get() = change.treeConflictMarkHolder
override val conflictState: ConflictState get() = change.conflictState
override fun getPathsToRefresh(): Collection<FilePath> {
val beforePath = getBeforePath(change)
val afterPath = getAfterPath(change)
val isAddMoveRename = beforePath == null || change.isMoved || change.isRenamed
return listOfNotNull(beforePath, if (isAddMoveRename) afterPath else null)
}
}
private class LocallyDeletedChangeConflict(val change: SvnLocallyDeletedChange) : Conflict {
override val path: FilePath get() = change.path
override val conflictState: ConflictState get() = change.conflictState
override fun getPathsToRefresh(): Collection<FilePath> = listOf(path)
} | apache-2.0 | a73d57adad55d6e10875617b4d1d4048 | 36.877193 | 140 | 0.749595 | 4.37386 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/HintsBuffer.kt | 12 | 2522 | // 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.codeInsight.hints
import com.intellij.openapi.editor.Inlay
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import it.unimi.dsi.fastutil.ints.IntSet
/**
* Utility class to accumulate hints. Non thread-safe.
*/
class HintsBuffer {
val inlineHints = Int2ObjectOpenHashMap<MutableList<ConstrainedPresentation<*, HorizontalConstraints>>>()
internal val blockBelowHints = Int2ObjectOpenHashMap<MutableList<ConstrainedPresentation<*, BlockConstraints>>>()
internal val blockAboveHints = Int2ObjectOpenHashMap<MutableList<ConstrainedPresentation<*, BlockConstraints>>>()
internal fun mergeIntoThis(another: HintsBuffer) {
mergeIntoThis(inlineHints, another.inlineHints)
mergeIntoThis(blockBelowHints, another.blockBelowHints)
mergeIntoThis(blockAboveHints, another.blockAboveHints)
}
/**
* Counts all offsets of given [placement] which are not inside [other]
*/
internal fun countDisjointElements(other: IntSet, placement: Inlay.Placement): Int {
val map = getMap(placement)
var count = 0
val iterator = map.keys.iterator()
while (iterator.hasNext()) {
if (!other.contains(iterator.nextInt())) {
count++
}
}
return count
}
internal fun contains(offset: Int, placement: Inlay.Placement): Boolean {
return getMap(placement).contains(offset)
}
fun remove(offset: Int, placement: Inlay.Placement): MutableList<ConstrainedPresentation<*, *>>? {
return getMap(placement).remove(offset)
}
@Suppress("UNCHECKED_CAST")
private fun getMap(placement: Inlay.Placement) : Int2ObjectMap<MutableList<ConstrainedPresentation<*, *>>> {
return when (placement) {
Inlay.Placement.INLINE -> inlineHints
Inlay.Placement.ABOVE_LINE -> blockAboveHints
Inlay.Placement.BELOW_LINE -> blockBelowHints
Inlay.Placement.AFTER_LINE_END -> TODO()
} as Int2ObjectOpenHashMap<MutableList<ConstrainedPresentation<*, *>>>
}
}
private fun <V> mergeIntoThis(one: Int2ObjectMap<MutableList<V>>, another: Int2ObjectMap<MutableList<V>>) {
for (otherEntry in another.int2ObjectEntrySet()) {
val otherOffset = otherEntry.intKey
val current = one.get(otherOffset)
if (current == null) {
one.put(otherOffset, otherEntry.value)
}
else {
current.addAll(otherEntry.value)
}
}
} | apache-2.0 | 72fc4c3a54d414b336eb8a6bdc522ba4 | 36.102941 | 140 | 0.733941 | 4.231544 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinModuleDependencyUtils.kt | 2 | 5414 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("KotlinModuleDependencyUtils")
package org.jetbrains.kotlin.idea.base.projectStructure
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import org.jetbrains.kotlin.config.KotlinSourceRootType
import org.jetbrains.kotlin.config.SourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.buildSystemType
import org.jetbrains.kotlin.platform.TargetPlatform
@Service(Service.Level.PROJECT)
class ModuleDependencyCollector(private val project: Project) {
companion object {
private val LOG = Logger.getInstance(ModuleDependencyCollector::class.java)
fun getInstance(project: Project): ModuleDependencyCollector = project.service()
}
fun collectModuleDependencies(
module: Module,
platform: TargetPlatform,
sourceRootType: KotlinSourceRootType,
includeExportedDependencies: Boolean
): Collection<IdeaModuleInfo> {
val debugInfo = if (LOG.isDebugEnabled) ArrayList<String>() else null
val orderEnumerator = getOrderEnumerator(module, sourceRootType, includeExportedDependencies)
val dependencyFilter = when {
module.isHMPPEnabled -> HmppSourceModuleDependencyFilter(platform)
else -> NonHmppSourceModuleDependenciesFilter(platform)
}
val result = LinkedHashSet<IdeaModuleInfo>()
orderEnumerator.forEach { orderEntry ->
if (isApplicable(orderEntry, sourceRootType)) {
debugInfo?.add("Add entry ${orderEntry.presentableName}")
for (moduleInfo in collectModuleDependenciesForOrderEntry(orderEntry, sourceRootType)) {
if (dependencyFilter.isSupportedDependency(moduleInfo)) {
debugInfo?.add("Add module ${moduleInfo.displayedName}")
result.add(moduleInfo)
}
}
} else {
debugInfo?.add("Skip entry ${orderEntry.presentableName}")
}
return@forEach true
}
if (debugInfo != null) {
val debugString = buildString {
appendLine("Building dependency list for module ${this}")
appendLine("Platform = ${platform}, isForTests = ${sourceRootType == TestSourceKotlinRootType}")
debugInfo.joinTo(this, separator = "; ", prefix = "[", postfix = "]")
}
LOG.debug(debugString)
}
return result
}
private fun getOrderEnumerator(
module: Module,
sourceRootType: KotlinSourceRootType,
includeExportedDependencies: Boolean,
): OrderEnumerator {
val rootManager = ModuleRootManager.getInstance(module)
val dependencyEnumerator = rootManager.orderEntries().compileOnly()
if (includeExportedDependencies) {
dependencyEnumerator.recursively().exportedOnly()
}
if (sourceRootType == SourceKotlinRootType && module.buildSystemType == BuildSystemType.JPS) {
dependencyEnumerator.productionOnly()
}
return dependencyEnumerator
}
private fun isApplicable(orderEntry: OrderEntry, sourceRootType: KotlinSourceRootType): Boolean {
if (!orderEntry.isValid) {
return false
}
return orderEntry !is ExportableOrderEntry
|| sourceRootType == TestSourceKotlinRootType
|| orderEntry is ModuleOrderEntry && orderEntry.isProductionOnTestDependency
|| orderEntry.scope.isForProductionCompile
}
private fun collectModuleDependenciesForOrderEntry(orderEntry: OrderEntry, sourceRootType: KotlinSourceRootType): List<IdeaModuleInfo> {
fun Module.toInfos() = sourceModuleInfos.filter {
sourceRootType == TestSourceKotlinRootType || it is ModuleProductionSourceInfo
}
return when (orderEntry) {
is ModuleSourceOrderEntry -> {
orderEntry.ownerModule.toInfos()
}
is ModuleOrderEntry -> {
val module = orderEntry.module ?: return emptyList()
if (sourceRootType == SourceKotlinRootType && orderEntry.isProductionOnTestDependency) {
listOfNotNull(module.testSourceInfo)
} else {
module.toInfos()
}
}
is LibraryOrderEntry -> {
val library = orderEntry.library ?: return listOf()
LibraryInfoCache.getInstance(project)[library]
}
is JdkOrderEntry -> {
val sdk = orderEntry.jdk ?: return listOf()
listOfNotNull(SdkInfo(project, sdk))
}
else -> {
throw IllegalStateException("Unexpected order entry $orderEntry")
}
}
}
} | apache-2.0 | 49d0a4bdd3b5c66aa42e37f1c477c6f9 | 38.23913 | 140 | 0.656446 | 5.827772 | false | true | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/RowImpl.kt | 1 | 16058 | // 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.ui.dsl.builder.impl
import com.intellij.BundleBase
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.util.PopupUtil
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.*
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.components.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.VerticalGaps
import com.intellij.ui.layout.*
import com.intellij.ui.popup.PopupState
import com.intellij.util.Function
import com.intellij.util.MathUtil
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.event.ActionEvent
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.util.*
import javax.swing.*
@ApiStatus.Internal
internal open class RowImpl(private val dialogPanelConfig: DialogPanelConfig,
private val panelContext: PanelContext,
val parent: PanelImpl,
rowLayout: RowLayout) : Row {
var rowLayout = rowLayout
private set
var resizableRow = false
private set
var rowComment: JComponent? = null
private set
var topGap: TopGap? = null
private set
/**
* Used if topGap is not set, skipped for first row
*/
var internalTopGap = 0
var bottomGap: BottomGap? = null
private set
/**
* Used if bottomGap is not set, skipped for last row
*/
var internalBottomGap = 0
val cells = mutableListOf<CellBaseImpl<*>?>()
private var visible = true
private var enabled = true
override fun layout(rowLayout: RowLayout): RowImpl {
this.rowLayout = rowLayout
return this
}
override fun resizableRow(): RowImpl {
resizableRow = true
return this
}
override fun rowComment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int): Row {
this.rowComment = ComponentPanelBuilder.createCommentComponent(comment, true, maxLineLength, true)
return this
}
override fun rowComment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int, action: HyperlinkEventAction): RowImpl {
this.rowComment = createComment(comment, maxLineLength, action)
return this
}
override fun <T : JComponent> cell(component: T, viewComponent: JComponent): CellImpl<T> {
val result = CellImpl(dialogPanelConfig, component, this, viewComponent)
cells.add(result)
return result
}
override fun <T : JComponent> cell(component: T): CellImpl<T> {
return cell(component, component)
}
override fun cell() {
cells.add(null)
}
override fun <T : JComponent> scrollCell(component: T): CellImpl<T> {
return cell(component, JBScrollPane(component))
}
fun cell(cell: CellBaseImpl<*>) {
cells.add(cell)
}
override fun placeholder(): PlaceholderImpl {
val result = PlaceholderImpl(this)
cells.add(result)
return result
}
override fun enabled(isEnabled: Boolean): RowImpl {
enabled = isEnabled
if (parent.isEnabled()) {
doEnabled(enabled)
}
return this
}
fun enabledFromParent(parentEnabled: Boolean): RowImpl {
doEnabled(parentEnabled && enabled)
return this
}
fun isEnabled(): Boolean {
return enabled && parent.isEnabled()
}
override fun enabledIf(predicate: ComponentPredicate): RowImpl {
enabled(predicate())
predicate.addListener { enabled(it) }
return this
}
override fun visible(isVisible: Boolean): RowImpl {
visible = isVisible
if (parent.isVisible()) {
doVisible(visible)
}
return this
}
override fun visibleIf(predicate: ComponentPredicate): Row {
visible(predicate())
predicate.addListener { visible(it) }
return this
}
fun visibleFromParent(parentVisible: Boolean): RowImpl {
doVisible(parentVisible && visible)
return this
}
fun isVisible(): Boolean {
return visible && parent.isVisible()
}
override fun topGap(topGap: TopGap): RowImpl {
this.topGap = topGap
return this
}
override fun bottomGap(bottomGap: BottomGap): RowImpl {
this.bottomGap = bottomGap
return this
}
override fun panel(init: Panel.() -> Unit): PanelImpl {
val result = PanelImpl(dialogPanelConfig, parent.spacingConfiguration, this)
result.init()
cells.add(result)
return result
}
override fun checkBox(@NlsContexts.Checkbox text: String): CellImpl<JBCheckBox> {
return cell(JBCheckBox(text))
}
override fun radioButton(@NlsContexts.RadioButton text: String): Cell<JBRadioButton> {
return radioButton(text, null)
}
override fun radioButton(text: String, value: Any?): Cell<JBRadioButton> {
val buttonsGroup = dialogPanelConfig.context.getButtonsGroup() ?: throw UiDslException(
"Button group must be defined before using radio button")
val result = cell(JBRadioButton(text))
buttonsGroup.add(result, value)
return result
}
override fun button(@NlsContexts.Button text: String, actionListener: (event: ActionEvent) -> Unit): CellImpl<JButton> {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener(actionListener)
return cell(button)
}
override fun button(text: String, action: AnAction, actionPlace: String): Cell<JButton> {
lateinit var result: CellImpl<JButton>
result = button(text) {
ActionUtil.invokeAction(action, result.component, actionPlace, null, null)
}
return result
}
override fun actionButton(action: AnAction, actionPlace: String): Cell<ActionButton> {
val component = ActionButton(action, action.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE)
return cell(component)
}
override fun actionsButton(vararg actions: AnAction, actionPlace: String, icon: Icon): Cell<ActionButton> {
val actionGroup = PopupActionGroup(arrayOf(*actions))
actionGroup.templatePresentation.icon = icon
return cell(ActionButton(actionGroup, actionGroup.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE))
}
override fun <T> segmentedButton(options: Collection<T>, property: GraphProperty<T>, renderer: (T) -> String): Cell<SegmentedButtonToolbar> {
val actionGroup = DefaultActionGroup(options.map { SegmentedButtonAction(it, property, renderer(it)) })
val toolbar = SegmentedButtonToolbar(actionGroup, parent.spacingConfiguration)
toolbar.targetComponent = null // any data context is supported, suppress warning
return cell(toolbar)
}
override fun <T> segmentedButton(items: Collection<T>, renderer: (T) -> String): SegmentedButton<T> {
val result = SegmentedButtonImpl(this, renderer)
result.items(items)
cells.add(result)
return result
}
override fun tabbedPaneHeader(items: Collection<String>): Cell<JBTabbedPane> {
val tabbedPaneHeader = TabbedPaneHeader()
for (item in items) {
tabbedPaneHeader.add(item, JPanel())
}
return cell(tabbedPaneHeader)
}
override fun slider(min: Int, max: Int, minorTickSpacing: Int, majorTickSpacing: Int): Cell<JSlider> {
val slider = JSlider()
UIUtil.setSliderIsFilled(slider, true)
slider.paintLabels = true
slider.paintTicks = true
slider.paintTrack = true
slider.minimum = min
slider.maximum = max
slider.minorTickSpacing = minorTickSpacing
slider.majorTickSpacing = majorTickSpacing
return cell(slider)
}
override fun label(text: String): CellImpl<JLabel> {
return cell(Label(text))
}
override fun labelHtml(@NlsContexts.Label text: String, action: HyperlinkEventAction): Cell<JEditorPane> {
return text(removeHtml(text), MAX_LINE_LENGTH_WORD_WRAP, action)
}
override fun text(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): Cell<JEditorPane> {
val dslLabel = DslLabel(DslLabelType.LABEL)
dslLabel.action = action
dslLabel.maxLineLength = maxLineLength
dslLabel.text = text
return cell(dslLabel)
}
override fun comment(@NlsContexts.DetailedDescription text: String, maxLineLength: Int): Cell<JLabel> {
return cell(ComponentPanelBuilder.createCommentComponent(text, true, maxLineLength, true))
}
override fun comment(comment: String, maxLineLength: Int, action: HyperlinkEventAction): CellImpl<JEditorPane> {
return cell(createComment(comment, maxLineLength, action))
}
override fun commentNoWrap(text: String): Cell<JLabel> {
return cell(ComponentPanelBuilder.createNonWrappingCommentComponent(text))
}
override fun commentHtml(text: String, action: HyperlinkEventAction): Cell<JEditorPane> {
return comment(text, MAX_LINE_LENGTH_WORD_WRAP, action)
}
override fun link(text: String, action: (ActionEvent) -> Unit): CellImpl<ActionLink> {
return cell(ActionLink(text, action))
}
override fun browserLink(text: String, url: String): CellImpl<BrowserLink> {
return cell(BrowserLink(text, url))
}
override fun <T> dropDownLink(item: T, items: List<T>, onSelected: ((T) -> Unit)?, updateText: Boolean): Cell<DropDownLink<T>> {
return cell(DropDownLink(item, items, onSelect = { t -> onSelected?.let { it(t) } }, updateText = updateText))
}
override fun icon(icon: Icon): CellImpl<JLabel> {
return cell(JBLabel(icon))
}
override fun contextHelp(description: String, title: String?): CellImpl<JLabel> {
val result = if (title == null) ContextHelpLabel.create(description)
else ContextHelpLabel.create(title, description)
return cell(result)
}
override fun textField(): CellImpl<JBTextField> {
val result = cell(JBTextField())
result.columns(COLUMNS_SHORT)
return result
}
override fun textFieldWithBrowseButton(browseDialogTitle: String?,
project: Project?,
fileChooserDescriptor: FileChooserDescriptor,
fileChosen: ((chosenFile: VirtualFile) -> String)?): Cell<TextFieldWithBrowseButton> {
val result = cell(textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen))
result.columns(COLUMNS_SHORT)
return result
}
override fun expandableTextField(parser: Function<in String, out MutableList<String>>,
joiner: Function<in MutableList<String>, String>): Cell<ExpandableTextField> {
val result = cell(ExpandableTextField(parser, joiner))
result.columns(COLUMNS_SHORT)
return result
}
override fun intTextField(range: IntRange?, keyboardStep: Int?): CellImpl<JBTextField> {
val result = cell(JBTextField())
.validationOnInput {
val value = it.text.toIntOrNull()
when {
value == null -> error(UIBundle.message("please.enter.a.number"))
range != null && value !in range -> error(UIBundle.message("please.enter.a.number.from.0.to.1", range.first, range.last))
else -> null
}
}
result.columns(COLUMNS_TINY)
result.component.putClientProperty(DSL_INT_TEXT_RANGE_PROPERTY, range)
keyboardStep?.let {
result.component.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
val increment: Int = when (e?.keyCode) {
KeyEvent.VK_UP -> keyboardStep
KeyEvent.VK_DOWN -> -keyboardStep
else -> return
}
var value = result.component.text.toIntOrNull()
if (value != null) {
value += increment
if (range != null) {
value = MathUtil.clamp(value, range.first, range.last)
}
result.component.text = value.toString()
e.consume()
}
}
})
}
return result
}
override fun spinner(range: IntRange, step: Int): CellImpl<JBIntSpinner> {
return cell(JBIntSpinner(range.first, range.first, range.last, step))
}
override fun spinner(range: ClosedRange<Double>, step: Double): Cell<JSpinner> {
return cell(JSpinner(SpinnerNumberModel(range.start, range.start, range.endInclusive, step)))
}
override fun textArea(): Cell<JBTextArea> {
val textArea = JBTextArea()
// Text area should have same margins as TextField. When margin is TestArea used then border is MarginBorder and margins are taken
// into account twice, which is hard to workaround in current API. So use border instead
textArea.border = JBEmptyBorder(3, 5, 3, 5)
textArea.columns = COLUMNS_SHORT
textArea.font = JBFont.regular()
textArea.emptyText.setFont(JBFont.regular())
textArea.putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY)
return cell(textArea, JBScrollPane(textArea))
}
override fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> {
val component = ComboBox(model)
component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() }
return cell(component)
}
override fun <T> comboBox(items: Collection<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> {
val component = ComboBox(DefaultComboBoxModel(Vector(items)))
component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() }
return cell(component)
}
override fun <T> comboBox(items: Array<T>, renderer: ListCellRenderer<T?>?): Cell<ComboBox<T>> {
val component = ComboBox(items)
component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() }
return cell(component)
}
override fun customize(customRowGaps: VerticalGaps): Row {
internalTopGap = customRowGaps.top
internalBottomGap = customRowGaps.bottom
topGap = null
bottomGap = null
return this
}
fun getIndent(): Int {
return panelContext.indentCount * parent.spacingConfiguration.horizontalIndent
}
private fun doVisible(isVisible: Boolean) {
for (cell in cells) {
cell?.visibleFromParent(isVisible)
}
rowComment?.let { it.isVisible = isVisible }
}
private fun doEnabled(isEnabled: Boolean) {
for (cell in cells) {
cell?.enabledFromParent(isEnabled)
}
rowComment?.let { it.isEnabled = isEnabled }
}
}
private class PopupActionGroup(private val actions: Array<AnAction>): ActionGroup(), DumbAware {
private val popupState = PopupState.forPopup()
init {
isPopup = true
templatePresentation.isPerformGroup = actions.isNotEmpty()
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> = actions
override fun actionPerformed(e: AnActionEvent) {
if (popupState.isRecentlyHidden) {
return
}
val popup = JBPopupFactory.getInstance().createActionGroupPopup(null, this, e.dataContext,
JBPopupFactory.ActionSelectionAid.MNEMONICS, true)
popupState.prepareToShow(popup)
PopupUtil.showForActionButtonEvent(popup, e)
}
}
| apache-2.0 | 94826d8db590aabb8977902517beee20 | 33.238806 | 158 | 0.713103 | 4.493005 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt | 6 | 10270 | // 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.j2k.ast
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.append
import org.jetbrains.kotlin.lexer.KtTokens
import java.util.*
class ArrayAccessExpression(val expression: Expression, val index: Expression, val lvalue: Boolean) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression)
if (!lvalue && expression.isNullable) builder.append("!!")
builder append "[" append index append "]"
}
}
open class AssignmentExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() {
fun isMultiAssignment() = right is AssignmentExpression
fun appendAssignment(builder: CodeBuilder, left: Expression, right: Expression) {
builder.appendOperand(this, left).append(" ").append(op).append(" ").appendOperand(this, right)
}
override fun generateCode(builder: CodeBuilder) {
if (right !is AssignmentExpression)
appendAssignment(builder, left, right)
else {
right.generateCode(builder)
builder.append("\n")
appendAssignment(builder, left, right.left)
}
}
}
class BangBangExpression(val expr: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expr).append("!!")
}
companion object {
fun surroundIfNullable(expression: Expression): Expression {
return if (expression.isNullable)
BangBangExpression(expression).assignNoPrototype()
else
expression
}
}
}
class BinaryExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, left, false).append(" ").append(op).append(" ").appendOperand(this, right, true)
}
}
class IsOperator(val expression: Expression, val type: Type) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression).append(" is ").append(type)
}
}
class TypeCastExpression(val type: Type, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression).append(" as ").append(type)
}
override val isNullable: Boolean
get() = type.isNullable
}
open class LiteralExpression(val literalText: String) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(literalText)
}
object NullLiteral : LiteralExpression("null"){
override val isNullable: Boolean
get() = true
}
}
class ArrayLiteralExpression(val expressions: List<Expression>) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("[")
builder.append(expressions, ", ")
builder.append("]")
}
}
class ParenthesizedExpression(val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder append "(" append expression append ")"
}
}
class PrefixExpression(val op: Operator, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder){
builder.append(op).appendOperand(this, expression)
}
override val isNullable: Boolean
get() = expression.isNullable
}
class PostfixExpression(val op: Operator, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression) append op
}
}
class ThisExpression(val identifier: Identifier) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("this").appendWithPrefix(identifier, "@")
}
}
class SuperExpression(val identifier: Identifier) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("super").appendWithPrefix(identifier, "@")
}
}
class QualifiedExpression(val qualifier: Expression, val identifier: Expression, dotPrototype: PsiElement?) : Expression() {
private val dot = Dot().assignPrototype(dotPrototype, CommentsAndSpacesInheritance.LINE_BREAKS)
override val isNullable: Boolean
get() = identifier.isNullable
override fun generateCode(builder: CodeBuilder) {
if (!qualifier.isEmpty) {
builder.appendOperand(this, qualifier).append(if (qualifier.isNullable) "!!" else "")
builder.append(dot)
}
builder.append(identifier)
}
private class Dot : Element() {
override fun generateCode(builder: CodeBuilder) {
builder.append(".")
}
}
}
open class Operator(val operatorType: IElementType): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(asString(operatorType))
}
fun asString() = asString(operatorType)
fun acceptLineBreakBefore(): Boolean {
return when(operatorType) {
JavaTokenType.ANDAND,
JavaTokenType.OROR,
JavaTokenType.PLUS,
JavaTokenType.MINUS -> true
else -> false
}
}
val precedence: Int
get() = when (this.operatorType) {
JavaTokenType.ASTERISK, JavaTokenType.DIV, JavaTokenType.PERC -> 3
JavaTokenType.PLUS, JavaTokenType.MINUS -> 4
KtTokens.ELVIS -> 7
JavaTokenType.GT, JavaTokenType.LT, JavaTokenType.GE, JavaTokenType.LE -> 9
JavaTokenType.EQEQ, JavaTokenType.NE, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ -> 10
JavaTokenType.ANDAND -> 11
JavaTokenType.OROR -> 12
JavaTokenType.GTGTGT, JavaTokenType.GTGT, JavaTokenType.LTLT -> 7
else -> 6 /* simple name */
}
private fun asString(tokenType: IElementType): String {
return when (tokenType) {
JavaTokenType.EQ -> "="
JavaTokenType.EQEQ -> "=="
JavaTokenType.NE -> "!="
JavaTokenType.ANDAND -> "&&"
JavaTokenType.OROR -> "||"
JavaTokenType.GT -> ">"
JavaTokenType.LT -> "<"
JavaTokenType.GE -> ">="
JavaTokenType.LE -> "<="
JavaTokenType.EXCL -> "!"
JavaTokenType.PLUS -> "+"
JavaTokenType.MINUS -> "-"
JavaTokenType.ASTERISK -> "*"
JavaTokenType.DIV -> "/"
JavaTokenType.PERC -> "%"
JavaTokenType.PLUSEQ -> "+="
JavaTokenType.MINUSEQ -> "-="
JavaTokenType.ASTERISKEQ -> "*="
JavaTokenType.DIVEQ -> "/="
JavaTokenType.PERCEQ -> "%="
JavaTokenType.GTGT -> "shr"
JavaTokenType.LTLT -> "shl"
JavaTokenType.XOR -> "xor"
JavaTokenType.AND -> "and"
JavaTokenType.OR -> "or"
JavaTokenType.GTGTGT -> "ushr"
JavaTokenType.GTGTEQ -> "shr"
JavaTokenType.LTLTEQ -> "shl"
JavaTokenType.XOREQ -> "xor"
JavaTokenType.ANDEQ -> "and"
JavaTokenType.OREQ -> "or"
JavaTokenType.GTGTGTEQ -> "ushr"
JavaTokenType.PLUSPLUS -> "++"
JavaTokenType.MINUSMINUS -> "--"
KtTokens.EQEQEQ -> "==="
KtTokens.EXCLEQEQEQ -> "!=="
else -> "" //System.out.println("UNSUPPORTED TOKEN TYPE: " + tokenType?.toString())
}
}
companion object {
val EQEQ = Operator(JavaTokenType.EQEQ).assignNoPrototype()
val EQ = Operator(JavaTokenType.EQ).assignNoPrototype()
}
}
class LambdaExpression(val parameterList: ParameterList?, val block: Block) : Expression() {
init {
assignPrototypesFrom(block)
}
override fun generateCode(builder: CodeBuilder) {
builder append block.lBrace append " "
if (parameterList != null && !parameterList.parameters.isEmpty()) {
builder.append(parameterList)
.append("->")
.append(if (block.statements.size > 1) "\n" else " ")
.append(block.statements, "\n")
}
else {
builder.append(block.statements, "\n")
}
builder append " " append block.rBrace
}
}
class StarExpression(val operand: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("*").appendOperand(this, operand)
}
}
class RangeExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append("..").appendOperand(this, end)
}
}
class UntilExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" until ").appendOperand(this, end)
}
}
class DownToExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" downTo ").appendOperand(this, end)
}
}
class ClassLiteralExpression(val type: Type): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(type).append("::class")
}
}
fun createArrayInitializerExpression(arrayType: ArrayType, initializers: List<Expression>, needExplicitType: Boolean = true) : MethodCallExpression {
val elementType = arrayType.elementType
val createArrayFunction = when {
elementType is PrimitiveType -> (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize(Locale.US)
needExplicitType -> "arrayOf<" + arrayType.elementType.canonicalCode() + ">"
else -> "arrayOf"
}
return MethodCallExpression.buildNonNull(null, createArrayFunction, ArgumentList.withNoPrototype(initializers))
}
| apache-2.0 | 094ae832d12ba6ff5a802b6b63d5ce22 | 34.536332 | 158 | 0.64372 | 4.867299 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginEnabler.kt | 2 | 3149 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.ide.feedback.kotlinRejecters.state.KotlinRejectersInfoService
import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector
import com.intellij.openapi.diagnostic.getOrLogException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
private val LOG
get() = logger<DynamicPluginEnabler>()
@ApiStatus.Internal
internal class DynamicPluginEnabler : PluginEnabler {
override fun isDisabled(pluginId: PluginId): Boolean =
PluginEnabler.HEADLESS.isDisabled(pluginId)
override fun enable(descriptors: Collection<IdeaPluginDescriptor>): Boolean =
enable(descriptors, project = null)
fun enable(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
): Boolean {
PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = true, project)
PluginEnabler.HEADLESS.enable(descriptors)
val installedDescriptors = findInstalledPlugins(descriptors)
return installedDescriptors != null
&& DynamicPlugins.loadPlugins(installedDescriptors)
}
override fun disable(descriptors: Collection<IdeaPluginDescriptor>): Boolean =
disable(descriptors, project = null)
fun disable(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
parentComponent: JComponent? = null,
): Boolean {
PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = false, project)
recordKotlinPluginDisabling(descriptors)
PluginEnabler.HEADLESS.disable(descriptors)
val installedDescriptors = findInstalledPlugins(descriptors)
return installedDescriptors != null
&& DynamicPlugins.unloadPlugins(installedDescriptors, project, parentComponent)
}
private fun recordKotlinPluginDisabling(descriptors: Collection<IdeaPluginDescriptor>) {
// Kotlin Plugin + 4 plugin dependency
if (descriptors.size <= 5
&& descriptors.any { it.pluginId.idString == "org.jetbrains.kotlin" }) {
KotlinRejectersInfoService.getInstance().state.showNotificationAfterRestart = true
}
}
}
private fun findInstalledPlugins(descriptors: Collection<IdeaPluginDescriptor>): List<IdeaPluginDescriptorImpl>? {
val result = descriptors.mapNotNull {
runCatching { findInstalledPlugin(it) }
.getOrLogException(LOG)
}
return if (result.size == descriptors.size) result else null
}
private fun findInstalledPlugin(descriptor: IdeaPluginDescriptor): IdeaPluginDescriptorImpl {
return when (descriptor) {
is IdeaPluginDescriptorImpl -> descriptor
is PluginNode -> {
val pluginId = descriptor.pluginId
PluginManagerCore.getPluginSet().findInstalledPlugin(pluginId)
?: throw IllegalStateException("Plugin '$pluginId' is not installed")
}
else -> throw IllegalArgumentException("Unknown descriptor kind: $descriptor")
}
} | apache-2.0 | 6d53cd0699f42e4533a2435136c72a06 | 36.951807 | 120 | 0.774214 | 5.179276 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/ui/user/shots/ShotsFragment.kt | 1 | 5225 | /*
* Copyright (c) 2017 Lizhaotailang
*
* 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 io.github.tonnyl.mango.ui.user.shots
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.tonnyl.mango.R
import io.github.tonnyl.mango.data.Shot
import io.github.tonnyl.mango.databinding.FragmentSimpleListBinding
import io.github.tonnyl.mango.ui.shot.ShotActivity
import io.github.tonnyl.mango.ui.shot.ShotPresenter
import kotlinx.android.synthetic.main.fragment_simple_list.*
import org.jetbrains.anko.startActivity
/**
* Created by lizhaotailang on 2017/7/19.
*
* Main ui for the user's shots screen.
*/
class ShotsFragment : Fragment(), ShotsContract.View {
private lateinit var mPresenter: ShotsContract.Presenter
private var mIsLoading = false
private var mAdapter: ShotsAdapter? = null
private var _binding: FragmentSimpleListBinding? = null
private val binding get() =_binding!!
companion object {
@JvmStatic
fun newInstance(): ShotsFragment {
return ShotsFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentSimpleListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
mPresenter.subscribe()
binding.refreshLayout.setOnRefreshListener {
mIsLoading = true
mPresenter.loadShots()
}
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView?.layoutManager as GridLayoutManager
if (dy > 0 && layoutManager.findLastVisibleItemPosition() == binding.recyclerView.adapter.itemCount - 1 && !mIsLoading) {
Log.d("view", "load")
mPresenter.loadShotsOfNextPage()
mIsLoading = true
}
}
})
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.unsubscribe()
}
override fun setPresenter(presenter: ShotsContract.Presenter) {
mPresenter = presenter
}
override fun setLoadingIndicator(loading: Boolean) {
binding.refreshLayout.isRefreshing = loading
}
override fun showShots(shots: List<Shot>) {
if (mAdapter == null) {
mAdapter = ShotsAdapter(context ?: return, shots)
mAdapter?.setItemClickListener({ _, position ->
context?.startActivity<ShotActivity>(ShotPresenter.EXTRA_SHOT to shots[position])
})
binding.recyclerView.adapter = mAdapter
}
mIsLoading = false
}
override fun setEmptyViewVisibility(visible: Boolean) {
binding.emptyView.visibility = if (visible && (mAdapter == null)) View.VISIBLE else View.GONE
}
override fun showNetworkError() {
Snackbar.make(binding.recyclerView, R.string.network_error, Snackbar.LENGTH_SHORT).show()
}
override fun notifyDataAllRemoved(size: Int) {
mAdapter?.notifyItemRangeRemoved(0, size)
mIsLoading = false
}
override fun notifyDataAdded(startPosition: Int, size: Int) {
mAdapter?.notifyItemRangeInserted(startPosition, size)
mIsLoading = false
}
private fun initViews() {
binding.refreshLayout.setColorSchemeColors(ContextCompat.getColor(context ?: return, R.color.colorAccent))
binding.recyclerView.layoutManager = GridLayoutManager(context, 2)
binding.recyclerView.setHasFixedSize(true)
}
} | mit | ec739a5db0e9f01638c7f2ae7b86b6fc | 35.041379 | 137 | 0.701627 | 4.837963 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirSuperEntryContributor.kt | 4 | 2077 | // 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.contributors
import com.intellij.codeInsight.lookup.LookupElementBuilder
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirSuperTypeCallNameReferencePositionContext
import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirSuperEntriesProvider.getSuperClassesAvailableForSuperCall
import org.jetbrains.kotlin.idea.completion.contributors.helpers.SuperCallLookupObject
import org.jetbrains.kotlin.idea.completion.contributors.helpers.SuperCallInsertionHandler
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
internal class FirSuperEntryContributor(
basicContext: FirBasicCompletionContext,
priority: Int,
) : FirCompletionContributorBase<FirSuperTypeCallNameReferencePositionContext>(basicContext, priority) {
override fun KtAnalysisSession.complete(positionContext: FirSuperTypeCallNameReferencePositionContext) {
getSuperClassesAvailableForSuperCall(positionContext.nameExpression).forEach { superType ->
val tailText = superType.classIdIfNonLocal?.asString()?.let { "($it)" }
LookupElementBuilder.create(SuperLookupObject(superType.name, superType.classIdIfNonLocal), superType.name.asString())
.withTailText(tailText)
.withInsertHandler(SuperCallInsertionHandler)
.let { sink.addElement(it) }
}
}
}
private class SuperLookupObject(val className: Name, val classId: ClassId?) : SuperCallLookupObject {
override val replaceTo: String
get() = when {
classId != null -> "${classId.asSingleFqName().asString()}>"
else -> "${className.asString()}>"
}
override val shortenReferencesInReplaced: Boolean
get() = classId != null
}
| apache-2.0 | 8091db036a133e9685c30eaf808e3b1d | 50.925 | 158 | 0.772749 | 5.004819 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformExtensionReceiverOfInlineInspection.kt | 1 | 5401 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.ui.EditorTextField
import org.intellij.lang.regexp.RegExpFileType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullabilityFlexible
import org.jetbrains.kotlin.types.isNullable
import java.awt.BorderLayout
import java.util.regex.PatternSyntaxException
import javax.swing.JPanel
class PlatformExtensionReceiverOfInlineInspection : AbstractKotlinInspection() {
private var nameRegex: Regex? = defaultNamePattern.toRegex()
var namePattern: String = defaultNamePattern
set(value) {
field = value
nameRegex = try {
value.toRegex()
} catch (e: PatternSyntaxException) {
null
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
object : KtVisitorVoid() {
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
super.visitDotQualifiedExpression(expression)
val languageVersionSettings = expression.languageVersionSettings
if (!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)) {
return
}
val nameRegex = nameRegex
val callExpression = expression.selectorExpression as? KtCallExpression ?: return
val calleeText = callExpression.calleeExpression?.text ?: return
if (nameRegex != null && !nameRegex.matches(calleeText)) {
return
}
val resolutionFacade = expression.getResolutionFacade()
val context = expression.analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val resolvedCall = expression.getResolvedCall(context) ?: return
val extensionReceiverType = resolvedCall.extensionReceiver?.type ?: return
if (!extensionReceiverType.isNullabilityFlexible()) return
val descriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return
if (!descriptor.isInline || descriptor.extensionReceiverParameter?.type?.isNullable() == true) return
val receiverExpression = expression.receiverExpression
val dataFlowValueFactory = resolutionFacade.getDataFlowValueFactory()
val dataFlow = dataFlowValueFactory.createDataFlowValue(receiverExpression, extensionReceiverType, context, descriptor)
val stableNullability = context.getDataFlowInfoBefore(receiverExpression).getStableNullability(dataFlow)
if (!stableNullability.canBeNull()) return
holder.registerProblem(
receiverExpression,
KotlinBundle.message("call.of.inline.function.with.nullable.extension.receiver.can.cause.npe.in.kotlin.1.2"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(AddExclExclCallFix(receiverExpression))
)
}
}
override fun createOptionsPanel() = OptionsPanel(this)
class OptionsPanel internal constructor(owner: PlatformExtensionReceiverOfInlineInspection) : JPanel() {
init {
layout = BorderLayout()
val regexField = EditorTextField(owner.namePattern, null, RegExpFileType.INSTANCE).apply {
setOneLineMode(true)
}
regexField.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
owner.namePattern = regexField.text
}
})
val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("text.pattern"), BorderLayout.WEST)
add(labeledComponent, BorderLayout.NORTH)
}
}
companion object {
const val defaultNamePattern = "(toBoolean)|(content.*)"
}
}
| apache-2.0 | 9a4e7ed8c90a515f30704404168d29d5 | 48.550459 | 158 | 0.714127 | 5.795064 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/CleanupExtensionsExternalFilesAction.kt | 1 | 1614 | package org.intellij.plugins.markdown.extensions
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.runModalTask
import com.intellij.util.application
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.settings.MarkdownExtensionsSettings
internal class CleanupExtensionsExternalFilesAction: AnAction() {
override fun actionPerformed(event: AnActionEvent) {
runModalTask(MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.task.title"), event.project, cancellable = false) {
val extensions = MarkdownExtensionsUtil.collectExtensionsWithExternalFiles()
val pathManager = ExtensionsExternalFilesPathManager.getInstance()
for (extension in extensions) {
pathManager.cleanupExternalFiles(extension)
}
MarkdownExtensionsSettings.getInstance().extensionsEnabledState.clear()
val publisher = application.messageBus.syncPublisher(MarkdownExtensionsSettings.ChangeListener.TOPIC)
publisher.extensionsSettingsChanged(fromSettingsDialog = false)
Notifications.Bus.notify(
Notification(
"Markdown",
MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.notification.title"),
MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.notification.text"),
NotificationType.INFORMATION
)
)
}
}
}
| apache-2.0 | c9bf43004d656440651387a0213a191e | 46.470588 | 133 | 0.796159 | 5.508532 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/tail/Log.kt | 1 | 3686 | package com.cognifide.gradle.aem.common.instance.tail
import com.cognifide.gradle.common.utils.Formats
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
class Log(
val info: LogInfo = NoLogInfo(),
val text: String,
val timestamp: ZonedDateTime,
val level: String,
val source: String,
messageLines: List<String>
) {
val checksum = Formats.toMd5(text)
val message = messageLines.joinToString("\n")
val cause: String
get() = message.splitToSequence("\n").firstOrNull()?.run { trim() }
?.substringAfter(" ")?.capitalize() ?: ""
val logWithLocalTimestamp: String
get() =
"[${info.name.padEnd(13)}]" +
"$LOGS_SEPARATOR${timestamp.toLocalDateTime().format(PRINT_DATE_TIME_FORMATTER)}" +
"$LOGS_SEPARATOR${level.padEnd(5)}" +
"$LOGS_SEPARATOR$source" +
"$LOGS_SEPARATOR$message"
fun isLevel(vararg levels: String) = isLevel(levels.asIterable())
fun isLevel(levels: Iterable<String>): Boolean = levels.any { it.equals(level, true) }
fun isOlderThan(millis: Long): Boolean {
val nowTimestamp = LocalDateTime.now().atZone(ZoneId.systemDefault())
val diffMillis = ChronoUnit.MILLIS.between(timestamp, nowTimestamp)
return diffMillis > millis
}
companion object {
private const val TIMESTAMP = """(?<timestamp>[0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3})"""
private const val LEVEL = """\*(?<level>[A-Z]+)\*"""
private const val SOURCE = """(?<source>\[.*\])"""
private const val MESSAGE = """(?<message>.*)"""
private const val LOG_PATTERN = "$TIMESTAMP\\s$LEVEL\\s$SOURCE\\s$MESSAGE"
private const val LOGS_SEPARATOR = " "
private val DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss.SSS")
private val PRINT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
fun create(info: LogInfo, logLines: List<String>): Log {
if (logLines.isEmpty() || logLines.first().isBlank()) {
throw TailerException("Passed log entry is empty!")
}
val fullLog = logLines.joinToString("\n")
when (val result = matchLogLine(logLines.first())) {
null -> throw TailerException("Passed text is not a log entry\nPattern:\n$LOG_PATTERN\nText:\n${logLines.first()}")
else -> {
val (timestamp, level, source, message) = result.destructured
val followingMessageLines = logLines.slice(1 until logLines.size)
return Log(
info,
fullLog,
parseTimestamp(timestamp, info),
level,
source,
listOf(message) + followingMessageLines
)
}
}
}
fun isFirstLineOfLog(text: String) = matchLogLine(text) != null
fun parseTimestamp(timestamp: String, logInfo: LogInfo = NoLogInfo()): ZonedDateTime {
return LocalDateTime.parse(timestamp, DATE_TIME_FORMATTER).atZone(logInfo.zoneId)
?: throw TailerException("Invalid timestamp in log:\n$timestamp" +
"\n required format: $DATE_TIME_FORMATTER")
}
private fun matchLogLine(text: String) = LOG_PATTERN.toRegex().matchEntire(text)
}
}
| apache-2.0 | 937fa0c255212fc22be0325785b0faf1 | 36.612245 | 131 | 0.580575 | 4.403823 | false | false | false | false |
abatR/libqx1 | src/test/kotlin/net/fudiyama/libqx1/CameraManagerTest.kt | 1 | 1916 | package net.fudiyama.libqx1
import net.fudiyama.libqx1.ssdp.DeviceDescription
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.net.NetworkInterface
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class CameraManagerTest {
lateinit var cameraManager: CameraManager
@Before
fun setup() {
cameraManager = CameraManager(CameraManager.getNetworkInterfaces()[0])
}
@After
fun release() {
cameraManager.release()
}
@Test
fun testGetNetworkInterfaces() {
val interfaces: Array<NetworkInterface> = CameraManager.getNetworkInterfaces()
Assert.assertNotNull(interfaces)
for (ifs in interfaces) {
println(ifs)
}
}
@Test
fun testDiscovery() {
var discoveredDescription: DeviceDescription? = null
val startLatch = CountDownLatch(1)
val finishLatch = CountDownLatch(1)
val discoveryListener = object : DiscoveryListener {
override fun onDiscoveryStarted() {
println("onDiscoveryStarted")
startLatch.countDown()
}
override fun onDiscovered(description: DeviceDescription) {
println("onDiscovered description=$description")
discoveredDescription = description
}
override fun onDiscoveryFinished() {
println("onDiscoveryFinished")
finishLatch.countDown()
}
}
cameraManager.registerDiscoveryListener(discoveryListener)
cameraManager.discovery()
Assert.assertTrue(startLatch.await(1, TimeUnit.SECONDS))
Assert.assertTrue(finishLatch.await(10, TimeUnit.SECONDS))
Assert.assertNotNull(discoveredDescription)
cameraManager.unregisterDiscoveryListener(discoveryListener)
}
} | apache-2.0 | 77e91e36c42f094478ac8a7a4dc3f981 | 28.953125 | 86 | 0.665449 | 5.263736 | false | true | false | false |
merrillogic/stump | stump-logging/src/main/kotlin/com/merrillogic/stump/LoggingRoot.kt | 1 | 5663 | package com.merrillogic.stump.logging
import com.merrillogic.stump.StumpObserver
import com.merrillogic.stump.event
import timber.log.Timber
import java.util.ArrayList
import java.util.Arrays
import java.util.LinkedList
import java.util.Stack
/**
* A function to log things when you just want to see what the heck is going on. Logs at the
* warn level so that it still appears if you've set your filter to higher levels. Does not
* output unless it is a debug build, so it is technically safe to leave it in release code.
* Should still probably never make it into committed code - use event() instead.
* @param logStatement The statement to be output into the log.
*/
public fun dev(logStatement: String) {
Timber.w("!!!",
logStatement)
}
/**
* A function for logging things that shouldn't be happening, but we want to know about them if
* they are.
* @param logStatement The description of the odd thing happening, to be output into the log.
*/
public fun odd(logStatement: String) {
Timber.w("???",
logStatement)
}
public fun broken(error: Throwable) {
val errorString = error.toString()
Timber.e("***",
error)
event(errorString + Arrays.toString(error.getStackTrace()))
LoggingRoot.dump()
}
/*
TODO:
Add annotations from support library
Add rx capabilities, again assuming we don't muck up the minSdk
Use timestamps for events? Or at least, relative times.
*/
private data class Event(val eventName:String, val params: Array<out Any>)
public object LoggingRoot : StumpObserver {
interface Listener {
public fun onDump(events: String, ui: String);
}
override fun onEvent(event: String,
vararg args: Any) {
sEventList.add(Event(event, args))
}
//TODO: Memory usage concerns, output, threading conflicts, etc.
private val sUiStackLock = Object()
private val sListeners = ArrayList<Listener>()
private val sEventList = LinkedList<Event>()
private val sUiStateStack = Stack<String>() //Or instead I could just use a linkedlist, and then when I'm popping I don't change anything until I find what I need, then can convert it all.
private var sEventTag = "^^^"
private var sUiString = "[ ]"
private var sUiAddString = "++"
private var sUiPopSting = "--"
private var sUiJoinerString = " -> "
private var sMemoryTrimString = "||]/"
/**
* Sets the key words to be output to the log at various points. Useful if you code in a
* language other than English or just prefer different phrasing.
* @param eventTag
* *
* @param uiString
* *
* @param uiAddSTring
* *
* @param uiPopString
* *
* @param uiJoinerStartString
* *
* @param memoryTrimString
*/
public fun setWording(
eventTag: String,
uiString: String,
uiAddSTring: String,
uiPopString: String,
uiJoinerStartString: String,
memoryTrimString: String) {
sEventTag = eventTag
sUiString = uiString
sUiAddString = uiAddSTring
sUiPopSting = uiPopString
sUiJoinerString = uiJoinerStartString
sMemoryTrimString = memoryTrimString
}
/**
* In the hopes of preserving some small amount of memory, dumps the event and uiStack, then
* clears the event list. If you're app has been running a long time or you have surprisingly
* long event names, this could free up a bit of memory.
* @param memoryLevel
*/
public fun trimMemory(memoryLevel: Int) {
event(sMemoryTrimString + "(" + memoryLevel + ")")
dump()
sEventList.clear()
}
public fun uiEvent(uiEvent: String) {
synchronized (sUiStackLock) {
sUiStateStack.add(uiEvent)
}
//This constructs a stringbuilder for us, which is something to be aware of.
event(sUiString + " " + sUiAddString + " " + uiEvent)
}
/**
* Clear the ui stack up to and including the given string. You should be very certain that
* the string is in the stack, or else the entire thing will be cleared.
*
*
* Logs the pop event to the event list.
* @param uiEvent The ui tag string to pop up to (inclusive).
*/
public fun uiPopTo(uiEvent: String) {
var done = false
val poppedSummaryBuilder = StringBuilder()
poppedSummaryBuilder.append(sUiString).append(" ").append(sUiPopSting).append("(").append(uiEvent).append(") [")
var poppedItem: String
synchronized (sUiStackLock) {
while (!done && !sUiStateStack.empty()) {
poppedItem = sUiStateStack.pop()
poppedSummaryBuilder.append(poppedItem)
done = uiEvent == poppedItem
if (!done) {
poppedSummaryBuilder.append(sUiJoinerString)
}
}
}
event(poppedSummaryBuilder.toString())
}
/**
* Write entire event stream to log, also transmits it to the listener
*/
//ANALYZE: memory concerns for constructing potentially massive string
public fun dump() {
val events = getIndentedIteratedString("Event Stream",
sEventList)
val uiStack = getIndentedIteratedString("Ui Stack",
sUiStateStack)
Timber.d(events)
Timber.d(uiStack)
//Make a local pointer to that object so that it can't be swapped out from under us
for (listener in sListeners) {
listener?.onDump(events,
uiStack)
}
}
public fun addListener(newListener: Listener) {
sListeners.add(newListener)
}
public fun removeListener(oldListener: Listener) {
sListeners.remove(oldListener)
}
private fun getIndentedIteratedString(title: String,
items: Iterable<Any>): String {
val builder = StringBuilder()
builder.append(title).append(":\n")
for (event in items) {
builder.append("\t").append(event.toString()).append("\n")
}
return builder.toString()
}
}
| mit | 89367ad916a9d90f70c4427264241785 | 28.190722 | 189 | 0.693978 | 3.63946 | false | false | false | false |
7449/Album | material/src/main/java/com/gallery/ui/material/activity/MaterialGalleryActivity.kt | 1 | 8729 | package com.gallery.ui.material.activity
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.gallery.compat.activity.GalleryCompatActivity
import com.gallery.compat.extensions.requireGalleryFragment
import com.gallery.compat.finder.GalleryFinderAdapter
import com.gallery.compat.widget.GalleryImageView
import com.gallery.core.GalleryBundle
import com.gallery.core.crop.ICrop
import com.gallery.core.delegate.IScanDelegate
import com.gallery.core.entity.ScanEntity
import com.gallery.core.extensions.drawableExpand
import com.gallery.core.extensions.safeToastExpand
import com.gallery.scan.Types
import com.gallery.scan.extensions.isScanAllExpand
import com.gallery.ui.material.R
import com.gallery.ui.material.args.MaterialGalleryBundle
import com.gallery.ui.material.crop.MaterialGalleryCropper
import com.gallery.ui.material.databinding.MaterialGalleryActivityGalleryBinding
import com.gallery.ui.material.finder.MaterialFinderAdapter
import com.gallery.ui.material.materialGalleryArgOrDefault
import com.gallery.ui.material.minimumDrawableExpand
import com.theartofdev.edmodo.cropper.CropImageOptions
open class MaterialGalleryActivity : GalleryCompatActivity(), View.OnClickListener,
GalleryFinderAdapter.AdapterFinderListener {
private val viewBinding: MaterialGalleryActivityGalleryBinding by lazy {
MaterialGalleryActivityGalleryBinding.inflate(layoutInflater)
}
private val materialGalleryBundle: MaterialGalleryBundle by lazy {
gapConfig.materialGalleryArgOrDefault
}
override val finderAdapter: GalleryFinderAdapter by lazy {
MaterialFinderAdapter(
this@MaterialGalleryActivity,
viewBinding.finderAll,
materialGalleryBundle,
this@MaterialGalleryActivity
)
}
override val cropImpl: ICrop?
get() = MaterialGalleryCropper(CropImageOptions())
override val currentFinderName: String
get() = viewBinding.finderAll.text.toString()
override val galleryFragmentId: Int
get() = R.id.galleryFrame
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
window.statusBarColor = materialGalleryBundle.statusBarColor
viewBinding.toolbar.title = materialGalleryBundle.toolbarText
viewBinding.toolbar.setTitleTextColor(materialGalleryBundle.toolbarTextColor)
val drawable = drawableExpand(materialGalleryBundle.toolbarIcon)
drawable?.colorFilter =
PorterDuffColorFilter(materialGalleryBundle.toolbarIconColor, PorterDuff.Mode.SRC_ATOP)
viewBinding.toolbar.navigationIcon = drawable
viewBinding.toolbar.setBackgroundColor(materialGalleryBundle.toolbarBackground)
viewBinding.toolbar.elevation = materialGalleryBundle.toolbarElevation
viewBinding.finderAll.textSize = materialGalleryBundle.finderTextSize
viewBinding.finderAll.setTextColor(materialGalleryBundle.finderTextColor)
viewBinding.finderAll.setCompoundDrawables(
null,
null,
minimumDrawableExpand(
materialGalleryBundle.finderTextCompoundDrawable,
materialGalleryBundle.finderTextDrawableColor
),
null
)
viewBinding.openPrev.text = materialGalleryBundle.preViewText
viewBinding.openPrev.textSize = materialGalleryBundle.preViewTextSize
viewBinding.openPrev.setTextColor(materialGalleryBundle.preViewTextColor)
viewBinding.select.text = materialGalleryBundle.selectText
viewBinding.select.textSize = materialGalleryBundle.selectTextSize
viewBinding.select.setTextColor(materialGalleryBundle.selectTextColor)
viewBinding.bottomView.setBackgroundColor(materialGalleryBundle.bottomViewBackground)
finderAdapter.finderInit()
viewBinding.openPrev.setOnClickListener(this)
viewBinding.select.setOnClickListener(this)
viewBinding.finderAll.setOnClickListener(this)
viewBinding.finderAll.text = finderName
viewBinding.openPrev.visibility =
if (galleryConfig.radio || galleryConfig.isVideoScanExpand) View.GONE else View.VISIBLE
viewBinding.select.visibility = if (galleryConfig.radio) View.GONE else View.VISIBLE
viewBinding.toolbar.setNavigationOnClickListener { onGalleryFinish() }
}
override fun onGalleryCreated(
delegate: IScanDelegate,
bundle: GalleryBundle,
savedInstanceState: Bundle?
) {
delegate.rootView.setBackgroundColor(materialGalleryBundle.galleryRootBackground)
}
override fun onClick(v: View) {
when (v.id) {
R.id.open_prev -> {
if (requireGalleryFragment.isSelectEmpty) {
onGalleryPreEmpty()
return
}
startPrevPage(
parentId = Types.Scan.NONE,
position = 0,
customBundle = materialGalleryBundle,
cla = MaterialPreActivity::class.java
)
}
R.id.select -> {
if (requireGalleryFragment.isSelectEmpty) {
onGalleryOkEmpty()
return
}
onGalleryResources(requireGalleryFragment.selectItem)
}
R.id.finder_all -> {
if (finderList.isEmpty()) {
onGalleryFinderEmpty()
return
}
finderAdapter.finderUpdate(finderList)
finderAdapter.show()
}
}
}
override fun onGalleryAdapterItemClick(view: View, position: Int, item: ScanEntity) {
val fragment = requireGalleryFragment
if (item.parent == fragment.parentId) {
finderAdapter.hide()
return
}
viewBinding.finderAll.text = item.bucketDisplayName
fragment.onScanGallery(item.parent)
finderAdapter.hide()
}
override fun onGalleryFinderThumbnails(finderEntity: ScanEntity, container: FrameLayout) {
onDisplayGalleryThumbnails(finderEntity, container)
}
override fun onDisplayGallery(
width: Int,
height: Int,
scanEntity: ScanEntity,
container: FrameLayout,
checkBox: TextView
) {
container.removeAllViews()
val imageView = GalleryImageView(container.context)
Glide.with(container.context).load(scanEntity.uri).apply(
RequestOptions().centerCrop().override(width, height)
).into(imageView)
container.addView(imageView, FrameLayout.LayoutParams(width, height))
}
override fun onDisplayGalleryThumbnails(finderEntity: ScanEntity, container: FrameLayout) {
container.removeAllViews()
val imageView = GalleryImageView(container.context)
Glide.with(container.context).load(finderEntity.uri).apply(
RequestOptions().centerCrop()
).into(imageView)
container.addView(imageView)
}
override fun onPhotoItemClick(
context: Context,
bundle: GalleryBundle,
scanEntity: ScanEntity,
position: Int,
parentId: Long
) {
startPrevPage(
parentId = parentId,
position = if (parentId.isScanAllExpand && !bundle.hideCamera) position - 1 else position,
customBundle = materialGalleryBundle,
cla = MaterialPreActivity::class.java
)
}
/** 点击预览但是未选择图片 */
open fun onGalleryPreEmpty() {
getString(R.string.material_gallery_prev_select_empty).safeToastExpand(this)
}
/** 点击确定但是未选择图片 */
open fun onGalleryOkEmpty() {
getString(R.string.material_gallery_ok_select_empty).safeToastExpand(this)
}
/** 扫描到的文件目录为空 */
open fun onGalleryFinderEmpty() {
getString(R.string.material_gallery_finder_empty).safeToastExpand(this)
}
} | mpl-2.0 | f38f4060653984eb0d44aae292a73852 | 37.575342 | 106 | 0.666013 | 5.362005 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/headers/RequestHeadersActivity.kt | 1 | 3365 | package ch.rmy.android.http_shortcuts.activities.editor.headers
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import ch.rmy.android.framework.extensions.bindViewModel
import ch.rmy.android.framework.extensions.collectEventsWhileActive
import ch.rmy.android.framework.extensions.collectViewStateWhileActive
import ch.rmy.android.framework.extensions.initialize
import ch.rmy.android.framework.extensions.whileLifecycleActive
import ch.rmy.android.framework.ui.BaseIntentBuilder
import ch.rmy.android.framework.utils.DragOrderingHelper
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.databinding.ActivityRequestHeadersBinding
import ch.rmy.android.http_shortcuts.extensions.applyTheme
import javax.inject.Inject
class RequestHeadersActivity : BaseActivity() {
@Inject
lateinit var adapter: RequestHeadersAdapter
private val viewModel: RequestHeadersViewModel by bindViewModel()
private lateinit var binding: ActivityRequestHeadersBinding
private var isDraggingEnabled = false
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override fun onCreated(savedState: Bundle?) {
viewModel.initialize()
initViews()
initUserInputBindings()
initViewModelBindings()
}
private fun initViews() {
binding = applyBinding(ActivityRequestHeadersBinding.inflate(layoutInflater))
setTitle(R.string.section_request_headers)
val manager = LinearLayoutManager(context)
binding.headerList.layoutManager = manager
binding.headerList.setHasFixedSize(true)
binding.headerList.adapter = adapter
binding.buttonAddHeader.applyTheme(themeHelper)
}
private fun initUserInputBindings() {
initDragOrdering()
whileLifecycleActive {
adapter.userEvents.collect { event ->
when (event) {
is RequestHeadersAdapter.UserEvent.HeaderClicked -> viewModel.onHeaderClicked(event.id)
}
}
}
binding.buttonAddHeader.setOnClickListener {
viewModel.onAddHeaderButtonClicked()
}
}
private fun initDragOrdering() {
val dragOrderingHelper = DragOrderingHelper(
isEnabledCallback = { isDraggingEnabled },
getId = { (it as? RequestHeadersAdapter.HeaderViewHolder)?.headerId },
)
dragOrderingHelper.attachTo(binding.headerList)
whileLifecycleActive {
dragOrderingHelper.movementSource.collect { (headerId1, headerId2) ->
viewModel.onHeaderMoved(headerId1, headerId2)
}
}
}
private fun initViewModelBindings() {
collectViewStateWhileActive(viewModel) { viewState ->
adapter.items = viewState.headerItems
isDraggingEnabled = viewState.isDraggingEnabled
setDialogState(viewState.dialogState, viewModel)
}
collectEventsWhileActive(viewModel, ::handleEvent)
}
override fun onBackPressed() {
viewModel.onBackPressed()
}
class IntentBuilder : BaseIntentBuilder(RequestHeadersActivity::class)
}
| mit | 6f0ba28f8effe3a60549dc573c833af4 | 34.052083 | 107 | 0.721842 | 5.315956 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/widgets/WidgetsRepository.kt | 1 | 1928 | package ch.rmy.android.http_shortcuts.data.domains.widgets
import ch.rmy.android.framework.data.BaseRepository
import ch.rmy.android.framework.data.RealmFactory
import ch.rmy.android.http_shortcuts.data.domains.getDeadWidgets
import ch.rmy.android.http_shortcuts.data.domains.getShortcutById
import ch.rmy.android.http_shortcuts.data.domains.getWidgetsByIds
import ch.rmy.android.http_shortcuts.data.domains.getWidgetsForShortcut
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.data.models.WidgetModel
import io.realm.kotlin.deleteFromRealm
import javax.inject.Inject
class WidgetsRepository
@Inject
constructor(
realmFactory: RealmFactory,
) : BaseRepository(realmFactory) {
suspend fun createWidget(widgetId: Int, shortcutId: ShortcutId, showLabel: Boolean, labelColor: String?) {
commitTransaction {
copyOrUpdate(
WidgetModel(
widgetId = widgetId,
shortcut = getShortcutById(shortcutId).findFirst(),
showLabel = showLabel,
labelColor = labelColor,
)
)
}
}
suspend fun getWidgetsByIds(widgetIds: List<Int>): List<WidgetModel> =
query {
getWidgetsByIds(widgetIds)
}
suspend fun getWidgetsByShortcutId(shortcutId: ShortcutId): List<WidgetModel> =
query {
getWidgetsForShortcut(shortcutId)
}
suspend fun deleteDeadWidgets() {
commitTransaction {
getDeadWidgets()
.findAll()
.forEach { widget ->
widget.deleteFromRealm()
}
}
}
suspend fun deleteWidgets(widgetIds: List<Int>) {
commitTransaction {
getWidgetsByIds(widgetIds)
.findAll()
.deleteAllFromRealm()
}
}
}
| mit | 8159895c71d1c57c938559d334072bba | 31.133333 | 110 | 0.64471 | 4.79602 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/data/forAll5.kt | 1 | 2052 | package io.kotest.data
import io.kotest.mpp.reflection
import kotlin.jvm.JvmName
suspend fun <A, B, C, D, E> forAll(vararg rows: Row5<A, B, C, D, E>, testfn: suspend (A, B, C, D, E) -> Unit) {
val params = reflection.paramNames(testfn) ?: emptyList<String>()
val paramA = params.getOrElse(0) { "a" }
val paramB = params.getOrElse(1) { "b" }
val paramC = params.getOrElse(2) { "c" }
val paramD = params.getOrElse(3) { "d" }
val paramE = params.getOrElse(4) { "e" }
table(headers(paramA, paramB, paramC, paramD, paramE), *rows).forAll { A, B, C, D, E -> testfn(A, B, C, D, E) }
}
@JvmName("forall5")
inline fun <A, B, C, D, E> forAll(table: Table5<A, B, C, D, E>, testfn: (A, B, C, D, E) -> Unit) = table.forAll(testfn)
inline fun <A, B, C, D, E> Table5<A, B, C, D, E>.forAll(fn: (A, B, C, D, E) -> Unit) {
val collector = ErrorCollector()
for (row in rows) {
try {
fn(row.a, row.b, row.c, row.d, row.e)
} catch (e: Throwable) {
collector.append(error(e, headers.values(), row.values()))
}
}
collector.assertAll()
}
suspend fun <A, B, C, D, E> forNone(vararg rows: Row5<A, B, C, D, E>, testfn: suspend (A, B, C, D, E) -> Unit) {
val params = reflection.paramNames(testfn) ?: emptyList<String>()
val paramA = params.getOrElse(0) { "a" }
val paramB = params.getOrElse(1) { "b" }
val paramC = params.getOrElse(2) { "c" }
val paramD = params.getOrElse(3) { "d" }
val paramE = params.getOrElse(4) { "e" }
table(headers(paramA, paramB, paramC, paramD, paramE), *rows).forNone { A, B, C, D, E -> testfn(A, B, C, D, E) }
}
@JvmName("fornone5")
inline fun <A, B, C, D, E> forNone(table: Table5<A, B, C, D, E>, testfn: (A, B, C, D, E) -> Unit) =
table.forNone(testfn)
inline fun <A, B, C, D, E> Table5<A, B, C, D, E>.forNone(fn: (A, B, C, D, E) -> Unit) {
for (row in rows) {
try {
fn(row.a, row.b, row.c, row.d, row.e)
} catch (e: AssertionError) {
continue
}
throw forNoneError(headers.values(), row.values())
}
}
| mit | 6db9b1038f179a4d0f96935be8d3f018 | 37 | 119 | 0.577485 | 2.654592 | false | true | false | false |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/_common/network/entity/EntryInfoResponse.kt | 1 | 313 | package me.kirimin.mitsumine._common.network.entity;
data class EntryInfoResponse(
val title: String? = null,
val count: Int = 0,
val url: String? = null,
val screenshot: String? = null,
val bookmarks: List<BookmarkResponse> = emptyList(),
val eid: String? = null) | apache-2.0 | 7bdd10246c9c71dbaa2df947283e52ee | 33.888889 | 60 | 0.626198 | 4.064935 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/data/repository/file/webdav/WebDavClientV2.kt | 1 | 8846 | package com.ivanovsky.passnotes.data.repository.file.webdav
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.OperationError.MESSAGE_FAILED_TO_GET_PARENT_PATH
import com.ivanovsky.passnotes.data.entity.OperationError.MESSAGE_FILE_IS_NOT_A_DIRECTORY
import com.ivanovsky.passnotes.data.entity.OperationError.MESSAGE_INCORRECT_FILE_SYSTEM_CREDENTIALS
import com.ivanovsky.passnotes.data.entity.OperationError.MESSAGE_IO_ERROR
import com.ivanovsky.passnotes.data.entity.OperationError.newAuthError
import com.ivanovsky.passnotes.data.entity.OperationError.newFileAccessError
import com.ivanovsky.passnotes.data.entity.OperationError.newFileNotFoundError
import com.ivanovsky.passnotes.data.entity.OperationError.newGenericError
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.entity.RemoteFileMetadata
import com.ivanovsky.passnotes.data.repository.file.remote.RemoteApiClientV2
import com.ivanovsky.passnotes.util.FileUtils
import com.ivanovsky.passnotes.util.FileUtils.ROOT_PATH
import com.ivanovsky.passnotes.util.InputOutputUtils
import com.ivanovsky.passnotes.util.Logger
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
import com.thegrizzlylabs.sardineandroid.DavResource
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import okhttp3.OkHttpClient
class WebDavClientV2(
private val authenticator: WebdavAuthenticator,
httpClient: OkHttpClient
) : RemoteApiClientV2 {
private val webDavClient = WebDavNetworkLayer(httpClient).apply {
val creds = authenticator.getFsAuthority().credentials
if (creds != null) {
setCredentials(creds)
}
}
private var fsAuthority = authenticator.getFsAuthority()
override fun listFiles(dir: FileDescriptor): OperationResult<List<FileDescriptor>> {
Logger.d(TAG, "listFiles: dir=$dir")
if (!dir.isDirectory) {
return OperationResult.error(newFileAccessError(MESSAGE_FILE_IS_NOT_A_DIRECTORY))
}
val files = fetchFileList(dir.path)
if (files.isFailed) {
return files.takeError()
}
return OperationResult.success(files.obj.excludeByPath(dir.path))
}
override fun getParent(file: FileDescriptor): OperationResult<FileDescriptor> {
Logger.d(TAG, "getParent: file=$file")
val checkAuthority = checkFsAuthority(file)
if (checkAuthority.isFailed) {
return checkAuthority.takeError()
}
val parentPath = FileUtils.getParentPath(file.path)
?: return OperationResult.error(newFileAccessError(MESSAGE_FAILED_TO_GET_PARENT_PATH))
val files = fetchFileList(parentPath)
if (files.isFailed) {
return files.takeError()
}
val parentFile = files.obj.firstOrNull { it.path == parentPath }
?: return OperationResult.error(newFileNotFoundError())
return OperationResult.success(parentFile)
}
override fun getRoot(): OperationResult<FileDescriptor> {
Logger.d(TAG, "getRoot:")
val files = fetchFileList(EMPTY)
if (files.isFailed) {
return files.takeError()
}
val root = files.obj.firstOrNull { it.isRoot }
?: return OperationResult.error(newFileNotFoundError())
return OperationResult.success(root)
}
override fun getFileMetadata(file: FileDescriptor): OperationResult<RemoteFileMetadata> {
val checkAuthority = checkFsAuthority(file)
if (checkAuthority.isFailed) {
return checkAuthority.takeError()
}
return getFileMetadata(file.path)
}
private fun getFileMetadata(path: String): OperationResult<RemoteFileMetadata> {
Logger.d(TAG, "getFileMetadata: path=%s", path)
val metadata = fetchDavResource(path)
if (metadata.isFailed) {
return metadata.takeError()
}
return OperationResult.success(metadata.obj.toRemoteFileMetadata())
}
override fun downloadFile(
remotePath: String,
destinationPath: String
): OperationResult<RemoteFileMetadata> {
val input = webDavClient.execute { client ->
client.get(formatUrl(remotePath))
}
if (input.isFailed) {
return input.takeError()
}
val cancellation = AtomicBoolean(false)
try {
val out = FileOutputStream(File(destinationPath))
InputOutputUtils.copy(input.obj, out, true, cancellation)
} catch (e: IOException) {
Logger.printStackTrace(e)
cancellation.set(true)
return OperationResult.error(newGenericError(MESSAGE_IO_ERROR))
}
return getFileMetadata(remotePath)
}
override fun uploadFile(
remotePath: String,
localPath: String
): OperationResult<RemoteFileMetadata> {
val put = webDavClient.execute { client ->
client.put(formatUrl(remotePath), File(localPath), CONTENT_TYPE)
}
if (put.isFailed) {
return put.takeError()
}
return getFileMetadata(remotePath)
}
private fun checkCredentials(): OperationResult<Unit> {
val authenticatorCreds = authenticator.getFsAuthority().credentials
val currentCreds = fsAuthority.credentials
if (currentCreds != authenticatorCreds && authenticatorCreds != null) {
fsAuthority = authenticator.getFsAuthority()
webDavClient.setCredentials(authenticatorCreds)
}
if (fsAuthority.credentials == null) {
return OperationResult.error(newAuthError())
}
return OperationResult.success(Unit)
}
private fun checkFsAuthority(file: FileDescriptor): OperationResult<Unit> {
if (file.fsAuthority != fsAuthority) {
return OperationResult.error(newAuthError(MESSAGE_INCORRECT_FILE_SYSTEM_CREDENTIALS))
}
return OperationResult.success(Unit)
}
private fun fetchFileList(path: String): OperationResult<List<FileDescriptor>> {
val checkCreds = checkCredentials()
if (checkCreds.isFailed) {
return checkCreds.takeError()
}
val url = formatUrl(path)
Logger.d(TAG, "fetchFileList: url=%s, cred=%s", url, fsAuthority.credentials)
val files = webDavClient.execute { client ->
client
.list(url)
.toFileDescriptors()
}
if (files.isFailed) {
return files.takeError()
}
return files
}
private fun fetchDavResource(path: String): OperationResult<DavResource> {
val checkCreds = checkCredentials()
if (checkCreds.isFailed) {
return checkCreds.takeError()
}
Logger.d(TAG, "fetchDavResource: path=%s", path)
val data = webDavClient.execute { client ->
client
.list(formatUrl(path))
.firstOrNull()
}
if (data.isFailed) {
return data.takeError()
}
if (data.obj == null) {
return OperationResult.error(newFileNotFoundError())
}
return OperationResult.success(data.obj)
}
private fun formatUrl(path: String): String {
return getServerUrl() + path
}
private fun getServerUrl(): String {
return fsAuthority.credentials?.serverUrl ?: throw IllegalStateException()
}
private fun List<DavResource>.toFileDescriptors(): List<FileDescriptor> {
return this.map { it.toFileDescriptor() }
}
private fun List<FileDescriptor>.excludeByPath(excludePath: String): List<FileDescriptor> {
return this.filter { it.path != excludePath }
}
private fun DavResource.toFileDescriptor(): FileDescriptor {
val path = FileUtils.removeSeparatorIfNeed(href.toString())
return FileDescriptor(
fsAuthority = fsAuthority,
path = path,
uid = path,
name = FileUtils.getFileNameFromPath(path),
isDirectory = isDirectory,
isRoot = (path == ROOT_PATH),
modified = modified.time
)
}
private fun DavResource.toRemoteFileMetadata(): RemoteFileMetadata {
val path = FileUtils.removeSeparatorIfNeed(href.toString())
return RemoteFileMetadata(
uid = path,
path = path,
serverModified = this.modified,
clientModified = this.modified,
revision = this.etag
)
}
companion object {
private const val CONTENT_TYPE = "application/octet-stream"
private val TAG = WebDavClientV2::class.simpleName
}
} | gpl-2.0 | 41eb703a37b8e649a11a20fb6ff0513c | 33.158301 | 99 | 0.663577 | 4.697823 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.