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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Magneticraft-Team/Magneticraft | ignore/test/integration/jei/hydraulicpress/HydraulicPressRecipeWrapper.kt | 2 | 1257 | package integration.jei.hydraulicpress
import com.cout970.magneticraft.api.registries.machines.hydraulicpress.IHydraulicPressRecipe
import mezz.jei.api.ingredients.IIngredients
import mezz.jei.api.recipe.IRecipeWrapper
import net.minecraft.client.Minecraft
import net.minecraftforge.fluids.FluidStack
/**
* Created by cout970 on 24/08/2016.
*/
class HydraulicPressRecipeWrapper(val recipe : IHydraulicPressRecipe ) : IRecipeWrapper {
override fun drawAnimations(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int) = Unit
override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) = Unit
override fun getTooltipStrings(mouseX: Int, mouseY: Int): MutableList<String>? = mutableListOf()
override fun getFluidInputs(): MutableList<FluidStack>? = mutableListOf()
override fun handleClick(minecraft: Minecraft, mouseX: Int, mouseY: Int, mouseButton: Int): Boolean = false
override fun getOutputs(): MutableList<Any?>? = mutableListOf(recipe.output)
override fun getFluidOutputs(): MutableList<FluidStack>? = mutableListOf()
override fun getInputs(): MutableList<Any?>? = mutableListOf(recipe.input)
override fun getIngredients(ingredients: IIngredients?) {}
} | gpl-2.0 | 99bf4b0125e6a4dcbaca92bda4f0b1a1 | 39.580645 | 117 | 0.777247 | 4.204013 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/widget/DefaultBrowserPreference.kt | 1 | 4202 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.widget
import android.app.role.RoleManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.util.AttributeSet
import androidx.core.os.bundleOf
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.google.android.material.switchmaterial.SwitchMaterial
import mozilla.components.support.utils.Browsers
import org.mozilla.focus.GleanMetrics.SetDefaultBrowser
import org.mozilla.focus.R
import org.mozilla.focus.ext.tryAsActivity
import org.mozilla.focus.utils.SupportUtils.openDefaultBrowserSumoPage
class DefaultBrowserPreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : Preference(context, attrs, defStyleAttr) {
private var switchView: SwitchMaterial? = null
private val browsers
get() = Browsers.all(context)
init {
widgetLayoutResource = R.layout.preference_default_browser
val appName = context.resources.getString(R.string.app_name)
val title = context.resources.getString(R.string.preference_default_browser2, appName)
setTitle(title)
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
switchView = holder.findViewById(R.id.switch_widget) as SwitchMaterial
update()
}
fun update() {
switchView?.isChecked = browsers.isDefaultBrowser
}
public override fun onClick() {
val isDefault = browsers.isDefaultBrowser
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
context.getSystemService(RoleManager::class.java).also {
if (it.isRoleAvailable(RoleManager.ROLE_BROWSER) && !it.isRoleHeld(
RoleManager.ROLE_BROWSER,
)
) {
context.tryAsActivity()?.startActivityForResult(
it.createRequestRoleIntent(RoleManager.ROLE_BROWSER),
REQUEST_CODE_BROWSER_ROLE,
)
SetDefaultBrowser.fromAppSettings.record(
SetDefaultBrowser.FromAppSettingsExtra(
isDefault,
),
)
} else {
navigateToDefaultBrowserAppsSettings(isDefault)
}
}
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
navigateToDefaultBrowserAppsSettings(isDefault)
}
else -> {
openDefaultBrowserSumoPage(context)
SetDefaultBrowser.learnMoreOpened.record(
SetDefaultBrowser.LearnMoreOpenedExtra(
isDefault,
),
)
}
}
}
private fun navigateToDefaultBrowserAppsSettings(isDefault: Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
intent.putExtra(
SETTINGS_SELECT_OPTION_KEY,
DEFAULT_BROWSER_APP_OPTION,
)
intent.putExtra(
SETTINGS_SHOW_FRAGMENT_ARGS,
bundleOf(SETTINGS_SELECT_OPTION_KEY to DEFAULT_BROWSER_APP_OPTION),
)
context.startActivity(intent)
SetDefaultBrowser.fromOsSettings.record(SetDefaultBrowser.FromOsSettingsExtra(isDefault))
}
}
companion object {
const val REQUEST_CODE_BROWSER_ROLE = 1
const val SETTINGS_SELECT_OPTION_KEY = ":settings:fragment_args_key"
const val SETTINGS_SHOW_FRAGMENT_ARGS = ":settings:show_fragment_args"
const val DEFAULT_BROWSER_APP_OPTION = "default_browser"
}
}
| mpl-2.0 | 7e5e738a7d1a32a2a00a96583b8ba47f | 37.2 | 101 | 0.618753 | 4.990499 | false | false | false | false |
fare1990/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/java/com/github/bumblebee/bot/consumer/TelegramUpdateRouter.kt | 1 | 1999 | package com.github.bumblebee.bot.consumer
import com.github.bumblebee.util.logger
import com.github.telegram.domain.Update
import org.springframework.stereotype.Component
import java.time.Instant
import java.util.regex.Pattern
/**
* Route update to concrete handler using handler registry
*/
@Component
class TelegramUpdateRouter(private val handlerRegistry: HandlerRegistry) {
fun route(update: Update) {
try {
if (isOutdatedUpdate(update)) {
log.debug("Outdated update skipped")
return
}
// try invoking command
val consumed = invokeCommand(update)
if (!consumed) {
// run handler chain if not consumed, stop if handler returns true
handlerRegistry.handlerChain.any { it.onUpdate(update) }
}
} catch (e: Exception) {
log.error("Exception during update processing", e)
}
}
private fun isOutdatedUpdate(update: Update): Boolean {
val unixTime = update.message?.date
return unixTime != null && Instant.ofEpochSecond(unixTime.toLong())
.isBefore(Instant.now().minusSeconds(updateExpirationSeconds.toLong()))
}
private fun invokeCommand(update: Update): Boolean {
val text = update.message?.text
if (text != null && text.startsWith("/")) {
val handler = handlerRegistry[parse(text)]
if (handler != null) {
handler.onUpdate(update)
return true
}
}
return false
}
private fun parse(message: String): String? {
val matcher = commandPattern.matcher(message)
return if (matcher.find()) {
matcher.group()
} else null
}
companion object {
private val log = logger<TelegramUpdateRouter>()
private val updateExpirationSeconds = 2 * 60
private val commandPattern = Pattern.compile("^/[\\w]+")
}
}
| mit | 2522990250e8f74801cfe1f5161ce26e | 30.234375 | 87 | 0.606803 | 4.851942 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/vadapter/VBaseAdapter.kt | 1 | 989 | package cn.thens.kdroid.core.vadapter
import android.util.SparseArray
import android.view.ViewGroup
import java.lang.ref.WeakReference
interface VBaseAdapter<D> : VAdapter<D> {
val holderList: SparseArray<WeakReference<VAdapter.Holder<D>>>
private fun getHolder(position: Int): VAdapter.Holder<D>? {
return holderList.get(position)?.get()
}
fun getHolder(container: ViewGroup, position: Int): VAdapter.Holder<D> {
var holder = getHolder(position)
if (holder == null) {
holder = createHolder(container, getItemViewType(position))
holderList.put(position, WeakReference(holder))
}
return holder
}
fun removeHolder(position: Int): VAdapter.Holder<D>? {
val holder = getHolder(position)
if (holder != null) {
val view = holder.view
(view.parent as? ViewGroup)?.removeView(view)
holderList.removeAt(position)
}
return holder
}
}
| apache-2.0 | 4d69cb45187fae683626167417755c26 | 29.90625 | 76 | 0.646107 | 4.226496 | false | false | false | false |
rovkinmax/RxRetainFragment | app/src/main/java/com/github/rovkinmax/rxretainexample/ProgressActivity.kt | 1 | 2186 | package com.github.rovkinmax.rxretainexample
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.ProgressBar
import com.github.rovkinmax.rxretain.EmptySubscriber
import com.github.rovkinmax.rxretain.RetainFactory
import com.github.rovkinmax.rxretain.RetainWrapper
import com.github.rovkinmax.rxretainexample.test.rangeWithDelay
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit
/**
* @author Rovkin Max
*/
class ProgressActivity : Activity() {
private var dialog: ProgressDialog? = null
private var wrapper: RetainWrapper<Int>? = null
val observable = rangeWithDelay(0, 100, TimeUnit.SECONDS.toMillis(120))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val button = Button(this).apply {
text = "click"
}
setContentView(button)
button.setOnClickListener {
wrapper?.subscribe()
}
}
override fun onResume() {
super.onResume()
wrapper = RetainFactory.create(fragmentManager, observable, object : EmptySubscriber<Int>() {
override fun onStart() {
dialog = ProgressDialog(this@ProgressActivity)
dialog!!.show()
}
override fun onNext(t: Int) {
if (dialog?.isShowing ?: false)
dialog?.progressBar?.progress = t
}
override fun onCompleted() {
hideDialog()
}
})
}
override fun onPause() {
super.onPause()
hideDialog()
}
private fun hideDialog() {
dialog?.dismiss()
}
}
class ProgressDialog(context: Context) : Dialog(context) {
lateinit var progressBar: ProgressBar
init {
progressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal)
progressBar.max = 100
setContentView(progressBar)
}
} | apache-2.0 | 930426691b323087d37a62fae7d23800 | 26.683544 | 101 | 0.653248 | 4.711207 | false | false | false | false |
domaframework/doma | integration-test-kotlin/src/test/kotlin/org/seasar/doma/it/criteria/KEntityqlBatchInsertTest.kt | 1 | 1579 | package org.seasar.doma.it.criteria
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.seasar.doma.it.IntegrationTestEnvironment
import org.seasar.doma.jdbc.Config
import org.seasar.doma.kotlin.jdbc.criteria.KEntityql
@ExtendWith(IntegrationTestEnvironment::class)
class KEntityqlBatchInsertTest(config: Config) {
private val entityql = KEntityql(config)
@Test
fun test() {
val d = Department_()
val department = Department()
department.departmentId = 99
department.departmentNo = 99
department.departmentName = "aaa"
department.location = "bbb"
val department2 = Department()
department2.departmentId = 100
department2.departmentNo = 100
department2.departmentName = "ccc"
department2.location = "ddd"
val departments = listOf(department, department2)
val result = entityql.insert(d, departments).execute()
assertEquals(departments, result.entities)
val ids = departments.map { it.departmentId }
val departments2 = entityql
.from(d)
.where { `in`(d.departmentId, ids) }
.orderBy { asc(d.departmentId) }
.fetch()
assertEquals(2, departments2.size)
}
@Test
fun empty() {
val e = Employee_()
val result = entityql.insert(e, emptyList()).execute()
assertTrue(result.entities.isEmpty())
}
}
| apache-2.0 | 5aa1f32c39d0b501aa12a9f08bb92ced | 30.58 | 62 | 0.668144 | 4.244624 | false | true | false | false |
clhols/zapr | app/src/main/java/dk/youtec/zapr/util/SharedPreferences.kt | 1 | 1430 | package dk.youtec.zapr.util
import android.content.Context
import android.preference.PreferenceManager
object SharedPreferences {
const val SMART_CARD_ID = "selectedSmartCardId"
const val FAVOURITE_LIST_KEY = "selectedFavouriteList"
const val REMOTE_CONTROL_MODE = "remoteControlMode"
const val EMAIL = "email"
const val PASSWORD = "password"
const val UID = "uid"
fun getString(context: Context, key: String, default: String = ""): String {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, default)
}
fun setString(context: Context, key: String, value: String) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(key, value)
.apply()
}
fun setInt(context: Context, key: String, value: Int) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putInt(key, value)
.apply()
}
fun getBoolean(context: Context, key: String, default: Boolean = false): Boolean {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, default)
}
fun setBoolean(context: Context, key: String, value: Boolean) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(key, value)
.apply()
}
} | mit | 91fb6a8d9b002e9b0a450f36fa682405 | 32.27907 | 94 | 0.647552 | 4.798658 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/GameHubGameActionServiceImpl.kt | 1 | 7057 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.blockball.core.logic.business.service
import com.github.shynixn.blockball.api.business.enumeration.Team
import com.github.shynixn.blockball.api.business.service.*
import com.github.shynixn.blockball.api.persistence.entity.HubGame
import com.github.shynixn.blockball.api.persistence.entity.TeamMeta
import com.github.shynixn.blockball.core.logic.persistence.entity.GameStorageEntity
import com.google.inject.Inject
import java.util.*
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class GameHubGameActionServiceImpl @Inject constructor(
private val configurationService: ConfigurationService,
private val proxyService: ProxyService,
private val gameExecutionService: GameExecutionService,
private val placeholderService: PlaceholderService
) :
GameHubGameActionService {
/**
* Lets the given [player] leave join the given [game]. Optional can the prefered
* [team] be specified but the team can still change because of arena settings.
* Does nothing if the player is already in a Game.
*/
override fun <P> joinGame(game: HubGame, player: P, team: Team?): Boolean {
require(player is Any)
var joiningTeam = team
if (game.arena.meta.lobbyMeta.onlyAllowEventTeams) {
if (joiningTeam == Team.RED && game.redTeam.size > game.blueTeam.size) {
joiningTeam = null
} else if (joiningTeam == Team.BLUE && game.blueTeam.size > game.redTeam.size) {
joiningTeam = null
}
}
if (joiningTeam == null) {
joiningTeam = Team.BLUE
if (game.redTeam.size < game.blueTeam.size) {
joiningTeam = Team.RED
}
}
if (joiningTeam == Team.RED && game.redTeam.size < game.arena.meta.redTeamMeta.maxAmount) {
this.prepareLobbyStorageForPlayer(game, player, joiningTeam, game.arena.meta.redTeamMeta)
return true
} else if (joiningTeam == Team.BLUE && game.blueTeam.size < game.arena.meta.blueTeamMeta.maxAmount) {
this.prepareLobbyStorageForPlayer(game, player, joiningTeam, game.arena.meta.blueTeamMeta)
return true
}
return false
}
/**
* Lets the given [player] leave the given [game].
* Does nothing if the player is not in the game.
*/
override fun <P> leaveGame(game: HubGame, player: P) {
require(player is Any)
if (!game.ingamePlayersStorage.containsKey(player)) {
return
}
val stats = game.ingamePlayersStorage[player]!!
proxyService.setGameMode(player, stats.gameMode)
proxyService.setPlayerAllowFlying(player, stats.allowedFlying)
proxyService.setPlayerFlying(player, stats.flying)
proxyService.setPlayerWalkingSpeed(player, stats.walkingSpeed)
proxyService.setPlayerScoreboard(player, stats.scoreboard)
if (!game.arena.meta.customizingMeta.keepInventoryEnabled) {
proxyService.setInventoryContents(player, stats.inventoryContents, stats.armorContents)
}
}
/**
* Handles the game actions per tick. [ticks] parameter shows the amount of ticks
* 0 - 20 for each second.
*/
override fun handle(game: HubGame, ticks: Int) {
if (ticks < 20) {
return
}
if (game.arena.meta.hubLobbyMeta.resetArenaOnEmpty && game.ingamePlayersStorage.isEmpty() && (game.redScore > 0 || game.blueScore > 0)) {
game.closing = true
}
}
/**
* Prepares the storage for a hubgame.
*/
private fun prepareLobbyStorageForPlayer(game: HubGame, player: Any, team: Team, teamMeta: TeamMeta) {
val uuid = proxyService.getPlayerUUID(player)
val stats = GameStorageEntity(UUID.fromString(uuid))
game.ingamePlayersStorage[player] = stats
stats.scoreboard = proxyService.generateNewScoreboard()
stats.team = team
stats.goalTeam = team
stats.gameMode = proxyService.getPlayerGameMode(player)
stats.flying = proxyService.getPlayerFlying(player)
stats.allowedFlying = proxyService.getPlayerAllowFlying(player)
stats.walkingSpeed = proxyService.getPlayerWalkingSpeed(player)
stats.scoreboard = proxyService.getPlayerScoreboard(player)
stats.armorContents = proxyService.getPlayerInventoryArmorCopy(player)
stats.inventoryContents = proxyService.getPlayerInventoryCopy(player)
stats.level = proxyService.getPlayerLevel(player)
stats.exp = proxyService.getPlayerExp(player)
stats.maxHealth = proxyService.getPlayerMaxHealth(player)
stats.health = proxyService.getPlayerHealth(player)
stats.hunger = proxyService.getPlayerHunger(player)
proxyService.setGameMode(player, game.arena.meta.lobbyMeta.gamemode)
proxyService.setPlayerAllowFlying(player, false)
proxyService.setPlayerFlying(player, false)
proxyService.setPlayerWalkingSpeed(player, teamMeta.walkingSpeed)
if (!game.arena.meta.customizingMeta.keepInventoryEnabled) {
proxyService.setInventoryContents(
player,
teamMeta.inventoryContents,
teamMeta.armorContents
)
}
if (game.arena.meta.hubLobbyMeta.teleportOnJoin) {
this.gameExecutionService.respawn(game, player)
} else {
val velocityIntoArena = proxyService.getPlayerDirection(player).normalize().multiply(0.5)
proxyService.setEntityVelocity(player, velocityIntoArena)
}
val prefix = configurationService.findValue<String>("messages.prefix")
val message = prefix + placeholderService.replacePlaceHolders(teamMeta.joinMessage, game, teamMeta)
proxyService.sendMessage(player, message)
}
} | apache-2.0 | 724021a8c5ede2cfc2cd344a0490b99f | 41.011905 | 145 | 0.691512 | 4.40787 | false | false | false | false |
abdodaoud/Merlin | app/src/main/java/com/abdodaoud/merlin/domain/datasource/FactProvider.kt | 1 | 1481 | package com.abdodaoud.merlin.domain.datasource
import com.abdodaoud.merlin.data.db.FactDb
import com.abdodaoud.merlin.data.server.FactServer
import com.abdodaoud.merlin.domain.model.Fact
import com.abdodaoud.merlin.domain.model.FactList
import com.abdodaoud.merlin.extensions.firstResult
import com.abdodaoud.merlin.extensions.maxDate
import com.abdodaoud.merlin.extensions.zeroedTime
class FactProvider(val sources: List<FactDataSource> = FactProvider.SOURCES) {
companion object {
val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
val SOURCES = listOf(FactDb(), FactServer())
}
fun request(currentPage: Int, lastDate: Long): FactList = requestToSources {
val res = it.request(todayTimeSpan(), currentPage, lastDate)
if (res != null && hasTodayFact(res, currentPage)) res else null
}
private fun hasTodayFact(res: FactList, currentPage: Int): Boolean {
if (currentPage == -1) currentPage == 1
val created = System.currentTimeMillis().zeroedTime()
for (fact in res.dailyFact) {
if (fact.created == created.maxDate(currentPage)) return true
}
return false
}
fun requestFact(id: Long): Fact = requestToSources { it.requestDayFact(id) }
private fun todayTimeSpan() = System.currentTimeMillis().zeroedTime() /
DAY_IN_MILLIS * DAY_IN_MILLIS
private fun <T : Any> requestToSources(f: (FactDataSource) -> T?): T =
sources.firstResult { f(it) }
} | mit | 3c336410332c934693e831319fc93ca9 | 36.05 | 80 | 0.694126 | 3.749367 | false | false | false | false |
MyDogTom/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/documentation/CommentOverPrivateProperty.kt | 1 | 1019 | package io.gitlab.arturbosch.detekt.rules.documentation
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtProperty
/**
* @author Artur Bosch
*/
class CommentOverPrivateProperty(config: Config = Config.empty) : Rule(config) {
override val issue = Issue("CommentOverPrivateProperty",
Severity.Maintainability,
"Private properties should be named such that they explain themselves even without a comment.")
override fun visitProperty(property: KtProperty) {
val modifierList = property.modifierList
if (modifierList != null && property.docComment != null) {
if (modifierList.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
report(CodeSmell(issue, Entity.from(property.docComment!!)))
}
}
}
}
| apache-2.0 | f56932d6a0969290514a760fa79cfa8e | 32.966667 | 98 | 0.784102 | 3.904215 | false | true | false | false |
gantsign/restrulz-jvm | com.gantsign.restrulz.json/src/main/kotlin/com/gantsign/restrulz/json/JsonObjectMapper.kt | 1 | 10876 | /*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* 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.
* #L%
*/
package com.gantsign.restrulz.json
import com.gantsign.restrulz.json.reader.JsonObjectReader
import com.gantsign.restrulz.json.reader.JsonObjectReaderFactory
import com.gantsign.restrulz.json.writer.JsonObjectWriter
import com.gantsign.restrulz.json.writer.JsonObjectWriterFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.io.OutputStream
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.concurrent.ConcurrentHashMap
/**
* Maps objects to/from JSON.
*/
@Suppress("unused")
class JsonObjectMapper {
private val log: Logger = LoggerFactory.getLogger(JsonObjectMapper::class.java)
private val readerUnsupportedTypes = ConcurrentHashMap.newKeySet<Type>()
private val arrayReaderUnsupportedTypes = ConcurrentHashMap.newKeySet<Type>()
private val readerMap = ConcurrentHashMap<Type, JsonObjectReader<*>>()
private val arrayReaderMap = ConcurrentHashMap<Type, JsonObjectReader<*>>()
private val writerUnsupportedTypes = ConcurrentHashMap.newKeySet<Type>()
private val arrayWriterUnsupportedTypes = ConcurrentHashMap.newKeySet<Type>()
private val writerMap = ConcurrentHashMap<Type, JsonObjectWriter<Any>>()
private val arrayWriterMap = ConcurrentHashMap<Type, JsonObjectWriter<Any>>()
private val typeMap = ConcurrentHashMap<Type, Type>()
private fun mapType(type: Type): Type {
val cachedType = typeMap[type]
if (cachedType !== null) {
return cachedType
}
if (type !is ParameterizedType && type is Class<*>
&& ArrayList::class.java == type.superclass) {
val genericSuperclass = type.genericSuperclass
if (genericSuperclass !== null) {
// By sub-classing ArrayList you can pass the generic type for the list
typeMap.put(type, genericSuperclass)
return genericSuperclass
}
}
typeMap.put(type, type)
return type
}
private fun getReaderFactory(clazz: Class<*>): JsonObjectReaderFactory<*>? {
val factoryName = "${clazz.`package`.name}.json.reader.${clazz.simpleName}ReaderFactory"
val factoryClass: Class<*>
try {
factoryClass = Thread.currentThread().contextClassLoader.loadClass(factoryName)
} catch(e: ClassNotFoundException) {
readerUnsupportedTypes.add(clazz)
log.trace("Unsupported type {}", clazz.name)
return null
}
if (!JsonObjectReaderFactory::class.java.isAssignableFrom(factoryClass)) {
readerUnsupportedTypes.add(clazz)
log.warn("Expected that {} implement {}", factoryClass.name, JsonObjectReaderFactory::class.java.name)
return null
}
return factoryClass.getField("INSTANCE").get(null) as JsonObjectReaderFactory<*>
}
private fun objectReaderFor(type: Type): JsonObjectReader<*>? {
val cachedReader: JsonObjectReader<*>? = readerMap[type]
if (cachedReader !== null) {
return cachedReader
}
if (readerUnsupportedTypes.contains(type)) {
return null
}
if (type !is Class<*>) {
readerUnsupportedTypes.add(type)
log.trace("Unsupported type {}", type.typeName)
return null
}
val clazz = type
val factory = getReaderFactory(clazz)
if (factory === null) {
return null
}
val jsonReader = factory.jsonReader
readerMap.put(clazz, jsonReader)
return jsonReader
}
private fun arrayReaderFor(type: ParameterizedType): JsonObjectReader<*>? {
val cachedReader: JsonObjectReader<*>? = arrayReaderMap[type]
if (cachedReader !== null) {
return cachedReader
}
if (arrayReaderUnsupportedTypes.contains(type)) {
return null
}
val listClass = type.rawType
if (!(listClass is Class<*> && List::class.java.isAssignableFrom(listClass))) {
arrayReaderUnsupportedTypes.add(type)
log.trace("Unsupported array type {}", type.typeName)
return null
}
val clazz = type.actualTypeArguments[0]
val reader = objectReaderFor(clazz)
if (reader === null) {
arrayReaderUnsupportedTypes.add(type)
log.trace("Unsupported array type {}", type.typeName)
return null
}
arrayReaderMap.put(type, reader)
return reader
}
private fun readerFor(type: Type): JsonObjectReader<*>? {
if (type is ParameterizedType) {
val reader = arrayReaderFor(type)
if (reader !== null) {
return reader
}
}
return objectReaderFor(type)
}
/**
* Returns `true` if the specified type can be read from JSON.
*
* @param type the type to check if it can be read.
* @return `true` if the specified type can be read from JSON.
*/
fun isSupportedForReading(type: Type): Boolean {
return readerFor(mapType(type)) !== null
}
/**
* Reads an instance of the type from the JSON encoded stream.
*
* @param type the type of the object to return.
* @param inputStream the stream containing the JSON.
* @return The object being read.
*/
fun read(type: Type, inputStream: InputStream): Any {
val mappedType = mapType(type)
if (mappedType is ParameterizedType) {
val arrayReader = arrayReaderFor(mappedType)
if (arrayReader !== null) {
return arrayReader.readArray(inputStream)
}
}
val reader = objectReaderFor(mappedType)
if (reader === null) {
throw IllegalArgumentException("Unsupported type ${mappedType.typeName}")
}
return reader.readObject(inputStream)!!
}
private fun getWriterFactory(clazz: Class<*>): JsonObjectWriterFactory<*>? {
val factoryName = "${clazz.`package`.name}.json.writer.${clazz.simpleName}WriterFactory"
val factoryClass: Class<*>
try {
factoryClass = Thread.currentThread().contextClassLoader.loadClass(factoryName)
} catch(e: ClassNotFoundException) {
writerUnsupportedTypes.add(clazz)
log.trace("Unsupported type {}", clazz.name)
return null
}
if (!JsonObjectWriterFactory::class.java.isAssignableFrom(factoryClass)) {
writerUnsupportedTypes.add(clazz)
log.warn("Expected that {} implement {}", factoryClass.name, JsonObjectWriterFactory::class.java.name)
return null
}
return factoryClass.getField("INSTANCE").get(null) as JsonObjectWriterFactory<*>
}
private fun objectWriterFor(type: Type): JsonObjectWriter<Any>? {
val cachedWriter: JsonObjectWriter<Any>? = writerMap[type]
if (cachedWriter !== null) {
return cachedWriter
}
if (type !is Class<*>) {
readerUnsupportedTypes.add(type)
log.trace("Unsupported type {}", type.typeName)
return null
}
val clazz = type
val factory = getWriterFactory(clazz)
if (factory === null) {
return null
}
@Suppress("UNCHECKED_CAST")
val jsonWriter = factory.jsonWriter as JsonObjectWriter<Any>
writerMap.put(type, jsonWriter)
return jsonWriter
}
private fun arrayWriterFor(type: ParameterizedType): JsonObjectWriter<Any>? {
val cachedWriter: JsonObjectWriter<Any>? = arrayWriterMap[type]
if (cachedWriter !== null) {
return cachedWriter
}
if (arrayWriterUnsupportedTypes.contains(type)) {
return null
}
val listClass = type.rawType
if (!(listClass is Class<*> && List::class.java.isAssignableFrom(listClass))) {
arrayWriterUnsupportedTypes.add(type)
log.trace("Unsupported array type {}", type.typeName)
return null
}
val clazz = type.actualTypeArguments[0]
val writer = objectWriterFor(clazz)
if (writer === null) {
arrayWriterUnsupportedTypes.add(type)
log.trace("Unsupported array type {}", type.typeName)
return null
}
arrayWriterMap.put(type, writer)
return writer
}
private fun writerFor(type: Type): JsonObjectWriter<Any>? {
if (type is ParameterizedType) {
val writer = arrayWriterFor(type)
if (writer !== null) {
return writer
}
}
return objectWriterFor(type)
}
/**
* Returns `true` if the specified type can be written to JSON.
*
* @param type the type to check if it can be written.
* @return `true` if the specified type can be written to JSON.
*/
fun isSupportedForWriting(type: Type): Boolean {
return writerFor(mapType(type)) !== null
}
/**
* Writes the specified object to the stream using JSON encoding.
*
* @param value the value to write out as JSON.
* @param type the type of the object being written.
* @param outputStream the destination for the JSON.
*/
fun write(value: Any, type: Type?, outputStream: OutputStream) {
val mappedType = mapType(type ?: value::class.java)
if (mappedType is ParameterizedType) {
if (value !is List<*>) {
throw IllegalArgumentException("Expected ${List::class.java.name} but was ${value::class.java.name}")
}
@Suppress("UNCHECKED_CAST")
val values = value as List<Any>
val arrayWriter = arrayWriterFor(mappedType)
if (arrayWriter !== null) {
arrayWriter.writeAsJsonArray(outputStream, values)
return
}
}
val writer = objectWriterFor(mappedType)
if (writer === null) {
throw IllegalArgumentException("Unsupported type ${mappedType.typeName}")
}
writer.writeAsJson(outputStream, value)
}
}
| apache-2.0 | 748147ef015d353d6ce013c9b8b656e8 | 34.659016 | 117 | 0.62523 | 4.79753 | false | false | false | false |
lbbento/pitchup | androidgauge/src/main/kotlin/com/lbbento/pitchuptunergauge/view/TunerGauge.kt | 1 | 5243 | package com.lbbento.pitchuptunergauge.view
import android.content.Context
import android.graphics.*
import android.graphics.Color.*
import android.util.AttributeSet
import com.github.anastr.speedviewlib.base.Speedometer
import com.github.anastr.speedviewlib.base.SpeedometerDefault
class TunerGauge(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : Speedometer(context, attrs, defStyleAttr) {
companion object {
val INDICATOR_COLOR = "#c6c6c6"
val TUNED_COLOR = "#77C577"
}
private val ARC_COLOR = "#c6c6c6"
private val markPath: Path
private val circlePaint: Paint
private val speedometerPaint: Paint
private val markPaint: Paint
private val middleMarkPaint: Paint
private val speedometerRect: RectF
init {
this.markPath = Path()
this.circlePaint = Paint(1)
this.speedometerPaint = Paint(1)
this.markPaint = Paint(1)
this.middleMarkPaint = Paint(1)
this.speedometerRect = RectF()
this.init()
}
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
override fun defaultValues() {}
override fun getSpeedometerDefault(): SpeedometerDefault {
val speedometerDefault = SpeedometerDefault()
speedometerDefault.indicator = TunerIndicator(this.context)
speedometerDefault.backgroundCircleColor = 0
return speedometerDefault
}
private fun init() {
this.speedometerPaint.style = Paint.Style.STROKE
this.markPaint.style = Paint.Style.STROKE
this.middleMarkPaint.style = Paint.Style.STROKE
this.middleMarkPaint.color = parseColor(TUNED_COLOR)
this.circlePaint.color = parseColor(INDICATOR_COLOR)
this.startDegree = 180
this.endDegree = 360
this.lowSpeedPercent = 49
this.mediumSpeedPercent = 51
this.mediumSpeedColor = parseColor(ARC_COLOR)
this.lowSpeedColor = parseColor(ARC_COLOR)
this.highSpeedColor = parseColor(ARC_COLOR)
this.indicatorColor = parseColor(INDICATOR_COLOR)
this.markColor = parseColor(ARC_COLOR)
this.speedTextColor = context.resources.getColor(android.R.color.transparent)
this.speedTextTypeface = Typeface.SANS_SERIF
this.speedometerWidth = 10f
this.textColor = context.resources.getColor(android.R.color.transparent)
this.unit = "Hz"
this.unitTextColor = context.resources.getColor(android.R.color.transparent)
this.backgroundCircleColor = context.resources.getColor(android.R.color.transparent)
}
override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) {
super.onSizeChanged(w, h, oldW, oldH)
this.updateBackgroundBitmap()
}
private fun initDraw() {
this.speedometerPaint.strokeWidth = this.speedometerWidth
this.markPaint.color = this.markColor
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
this.initDraw()
this.drawSpeedUnitText(canvas)
this.drawIndicator(canvas)
canvas.drawCircle(this.size.toFloat() * 0.5f, this.size.toFloat() * 0.5f, this.widthPa.toFloat() / 20.0f, this.circlePaint)
this.drawNotes(canvas)
}
override fun updateBackgroundBitmap() {
val c = this.createBackgroundBitmapCanvas()
this.initDraw()
val markH = this.sizePa.toFloat() / 32.0f
this.markPath.reset()
this.markPath.moveTo((this.size.toFloat()) * 0.5f, this.padding.toFloat())
this.markPath.lineTo((this.size.toFloat()) * 0.5f, markH + this.padding.toFloat())
this.markPaint.strokeWidth = markH / 5.0f
val risk = this.speedometerWidth * 0.5f + 30f //markers
this.speedometerRect.set(risk, risk, this.size.toFloat() - risk, this.size.toFloat() - risk)
//draw arc
this.speedometerPaint.color = this.highSpeedColor
c.drawArc(this.speedometerRect, this.startDegree.toFloat(), (this.endDegree - this.startDegree).toFloat(), false, this.speedometerPaint)
this.speedometerPaint.color = this.mediumSpeedColor
c.drawArc(this.speedometerRect, this.startDegree.toFloat(), (this.endDegree - this.startDegree).toFloat() * this.mediumSpeedOffset, false, this.speedometerPaint)
this.speedometerPaint.color = this.lowSpeedColor
c.drawArc(this.speedometerRect, this.startDegree.toFloat(), (this.endDegree - this.startDegree).toFloat() * this.lowSpeedOffset, false, this.speedometerPaint)
c.save()
c.rotate(90.0f + this.startDegree.toFloat(), this.size.toFloat() * 0.5f, this.size.toFloat() * 0.5f)
c.rotate(10f, this.size.toFloat() * 0.5f, this.size.toFloat() * 0.5f)
c.drawPath(this.markPath, this.markPaint)
this.middleMarkPaint.strokeWidth = indicatorWidth + 10f
c.rotate(80f, this.size.toFloat() * 0.5f, this.size.toFloat() * 0.5f)
c.drawPath(this.markPath, this.middleMarkPaint) //Middle one
c.rotate(80f, this.size.toFloat() * 0.5f, this.size.toFloat() * 0.5f)
c.drawPath(this.markPath, this.markPaint)
c.restore()
this.drawDefMinMaxSpeedPosition(c)
}
} | apache-2.0 | d9ea201def1176d5b3c3b571aca78b54 | 39.338462 | 169 | 0.683578 | 3.729018 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/dao/Entity.kt | 1 | 24127 | package kotlin.dao
import java.util.*
import kotlin.properties.Delegates
import kotlin.reflect.KProperty
import kotlin.sql.*
/**
* @author max
*/
public class EntityID(id: Int, val table: IdTable) {
var _value = id
val value: Int get() {
if (_value == -1) {
EntityCache.getOrCreate(Session.get()).flushInserts(table)
assert(_value > 0) { "Entity must be inserted" }
}
return _value
}
override fun toString() = value.toString()
override fun hashCode() = value
override fun equals(other: Any?): Boolean {
if (other !is EntityID) return false
return other._value == _value && other.table == table
}
}
private fun <T:EntityID?>checkReference(reference: Column<T>, factory: EntityClass<*>) {
val refColumn = reference.referee
if (refColumn == null) error("Column $reference is not a reference")
val targetTable = refColumn.table
if (factory.table != targetTable) {
error("Column and factory point to different tables")
}
}
class Reference<out Target : Entity> (val reference: Column<EntityID>, val factory: EntityClass<Target>) {
init {
checkReference(reference, factory)
}
}
class OptionalReference<out Target: Entity> (val reference: Column<EntityID?>, val factory: EntityClass<Target>) {
init {
checkReference(reference, factory)
}
}
class OptionalReferenceSureNotNull<out Target: Entity> (val reference: Column<EntityID?>, val factory: EntityClass<Target>) {
init {
checkReference(reference, factory)
}
}
class Referrers<out Source:Entity>(val reference: Column<EntityID>, val factory: EntityClass<Source>, val cache: Boolean) {
init {
val refColumn = reference.referee
if (refColumn == null) error("Column $reference is not a reference")
if (factory.table != reference.table) {
error("Column and factory point to different tables")
}
}
operator fun getValue(o: Entity, desc: KProperty<*>): SizedIterable<Source> {
val query = {factory.find{reference eq o.id}}
return if (cache) EntityCache.getOrCreate(Session.get()).getOrPutReferrers(o, reference, query) else query()
}
}
class OptionalReferrers<out Source:Entity>(val reference: Column<EntityID?>, val factory: EntityClass<Source>, val cache: Boolean) {
init {
val refColumn = reference.referee ?: error("Column $reference is not a reference")
if (factory.table != reference.table) {
error("Column and factory point to different tables")
}
}
operator fun getValue(o: Entity, desc: KProperty<*>): SizedIterable<Source> {
val query = {factory.find{reference eq o.id}}
return if (cache) EntityCache.getOrCreate(Session.get()).getOrPutReferrers(o, reference, query) else query()
}
}
open class ColumnWithTransform<TColumn, TReal>(val column: Column<TColumn>, val toColumn: (TReal) -> TColumn, val toReal: (TColumn) -> TReal) {
}
public class View<out Target: Entity> (val op : Op<Boolean>, val factory: EntityClass<Target>) : SizedIterable<Target> {
override fun limit(n: Int): SizedIterable<Target> = factory.find(op).limit(n)
override fun count(): Int = factory.find(op).count()
override fun empty(): Boolean = factory.find(op).empty()
override fun forUpdate(): SizedIterable<Target> = factory.find(op).forUpdate()
override fun notForUpdate(): SizedIterable<Target> = factory.find(op).notForUpdate()
operator public override fun iterator(): Iterator<Target> = factory.find(op).iterator()
operator fun getValue(o: Any?, desc: KProperty<*>): SizedIterable<Target> = factory.find(op)
}
@Suppress("UNCHECKED_CAST")
class InnerTableLink<Target: Entity>(val table: Table,
val target: EntityClass<Target>) {
private fun getSourceRefColumn(o: Entity): Column<EntityID> {
val sourceRefColumn = table.columns.firstOrNull { it.referee == o.klass.table.id } as? Column<EntityID> ?: error("Table does not reference source")
return sourceRefColumn
}
private fun getTargetRefColumn(): Column<EntityID> {
val sourceRefColumn = table.columns.firstOrNull { it.referee == target.table.id } as? Column<EntityID> ?: error("Table does not reference source")
return sourceRefColumn
}
operator fun getValue(o: Entity, desc: KProperty<*>): SizedIterable<Target> {
fun alreadyInJoin() = (target.dependsOnTables as? Join)?.joinParts?.any { it.joinType == JoinType.INNER && it.table == table} ?: false
val sourceRefColumn = getSourceRefColumn(o)
val entityTables: ColumnSet = when {
target.dependsOnTables is Table -> (target.dependsOnTables as Table).innerJoin(table)
alreadyInJoin() -> target.dependsOnTables
else -> (target.dependsOnTables as Join).innerJoin(table)
}
val columns = (target.dependsOnColumns + (if (!alreadyInJoin()) table.columns else emptyList())
- sourceRefColumn).distinct() + sourceRefColumn
val query = {target.wrapRows(entityTables.slice(columns).select{sourceRefColumn eq o.id})}
return EntityCache.getOrCreate(Session.get()).getOrPutReferrers(o, sourceRefColumn, query)
}
operator fun setValue(o: Entity, desc: KProperty<*>, value: SizedIterable<Target>) {
val sourceRefColumn = getSourceRefColumn(o)
val targeRefColumn = getTargetRefColumn()
with(Session.get()) {
val entityCache = EntityCache.getOrCreate(Session.get())
entityCache.flush()
val existingIds = getValue(o, desc).map { it.id }.toSet()
entityCache.clearReferrersCache()
val targetIds = value.map { it.id }.toList()
table.deleteWhere { (sourceRefColumn eq o.id) and (targeRefColumn notInList targetIds) }
table.batchInsert(targetIds.filter { !existingIds.contains(it) }) { targetId ->
this[sourceRefColumn] = o.id
this[targeRefColumn] = targetId
}
}
}
}
open public class Entity(val id: EntityID) {
var klass: EntityClass<*> by Delegates.notNull()
val writeValues = LinkedHashMap<Column<Any?>, Any?>()
var _readValues: ResultRow? = null
val readValues: ResultRow
get() {
return _readValues ?: run {
val table = klass.table
_readValues = klass.searchQuery( Op.build {table.id eq id }).firstOrNull() ?: table.select { table.id eq id }.first()
_readValues!!
}
}
/*private val cachedData = LinkedHashMap<String, Any>()
public fun<T> getOrCreate(key: String, evaluate: ()->T) : T {
return cachedData.getOrPut(key, evaluate) as T
}*/
operator fun <T: Entity> Reference<T>.getValue(o: Entity, desc: KProperty<*>): T {
val id = reference.getValue(o, desc)
return factory.findById(id) ?: error("Cannot find ${factory.table.tableName} WHERE id=$id")
}
operator fun <T: Entity> Reference<T>.setValue(o: Entity, desc: KProperty<*>, value: T) {
reference.setValue(o, desc, value.id)
}
operator fun <T: Entity> OptionalReference<T>.getValue(o: Entity, desc: KProperty<*>): T? {
return reference.getValue(o, desc)?.let{factory.findById(it)}
}
operator fun <T: Entity> OptionalReference<T>.setValue(o: Entity, desc: KProperty<*>, value: T?) {
reference.setValue(o, desc, value?.id)
}
operator fun <T: Entity> OptionalReferenceSureNotNull<T>.getValue(o: Entity, desc: KProperty<*>): T {
val id = reference.getValue(o, desc) ?: error("${o.id}.$desc is null")
return factory.findById(id) ?: error("Cannot find ${factory.table.tableName} WHERE id=$id")
}
operator fun <T: Entity> OptionalReferenceSureNotNull<T>.setValue(o: Entity, desc: KProperty<*>, value: T) {
reference.setValue(o, desc, value.id)
}
operator fun <T> Column<T>.getValue(o: Entity, desc: KProperty<*>): T {
return lookup()
}
@Suppress("UNCHECKED_CAST")
fun <T, R:Any> Column<T>.lookupInReadValues(found: (T?) -> R?, notFound: () -> R?): R? {
if (_readValues?.hasValue(this) ?: false)
return found(readValues[this])
else
return notFound()
}
@Suppress("UNCHECKED_CAST")
fun <T:Any?> Column<T>.lookup(): T = when {
writeValues.containsKeyRaw(this) -> writeValues.getRaw(this) as T
id._value == -1 && _readValues?.hasValue(this)?.not() ?: true -> defaultValue as T
else -> readValues[this]
}
operator fun <T> Column<T>.setValue(o: Entity, desc: KProperty<*>, value: T) {
if (writeValues.containsKeyRaw(this) || _readValues?.tryGet(this) != value) {
if (referee != null) {
EntityCache.getOrCreate(Session.get()).referrers.run {
filterKeys { it.id == value }.forEach {
if (it.value.keys.any { it == this@setValue } ) {
this.remove(it.key)
}
}
}
EntityCache.getOrCreate(Session.get()).removeTablesReferrers(listOf(referee!!.table))
}
writeValues.set(this as Column<Any?>, value)
}
}
operator fun <TColumn, TReal> ColumnWithTransform<TColumn, TReal>.getValue(o: Entity, desc: KProperty<*>): TReal {
return toReal(column.getValue(o, desc))
}
operator fun <TColumn, TReal> ColumnWithTransform<TColumn, TReal>.setValue(o: Entity, desc: KProperty<*>, value: TReal) {
column.setValue(o, desc, toColumn(value))
}
infix public fun <Target:Entity> EntityClass<Target>.via(table: Table): InnerTableLink<Target> {
return InnerTableLink(table, this@via)
}
public fun <T: Entity> s(c: EntityClass<T>): EntityClass<T> = c
public open fun delete(){
klass.removeFromCache(this)
val table = klass.table
table.deleteWhere{table.id eq id}
}
open fun flush(batch: BatchUpdateQuery? = null): Boolean {
if (!writeValues.isEmpty()) {
if (batch == null) {
val table = klass.table
table.update({table.id eq id}) {
for ((c, v) in writeValues) {
it[c] = v
}
}
}
else {
batch.addBatch(id)
for ((c, v) in writeValues) {
batch[c] = v
}
}
storeWrittenValues()
return true
}
return false
}
public fun storeWrittenValues() {
// move write values to read values
if (_readValues != null) {
for ((c, v) in writeValues) {
_readValues!!.set(c, v?.let { c.columnType.valueFromDB(c.columnType.valueToDB(it)!!)})
}
if (klass.dependsOnColumns.any { it.table == klass.table && !_readValues!!.hasValue(it) } ) {
_readValues = null
}
}
// clear write values
writeValues.clear()
}
}
@Suppress("UNCHECKED_CAST")
class EntityCache {
val data = HashMap<IdTable, MutableMap<Int, Entity>>()
val inserts = HashMap<IdTable, MutableList<Entity>>()
val referrers = HashMap<Entity, MutableMap<Column<*>, SizedIterable<*>>>()
private fun <T: Entity> getMap(f: EntityClass<T>) : MutableMap<Int, T> {
return getMap(f.table)
}
private fun <T: Entity> getMap(table: IdTable) : MutableMap<Int, T> {
val answer = data.getOrPut(table, {
HashMap()
}) as MutableMap<Int, T>
return answer
}
fun <T: Entity, R: Entity> getOrPutReferrers(source: T, key: Column<*>, refs: ()-> SizedIterable<R>): SizedIterable<R> {
return referrers.getOrPut(source, {HashMap()}).getOrPut(key, {LazySizedCollection(refs())}) as SizedIterable<R>
}
fun <T: Entity> find(f: EntityClass<T>, id: EntityID): T? {
return getMap(f)[id.value]
}
fun <T: Entity> findAll(f: EntityClass<T>): SizedIterable<T> {
return SizedCollection(getMap(f).values)
}
fun <T: Entity> store(f: EntityClass<T>, o: T) {
getMap(f).put(o.id.value, o)
}
fun <T: Entity> store(table: IdTable, o: T) {
getMap<T>(table).put(o.id.value, o)
}
fun <T: Entity> remove(table: IdTable, o: T) {
getMap<T>(table).remove(o.id.value)
}
fun <T: Entity> scheduleInsert(f: EntityClass<T>, o: T) {
val list = inserts.getOrPut(f.table) {
ArrayList<Entity>()
}
list.add(o)
}
infix private fun Table.references(another: Table): Boolean {
return columns.any { it.referee?.table == another }
}
private fun<T> swap (list: ArrayList<T>, i : Int, j: Int) {
val tmp = list[i]
list[i] = list[j]
list[j] = tmp
}
fun<T> ArrayList<T>.topoSort (comparer: (T,T) -> Int) {
for (i in 0..this.size -2) {
var minIndex = i
for (j in (i+1)..this.size -1) {
if (comparer(this[minIndex], this[j]) > 0) {
minIndex = j
}
}
if (minIndex != i)
swap(this, i, minIndex)
}
}
fun flush() {
flush((inserts.keys + data.keys).toSet())
}
fun addDependencies(tables: Iterable<IdTable>): Iterable<IdTable> {
val workset = HashSet<IdTable>()
fun checkTable(table: IdTable) {
if (workset.add(table)) {
for (c in table.columns) {
val referee = c.referee
if (referee != null) {
if (referee.table is IdTable) checkTable(referee.table)
}
}
}
}
for (t in tables) checkTable(t)
return workset
}
fun flush(tables: Iterable<IdTable>) {
val sorted = addDependencies(tables).toArrayList()
sorted.topoSort { a, b ->
when {
a == b -> 0
a references b && b references a -> 0
a references b -> 1
b references a -> -1
else -> 0
}
}
val insertedTables = inserts.map { it.key }
for (t in sorted) {
flushInserts(t)
}
for (t in tables) {
val map = data[t]
if (map != null) {
val updatedEntities = HashSet<Entity>()
val batch = BatchUpdateQuery(t)
for ((i, entity) in map) {
if (entity.flush(batch)) {
if (entity.klass is ImmutableEntityClass<*>) {
throw IllegalStateException("Update on immutable entity ${entity.javaClass.simpleName} ${entity.id}")
}
updatedEntities.add(entity)
}
}
batch.execute(Session.get())
updatedEntities.forEach {
EntityHook.alertSubscribers(it, false)
}
}
}
if (insertedTables.isNotEmpty()) {
removeTablesReferrers(insertedTables)
}
}
internal fun removeTablesReferrers(insertedTables: List<Table>) {
referrers.filterValues { it.any { it.key.table in insertedTables } }.map { it.key }.forEach {
referrers.remove(it)
}
}
fun flushInserts(table: IdTable) {
inserts.remove(table)?.let {
val ids = table.batchInsert(it) { entry ->
for ((c, v) in entry.writeValues) {
this[c] = v
}
}
for ((entry, id) in it.zip(ids)) {
entry.id._value = id
entry.writeValues.set(entry.klass.table.id as Column<Any?>, id)
entry.storeWrittenValues()
EntityCache.getOrCreate(Session.get()).store(table, entry)
EntityHook.alertSubscribers(entry, true)
}
}
}
fun clearReferrersCache() {
referrers.clear()
}
companion object {
val key = Key<EntityCache>()
val newCache = { EntityCache()}
fun invalidateGlobalCaches(created: List<Entity>) {
created.map { it.klass }.filterNotNull().filterIsInstance<ImmutableCachedEntityClass<*>>().toSet().forEach {
it.expireCache()
}
}
fun getOrCreate(s: Session): EntityCache {
return s.getOrCreate(key, newCache)
}
}
}
@Suppress("UNCHECKED_CAST")
abstract public class EntityClass<out T: Entity>(val table: IdTable) {
private val klass = javaClass.enclosingClass!!
private val ctor = klass.constructors[0]
public operator fun get(id: EntityID): T {
return findById(id) ?: error("Entity not found in database")
}
public operator fun get(id: Int): T {
return findById(id) ?: error("Entity not found in database")
}
open protected fun warmCache(): EntityCache = EntityCache.getOrCreate(Session.get())
public fun findById(id: Int): T? {
return findById(EntityID(id, table))
}
public fun findById(id: EntityID): T? {
return testCache(id) ?: find{table.id eq id}.firstOrNull()
}
public fun reload(entity: Entity): T? {
removeFromCache(entity)
return find { table.id eq entity.id }.firstOrNull()
}
public fun testCache(id: EntityID): T? {
return warmCache().find(this, id)
}
fun testCache(cacheCheckCondition: T.()->Boolean): List<T> = warmCache().findAll(this).filter { it.cacheCheckCondition() }
fun removeFromCache(entity: Entity) {
val cache = warmCache()
cache.remove(table, entity)
cache.referrers.remove(entity)
cache.removeTablesReferrers(listOf(table))
}
public fun forEntityIds(ids: List<EntityID>) : SizedIterable<T> {
val cached = ids.map { testCache(it) }.filterNotNull()
if (cached.size == ids.size) {
return SizedCollection(cached)
}
return wrapRows(searchQuery(Op.build {table.id inList ids}))
}
public fun forIds(ids: List<Int>) : SizedIterable<T> {
val cached = ids.map { testCache(EntityID(it, table)) }.filterNotNull()
if (cached.size == ids.size) {
return SizedCollection(cached)
}
return wrapRows(searchQuery(Op.build {table.id inList ids.map {EntityID(it, table)}}))
}
public fun wrapRows(rows: SizedIterable<ResultRow>): SizedIterable<T> {
val session = Session.get()
return rows mapLazy {
wrapRow(it, session)
}
}
public fun wrapRow (row: ResultRow, session: Session) : T {
val entity = wrap(row[table.id], row, session)
if (entity._readValues == null)
entity._readValues = row
return entity
}
open public fun all(): SizedIterable<T> = wrapRows(table.selectAll().notForUpdate())
public fun find(op: Op<Boolean>): SizedIterable<T> {
warmCache()
return wrapRows(searchQuery(op))
}
public fun find(op: SqlExpressionBuilder.()->Op<Boolean>): SizedIterable<T> {
warmCache()
return find(SqlExpressionBuilder.op())
}
fun findWithCacheCondition(cacheCheckCondition: T.()->Boolean, op: SqlExpressionBuilder.()->Op<Boolean>): SizedIterable<T> {
val cached = testCache(cacheCheckCondition)
return if (cached.isNotEmpty()) SizedCollection(cached) else find(op)
}
open val dependsOnTables: ColumnSet get() = table
open val dependsOnColumns: List<Column<out Any?>> get() = dependsOnTables.columns
open fun searchQuery(op: Op<Boolean>): Query {
return dependsOnTables.slice(dependsOnColumns).select { op }.setForUpdateStatus()
}
public fun count(op: Op<Boolean>? = null): Int {
return with (Session.get()) {
val query = table.slice(table.id.count())
(if (op == null) query.selectAll() else query.select{op}).notForUpdate().first()[
table.id.count()
]
}
}
protected open fun createInstance(entityId: EntityID, row: ResultRow?) : T = ctor.newInstance(entityId) as T
public fun wrap(id: EntityID, row: ResultRow?, s: Session): T {
val cache = EntityCache.getOrCreate(s)
return cache.find(this, id) ?: run {
val new = createInstance(id, row)
new.klass = this
cache.store(this, new)
new
}
}
public fun new(init: T.() -> Unit): T {
val prototype: T = createInstance(EntityID(-1, table), null)
prototype.klass = this
prototype._readValues = ResultRow.create(dependsOnColumns)
prototype.init()
warmCache().scheduleInsert(this, prototype)
return prototype
}
public inline fun view (op: SqlExpressionBuilder.() -> Op<Boolean>) : View<T> = View(SqlExpressionBuilder.op(), this)
infix public fun referencedOn(column: Column<EntityID>): Reference<T> {
return Reference(column, this)
}
infix public fun optionalReferencedOn(column: Column<EntityID?>): OptionalReference<T> {
return OptionalReference(column, this)
}
infix public fun optionalReferencedOnSureNotNull(column: Column<EntityID?>): OptionalReferenceSureNotNull<T> {
return OptionalReferenceSureNotNull(column, this)
}
public fun referrersOn(column: Column<EntityID>, cache: Boolean = false): Referrers<T> {
return Referrers(column, this, cache)
}
//TODO: what's the difference with referrersOn?
public fun optionalReferrersOn(column: Column<EntityID?>, cache: Boolean = false): OptionalReferrers<T> {
return OptionalReferrers(column, this, cache)
}
fun<TColumn: Any?,TReal: Any?> Column<TColumn>.transform(toColumn: (TReal) -> TColumn, toReal: (TColumn) -> TReal): ColumnWithTransform<TColumn, TReal> {
return ColumnWithTransform(this, toColumn, toReal)
}
fun<TReal: Enum<TReal>> Column<String?>.byEnumNullable(clazz : Class<TReal>): ColumnWithTransform<String?, TReal?> {
return ColumnWithTransform(this, { it?.name }, {it?.let{clazz.findValue(it)}})
}
fun<TReal: Enum<TReal>> Column<String>.byEnum(clazz : Class<TReal>): ColumnWithTransform<String, TReal> {
return ColumnWithTransform(this, { it.name }, {clazz.findValue(it)})
}
fun <T: Enum<T>> Class<T>.findValue(name: String) = enumConstants.first { it.name == name }
private fun Query.setForUpdateStatus(): Query = if (this@EntityClass is ImmutableEntityClass<*>) this.notForUpdate() else this
}
abstract public class ImmutableEntityClass<out T: Entity>(table: IdTable) : EntityClass<T>(table) {
open public fun <T> forceUpdateEntity(entity: Entity, column: Column<T>, value: T?) {
table.update({ table.id eq entity.id }) {
it[column] = value
}
}
}
abstract public class ImmutableCachedEntityClass<T: Entity>(table: IdTable) : ImmutableEntityClass<T>(table) {
private var _cachedValues: MutableMap<Int, Entity>? = null
final override fun warmCache(): EntityCache {
val sessionCache = super.warmCache()
if (_cachedValues == null) synchronized(this) {
for(r in super.all()) { /* force iteration to initialize lazy collection */ }
_cachedValues = sessionCache.data[table]
} else {
sessionCache.data.getOrPut(table) { _cachedValues!! }
}
return sessionCache
}
override fun all(): SizedIterable<T> = warmCache().findAll(this)
public @Synchronized fun expireCache() {
_cachedValues = null
}
override public fun <T> forceUpdateEntity(entity: Entity, column: Column<T>, value: T?) {
super.forceUpdateEntity(entity, column, value)
entity._readValues?.set(column, value)
expireCache()
}
}
| agpl-3.0 | 2d02c549b2a41372c07325bd81299bd5 | 34.690828 | 157 | 0.599411 | 4.262721 | false | false | false | false |
craigjbass/pratura | src/test/kotlin/uk/co/craigbass/pratura/unit/usecase/administration/AddProductSpec.kt | 1 | 1254 | package uk.co.craigbass.pratura.unit.usecase.administration
import org.amshove.kluent.shouldEqual
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.it
import uk.co.craigbass.pratura.acceptance.testdouble.InMemoryProductGateway
import uk.co.craigbass.pratura.boundary.administration.AddProduct.Request
import uk.co.craigbass.pratura.math.toDecimal
import uk.co.craigbass.pratura.usecase.administration.AddProduct
class AddProductSpec : Spek({
val productGateway = InMemoryProductGateway()
val useCase = memoized { AddProduct(productGateway) }
beforeEachTest {
useCase().execute(Request(
sku = "sku:1029317",
price = "6.99".toDecimal(),
name = "Pack of 4 AA Batteries"
))
}
val savedProducts = memoized { productGateway.all() }
val firstSavedProduct = memoized { savedProducts().first() }
it("should have saved one product") {
savedProducts().count().shouldEqual(1)
}
it("should have the correct sku") {
firstSavedProduct().sku.shouldEqual("sku:1029317")
}
it("should have the correct price") {
firstSavedProduct().price.shouldEqual("6.99".toDecimal())
}
it("should have the correct name") {
firstSavedProduct().name.shouldEqual("Pack of 4 AA Batteries")
}
})
| bsd-3-clause | 35c97ddfd55be1c3720b1e74949146fa | 30.35 | 75 | 0.735247 | 3.823171 | false | false | false | false |
pdvrieze/ProcessManager | darwin/ktor/src/jvmMain/kotlin/io/github/pdvrieze/darwin/ktor/main.kt | 1 | 2811 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
/**
* Created by pdvrieze on 28/03/16.
*/
package io.github.pdvrieze.darwin.ktor
import io.github.pdvrieze.darwin.ktor.support.KtorServletRequestInfo
import io.github.pdvrieze.darwin.ktor.support.darwinResponse
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.content.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.serialization.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.util.pipeline.*
import kotlinx.html.img
import kotlinx.html.stream.appendHTML
import uk.ac.bournemouth.darwin.html.darwinDialog
import uk.ac.bournemouth.darwin.html.darwinMenu
import java.io.File
fun main() {
embeddedServer(Netty, 9090) {
install(ContentNegotiation) {
json()
// xml()
}
install(Compression) {
gzip()
}
routing {
get("/") { mainPage() }
get("/common/menu") { menu() }
static("/") {
resources("")
}
route("/js") {
get("{static-content-path-parameter...}") {
// val packageName = staticBasePackage.combinePackage(resourcePackage)
val relativePath = call.parameters.getAll("static-content-path-parameter")?.joinToString(File.separator) ?: return@get
val content = call.resolveResource(relativePath, "js") ?:
call.resolveResource("META-INF/resources/webjars/requirejs/2.3.5/"+relativePath, "")
if (content != null) {
call.respond(content)
}
}
}
}
}.start(wait = true)
}
private suspend fun PipelineContext<Unit, ApplicationCall>.mainPage() {
darwinResponse {
darwinDialog(title = "loading", id="banner") {
img(alt="loading...", src="/assets/progress_large.gif") { width="192"; height="192"}
}
}
}
private suspend fun PipelineContext<Unit, ApplicationCall>.menu() {
call.respondTextWriter {
appendHTML().darwinMenu(KtorServletRequestInfo(call))
}
}
| lgpl-3.0 | 298b2c96e1941ebaaccc135602b0b2d1 | 32.464286 | 138 | 0.63963 | 4.265554 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmMain/kotlin/nl/adaptivity/process/engine/HProcessInstance.kt | 1 | 2191 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
typealias HProcessInstance = Handle<SecureObject<ProcessInstance>>
//@Serializable
//@XmlSerialName(HProcessInstance.ELEMENTLOCALNAME, Engine.NAMESPACE, Engine.NSPREFIX)
//class HProcessInstance : XmlHandle<@UseContextualSerialization SecureObject<@UseContextualSerialization ProcessInstance>> {
//
// constructor(handle: ComparableHandle<SecureObject<ProcessInstance>>) : super(handle)
//
// class Factory : XmlDeserializerFactory<HProcessInstance> {
//
// @Throws(XmlException::class)
// override fun deserialize(reader: XmlReader): HProcessInstance {
// return HProcessInstance.deserialize(reader)
// }
// }
//
// constructor() : this(getInvalidHandle<SecureObject<ProcessInstance>>())
//
// override fun equals(other: Any?): Boolean {
// return other === this || other is HProcessInstance && handleValue == other.handleValue
// }
//
// override fun hashCode(): Int {
// return handleValue.toInt()
// }
//
// companion object {
//
// @Throws(XmlException::class)
// private fun deserialize(xmlReader: XmlReader): HProcessInstance {
// return XML.parse(xmlReader, serializer())
// }
// }
//
//}
//
//@Serializable
//@XmlSerialName(HProcessInstance.ELEMENTLOCALNAME, Engine.NAMESPACE, Engine.NSPREFIX)
//internal class HProcessInstanceSerialHelper(@XmlValue(true) val handle: Long)
| lgpl-3.0 | 61ff2573b715a30973d7ad266d0a8766 | 36.135593 | 125 | 0.720219 | 4.355865 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/ProductsStore.kt | 2 | 2680 | package org.wordpress.android.fluxc.store
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.ProductAction
import org.wordpress.android.fluxc.action.ProductAction.FETCH_PRODUCTS
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.model.products.Product
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.products.ProductsRestClient
import org.wordpress.android.fluxc.store.ProductsStore.FetchProductsErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProductsStore @Inject constructor(
private val productsRestClient: ProductsRestClient,
private val coroutineEngine: CoroutineEngine,
dispatcher: Dispatcher
) : Store(dispatcher) {
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
when (action.type as? ProductAction ?: return) {
FETCH_PRODUCTS -> {
coroutineEngine.launch(AppLog.T.API, this, "FETCH_PRODUCTS") {
emitChange(fetchProducts())
}
}
}
}
override fun onRegister() {
AppLog.d(AppLog.T.API, ProductsStore::class.java.simpleName + " onRegister")
}
suspend fun fetchProducts(): OnProductsFetched =
coroutineEngine.withDefaultContext(T.API, this, "Fetch products") {
return@withDefaultContext when (val response = productsRestClient.fetchProducts()) {
is Success -> {
OnProductsFetched(response.data.products)
}
is Error -> {
OnProductsFetched(FetchProductsError(GENERIC_ERROR, response.error.message))
}
}
}
data class OnProductsFetched(val products: List<Product>? = null) : Store.OnChanged<FetchProductsError>() {
constructor(error: FetchProductsError) : this() {
this.error = error
}
}
data class FetchProductsError(
val type: FetchProductsErrorType,
val message: String = ""
) : OnChangedError
enum class FetchProductsErrorType {
GENERIC_ERROR
}
}
| gpl-2.0 | 9bc80b5a183b0c334dacc4a8b1fd23a5 | 39 | 111 | 0.683209 | 4.768683 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/scenario/verifycode/SelfVerifiedCode.kt | 1 | 885 | package scenario.verifycode
fun generateCode(productId: String) : String{
var sum1 = 0
var sum2 = 0
val chars = productId.toCharArray()
for (i in 0 until productId.length) {
val num = chars[i] - '0'
sum1 += num * (10 - i)
sum2 += num * (7 + i)
}
val suffix1 = getSuffix(sum1)
val suffix2 = getSuffix(sum2)
return productId + suffix1 + suffix2
}
fun getSuffix(sum : Int) : String{
val mod = sum % 11
val result = (11 - mod) % 11 //结果为11, 就要变成0. 因为每个校验码都只有一位
val suffix = if (result == 10) "x" else "" + result
return suffix
}
fun main(args: Array<String>) {
println("output = " + generateCode("155192370"))
println("output = " + generateCode("140007917"))
println("output = " + generateCode("037541457"))
println("output = " + generateCode("037428158"))
} | apache-2.0 | c16c967395cdd40e57a426f7309e8c93 | 26.354839 | 61 | 0.604486 | 3.232824 | false | false | false | false |
mopsalarm/Pr0 | model/src/main/java/com/pr0gramm/app/model/update/UpdateModel.kt | 1 | 393 | package com.pr0gramm.app.model.update
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class UpdateModel(val version: Int, val apk: String, val changelog: String)
@JsonClass(generateAdapter = true)
class Change(val type: String, val change: String)
@JsonClass(generateAdapter = true)
class ChangeGroup(val version: Int = 0, val changes: List<Change> = listOf())
| mit | 9c04713fbcf89254fa212be4167100fc | 31.75 | 80 | 0.776081 | 3.672897 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher | web/src/main/kotlin/org/metplus/cruncher/web/security/filters/ApplicationLoginFilter.kt | 1 | 1734 | package org.metplus.cruncher.web.security.filters
import org.metplus.cruncher.web.security.services.TokenService
import org.metplus.cruncher.web.security.useCases.UserTryToLogin
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class ApplicationLoginFilter(@field:Autowired
private val loginUseCase: UserTryToLogin, @field:Autowired
private val tokenService: TokenService) : HandlerInterceptorAdapter() {
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest?, response: HttpServletResponse?, handler: Any?): Boolean {
val username = request!!.getHeader("X-Auth-Username")
val password = request.getHeader("X-Auth-Password")
if (loginUseCase.canUserLogin(username, password)) {
logger.info("Login successful for '{}'", username)
response!!.status = 200
response.outputStream.print("{\"token\": \"" + tokenService.generateToken(request.remoteAddr) + "\"}")
response.outputStream.flush()
response.contentType = "application/json"
} else {
logger.info("Invalid credentials on request from '{}'", request.remoteAddr)
response!!.status = 401
response.outputStream.print("{\"error\": \"the username `${username}` and password provided do not match\"}")
}
return false
}
companion object {
private val logger = LoggerFactory.getLogger(ApplicationLoginFilter::class.java)
}
}
| gpl-3.0 | acf2cb5b7c835de1b62999c7c6d03018 | 44.631579 | 121 | 0.692618 | 5.040698 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/widget/VLCAppWidgetProvider.kt | 1 | 8223 | /*****************************************************************************
* VLCAppWidgetProvider.java
*
* Copyright © 2012 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.widget
import android.annotation.TargetApi
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import android.widget.RemoteViews
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.videolan.resources.*
import org.videolan.tools.runIO
import org.videolan.tools.runOnMainThread
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.PlaybackService
import org.videolan.vlc.R
import org.videolan.vlc.StartActivity
import org.videolan.vlc.gui.helpers.AudioUtil
import org.videolan.vlc.util.getPendingIntent
import java.util.*
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
abstract class VLCAppWidgetProvider : AppWidgetProvider() {
protected abstract fun getlayout(): Int
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
/* init widget */
onReceive(context, Intent(ACTION_WIDGET_INIT))
/* ask a refresh from the service if there is one */
context.sendBroadcast(Intent(ACTION_WIDGET_INIT).setPackage(BuildConfig.APP_ID))
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action == null || !action.startsWith(ACTION_WIDGET_PREFIX)) {
super.onReceive(context, intent)
return
}
val views = RemoteViews(BuildConfig.APP_ID, getlayout())
val partial = ACTION_WIDGET_INIT != action
if (!partial) {
/* commands */
val appCtx = context.applicationContext
val iBackward = Intent(ACTION_REMOTE_BACKWARD, null, appCtx, PlaybackService::class.java)
val iPlay = Intent(ACTION_REMOTE_PLAYPAUSE, null, appCtx, PlaybackService::class.java)
val iStop = Intent(ACTION_REMOTE_STOP, null, appCtx, PlaybackService::class.java)
val iForward = Intent(ACTION_REMOTE_FORWARD, null, appCtx, PlaybackService::class.java)
val iVlc = Intent(appCtx, StartActivity::class.java)
val piBackward = context.getPendingIntent(iBackward)
val piPlay = context.getPendingIntent(iPlay)
val piStop = context.getPendingIntent(iStop)
val piForward = context.getPendingIntent(iForward)
val piVlc = PendingIntent.getActivity(context, 0, iVlc, PendingIntent.FLAG_UPDATE_CURRENT)
views.setOnClickPendingIntent(R.id.backward, piBackward)
views.setOnClickPendingIntent(R.id.play_pause, piPlay)
views.setOnClickPendingIntent(R.id.stop, piStop)
views.setOnClickPendingIntent(R.id.forward, piForward)
views.setOnClickPendingIntent(R.id.cover, piVlc)
views.setOnClickPendingIntent(R.id.widget_container, piVlc)
if (TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL) {
val black = this is VLCAppWidgetProviderBlack
views.setImageViewResource(R.id.forward, if (black) R.drawable.ic_widget_previous_w else R.drawable.ic_widget_previous)
views.setImageViewResource(R.id.backward, if (black) R.drawable.ic_widget_next_w else R.drawable.ic_widget_next)
}
}
when {
ACTION_WIDGET_UPDATE == action -> {
val title = intent.getStringExtra("title")
val artist = intent.getStringExtra("artist")
val isplaying = intent.getBooleanExtra("isplaying", false)
views.setTextViewText(R.id.songName, title)
views.setTextViewText(R.id.artist, artist)
views.setImageViewResource(R.id.play_pause, getPlayPauseImage(isplaying))
}
ACTION_WIDGET_UPDATE_COVER == action -> {
val artworkMrl = intent.getStringExtra("artworkMrl")
if (!TextUtils.isEmpty(artworkMrl)) {
runIO(Runnable {
val cover = AudioUtil.readCoverBitmap(Uri.decode(artworkMrl), 320)
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val dm = DisplayMetrics().also { wm.defaultDisplay.getMetrics(it) }
runOnMainThread(Runnable {
if (cover != null) {
if (cover.byteSize() < dm.widthPixels * dm.heightPixels * 6) views.setImageViewBitmap(R.id.cover, cover)
} else
views.setImageViewResource(R.id.cover, R.drawable.icon)
views.setProgressBar(R.id.timeline, 100, 0, false)
applyUpdate(context, views, partial)
})
})
} else
views.setImageViewResource(R.id.cover, R.drawable.icon)
views.setProgressBar(R.id.timeline, 100, 0, false)
}
ACTION_WIDGET_UPDATE_POSITION == action -> {
val pos = intent.getFloatExtra("position", 0f)
views.setProgressBar(R.id.timeline, 100, (100 * pos).toInt(), false)
}
}
applyUpdate(context, views, partial)
}
private fun applyUpdate(context: Context, views: RemoteViews, partial: Boolean) {
val widget = ComponentName(context, this.javaClass)
val manager = AppWidgetManager.getInstance(context)
if (partial)
manager.partiallyUpdateAppWidget(manager.getAppWidgetIds(widget), views)
else
manager.updateAppWidget(widget, views)
}
protected abstract fun getPlayPauseImage(isPlaying: Boolean): Int
override fun onEnabled(context: Context) {
super.onEnabled(context)
context.sendBroadcast(Intent(ACTION_WIDGET_ENABLED, null, context.applicationContext, PlaybackService::class.java))
}
override fun onDisabled(context: Context) {
super.onDisabled(context)
context.sendBroadcast(Intent(ACTION_WIDGET_DISABLED, null, context.applicationContext, PlaybackService::class.java))
}
companion object {
const val TAG = "VLC/VLCAppWidgetProvider"
val ACTION_WIDGET_PREFIX = "widget.".buildPkgString()
val ACTION_WIDGET_INIT = ACTION_WIDGET_PREFIX + "INIT"
val ACTION_WIDGET_UPDATE = ACTION_WIDGET_PREFIX + "UPDATE"
val ACTION_WIDGET_UPDATE_COVER = ACTION_WIDGET_PREFIX + "UPDATE_COVER"
val ACTION_WIDGET_UPDATE_POSITION = ACTION_WIDGET_PREFIX + "UPDATE_POSITION"
val ACTION_WIDGET_ENABLED = ACTION_WIDGET_PREFIX + "ENABLED"
val ACTION_WIDGET_DISABLED = ACTION_WIDGET_PREFIX + "DISABLED"
}
}
fun Bitmap.byteSize(): Int {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
return allocationByteCount
}
return rowBytes * height
} | gpl-2.0 | ca26f9131aae201247046ad1d1729127 | 43.934426 | 136 | 0.663221 | 4.632113 | false | false | false | false |
didi/DoraemonKit | Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/processor/DoKitPluginConfigProcessor.kt | 2 | 8130 | package com.didichuxing.doraemonkit.plugin.processor
import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.ApplicationVariant
import com.android.build.gradle.api.BaseVariant
import com.android.build.gradle.internal.pipeline.TransformTask
import com.didichuxing.doraemonkit.plugin.*
import com.didichuxing.doraemonkit.plugin.extension.DoKitExt
import com.didiglobal.booster.gradle.dependencies
import com.didiglobal.booster.gradle.getAndroid
import com.didiglobal.booster.gradle.mergedManifests
import com.didiglobal.booster.gradle.project
import com.didiglobal.booster.task.spi.VariantProcessor
import com.didiglobal.booster.transform.ArtifactManager
import com.didiglobal.booster.transform.artifacts
import com.didiglobal.booster.transform.util.ComponentHandler
import org.gradle.api.Project
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import java.lang.NullPointerException
import javax.xml.parsers.SAXParserFactory
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/5/15-11:28
* 描 述:
* 修订历史:
* ================================================
*/
class DoKitPluginConfigProcessor(val project: Project) : VariantProcessor {
override fun process(variant: BaseVariant) {
if (!DoKitExtUtil.DOKIT_PLUGIN_SWITCH) {
return
}
if (variant.isRelease()) {
return
}
//统计三方库信息
if (DoKitExtUtil.THIRD_LIBINFO_SWITCH) {
//遍历三方库
val dependencies = variant.dependencies
DoKitExtUtil.THIRD_LIB_INFOS.clear()
for (artifactResult: ResolvedArtifactResult in dependencies) {
//println("三方库信息===>${artifactResult.variant.displayName}____${artifactResult.file.toString()}")
///Users/didi/project/android/dokit_github/DoraemonKit/Android/java/app/libs/BaiduLBS_Android.jar
///Users/didi/.gradle/caches/modules-2/files-2.1/androidx.activity/activity-ktx/1.2.0/c16aac66e6c4617b01118ab2509f009bb7919b3b/activity-ktx-1.2.0.aar
//println("三方库信息===>${artifactResult.variant.displayName}____${artifactResult.file.toString()}")
// "artifactResult===>${artifactResult.file}|${artifactResult.variant}|${artifactResult.id}|${artifactResult.type}".println()
//"artifactResult===>${artifactResult.variant.owner}|${artifactResult.variant.attributes}|${artifactResult.variant.displayName}|${artifactResult.variant.capabilities}|${artifactResult.variant.externalVariant}".println()
//"artifactResult===>${artifactResult.variant.displayName}".println()
val variants = artifactResult.variant.displayName.split(" ")
var thirdLibInfo: ThirdLibInfo? = null
if (variants.size == 3) {
thirdLibInfo = ThirdLibInfo(
variants[0],
artifactResult.file.length()
)
if (thirdLibInfo.variant.contains("dokitx-rpc")) {
DoKitExtUtil.HAS_DOKIT_RPC_MODULE = true
}
if (thirdLibInfo.variant.contains("dokitx-tcp-hook-dj")) {
DoKitExtUtil.HAS_DOKIT_TCP_HOOK_DJ = true
}
if (thirdLibInfo.variant.contains("dokitx-gps-mock") || thirdLibInfo.variant.contains("dokit-gps-mock")){
DoKitExtUtil.DOKIT_GPS_MOCK_INCLUDE = true;
}
// "thirdLibInfo.variant===>${thirdLibInfo.variant}".println()
DoKitExtUtil.THIRD_LIB_INFOS.add(thirdLibInfo)
} else if (variants.size == 4) {
thirdLibInfo = ThirdLibInfo(
"porject ${variants[1]}",
artifactResult.file.length()
)
if (thirdLibInfo.variant.contains("doraemonkit-rpc")) {
DoKitExtUtil.HAS_DOKIT_RPC_MODULE = true
}
if (thirdLibInfo.variant.contains("dokitx-tcp-hook-dj")) {
DoKitExtUtil.HAS_DOKIT_TCP_HOOK_DJ = true
}
if (thirdLibInfo.variant.contains("dokitx-gps-mock") || thirdLibInfo.variant.contains("dokit-gps-mock")){
DoKitExtUtil.DOKIT_GPS_MOCK_INCLUDE = true;
}
// "thirdLibInfo.variant===>${thirdLibInfo.variant}".println()
DoKitExtUtil.THIRD_LIB_INFOS.add(thirdLibInfo)
}
// val paths = artifactResult.file.toString().split("/")
// var fileName: String = ""
// var groupId: String = ""
// var artifactId: String = ""
// var version: String = ""
// if (artifactResult.file.toString().contains(".gradle/caches")) {
// if (paths.size >= 5) {
// groupId = paths[paths.size - 5]
// artifactId = paths[paths.size - 4]
// version = paths[paths.size - 3]
// fileName =
// "$groupId:$artifactId:$version"
// } else {
// fileName = paths[paths.size - 1]
// }
// } else {
// fileName = paths[paths.size - 1]
// }
//
// val thirdLibInfo =
// ThirdLibInfo(
// groupId,
// artifactId,
// version,
// fileName,
// artifactResult.file.length(),
// artifactResult.variant.displayName
// )
// val key = "$groupId:$artifactId"
// if (DoKitExtUtil.THIRD_LIB_INFOS[key] == null) {
// DoKitExtUtil.THIRD_LIB_INFOS[key] = thirdLibInfo
// } else {
// val libInfo = DoKitExtUtil.THIRD_LIB_INFOS[key]
// if (DoKitPluginUtil.compareVersion(thirdLibInfo.version, libInfo!!.version) > 0) {
// DoKitExtUtil.THIRD_LIB_INFOS[key] = thirdLibInfo
// }
// }
}
}
//查找application module下的配置
if (variant is ApplicationVariant) {
project.tasks.find {
//"===task Name is ${it.name}".println()
it.name == "processDebugManifest"
}?.let { transformTask ->
transformTask.doLast {
"===processDebugManifest task has executed===".println()
//查找AndroidManifest.xml 文件路径
variant.mergedManifests.forEach { manifest ->
val parser = SAXParserFactory.newInstance().newSAXParser()
val handler = DoKitComponentHandler()
"App Manifest path====>$manifest".println()
parser.parse(manifest, handler)
"App PackageName is====>${handler.appPackageName}".println()
"App Application path====>${handler.applications}".println()
DoKitExtUtil.setAppPackageName(handler.appPackageName)
DoKitExtUtil.setApplications(handler.applications)
}
//读取插件配置
variant.project.getAndroid<AppExtension>().let { appExt ->
//查找Application路径
val doKitExt = variant.project.extensions.getByType(DoKitExt::class.java)
DoKitExtUtil.init(doKitExt)
}
}
}
} else {
"${variant.project.name}-不建议在Library Module下引入dokit插件".println()
}
}
}
| apache-2.0 | dd721560e2e52dfc2afb7fcff7e95237 | 45.115607 | 235 | 0.534846 | 4.71513 | false | false | false | false |
didi/DoraemonKit | Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/action/file/FileListAction.kt | 1 | 4415 | package com.didichuxing.doraemonkit.kit.filemanager.action.file
import com.didichuxing.doraemonkit.util.ConvertUtils
import com.didichuxing.doraemonkit.util.FileUtils
import com.didichuxing.doraemonkit.util.PathUtils
import com.didichuxing.doraemonkit.util.ToastUtils
import com.didichuxing.doraemonkit.R as DoKitR
import com.didichuxing.doraemonkit.kit.filemanager.FileManagerUtil
import com.didichuxing.doraemonkit.util.DoKitCommUtil
import java.io.File
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/6/23-15:26
* 描 述:
* 修订历史:
* ================================================
*/
object FileListAction {
fun fileListRes(dirPath: String): MutableMap<String, Any> {
//root path
val params = mutableMapOf<String, Any>().apply {
this["code"] = 200
}
if (dirPath == FileManagerUtil.ROOT_PATH_STR) {
val data = mutableMapOf<String, Any>().apply {
this["dirPath"] = FileManagerUtil.ROOT_PATH_STR
this["fileList"] = createRootInfo()
}
params["data"] = data
} else {
//not root path
val data = mutableMapOf<String, Any>().apply {
this["dirPath"] = FileManagerUtil.relativeRootPath(dirPath)
val fileInfos = traverseDir(dirPath)
if (dirPath == FileManagerUtil.externalStorageRootPath && fileInfos.isEmpty()) {
this["code"] = 0
this["message"] =
DoKitCommUtil.getString(DoKitR.string.dk_file_manager_sd_permission_tip)
ToastUtils.showShort(DoKitCommUtil.getString(DoKitR.string.dk_file_manager_sd_permission_tip))
}
this["fileList"] = fileInfos
}
params["data"] = data
}
return params
}
/**
* 遍历根文件夹
*/
private fun createRootInfo(): MutableList<FileInfo> {
val fileInfos = mutableListOf<FileInfo>()
val internalAppDataPath = PathUtils.getInternalAppDataPath()
val externalStoragePath = PathUtils.getExternalStoragePath()
fileInfos.add(
FileInfo(
FileManagerUtil.ROOT_PATH_STR,
FileUtils.getFileName(internalAppDataPath),
"",
"folder",
"",
"" + FileUtils.getFileLastModified(internalAppDataPath),
true
)
)
fileInfos.add(
FileInfo(
FileManagerUtil.ROOT_PATH_STR,
"external",
"",
"folder",
"",
"" + FileUtils.getFileLastModified(externalStoragePath),
true
)
)
return fileInfos
}
/**
* 遍历文件夹
*/
private fun traverseDir(dirPath: String): MutableList<FileInfo> {
val fileInfos = mutableListOf<FileInfo>()
val dir = File(dirPath)
if (FileUtils.isFileExists(dir) && FileUtils.isDir(dir)) {
dir.listFiles()?.forEach { file ->
val fileInfo = FileInfo(
FileManagerUtil.relativeRootPath(dirPath), file.name,
if (FileUtils.isDir(file)) {
""
} else {
ConvertUtils.byte2FitMemorySize(file.length(), 1)
},
if (FileUtils.isDir(file)) {
"folder"
} else if (dir.absolutePath.contains("/databases")) {
"db"
} else {
if (FileUtils.getFileExtension(file).isNotBlank()) {
FileUtils.getFileExtension(file)
} else {
"txt"
}
}, "", "" + FileUtils.getFileLastModified(file), false
)
fileInfos.add(fileInfo)
}
}
return fileInfos
}
data class FileInfo(
val dirPath: String,
val fileName: String,
val fileSize: String,
val fileType: String,
val fileUri: String,
val modifyTime: String,
val isRootPath: Boolean
)
}
| apache-2.0 | 2096472359f39b6391d62ce667923388 | 31.684211 | 114 | 0.509777 | 5.060536 | false | false | false | false |
songzhw/AndroidArchitecture | deprecated/RxJavaDemo/app/src/main/java/ca/six/rxdemo/combine/withLatestFrom.kt | 1 | 844 | package ca.six.rxdemo.combine
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
fun rxDemo() {
val one = Observable.interval(3, TimeUnit.SECONDS)
val two = Observable.interval(2, TimeUnit.SECONDS)
val disposable = two
.withLatestFrom(one, BiFunction<Long, Long, String> { num1, num2 ->
val sdf = SimpleDateFormat("hh:mm:ss")
"$num1, $num2 - ${sdf.format(Date())}"
})
.subscribe { str -> println("szw output = $str") }
}
/*
szw output = 1, 0 - 01:27:35
szw output = 2, 0 - 01:27:37
szw output = 3, 1 - 01:27:39
szw output = 4, 2 - 01:27:41
szw output = 5, 2 - 01:27:43
szw output = 6, 3 - 01:27:45
szw output = 7, 4 - 01:27:47
szw output = 8, 4 - 01:27:49
szw output = 9, 5 - 01:27:51
... ...
...
*/ | apache-2.0 | 2ef8c971a88d7888d2cce7736279a598 | 25.40625 | 71 | 0.652844 | 3.003559 | false | false | false | false |
dafi/photoshelf | core/src/main/java/com/ternaryop/photoshelf/activity/AbsPhotoShelfActivity.kt | 1 | 2939 | package com.ternaryop.photoshelf.activity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.ternaryop.photoshelf.core.R
import com.ternaryop.photoshelf.fragment.FragmentActivityStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
abstract class AbsPhotoShelfActivity : AppCompatActivity(), FragmentActivityStatus, CoroutineScope {
protected lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override val isDrawerMenuOpen: Boolean
get() = false
override val drawerToolbar: Toolbar
get() = findViewById<View>(R.id.drawer_toolbar) as Toolbar
/**
* The subclass doesn't call setContentView directly to avoid side effects (action mode bar doesn't overlap the
* toolbar but is shown above) but pass the layout id to use
* @return the layout id to use
*/
abstract val contentViewLayoutId: Int
/**
* The fragment returned by createFragment() replaces the existing one inside the specified [contentFrameId]
* It is not used when createFragment() returns null
*/
abstract val contentFrameId: Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
setContentView(contentViewLayoutId)
setupActionBar()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// create the fragment only if it doesn't already exist
if (savedInstanceState == null) {
createFragment()?.let { fragment ->
supportFragmentManager.beginTransaction().replace(contentFrameId, fragment).commit()
}
}
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
/**
* The fragment is added programmatically because in many cases its creation from XML layout can collide with
* the supportActionBar creation (eg the fragment needs the actionBar but it can't be created until
* the xml is full instantiated so it will be null)
* @return the fragment to use or null if no fragment must be added
*/
abstract fun createFragment(): Fragment?
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
// clicked the actionbar
// close and return to caller
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun setupActionBar(): Toolbar {
val toolbar = drawerToolbar
setSupportActionBar(toolbar)
return toolbar
}
}
| mit | 93a3e4adce0ed9334fab6a370ec7664b | 32.781609 | 115 | 0.686628 | 5.343636 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/report/pom/DependencyWriter.kt | 2 | 6365 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS 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 io.spine.internal.gradle.report.pom
import groovy.xml.MarkupBuilder
import java.io.Writer
import java.util.*
import kotlin.reflect.full.isSubclassOf
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.internal.artifacts.dependencies.AbstractExternalModuleDependency
import org.gradle.kotlin.dsl.withGroovyBuilder
/**
* Writes the dependencies of a Gradle project in a `pom.xml` format.
*
* Includes the dependencies of the subprojects. Does not include
* the transitive dependencies.
*
* ```
* <dependencies>
* <dependency>
* <groupId>io.spine</groupId>
* <artifactId>base</artifactId>
* <version>2.0.0-pre1</version>
* </dependency>
* ...
* </dependencies>
* ```
*
* When there are several versions of the same dependency, only the one with
* the newest version is retained.
*
* @see PomGenerator
*/
internal class DependencyWriter
private constructor(
private val dependencies: SortedSet<ScopedDependency>
) {
internal companion object {
/**
* Creates the `ProjectDependenciesAsXml` for the passed [project].
*/
fun of(project: Project): DependencyWriter {
return DependencyWriter(project.dependencies())
}
}
/**
* Writes the dependencies in their `pom.xml` format to the passed [out] writer.
*
* <p>Used writer will not be closed.
*/
fun writeXmlTo(out: Writer) {
val xml = MarkupBuilder(out)
xml.withGroovyBuilder {
"dependencies" {
dependencies.forEach { scopedDep ->
val dependency = scopedDep.dependency()
"dependency" {
"groupId" { xml.text(dependency.group) }
"artifactId" { xml.text(dependency.name) }
"version" { xml.text(dependency.version) }
if (scopedDep.hasDefinedScope()) {
"scope" { xml.text(scopedDep.scopeName()) }
}
}
}
}
}
}
}
/**
* Returns the [scoped dependencies][ScopedDependency] of a Gradle project.
*/
fun Project.dependencies(): SortedSet<ScopedDependency> {
val dependencies = mutableSetOf<ModuleDependency>()
dependencies.addAll(this.depsFromAllConfigurations())
this.subprojects.forEach { subproject ->
val subprojectDeps = subproject.depsFromAllConfigurations()
dependencies.addAll(subprojectDeps)
}
val result = deduplicate(dependencies)
.map { it.scoped }
.toSortedSet()
return result
}
/**
* Returns the external dependencies of the project from all the project configurations.
*/
private fun Project.depsFromAllConfigurations(): Set<ModuleDependency> {
val result = mutableSetOf<ModuleDependency>()
this.configurations.forEach { configuration ->
if (configuration.isCanBeResolved) {
// Force resolution of the configuration.
configuration.resolvedConfiguration
}
configuration.dependencies.filter { it.isExternal() }
.forEach { dependency ->
val moduleDependency = ModuleDependency(project, configuration, dependency)
result.add(moduleDependency)
}
}
return result
}
/**
* Tells whether the dependency is an external module dependency.
*/
private fun Dependency.isExternal(): Boolean {
return this.javaClass.kotlin.isSubclassOf(AbstractExternalModuleDependency::class)
}
/**
* Filters out duplicated dependencies by group and name.
*
* When there are several versions of the same dependency, the method will retain only
* the one with the newest version.
*
* Sometimes, a project uses several versions of the same dependency. This may happen
* when different modules of the project use different versions of the same dependency.
* But for our `pom.xml`, which has clearly representative character, a single version
* of a dependency is quite enough.
*
* The rejected duplicates are logged.
*/
private fun Project.deduplicate(dependencies: Set<ModuleDependency>): List<ModuleDependency> {
val groups = dependencies.distinctBy { it.gav }
.groupBy { it.run { "$group:$name" } }
logDuplicates(groups)
val filtered = groups.map { group ->
group.value.maxByOrNull { dep -> dep.version!! }!!
}
return filtered
}
private fun Project.logDuplicates(dependencies: Map<String, List<ModuleDependency>>) {
dependencies.filter { it.value.size > 1 }
.forEach { (dependency, versions) -> logDuplicate(dependency, versions) }
}
private fun Project.logDuplicate(dependency: String, versions: List<ModuleDependency>) {
logger.lifecycle("")
logger.lifecycle("The project uses several versions of `$dependency` dependency.")
versions.forEach {
logger.lifecycle(
"module: {}, configuration: {}, version: {}",
it.module.name,
it.configuration.name,
it.version
)
}
}
| apache-2.0 | 82d35dc98baedae6e4360167de4130da | 33.405405 | 94 | 0.670699 | 4.598988 | false | true | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/ProjectLabelManagementServiceImpl.kt | 2 | 2437 | package net.nemerosa.ontrack.service.labels
import net.nemerosa.ontrack.model.labels.*
import net.nemerosa.ontrack.model.security.ProjectView
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.repository.ProjectLabelRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class ProjectLabelManagementServiceImpl(
private val projectLabelRepository: ProjectLabelRepository,
private val labelManagementService: LabelManagementService,
private val labelProviderService: LabelProviderService,
private val securityService: SecurityService
) : ProjectLabelManagementService {
override fun getLabelsForProject(project: Project): List<Label> =
projectLabelRepository.getLabelsForProject(project.id())
.filter { record ->
val computedBy = record.computedBy
computedBy == null || (labelProviderService.getLabelProvider(computedBy)?.isEnabled ?: false)
}
.map { labelManagementService.getLabel(it.id) }
override fun getProjectsForLabel(label: Label): List<ID> =
projectLabelRepository.getProjectsForLabel(label.id)
.filter { securityService.isProjectFunctionGranted(it, ProjectView::class.java) }
.map { ID.of(it) }
override fun associateProjectToLabel(project: Project, label: Label) {
securityService.checkProjectFunction(project, ProjectLabelManagement::class.java)
projectLabelRepository.associateProjectToLabel(project.id(), label.id)
}
override fun unassociateProjectToLabel(project: Project, label: Label) {
securityService.checkProjectFunction(project, ProjectLabelManagement::class.java)
projectLabelRepository.unassociateProjectToLabel(project.id(), label.id)
}
override fun associateProjectToLabels(project: Project, form: ProjectLabelForm) {
securityService.checkProjectFunction(project, ProjectLabelManagement::class.java)
// Checks all labels
form.labels.map { labelManagementService.getLabel(it) }
// Saves the association
projectLabelRepository.associateProjectToLabels(project.id(), form)
}
} | mit | bc8eabe1f4dbe9e951d45c560c2ba267 | 46.803922 | 117 | 0.73492 | 4.98364 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/insight/InsightUtil.kt | 1 | 2667 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.facet.MinecraftFacet
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiModifier
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UParameter
import org.jetbrains.uast.getParentOfType
import org.jetbrains.uast.toUElementOfType
val UElement.uastEventListener: Pair<UClass, UMethod>?
get() {
// The PsiIdentifier is going to be a method of course!
val method = this.getParentOfType<UMethod>() ?: return null
if (method.javaPsi.hasModifierProperty(PsiModifier.ABSTRACT)) {
// I don't think any implementation allows for abstract method listeners.
return null
}
val module = ModuleUtilCore.findModuleForPsiElement(this.sourcePsi ?: return null) ?: return null
val instance = MinecraftFacet.getInstance(module) ?: return null
// Since each platform has their own valid listener annotations,
// some platforms may have multiple allowed annotations for various cases
val listenerAnnotations = instance.types.flatMap { it.listenerAnnotations }
var contains = false
for (listenerAnnotation in listenerAnnotations) {
if (method.findAnnotation(listenerAnnotation) != null) {
contains = true
break
}
}
if (!contains) {
return null
}
val (_, resolve) = method.uastEventParameterPair ?: return null
if (!instance.isStaticListenerSupported(method.javaPsi) && method.isStatic) {
return null
}
return resolve to method
}
val UMethod.uastEventParameterPair: Pair<UParameter, UClass>?
get() {
val firstParameter = this.uastParameters.firstOrNull()
?: return null // Listeners must have at least a single parameter
// Get the type of the parameter so we can start resolving it
@Suppress("UElementAsPsi") // UVariable overrides getType so it should be fine to use on UElements...
val type = firstParameter.type as? PsiClassType ?: return null
// Validate that it is a class reference type
// And again, make sure that we can at least resolve the type, otherwise it's not a valid
// class reference.
val resolve = type.resolve()?.toUElementOfType<UClass>() ?: return null
return firstParameter to resolve
}
| mit | 6b3e658896159daddb420086f6933b2f | 37.652174 | 109 | 0.681665 | 4.92976 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/DYRecordView.kt | 1 | 5111 | package com.hewking.custom
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import androidx.core.view.GestureDetectorCompat
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import com.hewking.custom.util.UiUtil
/**
* 类的描述:模仿抖音
* 创建人员:hewking
* 创建时间:2018/7/23
* 修改人员:hewking
* 修改时间:2018/7/23
* 修改备注:
* Version: 1.0.0
*/
class DYRecordView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) {
private var mLargeCanvas: Canvas? = null
private var mLargeBitmap: Bitmap? = null
private var mlargeRadius = UiUtil.dipToPx(ctx, 50)
private var mSmallRadius = UiUtil.dipToPx(ctx, 40)
private var mCx: Float = 0f
private var mCy: Float = 0f
private val mPaint: Paint by lazy {
Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
color = Color.GREEN
}
}
init {
val typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.DepthView)
typedArray.recycle()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
startBreatheAnim()
}
private var breathAnimator: ValueAnimator? = null
private var breathValue = 0f
private fun startBreatheAnim() {
if (breathAnimator == null) {
breathAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
repeatMode = ValueAnimator.REVERSE
duration = 1000
interpolator = DecelerateInterpolator()
repeatCount = ValueAnimator.INFINITE
addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
override fun onAnimationUpdate(animation: ValueAnimator?) {
breathValue = (animation?.animatedValue) as Float
postInvalidateOnAnimation()
}
})
addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
}
})
start()
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stopBreathAnim()
}
private val mGesterDetector = GestureDetectorCompat(ctx, object : GestureDetector.SimpleOnGestureListener() {
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
mCy -= distanceX
mCy -= distanceY
return true
}
override fun onDown(e: MotionEvent?): Boolean {
return super.onDown(e)
}
})
override fun onTouchEvent(event: MotionEvent): Boolean {
// return mGesterDetector.onTouchEvent(event)
mCx = event?.x
mCy = event?.y
when(event?.actionMasked) {
MotionEvent.ACTION_DOWN -> {
}
MotionEvent.ACTION_MOVE -> {
}
MotionEvent.ACTION_DOWN -> {
}
}
return true
}
private fun stopBreathAnim() {
breathAnimator?.cancel()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (w > 0 && h > 0) {
mLargeBitmap?.recycle()
mLargeBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
mLargeCanvas = Canvas(mLargeBitmap)
mCx = w / 2f
mCy = h / 2f
}
}
override fun onDraw(canvas: Canvas?) {
mLargeCanvas?.let {
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
it.drawPaint(mPaint)
mPaint?.xfermode = null
mPaint?.color = Color.GREEN
it.drawCircle(mCx, mCy, mlargeRadius.toFloat(), mPaint)
mPaint?.setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC_OUT))
mPaint?.color = Color.RED
it.drawCircle(mCx, mCy, mSmallRadius.toFloat() + breathValue * 15, mPaint)
canvas?.drawBitmap(mLargeBitmap, 0f, 0f, null)
}
}
}
| mit | 90ec44a084146f5d776161e5ab74b235 | 28.563636 | 113 | 0.574856 | 4.807436 | false | false | false | false |
lunivore/montecarluni | src/main/kotlin/com/lunivore/montecarluni/engine/RecordCreator.kt | 1 | 2791 | package com.lunivore.montecarluni.engine
import com.lunivore.montecarluni.Events
import com.lunivore.montecarluni.model.Record
import com.lunivore.montecarluni.model.UserNotification
import com.opencsv.CSVReader
import java.io.InputStream
import java.io.InputStreamReader
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* This will parse any date in UK or standard format, providing that a date with the year first also has
* 2-digit month and day (it is assumed that sensible people continue to be consistently sensible).
*
* Delimiters will also be parsed, so anything sensible is fine.
*
* Months are supported with both 3-letter and full word versions.
*
* Formats with the month at the start do not make sense and will not be supported.
*/
class RecordCreator(private val events: Events, private val dateFormatParser : (List<String>) -> DateTimeFormatter) {
constructor(events : Events) : this(events, DateFormatParser()){
}
init {
events.inputLoadedNotification.subscribe {
events.recordsParsedNotification.push(parseResolvedDates(it))
}
}
private fun parseResolvedDates(stream: InputStream): List<Record> {
val csv = CSVReader(InputStreamReader(stream))
val lines = csv.readAll()
if (lines.size < 2) { throw IllegalArgumentException("Csv file requires a header row and at least one row of data.") }
val resolvedIndex = lines[0].indexOfFirst { it == "Resolved" }
val updatedIndex = lines[0].indexOfFirst { it == "Updated" }
val resolveDatesAsLines = extractDate(lines, resolvedIndex)
val updatedDatesAsLines = extractDate(lines, updatedIndex)
val candidatesForDateFormat = resolveDatesAsLines.plus(updatedDatesAsLines).filter { it.isNotEmpty() }
val dateFormat = dateFormatParser(candidatesForDateFormat)
val result = resolveDatesAsLines.zip(updatedDatesAsLines)
if (result.any {it.first.isEmpty() && it.second.isEmpty()}) {
events.messageNotification.push(UserNotification("Could not find resolved or last updated dates for some records"))
return listOf()
} else {
return result.map {
Record(if (it.first.isEmpty()) null else LocalDateTime.parse(it.first, dateFormat),
if (it.second.isEmpty()) null else LocalDateTime.parse(it.second, dateFormat))
}
}
}
private fun extractDate(lines: MutableList<Array<String>>, resolvedIndex: Int): List<String> {
return lines.subList(1, lines.size)
.fold(listOf<String>()) { dates, value ->
if (!value.isEmpty()) dates.plus(value[resolvedIndex])
else dates
}
}
}
| apache-2.0 | 8f73b4f24b571a68e68a8cb5f3ddd3c4 | 38.309859 | 127 | 0.685059 | 4.508885 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/handlers/injectionPoint/AtResolver.kt | 1 | 8968 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint
import com.demonwav.mcdev.platform.mixin.reference.isMiscDynamicSelector
import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SLICE
import com.demonwav.mcdev.platform.mixin.util.findSourceElement
import com.demonwav.mcdev.util.computeStringArray
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiQualifiedReference
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.parentOfType
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
/**
* Resolves targets of @At.
*
* Resolution of this reference depends on @At.value(), each of which have their own [InjectionPoint]. This injection
* point is in charge of parsing, validating and resolving this reference.
*
* This reference can be resolved in four different ways.
* - [isUnresolved] only checks the bytecode of the target class, to check whether this reference is valid.
* - [TargetReference.resolveReference] resolves to the actual member being targeted, rather than the location it's
* referenced in the target method. This serves as a backup in case nothing else is found to navigate to, and so that
* find usages can take you back to this reference.
* - [collectTargetVariants] is used for auto-completion. It does not take into account what is actually in the target
* string, and instead matches everything the handler *could* match. The references resolve similarly to
* `resolveReference`, although new elements may be created if not found.
* - [resolveNavigationTargets] is used when the user attempts to navigate on this reference. This attempts to take you
* to the actual location in the source code of the target class which is being targeted. Potentially slow as it may
* decompile the target class.
*
* To support the above, injection points must be able to resolve the target element, and support a collect visitor and
* a navigation visitor. The collect visitor finds target instructions in the bytecode of the target method, and the
* navigation visitor makes a best-effort attempt at matching source code elements.
*/
class AtResolver(
private val at: PsiAnnotation,
private val targetClass: ClassNode,
private val targetMethod: MethodNode
) {
companion object {
private fun getInjectionPoint(at: PsiAnnotation): InjectionPoint<*>? {
var atCode = at.findDeclaredAttributeValue("value")?.constantStringValue ?: return null
// remove slice selector
val isInSlice = at.parentOfType<PsiAnnotation>()?.hasQualifiedName(SLICE) ?: false
if (isInSlice) {
if (SliceSelector.values().any { atCode.endsWith(":${it.name}") }) {
atCode = atCode.substringBeforeLast(':')
}
}
return InjectionPoint.byAtCode(atCode)
}
fun usesMemberReference(at: PsiAnnotation): Boolean {
val handler = getInjectionPoint(at) ?: return false
return handler.usesMemberReference()
}
fun getArgs(at: PsiAnnotation): Map<String, String> {
val args = at.findAttributeValue("args")?.computeStringArray() ?: return emptyMap()
return args.asSequence()
.map {
val parts = it.split('=', limit = 2)
if (parts.size == 1) {
parts[0] to ""
} else {
parts[0] to parts[1]
}
}
.toMap()
}
}
fun isUnresolved(): InsnResolutionInfo.Failure? {
val injectionPoint = getInjectionPoint(at)
?: return null // we don't know what to do with custom handlers, assume ok
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val collectVisitor = injectionPoint.createCollectVisitor(
at,
target,
targetClass,
CollectVisitor.Mode.MATCH_FIRST
)
if (collectVisitor == null) {
// syntax error in target
val stringValue = targetAttr?.constantStringValue ?: return InsnResolutionInfo.Failure()
return if (isMiscDynamicSelector(at.project, stringValue)) {
null
} else {
InsnResolutionInfo.Failure()
}
}
collectVisitor.visit(targetMethod)
return if (collectVisitor.result.isEmpty()) {
InsnResolutionInfo.Failure(collectVisitor.filterToBlame)
} else {
null
}
}
fun resolveInstructions(): List<CollectVisitor.Result<*>> {
return (getInstructionResolutionInfo() as? InsnResolutionInfo.Success)?.results ?: emptyList()
}
fun getInstructionResolutionInfo(): InsnResolutionInfo {
val injectionPoint = getInjectionPoint(at) ?: return InsnResolutionInfo.Failure()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val collectVisitor = injectionPoint.createCollectVisitor(at, target, targetClass, CollectVisitor.Mode.MATCH_ALL)
?: return InsnResolutionInfo.Failure()
collectVisitor.visit(targetMethod)
val result = collectVisitor.result
return if (result.isEmpty()) {
InsnResolutionInfo.Failure(collectVisitor.filterToBlame)
} else {
InsnResolutionInfo.Success(result)
}
}
fun resolveNavigationTargets(): List<PsiElement> {
// First resolve the actual target in the bytecode using the collect visitor
val injectionPoint = getInjectionPoint(at) ?: return emptyList()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val bytecodeResults = resolveInstructions()
// Then attempt to find the corresponding source elements using the navigation visitor
val targetElement = targetMethod.findSourceElement(
targetClass,
at.project,
GlobalSearchScope.allScope(at.project),
canDecompile = true
) ?: return emptyList()
val targetPsiClass = targetElement.parentOfType<PsiClass>() ?: return emptyList()
val navigationVisitor = injectionPoint.createNavigationVisitor(at, target, targetPsiClass) ?: return emptyList()
targetElement.accept(navigationVisitor)
return bytecodeResults.mapNotNull { bytecodeResult ->
navigationVisitor.result.getOrNull(bytecodeResult.index)
}
}
fun collectTargetVariants(completionHandler: (LookupElementBuilder) -> LookupElementBuilder): List<Any> {
val injectionPoint = getInjectionPoint(at) ?: return emptyList()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
// Collect all possible targets
fun <T : PsiElement> doCollectVariants(injectionPoint: InjectionPoint<T>): List<Any> {
val visitor = injectionPoint.createCollectVisitor(at, target, targetClass, CollectVisitor.Mode.COMPLETION)
?: return emptyList()
visitor.visit(targetMethod)
return visitor.result
.mapNotNull { result ->
injectionPoint.createLookup(targetClass, result)?.let { completionHandler(it) }
}
}
return doCollectVariants(injectionPoint)
}
}
sealed class InsnResolutionInfo {
class Success(val results: List<CollectVisitor.Result<*>>) : InsnResolutionInfo()
class Failure(val filterToBlame: String? = null) : InsnResolutionInfo() {
infix fun combine(other: Failure): Failure {
return if (filterToBlame != null) {
this
} else {
other
}
}
}
}
enum class SliceSelector {
FIRST, LAST, ONE
}
object QualifiedMember {
fun resolveQualifier(reference: PsiQualifiedReference): PsiClass? {
val qualifier = reference.qualifier ?: return null
((qualifier as? PsiReference)?.resolve() as? PsiClass)?.let { return it }
((qualifier as? PsiExpression)?.type as? PsiClassType)?.resolve()?.let { return it }
return null
}
}
| mit | 1094cc350f42ad721fe3c6005c05df45 | 41.50237 | 120 | 0.672614 | 5.156987 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/forge/reflection/reference/ReflectedFieldReference.kt | 1 | 5029 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.reflection.reference
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.simpleQualifiedMemberReference
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassObjectAccessExpression
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiExpressionList
import com.intellij.psi.PsiLiteral
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.ResolveResult
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.util.ProcessingContext
object ReflectedFieldReference : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
// The pattern for this provider should only match method params, but better be safe
if (element.parent !is PsiExpressionList) {
return arrayOf()
}
return arrayOf(Reference(element as PsiLiteral))
}
class Reference(element: PsiLiteral) : PsiReferenceBase.Poly<PsiLiteral>(element) {
val fieldName
get() = element.constantStringValue ?: ""
override fun getVariants(): Array<Any> {
val typeClass = findReferencedClass() ?: return arrayOf()
return typeClass.allFields
.asSequence()
.filter { !it.hasModifier(JvmModifier.PUBLIC) }
.map { field ->
JavaLookupElementBuilder.forField(field).withInsertHandler { context, _ ->
val literal = context.file.findElementAt(context.startOffset)?.parent as? PsiLiteral
?: return@withInsertHandler
val srgManager = literal.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val srgField = srgMap?.getSrgField(field.simpleQualifiedMemberReference)
?: return@withInsertHandler
context.setLaterRunnable {
// Commit changes made by code completion
context.commitDocument()
// Run command to replace PsiElement
CommandProcessor.getInstance().runUndoTransparentAction {
runWriteAction {
val params = literal.parent
val elementFactory = JavaPsiFacade.getElementFactory(context.project)
val srgLiteral = elementFactory.createExpressionFromText(
"\"${srgField.name}\"",
literal.parent
)
literal.replace(srgLiteral)
CodeStyleManager.getInstance(context.project).reformat(srgLiteral.parent, true)
context.editor.caretModel.moveToOffset(params.textRange.endOffset)
}
}
}
}
}
.toTypedArray()
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val typeClass = findReferencedClass() ?: return arrayOf()
val name = fieldName
val srgManager = element.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val mcpName = srgMap?.mapMcpToSrgName(name) ?: name
return typeClass.allFields.asSequence()
.filter { it.name == mcpName }
.map(::PsiElementResolveResult)
.toTypedArray()
}
private fun findReferencedClass(): PsiClass? {
val callParams = element.parent as? PsiExpressionList
val classRef = callParams?.expressions?.first() as? PsiClassObjectAccessExpression
val type = classRef?.operand?.type as? PsiClassType
return type?.resolve()
}
}
}
| mit | ac0db9467bb11c2fc35927e1257852e5 | 42.353448 | 115 | 0.616027 | 5.930425 | false | false | false | false |
egenvall/NameStats | NameStats/app/src/main/java/com/egenvall/namestats/main/MainPresenter.kt | 1 | 3064 | package com.egenvall.namestats.main
import com.egenvall.namestats.base.presentation.BaseDataView
import com.egenvall.namestats.base.presentation.BasePresenter
import com.egenvall.namestats.common.di.scope.PerScreen
import com.egenvall.namestats.base.presentation.BaseView
import com.egenvall.namestats.contacts.GetContactsUsecase
import com.egenvall.namestats.model.Contact
import com.egenvall.namestats.model.ContactItem
import com.egenvall.namestats.model.ContactList
import com.egenvall.namestats.model.ExpandableContactHeader
import com.genius.groupie.ExpandableGroup
import rx.Observer
import javax.inject.Inject
@PerScreen
class MainPresenter @Inject constructor(val getContactsUsecase: GetContactsUsecase) : BasePresenter<MainPresenter.View>() {
fun getContacts(){
getContactsUsecase.executeUsecase(object: Observer<ContactList>{
override fun onNext(response: ContactList) {
performViewAction { setContactList(formatContacts(response.contacts)) }
}
override fun onError(e: Throwable?) {
performViewAction { showMessage("Could not fetch contacts") }
}
override fun onCompleted() {}
})
}
/**
* Format the retrieved List of [Contact] into [ContactItem]
* These are then grouped by first character in the [ContactItem.name]
* into a [Map] <Character, List<ContactItem>>
* The Map is then traversed to construct[ExpandableGroup] [ExpandableContactHeader]
* that are used by Groupie for databinding & to create the expandable list headers.
*/
private fun formatContacts(input: List<Contact>) : List<ExpandableGroup>{
val list = mutableListOf<ContactItem>()
input.forEach {
list.add(ContactItem(it.name,it.number){view.clicked(it)})
}
val map = list.groupBy{ it.name[0]}.toSortedMap()
val groups = mutableListOf<ExpandableGroup>()
for ((letter,li) in map) {
val headerItem = ExpandableContactHeader(letter.toString(), li.size)
val expandableGroup = ExpandableGroup(headerItem)
for (item in li) {
expandableGroup.add(item)
}
headerItem.setExpandableGroup(expandableGroup)
groups.add(expandableGroup)
}
return groups
}
//===================================================================================
// View Interface
//===================================================================================
interface View : BaseView{
fun setContactList(group: List<ExpandableGroup>)
fun showMessage(message: String)
fun clicked(contact: ContactItem)
}
//===================================================================================
// Lifecycle Methods
//===================================================================================
override fun onViewAttached() {}
override fun onViewDetached() {}
override fun unsubscribe() {
getContactsUsecase.unsubscribe()
}
} | mit | 25800146303b63121a2e02a43eea712d | 38.805195 | 123 | 0.614883 | 4.990228 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/ai/analysis/AlgorithmRunnerInternal.kt | 1 | 5798 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmahjan.ai.analysis
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.collections.Mentsu
import java.util.*
/**
* Created by yuriel on 7/26/16.
*/
class AlgorithmRunnerInternal(
private val tehais: List<Hai>, private val furos: List<Mentsu>, private val algorithm: TehaiAnalysisAlgorithm) {
private val currentVector: IntArray
private val maxShantensu: Int
init {
this.currentVector = haiListToCountVector(tehais)
this.maxShantensu = algorithm.maxShantensu
}
fun runAlgorithm() {
tryChitoitsu()
tryNormalHora()
}
private fun tryChitoitsu() {
if (furos.size > 0) {
return
}
var numPairs = 0
var numSingles = 0
for (haiId in 0..NUM_HAI_ID - 1) {
if (currentVector[haiId] >= 2) {
numPairs++
} else if (currentVector[haiId] == 1) {
numSingles++
}
}
val numRequiredPairs = 7 - numPairs
val chitoitsuShantensu: Int
if (numSingles >= numRequiredPairs) {
chitoitsuShantensu = numRequiredPairs - 1
} else {
// This case is rarely important.
chitoitsuShantensu = numSingles + (numRequiredPairs - numSingles) * 2 - 1
}
if (chitoitsuShantensu > maxShantensu) {
return
}
val toitsuIds = ArrayList<Int>()
val targetVector = IntArray(NUM_HAI_ID)
for (haiId in 0..NUM_HAI_ID - 1) {
if (currentVector[haiId] >= 2) {
toitsuIds.add(haiId)
targetVector[haiId] = 2
}
}
tryChitoitusSearchToitsus(numRequiredPairs, 0, toitsuIds, targetVector)
}
private fun tryChitoitusSearchToitsus(
numRemainingToitsus: Int, minToitsuId: Int,
toitsuIds: MutableList<Int>, targetVector: IntArray) {
if (numRemainingToitsus == 0) {
algorithm.processChitoitsu(tehais, toitsuIds, currentVector, targetVector)
return
}
for (toitsuId in 0..NUM_HAI_ID - 1) {
if (currentVector[toitsuId] >= 2) {
continue
} else if (currentVector[toitsuId] == 1) {
toitsuIds.add(toitsuId)
targetVector[toitsuId] = 2
tryChitoitusSearchToitsus(
numRemainingToitsus - 1, toitsuId + 1, toitsuIds, targetVector)
toitsuIds.removeAt(toitsuIds.size - 1)
targetVector[toitsuId] = 0
}
// We ignore cases when we construct a toitsu of hais which a player doesn't have
// any.
}
}
private fun tryNormalHora() {
tryNormalHoraSearchMentsus(
4 - furos.size, 0, ArrayList<Int>(), IntArray(NUM_HAI_ID))
}
private fun tryNormalHoraSearchMentsus(
numRemainingMentsus: Int, minMentsuId: Int,
tehaiMentsuIds: MutableList<Int>, targetVector: IntArray) {
if (numRemainingMentsus == 0) {
tryNormalHoraSearchJanto(tehaiMentsuIds, targetVector)
return
}
for (mentsuId in minMentsuId..NUM_MENTSU_ID - 1) {
MentsuUtil.addMentsu(targetVector, mentsuId)
tehaiMentsuIds.add(mentsuId)
val shantensuLowerBound = getDistance(currentVector, targetVector) - 1
if (isValidTargetVector(targetVector) && shantensuLowerBound <= maxShantensu) {
tryNormalHoraSearchMentsus(
numRemainingMentsus - 1, mentsuId, tehaiMentsuIds, targetVector)
}
MentsuUtil.removeMentsu(targetVector, mentsuId)
tehaiMentsuIds.removeAt(tehaiMentsuIds.size - 1)
}
}
private fun tryNormalHoraSearchJanto(mentsuIds: List<Int>, targetVector: IntArray) {
for (haiId in 0..NUM_HAI_ID - 1) {
targetVector[haiId] += 2
if (isValidTargetVector(targetVector)) {
val shantensu = getDistance(currentVector, targetVector) - 1
if (shantensu <= maxShantensu) {
algorithm.processNormalHora(
tehais, furos, mentsuIds, haiId, currentVector, targetVector)
}
}
targetVector[haiId] -= 2
}
return
}
private fun isValidTargetVector(targetVector: IntArray): Boolean {
for (haiId in 0..NUM_HAI_ID - 1) {
if (targetVector[haiId] > 4) {
return false
}
}
return true
}
} | mit | 04f058c24b1fedde03e28d96add11776 | 35.018634 | 120 | 0.609865 | 3.883456 | false | false | false | false |
stoman/competitive-programming | problems/2020adventofcode17b/submissions/accepted/Stefan.kt | 2 | 1658 | import java.util.*
const val cycles = 6
fun main() {
val s = Scanner(System.`in`)
val input = mutableListOf<List<Boolean>>()
while (s.hasNext()) {
input.add(s.next().map { it == '#' })
}
var map = List(1 + 2 * cycles) {
List(1 + 2 * cycles) {
List(input.size + 2 * cycles) {
MutableList(input[0].size + 2 * cycles) { false }
}
}
}
for (i in input.indices) {
for (j in input[i].indices) {
map[cycles][cycles][i + cycles][j + cycles] = input[i][j]
}
}
for (i in 1..cycles) {
val newMap =
List(map.size) { List(map[0].size) { List(map[0][0].size) { MutableList(map[0][0][0].size) { false } } } }
for (a in map.indices) {
for (b in map[a].indices) {
for (c in map[a][b].indices) {
for (d in map[a][b][c].indices) {
var neighbors = if (map[a][b][c][d]) -1 else 0
for (x in -1..1) {
for (y in -1..1) {
for (z in -1..1) {
for (q in -1..1) {
if (a + x in map.indices
&& b + y in map[a + x].indices
&& c + z in map[a + x][b + y].indices
&& d + q in map[a + x][b + y][c + z].indices
&& map[a + x][b + y][c + z][d + q]) {
neighbors++
}
}
}
}
}
newMap[a][b][c][d] = (map[a][b][c][d] && neighbors in setOf(2, 3)) || (!map[a][b][c][d] && neighbors == 3)
}
}
}
}
map = newMap
}
println(map.flatten().flatten().flatten().count { it })
}
| mit | 41217a8224044be68b01f05fe71c302d | 28.087719 | 118 | 0.40772 | 3.188462 | false | false | false | false |
jitsi/jicofo | jicofo-common/src/main/kotlin/org/jitsi/jicofo/util/WeakValueMap.kt | 1 | 1600 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2022 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.util
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
/**
* Self-cleaning map with weak values.
* TODO: maybe move to jitsi-utils
*/
class WeakValueMap<K, V>(
private val cleanInterval: Int = 100
) {
private val map: MutableMap<K, WeakReference<V>> = ConcurrentHashMap<K, WeakReference<V>>()
private var i = 0
fun get(key: K) = map[key]?.get().also {
maybeClean()
}
fun put(key: K, value: V) {
map[key] = WeakReference(value)
maybeClean()
}
fun containsKey(key: K): Boolean = (map[key]?.get() != null).also {
maybeClean()
}
fun remove(key: K) = map.remove(key)?.get()
fun values(): List<V> {
clean()
return map.values.mapNotNull { it.get() }.toList()
}
private fun maybeClean() = ((i++ % cleanInterval == 0)) && clean()
private fun clean() = map.values.removeIf { it.get() == null }
}
| apache-2.0 | c4671f1684b647000f51af8fb5fdf6d8 | 30.372549 | 95 | 0.65625 | 3.729604 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/json/JsonUtil.kt | 1 | 1124 | package org.wikipedia.json
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.wikipedia.util.log.L
object JsonUtil {
val json = Json {
ignoreUnknownKeys = true
coerceInputValues = true
// This "default" class discriminator is necessary for EventPlatform classes.
// If you need a different discriminator for a different set of classes, you'll need
// to use a separate Json object.
classDiscriminator = "\$schema"
}
inline fun <reified T> decodeFromString(string: String?): T? {
if (string == null) {
return null
}
try {
return json.decodeFromString(string)
} catch (e: Exception) {
L.w(e)
}
return null
}
inline fun <reified T> encodeToString(value: T?): String? {
if (value == null) {
return null
}
try {
return json.encodeToString(value)
} catch (e: Exception) {
L.w(e)
}
return null
}
}
| apache-2.0 | 7da340c6a94ffae535d59810d7b5c453 | 26.414634 | 92 | 0.590747 | 4.606557 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsTasksFragment.kt | 1 | 22796 | package org.wikipedia.suggestededits
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.constraintlayout.widget.Group
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.SuggestedEditsFunnel
import org.wikipedia.analytics.eventplatform.BreadCrumbLogEvent
import org.wikipedia.analytics.eventplatform.UserContributionEvent
import org.wikipedia.auth.AccountUtil
import org.wikipedia.databinding.FragmentSuggestedEditsTasksBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwServiceError
import org.wikipedia.dataclient.mwapi.UserContribution
import org.wikipedia.descriptions.DescriptionEditActivity.Action.*
import org.wikipedia.login.LoginActivity
import org.wikipedia.main.MainActivity
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.languages.WikipediaLanguagesActivity
import org.wikipedia.usercontrib.UserContribListActivity
import org.wikipedia.usercontrib.UserContribStats
import org.wikipedia.util.*
import org.wikipedia.util.log.L
import org.wikipedia.views.DefaultRecyclerAdapter
import org.wikipedia.views.DefaultViewHolder
import java.util.*
import java.util.concurrent.TimeUnit
class SuggestedEditsTasksFragment : Fragment() {
private var _binding: FragmentSuggestedEditsTasksBinding? = null
private val binding get() = _binding!!
private lateinit var addDescriptionsTask: SuggestedEditsTask
private lateinit var addImageCaptionsTask: SuggestedEditsTask
private lateinit var addImageTagsTask: SuggestedEditsTask
private val displayedTasks = ArrayList<SuggestedEditsTask>()
private val callback = TaskViewCallback()
private val disposables = CompositeDisposable()
private var blockMessage: String? = null
private var isPausedOrDisabled = false
private var totalPageviews = 0L
private var totalContributions = 0
private var latestEditDate = Date()
private var latestEditStreak = 0
private var revertSeverity = 0
private val sequentialTooltipRunnable = Runnable {
if (!isAdded) {
return@Runnable
}
val balloon = FeedbackUtil.getTooltip(requireContext(), binding.contributionsStatsView.tooltipText, autoDismiss = true, showDismissButton = true)
balloon.showAlignBottom(binding.contributionsStatsView.getDescriptionView())
balloon.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), binding.editStreakStatsView.tooltipText, autoDismiss = true, showDismissButton = true), binding.editStreakStatsView.getDescriptionView())
.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), binding.pageViewStatsView.tooltipText, autoDismiss = true, showDismissButton = true), binding.pageViewStatsView.getDescriptionView())
.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), binding.editQualityStatsView.tooltipText, autoDismiss = true, showDismissButton = true), binding.editQualityStatsView.getDescriptionView())
Prefs.showOneTimeSequentialUserStatsTooltip = false
BreadCrumbLogEvent.logTooltipShown(requireActivity(), binding.contributionsStatsView)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentSuggestedEditsTasksBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupTestingButtons()
binding.userStatsViewsGroup.addOnClickListener {
startActivity(UserContribListActivity.newIntent(requireActivity(), AccountUtil.userName.orEmpty()))
}
binding.learnMoreCard.setOnClickListener {
FeedbackUtil.showAndroidAppEditingFAQ(requireContext())
}
binding.learnMoreButton.setOnClickListener {
FeedbackUtil.showAndroidAppEditingFAQ(requireContext())
}
binding.swipeRefreshLayout.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent))
binding.swipeRefreshLayout.setOnRefreshListener { refreshContents() }
binding.errorView.retryClickListener = View.OnClickListener { refreshContents() }
binding.suggestedEditsScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
(requireActivity() as MainActivity).updateToolbarElevation(scrollY > 0)
})
binding.tasksRecyclerView.layoutManager = LinearLayoutManager(context)
binding.tasksRecyclerView.adapter = RecyclerAdapter(displayedTasks)
clearContents()
}
private fun Group.addOnClickListener(listener: View.OnClickListener) {
referencedIds.forEach { id ->
binding.userStatsClickTarget.findViewById<View>(id).setOnClickListener(listener)
}
binding.userStatsClickTarget.setOnClickListener(listener)
}
override fun onPause() {
super.onPause()
SuggestedEditsFunnel.get().pause()
}
override fun onResume() {
super.onResume()
setUpTasks()
refreshContents()
SuggestedEditsFunnel.get().resume()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE) {
binding.tasksRecyclerView.adapter!!.notifyDataSetChanged()
} else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_TAGS_ONBOARDING && resultCode == Activity.RESULT_OK) {
Prefs.showImageTagsOnboarding = false
startActivity(SuggestionsActivity.newIntent(requireActivity(), ADD_IMAGE_TAGS, Constants.InvokeSource.SUGGESTED_EDITS))
} else if (requestCode == Constants.ACTIVITY_REQUEST_LOGIN && resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) {
clearContents()
}
}
override fun onDestroyView() {
binding.tasksRecyclerView.adapter = null
disposables.clear()
binding.suggestedEditsScrollView.removeCallbacks(sequentialTooltipRunnable)
SuggestedEditsFunnel.get().log()
SuggestedEditsFunnel.reset()
_binding = null
super.onDestroyView()
}
private fun fetchUserContributions() {
if (!AccountUtil.isLoggedIn) {
setRequiredLoginStatus()
return
}
disposables.clear()
blockMessage = null
isPausedOrDisabled = false
totalContributions = 0
latestEditStreak = 0
revertSeverity = 0
binding.progressBar.visibility = VISIBLE
disposables.add(Observable.zip(ServiceFactory.get(WikipediaApp.instance.wikiSite).getUserContributions(AccountUtil.userName!!, 10, null).subscribeOn(Schedulers.io()),
ServiceFactory.get(Constants.commonsWikiSite).getUserContributions(AccountUtil.userName!!, 10, null).subscribeOn(Schedulers.io()),
ServiceFactory.get(Constants.wikidataWikiSite).getUserContributions(AccountUtil.userName!!, 10, null).subscribeOn(Schedulers.io()),
UserContribStats.getEditCountsObservable()) { homeSiteResponse, commonsResponse, wikidataResponse, _ ->
var blockInfo: MwServiceError.BlockInfo? = null
when {
wikidataResponse.query?.userInfo!!.isBlocked -> blockInfo =
wikidataResponse.query?.userInfo!!
commonsResponse.query?.userInfo!!.isBlocked -> blockInfo =
commonsResponse.query?.userInfo!!
homeSiteResponse.query?.userInfo!!.isBlocked -> blockInfo =
homeSiteResponse.query?.userInfo!!
}
if (blockInfo != null) {
blockMessage = ThrowableUtil.getBlockMessageHtml(blockInfo)
}
totalContributions += wikidataResponse.query?.userInfo!!.editCount
totalContributions += commonsResponse.query?.userInfo!!.editCount
totalContributions += homeSiteResponse.query?.userInfo!!.editCount
latestEditDate = wikidataResponse.query?.userInfo!!.latestContribDate
if (commonsResponse.query?.userInfo!!.latestContribDate.after(latestEditDate)) {
latestEditDate = commonsResponse.query?.userInfo!!.latestContribDate
}
if (homeSiteResponse.query?.userInfo!!.latestContribDate.after(latestEditDate)) {
latestEditDate = homeSiteResponse.query?.userInfo!!.latestContribDate
}
val contributions = (wikidataResponse.query!!.userContributions +
commonsResponse.query!!.userContributions +
homeSiteResponse.query!!.userContributions).sortedByDescending { it.date() }
latestEditStreak = getEditStreak(contributions)
revertSeverity = UserContribStats.getRevertSeverity()
wikidataResponse
}
.flatMap { response ->
UserContribStats.getPageViewsObservable(response)
}
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
if (!blockMessage.isNullOrEmpty()) {
setIPBlockedStatus()
}
}
.subscribe({
if (maybeSetPausedOrDisabled()) {
isPausedOrDisabled = true
}
if (!isPausedOrDisabled && blockMessage.isNullOrEmpty()) {
binding.pageViewStatsView.setTitle(it.toString())
totalPageviews = it
setFinalUIState()
}
}, { t ->
L.e(t)
showError(t)
}))
}
fun refreshContents() {
requireActivity().invalidateOptionsMenu()
fetchUserContributions()
}
private fun clearContents(shouldScrollToTop: Boolean = true) {
binding.swipeRefreshLayout.isRefreshing = false
binding.progressBar.visibility = GONE
binding.tasksContainer.visibility = GONE
binding.errorView.visibility = GONE
binding.disabledStatesView.visibility = GONE
if (shouldScrollToTop) {
binding.suggestedEditsScrollView.scrollTo(0, 0)
}
binding.swipeRefreshLayout.setBackgroundColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color))
}
private fun showError(t: Throwable) {
clearContents()
binding.errorView.setError(t)
binding.errorView.visibility = VISIBLE
}
private fun setFinalUIState() {
clearContents(false)
binding.tasksRecyclerView.adapter!!.notifyDataSetChanged()
setUserStatsViewsAndTooltips()
if (latestEditStreak < 2) {
binding.editStreakStatsView.setTitle(if (latestEditDate.time > 0) DateUtil.getMDYDateString(latestEditDate) else resources.getString(R.string.suggested_edits_last_edited_never))
binding.editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_last_edited))
} else {
binding.editStreakStatsView.setTitle(resources.getQuantityString(R.plurals.suggested_edits_edit_streak_detail_text,
latestEditStreak, latestEditStreak))
binding.editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_edit_streak_label_text))
}
if (totalContributions == 0) {
binding.userStatsClickTarget.isEnabled = false
binding.userStatsViewsGroup.visibility = GONE
binding.onboardingImageView.visibility = VISIBLE
binding.onboardingTextView.visibility = VISIBLE
binding.onboardingTextView.text = StringUtil.fromHtml(getString(R.string.suggested_edits_onboarding_message, AccountUtil.userName))
} else {
binding.userStatsViewsGroup.visibility = VISIBLE
binding.onboardingImageView.visibility = GONE
binding.onboardingTextView.visibility = GONE
binding.userStatsClickTarget.isEnabled = true
binding.userNameView.text = AccountUtil.userName
binding.contributionsStatsView.setTitle(totalContributions.toString())
binding.contributionsStatsView.setDescription(resources.getQuantityString(R.plurals.suggested_edits_contribution, totalContributions))
if (Prefs.showOneTimeSequentialUserStatsTooltip) {
showOneTimeSequentialUserStatsTooltips()
}
}
binding.swipeRefreshLayout.setBackgroundColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color))
binding.tasksContainer.visibility = VISIBLE
}
private fun setUserStatsViewsAndTooltips() {
binding.contributionsStatsView.setImageDrawable(R.drawable.ic_mode_edit_white_24dp)
binding.contributionsStatsView.tooltipText = getString(R.string.suggested_edits_contributions_stat_tooltip)
binding.editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_edit_streak_label_text))
binding.editStreakStatsView.setImageDrawable(R.drawable.ic_timer_black_24dp)
binding.editStreakStatsView.tooltipText = getString(R.string.suggested_edits_edit_streak_stat_tooltip)
binding.pageViewStatsView.setDescription(getString(R.string.suggested_edits_views_label_text))
binding.pageViewStatsView.setImageDrawable(R.drawable.ic_trending_up_black_24dp)
binding.pageViewStatsView.tooltipText = getString(R.string.suggested_edits_page_views_stat_tooltip)
binding.editQualityStatsView.setGoodnessState(revertSeverity)
binding.editQualityStatsView.setDescription(getString(R.string.suggested_edits_quality_label_text))
binding.editQualityStatsView.tooltipText = getString(R.string.suggested_edits_edit_quality_stat_tooltip, UserContribStats.totalReverts)
}
private fun showOneTimeSequentialUserStatsTooltips() {
binding.suggestedEditsScrollView.fullScroll(View.FOCUS_UP)
binding.suggestedEditsScrollView.removeCallbacks(sequentialTooltipRunnable)
binding.suggestedEditsScrollView.postDelayed(sequentialTooltipRunnable, 500)
}
private fun setIPBlockedStatus() {
clearContents()
binding.disabledStatesView.setIPBlocked(blockMessage)
binding.disabledStatesView.visibility = VISIBLE
UserContributionEvent.logIpBlock()
}
private fun setRequiredLoginStatus() {
clearContents()
binding.disabledStatesView.setRequiredLogin(this)
binding.disabledStatesView.visibility = VISIBLE
}
private fun maybeSetPausedOrDisabled(): Boolean {
val pauseEndDate = UserContribStats.maybePauseAndGetEndDate()
if (totalContributions < MIN_CONTRIBUTIONS_FOR_SUGGESTED_EDITS && WikipediaApp.instance.appOrSystemLanguageCode == "en") {
clearContents()
binding.disabledStatesView.setDisabled(getString(R.string.suggested_edits_gate_message, AccountUtil.userName))
binding.disabledStatesView.setPositiveButton(R.string.suggested_edits_learn_more, {
UriUtil.visitInExternalBrowser(requireContext(), Uri.parse(MIN_CONTRIBUTIONS_GATE_URL))
}, true)
binding.disabledStatesView.visibility = VISIBLE
return true
} else if (UserContribStats.isDisabled()) {
// Disable the whole feature.
clearContents()
binding.disabledStatesView.setDisabled(getString(R.string.suggested_edits_disabled_message, AccountUtil.userName))
binding.disabledStatesView.visibility = VISIBLE
UserContributionEvent.logDisabled()
return true
} else if (pauseEndDate != null) {
clearContents()
binding.disabledStatesView.setPaused(getString(R.string.suggested_edits_paused_message, DateUtil.getShortDateString(pauseEndDate), AccountUtil.userName))
binding.disabledStatesView.visibility = VISIBLE
UserContributionEvent.logPaused()
return true
}
binding.disabledStatesView.visibility = GONE
return false
}
private fun getEditStreak(contributions: List<UserContribution>): Int {
if (contributions.isEmpty()) {
return 0
}
// TODO: This is a bit naive, and should be updated once we switch to java.time.*
val calendar = GregorianCalendar()
calendar.time = Date()
// Start with a calendar that is fixed at the beginning of today's date
val baseCal = GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
val dayMillis = TimeUnit.DAYS.toMillis(1)
var streak = 0
for (c in contributions) {
if (c.date().time >= baseCal.timeInMillis) {
// this contribution was on the same day.
continue
} else if (c.date().time < (baseCal.timeInMillis - dayMillis)) {
// this contribution is more than one day apart, so the streak is broken.
break
}
streak++
baseCal.timeInMillis = baseCal.timeInMillis - dayMillis
}
return streak
}
private fun setupTestingButtons() {
if (!ReleaseUtil.isPreBetaRelease) {
binding.showIPBlockedMessage.visibility = GONE
binding.showOnboardingMessage.visibility = GONE
}
binding.showIPBlockedMessage.setOnClickListener { setIPBlockedStatus() }
binding.showOnboardingMessage.setOnClickListener { totalContributions = 0; setFinalUIState() }
}
private fun setUpTasks() {
displayedTasks.clear()
addImageTagsTask = SuggestedEditsTask()
addImageTagsTask.title = getString(R.string.suggested_edits_image_tags)
addImageTagsTask.description = getString(R.string.suggested_edits_image_tags_task_detail)
addImageTagsTask.imageDrawable = R.drawable.ic_image_tag
addImageTagsTask.primaryAction = getString(R.string.suggested_edits_task_action_text_add)
addImageCaptionsTask = SuggestedEditsTask()
addImageCaptionsTask.title = getString(R.string.suggested_edits_image_captions)
addImageCaptionsTask.description = getString(R.string.suggested_edits_image_captions_task_detail)
addImageCaptionsTask.imageDrawable = R.drawable.ic_image_caption
addImageCaptionsTask.primaryAction = getString(R.string.suggested_edits_task_action_text_add)
addImageCaptionsTask.secondaryAction = getString(R.string.suggested_edits_task_action_text_translate)
addDescriptionsTask = SuggestedEditsTask()
addDescriptionsTask.title = getString(R.string.description_edit_tutorial_title_descriptions)
addDescriptionsTask.description = getString(R.string.suggested_edits_add_descriptions_task_detail)
addDescriptionsTask.imageDrawable = R.drawable.ic_article_ltr_ooui
addDescriptionsTask.primaryAction = getString(R.string.suggested_edits_task_action_text_add)
addDescriptionsTask.secondaryAction = getString(R.string.suggested_edits_task_action_text_translate)
displayedTasks.add(addDescriptionsTask)
displayedTasks.add(addImageCaptionsTask)
displayedTasks.add(addImageTagsTask)
}
private inner class TaskViewCallback : SuggestedEditsTaskView.Callback {
override fun onViewClick(task: SuggestedEditsTask, secondary: Boolean) {
if (WikipediaApp.instance.languageState.appLanguageCodes.size < Constants.MIN_LANGUAGES_TO_UNLOCK_TRANSLATION && secondary) {
startActivityForResult(WikipediaLanguagesActivity.newIntent(requireActivity(), Constants.InvokeSource.SUGGESTED_EDITS), Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE)
return
}
if (task == addDescriptionsTask) {
startActivity(SuggestionsActivity.newIntent(requireActivity(), if (secondary) TRANSLATE_DESCRIPTION else ADD_DESCRIPTION, Constants.InvokeSource.SUGGESTED_EDITS))
} else if (task == addImageCaptionsTask) {
startActivity(SuggestionsActivity.newIntent(requireActivity(), if (secondary) TRANSLATE_CAPTION else ADD_CAPTION, Constants.InvokeSource.SUGGESTED_EDITS))
} else if (task == addImageTagsTask) {
if (Prefs.showImageTagsOnboarding) {
startActivityForResult(SuggestedEditsImageTagsOnboardingActivity.newIntent(requireContext()), Constants.ACTIVITY_REQUEST_IMAGE_TAGS_ONBOARDING)
} else {
startActivity(SuggestionsActivity.newIntent(requireActivity(), ADD_IMAGE_TAGS, Constants.InvokeSource.SUGGESTED_EDITS))
}
}
}
}
internal inner class RecyclerAdapter(tasks: List<SuggestedEditsTask>) : DefaultRecyclerAdapter<SuggestedEditsTask, SuggestedEditsTaskView>(tasks) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<SuggestedEditsTaskView> {
return DefaultViewHolder(SuggestedEditsTaskView(parent.context))
}
override fun onBindViewHolder(holder: DefaultViewHolder<SuggestedEditsTaskView>, i: Int) {
holder.view.setUpViews(items[i], callback)
}
}
companion object {
private const val MIN_CONTRIBUTIONS_FOR_SUGGESTED_EDITS = 3
private const val MIN_CONTRIBUTIONS_GATE_URL = "https://en.wikipedia.org/wiki/Help:Introduction_to_editing_with_Wiki_Markup/1"
fun newInstance(): SuggestedEditsTasksFragment {
return SuggestedEditsTasksFragment()
}
}
}
| apache-2.0 | 8a6a41764522abf4d07a3e263d198855 | 48.664488 | 216 | 0.700079 | 5.478491 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/ComponentPickerPreference.kt | 1 | 2540 | /*
* 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.preference
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.util.AttributeSet
abstract class ComponentPickerPreference(context: Context, attrs: AttributeSet? = null) : ThemedListPreference(context, attrs) {
protected val packageManager: PackageManager = context.packageManager
init {
setup()
}
override fun getSummary(): CharSequence {
if (isNoneValue(value)) return noneEntry
return entry ?: noneEntry
}
protected abstract val intentAction: String
protected abstract val noneEntry: String
protected abstract fun getComponentName(info: ResolveInfo): ComponentName
protected abstract fun resolve(queryIntent: Intent): List<ResolveInfo>
private fun setup() {
val queryIntent = Intent(intentAction)
val infoList = resolve(queryIntent)
val infoListSize = infoList.size
val entries = arrayOfNulls<CharSequence>(infoListSize + 1)
val values = arrayOfNulls<CharSequence>(infoListSize + 1)
entries[0] = noneEntry
values[0] = ""
for (i in 0 until infoListSize) {
val info = infoList[i]
entries[i + 1] = info.loadLabel(packageManager)
values[i + 1] = getComponentName(info).flattenToString()
}
setEntries(entries)
entryValues = values
}
companion object {
fun isNoneValue(value: String?): Boolean {
return value.isNullOrEmpty() || "none" == value
}
}
} | gpl-3.0 | c3c9ad93915006a6ffe024163527498f | 32 | 128 | 0.701969 | 4.568345 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/paymentmethod/PaymentMethodBody.kt | 1 | 11129 | package com.stripe.android.link.ui.paymentmethod
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
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.financialconnections.FinancialConnectionsSheet
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetActivityArgs
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetForLinkContract
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.PaymentsThemeForLink
import com.stripe.android.link.theme.linkColors
import com.stripe.android.link.theme.linkShapes
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.PrimaryButtonState
import com.stripe.android.link.ui.ScrollableTopLevelColumn
import com.stripe.android.link.ui.SecondaryButton
import com.stripe.android.link.ui.forms.Form
@Preview
@Composable
private fun PaymentMethodBodyPreview() {
DefaultLinkTheme {
Surface {
PaymentMethodBody(
supportedPaymentMethods = SupportedPaymentMethod.values().toList(),
selectedPaymentMethod = SupportedPaymentMethod.Card,
primaryButtonLabel = "Pay $10.99",
primaryButtonState = PrimaryButtonState.Enabled,
secondaryButtonLabel = "Cancel",
errorMessage = null,
onPaymentMethodSelected = {},
onPrimaryButtonClick = {},
onSecondaryButtonClick = {}
) {}
}
}
}
@Composable
internal fun PaymentMethodBody(
linkAccount: LinkAccount,
injector: NonFallbackInjector,
loadFromArgs: Boolean
) {
val viewModel: PaymentMethodViewModel = viewModel(
factory = PaymentMethodViewModel.Factory(linkAccount, injector, loadFromArgs)
)
val activityResultLauncher = rememberLauncherForActivityResult(
contract = FinancialConnectionsSheetForLinkContract(),
onResult = viewModel::onFinancialConnectionsAccountLinked
)
val clientSecret by viewModel.financialConnectionsSessionClientSecret.collectAsState()
clientSecret?.let { secret ->
LaunchedEffect(secret) {
activityResultLauncher.launch(
FinancialConnectionsSheetActivityArgs.ForLink(
FinancialConnectionsSheet.Configuration(
financialConnectionsSessionClientSecret = secret,
publishableKey = viewModel.publishableKey
)
)
)
}
}
val formController by viewModel.formController.collectAsState()
formController?.let { controller ->
val formValues by controller.completeFormValues.collectAsState(null)
val primaryButtonState by viewModel.primaryButtonState.collectAsState()
val errorMessage by viewModel.errorMessage.collectAsState()
val paymentMethod by viewModel.paymentMethod.collectAsState()
PaymentMethodBody(
supportedPaymentMethods = viewModel.supportedTypes,
selectedPaymentMethod = paymentMethod,
primaryButtonLabel = paymentMethod.primaryButtonLabel(
viewModel.args.stripeIntent,
LocalContext.current.resources
),
primaryButtonState = primaryButtonState.takeIf { formValues != null }
?: PrimaryButtonState.Disabled,
secondaryButtonLabel = stringResource(id = viewModel.secondaryButtonLabel),
errorMessage = errorMessage,
onPaymentMethodSelected = viewModel::onPaymentMethodSelected,
onPrimaryButtonClick = {
formValues?.let {
viewModel.startPayment(it)
}
},
onSecondaryButtonClick = viewModel::onSecondaryButtonClick,
formContent = {
Form(
controller,
viewModel.isEnabled
)
}
)
} ?: run {
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
}
@Composable
internal fun PaymentMethodBody(
supportedPaymentMethods: List<SupportedPaymentMethod>,
selectedPaymentMethod: SupportedPaymentMethod,
primaryButtonLabel: String,
primaryButtonState: PrimaryButtonState,
secondaryButtonLabel: String,
errorMessage: ErrorMessage?,
onPaymentMethodSelected: (SupportedPaymentMethod) -> Unit,
onPrimaryButtonClick: () -> Unit,
onSecondaryButtonClick: () -> Unit,
formContent: @Composable ColumnScope.() -> Unit
) {
ScrollableTopLevelColumn {
Text(
text = stringResource(R.string.add_payment_method),
modifier = Modifier
.padding(top = 4.dp, bottom = 32.dp),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h2,
color = MaterialTheme.colors.onPrimary
)
if (supportedPaymentMethods.size > 1) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
horizontalArrangement = Arrangement.spacedBy(20.dp)
) {
supportedPaymentMethods.forEach { paymentMethod ->
PaymentMethodTypeCell(
paymentMethod = paymentMethod,
selected = paymentMethod == selectedPaymentMethod,
enabled = !primaryButtonState.isBlocking,
onSelected = {
onPaymentMethodSelected(paymentMethod)
}
)
}
}
}
if (selectedPaymentMethod.showsForm) {
Spacer(modifier = Modifier.height(4.dp))
PaymentsThemeForLink {
formContent()
}
Spacer(modifier = Modifier.height(8.dp))
}
AnimatedVisibility(visible = errorMessage != null) {
ErrorText(
text = errorMessage?.getMessage(LocalContext.current.resources).orEmpty(),
modifier = Modifier.fillMaxWidth()
)
}
PrimaryButton(
label = primaryButtonLabel,
state = primaryButtonState,
onButtonClick = onPrimaryButtonClick,
iconStart = selectedPaymentMethod.primaryButtonStartIconResourceId,
iconEnd = selectedPaymentMethod.primaryButtonEndIconResourceId
)
SecondaryButton(
enabled = !primaryButtonState.isBlocking,
label = secondaryButtonLabel,
onClick = onSecondaryButtonClick
)
}
}
@Composable
private fun RowScope.PaymentMethodTypeCell(
paymentMethod: SupportedPaymentMethod,
selected: Boolean,
enabled: Boolean,
onSelected: () -> Unit,
modifier: Modifier = Modifier
) {
CompositionLocalProvider(LocalContentAlpha provides if (enabled) 1f else 0.6f) {
Surface(
modifier = modifier
.height(56.dp)
.weight(1f),
shape = MaterialTheme.linkShapes.small,
color = MaterialTheme.linkColors.componentBackground,
border = BorderStroke(
width = if (selected) {
2.dp
} else {
1.dp
},
color = if (selected) {
MaterialTheme.colors.primary
} else {
MaterialTheme.linkColors.componentBorder
}
)
) {
Row(
modifier = Modifier
.fillMaxSize()
.clickable(
enabled = enabled,
onClick = onSelected
),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = paymentMethod.iconResourceId),
contentDescription = null,
modifier = Modifier
.width(50.dp)
.padding(horizontal = 16.dp),
alpha = LocalContentAlpha.current,
colorFilter = ColorFilter.tint(
color = if (selected) {
MaterialTheme.colors.primary
} else {
MaterialTheme.colors.onSecondary
}
)
)
Text(
text = stringResource(id = paymentMethod.nameResourceId),
modifier = Modifier.padding(end = 16.dp),
color = if (selected) {
MaterialTheme.colors.onPrimary
} else {
MaterialTheme.colors.onSecondary
},
style = MaterialTheme.typography.h6
)
}
}
}
}
| mit | 05bbf3076b1d1e843619a1047b1e7dce | 37.777003 | 96 | 0.630784 | 5.769311 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/fragments/topic/editpost/tasks/BaseTask.kt | 1 | 2473 | package org.softeg.slartus.forpdaplus.fragments.topic.editpost.tasks
import android.content.Context
import android.os.AsyncTask
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import org.softeg.slartus.forpdaplus.App
import org.softeg.slartus.forpdaplus.R
import org.softeg.slartus.forpdaplus.common.AppLog
import org.softeg.slartus.forpdaplus.fragments.topic.editpost.EditPostFragmentListener
import java.lang.ref.WeakReference
abstract class BaseTask<Params, Progress>(
editPostFragmentListener: EditPostFragmentListener,
progressMessageResId: Int)
: AsyncTask<Params, Progress, Boolean>() {
protected val editPostFragmentListener: WeakReference<EditPostFragmentListener> = WeakReference(editPostFragmentListener)
init {
this.editPostFragmentListener.get()?.getContext()?.let {
dialog = createProgressDialolg(it, progressMessageResId)
}
}
protected open fun createProgressDialolg(context: Context, progressMessageResId: Int): MaterialDialog = MaterialDialog.Builder(context)
.progress(true, 0)
.cancelListener { cancel(true) }
.content(progressMessageResId)
.build()
protected var dialog: MaterialDialog? = null
protected var ex: Exception? = null
abstract fun work(params: Array<out Params>)
override fun doInBackground(vararg params: Params): Boolean {
return try {
work(params)
true
} catch (e: Exception) {
ex = e
false
}
}
override fun onPreExecute() {
this.dialog?.show()
}
override fun onCancelled() {
Toast.makeText(this.editPostFragmentListener.get()?.getContext()
?: App.getContext(), R.string.canceled, Toast.LENGTH_SHORT).show()
//finish();
}
abstract fun onSuccess()
fun showError() {
if (ex != null)
AppLog.e(this.editPostFragmentListener.get()?.getContext(), ex)
else
Toast.makeText(this.editPostFragmentListener.get()?.getContext()
?: App.getContext(), R.string.unknown_error,
Toast.LENGTH_SHORT).show()
}
override fun onPostExecute(success: Boolean) {
if (this.dialog?.isShowing == true) {
this.dialog?.dismiss()
}
if (success) {
onSuccess()
} else {
showError()
}
}
} | apache-2.0 | f075cbf30c12500edc94e46112c22a7a | 29.170732 | 139 | 0.648201 | 4.755769 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/core/track/TrackTools.kt | 1 | 1943 | package com.peterlaurence.trekme.core.track
import com.peterlaurence.trekme.core.map.Map
import com.peterlaurence.trekme.core.map.gson.MarkerGson
import com.peterlaurence.trekme.core.map.gson.RouteGson
import com.peterlaurence.trekme.util.FileUtils
import java.io.File
import java.util.HashMap
object TrackTools {
fun renameTrack(record: File, newName: String): Boolean {
return try {
/* Rename the file */
record.renameTo(File(record.parent, newName + "." + FileUtils.getFileExtension(record)))
//TODO if the file contains only one track, rename one with the same name
true
} catch (e: Exception) {
false
}
}
/**
* Add new [RouteGson.Route]s to a [Map].
*
* @return the number of [RouteGson.Route] that have been appended to the list.
*/
fun updateRouteList(map: Map, newRouteList: List<RouteGson.Route>?): Int {
if (newRouteList == null) return 0
val hashMap = HashMap<String, RouteGson.Route>()
val routeList = map.routes
if (routeList != null) {
for (route in routeList) {
hashMap[route.name] = route
}
}
var newRouteCount = 0
for (route in newRouteList) {
if (hashMap.containsKey(route.name)) {
val existingRoute = hashMap[route.name]
existingRoute?.copyRoute(route)
} else {
map.addRoute(route)
newRouteCount++
}
}
return newRouteCount
}
fun updateMarkerList(map: Map, newMarkerList: List<MarkerGson.Marker>): Int {
val toBeAdded = newMarkerList.toMutableList()
val existing = map.markers
existing?.let {
toBeAdded.removeAll(existing)
}
toBeAdded.forEach {
map.addMarker(it)
}
return toBeAdded.count()
}
} | gpl-3.0 | 7c61a6aa9ab32cc0ce3543c5dfe0d692 | 29.375 | 100 | 0.591868 | 4.337054 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/scriptsDebug/JSRemoteScriptsDebugConfiguration.kt | 1 | 8428 | package com.github.jk1.ytplugin.scriptsDebug
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.debug.JSDebugScriptsEditor
import com.github.jk1.ytplugin.logger
import com.github.jk1.ytplugin.setup.getInstanceUUID
import com.github.jk1.ytplugin.setup.getInstanceVersion
import com.github.jk1.ytplugin.setup.obtainYouTrackConfiguration
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.google.common.collect.ImmutableBiMap
import com.intellij.execution.ExecutionResult
import com.intellij.execution.Executor
import com.intellij.execution.configuration.EmptyRunProfileState
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.LocatableConfigurationBase
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.RunConfigurationWithSuppressedDefaultRunAction
import com.intellij.javascript.JSRunProfileWithCompileBeforeLaunchOption
import com.intellij.javascript.debugger.LocalFileSystemFileFinder
import com.intellij.javascript.debugger.execution.RemoteUrlMappingBean
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.xmlb.SkipEmptySerializationFilter
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.XCollection
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.jetbrains.debugger.wip.BrowserChromeDebugProcess
import io.netty.handler.codec.http.HttpScheme
import org.jdom.Element
import org.jetbrains.debugger.DebuggableRunConfiguration
import org.jetbrains.io.LocalFileFinder
import java.net.InetSocketAddress
import java.net.URI
import java.net.URL
class JSRemoteScriptsDebugConfiguration(project: Project, factory: ConfigurationFactory, name: String) :
LocatableConfigurationBase<Element>(project, factory, name),
RunConfigurationWithSuppressedDefaultRunAction,
JSRunProfileWithCompileBeforeLaunchOption,
DebuggableRunConfiguration {
private val repositories = ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories()
private val repo = if (repositories.isNotEmpty()) {
repositories.first()
} else null
private val DEFAULT_PORT = HttpScheme.HTTPS.port()
private val SERIALIZATION_FILTER = SkipEmptySerializationFilter()
private val ROOT_FOLDER = "youtrack-scripts"
private val DEFAULT_INSTANCE_FOLDER = "scripts"
@Attribute
var host: String? = null
@Attribute
var port: Int = DEFAULT_PORT
@Attribute
var rootFolder: String = ROOT_FOLDER
@Attribute
var instanceFolder: String = DEFAULT_INSTANCE_FOLDER
@Property(surroundWithTag = false)
@XCollection
var mappings: MutableList<RemoteUrlMappingBean> = SmartList()
private set
override fun getConfigurationEditor(): SettingsEditor<out RunConfiguration> {
return JSDebugScriptsEditor(project)
}
override fun getState(executor: Executor, env: ExecutionEnvironment): RunProfileState? {
return EmptyRunProfileState.INSTANCE
}
override fun clone(): RunConfiguration {
val configuration = super.clone() as JSRemoteScriptsDebugConfiguration
configuration.host = host
configuration.port = port
configuration.rootFolder = rootFolder
configuration.mappings = SmartList(mappings)
return configuration
}
@Throws(InvalidDataException::class)
override fun readExternal(element: Element) {
super<LocatableConfigurationBase>.readExternal(element)
XmlSerializer.deserializeInto(this, element)
if (port < 0) {
port = assignRelevantPort()
}
}
override fun writeExternal(element: Element) {
super<LocatableConfigurationBase>.writeExternal(element)
XmlSerializer.serializeInto(this, element, SERIALIZATION_FILTER)
}
override fun computeDebugAddress(state: RunProfileState): InetSocketAddress {
val repositories = ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories()
val repo = if (repositories.isNotEmpty()) {
repositories.first()
} else null
host = URL(repo?.url).host
port = URL(repo?.url).port
if (port < 0) {
port = assignRelevantPort()
}
logger.info("Connection is to be opened on $host:$port")
return InetSocketAddress(host, port)
}
private fun assignRelevantPort() : Int {
return if (URI(repo?.url ?: "").scheme == HttpScheme.HTTPS.toString()){
logger.debug("InetSocket https port assigned: $port")
HttpScheme.HTTPS.port()
} else {
logger.debug("InetSocket http port assigned: $port")
HttpScheme.HTTP.port()
}
}
private fun loadScripts() {
val application = ApplicationManager.getApplication()
application.invokeAndWait({
ScriptsRulesHandler(project).loadWorkflowRules(mappings, rootFolder, instanceFolder)
}, application.noneModalityState)
}
override fun createDebugProcess(
socketAddress: InetSocketAddress,
session: XDebugSession,
executionResult: ExecutionResult?,
environment: ExecutionEnvironment
): XDebugProcess {
return createWipDebugProcess(socketAddress, session, executionResult)
}
private fun createWipDebugProcess(
socketAddress: InetSocketAddress,
session: XDebugSession,
executionResult: ExecutionResult?
): BrowserChromeDebugProcess {
val process: BrowserChromeDebugProcess?
val repositories = ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories()
val repo = if (repositories.isNotEmpty()) repositories[0] else null
if (getInstanceVersion() == null && repo != null){
obtainYouTrackConfiguration(repo.getRepo())
}
val version = getInstanceVersion()
when (version) {
null -> throw InvalidDataException("The YouTrack Integration plugin has not been configured to connect with a YouTrack site")
in 2021.3..Double.MAX_VALUE -> {
// clear mappings on each run of the configuration
mappings.clear()
// old versions support - folder based on uuid and no uuid in config cases
if (version < 2022.3){
instanceFolder = getInstanceUUID() ?: URL(repo?.url).host.split(".").first()
}
loadScripts()
val connection = WipConnection(project)
val finder = createUrlToLocalMapping(mappings)?.let {
RemoteDebuggingFileFinder(
it,
LocalFileSystemFileFinder(), rootFolder, instanceFolder
)
}
process = finder?.let { BrowserChromeDebugProcess(session, it, connection, executionResult) }
connection.open(socketAddress)
logger.info("connection is opened")
}
else -> throw InvalidDataException("YouTrack version is not sufficient")
}
return process!!
}
private fun createUrlToLocalMapping(mappings: List<RemoteUrlMappingBean>): HashBiMap<String, VirtualFile>? {
if (mappings.isEmpty()) {
return HashBiMap.create<String, VirtualFile>()
}
val map = HashBiMap.create<String, VirtualFile>(mappings.size)
for (mapping in mappings) {
val file = LocalFileFinder.findFile(mapping.localFilePath)
if (file != null) {
logger.info("Url to local mapping: ${mapping.remoteUrl}, ${file.url}")
map.forcePut(mapping.remoteUrl, file)
}
}
return map
}
}
| apache-2.0 | 80aaa94f1f5eb9e5b53b26e72434aab5 | 37.135747 | 137 | 0.707285 | 5.126521 | false | true | false | false |
Soya93/Extract-Refactoring | plugins/settings-repository/src/git/GitRepositoryManager.kt | 4 | 10790 | /*
* Copyright 2000-2016 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.settingsRepository.git
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.*
import org.eclipse.jgit.api.AddCommand
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.api.errors.UnmergedPathsException
import org.eclipse.jgit.errors.TransportException
import org.eclipse.jgit.ignore.IgnoreNode
import org.eclipse.jgit.lib.ConfigConstants
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.RepositoryState
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.transport.*
import org.jetbrains.jgit.dirCache.AddLoadedFile
import org.jetbrains.jgit.dirCache.DeleteDirectory
import org.jetbrains.jgit.dirCache.deletePath
import org.jetbrains.jgit.dirCache.edit
import org.jetbrains.keychain.CredentialsStore
import org.jetbrains.settingsRepository.*
import org.jetbrains.settingsRepository.RepositoryManager.Updater
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import kotlin.concurrent.write
class GitRepositoryManager(private val credentialsStore: NotNullLazyValue<CredentialsStore>, dir: Path) : BaseRepositoryManager(dir) {
val repository: Repository
get() {
var r = _repository
if (r == null) {
r = FileRepositoryBuilder().setWorkTree(dir.toFile()).build()
_repository = r
if (ApplicationManager.getApplication()?.isUnitTestMode != true) {
ShutDownTracker.getInstance().registerShutdownTask { _repository?.close() }
}
}
return r!!
}
// we must recreate repository if dir changed because repository stores old state and cannot be reinitialized (so, old instance cannot be reused and we must instantiate new one)
var _repository: Repository? = null
val credentialsProvider: CredentialsProvider by lazy {
JGitCredentialsProvider(credentialsStore, repository)
}
private var ignoreRules: IgnoreNode? = null
override fun createRepositoryIfNeed(): Boolean {
ignoreRules = null
if (isRepositoryExists()) {
return false
}
repository.create()
repository.disableAutoCrLf()
return true
}
override fun deleteRepository() {
ignoreRules = null
super.deleteRepository()
val r = _repository
if (r != null) {
_repository = null
r.close()
}
}
override fun getUpstream(): String? {
return StringUtil.nullize(repository.config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL))
}
override fun setUpstream(url: String?, branch: String?) {
repository.setUpstream(url, branch ?: Constants.MASTER)
}
override fun isRepositoryExists(): Boolean {
val repo = _repository
if (repo == null) {
return dir.exists() && FileRepositoryBuilder().setWorkTree(dir.toFile()).setup().objectDirectory.exists()
}
else {
return repo.objectDatabase.exists()
}
}
override fun hasUpstream() = getUpstream() != null
override fun addToIndex(file: Path, path: String, content: ByteArray, size: Int) {
repository.edit(AddLoadedFile(path, content, size, file.lastModified().toMillis()))
}
override fun deleteFromIndex(path: String, isFile: Boolean) {
repository.deletePath(path, isFile, false)
}
override fun commit(indicator: ProgressIndicator?, syncType: SyncType?, fixStateIfCannotCommit: Boolean): Boolean {
lock.write {
try {
// will be reset if OVERWRITE_LOCAL, so, we should not fix state in this case
return commitIfCan(indicator, if (!fixStateIfCannotCommit || syncType == SyncType.OVERWRITE_LOCAL) repository.repositoryState else repository.fixAndGetState())
}
catch (e: UnmergedPathsException) {
if (syncType == SyncType.OVERWRITE_LOCAL) {
LOG.warn("Unmerged detected, ignored because sync type is OVERWRITE_LOCAL", e)
return false
}
else {
indicator?.checkCanceled()
LOG.warn("Unmerged detected, will be attempted to resolve", e)
resolveUnmergedConflicts(repository)
indicator?.checkCanceled()
return commitIfCan(indicator, repository.fixAndGetState())
}
}
catch (e: NoHeadException) {
LOG.warn("Cannot commit - no HEAD", e)
return false
}
}
}
private fun commitIfCan(indicator: ProgressIndicator?, state: RepositoryState): Boolean {
if (state.canCommit()) {
return commit(repository, indicator)
}
else {
LOG.warn("Cannot commit, repository in state ${state.description}")
return false
}
}
override fun getAheadCommitsCount() = repository.getAheadCommitsCount()
override fun commit(paths: List<String>) {
}
override fun push(indicator: ProgressIndicator?) {
LOG.debug("Push")
val refSpecs = SmartList(RemoteConfig(repository.config, Constants.DEFAULT_REMOTE_NAME).pushRefSpecs)
if (refSpecs.isEmpty()) {
val head = repository.findRef(Constants.HEAD)
if (head != null && head.isSymbolic) {
refSpecs.add(RefSpec(head.leaf.name))
}
}
val monitor = indicator.asProgressMonitor()
for (transport in Transport.openAll(repository, Constants.DEFAULT_REMOTE_NAME, Transport.Operation.PUSH)) {
for (attempt in 0..1) {
transport.credentialsProvider = credentialsProvider
try {
val result = transport.push(monitor, transport.findRemoteRefUpdatesFor(refSpecs))
if (LOG.isDebugEnabled) {
printMessages(result)
for (refUpdate in result.remoteUpdates) {
LOG.debug(refUpdate.toString())
}
}
break;
}
catch (e: TransportException) {
if (e.status == TransportException.Status.NOT_PERMITTED) {
if (attempt == 0) {
credentialsProvider.reset(transport.uri)
}
else {
throw AuthenticationException(e)
}
}
else {
wrapIfNeedAndReThrow(e)
}
}
finally {
transport.close()
}
}
}
}
override fun fetch(indicator: ProgressIndicator?): Updater {
val pullTask = Pull(this, indicator ?: EmptyProgressIndicator())
val refToMerge = pullTask.fetch()
return object : Updater {
override var definitelySkipPush = false
// KT-8632
override fun merge(): UpdateResult? = lock.write {
val committed = commit(pullTask.indicator)
if (refToMerge == null && !committed && getAheadCommitsCount() == 0) {
definitelySkipPush = true
return null
}
else {
return pullTask.pull(prefetchedRefToMerge = refToMerge)
}
}
}
}
override fun pull(indicator: ProgressIndicator?) = Pull(this, indicator).pull()
override fun resetToTheirs(indicator: ProgressIndicator) = Reset(this, indicator).reset(true)
override fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?) = Reset(this, indicator).reset(false, localRepositoryInitializer)
override fun canCommit() = repository.repositoryState.canCommit()
fun renameDirectory(pairs: Map<String, String?>): Boolean {
var addCommand: AddCommand? = null
val toDelete = SmartList<DeleteDirectory>()
for ((oldPath, newPath) in pairs) {
val old = dir.resolve(oldPath)
if (!old.exists()) {
continue
}
LOG.info("Rename $oldPath to $newPath")
old.directoryStreamIfExists {
val new = if (newPath == null) dir else dir.resolve(newPath)
for (file in it) {
try {
if (file.isHidden()) {
file.delete()
}
else {
Files.move(file, new.resolve(file.fileName))
if (addCommand == null) {
addCommand = AddCommand(repository)
}
addCommand!!.addFilepattern(if (newPath == null) file.fileName.toString() else "$newPath/${file.fileName}")
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
toDelete.add(DeleteDirectory(oldPath))
}
try {
old.deleteRecursively()
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (toDelete.isEmpty() && addCommand == null) {
return false
}
repository.edit(toDelete)
if (addCommand != null) {
addCommand!!.call()
}
repository.commit(with(IdeaCommitMessageFormatter()) { StringBuilder().appendCommitOwnerInfo(true) }.append("Get rid of \$ROOT_CONFIG$ and \$APP_CONFIG").toString())
return true
}
private fun getIgnoreRules(): IgnoreNode? {
var node = ignoreRules
if (node == null) {
val file = dir.resolve(Constants.DOT_GIT_IGNORE)
if (file.exists()) {
node = IgnoreNode()
file.inputStream().use { node!!.parse(it) }
ignoreRules = node
}
}
return node
}
override fun isPathIgnored(path: String): Boolean {
// add first slash as WorkingTreeIterator does "The ignore code wants path to start with a '/' if possible."
return getIgnoreRules()?.isIgnored("/$path", false) == IgnoreNode.MatchResult.IGNORED
}
}
fun printMessages(fetchResult: OperationResult) {
if (LOG.isDebugEnabled) {
val messages = fetchResult.messages
if (!StringUtil.isEmptyOrSpaces(messages)) {
LOG.debug(messages)
}
}
}
class GitRepositoryService : RepositoryService {
override fun isValidRepository(file: Path): Boolean {
if (file.resolve(Constants.DOT_GIT).exists()) {
return true
}
// existing bare repository
try {
FileRepositoryBuilder().setGitDir(file.toFile()).setMustExist(true).build()
}
catch (e: IOException) {
return false
}
return true
}
} | apache-2.0 | da457bda4cfd94a7bbd43dfd56946d82 | 31.21194 | 179 | 0.667933 | 4.44765 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/notifications/dto/NotificationsGetResponse.kt | 1 | 2745 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.notifications.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.apps.dto.AppsApp
import com.vk.sdk.api.groups.dto.GroupsGroup
import com.vk.sdk.api.photos.dto.PhotosPhoto
import com.vk.sdk.api.users.dto.UsersUser
import com.vk.sdk.api.video.dto.VideoVideo
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param count - Total number
* @param items
* @param profiles
* @param groups
* @param lastViewed - Time when user has been checked notifications last time
* @param photos
* @param videos
* @param apps
* @param nextFrom
* @param ttl
*/
data class NotificationsGetResponse(
@SerializedName("count")
val count: Int? = null,
@SerializedName("items")
val items: List<NotificationsNotificationItem>? = null,
@SerializedName("profiles")
val profiles: List<UsersUser>? = null,
@SerializedName("groups")
val groups: List<GroupsGroup>? = null,
@SerializedName("last_viewed")
val lastViewed: Int? = null,
@SerializedName("photos")
val photos: List<PhotosPhoto>? = null,
@SerializedName("videos")
val videos: List<VideoVideo>? = null,
@SerializedName("apps")
val apps: List<AppsApp>? = null,
@SerializedName("next_from")
val nextFrom: String? = null,
@SerializedName("ttl")
val ttl: Int? = null
)
| mit | e84afceab3790afc0fc0f2cb25609da5 | 36.60274 | 81 | 0.691075 | 4.19084 | false | false | false | false |
SiimKinks/sqlitemagic | sqlitemagic-tests/app-kotlin/src/test/kotlin/com/example/SelectSqlBuilderTest.kt | 1 | 59921 | package com.example
import com.siimkinks.sqlitemagic.*
import com.siimkinks.sqlitemagic.AuthorTable.AUTHOR
import com.siimkinks.sqlitemagic.ComplexObjectWithSameLeafsTable.COMPLEX_OBJECT_WITH_SAME_LEAFS
import com.siimkinks.sqlitemagic.ImmutableValueWithFieldsTable.IMMUTABLE_VALUE_WITH_FIELDS
import com.siimkinks.sqlitemagic.MagazineTable.MAGAZINE
import com.siimkinks.sqlitemagic.Select.*
import com.siimkinks.sqlitemagic.SelectSqlNode.SelectNode
import com.siimkinks.sqlitemagic.ValueParser.*
import com.siimkinks.sqlitemagic.model.Author
import com.siimkinks.sqlitemagic.model.immutable.ImmutableValueWithFields
import com.siimkinks.sqlitemagic.transformer.BooleanTransformer
import org.junit.Test
class SelectSqlBuilderTest : DSLTests {
@Test
fun rawSelect() {
(SELECT
RAW "SELECT * FROM author")
.compile()
.isEqualTo("SELECT * FROM author")
}
@Test
fun rawSelectWithArgs() {
(SELECT
RAW "SELECT * FROM author WHERE author.name=?"
WITH_ARGS arrayOf("foo"))
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM author WHERE author.name=?",
expectedArgs = arrayOf("foo"))
(SELECT
RAW "SELECT * FROM author WHERE author.name=?"
WITH_ARGS arrayOf("foo")
FROM AUTHOR)
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM author WHERE author.name=?",
expectedObservedTables = arrayOf("author"),
expectedArgs = arrayOf("foo"))
(SELECT
RAW "SELECT * FROM author WHERE author.name=?"
FROM AUTHOR
WITH_ARGS arrayOf("foo"))
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM author WHERE author.name=?",
expectedObservedTables = arrayOf("author"),
expectedArgs = arrayOf("foo"))
}
@Test
fun rawSelectWithObservedTable() {
(SELECT
RAW "SELECT * FROM author"
FROM AUTHOR)
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM author",
expectedObservedTables = arrayOf("author"))
(SELECT
RAW "SELECT * FROM magazine, author"
FROM arrayOf(MAGAZINE, AUTHOR))
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM magazine, author",
expectedObservedTables = arrayOf("magazine", "author"))
(SELECT
RAW "SELECT * FROM author"
FROM listOf(AUTHOR))
.compile()
.isEqualTo(
expectedSql = "SELECT * FROM author",
expectedObservedTables = arrayOf("author"))
}
@Test
fun selectAllFrom() {
(SELECT FROM MAGAZINE)
.isEqualTo("SELECT * FROM magazine ")
(SELECT.DISTINCT FROM MAGAZINE)
.isEqualTo("SELECT DISTINCT * FROM magazine ")
}
@Test
fun selectAllFromSubquery() {
(SELECT FROM (SELECT FROM AUTHOR))
.isEqualTo("SELECT * FROM (SELECT * FROM author ) ")
(SELECT.DISTINCT
FROM (SELECT FROM AUTHOR))
.isEqualTo("SELECT DISTINCT * FROM (SELECT * FROM author ) ")
}
@Test
fun compoundSelectWithArgs() {
(SELECT
FROM AUTHOR
UNION
(SELECT
FROM AUTHOR
WHERE (AUTHOR.NAME IS "foo")))
.isEqualTo("SELECT * FROM author UNION SELECT * FROM author WHERE author.name=? ")
}
@Test
fun compoundSelectWithArgsInBothSelects() {
(SELECT
FROM AUTHOR
WHERE (AUTHOR.NAME IS "foo")
UNION
(SELECT
FROM AUTHOR
WHERE (AUTHOR.NAME IS "foo")))
.isEqualTo("SELECT * FROM author WHERE author.name=? UNION SELECT * FROM author WHERE author.name=? ")
}
@Test
fun unionSelect() {
(SELECT
FROM AUTHOR
UNION (SELECT FROM AUTHOR))
.isEqualTo("SELECT * FROM author UNION SELECT * FROM author ")
}
@Test
fun unionSelectExplicitColumns() {
(SELECT
FROM AUTHOR
UNION
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT * FROM author UNION SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun unionSelectExplicitAllColumns() {
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR
UNION
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author UNION SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun unionAllSelect() {
(SELECT
FROM AUTHOR
UNION_ALL (SELECT FROM AUTHOR))
.isEqualTo("SELECT * FROM author UNION ALL SELECT * FROM author ")
}
@Test
fun unionAllSelectExplicitColumns() {
(SELECT
FROM AUTHOR
UNION_ALL
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT * FROM author UNION ALL SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun unionAllSelectExplicitAllColumns() {
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR
UNION_ALL
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author UNION ALL SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun intersectSelect() {
(SELECT
FROM AUTHOR
INTERSECT (SELECT FROM AUTHOR))
.isEqualTo("SELECT * FROM author INTERSECT SELECT * FROM author ")
}
@Test
fun intersectSelectExplicitColumns() {
(SELECT
FROM AUTHOR
INTERSECT
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT * FROM author INTERSECT SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun intersectSelectExplicitAllColumns() {
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR
INTERSECT
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author INTERSECT SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun exceptSelect() {
(SELECT
FROM AUTHOR
EXCEPT (SELECT FROM AUTHOR))
.isEqualTo("SELECT * FROM author EXCEPT SELECT * FROM author ")
}
@Test
fun exceptSelectExplicitColumns() {
(SELECT
FROM AUTHOR
EXCEPT
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT * FROM author EXCEPT SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun exceptSelectExplicitAllColumns() {
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR
EXCEPT
(SELECT
COLUMNS arrayOf(
AUTHOR.ID,
AUTHOR.NAME,
AUTHOR.BOXED_BOOLEAN,
AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR))
.isEqualTo("SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author EXCEPT SELECT author.id,author.name,author.boxed_boolean,author.primitive_boolean FROM author ")
}
@Test
fun selectAllFromAliased() {
(SELECT FROM (MAGAZINE AS "b"))
.isEqualTo("SELECT * FROM magazine AS b ")
}
@Test
fun selectAllFromAliasedSubquery() {
val expected = "SELECT * FROM (SELECT * FROM author ) AS b "
val b = (SELECT
FROM AUTHOR)
.toTable("b")
val b2 = b AS "b"
(SELECT FROM b)
.isEqualTo(expected)
(SELECT FROM b2)
.isEqualTo(expected)
}
@Test
fun selectSingleColumn() {
(SELECT
COLUMN MAGAZINE.AUTHOR
FROM MAGAZINE)
.isEqualTo("SELECT magazine.author FROM magazine ")
(SELECT
DISTINCT MAGAZINE.AUTHOR
FROM MAGAZINE)
.isEqualTo("SELECT DISTINCT magazine.author FROM magazine ")
}
@Test
fun selectSingleColumnFromSubquery() {
(SELECT
COLUMN MAGAZINE.AUTHOR
FROM (SELECT FROM AUTHOR))
.isEqualTo("SELECT magazine.author FROM (SELECT * FROM author ) ")
(SELECT
DISTINCT MAGAZINE.AUTHOR
FROM (SELECT FROM AUTHOR))
.isEqualTo("SELECT DISTINCT magazine.author FROM (SELECT * FROM author ) ")
}
@Test
fun selectSingleColumnFromAliased() {
val b = MAGAZINE AS "b"
(SELECT
COLUMN MAGAZINE.AUTHOR
FROM b)
.isEqualTo("SELECT magazine.author FROM magazine AS b ")
(SELECT
DISTINCT MAGAZINE.AUTHOR
FROM b)
.isEqualTo("SELECT DISTINCT magazine.author FROM magazine AS b ")
}
@Test
fun selectSingleColumnFromAliasedSubquery() {
val a = (SELECT
FROM AUTHOR)
.toTable("a")
(SELECT
COLUMN MAGAZINE.AUTHOR
FROM a)
.isEqualTo("SELECT magazine.author FROM (SELECT * FROM author ) AS a ")
(SELECT
DISTINCT MAGAZINE.AUTHOR
FROM a)
.isEqualTo("SELECT DISTINCT magazine.author FROM (SELECT * FROM author ) AS a ")
}
@Test
fun selectColumn() {
(SELECT
COLUMN MAGAZINE.NAME
FROM MAGAZINE)
.isEqualTo("SELECT magazine.name FROM magazine ")
(SELECT
DISTINCT MAGAZINE.NAME
FROM MAGAZINE)
.isEqualTo("SELECT DISTINCT magazine.name FROM magazine ")
}
@Test
fun selectColumnAliased() {
val m = MAGAZINE AS "m"
(SELECT
COLUMN m.NAME
FROM m)
.isEqualTo("SELECT m.name FROM magazine AS m ")
(SELECT
DISTINCT m.NAME
FROM m)
.isEqualTo("SELECT DISTINCT m.name FROM magazine AS m ")
}
@Test
fun selectColumns() {
(SELECT
COLUMNS arrayOf(MAGAZINE.AUTHOR, MAGAZINE.NAME, MAGAZINE.NR_OF_RELEASES)
FROM MAGAZINE)
.isEqualTo("SELECT magazine.author,magazine.name,magazine.nr_of_releases FROM magazine ")
(SELECT
DISTINCT arrayOf(MAGAZINE.AUTHOR, MAGAZINE.NAME, MAGAZINE.NR_OF_RELEASES)
FROM MAGAZINE)
.isEqualTo("SELECT DISTINCT magazine.author,magazine.name,magazine.nr_of_releases FROM magazine ")
}
@Test
fun selectColumnsAliased() {
val m = MAGAZINE AS "m"
val nroe = m.NR_OF_RELEASES AS "nroe"
(SELECT
COLUMNS arrayOf(m.AUTHOR, m.NAME, nroe)
FROM m)
.isEqualTo("SELECT m.author,m.name,m.nr_of_releases AS 'nroe' FROM magazine AS m ")
(SELECT
DISTINCT arrayOf(m.AUTHOR, m.NAME, nroe)
FROM m)
.isEqualTo("SELECT DISTINCT m.author,m.name,m.nr_of_releases AS 'nroe' FROM magazine AS m ")
}
@Test
fun joins() {
var expected = "SELECT * FROM magazine LEFT OUTER JOIN author ON magazine.author=author.id "
var sqlNode = (SELECT
FROM MAGAZINE
LEFT_OUTER_JOIN (AUTHOR ON (MAGAZINE.AUTHOR IS AUTHOR.ID)))
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode NATURAL_JOIN AUTHOR)
expected += "NATURAL JOIN author "
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode INNER_JOIN (AUTHOR USING arrayOf(MAGAZINE.AUTHOR, AUTHOR.ID)))
expected += "INNER JOIN author USING (author,id) "
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode CROSS_JOIN (AUTHOR USING arrayOf(MAGAZINE.AUTHOR, AUTHOR.ID)))
expected += "CROSS JOIN author USING (author,id) "
sqlNode.isEqualTo(expected)
(SELECT
FROM COMPLEX_OBJECT_WITH_SAME_LEAFS
JOIN MAGAZINE
JOIN AUTHOR)
.isEqualTo("SELECT * FROM complex_object_with_same_leafs , magazine , author ")
}
@Test
fun joinsAliased() {
var expected = "SELECT * FROM magazine AS m LEFT OUTER JOIN author AS a ON m.author=a.id "
val m = MAGAZINE AS "m"
val a = AUTHOR AS "a"
var sqlNode = (SELECT
FROM m
LEFT_OUTER_JOIN (a ON (m.AUTHOR IS a.ID)))
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode NATURAL_JOIN a)
expected += "NATURAL JOIN author AS a "
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode INNER_JOIN (a USING arrayOf(m.AUTHOR, a.ID)))
expected += "INNER JOIN author AS a USING (author,id) "
sqlNode.isEqualTo(expected)
sqlNode = (sqlNode CROSS_JOIN (a USING arrayOf(m.AUTHOR, a.ID)))
expected += "CROSS JOIN author AS a USING (author,id) "
sqlNode.isEqualTo(expected)
(SELECT
FROM (COMPLEX_OBJECT_WITH_SAME_LEAFS AS "c")
JOIN m
JOIN a)
.isEqualTo("SELECT * FROM complex_object_with_same_leafs AS c , magazine AS m , author AS a ")
}
@Test
fun whereCondition() {
val expectedBase = "SELECT * FROM magazine WHERE "
val titleIs = MAGAZINE.NAME IS "asd"
val intIs = MAGAZINE.NR_OF_RELEASES IS 1920
val titleIsNot = MAGAZINE.NAME IS_NOT "asd"
val titleIsNotNull = MAGAZINE.NAME.isNotNull
val titleIsNull = MAGAZINE.NAME.isNull
val titleGlob = MAGAZINE.NAME GLOB "asd"
val titleLike = MAGAZINE.NAME LIKE "asd"
val lessThan = MAGAZINE.NR_OF_RELEASES LESS_THAN 1990
val greaterThan = MAGAZINE.NR_OF_RELEASES GREATER_THAN 1990
val between = MAGAZINE.NR_OF_RELEASES BETWEEN (1910 AND 2000)
val notBetween = MAGAZINE.NR_OF_RELEASES NOT_BETWEEN (1910 AND 2000)
val `in` = MAGAZINE.NR_OF_RELEASES IN arrayOf(1910, 1999, 1920)
val notIn = MAGAZINE.NR_OF_RELEASES NOT_IN arrayOf(1910, 1999, 1920)
val oneIn = MAGAZINE.NR_OF_RELEASES IN arrayOf(1910)
val oneNotIn = MAGAZINE.NR_OF_RELEASES NOT_IN arrayOf(1910)
var expected = expectedBase + "magazine.name=? "
(SELECT FROM MAGAZINE WHERE titleIs)
.isEqualTo(expected, "asd")
expected = expectedBase + "(magazine.name=? AND magazine.nr_of_releases=?) "
(SELECT FROM MAGAZINE WHERE (titleIs AND intIs))
.isEqualTo(expected, "asd", "1920")
expected = expectedBase + "magazine.nr_of_releases BETWEEN ? AND ? "
(SELECT FROM MAGAZINE WHERE between)
.isEqualTo(expected, "1910", "2000")
expected = expectedBase + "magazine.nr_of_releases NOT BETWEEN ? AND ? "
(SELECT FROM MAGAZINE WHERE notBetween)
.isEqualTo(expected, "1910", "2000")
expected = expectedBase + "magazine.nr_of_releases IN (?,?,?) "
(SELECT FROM MAGAZINE WHERE `in`)
.isEqualTo(expected, "1910", "1999", "1920")
val expectedLongWhereClause = "((((((((magazine.name!=? AND magazine.name IS NOT NULL) AND magazine.name IS NULL) " +
"AND magazine.name GLOB ?) AND magazine.name LIKE ?) AND magazine.nr_of_releases<?) AND magazine.nr_of_releases>?) " +
"AND magazine.nr_of_releases BETWEEN ? AND ?) AND magazine.nr_of_releases NOT BETWEEN ? AND ?) "
expected = expectedBase + expectedLongWhereClause
(SELECT FROM MAGAZINE WHERE ((((((((titleIsNot AND titleIsNotNull) AND titleIsNull) AND titleGlob)
AND titleLike) AND lessThan) AND greaterThan) AND between) AND notBetween))
.isEqualTo(expected, "asd", "asd", "asd", "1990", "1990", "1910", "2000", "1910", "2000")
expected = expectedBase + "(((magazine.nr_of_releases IN (?,?,?) AND magazine.nr_of_releases NOT IN (?,?,?)) " +
"AND magazine.nr_of_releases IN (?)) AND magazine.nr_of_releases NOT IN (?)) "
(SELECT FROM MAGAZINE WHERE (((`in` AND notIn) AND oneIn) AND oneNotIn))
.isEqualTo(expected, "1910", "1999", "1920", "1910", "1999", "1920", "1910", "1910")
expected = expectedBase + "(magazine.nr_of_releases IN (?,?,?) OR magazine.name!=?) "
(SELECT FROM MAGAZINE WHERE (`in` OR titleIsNot))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(magazine.nr_of_releases IN (?,?,?) AND (magazine.name!=? AND magazine.name IS NOT NULL)) "
(SELECT FROM MAGAZINE WHERE (`in` AND (titleIsNot AND titleIsNotNull)))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(magazine.nr_of_releases IN (?,?,?) OR (magazine.nr_of_releases BETWEEN ? AND ? AND magazine.name IS NOT NULL)) "
(SELECT FROM MAGAZINE WHERE (`in` OR (between AND titleIsNotNull)))
.isEqualTo(expected, "1910", "1999", "1920", "1910", "2000")
expected = expectedBase + "(magazine.nr_of_releases IN (?,?,?) AND ((magazine.name!=? OR magazine.name IS NOT NULL) OR magazine.name IS NULL)) "
(SELECT FROM MAGAZINE WHERE (`in` AND ((titleIsNot OR titleIsNotNull) OR titleIsNull)))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(magazine.nr_of_releases IN (?,?,?) OR magazine.name!=?) "
(SELECT FROM MAGAZINE WHERE (`in` OR titleIsNot))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
}
@Test
fun whereConditionAliased() {
val expectedBase = "SELECT * FROM magazine AS m WHERE "
val m = MAGAZINE AS "m"
val titleIs = m.NAME IS "asd"
val intIs = m.NR_OF_RELEASES IS 1920
val titleIsNot = m.NAME IS_NOT "asd"
val titleIsNotNull = m.NAME.isNotNull
val titleIsNull = m.NAME.isNull
val titleGlob = m.NAME GLOB "asd"
val titleLike = m.NAME LIKE "asd"
val lessThan = m.NR_OF_RELEASES LESS_THAN 1990
val greaterThan = m.NR_OF_RELEASES GREATER_THAN 1990
val between = m.NR_OF_RELEASES BETWEEN (1910 AND 2000)
val notBetween = m.NR_OF_RELEASES NOT_BETWEEN (1910 AND 2000)
val `in` = m.NR_OF_RELEASES IN arrayOf(1910, 1999, 1920)
val notIn = m.NR_OF_RELEASES NOT_IN arrayOf(1910, 1999, 1920)
val oneIn = m.NR_OF_RELEASES IN arrayOf(1910)
val oneNotIn = m.NR_OF_RELEASES NOT_IN arrayOf(1910)
var expected = expectedBase + "m.name=? "
(SELECT FROM m WHERE titleIs)
.isEqualTo(expected, "asd")
expected = expectedBase + "(m.name=? AND m.nr_of_releases=?) "
(SELECT FROM m WHERE (titleIs AND intIs))
.isEqualTo(expected, "asd", "1920")
expected = expectedBase + "m.nr_of_releases BETWEEN ? AND ? "
(SELECT FROM m WHERE between)
.isEqualTo(expected, "1910", "2000")
expected = expectedBase + "m.nr_of_releases NOT BETWEEN ? AND ? "
(SELECT FROM m WHERE notBetween)
.isEqualTo(expected, "1910", "2000")
expected = expectedBase + "m.nr_of_releases IN (?,?,?) "
(SELECT FROM m WHERE `in`)
.isEqualTo(expected, "1910", "1999", "1920")
val expectedLongWhereClause = "((((((((m.name!=? AND m.name IS NOT NULL) AND m.name IS NULL) " +
"AND m.name GLOB ?) AND m.name LIKE ?) AND m.nr_of_releases<?) AND m.nr_of_releases>?) " +
"AND m.nr_of_releases BETWEEN ? AND ?) AND m.nr_of_releases NOT BETWEEN ? AND ?) "
expected = expectedBase + expectedLongWhereClause
(SELECT FROM m WHERE ((((((((titleIsNot AND titleIsNotNull) AND titleIsNull) AND titleGlob)
AND titleLike) AND lessThan) AND greaterThan) AND between) AND notBetween))
.isEqualTo(expected, "asd", "asd", "asd", "1990", "1990", "1910", "2000", "1910", "2000")
expected = expectedBase + "(((m.nr_of_releases IN (?,?,?) AND m.nr_of_releases NOT IN (?,?,?)) " +
"AND m.nr_of_releases IN (?)) AND m.nr_of_releases NOT IN (?)) "
(SELECT FROM m WHERE (((`in` AND notIn) AND oneIn) AND oneNotIn))
.isEqualTo(expected, "1910", "1999", "1920", "1910", "1999", "1920", "1910", "1910")
expected = expectedBase + "(m.nr_of_releases IN (?,?,?) OR m.name!=?) "
(SELECT FROM m WHERE (`in` OR titleIsNot))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(m.nr_of_releases IN (?,?,?) AND (m.name!=? AND m.name IS NOT NULL)) "
(SELECT FROM m WHERE (`in` AND (titleIsNot AND titleIsNotNull)))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(m.nr_of_releases IN (?,?,?) OR (m.nr_of_releases BETWEEN ? AND ? AND m.name IS NOT NULL)) "
(SELECT FROM m WHERE (`in` OR (between AND titleIsNotNull)))
.isEqualTo(expected, "1910", "1999", "1920", "1910", "2000")
expected = expectedBase + "(m.nr_of_releases IN (?,?,?) AND ((m.name!=? OR m.name IS NOT NULL) OR m.name IS NULL)) "
(SELECT FROM m WHERE (`in` AND ((titleIsNot OR titleIsNotNull) OR titleIsNull)))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
expected = expectedBase + "(m.nr_of_releases IN (?,?,?) OR m.name!=?) "
(SELECT FROM m WHERE (`in` OR titleIsNot))
.isEqualTo(expected, "1910", "1999", "1920", "asd")
}
@Test
fun columnNotRedefinedWhenAliased() {
var expected = "SELECT magazine.*,magazine.name || ' ' || magazine.nr_of_releases AS 'search_column' " +
"FROM magazine " +
"WHERE magazine.name=search_column "
val searchColumn = concat(MAGAZINE.NAME, " ".asColumn, MAGAZINE.NR_OF_RELEASES) AS "search_column"
(SELECT
COLUMNS arrayOf(MAGAZINE.all(), searchColumn)
FROM MAGAZINE
WHERE (MAGAZINE.NAME IS (searchColumn)))
.isEqualTo(expected)
expected = "SELECT trim(magazine.name) AS 'trimmed_title' " +
"FROM magazine " +
"WHERE trim(magazine.name)=trimmed_title "
val trimmedTitle = MAGAZINE.NAME.trim() AS "trimmed_title"
(SELECT
COLUMN trimmedTitle
FROM MAGAZINE
WHERE (MAGAZINE.NAME.trim() IS trimmedTitle))
.isEqualTo(expected)
}
@Test
fun betweenComplex() {
val expectedBase = "SELECT * FROM magazine "
val randomAuthor = Author.newRandom()
val randomAuthor2 = Author.newRandom()
var expected = expectedBase + "WHERE magazine.author BETWEEN ? AND ? "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (randomAuthor AND randomAuthor2)))
.isEqualTo(expected, randomAuthor.id.toString(), randomAuthor2.id.toString())
expected = expectedBase + "WHERE magazine.author BETWEEN ? AND author.id "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (randomAuthor AND AUTHOR.ID)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE magazine.author BETWEEN author.id AND ? "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (AUTHOR.ID AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE magazine.author BETWEEN author.id AND magazine.id "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (AUTHOR.ID AND MAGAZINE.ID)))
.isEqualTo(expected)
expected = expectedBase + "WHERE magazine.author BETWEEN magazine.author AND magazine.id "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (MAGAZINE.AUTHOR AND MAGAZINE.ID)))
.isEqualTo(expected)
expected = expectedBase + "WHERE magazine.author BETWEEN magazine.author AND magazine.author "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (MAGAZINE.AUTHOR AND MAGAZINE.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "WHERE magazine.author BETWEEN magazine.author AND ? "
(SELECT
FROM MAGAZINE
WHERE (MAGAZINE.AUTHOR BETWEEN (MAGAZINE.AUTHOR AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
}
@Test
fun betweenComplexAliased() {
val expectedBase = "SELECT * FROM magazine AS m "
val randomAuthor = Author.newRandom()
val randomAuthor2 = Author.newRandom()
val a = AUTHOR AS "a"
val m = MAGAZINE AS "m"
var expected = expectedBase + "WHERE m.author BETWEEN ? AND ? "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (randomAuthor AND randomAuthor2)))
.isEqualTo(expected, randomAuthor.id.toString(), randomAuthor2.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN ? AND author.id "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (randomAuthor AND AUTHOR.ID)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN ? AND a.id "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (randomAuthor AND a.ID)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN author.id AND ? "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (AUTHOR.ID AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN a.id AND ? "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (a.ID AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN author.id AND m.id "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (AUTHOR.ID AND m.ID)))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author BETWEEN a.id AND m.id "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (a.ID AND m.ID)))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author BETWEEN magazine.author AND m.author "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (MAGAZINE.AUTHOR AND m.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author BETWEEN m.author AND m.author "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (m.AUTHOR AND m.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author BETWEEN magazine.author AND ? "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (MAGAZINE.AUTHOR AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author BETWEEN m.author AND ? "
(SELECT
FROM m
WHERE (m.AUTHOR BETWEEN (m.AUTHOR AND randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
}
@Test
fun rawExpr() {
var sql = "author.name IS NOT NULL"
sql.expr.isEqualTo(sql)
sql = "author.name = ?"
sql.expr("asd").isEqualTo(sql, "asd")
sql = "author.name = ? AND author.name != ?"
sql.expr("asd", "dsa").isEqualTo(sql, "asd", "dsa")
}
@Test
fun rawExprWithNonRawExpr() {
var sql = "author.name = ?"
var expr = (AUTHOR.NAME IS_NOT "dsa") AND sql.expr("asd")
expr.isEqualTo("(author.name!=? AND $sql)", "dsa", "asd")
sql = "author.name = ?"
expr = sql.expr("asd") AND (AUTHOR.NAME IS_NOT "dsa")
expr.isEqualTo("($sql AND author.name!=?)", "asd", "dsa")
sql = "author.name IS NOT NULL"
expr = AUTHOR.NAME IS_NOT "asd" AND sql.expr
expr.isEqualTo("(author.name!=? AND $sql)", "asd")
sql = "author.name IS NOT NULL"
expr = sql.expr AND (AUTHOR.NAME IS_NOT "asd")
expr.isEqualTo("($sql AND author.name!=?)", "asd")
}
@Test
fun exprSimple() {
assertSimpleExpr("=?", AUTHOR.NAME IS "asd")
assertSimpleExpr("!=?", AUTHOR.NAME IS_NOT "asd")
assertSimpleExpr(" IN (?)", AUTHOR.NAME IN arrayOf("asd"))
assertSimpleExpr(" NOT IN (?)", AUTHOR.NAME NOT_IN arrayOf("asd"))
assertSimpleColumnExpr("=", AUTHOR.NAME IS MAGAZINE.NAME)
assertSimpleColumnExpr("!=", AUTHOR.NAME IS_NOT MAGAZINE.NAME)
}
private fun assertSimpleExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM author WHERE author.name%s "
(SELECT FROM AUTHOR WHERE expr)
.isEqualTo(String.format(expectedBase, operator), "asd")
}
private fun assertSimpleColumnExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM author WHERE author.name%smagazine.name "
(SELECT FROM AUTHOR WHERE expr)
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun unaryExpr() {
(SELECT
FROM AUTHOR
WHERE !(AUTHOR.PRIMITIVE_BOOLEAN.isNotNull))
.isEqualTo("SELECT * FROM author WHERE NOT(author.primitive_boolean IS NOT NULL) ")
(SELECT
FROM AUTHOR
WHERE !((AUTHOR.PRIMITIVE_BOOLEAN GREATER_THAN AUTHOR.BOXED_BOOLEAN) AND AUTHOR.BOXED_BOOLEAN.isNotNull))
.isEqualTo("SELECT * FROM author WHERE NOT((author.primitive_boolean>author.boxed_boolean AND author.boxed_boolean IS NOT NULL)) ")
}
@Test
fun numericExprWithSameType() {
assertNumericExpr("=?", (MAGAZINE.NR_OF_RELEASES IS 4))
assertNumericExpr("!=?", (MAGAZINE.NR_OF_RELEASES IS_NOT 4))
assertNumericExpr(" IN (?)", (MAGAZINE.NR_OF_RELEASES IN arrayOf(4)))
assertNumericExpr(" NOT IN (?)", (MAGAZINE.NR_OF_RELEASES NOT_IN arrayOf(4)))
assertNumericExpr(">?", (MAGAZINE.NR_OF_RELEASES GREATER_THAN 4))
assertNumericExpr(">=?", (MAGAZINE.NR_OF_RELEASES GREATER_OR_EQUAL 4))
assertNumericExpr("<?", (MAGAZINE.NR_OF_RELEASES LESS_THAN 4))
assertNumericExpr("<=?", (MAGAZINE.NR_OF_RELEASES LESS_OR_EQUAL 4))
}
@Test
fun numericExprWithSameColumnType() {
assertNumericSameTypeExpr("=", (MAGAZINE.NR_OF_RELEASES IS IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
assertNumericSameTypeExpr("!=", (MAGAZINE.NR_OF_RELEASES IS_NOT IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
assertNumericSameTypeExpr(">", (MAGAZINE.NR_OF_RELEASES GREATER_THAN IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
assertNumericSameTypeExpr(">=", (MAGAZINE.NR_OF_RELEASES GREATER_OR_EQUAL IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
assertNumericSameTypeExpr("<", (MAGAZINE.NR_OF_RELEASES LESS_THAN IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
assertNumericSameTypeExpr("<=", (MAGAZINE.NR_OF_RELEASES LESS_OR_EQUAL IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
}
@Test
fun numericExprWithEquivalentColumnType() {
assertNumericEquivalentTypeExpr("=", (MAGAZINE.NR_OF_RELEASES IS IMMUTABLE_VALUE_WITH_FIELDS.ID))
assertNumericEquivalentTypeExpr("!=", (MAGAZINE.NR_OF_RELEASES IS_NOT IMMUTABLE_VALUE_WITH_FIELDS.ID))
assertNumericEquivalentTypeExpr(">", (MAGAZINE.NR_OF_RELEASES GREATER_THAN IMMUTABLE_VALUE_WITH_FIELDS.ID))
assertNumericEquivalentTypeExpr(">=", (MAGAZINE.NR_OF_RELEASES GREATER_OR_EQUAL IMMUTABLE_VALUE_WITH_FIELDS.ID))
assertNumericEquivalentTypeExpr("<", (MAGAZINE.NR_OF_RELEASES LESS_THAN IMMUTABLE_VALUE_WITH_FIELDS.ID))
assertNumericEquivalentTypeExpr("<=", (MAGAZINE.NR_OF_RELEASES LESS_OR_EQUAL IMMUTABLE_VALUE_WITH_FIELDS.ID))
}
private fun assertNumericExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.nr_of_releases%s "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator), "4")
}
private fun assertNumericSameTypeExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.nr_of_releases%simmutable_value_with_fields.integer "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator))
}
private fun assertNumericEquivalentTypeExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.nr_of_releases%simmutable_value_with_fields.id "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun complexExprWithSameType() {
val randomAuthor = Author.newRandom()
assertComplexSameTypeExpr("=?", randomAuthor, MAGAZINE.AUTHOR IS randomAuthor)
assertComplexSameTypeExpr("!=?", randomAuthor, MAGAZINE.AUTHOR.isNot(randomAuthor))
assertComplexSameTypeExpr(" IN (?)", randomAuthor, MAGAZINE.AUTHOR.`in`(randomAuthor))
assertComplexSameTypeExpr(" IN (?)", randomAuthor, MAGAZINE.AUTHOR.`in`(randomAuthor))
assertComplexSameTypeExpr(" NOT IN (?)", randomAuthor, MAGAZINE.AUTHOR.notIn(randomAuthor))
assertComplexSameTypeExpr(">?", randomAuthor, MAGAZINE.AUTHOR.greaterThan(randomAuthor))
assertComplexSameTypeExpr(">=?", randomAuthor, MAGAZINE.AUTHOR.greaterOrEqual(randomAuthor))
assertComplexSameTypeExpr("<?", randomAuthor, MAGAZINE.AUTHOR.lessThan(randomAuthor))
assertComplexSameTypeExpr("<=?", randomAuthor, MAGAZINE.AUTHOR.lessOrEqual(randomAuthor))
}
@Test
fun complexExprWithEquivalentType() {
val authorId: Long = 42
assertComplexEquivalentTypeExpr("=?", authorId, MAGAZINE.AUTHOR IS authorId)
assertComplexEquivalentTypeExpr("!=?", authorId, MAGAZINE.AUTHOR IS_NOT authorId)
assertComplexEquivalentTypeExpr(" IN (?)", authorId, MAGAZINE.AUTHOR IN longArrayOf(authorId))
assertComplexEquivalentTypeExpr(" NOT IN (?)", authorId, MAGAZINE.AUTHOR NOT_IN longArrayOf(authorId))
assertComplexEquivalentTypeExpr(">?", authorId, MAGAZINE.AUTHOR GREATER_THAN authorId)
assertComplexEquivalentTypeExpr(">=?", authorId, MAGAZINE.AUTHOR GREATER_OR_EQUAL authorId)
assertComplexEquivalentTypeExpr("<?", authorId, MAGAZINE.AUTHOR LESS_THAN authorId)
assertComplexEquivalentTypeExpr("<=?", authorId, MAGAZINE.AUTHOR LESS_OR_EQUAL authorId)
}
@Test
fun complexExprWithSameColumnType() {
assertComplexSameColumnTypeExpr("=", MAGAZINE.AUTHOR IS MAGAZINE.AUTHOR)
assertComplexSameColumnTypeExpr("!=", MAGAZINE.AUTHOR IS_NOT MAGAZINE.AUTHOR)
assertComplexSameColumnTypeExpr(">", MAGAZINE.AUTHOR GREATER_THAN MAGAZINE.AUTHOR)
assertComplexSameColumnTypeExpr(">=", MAGAZINE.AUTHOR GREATER_OR_EQUAL MAGAZINE.AUTHOR)
assertComplexSameColumnTypeExpr("<", MAGAZINE.AUTHOR LESS_THAN MAGAZINE.AUTHOR)
assertComplexSameColumnTypeExpr("<=", MAGAZINE.AUTHOR LESS_OR_EQUAL MAGAZINE.AUTHOR)
}
@Test
fun complexExprWithEquivalentColumnType() {
assertComplexEquivalentColumnTypeExpr("=", MAGAZINE.AUTHOR IS MAGAZINE.ID)
assertComplexEquivalentColumnTypeExpr("!=", MAGAZINE.AUTHOR IS_NOT MAGAZINE.ID)
assertComplexEquivalentColumnTypeExpr(">", MAGAZINE.AUTHOR GREATER_THAN MAGAZINE.ID)
assertComplexEquivalentColumnTypeExpr(">=", MAGAZINE.AUTHOR GREATER_OR_EQUAL MAGAZINE.ID)
assertComplexEquivalentColumnTypeExpr("<", MAGAZINE.AUTHOR LESS_THAN MAGAZINE.ID)
assertComplexEquivalentColumnTypeExpr("<=", MAGAZINE.AUTHOR LESS_OR_EQUAL MAGAZINE.ID)
}
private fun assertComplexSameTypeExpr(operator: String, `val`: Author, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%s "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator),
`val`.id.toString())
}
private fun assertComplexEquivalentTypeExpr(operator: String, `val`: Long, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%s "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator),
java.lang.Long.toString(`val`))
}
private fun assertComplexSameColumnTypeExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%smagazine.author "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator))
}
private fun assertComplexEquivalentColumnTypeExpr(operator: String, expr: Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%smagazine.id "
(SELECT FROM MAGAZINE WHERE expr)
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun exprComplexAliased() {
val expectedBase = "SELECT * FROM magazine AS m "
val randomAuthor = Author.newRandom()
val m = MAGAZINE AS "m"
var expected = expectedBase + "WHERE m.author=? "
(SELECT
FROM m
WHERE (m.AUTHOR IS randomAuthor))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "WHERE m.author=magazine.author "
(SELECT
FROM m
WHERE (m.AUTHOR IS MAGAZINE.AUTHOR))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author=m.author "
(SELECT
FROM m
WHERE (m.AUTHOR IS m.AUTHOR))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author=magazine.id "
(SELECT
FROM m
WHERE (m.AUTHOR IS MAGAZINE.ID))
.isEqualTo(expected)
expected = expectedBase + "WHERE m.author=m.id "
(SELECT
FROM m
WHERE (m.AUTHOR IS m.ID))
.isEqualTo(expected)
}
@Test
fun joinComplex() {
val randomAuthor = Author.newRandom()
val expectedBase = "SELECT * FROM magazine "
var expected = expectedBase + "LEFT JOIN magazine ON magazine.author!=magazine.author "
(SELECT
FROM MAGAZINE
LEFT_JOIN (MAGAZINE ON (MAGAZINE.AUTHOR IS_NOT MAGAZINE.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine ON magazine.author!=magazine.id "
(SELECT
FROM MAGAZINE
LEFT_JOIN (MAGAZINE ON (MAGAZINE.AUTHOR IS_NOT MAGAZINE.ID)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine ON magazine.author=? "
(SELECT
FROM MAGAZINE
LEFT_JOIN (MAGAZINE ON (MAGAZINE.AUTHOR IS randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
}
@Test
fun joinComplexAliased() {
val randomAuthor = Author.newRandom()
val expectedBase = "SELECT * FROM magazine AS m "
val m = MAGAZINE AS "m"
var expected = expectedBase + "LEFT JOIN magazine ON m.author!=magazine.author "
(SELECT
FROM m
LEFT_JOIN (MAGAZINE.on(m.AUTHOR IS_NOT MAGAZINE.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine AS m ON m.author!=m.author "
(SELECT
FROM m
LEFT_JOIN (m.on(m.AUTHOR IS_NOT m.AUTHOR)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine ON m.author!=magazine.id "
(SELECT
FROM m
LEFT_JOIN (MAGAZINE.on(m.AUTHOR IS_NOT MAGAZINE.ID)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine AS m ON m.author!=m.id "
(SELECT
FROM m
LEFT_JOIN (m.on(m.AUTHOR IS_NOT m.ID)))
.isEqualTo(expected)
expected = expectedBase + "LEFT JOIN magazine ON m.author=? "
(SELECT
FROM m
LEFT_JOIN (MAGAZINE.on(m.AUTHOR IS randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
expected = expectedBase + "LEFT JOIN magazine AS m ON m.author=? "
(SELECT
FROM m
LEFT_JOIN (m.on(m.AUTHOR IS randomAuthor)))
.isEqualTo(expected, randomAuthor.id.toString())
}
@Test
fun groupByTest() {
val expectedBase = "SELECT * FROM magazine "
(SELECT
FROM MAGAZINE
GROUP_BY MAGAZINE.NAME)
.isEqualTo(expectedBase + "GROUP BY magazine.name ")
(SELECT
FROM MAGAZINE
GROUP_BY MAGAZINE.AUTHOR)
.isEqualTo(expectedBase + "GROUP BY magazine.author ")
(SELECT
FROM MAGAZINE
GROUP_BY arrayOf(MAGAZINE.ID, MAGAZINE.NAME, MAGAZINE.AUTHOR))
.isEqualTo(expectedBase + "GROUP BY magazine.id,magazine.name,magazine.author ")
(SELECT
FROM MAGAZINE
GROUP_BY MAGAZINE.NAME
HAVING (MAGAZINE.NR_OF_RELEASES IS 1990))
.isEqualTo(expectedBase + "GROUP BY magazine.name HAVING magazine.nr_of_releases=? ", "1990")
(SELECT
FROM MAGAZINE
GROUP_BY arrayOf(MAGAZINE.NAME, MAGAZINE.AUTHOR)
HAVING (MAGAZINE.NR_OF_RELEASES IS 1990))
.isEqualTo(expectedBase + "GROUP BY magazine.name,magazine.author HAVING magazine.nr_of_releases=? ", "1990")
(SELECT
FROM MAGAZINE
LEFT_JOIN IMMUTABLE_VALUE_WITH_FIELDS
GROUP_BY arrayOf(MAGAZINE.NAME, MAGAZINE.AUTHOR)
HAVING (MAGAZINE.NR_OF_RELEASES IS IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
.isEqualTo(expectedBase + "LEFT JOIN immutable_value_with_fields GROUP BY magazine.name,magazine.author HAVING magazine.nr_of_releases=immutable_value_with_fields.integer ")
(SELECT
FROM MAGAZINE
LEFT_JOIN AUTHOR
GROUP_BY AUTHOR.BOXED_BOOLEAN
HAVING (AUTHOR.PRIMITIVE_BOOLEAN IS true))
.isEqualTo(expectedBase + "LEFT JOIN author GROUP BY author.boxed_boolean HAVING author.primitive_boolean=? ", BooleanTransformer.objectToDbValue(true)!!.toString())
(SELECT
FROM MAGAZINE
LEFT_JOIN AUTHOR
GROUP_BY AUTHOR.BOXED_BOOLEAN
HAVING (AUTHOR.PRIMITIVE_BOOLEAN IS AUTHOR.PRIMITIVE_BOOLEAN))
.isEqualTo(expectedBase + "LEFT JOIN author GROUP BY author.boxed_boolean HAVING author.primitive_boolean=author.primitive_boolean ")
}
@Test
fun groupByTestAliased() {
val expectedBase = "SELECT * FROM magazine AS m "
val m = MAGAZINE AS "m"
val s = IMMUTABLE_VALUE_WITH_FIELDS AS "s"
val a = AUTHOR AS "a"
(SELECT
FROM m
GROUP_BY m.NAME)
.isEqualTo(expectedBase + "GROUP BY m.name ")
(SELECT
FROM m
GROUP_BY m.AUTHOR)
.isEqualTo(expectedBase + "GROUP BY m.author ")
(SELECT
FROM m
GROUP_BY arrayOf(m.ID, m.NAME, m.AUTHOR))
.isEqualTo(expectedBase + "GROUP BY m.id,m.name,m.author ")
(SELECT
FROM m
GROUP_BY m.NAME
HAVING (m.NR_OF_RELEASES IS 1990))
.isEqualTo(expectedBase + "GROUP BY m.name HAVING m.nr_of_releases=? ", "1990")
(SELECT
FROM m
GROUP_BY arrayOf(m.NAME, m.AUTHOR)
HAVING (m.NR_OF_RELEASES IS 1990))
.isEqualTo(expectedBase + "GROUP BY m.name,m.author HAVING m.nr_of_releases=? ", "1990")
(SELECT
FROM m
LEFT_JOIN IMMUTABLE_VALUE_WITH_FIELDS
GROUP_BY arrayOf(m.NAME, m.AUTHOR)
HAVING (m.NR_OF_RELEASES IS IMMUTABLE_VALUE_WITH_FIELDS.INTEGER))
.isEqualTo(expectedBase + "LEFT JOIN immutable_value_with_fields GROUP BY m.name,m.author HAVING m.nr_of_releases=immutable_value_with_fields.integer ")
(SELECT
FROM m
LEFT_JOIN s
GROUP_BY arrayOf(m.NAME, m.AUTHOR)
HAVING (m.NR_OF_RELEASES IS s.INTEGER))
.isEqualTo(expectedBase + "LEFT JOIN immutable_value_with_fields AS s GROUP BY m.name,m.author HAVING m.nr_of_releases=s.integer ")
(SELECT
FROM m
LEFT_JOIN AUTHOR
GROUP_BY AUTHOR.BOXED_BOOLEAN
HAVING (AUTHOR.PRIMITIVE_BOOLEAN IS true))
.isEqualTo(expectedBase + "LEFT JOIN author GROUP BY author.boxed_boolean HAVING author.primitive_boolean=? ", BooleanTransformer.objectToDbValue(true)!!.toString())
(SELECT
FROM m
LEFT_JOIN a
GROUP_BY a.BOXED_BOOLEAN
HAVING (a.PRIMITIVE_BOOLEAN IS true))
.isEqualTo(expectedBase + "LEFT JOIN author AS a GROUP BY a.boxed_boolean HAVING a.primitive_boolean=? ", BooleanTransformer.objectToDbValue(true)!!.toString())
(SELECT
FROM m
LEFT_JOIN AUTHOR
GROUP_BY AUTHOR.BOXED_BOOLEAN
HAVING (AUTHOR.PRIMITIVE_BOOLEAN IS AUTHOR.PRIMITIVE_BOOLEAN))
.isEqualTo(expectedBase + "LEFT JOIN author GROUP BY author.boxed_boolean HAVING author.primitive_boolean=author.primitive_boolean ")
(SELECT
FROM m
LEFT_JOIN a
GROUP_BY a.BOXED_BOOLEAN
HAVING (a.PRIMITIVE_BOOLEAN IS a.PRIMITIVE_BOOLEAN))
.isEqualTo(expectedBase + "LEFT JOIN author AS a GROUP BY a.boxed_boolean HAVING a.primitive_boolean=a.primitive_boolean ")
}
@Test
fun orderByTest() {
val expectedBase = "SELECT * FROM magazine "
var expected = expectedBase + "ORDER BY magazine.nr_of_releases ASC "
(SELECT
FROM MAGAZINE
ORDER_BY MAGAZINE.NR_OF_RELEASES.asc())
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases ASC,magazine.name ASC "
(SELECT
FROM MAGAZINE
ORDER_BY arrayOf(MAGAZINE.NR_OF_RELEASES.asc(), MAGAZINE.NAME.asc()))
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases ASC,magazine.name ASC,magazine.author ASC "
(SELECT
FROM MAGAZINE
ORDER_BY arrayOf(MAGAZINE.NR_OF_RELEASES.asc(), MAGAZINE.NAME.asc(), MAGAZINE.AUTHOR.asc()))
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases DESC "
(SELECT
FROM MAGAZINE
ORDER_BY MAGAZINE.NR_OF_RELEASES.desc())
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases DESC,magazine.name ASC "
(SELECT
FROM MAGAZINE
ORDER_BY arrayOf(MAGAZINE.NR_OF_RELEASES.desc(), MAGAZINE.NAME.asc()))
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases ASC,magazine.name DESC "
(SELECT
FROM MAGAZINE
ORDER_BY arrayOf(MAGAZINE.NR_OF_RELEASES.asc(), MAGAZINE.NAME.desc()))
.isEqualTo(expected)
expected = expectedBase + "ORDER BY trim(magazine.nr_of_releases) DESC "
(SELECT
FROM MAGAZINE
ORDER_BY MAGAZINE.NR_OF_RELEASES.trim().desc())
.isEqualTo(expected)
expected = expectedBase + "ORDER BY magazine.nr_of_releases || ' ' || magazine.name ASC "
(SELECT
FROM MAGAZINE
ORDER_BY ((MAGAZINE.NR_OF_RELEASES concat " ".asColumn) concat MAGAZINE.NAME).asc())
.isEqualTo(expected)
}
@Test
fun limitTest() {
val expectedBase = "SELECT * FROM magazine "
(SELECT
FROM MAGAZINE
LIMIT 4)
.isEqualTo(expectedBase + "LIMIT 4 ")
(SELECT
FROM MAGAZINE
LIMIT 55
OFFSET 6)
.isEqualTo(expectedBase + "LIMIT 55 OFFSET 6 ")
}
@Test
fun simpleSubquery() {
assertSimpleSubquery("=") { AUTHOR.NAME IS it }
assertSimpleSubquery("!=") { AUTHOR.NAME IS_NOT it }
assertSimpleSubquery(" IN ") { AUTHOR.NAME IN it }
assertSimpleSubquery(" NOT IN ") { AUTHOR.NAME NOT_IN it }
}
private fun assertSimpleSubquery(operator: String, callback: (SelectNode<String, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM author WHERE author.name%s(SELECT immutable_value_with_fields.string_value FROM immutable_value_with_fields ) "
val subQuery = (SELECT
COLUMN IMMUTABLE_VALUE_WITH_FIELDS.STRING_VALUE
FROM IMMUTABLE_VALUE_WITH_FIELDS)
(SELECT
FROM AUTHOR
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun numericSubquery() {
assertSameTypeNumericSubquery("=") { MAGAZINE.NR_OF_RELEASES IS it }
assertSameTypeNumericSubquery("!=") { MAGAZINE.NR_OF_RELEASES IS_NOT it }
assertSameTypeNumericSubquery(" IN ") { MAGAZINE.NR_OF_RELEASES IN it }
assertSameTypeNumericSubquery(" NOT IN ") { MAGAZINE.NR_OF_RELEASES NOT_IN it }
assertSameTypeNumericSubquery(">") { MAGAZINE.NR_OF_RELEASES GREATER_THAN it }
assertSameTypeNumericSubquery(">=") { MAGAZINE.NR_OF_RELEASES GREATER_OR_EQUAL it }
assertSameTypeNumericSubquery("<") { MAGAZINE.NR_OF_RELEASES LESS_THAN it }
assertSameTypeNumericSubquery("<=") { MAGAZINE.NR_OF_RELEASES LESS_OR_EQUAL it }
assertEquivalentTypeNumericSubquery(">") { MAGAZINE.NR_OF_RELEASES GREATER_THAN it }
assertEquivalentTypeNumericSubquery(">=") { MAGAZINE.NR_OF_RELEASES GREATER_OR_EQUAL it }
assertEquivalentTypeNumericSubquery("<") { MAGAZINE.NR_OF_RELEASES LESS_THAN it }
assertEquivalentTypeNumericSubquery("<=") { MAGAZINE.NR_OF_RELEASES LESS_OR_EQUAL it }
}
private fun assertSameTypeNumericSubquery(operator: String, callback: (SelectNode<Int, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.nr_of_releases%s(SELECT immutable_value_with_fields.integer FROM immutable_value_with_fields ) "
val subQuery = (SELECT
COLUMN IMMUTABLE_VALUE_WITH_FIELDS.INTEGER
FROM IMMUTABLE_VALUE_WITH_FIELDS)
(SELECT
FROM MAGAZINE
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
private fun assertEquivalentTypeNumericSubquery(operator: String, callback: (SelectNode<out Number, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.nr_of_releases%s(SELECT immutable_value_with_fields.a_double FROM immutable_value_with_fields ) "
val subQuery = (SELECT
COLUMN IMMUTABLE_VALUE_WITH_FIELDS.A_DOUBLE
FROM IMMUTABLE_VALUE_WITH_FIELDS)
(SELECT
FROM MAGAZINE
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun complexSubquery() {
assertSameTypeComplexSubquery("=") { MAGAZINE.AUTHOR IS it }
assertSameTypeComplexSubquery("!=") { MAGAZINE.AUTHOR IS_NOT it }
assertSameTypeComplexSubquery(" IN ") { MAGAZINE.AUTHOR IN it }
assertSameTypeComplexSubquery(" NOT IN ") { MAGAZINE.AUTHOR NOT_IN it }
assertSameTypeComplexSubquery(">") { MAGAZINE.AUTHOR GREATER_THAN it }
assertSameTypeComplexSubquery(">=") { MAGAZINE.AUTHOR GREATER_OR_EQUAL it }
assertSameTypeComplexSubquery("<") { MAGAZINE.AUTHOR LESS_THAN it }
assertSameTypeComplexSubquery("<=") { MAGAZINE.AUTHOR LESS_OR_EQUAL it }
assertIdTypeComplexSubquery("=") { MAGAZINE.AUTHOR IS it }
assertIdTypeComplexSubquery("!=") { MAGAZINE.AUTHOR IS_NOT it }
assertIdTypeComplexSubquery(" IN ") { MAGAZINE.AUTHOR IN it }
assertIdTypeComplexSubquery(" NOT IN ") { MAGAZINE.AUTHOR NOT_IN it }
assertIdTypeComplexSubquery(">") { MAGAZINE.AUTHOR GREATER_THAN it }
assertIdTypeComplexSubquery(">=") { MAGAZINE.AUTHOR GREATER_OR_EQUAL it }
assertIdTypeComplexSubquery("<") { MAGAZINE.AUTHOR LESS_THAN it }
assertIdTypeComplexSubquery("<=") { MAGAZINE.AUTHOR LESS_OR_EQUAL it }
assertEquivalentTypeComplexSubquery("=") { MAGAZINE.AUTHOR IS it }
assertEquivalentTypeComplexSubquery("!=") { MAGAZINE.AUTHOR IS_NOT it }
assertEquivalentTypeComplexSubquery(" IN ") { MAGAZINE.AUTHOR IN it }
assertEquivalentTypeComplexSubquery(" NOT IN ") { MAGAZINE.AUTHOR NOT_IN it }
assertEquivalentTypeComplexSubquery(">") { MAGAZINE.AUTHOR GREATER_THAN it }
assertEquivalentTypeComplexSubquery(">=") { MAGAZINE.AUTHOR GREATER_OR_EQUAL it }
assertEquivalentTypeComplexSubquery("<") { MAGAZINE.AUTHOR LESS_THAN it }
assertEquivalentTypeComplexSubquery("<=") { MAGAZINE.AUTHOR LESS_OR_EQUAL it }
}
private fun assertSameTypeComplexSubquery(operator: String, callback: (SelectNode<Long, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%s(SELECT magazine.author FROM magazine ) "
val subQuery = (SELECT
COLUMN MAGAZINE.AUTHOR
FROM MAGAZINE)
(SELECT
FROM MAGAZINE
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
private fun assertIdTypeComplexSubquery(operator: String, callback: (SelectNode<Long, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%s(SELECT magazine.id FROM magazine ) "
val subQuery = (SELECT
COLUMN MAGAZINE.ID
FROM MAGAZINE)
(SELECT
FROM MAGAZINE
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
private fun assertEquivalentTypeComplexSubquery(operator: String, callback: (SelectNode<Int, Select1, *>) -> Expr) {
val expectedBase = "SELECT * FROM magazine WHERE magazine.author%s(SELECT immutable_value_with_fields.integer FROM immutable_value_with_fields ) "
val subQuery = (SELECT
COLUMN IMMUTABLE_VALUE_WITH_FIELDS.INTEGER
FROM IMMUTABLE_VALUE_WITH_FIELDS)
(SELECT
FROM MAGAZINE
WHERE callback(subQuery))
.isEqualTo(String.format(expectedBase, operator))
}
@Test
fun unaryMinus() {
(SELECT
COLUMN -(MAGAZINE.NR_OF_RELEASES - 42)
FROM MAGAZINE)
.isEqualTo("SELECT -((magazine.nr_of_releases-42)) FROM magazine ")
(SELECT
COLUMN -(MAGAZINE.NR_OF_RELEASES - -42)
FROM MAGAZINE)
.isEqualTo("SELECT -((magazine.nr_of_releases-(-42))) FROM magazine ")
(SELECT
COLUMN -(MAGAZINE.NR_OF_RELEASES - 42.asColumn)
FROM MAGAZINE)
.isEqualTo("SELECT -((magazine.nr_of_releases-42)) FROM magazine ")
(SELECT
COLUMN -(MAGAZINE.NR_OF_RELEASES - (-42).asColumn)
FROM MAGAZINE)
.isEqualTo("SELECT -((magazine.nr_of_releases-(-42))) FROM magazine ")
}
@Test
fun avgFunction() {
(SELECT
COLUMN IMMUTABLE_VALUE_WITH_FIELDS.ID
FROM IMMUTABLE_VALUE_WITH_FIELDS
WHERE ((avg(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER) GREATER_THAN 5555.0)
AND (avg(IMMUTABLE_VALUE_WITH_FIELDS.A_DOUBLE) LESS_THAN 8888.8)))
.isEqualTo("SELECT immutable_value_with_fields.id FROM immutable_value_with_fields WHERE (avg(immutable_value_with_fields.integer)>? AND avg(immutable_value_with_fields.a_double)<?) ")
}
@Test
fun concatFunction() {
var expected = "SELECT author.id || author.name FROM author "
(SELECT
COLUMN (AUTHOR.ID concat AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
expected = "SELECT author.id || author.name || author.primitive_boolean FROM author "
(SELECT
COLUMN concat(AUTHOR.ID, AUTHOR.NAME, AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR)
.isEqualTo(expected)
(SELECT
COLUMN ((AUTHOR.ID concat AUTHOR.NAME) concat AUTHOR.PRIMITIVE_BOOLEAN)
FROM AUTHOR)
.isEqualTo(expected)
}
@Test
fun replaceFunction() {
var expected = "SELECT replace(author.name,'a','____') FROM author "
(SELECT
COLUMN AUTHOR.NAME.replace("a" with "____")
FROM AUTHOR)
.isEqualTo(expected)
expected = "SELECT replace(author.name,'a','____') AS 'asd' FROM author "
(SELECT
COLUMN (AUTHOR.NAME.replace("a" with "____") AS "asd")
FROM AUTHOR)
.isEqualTo(expected)
}
@Test
fun valColumn() {
var expected = "SELECT author.id || ' ' || author.name FROM author "
val strVal = " ".asColumn
(SELECT
COLUMN concat(AUTHOR.ID, strVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
strVal.parsesWith(STRING)
expected = "SELECT author.id || 3 || author.name FROM author "
val intVal = 3.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, intVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
intVal.parsesWith(INTEGER)
expected = "SELECT author.id || 3 || author.name FROM author "
val longVal = 3L.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, longVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
longVal.parsesWith(LONG)
val s: Short = 3
expected = "SELECT author.id || 3 || author.name FROM author "
val shortVal = s.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, shortVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
shortVal.parsesWith(SHORT)
val b: Byte = 3
expected = "SELECT author.id || 3 || author.name FROM author "
val byteVal = b.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, byteVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
byteVal.parsesWith(BYTE)
val f = 3.3f
expected = "SELECT author.id || 3.3 || author.name FROM author "
val floatVal = f.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, floatVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
floatVal.parsesWith(FLOAT)
val d = 3.3
expected = "SELECT author.id || 3.3 || author.name FROM author "
val doubleVal = d.asColumn
(SELECT
COLUMN concat(AUTHOR.ID, doubleVal, AUTHOR.NAME)
FROM AUTHOR)
.isEqualTo(expected)
doubleVal.parsesWith(DOUBLE)
}
@Test
fun addFunction() {
assertArithmeticExpression('+',
{ v1, v2 -> v1 + v2 },
{ v1, v2 -> v1 + v2 },
{ v1, v2 -> v1 + v2 })
}
@Test
fun subFunction() {
assertArithmeticExpression('-',
{ v1, v2 -> v1 - v2 },
{ v1, v2 -> v1 - v2 },
{ v1, v2 -> v1 - v2 })
}
@Test
fun mulFunction() {
assertArithmeticExpression('*',
{ v1, v2 -> v1 * v2 },
{ v1, v2 -> v1 * v2 },
{ v1, v2 -> v1 * v2 })
}
@Test
fun divFunction() {
assertArithmeticExpression('/',
{ v1, v2 -> v1 / v2 },
{ v1, v2 -> v1 / v2 },
{ v1, v2 -> v1 / v2 })
}
@Test
fun modFunction() {
assertArithmeticExpression('%',
{ v1, v2 -> v1 % v2 },
{ v1, v2 -> v1 % v2 },
{ v1, v2 -> v1 % v2 })
}
@Test
fun numericArithmeticExpressionsChained() {
var expected = "SELECT ((((1+2)*(5-3))/2.0)%10.0) FROM immutable_value_with_fields "
(SELECT
COLUMN ((((1.asColumn + 2) * (5.asColumn - 3)) / 2.0) % 10.0)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
expected = "SELECT ((((immutable_value_with_fields.integer+2)*(5-3))/2.0)%10.0) FROM immutable_value_with_fields "
(SELECT
COLUMN ((((IMMUTABLE_VALUE_WITH_FIELDS.INTEGER + 2) * (5.asColumn - 3)) / 2.0) % 10.0)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
}
private fun assertArithmeticExpression(op: Char,
columnCallback: (NumericColumn<Int, Int, Number, ImmutableValueWithFields, *>, NumericColumn<Short, Short, Number, ImmutableValueWithFields, *>) -> NumericColumn<*, *, *, *, *>,
columnValueCallback: (NumericColumn<Int, Int, Number, ImmutableValueWithFields, *>, NumericColumn<Long, Long, Number, *, *>) -> NumericColumn<*, *, *, *, *>,
valueCallback: (NumericColumn<Int, Int, Number, ImmutableValueWithFields, *>, Int) -> NumericColumn<*, *, *, *, *>) {
var expected = String.format("SELECT (immutable_value_with_fields.integer%simmutable_value_with_fields.a_short) FROM immutable_value_with_fields ", op)
(SELECT
COLUMN columnCallback(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER, IMMUTABLE_VALUE_WITH_FIELDS.A_SHORT)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
expected = String.format("SELECT (immutable_value_with_fields.integer%s5) FROM immutable_value_with_fields ", op)
(SELECT
COLUMN columnValueCallback(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER, 5L.asColumn)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
expected = String.format("SELECT (immutable_value_with_fields.integer%s(-5)) FROM immutable_value_with_fields ", op)
(SELECT
COLUMN columnValueCallback(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER, (-5L).asColumn)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
expected = String.format("SELECT (immutable_value_with_fields.integer%s5) FROM immutable_value_with_fields ", op)
(SELECT
COLUMN valueCallback(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER, 5)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
expected = String.format("SELECT (immutable_value_with_fields.integer%s(-5)) FROM immutable_value_with_fields ", op)
(SELECT
COLUMN valueCallback(IMMUTABLE_VALUE_WITH_FIELDS.INTEGER, -5)
FROM IMMUTABLE_VALUE_WITH_FIELDS)
.isEqualTo(expected)
}
} | apache-2.0 | facc5ff423bea1c28613e56b7f8b5f4a | 35.382514 | 218 | 0.652092 | 3.943209 | false | false | false | false |
btnewton/tartarus | core/src/com/brandtsoftwarecompany/JsonSerializationTools.kt | 1 | 1947 | package com.brandtsoftwarecompany
import org.json.JSONArray
import org.json.JSONObject
import java.util.ArrayList
val TITLE_KEY = "title"
val USERNAME_KEY = "username"
val EMAIL_KEY = "email"
val WEBSITES_KEY = "websites"
val NOTES_KEY = "notes"
val PASSWORD_KEY = "password"
val LABELS_KEY = "labels"
val TAGS_KEY = "tags"
val LABEL_NAME_KEY = "name"
val LABEL_VALUE_KEY = "value"
fun Credentials.toJson(): JSONObject {
return JSONObject(mapOf(
TITLE_KEY to title,
USERNAME_KEY to username,
WEBSITES_KEY to JSONArray(websites),
PASSWORD_KEY to password,
NOTES_KEY to notes,
LABELS_KEY to JSONArray(labels.map { it.toJson() }),
TAGS_KEY to JSONArray(tags)
))
}
fun Label.toJson(): JSONObject {
return JSONObject(mapOf(
LABEL_NAME_KEY to name,
LABEL_VALUE_KEY to value
))
}
fun deserializeCredentials(json: JSONObject): Credentials {
val title = json.getString(TITLE_KEY)
val username = json.getString(USERNAME_KEY)
val email = json.getString(EMAIL_KEY)
val websites = json.getJSONArray<String>(WEBSITES_KEY, JSONArray::getString)
val password = json.getString(PASSWORD_KEY)
val notes = json.getString(NOTES_KEY)
val labels = json.getJSONArray<JSONObject>(LABELS_KEY, JSONArray::getJSONObject).map { deserializeLabel(it) }
val tags = json.getJSONArray<String>(TAGS_KEY, JSONArray::getString)
return Credentials(title, username, email, websites, password, notes, labels, tags)
}
private fun deserializeLabel(json: JSONObject): Label = Label(json.getString(LABEL_NAME_KEY), json.getString(LABEL_VALUE_KEY))
private inline fun <reified T> JSONObject.getJSONArray(key: String, f: (JSONArray, Int) -> T): ArrayList<T> {
val jsonArray = getJSONArray(key)
val result = arrayListOf<T>()
(0..jsonArray.length() - 1).mapTo(result) { f.invoke(jsonArray, it) }
return result
} | mit | 27f21f9c17ab8ec3be4b1b66f4f35eba | 33.175439 | 126 | 0.689266 | 3.715649 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/main/MainActivityViewModel.kt | 1 | 14348 | package wangdaye.com.geometricweather.main
import android.app.Application
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.core.app.ActivityCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import dagger.hilt.android.lifecycle.HiltViewModel
import wangdaye.com.geometricweather.common.basic.GeoViewModel
import wangdaye.com.geometricweather.common.basic.livedata.BusLiveData
import wangdaye.com.geometricweather.common.basic.livedata.EqualtableLiveData
import wangdaye.com.geometricweather.common.basic.models.Location
import wangdaye.com.geometricweather.main.utils.StatementManager
import wangdaye.com.geometricweather.settings.SettingsManager
import javax.inject.Inject
@HiltViewModel
class MainActivityViewModel @Inject constructor(
application: Application,
private val savedStateHandle: SavedStateHandle,
private val repository: MainActivityRepository,
val statementManager: StatementManager,
) : GeoViewModel(application),
MainActivityRepository.WeatherRequestCallback {
// live data.
val currentLocation = EqualtableLiveData<DayNightLocation>()
val validLocationList = MutableLiveData<SelectableLocationList>()
val totalLocationList = MutableLiveData<SelectableLocationList>()
val loading = EqualtableLiveData<Boolean>()
val indicator = EqualtableLiveData<Indicator>()
val permissionsRequest = MutableLiveData<PermissionsRequest?>()
val mainMessage = BusLiveData<MainMessage?>(Handler(Looper.getMainLooper()))
// inner data.
private var initCompleted = false
private var updating = false
companion object {
private const val KEY_FORMATTED_ID = "formatted_id"
}
// life cycle.
override fun onCleared() {
super.onCleared()
repository.destroy()
}
@JvmOverloads
fun init(formattedId: String? = null) {
onCleared()
var id = formattedId ?: savedStateHandle[KEY_FORMATTED_ID]
// init live data.
val totalList = repository.initLocations(
context = getApplication(),
formattedId = id ?: ""
)
val validList = Location.excludeInvalidResidentLocation(getApplication(), totalList)
id = formattedId ?: validList[0].formattedId
val current = validList.first { item -> item.formattedId == id }
initCompleted = false
currentLocation.setValue(DayNightLocation(location = current))
validLocationList.value = SelectableLocationList(locationList = validList, selectedId = id)
totalLocationList.value = SelectableLocationList(locationList = totalList, selectedId = id)
loading.setValue(false)
indicator.setValue(
Indicator(
total = validList.size,
index = validList.indexOfFirst { it.formattedId == id }
)
)
permissionsRequest.value = null
mainMessage.setValue(null)
// read weather caches.
repository.getWeatherCacheForLocations(
context = getApplication(),
oldList = totalList,
ignoredFormattedId = id,
) { newList, _ ->
initCompleted = true
newList?.let { updateInnerData(it) }
}
}
// update inner data.
private fun updateInnerData(location: Location) {
val total = ArrayList(
totalLocationList.value?.locationList ?: emptyList()
)
for (i in total.indices) {
if (total[i].formattedId == location.formattedId) {
total[i] = location
break
}
}
updateInnerData(total)
}
private fun updateInnerData(total: List<Location>) {
// get valid locations and current index.
val valid = Location.excludeInvalidResidentLocation(
getApplication(),
total,
)
var index = 0
for (i in valid.indices) {
if (valid[i].formattedId == currentLocation.value?.location?.formattedId) {
index = i
break
}
}
indicator.setValue(Indicator(total = valid.size, index = index))
// update current location.
setCurrentLocation(valid[index])
// check difference in valid locations.
val diffInValidLocations = validLocationList.value?.locationList != valid
if (
diffInValidLocations
|| validLocationList.value?.selectedId != valid[index].formattedId
) {
validLocationList.value = SelectableLocationList(
locationList = valid,
selectedId = valid[index].formattedId,
)
}
// update total locations.
totalLocationList.value = SelectableLocationList(
locationList = total,
selectedId = valid[index].formattedId,
)
}
private fun setCurrentLocation(location: Location) {
currentLocation.setValue(DayNightLocation(location = location))
savedStateHandle[KEY_FORMATTED_ID] = location.formattedId
checkToUpdateCurrentLocation()
}
private fun onUpdateResult(
location: Location,
locationResult: Boolean,
weatherUpdateResult: Boolean,
) {
if (!weatherUpdateResult) {
mainMessage.setValue(MainMessage.WEATHER_REQ_FAILED)
} else if (!locationResult) {
mainMessage.setValue(MainMessage.LOCATION_FAILED)
}
updateInnerData(location)
loading.setValue(false)
updating = false
}
private fun checkToUpdateCurrentLocation() {
// is not loading
if (!updating) {
// if already valid, just return.
if (currentLocationIsValid()) {
return
}
// if is not valid, we need:
// update if init completed.
// otherwise, mark a loading state and wait the init progress complete.
if (initCompleted) {
updateWithUpdatingChecking(
triggeredByUser = false,
checkPermissions = true,
)
} else {
loading.setValue(true)
updating = false
}
return
}
// is loading, do nothing.
}
private fun currentLocationIsValid() = currentLocation.value?.location?.weather?.isValid(
SettingsManager.getInstance(getApplication()).updateInterval.intervalInHour
) ?: false
// update.
fun updateWithUpdatingChecking(
triggeredByUser: Boolean,
checkPermissions: Boolean,
) {
if (updating) {
return
}
loading.setValue(true)
// don't need to request any permission -> request data directly.
if (
Build.VERSION.SDK_INT < Build.VERSION_CODES.M
|| currentLocation.value?.location?.isCurrentPosition == false
|| !checkPermissions
) {
updating = true
repository.getWeather(
getApplication(),
currentLocation.value!!.location,
currentLocation.value!!.location.isCurrentPosition,
this
)
return
}
// check permissions.
val permissionList = getDeniedPermissionList()
if (permissionList.isEmpty()) {
// already got all permissions -> request data directly.
updating = true
repository.getWeather(
getApplication(),
currentLocation.value!!.location,
true,
this
)
return
}
// request permissions.
updating = false
permissionsRequest.value = PermissionsRequest(
permissionList,
currentLocation.value!!.location,
triggeredByUser
)
}
private fun getDeniedPermissionList(): List<String> {
val permissionList = repository
.getLocatePermissionList(getApplication())
.toMutableList()
for (i in permissionList.indices.reversed()) {
if (
ActivityCompat.checkSelfPermission(
getApplication(),
permissionList[i]
) == PackageManager.PERMISSION_GRANTED
) {
permissionList.removeAt(i)
}
}
return permissionList
}
fun cancelRequest() {
updating = false
loading.setValue(false)
repository.cancelWeatherRequest()
}
fun checkToUpdate() {
checkToUpdateCurrentLocation()
}
fun updateLocationFromBackground(location: Location) {
if (!initCompleted) {
return
}
if (currentLocation.value?.location?.formattedId == location.formattedId) {
cancelRequest()
}
updateInnerData(location)
}
// set location.
fun setLocation(index: Int) {
validLocationList.value?.locationList?.let {
setLocation(it[index].formattedId)
}
}
fun setLocation(formattedId: String) {
cancelRequest()
validLocationList.value?.locationList?.let {
for (i in it.indices) {
if (it[i].formattedId != formattedId) {
continue
}
setCurrentLocation(it[i])
indicator.setValue(Indicator(total = it.size, index = i))
totalLocationList.value = SelectableLocationList(
locationList = totalLocationList.value?.locationList ?: emptyList(),
selectedId = formattedId,
)
validLocationList.value = SelectableLocationList(
locationList = validLocationList.value?.locationList ?: emptyList(),
selectedId = formattedId,
)
break
}
}
}
// return true if current location changed.
fun offsetLocation(offset: Int): Boolean {
cancelRequest()
val oldFormattedId = currentLocation.value?.location?.formattedId ?: ""
// ensure current index.
var index = 0
validLocationList.value?.locationList?.let {
for (i in it.indices) {
if (it[i].formattedId == currentLocation.value?.location?.formattedId) {
index = i
break
}
}
}
// update index.
index = (
index + offset + (validLocationList.value?.locationList?.size ?: 0)
) % (
validLocationList.value?.locationList?.size ?: 1
)
// update location.
setCurrentLocation(validLocationList.value!!.locationList[index])
indicator.setValue(
Indicator(total = validLocationList.value!!.locationList.size, index = index)
)
totalLocationList.value = SelectableLocationList(
locationList = totalLocationList.value?.locationList ?: emptyList(),
selectedId = currentLocation.value?.location?.formattedId ?: "",
)
validLocationList.value = SelectableLocationList(
locationList = validLocationList.value?.locationList ?: emptyList(),
selectedId = currentLocation.value?.location?.formattedId ?: "",
)
return currentLocation.value?.location?.formattedId != oldFormattedId
}
// list.
// return false if failed.
fun addLocation(
location: Location,
index: Int? = null,
): Boolean {
// do not add an existed location.
if (totalLocationList.value!!.locationList.firstOrNull {
it.formattedId == location.formattedId
} != null) {
return false
}
val total = ArrayList(totalLocationList.value?.locationList ?: emptyList())
total.add(index ?: total.size, location)
updateInnerData(total)
repository.writeLocationList(context = getApplication(), locationList = total)
return true
}
fun moveLocation(from: Int, to: Int) {
if (from == to) {
return
}
val total = ArrayList(totalLocationList.value?.locationList ?: emptyList())
total.add(to, total.removeAt(from))
updateInnerData(total)
repository.writeLocationList(
context = getApplication(),
locationList = totalLocationList.value?.locationList ?: emptyList()
)
}
fun updateLocation(location: Location) {
updateInnerData(location)
repository.writeLocationList(
context = getApplication(),
locationList = totalLocationList.value?.locationList ?: emptyList(),
)
}
fun deleteLocation(position: Int): Location {
val total = ArrayList(totalLocationList.value?.locationList ?: emptyList())
val location = total.removeAt(position)
updateInnerData(total)
repository.deleteLocation(context = getApplication(), location = location)
return location
}
// MARK: - getter.
fun getValidLocation(offset: Int): Location {
// ensure current index.
var index = 0
validLocationList.value?.locationList?.let {
for (i in it.indices) {
if (it[i].formattedId == currentLocation.value?.location?.formattedId) {
index = i
break
}
}
}
// update index.
index = (
index + offset + (validLocationList.value?.locationList?.size ?: 0)
) % (
validLocationList.value?.locationList?.size ?: 1
)
return validLocationList.value!!.locationList[index]
}
// impl.
override fun onCompleted(
location: Location,
locationFailed: Boolean?,
weatherRequestFailed: Boolean
) {
onUpdateResult(
location = location,
locationResult = locationFailed != true,
weatherUpdateResult = !weatherRequestFailed
)
}
} | lgpl-3.0 | 8e7999b3e296dc67d6f7afecbabbc9f6 | 29.336152 | 99 | 0.594508 | 5.249909 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/widget/FeedWidgetService.kt | 2 | 2390 | /*
* Copyright (C) 2011 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.commit451.gitlab.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.widget.RemoteViewsService
import com.commit451.gitlab.api.MoshiProvider
import com.commit451.gitlab.model.Account
import timber.log.Timber
/**
* Service that basically just defers everything to a Factory. Yay!
*/
class FeedWidgetService : RemoteViewsService() {
companion object {
const val EXTRA_ACCOUNT_JSON = "account_json"
const val EXTRA_FEED_URL = "feed_url"
/**
* Currently, when we pass this Intent along to certain launchers, they will not
* be able to un-marshall the Account class. So, we will just pass the account as json
* :(
*/
fun newIntent(context: Context, widgetId: Int, account: Account, feedUrl: String): Intent {
val adapter = MoshiProvider.moshi.adapter<Account>(Account::class.java)
val accountJson = adapter.toJson(account)
val intent = Intent(context, FeedWidgetService::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
intent.putExtra(EXTRA_ACCOUNT_JSON, accountJson)
intent.putExtra(EXTRA_FEED_URL, feedUrl)
return intent
}
}
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
Timber.d("onGetViewFactory")
val accountJson = intent.getStringExtra(EXTRA_ACCOUNT_JSON)!!
val adapter = MoshiProvider.moshi.adapter<Account>(Account::class.java)
val account = adapter.fromJson(accountJson)!!
val feedUrl = intent.getStringExtra(EXTRA_FEED_URL)!!
return FeedRemoteViewsFactory(applicationContext, account, feedUrl)
}
}
| apache-2.0 | 0f24eff041fe43e9a33cea907276f290 | 38.180328 | 99 | 0.705858 | 4.417745 | false | false | false | false |
pnemonic78/Electric-Fields | electric-android/app/src/main/kotlin/com/github/fields/electric/FieldsTask.kt | 1 | 6586 | /*
* Copyright 2016, Moshe Waisberg
*
* 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.github.fields.electric
import android.graphics.*
import android.graphics.Color.WHITE
import android.graphics.Paint.ANTI_ALIAS_FLAG
import com.github.reactivex.DefaultDisposable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import java.lang.Thread.sleep
import kotlin.math.max
import kotlin.math.sqrt
/**
* Electric Fields task.
*
* @author Moshe Waisberg
*/
class FieldsTask(private val charges: List<Charge>, private val bitmap: Bitmap, private val density: Double = DEFAULT_DENSITY, private val hues: Double = DEFAULT_HUES) : Observable<Bitmap>(), Disposable {
private var runner: FieldRunner? = null
var brightness = 1f
set(value) {
field = value
runner?.let { it.brightness = value }
}
var saturation = 1f
set(value) {
field = value
runner?.let { it.saturation = value }
}
var startDelay = 0L
set(value) {
field = value
runner?.let { it.startDelay = value }
}
override fun subscribeActual(observer: Observer<in Bitmap>) {
val d = FieldRunner(charges, bitmap, density, hues, observer)
d.brightness = brightness
d.saturation = saturation
d.startDelay = startDelay
runner = d
observer.onSubscribe(d)
d.run()
}
override fun isDisposed(): Boolean {
return runner?.isDisposed ?: false
}
override fun dispose() {
runner?.dispose()
}
private class FieldRunner(val charges: List<Charge>, val bitmap: Bitmap, val density: Double, val hues: Double, val observer: Observer<in Bitmap>) : DefaultDisposable() {
private val paint = Paint(ANTI_ALIAS_FLAG).apply {
strokeCap = Paint.Cap.SQUARE
style = Paint.Style.FILL
strokeWidth = 1f
}
private val rect = RectF()
private val hsv = floatArrayOf(0f, 1f, 1f)
var startDelay = 0L
var running = false
private set
var saturation: Float
get() = hsv[1]
set(value) {
hsv[1] = value
}
var brightness: Float
get() = hsv[2]
set(value) {
hsv[2] = value
}
fun run() {
running = true
if (startDelay > 0L) {
try {
sleep(startDelay)
} catch (ignore: InterruptedException) {
}
}
if (isDisposed) {
running = false
return
}
observer.onNext(bitmap)
val w = bitmap.width
val h = bitmap.height
var size = max(w, h)
var shifts = 0
while (size > 1) {
size = size ushr 1
shifts++
}
// Make "resolution2" a power of 2, so that "resolution" is always divisible by 2.
var resolution2 = 1 shl shifts
var resolution = resolution2
val canvas = Canvas(bitmap)
canvas.drawColor(WHITE)
plot(charges, canvas, 0, 0, resolution, resolution, density)
var x1: Int
var y1: Int
var x2: Int
var y2: Int
loop@ do {
y1 = 0
y2 = resolution
do {
x1 = 0
x2 = resolution
do {
plot(charges, canvas, x1, y2, resolution, resolution, density)
plot(charges, canvas, x2, y1, resolution, resolution, density)
plot(charges, canvas, x2, y2, resolution, resolution, density)
x1 += resolution2
x2 += resolution2
} while ((x1 < w) && !isDisposed)
if (isDisposed) {
break@loop
}
observer.onNext(bitmap)
y1 += resolution2
y2 += resolution2
} while (y1 < h)
resolution2 = resolution
resolution = resolution2 shr 1
} while ((resolution >= 1) && !isDisposed)
running = false
if (!isDisposed) {
observer.onNext(bitmap)
observer.onComplete()
}
}
private fun plot(charges: List<Charge>, canvas: Canvas, x: Int, y: Int, w: Int, h: Int, zoom: Double) {
var dx: Int
var dy: Int
var d: Int
var r: Double
var v = 1.0
val count = charges.size
var charge: Charge
for (i in 0 until count) {
charge = charges[i]
dx = x - charge.x
dy = y - charge.y
d = (dx * dx) + (dy * dy)
r = sqrt(d.toDouble())
if (r == 0.0) {
//Force "overflow".
v = Double.POSITIVE_INFINITY
break
}
v += charge.size / r
}
paint.color = mapColor(v, zoom)
rect.set(x.toFloat(), y.toFloat(), (x + w).toFloat(), (y + h).toFloat())
canvas.drawRect(rect, paint)
}
private fun mapColor(z: Double, density: Double): Int {
if (z.isInfinite()) {
return WHITE
}
hsv[0] = ((z * density) % hues).toFloat()
return Color.HSVToColor(hsv)
}
override fun onDispose() {
}
}
fun cancel() {
dispose()
}
fun isIdle(): Boolean = (runner == null) || !runner!!.running || isDisposed
companion object {
const val DEFAULT_DENSITY = 1000.0
const val DEFAULT_HUES = 360.0
}
}
| apache-2.0 | 7aeea4dc367113c60cebcb275fe3c272 | 28.800905 | 204 | 0.51078 | 4.605594 | false | false | false | false |
da1z/intellij-community | platform/lang-impl/src/com/intellij/index/PrebuiltIndex.kt | 4 | 4123 | // Copyright 2000-2017 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.index
import com.google.common.hash.HashCode
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.stubs.FileContentHashing
import com.intellij.psi.stubs.HashCodeDescriptor
import com.intellij.psi.stubs.PrebuiltStubsProviderBase
import com.intellij.util.SystemProperties
import com.intellij.util.indexing.FileContent
import com.intellij.util.indexing.IndexInfrastructure
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.PersistentHashMap
import java.io.File
import java.io.FileFilter
import java.io.IOException
/**
* @author traff
*/
abstract class PrebuiltIndexProviderBase<Value> : Disposable {
private val myFileContentHashing = FileContentHashing()
private var myPrebuiltIndexStorage: PersistentHashMap<HashCode, Value>? = null
protected abstract val dirName: String
protected abstract val indexName: String
protected abstract val indexExternalizer: DataExternalizer<Value>
companion object {
private val LOG = Logger.getInstance("#com.intellij.index.PrebuiltIndexProviderBase")
@JvmField
val DEBUG_PREBUILT_INDICES = SystemProperties.getBooleanProperty("debug.prebuilt.indices", false)
}
init {
init()
}
internal fun init() {
var indexesRoot = findPrebuiltIndicesRoot()
try {
if (indexesRoot != null && indexesRoot.exists()) {
// we should copy prebuilt indexes to a writable folder
indexesRoot = copyPrebuiltIndicesToIndexRoot(indexesRoot)
// otherwise we can get access denied error, because persistent hash map opens file for read and write
myPrebuiltIndexStorage = openIndexStorage(indexesRoot)
LOG.info("Using prebuilt $indexName from " + myPrebuiltIndexStorage!!.baseFile.absolutePath)
}
else {
LOG.info("Prebuilt $indexName indices are missing for $dirName")
}
}
catch (e: Exception) {
myPrebuiltIndexStorage = null
LOG.warn("Prebuilt indices can't be loaded at " + indexesRoot!!, e)
}
}
fun get(fileContent: FileContent): Value? {
if (Registry.`is`("use.prebuilt.indices")) {
if (myPrebuiltIndexStorage != null) {
val hashCode = myFileContentHashing.hashString(fileContent)
try {
return myPrebuiltIndexStorage!!.get(hashCode)
}
catch (e: Exception) {
LOG.error("Error reading prebuilt stubs from " + myPrebuiltIndexStorage!!.baseFile.path, e)
myPrebuiltIndexStorage = null
}
}
}
return null
}
open fun openIndexStorage(indexesRoot: File): PersistentHashMap<HashCode, Value>? {
return object : PersistentHashMap<HashCode, Value>(
File(indexesRoot, indexName + ".input"),
HashCodeDescriptor.instance,
indexExternalizer) {
override fun isReadOnly(): Boolean {
return true
}
}
}
@Throws(IOException::class)
private fun copyPrebuiltIndicesToIndexRoot(prebuiltIndicesRoot: File): File {
val indexRoot = File(IndexInfrastructure.getPersistentIndexRoot(), "prebuilt/" + dirName)
FileUtil.copyDir(prebuiltIndicesRoot, indexRoot, FileFilter { f -> f.name.startsWith(indexName) })
return indexRoot
}
private fun findPrebuiltIndicesRoot(): File? {
val path: String? = System.getProperty(PrebuiltStubsProviderBase.PREBUILT_INDICES_PATH_PROPERTY)
if (path != null && File(path).exists()) {
return File(path, dirName)
}
val f = indexRoot()
return if (f.exists()) f else null
}
open fun indexRoot(): File = File(PathManager.getHomePath(), "index/$dirName") // compiled binary
override fun dispose() {
if (myPrebuiltIndexStorage != null) {
try {
myPrebuiltIndexStorage!!.close()
}
catch (e: IOException) {
LOG.error(e)
}
}
}
}
| apache-2.0 | 58f680c0a0b00eda59d37a248fb96be0 | 32.520325 | 140 | 0.714771 | 4.525796 | false | false | false | false |
ahmedeltaher/MVP-RX-Android-Sample | app/src/test/java/com/task/ui/component/login/LoginViewModelTest.kt | 1 | 4606 | package com.task.ui.component.login
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.task.data.DataRepository
import com.task.data.Resource
import com.task.data.dto.login.LoginRequest
import com.task.data.dto.login.LoginResponse
import com.task.data.error.CHECK_YOUR_FIELDS
import com.task.data.error.PASS_WORD_ERROR
import com.task.data.error.USER_NAME_ERROR
import com.util.InstantExecutorExtension
import com.util.MainCoroutineRule
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.extension.ExtendWith
/**
* Created by AhmedEltaher
*/
@ExperimentalCoroutinesApi
@ExtendWith(InstantExecutorExtension::class)
class LoginViewModelTest {
// Subject under test
private lateinit var loginViewModel: LoginViewModel
// Use a fake UseCase to be injected into the viewModel
private val dataRepository: DataRepository = mockk()
// Set the main coroutines dispatcher for unit testing.
@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
// Executes each task synchronously using Architecture Components.
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
}
@Test
fun `login Success`() {
// Let's do an answer for the liveData
val userName = "[email protected]"
val password = "ahmed"
val loginResponse = LoginResponse("123", "Ahmed", "Mahmoud",
"FrunkfurterAlle", "77", "12000", "Berlin",
"Germany", "[email protected]")
//1- Mock calls
coEvery { dataRepository.doLogin(LoginRequest(userName, password)) } returns flow {
emit(Resource.Success(loginResponse))
}
//2-Call
loginViewModel = LoginViewModel(dataRepository)
loginViewModel.doLogin(userName, password)
//active observer for livedata
loginViewModel.loginLiveData.observeForever { }
//3-verify
val loginSuccess = loginViewModel.loginLiveData.value?.data
assertEquals(loginSuccess, loginResponse)
}
@Test
fun `login with Wrong Password`() {
// Let's do an answer for the liveData
val userName = "[email protected]"
val password = " "
//1- Mock calls
coEvery { dataRepository.doLogin(LoginRequest(userName, password)) } returns flow {
val result: Resource<LoginResponse> = Resource.DataError(PASS_WORD_ERROR)
emit(result)
}
//2-Call
loginViewModel = LoginViewModel(dataRepository)
loginViewModel.doLogin(userName, password)
//active observer for livedata
loginViewModel.loginLiveData.observeForever { }
//3-verify
val loginFail = loginViewModel.loginLiveData.value?.errorCode
assertEquals(PASS_WORD_ERROR, loginFail)
}
@Test
fun `login With Wrong User Name`() {
// Let's do an answer for the liveData
val userName = " "
val password = "ahmed"
//1- Mock calls
coEvery { dataRepository.doLogin(LoginRequest(userName, password)) } returns flow {
val result: Resource<LoginResponse> = Resource.DataError(USER_NAME_ERROR)
emit(result)
}
//2-Call
loginViewModel = LoginViewModel(dataRepository)
loginViewModel.doLogin(userName, password)
//active observer for livedata
loginViewModel.loginLiveData.observeForever { }
//3-verify
val loginFail = loginViewModel.loginLiveData.value?.errorCode
assertEquals(USER_NAME_ERROR, loginFail)
}
@Test
fun `login With Wrong User Name and password`() {
// Let's do an answer for the liveData
val userName = " "
val password = " "
//1- Mock calls
coEvery { dataRepository.doLogin(LoginRequest(userName, password)) } returns flow {
val result: Resource<LoginResponse> = Resource.DataError(CHECK_YOUR_FIELDS)
emit(result)
}
//2-Call
loginViewModel = LoginViewModel(dataRepository)
loginViewModel.doLogin(userName, password)
//active observer for livedata
loginViewModel.loginLiveData.observeForever { }
//3-verify
val loginFail = loginViewModel.loginLiveData.value?.errorCode
assertEquals(CHECK_YOUR_FIELDS, loginFail)
}
}
| apache-2.0 | 9d7837ef6a9d17a2b72e2353ec1c420c | 31.666667 | 91 | 0.676509 | 4.480545 | false | true | false | false |
PolymerLabs/arcs | java/arcs/core/storage/DirectStore.kt | 1 | 19062 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtChange
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtException
import arcs.core.crdt.CrdtModel
import arcs.core.crdt.CrdtModelType
import arcs.core.crdt.CrdtOperation
import arcs.core.storage.DirectStore.State.Name.AwaitingDriverModel
import arcs.core.storage.DirectStore.State.Name.AwaitingResponse
import arcs.core.storage.DirectStore.State.Name.Idle
import arcs.core.storage.util.callbackManager
import arcs.core.util.Random
import arcs.core.util.TaggedLog
import kotlin.coroutines.coroutineContext
import kotlinx.atomicfu.AtomicRef
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.getAndUpdate
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
// import kotlinx.coroutines.flow.debounce
// import kotlinx.coroutines.flow.filter
// import kotlinx.coroutines.flow.first
/**
* An [ActiveStore] capable of communicating directly with a [Driver].
*
* This is what *directly* manages a [CrdtSingleton], [CrdtSet], or [CrdtCount].
*/
@Suppress("EXPERIMENTAL_API_USAGE")
class DirectStore<Data : CrdtData, Op : CrdtOperation, T> /* internal */ constructor(
options: StoreOptions,
/** Coroutinescope for launching jobs. Currently only used to close the drive on [close]. */
val scope: CoroutineScope,
/* internal */
val localModel: CrdtModel<Data, Op, T>,
/* internal */
val driver: Driver<Data>,
private val writeBack: WriteBack,
private val devTools: DevToolsForDirectStore?
) : ActiveStore<Data, Op, T>(options) {
// TODO(#5551): Consider including a hash of state.value and storage key in log prefix.
private val log = TaggedLog { "DirectStore" }
/** True if this store has been closed. */
var closed = false
/**
* [AtomicRef] of a [CompletableDeferred] which will be completed when the [DirectStore]
* transitions into the Idle state.
*/
private val idleDeferred: AtomicRef<IdleDeferred> = atomic(CompletableDeferred(Unit))
/**
* [AtomicRef] of a list of [PendingDriverModel]s, allowing us to treat it as a copy-on-write,
* threadsafe list using [AtomicRef.update].
*/
private var pendingDriverModels = atomic(listOf<PendingDriverModel<Data>>())
private var version = atomic(0)
private var state: AtomicRef<State<Data>> = atomic(
State.Idle(idleDeferred, driver)
)
private val stateChannel =
ConflatedBroadcastChannel<State<Data>>(State.Idle(idleDeferred, driver))
private val stateFlow = stateChannel.asFlow()
private val callbackManager = callbackManager<ProxyMessage<Data, Op, T>>(
"direct",
Random
)
private val storeIdlenessFlow =
combine(stateFlow, writeBack.idlenessFlow) { state, writebackIsIdle ->
state is State.Idle<*> && writebackIsIdle
}
override suspend fun idle() {
/**
* TODO(b/172498981): tune the debounce window
* Once this is enabled, change [DirectStoreMuxer.idle] accordingly to use
* simultaneous launches.
*/
// storeIdlenessFlow.debounce(50).filter { it }.first()
}
fun getLocalData(): Data = synchronized(this) { localModel.data }
override suspend fun on(callback: ProxyCallback<Data, Op, T>): CallbackToken {
val callbackInvoke = callback::invoke
synchronized(callbackManager) {
return callbackManager.register(callbackInvoke)
}
}
override suspend fun off(callbackToken: CallbackToken) {
synchronized(callbackManager) {
callbackManager.unregister(callbackToken)
}
}
/** Closes the store. Once closed, it cannot be re-opened. A new instance must be created. */
override fun close() {
synchronized(callbackManager) {
callbackManager.clear()
closeInternal()
}
}
private fun closeInternal() {
if (!closed) {
closed = true
stateChannel.offer(State.Closed())
stateChannel.close()
state.value = State.Closed()
writeBack.close()
/**
* The [scope] was initialized and assigned at the [StorageService.onBind], hence
* the [driver.close] would only take effect in real use-cases / integration tests
* but unit tests which don't spin up entire storage service stack.
*/
scope.launch { driver.close() }
}
}
/**
* Receives operations/model-updates from connected storage proxies.
*
* Additionally, StorageProxy objects may request a SyncRequest, which will result in an
* up-to-date model being sent back to that StorageProxy. A return value of `true` implies that
* the message was accepted, a return value of `false` requires that the proxy send a model
* sync.
*/
@Suppress("UNCHECKED_CAST")
override suspend fun onProxyMessage(
message: ProxyMessage<Data, Op, T>
) {
when (message) {
is ProxyMessage.SyncRequest -> {
callbackManager.getCallback(message.id)?.invoke(
ProxyMessage.ModelUpdate(getLocalData(), message.id)
)
}
is ProxyMessage.Operations -> {
val failure = synchronized(this) {
!message.operations.all { localModel.applyOperation(it) }
}
if (failure) {
callbackManager.getCallback(message.id)?.invoke(
ProxyMessage.SyncRequest(message.id)
)
} else {
if (message.operations.isNotEmpty()) {
val change = CrdtChange.Operations<Data, Op>(
message.operations.toMutableList()
)
// As the localModel has already been applied with new operations,
// leave the flush job to write-back threads.
writeBack.asyncFlush {
processModelChange(
change,
otherChange = null,
version = version.value,
channel = message.id
)
}
}
Unit
}
}
is ProxyMessage.ModelUpdate -> {
val (modelChange, otherChange) = synchronized(this) {
localModel.merge(message.model)
}
// As the localModel has already been merged with new model updates,
// leave the flush job to write-back threads.
writeBack.asyncFlush {
processModelChange(
modelChange,
otherChange,
version.value,
channel = message.id
)
}
}
}.also {
log.verbose { "Model after proxy message: ${localModel.data}" }
devTools?.onDirectStoreProxyMessage(proxyMessage = message as UntypedProxyMessage)
}
}
private suspend fun processModelChange(
modelChange: CrdtChange<Data, Op>,
otherChange: CrdtChange<Data, Op>?,
version: Int,
channel: Int?
) {
if (modelChange.isEmpty() && otherChange?.isEmpty() == true) return
deliverCallbacks(modelChange, source = channel)
updateStateAndAct(
noDriverSideChanges(modelChange, otherChange, false),
version,
messageFromDriver = false
)
}
/* internal */ suspend fun onReceive(data: Data, version: Int) {
log.verbose { "onReceive($data, $version)" }
if (state.value is State.Closed<Data> || closed) {
log.verbose { "onReceive($data, $version) called after close(), ignoring" }
return
}
val currentState = state.value as State.StateWithData<Data>
if (currentState.shouldApplyPendingDriverModelsOnReceive(data, version)) {
val pending = pendingDriverModels.getAndUpdate { emptyList() }
applyPendingDriverModels(pending + PendingDriverModel(data, version))
} else {
// If the current state doesn't allow us to apply the models yet, tack it onto our
// pending list.
pendingDriverModels.getAndUpdate { it + PendingDriverModel(data, version) }
}
}
private suspend fun applyPendingDriverModels(models: List<PendingDriverModel<Data>>) {
if (models.isEmpty()) return
log.verbose { "Applying ${models.size} pending models: $models" }
var noDriverSideChanges = true
var theVersion = 0
models.forEach { (model, version) ->
try {
log.verbose { "Merging $model into ${localModel.data}" }
val (modelChange, otherChange) = synchronized(this) { localModel.merge(model) }
log.verbose { "ModelChange: $modelChange" }
log.verbose { "OtherChange: $otherChange" }
theVersion = version
if (modelChange.isEmpty() && otherChange.isEmpty()) return@forEach
deliverCallbacks(modelChange, null)
noDriverSideChanges = noDriverSideChanges && noDriverSideChanges(
modelChange,
otherChange,
messageFromDriver = true
)
log.debug { "No driver side changes? $noDriverSideChanges" }
} catch (e: Exception) {
// TODO(b/160251910): Make logging detail more cleanly conditional.
log.debug(e) { "Error while applying pending driver models." }
log.info { "Error while applying pending driver models." }
idleDeferred.value.completeExceptionally(e)
throw e
}
}
updateStateAndAct(noDriverSideChanges, theVersion, messageFromDriver = true)
}
/**
* Note that driver-side changes are stored in 'otherChange' when the merged operations/model is
* sent from the driver, and 'thisChange' when the merged operations/model is sent from a
* storageProxy. In the former case, we want to look at what has changed between what the driver
* sent us and what we now have. In the latter, the driver is only as up-to-date as our local
* model before we've applied the operations.
*/
private fun noDriverSideChanges(
thisChange: CrdtChange<Data, Op>,
otherChange: CrdtChange<Data, Op>?,
messageFromDriver: Boolean
): Boolean {
return if (messageFromDriver) {
otherChange?.isEmpty() ?: true
} else {
thisChange.isEmpty()
}
}
private suspend fun deliverCallbacks(thisChange: CrdtChange<Data, Op>, source: Int?) {
when (thisChange) {
is CrdtChange.Operations -> {
callbackManager.allCallbacksExcept(source).forEach { callback ->
callback(ProxyMessage.Operations(thisChange.ops, source))
}
}
is CrdtChange.Data -> {
callbackManager.allCallbacksExcept(source).forEach { callback ->
callback(ProxyMessage.ModelUpdate(thisChange.data, source))
}
}
}
}
/**
* This function implements a state machine that controls when data is sent to the driver.
*
* You can see the state machine in all its glory
* [here](https://github.com/PolymerLabs/arcs/wiki/Store-object-State-Machine).
*/
private suspend fun updateStateAndAct(
noDriverSideChanges: Boolean,
version: Int,
messageFromDriver: Boolean
) {
if (noDriverSideChanges) {
// TODO: use a single lock here, rather than two separate atomics.
this.state.value = State.Idle(idleDeferred, driver).also {
if (!stateChannel.isClosedForSend) stateChannel.send(it)
}
this.version.value = version
return
}
if (state.value is State.Closed<Data>) {
return
}
// Wait until we're idle before we continue, unless - of course - we've been waiting on
// driver model information, in which case - we can start without being idle.
if (state.value !is State.AwaitingDriverModel<Data>) {
// Await is called on the old value of idleDeferred.
idleDeferred.getAndSet(IdleDeferred()).await()
}
var currentState = state.value as State.StateWithData<Data>
var currentVersion = version
var spins = 0
do {
val localModel = synchronized(this) { localModel.data }
val (newVersion, newState) = currentState.update(
currentVersion,
messageFromDriver,
localModel
)
// TODO: use a lock instead here, rather than two separate atomics.
this.state.value = newState.also {
if (!stateChannel.isClosedForSend) stateChannel.send(it)
}
this.version.value = currentVersion
currentState = newState
currentVersion = newVersion
// Make sure we don't loop infinitely.
check(++spins < MAX_UPDATE_SPINS) {
"updateAndAct iterated too many times, limit: $MAX_UPDATE_SPINS"
}
} while (newState !is State.Idle<Data> && newState !is State.AwaitingDriverModel<Data>)
// Finish applying the models from the driver, if we have any.
val models = pendingDriverModels.getAndSet(emptyList())
if (models.isNotEmpty()) {
applyPendingDriverModels(models)
}
}
private data class PendingDriverModel<Data : CrdtData>(val model: Data, val version: Int)
private suspend fun IdleDeferred(): CompletableDeferred<Unit> =
CompletableDeferred(coroutineContext[Job.Key])
private sealed class State<Data : CrdtData>(val stateName: Name) {
/** Simple names for each [State]. */
enum class Name { Idle, AwaitingResponse, AwaitingDriverModel, Closed }
open class StateWithData<Data : CrdtData>(
stateName: Name,
val idleDeferred: AtomicRef<IdleDeferred>,
val driver: Driver<Data>
) : State<Data>(stateName) {
/** Waits until the [idleDeferred] signal is triggered. */
open suspend fun idle() = idleDeferred.value.await()
/**
* Determines the next state and version of the model while acting. (e.g. sending the
* [localModel] to the [Driver])
*
* Core component of the state machine, called by [DirectStore.updateStateAndAct] to
* determine what state to transition into and perform any necessary operations.
*/
open suspend fun update(
version: Int,
messageFromDriver: Boolean,
localModel: Data
): Pair<Int, StateWithData<Data>> = version to this
/**
* Returns whether or not, given the machine being in this state, we should apply any
* pending driver models to the local model.
*/
open fun shouldApplyPendingDriverModelsOnReceive(data: Data, version: Int): Boolean =
true
}
/**
* Indicates that the current conflated Channel is closed, dropping any held objects in the
* channel.
*/
class Closed<Data : CrdtData> : State<Data>(Name.Closed)
/**
* The [DirectStore] is currently idle.
*/
class Idle<Data : CrdtData>(
idleDeferred: AtomicRef<IdleDeferred>,
driver: Driver<Data>
) : StateWithData<Data>(Idle, idleDeferred, driver) {
init {
// When a new idle state is created, complete the deferred so anything waiting on it
// will unblock.
idleDeferred.value.complete(Unit)
}
// We're already in idle state, so no need to do anything.
override suspend fun idle() = Unit
override suspend fun update(
version: Int,
messageFromDriver: Boolean,
localModel: Data
): Pair<Int, StateWithData<Data>> {
// On update() and when idle, we're ready to await the next version.
return (version + 1) to AwaitingResponse(idleDeferred, driver)
}
}
/**
* On update: sends the local model to the driver and awaits a response.
*/
class AwaitingResponse<Data : CrdtData>(
idleDeferred: AtomicRef<IdleDeferred>,
driver: Driver<Data>
) : StateWithData<Data>(AwaitingResponse, idleDeferred, driver) {
override fun shouldApplyPendingDriverModelsOnReceive(data: Data, version: Int) = false
override suspend fun update(
version: Int,
messageFromDriver: Boolean,
localModel: Data
): Pair<Int, StateWithData<Data>> {
val response = driver.send(localModel, version)
return if (response) {
// The driver ack'd our send, we can move to idle state.
version to Idle(idleDeferred, driver)
} else {
// The driver didn't ack, so we need to move to AwaitingDriverModel.
version to AwaitingDriverModel(idleDeferred, driver)
}
}
}
/**
* Awaiting a model from the driver after a failed send.
*/
class AwaitingDriverModel<Data : CrdtData>(
idleDeferred: AtomicRef<IdleDeferred>,
driver: Driver<Data>
) : StateWithData<Data>(AwaitingDriverModel, idleDeferred, driver) {
override suspend fun update(
version: Int,
messageFromDriver: Boolean,
localModel: Data
): Pair<Int, StateWithData<Data>> {
// If the message didn't come from the driver, we can't do anything.
if (!messageFromDriver) return version to this
// This loop implements:
// sending -> AwaitingResponse -> AwaitingResponseDirty -> sending.
// Breakouts happen if:
// (1) a response arrives while still AwaitingResponse. This returns the store to
// Idle.
// (2) a negative response arrives. This means we're now waiting for driver models
// (AwaitingDriverModel). Note that in this case we are likely to end up back
// in this loop when a driver model arrives.
return (version + 1) to AwaitingResponse(idleDeferred, driver)
}
}
override fun toString(): String = "$stateName"
}
companion object {
/**
* To avoid an infinite loop OMG situation, set a maximum number of update spins for the
* state machine to something large, but not *infinite*.
*/
private const val MAX_UPDATE_SPINS = 1000
@Suppress("UNCHECKED_CAST")
suspend fun <Data : CrdtData, Op : CrdtOperation, T> create(
options: StoreOptions,
scope: CoroutineScope,
driverFactory: DriverFactory,
writeBackProvider: WriteBackProvider,
devTools: DevToolsForStorage?
): DirectStore<Data, Op, T> {
val crdtType = requireNotNull(options.type as CrdtModelType<Data, Op, T>) {
"Type not supported: ${options.type}"
}
val driver = CrdtException.requireNotNull(
driverFactory.getDriver(
options.storageKey,
crdtType.crdtModelDataClass,
options.type
) as? Driver<Data>
) { "No driver exists to support storage key ${options.storageKey}" }
return DirectStore(
options,
scope,
writeBack = writeBackProvider(options.storageKey.protocol),
localModel = crdtType.createCrdtModel(),
driver = driver,
devTools = devTools?.forDirectStore(options)
).also { store ->
driver.registerReceiver(options.versionToken) { data, version ->
store.onReceive(data, version)
}
}
}
}
}
private typealias IdleDeferred = CompletableDeferred<Unit>
| bsd-3-clause | d817c2e676e9b64f68fce9e2a181f08f | 34.23475 | 98 | 0.664935 | 4.385093 | false | false | false | false |
blindpirate/gradle | .teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedback.kt | 1 | 1310 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package promotion
import common.VersionedSettingsBranch
import vcsroots.gradlePromotionBranches
class PublishNightlySnapshotFromQuickFeedback(branch: VersionedSettingsBranch) : PublishGradleDistributionBothSteps(
promotedBranch = branch.branchName,
prepTask = branch.prepNightlyTaskName(),
step2TargetTask = branch.promoteNightlyTaskName(),
triggerName = "QuickFeedback",
vcsRootId = gradlePromotionBranches
) {
init {
id("Promotion_SnapshotFromQuickFeedback")
name = "Nightly Snapshot (from QuickFeedback)"
description = "Promotes the latest successful changes on '${branch.branchName}' from Quick Feedback as a new nightly snapshot"
}
}
| apache-2.0 | 48c4caf67e423ca76da8cdd69de6943b | 37.529412 | 134 | 0.754962 | 4.729242 | false | false | false | false |
Hexworks/zircon | zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/graphics/DefaultAnimationTest.kt | 1 | 1234 | package org.hexworks.zircon.internal.graphics
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.animation.AnimationResource
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.internal.resource.BuiltInCP437TilesetResource
import org.junit.Test
class DefaultAnimationTest {
@Test
fun shouldProperlyBuildFromResource() {
val builder = AnimationResource.loadAnimationFromStream(
zipStream = this.javaClass.getResourceAsStream("/animations/skull.zap"),
tileset = BuiltInCP437TilesetResource.BISASAM_16X16
)
(0 until EXPECTED_LENGTH).forEach { _ ->
builder.addPosition(Position.defaultPosition())
}
val result = builder.build()
assertThat(result.totalFrameCount).isEqualTo(EXPECTED_LENGTH)
assertThat(result.uniqueFrameCount).isEqualTo(EXPECTED_FRAME_COUNT)
assertThat(result.tick).isEqualTo(EXPECTED_TICK)
assertThat(result.loopCount).isEqualTo(EXPECTED_LOOP_COUNT)
}
companion object {
const val EXPECTED_FRAME_COUNT = 58
const val EXPECTED_LENGTH = 90
const val EXPECTED_TICK = 66L
const val EXPECTED_LOOP_COUNT = 1
}
}
| apache-2.0 | 5de3aea615bca29888db1aec630bf60d | 35.294118 | 84 | 0.71718 | 4.50365 | false | true | false | false |
npryce/robots | common/src/main/kotlin/robots/PList.kt | 1 | 1349 | package robots
sealed class PList<out T> : Iterable<T> {
abstract val head: T?
abstract val tail: PList<T>
override fun iterator(): Iterator<T> =
PListIterator(this)
override fun toString() =
joinToString(prefix = "[", separator = ", ", postfix = "]")
}
object Empty : PList<Nothing>() {
override val head get() = null
override val tail get() = this
override fun toString() = super.toString()
}
data class Cons<out T>(override val head: T, override val tail: PList<T>) : PList<T>() {
override fun toString() = super.toString()
}
fun PList<*>.isEmpty() = this == Empty
fun PList<*>.isNotEmpty() = !isEmpty()
fun emptyPList() = Empty
fun <T> pListOf(element: T) = Cons(element, Empty)
fun <T> pListOf(vararg elements: T) = elements.foldRight(Empty, ::Cons)
fun <T> PList<T>.notEmpty(): Cons<T>? = this as? Cons<T>
// A short cut for this.notEmpty()?.let { cons -> ... }
fun <T, U> PList<T>.notEmpty(f: (Cons<T>) -> U): U? {
return when (this) {
Empty -> null
is Cons<T> -> f(this)
}
}
private class PListIterator<out T>(private var current: PList<T>) : Iterator<T> {
override fun hasNext() =
current.isNotEmpty()
override fun next() =
(current.head ?: throw NoSuchElementException())
.also { current = current.tail }
}
| gpl-3.0 | 223fa4b79c719093afaa2672d832bf30 | 26.530612 | 88 | 0.607858 | 3.441327 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt | 1 | 3809 | // 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.roots
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.vfs.NonPhysicalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiCodeFragment
import com.intellij.psi.PsiFile
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.config.ALL_KOTLIN_RESOURCE_ROOT_TYPES
import org.jetbrains.kotlin.idea.util.KOTLIN_AWARE_SOURCE_ROOT_TYPES
fun getKotlinAwareDestinationSourceRoots(project: Project): List<VirtualFile> {
return ModuleManager.getInstance(project).modules.flatMap { it.collectKotlinAwareDestinationSourceRoots() }
}
fun Module.collectKotlinAwareDestinationSourceRoots(): List<VirtualFile> {
return rootManager
.contentEntries
.asSequence()
.flatMap { it.getSourceFolders(KOTLIN_AWARE_SOURCE_ROOT_TYPES).asSequence() }
.filterNot { isForGeneratedSources(it) }
.mapNotNull { it.file }
.toList()
}
fun isOutsideSourceRootSet(psiFile: PsiFile?, sourceRootTypes: Set<JpsModuleSourceRootType<*>>): Boolean {
if (psiFile == null || psiFile is PsiCodeFragment) return false
val file = psiFile.virtualFile ?: return false
if (file.fileSystem is NonPhysicalFileSystem) return false
val projectFileIndex = ProjectRootManager.getInstance(psiFile.project).fileIndex
return !projectFileIndex.isUnderSourceRootOfType(file, sourceRootTypes) && !projectFileIndex.isInLibrary(file)
}
fun isOutsideKotlinAwareSourceRoot(psiFile: PsiFile?) = isOutsideSourceRootSet(psiFile, KOTLIN_AWARE_SOURCE_ROOT_TYPES)
/**
* @return list of all java source roots in the project which can be suggested as a target directory for a class created by user
*/
fun getSuitableDestinationSourceRoots(project: Project): List<VirtualFile> {
val roots = ArrayList<VirtualFile>()
for (module in ModuleManager.getInstance(project).modules) {
collectSuitableDestinationSourceRoots(module, roots)
}
return roots
}
fun getSuitableDestinationSourceRoots(module: Module): MutableList<VirtualFile> {
val roots = ArrayList<VirtualFile>()
collectSuitableDestinationSourceRoots(module, roots)
return roots
}
fun collectSuitableDestinationSourceRoots(module: Module, result: MutableList<VirtualFile>) {
for (entry in ModuleRootManager.getInstance(module).contentEntries) {
for (sourceFolder in entry.getSourceFolders(KOTLIN_AWARE_SOURCE_ROOT_TYPES)) {
if (!isForGeneratedSources(sourceFolder)) {
ContainerUtil.addIfNotNull(result, sourceFolder.file)
}
}
}
}
fun isForGeneratedSources(sourceFolder: SourceFolder): Boolean {
val properties = sourceFolder.jpsElement.getProperties(KOTLIN_AWARE_SOURCE_ROOT_TYPES)
val javaResourceProperties = sourceFolder.jpsElement.getProperties(JavaModuleSourceRootTypes.RESOURCES)
val kotlinResourceProperties = sourceFolder.jpsElement.getProperties(ALL_KOTLIN_RESOURCE_ROOT_TYPES)
return properties != null && properties.isForGeneratedSources
|| (javaResourceProperties != null && javaResourceProperties.isForGeneratedSources)
|| (kotlinResourceProperties != null && kotlinResourceProperties.isForGeneratedSources)
} | apache-2.0 | 3c7932231d60f878dde1b3378b307f10 | 46.625 | 158 | 0.783145 | 4.791195 | false | false | false | false |
apiok/ok-android-sdk | odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/OkWebViewClient.kt | 2 | 2132 | package ru.ok.android.sdk
import android.content.Context
import android.net.http.SslError
import android.view.View
import android.webkit.SslErrorHandler
import android.webkit.WebView
import android.webkit.WebViewClient
@Suppress("DEPRECATION", "OverridingDeprecatedMember")
internal open class OkWebViewClient(private val mContext: Context) : WebViewClient() {
protected var showPage = true
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
showPage = true
return super.shouldOverrideUrlLoading(view, url)
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
view.visibility = if (showPage) View.VISIBLE else View.INVISIBLE
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
showPage = false
super.onReceivedError(view, errorCode, description, failingUrl)
}
override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
showPage = false
super.onReceivedSslError(view, handler, error)
}
fun getErrorMessage(errorCode: Int): String = when (errorCode) {
ERROR_CONNECT -> getString(R.string.error_connect)
ERROR_FAILED_SSL_HANDSHAKE -> getString(R.string.error_failed_ssl_handshake)
ERROR_HOST_LOOKUP -> getString(R.string.error_host_lookup)
ERROR_TIMEOUT -> getString(R.string.error_timeout)
else -> getString(R.string.error_unknown)
}
fun getErrorMessage(error: SslError): String = when (error.primaryError) {
SslError.SSL_EXPIRED -> getString(R.string.error_ssl_expired)
SslError.SSL_IDMISMATCH -> getString(R.string.error_ssl_id_mismatch)
SslError.SSL_NOTYETVALID -> getString(R.string.error_ssl_not_yet_valid)
SslError.SSL_UNTRUSTED -> getString(R.string.error_ssl_untrusted)
SslError.SSL_DATE_INVALID -> getString(R.string.error_ssl_date_invalid)
else -> getString(R.string.error_unknown)
}
private fun getString(resId: Int): String = mContext.getString(resId)
}
| apache-2.0 | 796cc29ff7f996a6517092b0ebddd52d | 40 | 106 | 0.716698 | 4.14786 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/interactors/record/impl/SequenceRecordInteractor.kt | 1 | 3293 | package com.onyx.interactors.record.impl
import com.onyx.descriptor.EntityDescriptor
import com.onyx.diskmap.data.PutResult
import com.onyx.exception.OnyxException
import com.onyx.extension.*
import com.onyx.extension.common.ClassMetadata
import com.onyx.extension.common.castTo
import com.onyx.interactors.record.RecordInteractor
import com.onyx.lang.concurrent.impl.DefaultClosureLock
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.context.SchemaContext
import java.util.concurrent.atomic.AtomicLong
/**
* Created by timothy.osborn on 2/5/15.
*
* This implementation of the record controller will create a new sequence if the id was not defined
*/
class SequenceRecordInteractor(entityDescriptor: EntityDescriptor, context: SchemaContext) : DefaultRecordInteractor(entityDescriptor, context), RecordInteractor {
private val sequenceValue = AtomicLong(0)
private var metadata: MutableMap<Byte, Number>
private val sequenceLock = DefaultClosureLock()
init {
val dataFile = context.getDataFile(entityDescriptor)
metadata = dataFile.getHashMap(ClassMetadata.BYTE_TYPE, METADATA_MAP_NAME + entityDescriptor.entityClass.name)
// Initialize the sequence value
sequenceValue.set((metadata[LAST_SEQUENCE_VALUE]?:0L).toLong())
}
/**
* Save an entity
*
* @param entity Entity to save
* @return Pair of existing reference id and new identifier value
* @throws OnyxException Error saving entity
*
* @since 1.2.3 Added an optimization so it does not do a check if it exist before
* putting if there are no listeners for persist
* @since 2.0.0 Optimized to return the old reference value
*/
@Throws(OnyxException::class)
@Synchronized
override fun save(entity: IManagedEntity): PutResult {
autoIncrementSequence(entity)
return super.save(entity)
}
/**
* Automatically increment the identifier value if it is undefined. If it is, ensure the maximum sequence value
* is less than or equal to the id value so it skips unused sequences and does not mess up with the counting.
*
* @param entity Entity to determine identifier
* @since 2.0.0 Ensured this is compatible with any kind of number.
*/
private fun autoIncrementSequence(entity:IManagedEntity) {
var identifierValue:Number = entity.identifier(context) as Number? ?: 0L
sequenceLock.perform {
when {
identifierValue.toLong() == 0L -> {
identifierValue = sequenceValue.incrementAndGet().castTo(entityDescriptor.identifier!!.type) as Number
entity[context, entityDescriptor, entityDescriptor.identifier!!.name] = identifierValue
metadata.put(LAST_SEQUENCE_VALUE, identifierValue)
}
identifierValue.toLong() > sequenceValue.get() -> {
sequenceValue.set(identifierValue.toLong())
metadata.put(LAST_SEQUENCE_VALUE, identifierValue)
}
else -> {
}
}
}
}
companion object {
private const val LAST_SEQUENCE_VALUE = 1.toByte()
private const val METADATA_MAP_NAME = "_meta_"
}
}
| agpl-3.0 | ae62159bae502746913b76b790332216 | 39.158537 | 163 | 0.686608 | 4.625 | false | false | false | false |
moshbit/Kotlift | test-src/32_nullCoalescing.kt | 2 | 469 | fun main(args: Array<String>) {
try {
val x: Int? = 42
val y: Int? = null
val x1 = x ?: 0
val y1 = y ?: 0
val x2 = x ?: throw Exception("FAIL: Should never happen")
val y2 = y ?: throw Exception("SUCCESS: Should happen")
println("Fail")
} catch (e: Exception) {
println("Success")
}
val values: List<Int?> = arrayListOf(1, 2, null, null, 3, 4, null)
for (value in values) {
val a = value ?: continue
println(a)
}
}
| apache-2.0 | a80b31362431f3a2952ed0985a89a11d | 22.45 | 68 | 0.560768 | 3.190476 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/stats/sender/SenderComponent.kt | 2 | 2177 | /*
* 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.stats.sender
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.stats.experiment.WebServiceStatus
import com.intellij.util.Alarm
import com.intellij.util.Time
class SenderComponent(
private val sender: StatisticSender,
private val statusHelper: WebServiceStatus
) : ApplicationComponent {
private companion object {
val LOG = logger<SenderComponent>()
}
private val disposable = Disposer.newDisposable()
private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, disposable)
private val sendInterval = 5 * Time.MINUTE
private fun send() {
if (ApplicationManager.getApplication().isUnitTestMode) return
try {
ApplicationManager.getApplication().executeOnPooledThread {
statusHelper.updateStatus()
if (statusHelper.isServerOk()) {
val dataServerUrl = statusHelper.dataServerUrl()
sender.sendStatsData(dataServerUrl)
}
}
} catch (e: Exception) {
LOG.error(e.message)
} finally {
alarm.addRequest({ send() }, sendInterval)
}
}
override fun disposeComponent() {
Disposer.dispose(disposable)
}
override fun initComponent() {
ApplicationManager.getApplication().executeOnPooledThread {
send()
}
}
} | apache-2.0 | 5ddb4de39504a69c4e0a1120f54112ee | 32 | 75 | 0.685806 | 4.827051 | false | false | false | false |
cfieber/orca | orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/tasks/MonitorKayentaCanaryTask.kt | 1 | 4692 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.tasks
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.OverridableTimeoutRetryableTask
import com.netflix.spinnaker.orca.TaskResult
import com.netflix.spinnaker.orca.ext.mapTo
import com.netflix.spinnaker.orca.kayenta.CanaryResults
import com.netflix.spinnaker.orca.kayenta.KayentaService
import com.netflix.spinnaker.orca.kayenta.Thresholds
import com.netflix.spinnaker.orca.pipeline.model.Stage
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit.HOURS
@Component
class MonitorKayentaCanaryTask(
private val kayentaService: KayentaService
) : OverridableTimeoutRetryableTask {
override fun getBackoffPeriod() = 1000L
override fun getTimeout() = HOURS.toMillis(12)
data class MonitorKayentaCanaryContext(
val canaryPipelineExecutionId: String,
val storageAccountName: String?,
val metricsAccountName: String?,
val scoreThresholds: Thresholds
)
override fun execute(stage: Stage): TaskResult {
val context = stage.mapTo<MonitorKayentaCanaryContext>()
val canaryResults = kayentaService.getCanaryResults(context.storageAccountName, context.canaryPipelineExecutionId)
if (canaryResults.executionStatus == SUCCEEDED) {
val canaryScore = canaryResults.result!!.judgeResult.score.score
val warnings = getResultWarnings(context, canaryResults)
return if (canaryScore <= context.scoreThresholds.marginal) {
val resultStatus = if (stage.context["continuePipeline"] == true) FAILED_CONTINUE else TERMINAL
TaskResult(resultStatus, mapOf(
"canaryPipelineStatus" to SUCCEEDED,
"lastUpdated" to canaryResults.endTimeIso?.toEpochMilli(),
"lastUpdatedIso" to canaryResults.endTimeIso,
"durationString" to canaryResults.result.canaryDuration.toString(),
"canaryScore" to canaryScore,
"canaryScoreMessage" to "Canary score is not above the marginal score threshold.",
"warnings" to warnings
))
} else {
TaskResult(SUCCEEDED, mapOf(
"canaryPipelineStatus" to SUCCEEDED,
"lastUpdated" to canaryResults.endTimeIso?.toEpochMilli(),
"lastUpdatedIso" to canaryResults.endTimeIso,
"durationString" to canaryResults.result.canaryDuration.toString(),
"canaryScore" to canaryScore,
"warnings" to warnings
))
}
}
if (canaryResults.executionStatus.isHalt) {
val stageOutputs = mutableMapOf<String, Any>("canaryPipelineStatus" to canaryResults.executionStatus)
if (canaryResults.executionStatus == CANCELED) {
stageOutputs["exception"] = mapOf("details" to mapOf("errors" to listOf("Canary execution was canceled.")))
} else {
canaryResults.exception?.let { stageOutputs["exception"] = it }
}
// Indicates a failure of some sort.
return TaskResult(TERMINAL, stageOutputs)
}
return TaskResult(RUNNING, mapOf("canaryPipelineStatus" to canaryResults.executionStatus))
}
fun getResultWarnings(context: MonitorKayentaCanaryContext, canaryResults: CanaryResults): List<String> {
val warnings = mutableListOf<String>()
var credentialType = ""
if (context.metricsAccountName != null) {
val allCredentials = kayentaService.getCredentials()
val credential = allCredentials.find({ it.name == context.metricsAccountName })
credentialType = if (credential != null) {
credential.type
} else {
""
}
}
// Datadog doesn't return data points in the same way as other metrics providers
// and so are excluded here. See this Github comment for more information:
// https://github.com/spinnaker/kayenta/issues/283#issuecomment-397346975
if (credentialType != "datadog" && canaryResults.result!!.judgeResult.results.any({ it.controlMetadata.stats.count < 50 })) {
warnings.add("One of the metrics returned fewer than 50 data points, which can reduce confidence in the final canary score.")
}
return warnings
}
}
| apache-2.0 | a750567a2c554b6c1babc460de38d2d4 | 39.102564 | 131 | 0.727195 | 4.520231 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/opengl/OpenGLRenderer.kt | 1 | 119362 | package graphics.scenery.backends.opengl
import cleargl.*
import com.jogamp.nativewindow.WindowClosingProtocol
import com.jogamp.newt.event.WindowAdapter
import com.jogamp.newt.event.WindowEvent
import com.jogamp.opengl.*
import com.jogamp.opengl.util.Animator
import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil
import graphics.scenery.*
import graphics.scenery.backends.*
import graphics.scenery.geometry.GeometryType
import graphics.scenery.primitives.Plane
import graphics.scenery.attribute.HasDelegationType
import graphics.scenery.attribute.DelegationType
import graphics.scenery.attribute.geometry.Geometry
import graphics.scenery.attribute.material.Material
import graphics.scenery.attribute.renderable.Renderable
import graphics.scenery.spirvcrossj.Loader
import graphics.scenery.spirvcrossj.libspirvcrossj
import graphics.scenery.textures.Texture
import graphics.scenery.textures.Texture.BorderColor
import graphics.scenery.textures.Texture.RepeatMode
import graphics.scenery.textures.UpdatableTexture
import graphics.scenery.utils.*
import kotlinx.coroutines.*
import net.imglib2.type.numeric.NumericType
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.DoubleType
import net.imglib2.type.numeric.real.FloatType
import org.joml.*
import org.lwjgl.system.MemoryUtil
import org.lwjgl.system.Platform
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.image.DataBufferInt
import java.io.File
import java.io.FileOutputStream
import java.lang.Math
import java.lang.reflect.Field
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.IntBuffer
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
import javax.imageio.ImageIO
import javax.swing.BorderFactory
import kotlin.collections.LinkedHashMap
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
/**
* Deferred Lighting Renderer for scenery
*
* This is the main class of scenery's Deferred Lighting Renderer. Currently,
* a rendering strategy using a 32bit position, 16bit normal, 32bit RGBA diffuse/albedo,
* and 24bit depth buffer is employed. The renderer supports HDR rendering and does that
* by default. By deactivating the `hdr.Active` [Settings], HDR can be programmatically
* deactivated. The renderer also supports drawing to HMDs via OpenVR. If this is intended,
* make sure the `vr.Active` [Settings] is set to `true`, and that the `Hub` has a HMD
* instance attached.
*
* @param[hub] Hub instance to use and attach to.
* @param[applicationName] The name of this application.
* @param[scene] The [Scene] instance to initialize first.
* @param[width] Horizontal window size.
* @param[height] Vertical window size.
* @param[embedIn] An optional [SceneryPanel] in which to embed the renderer instance.
* @param[renderConfigFile] The file to create a [RenderConfigReader.RenderConfig] from.
*
* @author Ulrik Günther <[email protected]>
*/
@Suppress("MemberVisibilityCanBePrivate")
open class OpenGLRenderer(hub: Hub,
applicationName: String,
scene: Scene,
width: Int,
height: Int,
renderConfigFile: String,
final override var embedIn: SceneryPanel? = null,
var embedInDrawable: GLAutoDrawable? = null) : Renderer(), Hubable, ClearGLEventListener {
/** slf4j logger */
private val logger by LazyLogger()
private val className = this.javaClass.simpleName
/** [GL4] instance handed over, coming from [ClearGLDefaultEventListener]*/
private lateinit var gl: GL4
/** should the window close on next looping? */
@Volatile override var shouldClose = false
/** the scenery window */
final override var window: SceneryWindow = SceneryWindow.UninitializedWindow()
/** separately stored ClearGLWindow */
var cglWindow: ClearGLWindow? = null
/** drawble for offscreen rendering */
var drawable: GLAutoDrawable? = null
/** Whether the renderer manages its own event loop, which is the case for this one. */
override var managesRenderLoop = true
/** The currently active scene */
var scene: Scene = Scene()
/** Cache of [Node]s, needed e.g. for fullscreen quad rendering */
private var nodeStore = ConcurrentHashMap<String, Node>()
/** [Settings] for the renderer */
final override var settings: Settings = Settings()
/** The hub used for communication between the components */
final override var hub: Hub?
private var textureCache = HashMap<String, GLTexture>()
private var shaderPropertyCache = HashMap<Class<*>, List<Field>>()
private var uboCache = ConcurrentHashMap<String, OpenGLUBO>()
private var joglDrawable: GLAutoDrawable? = null
private var screenshotRequested = false
private var screenshotOverwriteExisting = false
private var screenshotFilename = ""
private var encoder: VideoEncoder? = null
private var recordMovie = false
private var movieFilename = ""
/**
* Activate or deactivate push-based rendering mode (render only on scene changes
* or input events). Push mode is activated if [pushMode] is true.
*/
override var pushMode: Boolean = false
private var updateLatch: CountDownLatch? = null
private var lastResizeTimer = Timer()
@Volatile private var mustRecreateFramebuffers = false
private var framebufferRecreateHook: () -> Unit = {}
private var gpuStats: GPUStats? = null
private var maxTextureUnits = 8
/** heartbeat timer */
private var heartbeatTimer = Timer()
override var lastFrameTime = System.nanoTime() * 1.0f
private var currentTime = System.nanoTime()
@Volatile override var initialized = false
override var firstImageReady: Boolean = false
protected set
protected var frames = 0L
var fps = 0
protected set
protected var framesPerSec = 0
val pboCount = 2
@Volatile private var pbos: IntArray = IntArray(pboCount) { 0 }
private var pboBuffers: Array<ByteBuffer?> = Array(pboCount) { null }
private var readIndex = 0
private var updateIndex = 1
private var renderCalled = false
private var renderConfig: RenderConfigReader.RenderConfig
final override var renderConfigFile = ""
set(config) {
field = config
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
mustRecreateFramebuffers = true
}
private var renderpasses = LinkedHashMap<String, OpenGLRenderpass>()
private var flow: List<String>
/**
* Extension function of Boolean to use Booleans in GLSL
*
* This function converts a Boolean to Int 0, if false, and to 1, if true
*/
fun Boolean.toInt(): Int {
return if (this) {
1
} else {
0
}
}
var applicationName = ""
inner class OpenGLResizeHandler: ResizeHandler {
@Volatile override var lastResize = -1L
override var lastWidth = 0
override var lastHeight = 0
@Synchronized override fun queryResize() {
if (lastWidth <= 0 || lastHeight <= 0) {
lastWidth = Math.max(1, lastWidth)
lastHeight = Math.max(1, lastHeight)
return
}
if (lastResize > 0L && lastResize + WINDOW_RESIZE_TIMEOUT < System.nanoTime()) {
lastResize = System.nanoTime()
return
}
if (lastWidth == window.width && lastHeight == window.height) {
return
}
mustRecreateFramebuffers = true
gl.glDeleteBuffers(pboCount, pbos, 0)
pbos = IntArray(pboCount) { 0 }
lastWidth = window.width
lastHeight = window.height
if(drawable is GLOffscreenAutoDrawable) {
(drawable as? GLOffscreenAutoDrawable)?.setSurfaceSize(window.width, window.height)
}
logger.debug("queryResize: $lastWidth/$lastHeight")
lastResize = -1L
}
}
/**
* OpenGL Buffer class, creates a buffer associated with the context [gl] and size [size] in bytes.
*
* @author Ulrik Guenther <[email protected]>
*/
class OpenGLBuffer(var gl: GL4, var size: Int) {
/** Temporary buffer for data before it is sent to the GPU. */
var buffer: ByteBuffer
private set
/** OpenGL id of the buffer. */
var id = intArrayOf(-1)
private set
/** Required buffer offset alignment for uniform buffers, determined from [GL4.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT] */
var alignment = 256L
private set
init {
val tmp = intArrayOf(0, 0)
gl.glGetIntegerv(GL4.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, tmp, 0)
alignment = tmp[0].toLong()
gl.glGenBuffers(1, id, 0)
buffer = MemoryUtil.memAlloc(maxOf(tmp[0], size))
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferData(GL4.GL_UNIFORM_BUFFER, size * 1L, null, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
}
/** Copies the [buffer] from main memory to GPU memory. */
fun copyFromStagingBuffer() {
buffer.flip()
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferSubData(GL4.GL_UNIFORM_BUFFER, 0, buffer.remaining() * 1L, buffer)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
}
/** Resets staging buffer position and limit */
fun reset() {
buffer.position(0)
buffer.limit(size)
}
/**
* Resizes the backing buffer to [newSize], which is 1.5x the original size by default,
* and returns the staging buffer.
*/
fun resize(newSize: Int = (buffer.capacity() * 1.5f).roundToInt()): ByteBuffer {
logger.debug("Resizing backing buffer of $this from ${buffer.capacity()} to $newSize")
// resize main memory-backed buffer
buffer = MemoryUtil.memRealloc(buffer, newSize) ?: throw IllegalStateException("Could not resize buffer")
size = buffer.capacity()
// resize OpenGL buffer as well
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferData(GL4.GL_UNIFORM_BUFFER, size * 1L, null, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
return buffer
}
/**
* Returns the [buffer]'s remaining bytes.
*/
fun remaining() = buffer.remaining()
/**
* Advances the backing buffer for population, aligning it by [alignment], or any given value
* that overrides it (not recommended), returns the buffers new position.
*/
fun advance(align: Long = this.alignment): Int {
val pos = buffer.position()
val rem = pos.rem(align)
if (rem != 0L) {
val newpos = pos + align.toInt() - rem.toInt()
buffer.position(newpos)
}
return buffer.position()
}
}
data class DefaultBuffers(var UBOs: OpenGLBuffer,
var LightParameters: OpenGLBuffer,
var ShaderParameters: OpenGLBuffer,
var VRParameters: OpenGLBuffer,
var ShaderProperties: OpenGLBuffer)
protected lateinit var buffers: DefaultBuffers
protected val sceneUBOs = CopyOnWriteArrayList<Node>()
protected val resizeHandler = OpenGLResizeHandler()
companion object {
private const val WINDOW_RESIZE_TIMEOUT = 200L
private const val MATERIAL_HAS_DIFFUSE = 0x0001
private const val MATERIAL_HAS_AMBIENT = 0x0002
private const val MATERIAL_HAS_SPECULAR = 0x0004
private const val MATERIAL_HAS_NORMAL = 0x0008
private const val MATERIAL_HAS_ALPHAMASK = 0x0010
init {
Loader.loadNatives()
libspirvcrossj.initializeProcess()
Runtime.getRuntime().addShutdownHook(object: Thread() {
override fun run() {
logger.debug("Finalizing libspirvcrossj")
libspirvcrossj.finalizeProcess()
}
})
}
}
/**
* Constructor for OpenGLRenderer, initialises geometry buffers
* according to eye configuration. Also initialises different rendering passes.
*
*/
init {
logger.info("Initializing OpenGL Renderer...")
this.hub = hub
this.settings = loadDefaultRendererSettings(hub.get(SceneryElement.Settings) as Settings)
this.window.width = width
this.window.height = height
this.renderConfigFile = renderConfigFile
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
this.flow = this.renderConfig.createRenderpassFlow()
logger.info("Loaded ${renderConfig.name} (${renderConfig.description ?: "no description"})")
this.scene = scene
this.applicationName = applicationName
val hmd = hub.getWorkingHMDDisplay()
if (settings.get("vr.Active") && hmd != null) {
this.window.width = hmd.getRenderTargetSize().x() * 2
this.window.height = hmd.getRenderTargetSize().y()
}
if (embedIn != null || embedInDrawable != null) {
if (embedIn != null && embedInDrawable == null) {
val profile = GLProfile.getMaxProgrammableCore(true)
if (!profile.isGL4) {
throw UnsupportedOperationException("Could not create OpenGL 4 context, perhaps you need a graphics driver update?")
}
val caps = GLCapabilities(profile)
caps.hardwareAccelerated = true
caps.doubleBuffered = true
caps.isOnscreen = false
caps.numSamples = 1
caps.isPBuffer = true
caps.redBits = 8
caps.greenBits = 8
caps.blueBits = 8
caps.alphaBits = 8
val panel = embedIn
/* maybe better?
var canvas: ClearGLWindow? = null
SwingUtilities.invokeAndWait {
canvas = ClearGLWindow("", width, height, this)
canvas!!.newtCanvasAWT.shallUseOffscreenLayer = true
panel.component = canvas!!.newtCanvasAWT
panel.layout = BorderLayout()
panel.add(canvas!!.newtCanvasAWT, BorderLayout.CENTER)
panel.preferredSize = Dimension(width, height)
val frame = SwingUtilities.getAncestorOfClass(JFrame::class.java, panel) as JFrame
frame.preferredSize = Dimension(width, height)
frame.layout = BorderLayout()
frame.pack()
frame.isVisible = true
}
canvas!!.glAutoDrawable
*/
drawable = if (panel is SceneryJPanel) {
val surfaceScale = hub.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f)
this.window.width = (panel.width * surfaceScale.x()).toInt()
this.window.height = (panel.height * surfaceScale.y()).toInt()
panel.panelWidth = this.window.width
panel.panelHeight = this.window.height
logger.debug("Surface scale: $surfaceScale")
val canvas = ClearGLWindow("",
this.window.width,
this.window.height, null)
canvas.newtCanvasAWT.shallUseOffscreenLayer = true
panel.component = canvas.newtCanvasAWT
panel.cglWindow = canvas
panel.layout = BorderLayout()
panel.preferredSize = Dimension(
(window.width * surfaceScale.x()).toInt(),
(window.height * surfaceScale.y()).toInt())
canvas.newtCanvasAWT.preferredSize = panel.preferredSize
panel.border = BorderFactory.createEmptyBorder()
panel.add(canvas.newtCanvasAWT, BorderLayout.CENTER)
cglWindow = canvas
canvas.glAutoDrawable
} else {
val factory = GLDrawableFactory.getFactory(profile)
factory.createOffscreenAutoDrawable(factory.defaultDevice, caps,
DefaultGLCapabilitiesChooser(), window.width, window.height)
}
} else {
drawable = embedInDrawable
}
drawable?.apply {
addGLEventListener(this@OpenGLRenderer)
animator = Animator()
animator.add(this)
animator.start()
embedInDrawable?.let { glAutoDrawable ->
window = SceneryWindow.JOGLDrawable(glAutoDrawable)
}
window.width = width
window.height = height
resizeHandler.lastWidth = window.width
resizeHandler.lastHeight = window.height
embedIn?.let { panel ->
panel.imageScaleY = -1.0f
window = panel.init(resizeHandler)
val surfaceScale = hub.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f)
window.width = (panel.panelWidth * surfaceScale.x()).toInt()
window.height = (panel.panelHeight * surfaceScale.y()).toInt()
}
resizeHandler.lastWidth = window.width
resizeHandler.lastHeight = window.height
}
} else {
val w = this.window.width
val h = this.window.height
// need to leak this here unfortunately
@Suppress("LeakingThis")
cglWindow = ClearGLWindow("",
w,
h, this,
false).apply {
if(embedIn == null) {
window = SceneryWindow.ClearGLWindow(this)
window.width = w
window.height = h
val windowAdapter = object: WindowAdapter() {
override fun windowDestroyNotify(e: WindowEvent?) {
logger.debug("Signalling close from window event")
e?.isConsumed = true
}
}
this.addWindowListener(windowAdapter)
this.setFPS(60)
this.start()
this.setDefaultCloseOperation(WindowClosingProtocol.WindowClosingMode.DISPOSE_ON_CLOSE)
this.isVisible = true
}
}
}
while(!initialized) {
Thread.sleep(20)
}
}
override fun init(pDrawable: GLAutoDrawable) {
this.gl = pDrawable.gl.gL4
val width = this.window.width
val height = this.window.height
gl.swapInterval = 0
val driverString = gl.glGetString(GL4.GL_RENDERER)
val driverVersion = gl.glGetString(GL4.GL_VERSION)
logger.info("OpenGLRenderer: $width x $height on $driverString, $driverVersion")
if (driverVersion.lowercase().indexOf("nvidia") != -1 && System.getProperty("os.name").lowercase().indexOf("windows") != -1) {
gpuStats = NvidiaGPUStats()
}
val tmp = IntArray(1)
gl.glGetIntegerv(GL4.GL_MAX_TEXTURE_IMAGE_UNITS, tmp, 0)
maxTextureUnits = tmp[0]
val numExtensionsBuffer = IntBuffer.allocate(1)
gl.glGetIntegerv(GL4.GL_NUM_EXTENSIONS, numExtensionsBuffer)
val extensions = (0 until numExtensionsBuffer[0]).map { gl.glGetStringi(GL4.GL_EXTENSIONS, it) }
logger.debug("Available OpenGL extensions: ${extensions.joinToString(", ")}")
settings.set("ssao.FilterRadius", Vector2f(5.0f / width, 5.0f / height))
buffers = DefaultBuffers(
UBOs = OpenGLBuffer(gl, 10 * 1024 * 1024),
LightParameters = OpenGLBuffer(gl, 10 * 1024 * 1024),
VRParameters = OpenGLBuffer(gl, 2 * 1024),
ShaderProperties = OpenGLBuffer(gl, 10 * 1024 * 1024),
ShaderParameters = OpenGLBuffer(gl, 128 * 1024))
prepareDefaultTextures()
renderpasses = prepareRenderpasses(renderConfig, window.width, window.height)
// enable required features
// gl.glEnable(GL4.GL_TEXTURE_GATHER)
gl.glEnable(GL4.GL_PROGRAM_POINT_SIZE)
heartbeatTimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
fps = framesPerSec
framesPerSec = 0
if(!pushMode) {
(hub?.get(SceneryElement.Statistics) as? Statistics)?.add("Renderer.fps", fps, false)
}
gpuStats?.let {
it.update(0)
hub?.get(SceneryElement.Statistics).let { s ->
val stats = s as Statistics
stats.add("GPU", it.get("GPU"), isTime = false)
stats.add("GPU bus", it.get("Bus"), isTime = false)
stats.add("GPU mem", it.get("AvailableDedicatedVideoMemory"), isTime = false)
}
if (settings.get("Renderer.PrintGPUStats")) {
logger.info(it.utilisationToString())
logger.info(it.memoryUtilisationToString())
}
}
}
}, 0, 1000)
initialized = true
}
private fun Renderable.rendererMetadata(): OpenGLObjectState? {
return this.metadata["OpenGLRenderer"] as? OpenGLObjectState
}
private fun getSupersamplingFactor(window: ClearGLWindow?): Float {
val supersamplingFactor = if(settings.get<Float>("Renderer.SupersamplingFactor").toInt() == 1) {
if(window != null && ClearGLWindow.isRetina(window.gl)) {
logger.debug("Setting Renderer.SupersamplingFactor to 0.5, as we are rendering on a retina display.")
settings.set("Renderer.SupersamplingFactor", 0.5f)
0.5f
} else {
settings.get("Renderer.SupersamplingFactor")
}
} else {
settings.get("Renderer.SupersamplingFactor")
}
return supersamplingFactor
}
fun prepareRenderpasses(config: RenderConfigReader.RenderConfig, windowWidth: Int, windowHeight: Int): LinkedHashMap<String, OpenGLRenderpass> {
if(config.sRGB) {
gl.glEnable(GL4.GL_FRAMEBUFFER_SRGB)
} else {
gl.glDisable(GL4.GL_FRAMEBUFFER_SRGB)
}
buffers.ShaderParameters.reset()
val framebuffers = ConcurrentHashMap<String, GLFramebuffer>()
val passes = LinkedHashMap<String, OpenGLRenderpass>()
val flow = renderConfig.createRenderpassFlow()
val supersamplingFactor = getSupersamplingFactor(cglWindow)
scene.findObserver()?.let { cam ->
when(cam.projectionType) {
Camera.ProjectionType.Perspective -> cam.perspectiveCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
Camera.ProjectionType.Orthographic -> cam.orthographicCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
Camera.ProjectionType.Undefined -> {
logger.warn("Camera ${cam.name} has undefined projection type, using default perspective projection")
cam.perspectiveCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
}
}
}
settings.set("Renderer.displayWidth", (windowWidth * supersamplingFactor).toInt())
settings.set("Renderer.displayHeight", (windowHeight * supersamplingFactor).toInt())
flow.map { passName ->
val passConfig = config.renderpasses.getValue(passName)
val pass = OpenGLRenderpass(passName, passConfig)
var width = windowWidth
var height = windowHeight
config.rendertargets.filter { it.key == passConfig.output.name }.map { rt ->
width = (supersamplingFactor * windowWidth * rt.value.size.first).toInt()
height = (supersamplingFactor * windowHeight * rt.value.size.second).toInt()
logger.info("Creating render framebuffer ${rt.key} for pass $passName (${width}x$height)")
settings.set("Renderer.$passName.displayWidth", width)
settings.set("Renderer.$passName.displayHeight", height)
if (framebuffers.containsKey(rt.key)) {
logger.info("Reusing already created framebuffer")
pass.output.put(rt.key, framebuffers.getValue(rt.key))
} else {
val framebuffer = GLFramebuffer(gl, width, height, renderConfig.sRGB)
rt.value.attachments.forEach { att ->
logger.info(" + attachment ${att.key}, ${att.value.name}")
when (att.value) {
RenderConfigReader.TargetFormat.RGBA_Float32 -> framebuffer.addFloatRGBABuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RGBA_Float16 -> framebuffer.addFloatRGBABuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGB_Float32 -> framebuffer.addFloatRGBBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RGB_Float16 -> framebuffer.addFloatRGBBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RG_Float32 -> framebuffer.addFloatRGBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RG_Float16 -> framebuffer.addFloatRGBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.R_Float16 -> framebuffer.addFloatRBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGBA_UInt16 -> framebuffer.addUnsignedByteRGBABuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGBA_UInt8 -> framebuffer.addUnsignedByteRGBABuffer(gl, att.key, 8)
RenderConfigReader.TargetFormat.R_UInt16 -> framebuffer.addUnsignedByteRBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.R_UInt8 -> framebuffer.addUnsignedByteRBuffer(gl, att.key, 8)
RenderConfigReader.TargetFormat.Depth32 -> framebuffer.addDepthBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.Depth24 -> framebuffer.addDepthBuffer(gl, att.key, 24)
}
}
pass.output[rt.key] = framebuffer
framebuffers.put(rt.key, framebuffer)
}
}
if(passConfig.output.name == "Viewport") {
width = (supersamplingFactor * windowWidth).toInt()
height = (supersamplingFactor * windowHeight).toInt()
logger.info("Creating render framebuffer Viewport for pass $passName (${width}x$height)")
settings.set("Renderer.$passName.displayWidth", width)
settings.set("Renderer.$passName.displayHeight", height)
val framebuffer = GLFramebuffer(gl, width, height)
framebuffer.addUnsignedByteRGBABuffer(gl, "Viewport", 8)
pass.output["Viewport"] = framebuffer
framebuffers["Viewport"] = framebuffer
}
pass.openglMetadata.renderArea = OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt())
logger.debug("Render area for $passName: ${pass.openglMetadata.renderArea.width}x${pass.openglMetadata.renderArea.height}")
pass.openglMetadata.viewport = OpenGLRenderpass.Viewport(OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt()),
0.0f, 1.0f)
pass.openglMetadata.scissor = OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt())
pass.openglMetadata.eye = pass.passConfig.eye
pass.defaultShader = prepareShaderProgram(
Shaders.ShadersFromFiles(pass.passConfig.shaders.map { "shaders/$it" }.toTypedArray()))
pass.initializeShaderParameters(settings, buffers.ShaderParameters)
passes.put(passName, pass)
}
// connect inputs
passes.forEach { pass ->
val passConfig = config.renderpasses.getValue(pass.key)
passConfig.inputs?.forEach { inputTarget ->
val targetName = if(inputTarget.name.contains(".")) {
inputTarget.name.substringBefore(".")
} else {
inputTarget.name
}
passes.filter {
it.value.output.keys.contains(targetName)
}.forEach {
val output = it.value.output[targetName] ?: throw IllegalStateException("Output for $targetName not found in configuration")
pass.value.inputs[inputTarget.name] = output
}
}
with(pass.value) {
// initialize pass if needed
}
}
return passes
}
protected fun prepareShaderProgram(shaders: Shaders): OpenGLShaderProgram? {
val modules = HashMap<ShaderType, OpenGLShaderModule>()
ShaderType.values().forEach { type ->
try {
val m = OpenGLShaderModule.getFromCacheOrCreate(gl, "main", shaders.get(Shaders.ShaderTarget.OpenGL, type))
modules[m.shaderType] = m
} catch (e: ShaderNotFoundException) {
if(shaders is Shaders.ShadersFromFiles) {
logger.debug("Could not locate shader for $shaders, type=$type, ${shaders.shaders.joinToString(",")} - this is normal if there are no errors reported")
} else {
logger.debug("Could not locate shader for $shaders, type=$type - this is normal if there are no errors reported")
}
}
}
val program = OpenGLShaderProgram(gl, modules)
return if(program.isValid()) {
program
} else {
null
}
}
override fun display(pDrawable: GLAutoDrawable) {
val fps = pDrawable.animator?.lastFPS ?: 0.0f
if(embedIn == null) {
window.title = "$applicationName [${[email protected]}] - ${fps.toInt()} fps"
}
this.joglDrawable = pDrawable
if (mustRecreateFramebuffers) {
logger.info("Recreating framebuffers (${window.width}x${window.height})")
// FIXME: This needs to be done here in order to be able to run on HiDPI screens correctly
// FIXME: On macOS, this _must_ not be called, otherwise JOGL bails out, on Windows, it needs to be called.
if(embedIn != null && Platform.get() != Platform.MACOSX) {
cglWindow?.newtCanvasAWT?.setBounds(0, 0, window.width, window.height)
}
renderpasses = prepareRenderpasses(renderConfig, window.width, window.height)
flow = renderConfig.createRenderpassFlow()
framebufferRecreateHook.invoke()
frames = 0
mustRecreateFramebuffers = false
}
[email protected]()
}
override fun setClearGLWindow(pClearGLWindow: ClearGLWindow) {
cglWindow = pClearGLWindow
}
override fun getClearGLWindow(): ClearGLDisplayable {
return cglWindow ?: throw IllegalStateException("No ClearGL window available")
}
override fun reshape(pDrawable: GLAutoDrawable,
pX: Int,
pY: Int,
pWidth: Int,
pHeight: Int) {
var height = pHeight
if (height == 0)
height = 1
[email protected](pWidth, height)
}
override fun dispose(pDrawable: GLAutoDrawable) {
initialized = false
try {
scene.discover(scene, { _ -> true }).forEach {
destroyNode(it, onShutdown = true)
}
// The hub might contain elements that are both in the scene graph,
// and in the hub, e.g. a VolumeManager. We clean them here as well.
hub?.find { it is Node }?.forEach { (_, node) ->
(node as? Node)?.let { destroyNode(it, onShutdown = true) }
}
scene.initialized = false
if(cglWindow != null) {
logger.debug("Closing window")
joglDrawable?.animator?.stop()
} else {
logger.debug("Closing drawable")
joglDrawable?.animator?.stop()
}
} catch(e: ThreadDeath) {
logger.debug("Caught JOGL ThreadDeath, ignoring.")
}
}
/**
* Based on the [GLFramebuffer], devises a texture unit that can be used
* for object textures.
*
* @param[type] texture type
* @return Int of the texture unit to be used
*/
fun textureTypeToUnit(target: OpenGLRenderpass, type: String): Int {
val offset = if (target.inputs.values.isNotEmpty()) {
target.inputs.values.sumOf { it.boundBufferNum }
} else {
0
}
return offset + when (type) {
"ambient" -> 0
"diffuse" -> 1
"specular" -> 2
"normal" -> 3
"alphamask" -> 4
"displacement" -> 5
"3D-volume" -> 6
else -> {
logger.warn("Unknown ObjecTextures type $type")
0
}
}
}
private fun textureTypeToArrayName(type: String): String {
return when (type) {
"ambient" -> "ObjectTextures[0]"
"diffuse" -> "ObjectTextures[1]"
"specular" -> "ObjectTextures[2]"
"normal" -> "ObjectTextures[3]"
"alphamask" -> "ObjectTextures[4]"
"displacement" -> "ObjectTextures[5]"
"3D-volume" -> "VolumeTextures"
else -> {
logger.debug("Unknown texture type $type")
type
}
}
}
/**
* Converts a [GeometryType] to an OpenGL geometry type
*
* @return Int of the OpenGL geometry type.
*/
private fun GeometryType.toOpenGLType(): Int {
return when (this) {
GeometryType.TRIANGLE_STRIP -> GL4.GL_TRIANGLE_STRIP
GeometryType.POLYGON -> GL4.GL_TRIANGLES
GeometryType.TRIANGLES -> GL4.GL_TRIANGLES
GeometryType.TRIANGLE_FAN -> GL4.GL_TRIANGLE_FAN
GeometryType.POINTS -> GL4.GL_POINTS
GeometryType.LINE -> GL4.GL_LINE_STRIP
GeometryType.LINES_ADJACENCY -> GL4.GL_LINES_ADJACENCY
GeometryType.LINE_STRIP_ADJACENCY -> GL4.GL_LINE_STRIP_ADJACENCY
}
}
fun Int.toggle(): Int {
if (this == 0) {
return 1
} else if (this == 1) {
return 0
}
logger.warn("Property is not togglable.")
return this
}
/**
* Toggles deferred shading buffer debug view. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand]
*/
@Suppress("UNUSED")
fun toggleDebug() {
settings.getAllSettings().forEach {
if (it.lowercase().contains("debug")) {
try {
val property = settings.get<Int>(it).toggle()
settings.set(it, property)
} catch(e: Exception) {
logger.warn("$it is a property that is not togglable.")
}
}
}
}
/**
* Toggles Screen-space ambient occlusion. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun toggleSSAO() {
if (!settings.get<Boolean>("ssao.Active")) {
settings.set("ssao.Active", true)
} else {
settings.set("ssao.Active", false)
}
}
/**
* Toggles HDR rendering. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun toggleHDR() {
if (!settings.get<Boolean>("hdr.Active")) {
settings.set("hdr.Active", true)
} else {
settings.set("hdr.Active", false)
}
}
/**
* Increases the HDR exposure value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun increaseExposure() {
val exp: Float = settings.get("hdr.Exposure")
settings.set("hdr.Exposure", exp + 0.05f)
}
/**
* Decreases the HDR exposure value.Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun decreaseExposure() {
val exp: Float = settings.get("hdr.Exposure")
settings.set("hdr.Exposure", exp - 0.05f)
}
/**
* Increases the HDR gamma value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun increaseGamma() {
val gamma: Float = settings.get("hdr.Gamma")
settings.set("hdr.Gamma", gamma + 0.05f)
}
/**
* Decreases the HDR gamma value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun decreaseGamma() {
val gamma: Float = settings.get("hdr.Gamma")
if (gamma - 0.05f >= 0) settings.set("hdr.Gamma", gamma - 0.05f)
}
/**
* Toggles fullscreen. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun toggleFullscreen() {
if (!settings.get<Boolean>("wantsFullscreen")) {
settings.set("wantsFullscreen", true)
} else {
settings.set("wantsFullscreen", false)
}
}
/**
* Convenience function that extracts the [OpenGLObjectState] from a [Node]'s
* metadata.
*
* @param[renderable] The node of interest
* @return The [OpenGLObjectState] of the [Renderable]
*/
fun getOpenGLObjectStateFromNode(renderable: Renderable): OpenGLObjectState {
return renderable.metadata["OpenGLRenderer"] as OpenGLObjectState
}
/**
* Initializes the [Scene] with the [OpenGLRenderer], to be called
* before [render].
*/
@Synchronized override fun initializeScene() {
scene.discover(scene, { it.geometryOrNull() != null })
.forEach { node ->
val renderable = node.renderableOrNull()
if(renderable != null) renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(node)
}
scene.initialized = true
logger.info("Initialized ${textureCache.size} textures")
}
@Suppress("UNUSED_VALUE")
@Synchronized protected fun updateDefaultUBOs(cam: Camera): Boolean {
// sticky boolean
var updated: Boolean by StickyBoolean(initial = false)
val hmd = hub?.getWorkingHMDDisplay()?.wantsVR(settings)
val camSpatial = cam.spatial()
camSpatial.view = camSpatial.getTransformation()
buffers.VRParameters.reset()
val vrUbo = uboCache.computeIfAbsent("VRParameters") {
OpenGLUBO(backingBuffer = buffers.VRParameters)
}
vrUbo.add("projection0", {
(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection)
})
vrUbo.add("projection1", {
(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection)
})
vrUbo.add("inverseProjection0", {
Matrix4f(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).invert()
})
vrUbo.add("inverseProjection1", {
Matrix4f(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).invert()
})
vrUbo.add("headShift", { hmd?.getHeadToEyeTransform(0) ?: Matrix4f().identity() })
vrUbo.add("IPD", { hmd?.getIPD() ?: 0.05f })
vrUbo.add("stereoEnabled", { renderConfig.stereoEnabled.toInt() })
updated = vrUbo.populate()
buffers.VRParameters.copyFromStagingBuffer()
buffers.UBOs.reset()
buffers.ShaderProperties.reset()
sceneUBOs.forEach { node ->
var nodeUpdated: Boolean by StickyBoolean(initial = false)
val renderable = node.renderableOrNull() ?: return@forEach
val material = node.materialOrNull() ?: return@forEach
val spatial = node.spatialOrNull()
if (!renderable.metadata.containsKey(className)) {
return@forEach
}
val s = renderable.metadata[className] as? OpenGLObjectState
if(s == null) {
logger.warn("Could not get OpenGLObjectState for ${node.name}")
return@forEach
}
val ubo = s.UBOs["Matrices"]
if(ubo?.backingBuffer == null) {
logger.warn("Matrices UBO for ${node.name} does not exist or does not have a backing buffer")
return@forEach
}
preDrawAndUpdateGeometryForNode(node)
var bufferOffset = ubo.advanceBackingBuffer()
ubo.offset = bufferOffset
spatial?.view?.set(camSpatial.view)
nodeUpdated = ubo.populate(offset = bufferOffset.toLong())
val materialUbo = (renderable.metadata["OpenGLRenderer"]!! as OpenGLObjectState).UBOs.getValue("MaterialProperties")
bufferOffset = ubo.advanceBackingBuffer()
materialUbo.offset = bufferOffset
nodeUpdated = materialUbo.populate(offset = bufferOffset.toLong())
if (s.UBOs.containsKey("ShaderProperties")) {
val propertyUbo = s.UBOs.getValue("ShaderProperties")
// TODO: Correct buffer advancement
val offset = propertyUbo.backingBuffer!!.advance()
updated = propertyUbo.populate(offset = offset.toLong())
propertyUbo.offset = offset
}
nodeUpdated = loadTexturesForNode(node, s)
nodeUpdated = if(material.materialHashCode() != s.materialHash) {
s.initialized = false
initializeNode(node)
true
} else {
false
}
if(nodeUpdated && node.getScene()?.onNodePropertiesChanged?.isNotEmpty() == true) {
GlobalScope.launch { node.getScene()?.onNodePropertiesChanged?.forEach { it.value.invoke(node) } }
}
updated = nodeUpdated
}
buffers.UBOs.copyFromStagingBuffer()
buffers.LightParameters.reset()
// val lights = sceneObjects.filter { it is PointLight }
val lightUbo = uboCache.computeIfAbsent("LightParameters") {
OpenGLUBO(backingBuffer = buffers.LightParameters)
}
lightUbo.add("ViewMatrix0", { camSpatial.getTransformationForEye(0) })
lightUbo.add("ViewMatrix1", { camSpatial.getTransformationForEye(1) })
lightUbo.add("InverseViewMatrix0", { camSpatial.getTransformationForEye(0).invert() })
lightUbo.add("InverseViewMatrix1", { camSpatial.getTransformationForEye(1).invert() })
lightUbo.add("ProjectionMatrix", { camSpatial.projection })
lightUbo.add("InverseProjectionMatrix", { Matrix4f(camSpatial.projection).invert() })
lightUbo.add("CamPosition", { camSpatial.position })
// lightUbo.add("numLights", { lights.size })
// lights.forEachIndexed { i, light ->
// val l = light as PointLight
// l.updateWorld(true, false)
//
// lightUbo.add("Linear-$i", { l.linear })
// lightUbo.add("Quadratic-$i", { l.quadratic })
// lightUbo.add("Intensity-$i", { l.intensity })
// lightUbo.add("Radius-$i", { -l.linear + Math.sqrt(l.linear * l.linear - 4 * l.quadratic * (1.0 - (256.0f / 5.0) * 100)).toFloat() })
// lightUbo.add("Position-$i", { l.position })
// lightUbo.add("Color-$i", { l.emissionColor })
// lightUbo.add("filler-$i", { 0.0f })
// }
updated = lightUbo.populate()
buffers.ShaderParameters.reset()
renderpasses.forEach { name, pass ->
logger.trace("Updating shader parameters for {}", name)
updated = pass.updateShaderParameters()
}
buffers.ShaderParameters.copyFromStagingBuffer()
buffers.LightParameters.copyFromStagingBuffer()
buffers.ShaderProperties.copyFromStagingBuffer()
return updated
}
/**
* Update a [Node]'s geometry, if needed and run it's preDraw() routine.
*
* @param[node] The Node to update and preDraw()
*/
private fun preDrawAndUpdateGeometryForNode(node: Node) {
val renderable = node.renderableOrNull() ?: return
node.ifGeometry {
if (dirty) {
renderable.preUpdate(this@OpenGLRenderer, hub)
if (node.lock.tryLock()) {
if (vertices.remaining() > 0 && normals.remaining() > 0) {
updateVertices(getOpenGLObjectStateFromNode(renderable))
updateNormals(getOpenGLObjectStateFromNode(renderable))
}
if (texcoords.remaining() > 0) {
updateTextureCoords(getOpenGLObjectStateFromNode(renderable))
}
if (indices.remaining() > 0) {
updateIndices(getOpenGLObjectStateFromNode(renderable))
}
dirty = false
node.lock.unlock()
}
}
renderable.preDraw()
}
}
/**
* Set a [GLProgram]'s uniforms according to a [Node]'s [ShaderProperty]s.
*
* This functions uses reflection to query for a Node's declared fields and checks
* whether they are marked up with the [ShaderProperty] annotation. If this is the case,
* the [GLProgram]'s uniform with the same name as the field is set to its value.
*
* Currently limited to Vector3f, Matrix4f, Int and Float properties.
*
* @param[n] The Node to search for [ShaderProperty]s
* @param[program] The [GLProgram] used to render the Node
*/
@Suppress("unused")
private fun setShaderPropertiesForNode(n: Node, program: GLProgram) {
shaderPropertyCache
.getOrPut(n.javaClass) { n.javaClass.declaredFields.filter { it.isAnnotationPresent(ShaderProperty::class.java) } }
.forEach { property ->
property.isAccessible = true
val field = property.get(n)
when (property.type) {
Vector2f::class.java -> {
val v = field as Vector2f
program.getUniform(property.name).setFloatVector2(v.x, v.y)
}
Vector3f::class.java -> {
val v = field as Vector3f
program.getUniform(property.name).setFloatVector3(v.x, v.y, v.z)
}
Vector4f::class.java -> {
val v = field as Vector4f
program.getUniform(property.name).setFloatVector3(v.x, v.y, v.z, v.w)
}
Int::class.java -> {
program.getUniform(property.name).setInt(field as Int)
}
Float::class.java -> {
program.getUniform(property.name).setFloat(field as Float)
}
Matrix4f::class.java -> {
val m = field as Matrix4f
val array = FloatArray(16)
m.get(array)
program.getUniform(property.name).setFloatMatrix(array, false)
}
else -> {
logger.warn("Could not derive shader data type for @ShaderProperty ${n.javaClass.canonicalName}.${property.name} of type ${property.type}!")
}
}
}
}
private fun blitFramebuffers(source: GLFramebuffer?, target: GLFramebuffer?,
sourceOffset: OpenGLRenderpass.Rect2D,
targetOffset: OpenGLRenderpass.Rect2D,
colorOnly: Boolean = false, depthOnly: Boolean = false,
sourceName: String? = null) {
if (target != null) {
target.setDrawBuffers(gl)
} else {
gl.glBindFramebuffer(GL4.GL_DRAW_FRAMEBUFFER, 0)
}
if (source != null) {
if(sourceName != null) {
source.setReadBuffers(gl, sourceName)
} else {
source.setReadBuffers(gl)
}
} else {
gl.glBindFramebuffer(GL4.GL_READ_FRAMEBUFFER, 0)
}
val (blitColor, blitDepth) = when {
colorOnly && !depthOnly -> true to false
!colorOnly && depthOnly -> false to true
else -> true to true
}
if(blitColor) {
if (source?.hasColorAttachment() != false) {
gl.glBlitFramebuffer(
sourceOffset.offsetX, sourceOffset.offsetY,
sourceOffset.offsetX + sourceOffset.width, sourceOffset.offsetY + sourceOffset.height,
targetOffset.offsetX, targetOffset.offsetY,
targetOffset.offsetX + targetOffset.width, targetOffset.offsetY + targetOffset.height,
GL4.GL_COLOR_BUFFER_BIT, GL4.GL_LINEAR)
}
}
if(blitDepth) {
if ((source?.hasDepthAttachment() != false && target?.hasDepthAttachment() != false) || (depthOnly && !colorOnly)) {
gl.glBlitFramebuffer(
sourceOffset.offsetX, sourceOffset.offsetY,
sourceOffset.offsetX + sourceOffset.width, sourceOffset.offsetY + sourceOffset.height,
targetOffset.offsetX, targetOffset.offsetY,
targetOffset.offsetX + targetOffset.width, targetOffset.offsetY + targetOffset.height,
GL4.GL_DEPTH_BUFFER_BIT, GL4.GL_NEAREST)
} else {
logger.trace("Either source or target don't have a depth buffer. If blitting to window surface, this is not a problem.")
}
}
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0)
}
private fun updateInstanceBuffers(sceneObjects:List<Node>): Boolean {
val instanceMasters = sceneObjects.filter { it is InstancedNode }.map { it as InstancedNode }
instanceMasters.forEach { parent ->
val renderable = parent.renderableOrNull()
var metadata = renderable?.rendererMetadata()
if(metadata == null) {
if(renderable != null) renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(parent)
metadata = renderable?.rendererMetadata()
}
updateInstanceBuffer(parent, metadata)
}
return instanceMasters.isNotEmpty()
}
private fun updateInstanceBuffer(parentNode: InstancedNode, state: OpenGLObjectState?): OpenGLObjectState {
if(state == null) {
throw IllegalStateException("Metadata for ${parentNode.name} is null at updateInstanceBuffer(${parentNode.name}). This is a bug.")
}
// parentNode.instances is a CopyOnWrite array list, and here we keep a reference to the original.
// If it changes in the meantime, no problemo.
val instances = parentNode.instances
logger.trace("Updating instance buffer for ${parentNode.name}")
if (instances.isEmpty()) {
logger.debug("$parentNode has no child instances attached, returning.")
return state
}
val maxUpdates = parentNode.metadata["MaxInstanceUpdateCount"] as? AtomicInteger
if(maxUpdates?.get() ?: 1 < 1) {
logger.debug("Instances updates blocked for ${parentNode.name}, returning")
return state
}
// first we create a fake UBO to gauge the size of the needed properties
val ubo = OpenGLUBO()
ubo.fromInstance(instances.first())
val instanceBufferSize = ubo.getSize() * instances.size
val existingStagingBuffer = state.vertexBuffers["instanceStaging"]
val stagingBuffer = if(existingStagingBuffer != null
&& existingStagingBuffer.capacity() >= instanceBufferSize
&& existingStagingBuffer.capacity() < 1.5*instanceBufferSize) {
existingStagingBuffer
} else {
logger.debug("${parentNode.name}: Creating new staging buffer with capacity=$instanceBufferSize (${ubo.getSize()} x ${parentNode.instances.size})")
val buffer = BufferUtils.allocateByte((1.2 * instanceBufferSize).toInt())
state.vertexBuffers["instanceStaging"] = buffer
buffer
}
logger.trace("{}: Staging buffer position, {}, cap={}", parentNode.name, stagingBuffer.position(), stagingBuffer.capacity())
val index = AtomicInteger(0)
instances.parallelStream().forEach { node ->
if(node.visible) {
node.ifSpatial {
updateWorld(true, false)
}
stagingBuffer.duplicate().order(ByteOrder.LITTLE_ENDIAN).run {
ubo.populateParallel(this,
offset = index.getAndIncrement() * ubo.getSize() * 1L,
elements = node.instancedProperties)
}
}
}
stagingBuffer.position(stagingBuffer.limit())
stagingBuffer.flip()
val instanceBuffer = state.additionalBufferIds.getOrPut("instance") {
logger.debug("Instance buffer for ${parentNode.name} needs to be reallocated due to insufficient size ($instanceBufferSize vs ${state.vertexBuffers["instance"]?.capacity() ?: "<not allocated yet>"})")
val bufferArray = intArrayOf(0)
gl.glGenBuffers(1, bufferArray, 0)
gl.glBindVertexArray(state.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, bufferArray[0])
// instance data starts after vertex, normal, texcoord
val locationBase = 3
var location = locationBase
var baseOffset = 0L
val stride = parentNode.instances.first().instancedProperties.map {
val res = it.value.invoke()
ubo.getSizeAndAlignment(res).first
}.sum()
parentNode.instances.first().instancedProperties.entries.forEachIndexed { locationOffset, element ->
val result = element.value.invoke()
val sizeAlignment = ubo.getSizeAndAlignment(result)
location += locationOffset
val glType = when(result.javaClass) {
java.lang.Integer::class.java,
Int::class.java -> GL4.GL_INT
java.lang.Float::class.java,
Float::class.java -> GL4.GL_FLOAT
java.lang.Boolean::class.java,
Boolean::class.java -> GL4.GL_INT
Matrix4f::class.java -> GL4.GL_FLOAT
Vector3f::class.java -> GL4.GL_FLOAT
else -> { logger.error("Don't know how to serialise ${result.javaClass} for instancing."); GL4.GL_FLOAT }
}
val count = when (result) {
is Matrix4f -> 4
is Vector2f -> 2
is Vector3f -> 3
is Vector4f -> 4
is Vector2i -> 2
is Vector3i -> 3
is Vector4i -> 4
else -> { logger.error("Don't know element size of ${result.javaClass} for instancing."); 1 }
}
val necessaryAttributes = if(result is Matrix4f) {
4 * 4 / count
} else {
1
}
logger.trace("{} needs {} locations with {} elements:", result.javaClass, necessaryAttributes, count)
(0 until necessaryAttributes).forEach { attributeLocation ->
// val stride = sizeAlignment.first
val offset = baseOffset + 1L * attributeLocation * (sizeAlignment.first/necessaryAttributes)
logger.trace("{}, stride={}, offset={}",
location + attributeLocation,
stride,
offset)
gl.glEnableVertexAttribArray(location + attributeLocation)
// glVertexAttribPoint takes parameters:
// * index: attribute location
// * size: element count per location
// * type: the OpenGL type
// * normalized: whether the OpenGL type should be taken as normalized
// * stride: the stride between different occupants in the instance array
// * pointer_buffer_offset: the offset of the current element (e.g. matrix row) with respect
// to the start of the element in the instance array
gl.glVertexAttribPointer(location + attributeLocation, count, glType, false,
stride, offset)
gl.glVertexAttribDivisor(location + attributeLocation, 1)
if(attributeLocation == necessaryAttributes - 1) {
baseOffset += sizeAlignment.first
}
}
location += necessaryAttributes - 1
}
gl.glBindVertexArray(0)
state.additionalBufferIds["instance"] = bufferArray[0]
bufferArray[0]
}
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, instanceBuffer)
gl.glBufferData(GL4.GL_ARRAY_BUFFER, instanceBufferSize.toLong(), stagingBuffer, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
state.instanceCount = index.get()
logger.trace("Updated instance buffer, {parentNode.name} has {} instances.", parentNode.name, state.instanceCount)
maxUpdates?.decrementAndGet()
return state
}
protected fun destroyNode(node: Node, onShutdown: Boolean = false) {
node.ifRenderable {
this.metadata.remove("OpenGLRenderer")
val s = this.metadata["OpenGLRenderer"] as? OpenGLObjectState ?: return@ifRenderable
gl.glDeleteBuffers(s.mVertexBuffers.size, s.mVertexBuffers, 0)
gl.glDeleteBuffers(1, s.mIndexBuffer, 0)
s.additionalBufferIds.forEach { _, id ->
gl.glDeleteBuffers(1, intArrayOf(id), 0)
}
node.metadata.remove("OpenGLRenderer")
if(onShutdown) {
s.textures.forEach { (name, texture) ->
texture.delete()
}
}
initialized = false
}
}
protected var previousSceneObjects: HashSet<Node> = HashSet(256)
/**
* Renders the [Scene].
*
* The general rendering workflow works like this:
*
* 1) All visible elements of the Scene are gathered into the renderOrderList, based on their position
* 2) Nodes that are an instance of another Node, as indicated by their instanceOf property, are gathered
* into the instanceGroups map.
* 3) The eye-dependent geometry buffers are cleared, both color and depth buffers.
* 4) First for the non-instanced Nodes, then for the instanced Nodes the following steps are executed
* for each eye:
*
* i) The world state of the given Node is updated
* ii) Model, view, and model-view-projection matrices are calculated for each. If a HMD is present,
* the transformation coming from that is taken into account.
* iii) The Node's geometry is updated, if necessary.
* iv) The eye's geometry buffer is activated and the Node drawn into it.
*
* 5) The deferred shading pass is executed, together with eventual post-processing steps, such as SSAO.
* 6) If HDR is active, Exposure/Gamma tone mapping is performed. Else, this part is skipped.
* 7) The resulting image is drawn to the screen, or -- if a HMD is present -- submitted to the OpenVR
* compositor.
*/
override fun render(activeCamera: Camera, sceneNodes: List<Node>) {
currentObserver = activeCamera
currentSceneNodes = sceneNodes
renderCalled = true
}
var currentObserver: Camera? = null
var currentSceneNodes: List<Node> = emptyList()
@Synchronized fun renderInternal() = runBlocking {
if(!initialized || !renderCalled) {
return@runBlocking
}
if (scene.children.count() == 0 || !scene.initialized) {
initializeScene()
return@runBlocking
}
val newTime = System.nanoTime()
lastFrameTime = (System.nanoTime() - currentTime)/1e6f
currentTime = newTime
val stats = hub?.get(SceneryElement.Statistics) as? Statistics
if (shouldClose) {
initialized = false
return@runBlocking
}
val running = hub?.getApplication()?.running ?: true
embedIn?.let {
resizeHandler.queryResize()
}
if (scene.children.count() == 0 || renderpasses.isEmpty() || mustRecreateFramebuffers || !running) {
delay(200)
return@runBlocking
}
val cam = currentObserver ?: return@runBlocking
val sceneObjects = currentSceneNodes
val startUboUpdate = System.nanoTime()
val ubosUpdated = updateDefaultUBOs(cam)
stats?.add("OpenGLRenderer.updateUBOs", System.nanoTime() - startUboUpdate)
var sceneUpdated = true
if(pushMode) {
val actualSceneObjects = sceneObjects.toHashSet()
sceneUpdated = actualSceneObjects != previousSceneObjects
previousSceneObjects = actualSceneObjects
}
val startInstanceUpdate = System.nanoTime()
val instancesUpdated = updateInstanceBuffers(sceneObjects)
stats?.add("OpenGLRenderer.updateInstanceBuffers", System.nanoTime() - startInstanceUpdate)
// if(pushMode) {
// logger.info("Push mode: ubosUpdated={} sceneUpdated={} screenshotRequested={} instancesUpdated={}", ubosUpdated, sceneUpdated, screenshotRequested, instancesUpdated)
// }
if(pushMode && !ubosUpdated && !sceneUpdated && !screenshotRequested && !recordMovie && !instancesUpdated) {
if(updateLatch == null) {
updateLatch = CountDownLatch(4)
}
logger.trace("UBOs have not been updated, returning ({})", updateLatch?.count)
if(updateLatch?.count == 0L) {
// val animator = when {
// cglWindow != null -> cglWindow?.glAutoDrawable?.animator
// drawable != null -> drawable?.animator
// else -> null
// } as? FPSAnimator
//
// if(animator != null && animator.fps > 15) {
// animator.stop()
// animator.fps = 15
// animator.start()
// }
delay(15)
return@runBlocking
}
}
if(ubosUpdated || sceneUpdated || screenshotRequested || recordMovie) {
updateLatch = null
}
flow.forEach { t ->
if(logger.isDebugEnabled || logger.isTraceEnabled) {
val error = gl.glGetError()
if (error != 0) {
throw Exception("OpenGL error: $error")
}
}
val pass = renderpasses.getValue(t)
logger.trace("Running pass {}", pass.passName)
val startPass = System.nanoTime()
if (pass.passConfig.blitInputs) {
pass.inputs.forEach { name, input ->
val targetName = name.substringAfter(".")
if(name.contains(".") && input.getTextureType(targetName) == 0) {
logger.trace("Blitting {} into {} (color only)", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area, colorOnly = true, sourceName = name.substringAfter("."))
} else if(name.contains(".") && input.getTextureType(targetName) == 1) {
logger.trace("Blitting {} into {} (depth only)", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area, depthOnly = true)
} else {
logger.trace("Blitting {} into {}", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area)
}
}
}
if (pass.output.isNotEmpty()) {
pass.output.values.first().setDrawBuffers(gl)
} else {
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0)
}
// bind framebuffers to texture units and determine total number
pass.inputs.values.reversed().fold(0) { acc, fb -> acc + fb.bindTexturesToUnitsWithOffset(gl, acc) }
gl.glViewport(
pass.openglMetadata.viewport.area.offsetX,
pass.openglMetadata.viewport.area.offsetY,
pass.openglMetadata.viewport.area.width,
pass.openglMetadata.viewport.area.height)
gl.glScissor(
pass.openglMetadata.scissor.offsetX,
pass.openglMetadata.scissor.offsetY,
pass.openglMetadata.scissor.width,
pass.openglMetadata.scissor.height
)
gl.glEnable(GL4.GL_SCISSOR_TEST)
gl.glClearColor(
pass.openglMetadata.clearValues.clearColor.x(),
pass.openglMetadata.clearValues.clearColor.y(),
pass.openglMetadata.clearValues.clearColor.z(),
pass.openglMetadata.clearValues.clearColor.w())
if (!pass.passConfig.blitInputs) {
pass.output.values.forEach {
if (it.hasDepthAttachment()) {
gl.glClear(GL4.GL_DEPTH_BUFFER_BIT)
}
}
gl.glClear(GL4.GL_COLOR_BUFFER_BIT)
}
gl.glDisable(GL4.GL_SCISSOR_TEST)
gl.glDepthRange(
pass.openglMetadata.viewport.minDepth.toDouble(),
pass.openglMetadata.viewport.maxDepth.toDouble())
if (pass.passConfig.type == RenderConfigReader.RenderpassType.geometry ||
pass.passConfig.type == RenderConfigReader.RenderpassType.lights) {
gl.glEnable(GL4.GL_DEPTH_TEST)
gl.glEnable(GL4.GL_CULL_FACE)
if (pass.passConfig.renderTransparent) {
gl.glEnable(GL4.GL_BLEND)
gl.glBlendFuncSeparate(
pass.passConfig.srcColorBlendFactor.toOpenGL(),
pass.passConfig.dstColorBlendFactor.toOpenGL(),
pass.passConfig.srcAlphaBlendFactor.toOpenGL(),
pass.passConfig.dstAlphaBlendFactor.toOpenGL())
gl.glBlendEquationSeparate(
pass.passConfig.colorBlendOp.toOpenGL(),
pass.passConfig.alphaBlendOp.toOpenGL()
)
} else {
gl.glDisable(GL4.GL_BLEND)
}
val actualObjects = if(pass.passConfig.type == RenderConfigReader.RenderpassType.geometry) {
sceneObjects.filter { it !is Light }.toMutableList()
} else {
sceneObjects.filter { it is Light }.toMutableList()
}
actualObjects.sortBy { (it as? RenderingOrder)?.renderingOrder }
var currentShader: OpenGLShaderProgram? = null
val seenDelegates = ArrayList<Renderable>(5)
actualObjects.forEach renderLoop@ { node ->
val renderable = node.renderableOrNull() ?: return@renderLoop
val material = node.materialOrNull() ?: return@renderLoop
if(node is HasDelegationType && node.getDelegationType() == DelegationType.OncePerDelegate) {
if(seenDelegates.contains(renderable)) {
return@renderLoop
} else {
seenDelegates.add(renderable)
}
}
if (pass.passConfig.renderOpaque && material.blending.transparent && pass.passConfig.renderOpaque != pass.passConfig.renderTransparent) {
return@renderLoop
}
if (pass.passConfig.renderTransparent && !material.blending.transparent && pass.passConfig.renderOpaque != pass.passConfig.renderTransparent) {
return@renderLoop
}
gl.glEnable(GL4.GL_CULL_FACE)
when(material.cullingMode) {
Material.CullingMode.None -> gl.glDisable(GL4.GL_CULL_FACE)
Material.CullingMode.Front -> gl.glCullFace(GL4.GL_FRONT)
Material.CullingMode.Back -> gl.glCullFace(GL4.GL_BACK)
Material.CullingMode.FrontAndBack -> gl.glCullFace(GL4.GL_FRONT_AND_BACK)
}
val depthTest = when(material.depthTest) {
Material.DepthTest.Less -> GL4.GL_LESS
Material.DepthTest.Greater -> GL4.GL_GREATER
Material.DepthTest.LessEqual -> GL4.GL_LEQUAL
Material.DepthTest.GreaterEqual -> GL4.GL_GEQUAL
Material.DepthTest.Always -> GL4.GL_ALWAYS
Material.DepthTest.Never -> GL4.GL_NEVER
Material.DepthTest.Equal -> GL4.GL_EQUAL
}
gl.glDepthFunc(depthTest)
if(material.wireframe) {
gl.glPolygonMode(GL4.GL_FRONT_AND_BACK, GL4.GL_LINE)
} else {
gl.glPolygonMode(GL4.GL_FRONT_AND_BACK, GL4.GL_FILL)
}
if (material.blending.transparent) {
with(material.blending) {
gl.glBlendFuncSeparate(
sourceColorBlendFactor.toOpenGL(),
destinationColorBlendFactor.toOpenGL(),
sourceAlphaBlendFactor.toOpenGL(),
destinationAlphaBlendFactor.toOpenGL()
)
gl.glBlendEquationSeparate(
colorBlending.toOpenGL(),
alphaBlending.toOpenGL()
)
}
}
if (!renderable.metadata.containsKey("OpenGLRenderer") || !node.initialized) {
renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(node)
return@renderLoop
}
val s = getOpenGLObjectStateFromNode(renderable)
val shader = s.shader ?: pass.defaultShader!!
if(currentShader != shader) {
shader.use(gl)
}
currentShader = shader
if (renderConfig.stereoEnabled) {
shader.getUniform("currentEye.eye").setInt(pass.openglMetadata.eye)
}
var unit = 0
pass.inputs.keys.reversed().forEach { name ->
renderConfig.rendertargets[name.substringBefore(".")]?.attachments?.forEach {
shader.getUniform("Input" + it.key).setInt(unit)
unit++
}
}
val unboundSamplers = (unit until maxTextureUnits).toMutableList()
var maxSamplerIndex = 0
val textures = s.textures.entries.groupBy { Texture.objectTextures.contains(it.key) }
val objectTextures = textures[true]
val others = textures[false]
objectTextures?.forEach { texture ->
val samplerIndex = textureTypeToUnit(pass, texture.key)
maxSamplerIndex = max(samplerIndex, maxSamplerIndex)
@Suppress("SENSELESS_COMPARISON")
if (texture.value != null) {
gl.glActiveTexture(GL4.GL_TEXTURE0 + samplerIndex)
val target = if (texture.value.depth > 1) {
GL4.GL_TEXTURE_3D
} else {
GL4.GL_TEXTURE_2D
}
gl.glBindTexture(target, texture.value.id)
shader.getUniform(textureTypeToArrayName(texture.key)).setInt(samplerIndex)
unboundSamplers.remove(samplerIndex)
}
}
var samplerIndex = maxSamplerIndex
others?.forEach { texture ->
@Suppress("SENSELESS_COMPARISON")
if(texture.value != null) {
val minIndex = unboundSamplers.minOrNull() ?: maxSamplerIndex
gl.glActiveTexture(GL4.GL_TEXTURE0 + minIndex)
val target = if (texture.value.depth > 1) {
GL4.GL_TEXTURE_3D
} else {
GL4.GL_TEXTURE_2D
}
gl.glBindTexture(target, texture.value.id)
shader.getUniform(texture.key).setInt(minIndex)
samplerIndex++
unboundSamplers.remove(minIndex)
}
}
var binding = 0
(s.UBOs + pass.UBOs).forEach { name, ubo ->
val actualName = if (name.contains("ShaderParameters")) {
"ShaderParameters"
} else {
name
}
if(shader.uboSpecs.containsKey(actualName) && shader.isValid()) {
val index = shader.getUniformBlockIndex(actualName)
logger.trace("Binding {} for {}, index={}, binding={}, size={}", actualName, node.name, index, binding, ubo.getSize())
if (index == -1) {
logger.error("Failed to bind UBO $actualName for ${node.name} to $binding")
} else {
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
ubo.backingBuffer!!.id[0], 1L * ubo.offset, 1L * ubo.getSize())
binding++
}
}
}
arrayOf("VRParameters" to buffers.VRParameters,
"LightParameters" to buffers.LightParameters).forEach uboBinding@ { b ->
val buffer = b.second
val name = b.first
if (shader.uboSpecs.containsKey(name) && shader.isValid()) {
val index = shader.getUniformBlockIndex(name)
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $name for ${pass.passName} to $binding, though it is required by the shader")
} else {
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
buffer.id[0],
0L, buffer.buffer.remaining().toLong())
binding++
}
}
}
if(node is InstancedNode) {
drawNodeInstanced(node)
} else {
drawNode(node)
}
}
} else {
gl.glDisable(GL4.GL_CULL_FACE)
if (pass.output.any { it.value.hasDepthAttachment() }) {
gl.glEnable(GL4.GL_DEPTH_TEST)
} else {
gl.glDisable(GL4.GL_DEPTH_TEST)
}
if (pass.passConfig.renderTransparent) {
gl.glEnable(GL4.GL_BLEND)
gl.glBlendFuncSeparate(
pass.passConfig.srcColorBlendFactor.toOpenGL(),
pass.passConfig.dstColorBlendFactor.toOpenGL(),
pass.passConfig.srcAlphaBlendFactor.toOpenGL(),
pass.passConfig.dstAlphaBlendFactor.toOpenGL())
gl.glBlendEquationSeparate(
pass.passConfig.colorBlendOp.toOpenGL(),
pass.passConfig.alphaBlendOp.toOpenGL()
)
} else {
gl.glDisable(GL4.GL_BLEND)
}
pass.defaultShader?.let { shader ->
shader.use(gl)
var unit = 0
pass.inputs.keys.reversed().forEach { name ->
renderConfig.rendertargets[name.substringBefore(".")]?.attachments?.forEach {
shader.getUniform("Input" + it.key).setInt(unit)
unit++
}
}
var binding = 0
pass.UBOs.forEach { name, ubo ->
val actualName = if (name.contains("ShaderParameters")) {
"ShaderParameters"
} else {
name
}
val index = shader.getUniformBlockIndex(actualName)
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
ubo.backingBuffer!!.id[0],
1L * ubo.offset, 1L * ubo.getSize())
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $actualName for ${pass.passName} to $binding")
}
binding++
}
arrayOf("LightParameters" to buffers.LightParameters,
"VRParameters" to buffers.VRParameters).forEach { b ->
val name = b.first
val buffer = b.second
if (shader.uboSpecs.containsKey(name)) {
val index = shader.getUniformBlockIndex(name)
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
buffer.id[0],
0L, buffer.buffer.remaining().toLong())
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $name for ${pass.passName} to $binding, though it is required by the shader")
}
binding++
}
}
renderFullscreenQuad(shader)
}
}
stats?.add("Renderer.$t.renderTiming", System.nanoTime() - startPass)
}
if(logger.isDebugEnabled || logger.isTraceEnabled) {
val error = gl.glGetError()
if (error != 0) {
throw Exception("OpenGL error: $error")
}
}
logger.trace("Running viewport pass")
val startPass = System.nanoTime()
val viewportPass = renderpasses.getValue(flow.last())
gl.glBindFramebuffer(GL4.GL_DRAW_FRAMEBUFFER, 0)
blitFramebuffers(viewportPass.output.values.first(), null,
OpenGLRenderpass.Rect2D(
settings.get("Renderer.${viewportPass.passName}.displayWidth"),
settings.get("Renderer.${viewportPass.passName}.displayHeight"), 0, 0),
OpenGLRenderpass.Rect2D(window.width, window.height, 0, 0))
// submit to OpenVR if attached
if(hub?.getWorkingHMDDisplay()?.hasCompositor() == true && !mustRecreateFramebuffers) {
hub?.getWorkingHMDDisplay()?.wantsVR(settings)?.submitToCompositor(
viewportPass.output.values.first().getTextureId("Viewport"))
}
val w = viewportPass.output.values.first().width
val h = viewportPass.output.values.first().height
if((embedIn != null && embedIn !is SceneryJPanel) || recordMovie) {
if (shouldClose || mustRecreateFramebuffers) {
encoder?.finish()
encoder = null
return@runBlocking
}
if (recordMovie && (encoder == null || encoder?.frameWidth != w || encoder?.frameHeight != h)) {
val file = SystemHelpers.addFileCounter(if(movieFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.mp4")
} else {
File(movieFilename)
}, false)
val supersamplingFactor = getSupersamplingFactor(cglWindow)
encoder = VideoEncoder(
(supersamplingFactor * window.width).toInt(),
(supersamplingFactor * window.height).toInt(),
file.absolutePath,
hub = hub)
}
readIndex = (readIndex + 1) % pboCount
updateIndex = (updateIndex + 1) % pboCount
if (pbos.any { it == 0 } || mustRecreateFramebuffers) {
gl.glGenBuffers(pboCount, pbos, 0)
pbos.forEachIndexed { index, pbo ->
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbo)
gl.glBufferData(GL4.GL_PIXEL_PACK_BUFFER, w * h * 4L, null, GL4.GL_STREAM_READ)
if(pboBuffers[index] != null) {
MemoryUtil.memFree(pboBuffers[index])
pboBuffers[index] = null
}
}
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, 0)
}
pboBuffers.forEachIndexed { i, _ ->
if(pboBuffers[i] == null) {
pboBuffers[i] = MemoryUtil.memAlloc(4 * w * h)
}
}
viewportPass.output.values.first().setReadBuffers(gl)
val startUpdate = System.nanoTime()
if(frames < pboCount) {
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbos[updateIndex])
gl.glReadPixels(0, 0, w, h, GL4.GL_BGRA, GL4.GL_UNSIGNED_BYTE, 0)
} else {
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbos[updateIndex])
val readBuffer = gl.glMapBuffer(GL4.GL_PIXEL_PACK_BUFFER, GL4.GL_READ_ONLY)
MemoryUtil.memCopy(readBuffer, pboBuffers[readIndex]!!)
gl.glUnmapBuffer(GL4.GL_PIXEL_PACK_BUFFER)
gl.glReadPixels(0, 0, w, h, GL4.GL_BGRA, GL4.GL_UNSIGNED_BYTE, 0)
}
if (!mustRecreateFramebuffers && frames > pboCount) {
embedIn?.let { embedPanel ->
pboBuffers[readIndex]?.let {
val id = viewportPass.output.values.first().getTextureId("Viewport")
embedPanel.update(it, id = id)
}
}
encoder?.let { e ->
pboBuffers[readIndex]?.let {
e.encodeFrame(it, flip = true)
}
}
}
val updateDuration = (System.nanoTime() - startUpdate)*1.0f
stats?.add("Renderer.updateEmbed", updateDuration, true)
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, 0)
}
val request = try {
imageRequests.poll()
} catch(e: NoSuchElementException) {
null
}
if ((screenshotRequested || request != null) && joglDrawable != null) {
try {
val readBufferUtil = AWTGLReadBufferUtil(joglDrawable!!.glProfile, false)
val image = readBufferUtil.readPixelsToBufferedImage(gl, true)
val file = SystemHelpers.addFileCounter(if(screenshotFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.png")
} else {
File(screenshotFilename)
}, screenshotOverwriteExisting)
if(request != null) {
request.width = window.width
request.height = window.height
val data = (image.raster.dataBuffer as DataBufferInt).data
val tmp = ByteBuffer.allocate(data.size * 4)
data.forEach { value ->
val r = (value shr 16).toByte()
val g = (value shr 8).toByte()
val b = value.toByte()
tmp.put(0)
tmp.put(b)
tmp.put(g)
tmp.put(r)
}
request.data = tmp.array()
}
if(screenshotRequested && image != null) {
ImageIO.write(image, "png", file)
logger.info("Screenshot saved to ${file.absolutePath}")
}
} catch (e: Exception) {
logger.error("Unable to take screenshot: ")
e.printStackTrace()
}
screenshotOverwriteExisting = false
screenshotRequested = false
}
stats?.add("Renderer.${flow.last()}.renderTiming", System.nanoTime() - startPass)
updateLatch?.countDown()
firstImageReady = true
frames++
framesPerSec++
}
/**
* Renders a fullscreen quad, using from an on-the-fly generated
* Node that is saved in [nodeStore], with the [GLProgram]'s ID.
*
* @param[program] The [GLProgram] to draw into the fullscreen quad.
*/
fun renderFullscreenQuad(program: OpenGLShaderProgram) {
val quad: Node
val quadName = "fullscreenQuad-${program.id}"
quad = nodeStore.getOrPut(quadName) {
val q = Plane(Vector3f(1.0f, 1.0f, 0.0f))
q.ifRenderable {
this.metadata["OpenGLRenderer"] = OpenGLObjectState()
}
initializeNode(q)
q
}
drawNode(quad, count = 3)
program.gl.glBindTexture(GL4.GL_TEXTURE_2D, 0)
}
/**
* Initializes a given [Node].
*
* This function initializes a Node, equipping its metadata with an [OpenGLObjectState],
* generating VAOs and VBOs. If the Node has a [Material] assigned, a [GLProgram] fitting
* this Material will be used. Else, a default GLProgram will be used.
*
* For the assigned Material case, the GLProgram is derived either from the class name of the
* Node (if useClassDerivedShader is set), or from a set [ShaderMaterial] which may define
* the whole shader pipeline for the Node.
*
* If the [Node] implements [HasGeometry], it's geometry is also initialized by this function.
*
* @param[node]: The [Node] to initialise.
* @return True if the initialisation went alright, False if it failed.
*/
@Synchronized fun initializeNode(node: Node): Boolean {
val renderable = node.renderableOrNull() ?: return false
val material = node.materialOrNull() ?: return false
val spatial = node.spatialOrNull()
if(!node.lock.tryLock()) {
return false
}
if(renderable.rendererMetadata() == null) {
renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
}
val s = renderable.metadata["OpenGLRenderer"] as OpenGLObjectState
if (s.initialized) {
return true
}
// generate VAO for attachment of VBO and indices
gl.glGenVertexArrays(1, s.mVertexArrayObject, 0)
// generate three VBOs for coords, normals, texcoords
gl.glGenBuffers(3, s.mVertexBuffers, 0)
gl.glGenBuffers(1, s.mIndexBuffer, 0)
when {
material is ShaderMaterial -> {
val shaders = material.shaders
try {
s.shader = prepareShaderProgram(shaders)
} catch (e: ShaderCompilationException) {
logger.warn("Shader compilation for node ${node.name} with shaders $shaders failed, falling back to default shaders.")
logger.warn("Shader compiler error was: ${e.message}")
}
}
else -> s.shader = null
}
node.ifGeometry {
setVerticesAndCreateBufferForNode(s)
setNormalsAndCreateBufferForNode(s)
if (this.texcoords.limit() > 0) {
setTextureCoordsAndCreateBufferForNode(s)
}
if (this.indices.limit() > 0) {
setIndicesAndCreateBufferForNode(s)
}
}
s.materialHash = material.materialHashCode()
val matricesUbo = OpenGLUBO(backingBuffer = buffers.UBOs)
with(matricesUbo) {
name = "Matrices"
if(spatial != null) {
add("ModelMatrix", { spatial.world })
add("NormalMatrix", { Matrix4f(spatial.world).invert().transpose() })
}
add("isBillboard", { renderable.isBillboard.toInt() })
sceneUBOs.add(node)
s.UBOs.put("Matrices", this)
}
loadTexturesForNode(node, s)
val materialUbo = OpenGLUBO(backingBuffer = buffers.UBOs)
with(materialUbo) {
name = "MaterialProperties"
add("materialType", { material.materialToMaterialType(s) })
add("Ka", { material.ambient })
add("Kd", { material.diffuse })
add("Ks", { material.specular })
add("Roughness", { material.roughness })
add("Metallic", { material.metallic })
add("Opacity", { material.blending.opacity })
s.UBOs.put("MaterialProperties", this)
}
if (renderable.parent.javaClass.kotlin.memberProperties.filter { it.findAnnotation<ShaderProperty>() != null }.count() > 0) {
val shaderPropertyUBO = OpenGLUBO(backingBuffer = buffers.ShaderProperties)
with(shaderPropertyUBO) {
name = "ShaderProperties"
val shader = if (material is ShaderMaterial) {
s.shader
} else {
renderpasses.filter {
(it.value.passConfig.type == RenderConfigReader.RenderpassType.geometry || it.value.passConfig.type == RenderConfigReader.RenderpassType.lights)
&& it.value.passConfig.renderTransparent == material.blending.transparent
}.entries.firstOrNull()?.value?.defaultShader
}
logger.debug("Shader properties are: ${shader?.getShaderPropertyOrder()}")
shader?.getShaderPropertyOrder()?.forEach { name, offset ->
add(name, { renderable.parent.getShaderProperty(name) ?: 0 }, offset)
}
}
s.UBOs["ShaderProperties"] = shaderPropertyUBO
}
s.initialized = true
node.initialized = true
renderable.metadata[className] = s
s.initialized = true
node.lock.unlock()
return true
}
private val defaultTextureNames = arrayOf("ambient", "diffuse", "specular", "normal", "alphamask", "displacement")
private fun Material.materialToMaterialType(s: OpenGLObjectState): Int {
var materialType = 0
if (this.textures.containsKey("ambient") && !s.defaultTexturesFor.contains("ambient")) {
materialType = materialType or MATERIAL_HAS_AMBIENT
}
if (this.textures.containsKey("diffuse") && !s.defaultTexturesFor.contains("diffuse")) {
materialType = materialType or MATERIAL_HAS_DIFFUSE
}
if (this.textures.containsKey("specular") && !s.defaultTexturesFor.contains("specular")) {
materialType = materialType or MATERIAL_HAS_SPECULAR
}
if (this.textures.containsKey("normal") && !s.defaultTexturesFor.contains("normal")) {
materialType = materialType or MATERIAL_HAS_NORMAL
}
if (this.textures.containsKey("alphamask") && !s.defaultTexturesFor.contains("alphamask")) {
materialType = materialType or MATERIAL_HAS_ALPHAMASK
}
return materialType
}
/**
* Initializes a default set of textures that the renderer can fall back to and provide a non-intrusive
* hint to the user that a texture could not be loaded.
*/
private fun prepareDefaultTextures() {
val t = GLTexture.loadFromFile(gl, Renderer::class.java.getResourceAsStream("DefaultTexture.png"), "png", false, true, 8)
if(t == null) {
logger.error("Could not load default texture! This indicates a serious issue.")
} else {
textureCache["DefaultTexture"] = t
}
}
/**
* Returns true if the current [GLTexture] can be reused to store the information in the [Texture]
* [other]. Returns false otherwise.
*/
protected fun GLTexture.canBeReused(other: Texture): Boolean {
return this.width == other.dimensions.x() &&
this.height == other.dimensions.y() &&
this.depth == other.dimensions.z() &&
this.nativeType.equivalentTo(other.type)
}
private fun GLTypeEnum.equivalentTo(type: NumericType<*>): Boolean {
return when {
this == GLTypeEnum.UnsignedByte && type is UnsignedByteType -> true
this == GLTypeEnum.Byte && type is ByteType -> true
this == GLTypeEnum.UnsignedShort && type is UnsignedShortType -> true
this == GLTypeEnum.Short && type is ShortType -> true
this == GLTypeEnum.UnsignedInt && type is UnsignedIntType -> true
this == GLTypeEnum.Int && type is IntType -> true
this == GLTypeEnum.Float && type is FloatType -> true
this == GLTypeEnum.Double && type is DoubleType -> true
else -> false
}
}
@Suppress("unused")
private fun dumpTextureToFile(gl: GL4, name: String, texture: GLTexture) {
val filename = "${name}_${Date().toInstant().epochSecond}.raw"
val bytes = texture.width*texture.height*texture.depth*texture.channels*texture.bitsPerChannel/8
logger.info("Dumping $name to $filename ($bytes bytes)")
val buffer = MemoryUtil.memAlloc(bytes)
gl.glPixelStorei(GL4.GL_PACK_ALIGNMENT, 1)
texture.bind()
gl.glGetTexImage(texture.textureTarget, 0, texture.format, texture.type, buffer)
texture.unbind()
val stream = FileOutputStream(filename)
val outChannel = stream.channel
outChannel.write(buffer)
logger.info("Written $texture to $stream")
outChannel.close()
stream.close()
MemoryUtil.memFree(buffer)
}
private fun RepeatMode.toOpenGL(): Int {
return when(this) {
RepeatMode.Repeat -> GL4.GL_REPEAT
RepeatMode.MirroredRepeat -> GL4.GL_MIRRORED_REPEAT
RepeatMode.ClampToEdge -> GL4.GL_CLAMP_TO_EDGE
RepeatMode.ClampToBorder -> GL4.GL_CLAMP_TO_BORDER
}
}
private fun BorderColor.toOpenGL(): FloatArray {
return when(this) {
BorderColor.TransparentBlack -> floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f)
BorderColor.OpaqueBlack -> floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f)
BorderColor.OpaqueWhite -> floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f)
}
}
private fun NumericType<*>.toOpenGL(): GLTypeEnum {
return when(this) {
is UnsignedByteType -> GLTypeEnum.UnsignedByte
is ByteType -> GLTypeEnum.Byte
is UnsignedShortType -> GLTypeEnum.UnsignedShort
is ShortType -> GLTypeEnum.Short
is UnsignedIntType -> GLTypeEnum.UnsignedInt
is IntType -> GLTypeEnum.Int
is FloatType -> GLTypeEnum.Float
is DoubleType -> GLTypeEnum.Double
else -> throw IllegalStateException("Type ${this.javaClass.simpleName} is not supported as OpenGL texture type")
}
}
/**
* Loads textures for a [Node]. The textures are loaded from a [Material.textures].
*
* @param[node] The [Node] to load textures for.
* @param[s] The [Node]'s [OpenGLObjectState]
*/
@Suppress("USELESS_ELVIS")
private fun loadTexturesForNode(node: Node, s: OpenGLObjectState): Boolean {
val material = node.materialOrNull() ?: return false
var changed = false
val last = s.texturesLastSeen
val now = System.nanoTime()
material.textures.forEachChanged(last) { (type, texture) ->
changed = true
logger.debug("Loading texture $texture for ${node.name}")
val generateMipmaps = Texture.mipmappedObjectTextures.contains(type)
val contentsNew = texture.contents?.duplicate()
logger.debug("Dims of $texture: ${texture.dimensions}, mipmaps=$generateMipmaps")
val mm = generateMipmaps or texture.mipmap
val miplevels = if (mm && texture.dimensions.z() == 1) {
1 + floor(ln(max(texture.dimensions.x() * 1.0, texture.dimensions.y() * 1.0)) / ln(2.0)).toInt()
} else {
1
}
val existingTexture = s.textures[type]
val t = if(existingTexture != null && existingTexture.canBeReused(texture)) {
existingTexture
} else {
GLTexture(gl, texture.type.toOpenGL(), texture.channels,
texture.dimensions.x(),
texture.dimensions.y(),
texture.dimensions.z() ?: 1,
texture.minFilter == Texture.FilteringMode.Linear,
miplevels, 32,
texture.normalized, renderConfig.sRGB)
}
if (mm) {
t.updateMipMaps()
}
t.setRepeatModeS(texture.repeatUVW.first.toOpenGL())
t.setRepeatModeT(texture.repeatUVW.second.toOpenGL())
t.setRepeatModeR(texture.repeatUVW.third.toOpenGL())
t.setTextureBorderColor(texture.borderColor.toOpenGL())
// textures might have very uneven dimensions, so we adjust GL_UNPACK_ALIGNMENT here correspondingly
// in case the byte count of the texture is not divisible by it.
val unpackAlignment = intArrayOf(0)
gl.glGetIntegerv(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment, 0)
texture.contents?.let { contents ->
t.copyFrom(contents.duplicate())
}
if (contentsNew != null && texture is UpdatableTexture && !texture.hasConsumableUpdates()) {
if (contentsNew.remaining() % unpackAlignment[0] == 0 && texture.dimensions.x() % unpackAlignment[0] == 0) {
t.copyFrom(contentsNew)
} else {
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, 1)
t.copyFrom(contentsNew)
}
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment[0])
}
if (texture is UpdatableTexture && texture.hasConsumableUpdates()) {
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, 1)
texture.getConsumableUpdates().forEach { update ->
t.copyFrom(update.contents,
update.extents.w, update.extents.h, update.extents.d,
update.extents.x, update.extents.y, update.extents.z, true)
update.consumed = true
}
texture.clearConsumedUpdates()
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment[0])
}
s.textures[type] = t
// textureCache.put(texture, t)
}
// update default textures
// s.defaultTexturesFor = defaultTextureNames.mapNotNull { if(!s.textures.containsKey(it)) { it } else { null } }.toHashSet()
s.defaultTexturesFor.clear()
defaultTextureNames.forEach {
if (!s.textures.containsKey(it)) {
s.defaultTexturesFor.add(it)
}
}
s.texturesLastSeen = now
s.initialized = true
return changed
}
/**
* Reshape the renderer's viewports
*
* This routine is called when a change in window size is detected, e.g. when resizing
* it manually or toggling fullscreen. This function updates the sizes of all used
* geometry buffers and will also create new buffers in case vr.Active is changed.
*
* This function also clears color and depth buffer bits.
*
* @param[newWidth] The resized window's width
* @param[newHeight] The resized window's height
*/
override fun reshape(newWidth: Int, newHeight: Int) {
if (!initialized) {
return
}
lastResizeTimer.cancel()
lastResizeTimer = Timer()
lastResizeTimer.schedule(object : TimerTask() {
override fun run() {
val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f))
?: Vector2f(1.0f, 1.0f)
val panel = embedIn
if(panel is SceneryJPanel && panel.width != (newWidth/surfaceScale.x()).toInt() && panel.height != (newWidth/surfaceScale.y()).toInt()) {
logger.debug("Panel is ${panel.width}x${panel.height} vs $newWidth x $newHeight")
window.width = (newWidth * surfaceScale.x()).toInt()
window.height = (newHeight * surfaceScale.y()).toInt()
} else {
window.width = newWidth
window.height = newHeight
}
logger.debug("Resizing window to ${newWidth}x$newHeight")
mustRecreateFramebuffers = true
}
}, WINDOW_RESIZE_TIMEOUT)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s vertices.
*/
fun Geometry.setVerticesAndCreateBufferForNode(s: OpenGLObjectState) {
updateVertices(s)
}
/**
* Updates a [Geometry]'s vertices.
*/
fun Geometry.updateVertices(s: OpenGLObjectState) {
val pVertexBuffer: FloatBuffer = vertices.duplicate()
s.mStoredPrimitiveCount = pVertexBuffer.remaining() / vertexSize
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[0])
gl.glEnableVertexAttribArray(0)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pVertexBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pVertexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(0,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s normals.
*/
fun Geometry.setNormalsAndCreateBufferForNode(s: OpenGLObjectState) {
val pNormalBuffer: FloatBuffer = normals.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[1])
if (pNormalBuffer.limit() > 0) {
gl.glEnableVertexAttribArray(1)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pNormalBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pNormalBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(1,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
}
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Updates a given [Geometry]'s normals.
*/
fun Geometry.updateNormals(s: OpenGLObjectState) {
val pNormalBuffer: FloatBuffer = normals.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[1])
gl.glEnableVertexAttribArray(1)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pNormalBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pNormalBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(1,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s texcoords.
*/
fun Geometry.setTextureCoordsAndCreateBufferForNode(s: OpenGLObjectState) {
updateTextureCoords(s)
}
/**
* Updates a given [Geometry]'s texcoords.
*/
fun Geometry.updateTextureCoords(s: OpenGLObjectState) {
val pTextureCoordsBuffer: FloatBuffer = texcoords.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER,
s.mVertexBuffers[2])
gl.glEnableVertexAttribArray(2)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pTextureCoordsBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pTextureCoordsBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(2,
texcoordSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates a index buffer for a given [Geometry]'s indices.
*/
fun Geometry.setIndicesAndCreateBufferForNode(s: OpenGLObjectState) {
val pIndexBuffer: IntBuffer = indices.duplicate()
s.mStoredIndexCount = pIndexBuffer.remaining()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, s.mIndexBuffer[0])
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER,
(pIndexBuffer.remaining() * (Integer.SIZE / java.lang.Byte.SIZE)).toLong(),
pIndexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
}
/**
* Updates a given [Geometry]'s indices.
*/
fun Geometry.updateIndices(s: OpenGLObjectState) {
val pIndexBuffer: IntBuffer = indices.duplicate()
s.mStoredIndexCount = pIndexBuffer.remaining()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, s.mIndexBuffer[0])
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER,
(pIndexBuffer.remaining() * (Integer.SIZE / java.lang.Byte.SIZE)).toLong(),
pIndexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
}
/**
* Draws a given [Node], either in element or in index draw mode.
*
* @param[node] The node to be drawn.
* @param[offset] offset in the array or index buffer.
*/
fun drawNode(node: Node, offset: Int = 0, count: Int? = null) {
val renderable = node.renderableOrNull() ?: return
val s = getOpenGLObjectStateFromNode(renderable)
if (s.mStoredIndexCount == 0 && s.mStoredPrimitiveCount == 0) {
return
}
logger.trace("Drawing {} with {}, {} primitives, {} indices", node.name, s.shader?.modules?.entries?.joinToString(", "), s.mStoredPrimitiveCount, s.mStoredIndexCount)
node.ifGeometry {
gl.glBindVertexArray(s.mVertexArrayObject[0])
if (s.mStoredIndexCount > 0) {
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER,
s.mIndexBuffer[0])
gl.glDrawElements(geometryType.toOpenGLType(),
count ?: s.mStoredIndexCount,
GL4.GL_UNSIGNED_INT,
offset.toLong())
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
} else {
gl.glDrawArrays(geometryType.toOpenGLType(), offset, count ?: s.mStoredPrimitiveCount)
}
// gl.glUseProgram(0)
// gl.glBindVertexArray(0)
}
}
/**
* Draws a given instanced [Node] either in element or in index draw mode.
*
* @param[node] The node to be drawn.
* @param[offset] offset in the array or index buffer.
*/
protected fun drawNodeInstanced(node: Node, offset: Long = 0) {
node.ifRenderable {
val s = getOpenGLObjectStateFromNode(this)
node.ifGeometry {
gl.glBindVertexArray(s.mVertexArrayObject[0])
if (s.mStoredIndexCount > 0) {
gl.glDrawElementsInstanced(
geometryType.toOpenGLType(),
s.mStoredIndexCount,
GL4.GL_UNSIGNED_INT,
offset,
s.instanceCount)
} else {
gl.glDrawArraysInstanced(
geometryType.toOpenGLType(),
0, s.mStoredPrimitiveCount, s.instanceCount)
}
// gl.glUseProgram(0)
// gl.glBindVertexArray(0)
}
}
}
override fun screenshot(filename: String, overwrite: Boolean) {
screenshotRequested = true
screenshotOverwriteExisting = overwrite
screenshotFilename = filename
}
@Suppress("unused")
override fun recordMovie(filename: String, overwrite: Boolean) {
if(recordMovie) {
encoder?.finish()
encoder = null
recordMovie = false
} else {
movieFilename = filename
recordMovie = true
}
}
private fun Blending.BlendFactor.toOpenGL() = when (this) {
Blending.BlendFactor.Zero -> GL4.GL_ZERO
Blending.BlendFactor.One -> GL4.GL_ONE
Blending.BlendFactor.SrcAlpha -> GL4.GL_SRC_ALPHA
Blending.BlendFactor.OneMinusSrcAlpha -> GL4.GL_ONE_MINUS_SRC_ALPHA
Blending.BlendFactor.SrcColor -> GL4.GL_SRC_COLOR
Blending.BlendFactor.OneMinusSrcColor -> GL4.GL_ONE_MINUS_SRC_COLOR
Blending.BlendFactor.DstColor -> GL4.GL_DST_COLOR
Blending.BlendFactor.OneMinusDstColor -> GL4.GL_ONE_MINUS_DST_COLOR
Blending.BlendFactor.DstAlpha -> GL4.GL_DST_ALPHA
Blending.BlendFactor.OneMinusDstAlpha -> GL4.GL_ONE_MINUS_DST_ALPHA
Blending.BlendFactor.ConstantColor -> GL4.GL_CONSTANT_COLOR
Blending.BlendFactor.OneMinusConstantColor -> GL4.GL_ONE_MINUS_CONSTANT_COLOR
Blending.BlendFactor.ConstantAlpha -> GL4.GL_CONSTANT_ALPHA
Blending.BlendFactor.OneMinusConstantAlpha -> GL4.GL_ONE_MINUS_CONSTANT_ALPHA
Blending.BlendFactor.Src1Color -> GL4.GL_SRC1_COLOR
Blending.BlendFactor.OneMinusSrc1Color -> GL4.GL_ONE_MINUS_SRC1_COLOR
Blending.BlendFactor.Src1Alpha -> GL4.GL_SRC1_ALPHA
Blending.BlendFactor.OneMinusSrc1Alpha -> GL4.GL_ONE_MINUS_SRC1_ALPHA
Blending.BlendFactor.SrcAlphaSaturate -> GL4.GL_SRC_ALPHA_SATURATE
}
private fun Blending.BlendOp.toOpenGL() = when (this) {
Blending.BlendOp.add -> GL4.GL_FUNC_ADD
Blending.BlendOp.subtract -> GL4.GL_FUNC_SUBTRACT
Blending.BlendOp.min -> GL4.GL_MIN
Blending.BlendOp.max -> GL4.GL_MAX
Blending.BlendOp.reverse_subtract -> GL4.GL_FUNC_REVERSE_SUBTRACT
}
/**
* Sets the rendering quality, if the loaded renderer config file supports it.
*
* @param[quality] The [RenderConfigReader.RenderingQuality] to be set.
*/
override fun setRenderingQuality(quality: RenderConfigReader.RenderingQuality) {
fun setConfigSetting(key: String, value: Any) {
val setting = "Renderer.$key"
logger.debug("Setting $setting: ${settings.get<Any>(setting)} -> $value")
settings.set(setting, value)
}
if(renderConfig.qualitySettings.isNotEmpty()) {
logger.info("Setting rendering quality to $quality")
renderConfig.qualitySettings[quality]?.forEach { setting ->
if(setting.key.endsWith(".shaders") && setting.value is List<*>) {
val pass = setting.key.substringBeforeLast(".shaders")
@Suppress("UNCHECKED_CAST")
val shaders = setting.value as? List<String> ?: return@forEach
renderConfig.renderpasses[pass]?.shaders = shaders
mustRecreateFramebuffers = true
framebufferRecreateHook = {
renderConfig.qualitySettings[quality]?.filter { !it.key.endsWith(".shaders") }?.forEach {
setConfigSetting(it.key, it.value)
}
framebufferRecreateHook = {}
}
} else {
setConfigSetting(setting.key, setting.value)
}
}
} else {
logger.warn("The current renderer config, $renderConfigFile, does not support setting quality options.")
}
}
/**
* Closes this renderer instance.
*/
override fun close() {
if (shouldClose || !initialized) {
return
}
shouldClose = true
lastResizeTimer.cancel()
encoder?.finish()
cglWindow?.closeNoEDT()
joglDrawable?.destroy()
}
}
| lgpl-3.0 | 9deeb496294112e77eada94823fb708a | 38.445142 | 212 | 0.562378 | 4.738616 | false | false | false | false |
neva-dev/javarel-framework | storage/database/src/main/kotlin/com/neva/javarel/storage/database/impl/connection/PgSqlDatabaseConnection.kt | 1 | 2508 | package com.neva.javarel.storage.database.impl.connection
import com.neva.javarel.foundation.api.JavarelConstants
import org.apache.felix.scr.annotations.Activate
import org.apache.felix.scr.annotations.Component
import org.apache.felix.scr.annotations.Property
import org.apache.felix.scr.annotations.Service
import org.postgresql.ds.PGSimpleDataSource
import javax.sql.DataSource
@Component(immediate = true, configurationFactory = true, metatype = true, label = "${JavarelConstants.SERVICE_PREFIX} Storage - PostgreSQL Connection")
@Service
class PgSqlDatabaseConnection : AbstractDatabaseConnection() {
companion object {
@Property(name = NAME_PROP, value = "pgsql", label = "Connection name", description = "Unique identifier")
const val NAME_PROP = "name"
@Property(name = HOST_PROP, value = "localhost", label = "Host", description = "Server IP address or hostname")
const val HOST_PROP = "hostProp"
@Property(name = PORT_PROP, value = "5432", label = "Port", description = "Port number")
const val PORT_PROP = "portProp"
@Property(name = DB_NAME_PROP, value = "javarel", label = "Database name")
const val DB_NAME_PROP = "dbNameProp"
@Property(name = USER_PROP, value = "root", label = "Username")
const val USER_PROP = "userProp"
@Property(name = PASSWORD_PROP, value = "toor", label = "Password")
const val PASSWORD_PROP = "passwordProp"
}
private lateinit var props: Map<String, Any>
@Activate
private fun activate(props: Map<String, Any>) {
this.props = props
}
override val name: String
get() = props[NAME_PROP] as String
private val host: String
get() = props[HOST_PROP] as String
private val port: Int
get() = Integer.parseInt(props[PORT_PROP] as String)
private val dbName: String
get() = props[DB_NAME_PROP] as String
private val user: String
get() = props[USER_PROP] as String
private val password: String
get() = props[PASSWORD_PROP] as String
override val source: DataSource
get() {
val ds = PGSimpleDataSource()
ds.setServerName(host);
ds.setDatabaseName(dbName);
ds.setPortNumber(port);
if (!user.isNullOrBlank()) {
ds.user = user;
}
if (!password.isNullOrBlank()) {
ds.password = password;
}
return ds
}
} | apache-2.0 | 2c37edea0869140363d4fe25f154a7fe | 31.584416 | 152 | 0.639155 | 4.138614 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/relationship/internal/RelationshipPostCall.kt | 1 | 5863 | /*
* Copyright (c) 2004-2022, University of Oslo
* 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 the HISP project nor the names of its 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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 org.hisp.dhis.android.core.relationship.internal
import dagger.Reusable
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import java.net.HttpURLConnection.*
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor
import org.hisp.dhis.android.core.arch.call.D2Progress
import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager
import org.hisp.dhis.android.core.common.State
import org.hisp.dhis.android.core.common.internal.DataStatePropagator
import org.hisp.dhis.android.core.imports.ImportStatus
import org.hisp.dhis.android.core.imports.internal.RelationshipDeleteWebResponse
import org.hisp.dhis.android.core.imports.internal.RelationshipWebResponse
import org.hisp.dhis.android.core.relationship.Relationship
import org.hisp.dhis.android.core.trackedentity.internal.TrackerPostStateManager
@Reusable
internal class RelationshipPostCall @Inject internal constructor(
private val relationshipService: RelationshipService,
private val relationshipStore: RelationshipStore,
private val relationshipImportHandler: RelationshipImportHandler,
private val dataStatePropagator: DataStatePropagator,
private val trackerStateManager: TrackerPostStateManager,
private val apiCallExecutor: APICallExecutor
) {
fun deleteRelationships(relationships: List<Relationship>): Observable<D2Progress> {
return Observable.create { emitter: ObservableEmitter<D2Progress> ->
for (relationship in relationships) {
val httpResponse = apiCallExecutor.executeObjectCallWithAcceptedErrorCodes(
relationshipService.deleteRelationship(relationship.uid()!!),
listOf(HTTP_NOT_FOUND),
RelationshipDeleteWebResponse::class.java
)
val status = httpResponse.response()?.status()
if ((httpResponse.httpStatusCode() == HTTP_OK && ImportStatus.SUCCESS == status) ||
httpResponse.httpStatusCode() == HTTP_NOT_FOUND
) {
relationshipStore.delete(relationship.uid()!!)
} else {
// TODO Implement better handling
// The relationship is marked as error, but there is no handling in the TEI. The TEI is being posted
relationshipStore.setSyncState(relationship.uid()!!, State.ERROR)
}
dataStatePropagator.propagateRelationshipUpdate(relationship)
}
emitter.onComplete()
}
}
@Suppress("TooGenericExceptionCaught")
fun postRelationships(relationships: List<Relationship>): Observable<D2Progress> {
val progressManager = D2ProgressManager(null)
return if (relationships.isEmpty()) {
Observable.just<D2Progress>(progressManager.increaseProgress(Relationship::class.java, false))
} else {
Observable.defer {
try {
val payload = RelationshipPayload.builder().relationships(relationships).build()
trackerStateManager.setPayloadStates(
relationships = relationships,
forcedState = State.UPLOADING
)
val httpResponse = apiCallExecutor.executeObjectCallWithAcceptedErrorCodes(
relationshipService.postRelationship(payload),
listOf(HTTP_CONFLICT),
RelationshipWebResponse::class.java
)
relationshipImportHandler.handleRelationshipImportSummaries(
importSummaries = httpResponse.response()?.importSummaries(),
relationships = relationships
)
Observable.just<D2Progress>(progressManager.increaseProgress(Relationship::class.java, false))
} catch (e: Exception) {
trackerStateManager.restorePayloadStates(relationships = relationships)
relationships.forEach { dataStatePropagator.propagateRelationshipUpdate(it) }
Observable.error<D2Progress>(e)
}
}
}
}
}
| bsd-3-clause | fc2f1c25d1baa235c783c12aaf2ae60e | 50.429825 | 120 | 0.691284 | 5.258296 | false | false | false | false |
cdietze/klay | klay-demo/src/main/kotlin/klay/tests/core/FullscreenTest.kt | 1 | 1205 | package klay.tests.core
class FullscreenTest(game: TestsGame) : Test(game, "Full Screen", "Tests support for full screen modes") {
class Mode {
var width: Int = 0
var height: Int = 0
var depth: Int = 0
override fun toString(): String {
return "" + width + "x" + height + "x" + depth
}
}
interface Host {
fun enumerateModes(): Array<Mode>
fun setMode(mode: Mode)
}
override fun available(): Boolean {
return host != null
}
override fun init() {
val spacing = 5f
var y = spacing
var x = spacing
var nextX = spacing
for (mode in host!!.enumerateModes()) {
val button = game.ui.createButton(mode.toString(), { host!!.setMode(mode) })
game.rootLayer.add(button)
if (y + button.height() + spacing >= game.graphics.viewSize.height) {
x = nextX + spacing
y = spacing
}
button.setTranslation(x, y)
y += button.height() + spacing
nextX = maxOf(nextX, x + button.width())
}
}
companion object {
var host: Host? = null
}
}
| apache-2.0 | a9001fecc87d9049f0f8909dfc45e53f | 26.386364 | 106 | 0.521162 | 4.288256 | false | true | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/view/MyListView.kt | 1 | 1653 | package jp.juggler.subwaytooter.view
import android.annotation.SuppressLint
import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ListView
import jp.juggler.subwaytooter.itemviewholder.StatusButtonsPopup
import jp.juggler.util.LogCategory
class MyListView : ListView {
companion object {
private val log = LogCategory("MyListView")
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent): Boolean {
// ポップアップを閉じた時にクリックでリストを触ったことになってしまう不具合の回避
val now = SystemClock.elapsedRealtime()
if (now - StatusButtonsPopup.lastPopupClose < 30L) {
val action = ev.action
if (action == MotionEvent.ACTION_DOWN) {
// ポップアップを閉じた直後はタッチダウンを無視する
return false
}
val rv = super.onTouchEvent(ev)
log.d("onTouchEvent action=$action, rv=$rv")
return rv
}
return super.onTouchEvent(ev)
}
override fun layoutChildren() {
try {
super.layoutChildren()
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
| apache-2.0 | b4a04a2a82dab59c1922ec4578b6e251 | 28.54 | 111 | 0.643091 | 4.253482 | false | false | false | false |
TechzoneMC/SonarPet | api/src/main/kotlin/net/techcable/sonarpet/EntityHookType.kt | 1 | 3520 | package net.techcable.sonarpet
import com.dsh105.echopet.compat.api.entity.PetType
import com.dsh105.echopet.compat.api.plugin.EchoPet
import net.techcable.sonarpet.utils.NmsVersion
import net.techcable.sonarpet.utils.Versioning
import net.techcable.sonarpet.utils.reflection.MinecraftReflection
enum class EntityHookType(
val nmsName: String,
val petType: PetType,
val earliestVersion: NmsVersion = NmsVersion.EARLIEST,
val latestVersion: NmsVersion = NmsVersion.LATEST
) {
BAT("Bat", PetType.BAT),
BLAZE("Blaze", PetType.BLAZE),
CAVE_SPIDER("CaveSpider", PetType.CAVESPIDER),
CHICKEN("Chicken", PetType.CHICKEN),
COW("Cow", PetType.COW),
CREEPER("Creeper", PetType.CREEPER),
ENDER_DRAGON("EnderDragon", PetType.ENDERDRAGON),
ENDERMAN("Enderman", PetType.ENDERMAN),
ENDERMITE("Endermite", PetType.ENDERMITE),
GHAST("Ghast", PetType.GHAST),
GUARDIAN("Guardian", PetType.GUARDIAN),
// As of 1.11, elder guardian is a separate entity type
ELDER_GUARDIAN("GuardianElder", PetType.GUARDIAN, earliestVersion = NmsVersion.v1_11_R1),
// Horses were split up into multiple different entity types as of 1.11
HORSE("Horse", PetType.HORSE),
MULE("HorseMule", PetType.HORSE, earliestVersion = NmsVersion.v1_11_R1),
DONKEY("HorseDonkey", PetType.HORSE, earliestVersion = NmsVersion.v1_11_R1),
ZOMBIE_HORSE("HorseZombie", PetType.HORSE, earliestVersion = NmsVersion.v1_11_R1),
SKELETON_HORSE("HorseSkeleton", PetType.HORSE, earliestVersion = NmsVersion.v1_11_R1),
LLAMA("Llama", PetType.HORSE, earliestVersion = NmsVersion.v1_11_R1),
IRON_GOLEM("IronGolem", PetType.IRONGOLEM),
MAGMA_CUBE("MagmaCube", PetType.MAGMACUBE),
MUSHROOM_COW("MushroomCow", PetType.MUSHROOMCOW),
OCELOT("Ocelot", PetType.OCELOT),
PIG("Pig", PetType.PIG),
PIG_ZOMBIE("PigZombie", PetType.ZOMBIE),
RABBIT("Rabbit", PetType.RABBIT),
SHEEP("Sheep", PetType.SHEEP),
SILVERFISH("Silverfish", PetType.SILVERFISH),
SKELETON("Skeleton", PetType.SKELETON),
STRAY_SKELETON("SkeletonStray", PetType.SKELETON),
WITHER_SKELETON("SkeletonWither", PetType.SKELETON),
SLIME("Slime", PetType.SLIME),
SNOWMAN("Snowman", PetType.SNOWMAN),
SPIDER("Spider", PetType.SPIDER),
SQUID("Squid", PetType.SQUID),
VILLAGER("Villager", PetType.VILLAGER),
WITCH("Witch", PetType.WITCH),
WITHER("Wither", PetType.WITHER),
WOLF("Wolf", PetType.WOLF),
// Zombies were split up into different entity types as of 1.11
ZOMBIE("Zombie", PetType.ZOMBIE),
HUSK_ZOMBIE("ZombieHusk", PetType.ZOMBIE, earliestVersion = NmsVersion.v1_11_R1),
VILLAGER_ZOMBIE("ZombieVillager", PetType.ZOMBIE, earliestVersion = NmsVersion.v1_11_R1),
GIANT_ZOMBIE("GiantZombie", PetType.ZOMBIE),
PARROT("Parrot", PetType.PARROT, earliestVersion = NmsVersion.v1_12_R1);
val isActive = Versioning.NMS_VERSION in earliestVersion..latestVersion
val nmsType: Class<*>
get() {
check(isActive)
return MinecraftReflection.getNmsClass("Entity$nmsName") ?: throw IllegalStateException("Unknown NMS name '$nmsName' on version ${Versioning.NMS_VERSION}")
}
val entityId: Int
get() {
check(isActive)
return EchoPet.getPlugin().entityRegistry.getEntityId(nmsType)
}
val entityName: String
get() {
check(isActive)
return EchoPet.getPlugin().entityRegistry.getEntityName(nmsType)
}
} | gpl-3.0 | 0a6b6d70d75acba34aa450a28cd250c9 | 44.141026 | 167 | 0.700568 | 3.214612 | false | false | false | false |
RockinRoel/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/store/BenchmarkSqlStore.kt | 1 | 3647 | package com.hexagonkt.store
import com.hexagonkt.CachedWorld
import com.hexagonkt.Fortune
import com.hexagonkt.Settings
import com.hexagonkt.World
import com.hexagonkt.helpers.Jvm
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import org.cache2k.Cache
import java.sql.Connection
import java.sql.PreparedStatement
internal class BenchmarkSqlStore(engine: String, private val settings: Settings = Settings())
: BenchmarkStore(settings) {
companion object {
private const val SELECT_WORLD = "select * from world where id = ?"
private const val UPDATE_WORLD = "update world set randomNumber = ? where id = ?"
private const val SELECT_ALL_FORTUNES = "select * from fortune"
}
private val dataSource: HikariDataSource by lazy {
val dbHost = Jvm.systemSetting("${engine.uppercase()}_DB_HOST") ?: "localhost"
val config = HikariConfig().apply {
jdbcUrl = "jdbc:postgresql://$dbHost/${settings.databaseName}"
maximumPoolSize = Jvm.systemSetting(Int::class, "maximumPoolSize") ?: 64
username = Jvm.systemSetting("databaseUsername") ?: "benchmarkdbuser"
password = Jvm.systemSetting("databasePassword") ?: "benchmarkdbpass"
}
HikariDataSource(config)
}
override fun findAllFortunes(): List<Fortune> {
val fortunes = mutableListOf<Fortune>()
dataSource.connection.use { con: Connection ->
val rs = con.prepareStatement(SELECT_ALL_FORTUNES).executeQuery()
while (rs.next())
fortunes += Fortune(rs.getInt(1), rs.getString(2))
}
return fortunes
}
override fun findWorlds(ids: List<Int>): List<World> =
dataSource.connection.use { con: Connection ->
val stmtSelect = con.prepareStatement(SELECT_WORLD)
ids.map { con.findWorld(it, stmtSelect) }
}
override fun replaceWorlds(worlds: List<World>) {
dataSource.connection.use { con: Connection ->
val stmtSelect = con.prepareStatement(SELECT_WORLD)
val stmtUpdate = con.prepareStatement(UPDATE_WORLD)
worlds.forEach {
val worldId = it.id
val newRandomNumber = it.randomNumber
stmtSelect.setInt(1, worldId)
val rs = stmtSelect.executeQuery()
rs.next()
rs.getInt(2) // Read 'randomNumber' to comply with Test type 5, point 6
stmtUpdate.setInt(1, newRandomNumber)
stmtUpdate.setInt(2, worldId)
stmtUpdate.executeUpdate()
}
}
}
override fun initWorldsCache(cache: Cache<Int, CachedWorld>) {
dataSource.connection.use { con: Connection ->
val stmtSelect = con.prepareStatement("select * from world")
val rs = stmtSelect.executeQuery()
while (rs.next()) {
val id = rs.getInt(1)
val randomNumber = rs.getInt(2)
cache.put(id, CachedWorld(id, randomNumber))
}
}
}
override fun loadCachedWorld(id: Int): CachedWorld =
dataSource.connection.use { con ->
con.findWorld(id).let { world -> CachedWorld(world.id, world.randomNumber) }
}
override fun close() {
dataSource.close()
}
private fun Connection.findWorld(id: Int, stmtSelect: PreparedStatement = prepareStatement(SELECT_WORLD)): World {
stmtSelect.setInt(1, id)
val rs = stmtSelect.executeQuery()
rs.next()
return World(rs.getInt(1), rs.getInt(2))
}
} | bsd-3-clause | fd0fc27fe53300cbae57058811fd3658 | 35.118812 | 118 | 0.6238 | 4.541719 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/ogcapifeatures/ApiEndpoint.kt | 1 | 2008 | package io.georocket.ogcapifeatures
import com.mitchellbosecke.pebble.PebbleEngine
import com.mitchellbosecke.pebble.loader.ClasspathLoader
import io.georocket.GeoRocket
import io.georocket.http.Endpoint
import io.georocket.ogcapifeatures.views.Views
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.Router
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory
import org.yaml.snakeyaml.Yaml
import java.io.StringWriter
import java.nio.charset.StandardCharsets
/**
* An endpoint that provides the WFS 3.0 OpenAPI definition
* @author Michel Kraemer
*/
class ApiEndpoint(private val vertx: Vertx) : Endpoint {
companion object {
private val log = LoggerFactory.getLogger(ApiEndpoint::class.java)
}
private val version: String by lazy {
val u = GeoRocket::class.java.getResource("version.dat")
IOUtils.toString(u, StandardCharsets.UTF_8)
}
override suspend fun createRouter(): Router {
val router = Router.router(vertx)
router.get("/").handler { ctx ->
val response = ctx.response()
try {
response.putHeader("content-type", Views.ContentTypes.JSON)
val engine = PebbleEngine.Builder()
.loader(ClasspathLoader(this::class.java.classLoader))
.newLineTrimming(false)
.build()
val compiledTemplate = engine.getTemplate("io/georocket/ogcapifeatures/api.yaml")
// add template data
val context = mutableMapOf<String, Any>()
context["version"] = version
context["path"] = "/ogcapifeatures"
// render template
val writer = StringWriter()
compiledTemplate.evaluate(writer, context)
val output = writer.toString()
val api = JsonObject(Yaml().load<Map<String, Any>>(output))
response.end(api.encodePrettily())
} catch (t: Throwable) {
log.error("Could not provide api description", t)
response.setStatusCode(500).end()
}
}
return router
}
}
| apache-2.0 | b894ac2af57955fd8d8297ec1e1dd243 | 29.892308 | 89 | 0.697709 | 4.089613 | false | false | false | false |
paplorinc/intellij-community | plugins/settings-repository/src/git/dirCacheEditor.kt | 2 | 7347 | // 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.settingsRepository.git
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.deleteWithParentsIfEmpty
import com.intellij.util.io.exists
import com.intellij.util.io.toByteArray
import org.eclipse.jgit.dircache.BaseDirCacheEditor
import org.eclipse.jgit.dircache.DirCache
import org.eclipse.jgit.dircache.DirCacheEntry
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.FileMode
import org.eclipse.jgit.lib.Repository
import java.io.File
import java.io.FileInputStream
import java.nio.charset.StandardCharsets
import java.text.MessageFormat
import java.util.*
private val EDIT_CMP = Comparator<PathEdit> { o1, o2 ->
val a = o1.path
val b = o2.path
DirCache.cmp(a, a.size, b, b.size)
}
/**
* Don't copy edits,
* DeletePath (renamed to DeleteFile) accepts raw path
* Pass repository to apply
*/
class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) {
private val edits = edits.sortedWith(EDIT_CMP)
override fun commit(): Boolean {
if (edits.isEmpty()) {
// No changes? Don't rewrite the index.
//
cache.unlock()
return true
}
return super.commit()
}
override fun finish() {
if (!edits.isEmpty()) {
applyEdits()
replace()
}
}
private fun applyEdits() {
val maxIndex = cache.entryCount
var lastIndex = 0
for (edit in edits) {
var entryIndex = cache.findEntry(edit.path, edit.path.size)
val missing = entryIndex < 0
if (entryIndex < 0) {
entryIndex = -(entryIndex + 1)
}
val count = Math.min(entryIndex, maxIndex) - lastIndex
if (count > 0) {
fastKeep(lastIndex, count)
}
lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex)
if (edit is DeleteFile) {
continue
}
if (edit is DeleteDirectory) {
lastIndex = cache.nextEntry(edit.path, edit.path.size, entryIndex)
continue
}
if (missing) {
val entry = DirCacheEntry(edit.path)
edit.apply(entry, repository)
if (entry.rawMode == 0) {
throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.pathString))
}
fastAdd(entry)
}
else if (edit is AddFile || edit is AddLoadedFile) {
// apply to first entry and remove others
val firstEntry = cache.getEntry(entryIndex)
val entry: DirCacheEntry
if (firstEntry.isMerged) {
entry = firstEntry
}
else {
entry = DirCacheEntry(edit.path)
entry.creationTime = firstEntry.creationTime
}
edit.apply(entry, repository)
fastAdd(entry)
}
else {
// apply to all entries of the current path (different stages)
for (i in entryIndex until lastIndex) {
val entry = cache.getEntry(i)
edit.apply(entry, repository)
fastAdd(entry)
}
}
}
val count = maxIndex - lastIndex
if (count > 0) {
fastKeep(lastIndex, count)
}
}
}
interface PathEdit {
val path: ByteArray
fun apply(entry: DirCacheEntry, repository: Repository)
}
abstract class PathEditBase(final override val path: ByteArray) : PathEdit
private fun encodePath(path: String): ByteArray {
val bytes = StandardCharsets.UTF_8.encode(path).toByteArray()
if (SystemInfo.isWindows) {
for (i in 0 until bytes.size) {
if (bytes[i].toChar() == '\\') {
bytes[i] = '/'.toByte()
}
}
}
return bytes
}
class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) {
override fun apply(entry: DirCacheEntry, repository: Repository) {
val file = File(repository.workTree, pathString)
entry.fileMode = FileMode.REGULAR_FILE
val length = file.length()
entry.setLength(length)
entry.lastModified = file.lastModified()
val input = FileInputStream(file)
val inserter = repository.newObjectInserter()
try {
entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input))
inserter.flush()
}
finally {
inserter.close()
input.close()
}
}
}
class AddLoadedFile(path: String, private val content: ByteArray, private val size: Int = content.size, private val lastModified: Long = System.currentTimeMillis()) : PathEditBase(
encodePath(path)) {
override fun apply(entry: DirCacheEntry, repository: Repository) {
entry.fileMode = FileMode.REGULAR_FILE
entry.length = size
entry.lastModified = lastModified
val inserter = repository.newObjectInserter()
inserter.use {
entry.setObjectId(it.insert(Constants.OBJ_BLOB, content, 0, size))
it.flush()
}
}
}
@Suppress("FunctionName")
fun DeleteFile(path: String): DeleteFile = DeleteFile(encodePath(path))
class DeleteFile(path: ByteArray) : PathEditBase(path) {
override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete)
}
class DeleteDirectory(entryPath: String) : PathEditBase(
encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) {
override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete)
}
fun Repository.edit(edit: PathEdit) {
edit(listOf(edit))
}
fun Repository.edit(edits: List<PathEdit>) {
if (edits.isEmpty()) {
return
}
val dirCache = lockDirCache()
try {
DirCacheEditor(edits, this, dirCache, dirCache.entryCount + 4).commit()
}
finally {
dirCache.unlock()
}
}
private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) {
override fun finish() {
replace()
}
}
fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) {
val dirCache = lockDirCache()
try {
if (deletedSet != null) {
for (i in 0 until dirCache.entryCount) {
val entry = dirCache.getEntry(i)
if (entry.fileMode == FileMode.REGULAR_FILE) {
deletedSet.add(entry.pathString)
}
}
}
DirCacheTerminator(dirCache).commit()
}
finally {
dirCache.unlock()
}
if (fromWorkingTree) {
val files = workTree.listFiles { file -> file.name != Constants.DOT_GIT }
if (files != null) {
for (file in files) {
FileUtil.delete(file)
}
}
}
}
fun Repository.writePath(path: String, bytes: ByteArray, size: Int = bytes.size) {
edit(AddLoadedFile(path, bytes, size))
FileUtil.writeToFile(File(workTree, path), bytes, 0, size)
}
fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) {
edit((if (isFile) DeleteFile(path) else DeleteDirectory(path)))
if (fromWorkingTree) {
val workTree = workTree.toPath()
val ioFile = workTree.resolve(path)
if (ioFile.exists()) {
ioFile.deleteWithParentsIfEmpty(workTree, isFile)
}
}
} | apache-2.0 | 9aaed48b6161ecde69b32e327816b03c | 28.51004 | 189 | 0.676467 | 4.036813 | false | false | false | false |
Werb/MoreType | app/src/main/java/com/werb/moretype/single/SingleRegisterActivity.kt | 1 | 1997 | package com.werb.moretype.single
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import com.werb.library.MoreAdapter
import com.werb.moretype.R
import com.werb.moretype.TitleViewHolder
import com.werb.moretype.data.DataServer
import kotlinx.android.synthetic.main.activity_single_register.*
/**
* Created by wanbo on 2017/7/14.
*/
class SingleRegisterActivity : AppCompatActivity() {
private val adapter = MoreAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_register)
toolbar.setNavigationIcon(R.mipmap.ic_close_white_24dp)
toolbar.setNavigationOnClickListener { finish() }
val gridLayoutManager = androidx.recyclerview.widget.GridLayoutManager(this, 3)
val spanSizeLookup = object : SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val item = adapter.getData(position)
return if (item is SingleImage) 1 else 3
}
}
gridLayoutManager.spanSizeLookup = spanSizeLookup
single_register_list.layoutManager = gridLayoutManager
single_register_list.addItemDecoration(SingleItemDecoration(12))
/* register viewType and attach to recyclerView */
adapter.apply {
register(SingleTypeOneViewHolder::class.java)
register(SingleTypeTwoViewHolder::class.java)
register(TitleViewHolder::class.java)
attachTo(single_register_list)
}
/* load any data List or model object */
adapter.loadData(DataServer.getSingleRegisterData())
}
companion object {
fun startActivity(activity: Activity) {
activity.startActivity(Intent(activity, SingleRegisterActivity::class.java))
}
}
} | apache-2.0 | e58a08c5f232e673d8c83c39878fd6b6 | 32.864407 | 88 | 0.70656 | 4.870732 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/AfterConversionPass.kt | 2 | 1283 | // 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.j2k
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtFile
class AfterConversionPass(val project: Project, val postProcessor: PostProcessor) {
@JvmOverloads
fun run(
kotlinFile: KtFile,
converterContext: ConverterContext?,
range: TextRange?,
onPhaseChanged: ((Int, String) -> Unit)? = null
) {
postProcessor.doAdditionalProcessing(
when {
range != null -> JKPieceOfCodePostProcessingTarget(kotlinFile, range.toRangeMarker(kotlinFile))
else -> JKMultipleFilesPostProcessingTarget(listOf(kotlinFile))
},
converterContext,
onPhaseChanged
)
}
}
fun TextRange.toRangeMarker(file: KtFile): RangeMarker =
runReadAction { file.viewProvider.document!!.createRangeMarker(startOffset, endOffset) }.apply {
isGreedyToLeft = true
isGreedyToRight = true
} | apache-2.0 | 64bede2ee30ba08da51c9dea8485cec9 | 36.764706 | 158 | 0.703819 | 4.805243 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.kt | 3 | 11042 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.IdeBundle
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.components.*
import com.intellij.openapi.editor.actions.CtrlYActionChooser
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.NaturalComparator
import com.intellij.ui.AppUIUtil
import com.intellij.util.ResourceUtil
import com.intellij.util.containers.ContainerUtil
import org.jdom.Element
import java.util.function.Function
import java.util.function.Predicate
const val KEYMAPS_DIR_PATH = "keymaps"
private const val ACTIVE_KEYMAP = "active_keymap"
private const val NAME_ATTRIBUTE = "name"
@State(name = "KeymapManager", storages = [(Storage(value = "keymap.xml", roamingType = RoamingType.PER_OS))],
additionalExportDirectory = KEYMAPS_DIR_PATH,
category = SettingsCategory.KEYMAP)
class KeymapManagerImpl : KeymapManagerEx(), PersistentStateComponent<Element> {
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<KeymapManagerListener>()
private val boundShortcuts = HashMap<String, String>()
private val schemeManager: SchemeManager<Keymap>
companion object {
@JvmStatic
var isKeymapManagerInitialized = false
private set
}
init {
schemeManager = SchemeManagerFactory.getInstance().create(KEYMAPS_DIR_PATH, object : LazySchemeProcessor<Keymap, KeymapImpl>() {
override fun createScheme(dataHolder: SchemeDataHolder<KeymapImpl>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean) = KeymapImpl(name, dataHolder)
override fun onCurrentSchemeSwitched(oldScheme: Keymap?,
newScheme: Keymap?,
processChangeSynchronously: Boolean) {
fireActiveKeymapChanged(newScheme, activeKeymap)
}
override fun reloaded(schemeManager: SchemeManager<Keymap>, schemes: Collection<Keymap>) {
if (schemeManager.activeScheme == null) {
// listeners expect that event will be fired in EDT
AppUIUtil.invokeOnEdt {
schemeManager.setCurrentSchemeName(DefaultKeymap.getInstance().defaultKeymapName, true)
}
}
}
}, settingsCategory = SettingsCategory.KEYMAP)
val defaultKeymapManager = DefaultKeymap.getInstance()
val systemDefaultKeymap = WelcomeWizardUtil.getWizardMacKeymap() ?: defaultKeymapManager.defaultKeymapName
for (keymap in defaultKeymapManager.keymaps) {
schemeManager.addScheme(keymap)
if (keymap.name == systemDefaultKeymap) {
schemeManager.setCurrent(keymap, notify = false)
}
}
schemeManager.loadSchemes()
isKeymapManagerInitialized = true
if (ConfigImportHelper.isNewUser()) {
CtrlYActionChooser.askAboutShortcut()
}
fun removeKeymap(keymapName: String) {
val isCurrent = schemeManager.activeScheme?.name.equals(keymapName)
val keymap = schemeManager.removeScheme(keymapName)
if (keymap != null) {
fireKeymapRemoved(keymap)
}
DefaultKeymap.getInstance().removeKeymap(keymapName)
if (isCurrent) {
val activeKeymap = schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)
schemeManager.setCurrent(activeKeymap, notify = true, processChangeSynchronously = true)
fireActiveKeymapChanged(activeKeymap, activeKeymap)
}
}
BundledKeymapBean.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<BundledKeymapBean> {
override fun extensionAdded(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
val keymapName = getKeymapName(ep)
//if (!SystemInfo.isMac &&
// keymapName != KeymapManager.MAC_OS_X_KEYMAP &&
// keymapName != KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP &&
// DefaultKeymap.isBundledKeymapHidden(keymapName) &&
// schemeManager.findSchemeByName(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP) == null) return
val keymap = DefaultKeymap.getInstance().loadKeymap(keymapName, object : SchemeDataHolder<KeymapImpl> {
override fun read(): Element {
return JDOMUtil.load(ResourceUtil.getResourceAsBytes(getEffectiveFile(ep), pluginDescriptor.classLoader, true))
}
}, pluginDescriptor)
schemeManager.addScheme(keymap)
fireKeymapAdded(keymap)
// do no set current keymap here, consider: multi-keymap plugins, parent keymaps loading
}
override fun extensionRemoved(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
removeKeymap(getKeymapName(ep))
}
}, null)
}
private fun fireKeymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapAdded(keymap)
for (listener in listeners) {
listener.keymapAdded(keymap)
}
}
private fun fireKeymapRemoved(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapRemoved(keymap)
for (listener in listeners) {
listener.keymapRemoved(keymap)
}
}
private fun fireActiveKeymapChanged(newScheme: Keymap?, activeKeymap: Keymap?) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).activeKeymapChanged(activeKeymap)
for (listener in listeners) {
listener.activeKeymapChanged(newScheme)
}
}
override fun getAllKeymaps(): Array<Keymap> = getKeymaps(null).toTypedArray()
fun getKeymaps(additionalFilter: Predicate<Keymap>?): List<Keymap> {
return schemeManager.allSchemes.filter { !it.presentableName.startsWith("$") && (additionalFilter == null || additionalFilter.test(it)) }
}
override fun getKeymap(name: String): Keymap? = schemeManager.findSchemeByName(name)
override fun getActiveKeymap(): Keymap {
return schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)!!
}
override fun setActiveKeymap(keymap: Keymap) {
schemeManager.setCurrent(keymap)
}
override fun bindShortcuts(sourceActionId: String, targetActionId: String) {
boundShortcuts.put(targetActionId, sourceActionId)
}
override fun unbindShortcuts(targetActionId: String) {
boundShortcuts.remove(targetActionId)
}
override fun getBoundActions(): MutableSet<String> = boundShortcuts.keys
override fun getActionBinding(actionId: String): String? {
var visited: MutableSet<String>? = null
var id = actionId
while (true) {
val next = boundShortcuts.get(id) ?: break
if (visited == null) {
visited = HashSet()
}
id = next
if (!visited.add(id)) {
break
}
}
return if (id == actionId) null else id
}
override fun getSchemeManager(): SchemeManager<Keymap> = schemeManager
fun setKeymaps(keymaps: List<Keymap>, active: Keymap?, removeCondition: Predicate<Keymap>?) {
schemeManager.setSchemes(keymaps, active, removeCondition)
fireActiveKeymapChanged(active, activeKeymap)
}
override fun getState(): Element {
val result = Element("state")
schemeManager.activeScheme?.let {
if (it.name != DefaultKeymap.getInstance().defaultKeymapName) {
val e = Element(ACTIVE_KEYMAP)
e.setAttribute(NAME_ATTRIBUTE, it.name)
result.addContent(e)
}
}
return result
}
override fun loadState(state: Element) {
val child = state.getChild(ACTIVE_KEYMAP)
val activeKeymapName = child?.getAttributeValue(NAME_ATTRIBUTE)
if (!activeKeymapName.isNullOrBlank()) {
schemeManager.currentSchemeName = activeKeymapName
if (schemeManager.currentSchemeName != activeKeymapName) {
notifyAboutMissingKeymap(activeKeymapName, IdeBundle.message("notification.content.cannot.find.keymap", activeKeymapName), false)
}
}
}
@Suppress("OverridingDeprecatedMember")
override fun addKeymapManagerListener(listener: KeymapManagerListener, parentDisposable: Disposable) {
pollQueue()
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(KeymapManagerListener.TOPIC, listener)
}
private fun pollQueue() {
listeners.removeAll { it is WeakKeymapManagerListener && it.isDead }
}
@Suppress("OverridingDeprecatedMember")
override fun removeKeymapManagerListener(listener: KeymapManagerListener) {
pollQueue()
listeners.remove(listener)
}
override fun addWeakListener(listener: KeymapManagerListener) {
pollQueue()
listeners.add(WeakKeymapManagerListener(this, listener))
}
override fun removeWeakListener(listenerToRemove: KeymapManagerListener) {
listeners.removeAll { it is WeakKeymapManagerListener && it.isWrapped(listenerToRemove) }
}
}
internal val keymapComparator: Comparator<Keymap?> by lazy {
val defaultKeymapName = DefaultKeymap.getInstance().defaultKeymapName
Comparator { keymap1, keymap2 ->
if (keymap1 === keymap2) return@Comparator 0
if (keymap1 == null) return@Comparator - 1
if (keymap2 == null) return@Comparator 1
val parent1 = (if (!keymap1.canModify()) null else keymap1.parent) ?: keymap1
val parent2 = (if (!keymap2.canModify()) null else keymap2.parent) ?: keymap2
if (parent1 === parent2) {
when {
!keymap1.canModify() -> - 1
!keymap2.canModify() -> 1
else -> compareByName(keymap1, keymap2, defaultKeymapName)
}
}
else {
compareByName(parent1, parent2, defaultKeymapName)
}
}
}
private fun compareByName(keymap1: Keymap, keymap2: Keymap, defaultKeymapName: String): Int {
return when (defaultKeymapName) {
keymap1.name -> -1
keymap2.name -> 1
else -> NaturalComparator.INSTANCE.compare(keymap1.presentableName, keymap2.presentableName)
}
} | apache-2.0 | 9f32872f5764ed1db6698e7693b2a156 | 38.580645 | 141 | 0.723782 | 4.971634 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.kt | 1 | 48878 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.openapi.project.impl
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.configurationStore.saveSettings
import com.intellij.conversion.CannotConvertException
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.*
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.impl.*
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.lightEdit.LightEditUtil
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.*
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectImpl.Companion.preloadServicesAndCreateComponents
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isLoadedFromCacheButHasNoModules
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.IdeUICustomization
import com.intellij.util.ArrayUtil
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.context.Context
import io.opentelemetry.extension.kotlin.asContextElement
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.io.File
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.CancellationException
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.coroutineContext
@Suppress("OVERRIDE_DEPRECATION")
@Internal
open class ProjectManagerImpl : ProjectManagerEx(), Disposable {
companion object {
@TestOnly
@JvmStatic
fun isLight(project: Project): Boolean {
return project is ProjectEx && project.isLight
}
private fun openProjectInstanceCommand(
projectStoreBaseDir: Path,
isChildProcess: Boolean,
): List<String> {
val customProperties = mapOf(
PathManager.PROPERTY_SYSTEM_PATH to PathManager.getSystemDir(),
PathManager.PROPERTY_CONFIG_PATH to PathManager.getConfigDir(),
PathManager.PROPERTY_LOG_PATH to PathManager.getLogDir(),
PathManager.PROPERTY_PLUGINS_PATH to PathManager.getPluginsDir(),
).mapValuesTo(mutableMapOf()) { (key, value) ->
val pathResolver: (String) -> Path = if (isChildProcess) value::resolveSibling else value::resolve
"-D$key=${pathResolver("perProject_${projectStoreBaseDir.fileName}")}"
}
val command = ArrayList<String>()
command += """${System.getProperty("java.home")}${File.separatorChar}bin${File.separatorChar}java"""
command += "-cp"
command += System.getProperty("java.class.path")
for (vmOption in VMOptions.readOptions("", true)) {
command += vmOption.asPatchedAgentLibOption()
?: vmOption.asPatchedVMOption("splash", "false")
?: vmOption.asPatchedVMOption("nosplash", "true")
?: vmOption.asPatchedVMOption(ConfigImportHelper.SHOW_IMPORT_CONFIG_DIALOG_PROPERTY, "default-production")
?: customProperties.keys.firstOrNull { vmOption.isVMOption(it) }?.let { customProperties.remove(it) }
?: vmOption
}
command += customProperties.values
command += System.getProperty("idea.main.class.name", "com.intellij.idea.Main")
command += projectStoreBaseDir.toString()
return command
}
private fun String.isVMOption(key: String) = startsWith("-D$key=")
private fun String.asPatchedVMOption(key: String, value: String): String? {
return if (isVMOption(key)) replaceAfter('=', value) else null
}
private fun String.asPatchedAgentLibOption(): String? {
return if (startsWith("-agentlib:jdwp=")) {
splitToSequence(",").joinToString(",") { option ->
val (key, value) = option.split('=', limit = 2)
val newValue = when (key) {
"address" -> patchedDebugPort(value)
"server" -> "y"
"suspend" -> "n"
else -> value
}
"$key=$newValue"
}
}
else {
null
}
}
private fun patchedDebugPort(address: String): String? {
return try {
val beginIndex = address.indexOf(':') + 1
val port = Integer.parseInt(
address,
beginIndex,
address.length,
10,
) + 1
address.substring(0, beginIndex) + port
}
catch (e: NumberFormatException) {
null
}
}
}
private var openProjects = arrayOf<Project>() // guarded by lock
private val openProjectByHash = ConcurrentHashMap<String, Project>()
private val lock = Any()
// we cannot use the same approach to migrate to message bus as CompilerManagerImpl because of method canCloseProject
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<ProjectManagerListener>()
private val defaultProject = DefaultProject()
private val excludeRootsCache: ExcludeRootsCache
private var getAllExcludedUrlsCallback: Runnable? = null
init {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(TOPIC, object : ProjectManagerListener {
@Suppress("removal")
override fun projectOpened(project: Project) {
for (listener in getAllListeners(project)) {
try {
@Suppress("DEPRECATION", "removal")
listener.projectOpened(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosed(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosed(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosing(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosing(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosingBeforeSave(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosingBeforeSave(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
})
excludeRootsCache = ExcludeRootsCache(connection)
}
@TestOnly
fun testOnlyGetExcludedUrlsCallback(parentDisposable: Disposable, callback: Runnable) {
check(getAllExcludedUrlsCallback == null) { "This method is not reentrant. Expected null but got $getAllExcludedUrlsCallback" }
getAllExcludedUrlsCallback = callback
Disposer.register(parentDisposable) { getAllExcludedUrlsCallback = null }
}
override val allExcludedUrls: List<String>
get() {
val callback = getAllExcludedUrlsCallback
callback?.run()
return excludeRootsCache.excludedUrls
}
override fun dispose() {
ApplicationManager.getApplication().assertWriteAccessAllowed()
// dispose manually, because TimedReference.dispose() can already be called (in Timed.disposeTimed()) and then default project resurrected
Disposer.dispose(defaultProject)
}
override fun loadProject(path: Path): Project {
check(!ApplicationManager.getApplication().isDispatchThread)
val project = ProjectImpl(filePath = path, projectName = null)
val modalityState = CoreProgressManager.getCurrentThreadProgressModality()
runBlocking(modalityState.asContextElement()) {
initProject(
file = path,
project = project,
isRefreshVfsNeeded = true,
preloadServices = true,
template = null,
isTrustCheckNeeded = false,
)
}
return project
}
override val isDefaultProjectInitialized: Boolean
get() = defaultProject.isCached
override fun getDefaultProject(): Project {
LOG.assertTrue(!ApplicationManager.getApplication().isDisposed, "Application has already been disposed!")
// call instance method to reset timeout
// re-instantiate if needed
val bus = defaultProject.messageBus
LOG.assertTrue(!bus.isDisposed)
LOG.assertTrue(defaultProject.isCached)
return defaultProject
}
@TestOnly
@Internal
fun disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests() {
defaultProject.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests()
}
override fun getOpenProjects(): Array<Project> = synchronized(lock) { openProjects }
override fun isProjectOpened(project: Project): Boolean = synchronized(lock) { openProjects.contains(project) }
protected fun addToOpened(project: Project): Boolean {
assert(!project.isDisposed) { "Must not open already disposed project" }
synchronized(lock) {
if (isProjectOpened(project)) {
return false
}
openProjects += project
}
updateTheOnlyProjectField()
openProjectByHash.put(project.locationHash, project)
return true
}
fun updateTheOnlyProjectField() {
val isLightEditActive = LightEditService.getInstance().project != null
if (ApplicationManager.getApplication().isUnitTestMode && !ApplicationManagerEx.isInStressTest()) {
// switch off optimization in non-stress tests to assert they don't query getProject for invalid PsiElements
ProjectCoreUtil.updateInternalTheOnlyProjectFieldTemporarily(null)
}
else {
val isDefaultInitialized = isDefaultProjectInitialized
synchronized(lock) {
val theOnlyProject = if (openProjects.size == 1 && !isDefaultInitialized && !isLightEditActive) openProjects.first() else null
ProjectCoreUtil.updateInternalTheOnlyProjectFieldTemporarily(theOnlyProject)
}
}
}
private fun removeFromOpened(project: Project) {
synchronized(lock) {
openProjects = ArrayUtil.remove(openProjects, project)
// remove by value and not by key!
openProjectByHash.values.remove(project)
}
}
override fun findOpenProjectByHash(locationHash: String?): Project? = openProjectByHash.get(locationHash)
override fun reloadProject(project: Project) {
StoreReloadManager.getInstance().reloadProject(project)
}
override fun closeProject(project: Project): Boolean {
return closeProject(project = project, saveProject = true, dispose = false, checkCanClose = true)
}
override fun forceCloseProject(project: Project, save: Boolean): Boolean {
return closeProject(project = project, saveProject = save, checkCanClose = false)
}
override suspend fun forceCloseProjectAsync(project: Project, save: Boolean): Boolean {
LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread)
if (save) {
// HeadlessSaveAndSyncHandler doesn't save, but if `save` is requested,
// it means that we must save in any case (for example, see GradleSourceSetsTest)
saveSettings(project, forceSavingAllSettings = true)
}
return withContext(Dispatchers.EDT) {
if (project.isDisposed) {
return@withContext false
}
closeProject(project = project, saveProject = save, checkCanClose = false)
}
}
// return true if successful
override fun closeAndDisposeAllProjects(checkCanClose: Boolean): Boolean {
var projects = openProjects
LightEditUtil.getProjectIfCreated()?.let {
projects += it
}
for (project in projects) {
if (!closeProject(project = project, checkCanClose = checkCanClose)) {
return false
}
}
return true
}
protected open fun closeProject(project: Project, saveProject: Boolean = true, dispose: Boolean = true, checkCanClose: Boolean): Boolean {
val app = ApplicationManager.getApplication()
check(!app.isWriteAccessAllowed) {
"Must not call closeProject() from under write action because fireProjectClosing() listeners must have a chance to do something useful"
}
app.assertIsWriteThread()
@Suppress("TestOnlyProblems")
if (isLight(project)) {
// if we close project at the end of the test, just mark it closed;
// if we are shutting down the entire test framework, proceed to full dispose
val projectImpl = project as ProjectImpl
if (!projectImpl.isTemporarilyDisposed) {
ApplicationManager.getApplication().runWriteAction {
projectImpl.disposeEarlyDisposable()
projectImpl.setTemporarilyDisposed(true)
removeFromOpened(project)
}
updateTheOnlyProjectField()
return true
}
projectImpl.setTemporarilyDisposed(false)
}
else if (!isProjectOpened(project) && !LightEdit.owns(project)) {
if (dispose) {
if (project is ComponentManagerImpl) {
project.stopServicePreloading()
}
ApplicationManager.getApplication().runWriteAction {
if (project is ProjectImpl) {
project.disposeEarlyDisposable()
project.startDispose()
}
Disposer.dispose(project)
}
}
return true
}
if (checkCanClose && !canClose(project)) {
return false
}
if (project is ComponentManagerImpl) {
(project as ComponentManagerImpl).stopServicePreloading()
}
publisher.projectClosingBeforeSave(project)
if (saveProject) {
FileDocumentManager.getInstance().saveAllDocuments()
SaveAndSyncHandler.getInstance().saveSettingsUnderModalProgress(project)
}
if (checkCanClose && !ensureCouldCloseIfUnableToSave(project)) {
return false
}
// somebody can start progress here, do not wrap in write action
fireProjectClosing(project)
app.runWriteAction {
removeFromOpened(project)
if (project is ProjectImpl) {
// ignore dispose flag (dispose is passed only via deprecated API that used only by some 3d-party plugins)
project.disposeEarlyDisposable()
if (dispose) {
project.startDispose()
}
}
fireProjectClosed(project)
if (!ApplicationManagerEx.getApplicationEx().isExitInProgress) {
ZipHandler.clearFileAccessorCache()
}
LaterInvocator.purgeExpiredItems()
if (dispose) {
Disposer.dispose(project)
}
}
return true
}
override fun closeAndDispose(project: Project) = closeProject(project, checkCanClose = true)
@Suppress("removal")
override fun addProjectManagerListener(listener: ProjectManagerListener) {
listeners.add(listener)
}
override fun addProjectManagerListener(listener: VetoableProjectManagerListener) {
listeners.add(listener)
}
@Suppress("removal")
override fun removeProjectManagerListener(listener: ProjectManagerListener) {
val removed = listeners.remove(listener)
LOG.assertTrue(removed)
}
override fun removeProjectManagerListener(listener: VetoableProjectManagerListener) {
val removed = listeners.remove(listener)
LOG.assertTrue(removed)
}
override fun addProjectManagerListener(project: Project, listener: ProjectManagerListener) {
if (project.isDefault) {
// nothing happens with default project
return
}
val listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY)
?: (project as UserDataHolderEx).putUserDataIfAbsent(LISTENERS_IN_PROJECT_KEY,
ContainerUtil.createLockFreeCopyOnWriteList())
listeners.add(listener)
}
override fun removeProjectManagerListener(project: Project, listener: ProjectManagerListener) {
if (project.isDefault) {
// nothing happens with default project
return
}
val listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY)
LOG.assertTrue(listeners != null)
val removed = listeners!!.remove(listener)
LOG.assertTrue(removed)
}
override fun canClose(project: Project): Boolean {
if (LOG.isDebugEnabled) {
LOG.debug("enter: canClose()")
}
for (handler in CLOSE_HANDLER_EP.iterable) {
if (handler == null) {
break
}
try {
if (!handler.canClose(project)) {
LOG.debug("close canceled by $handler")
return false
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
for (listener in getAllListeners(project)) {
try {
@Suppress("DEPRECATION", "removal")
val canClose = if (listener is VetoableProjectManagerListener) listener.canClose(project) else listener.canCloseProject(project)
if (!canClose) {
LOG.debug("close canceled by $listener")
return false
}
}
catch (e: Throwable) {
handleListenerError(e, listener)
}
}
return true
}
private fun getAllListeners(project: Project): List<ProjectManagerListener> {
val projectLevelListeners = getListeners(project)
// order is critically important due to backward compatibility - project level listeners must be first
return when {
projectLevelListeners.isEmpty() -> listeners
listeners.isEmpty() -> projectLevelListeners
else -> projectLevelListeners + listeners
}
}
@Suppress("OVERRIDE_DEPRECATION")
final override fun createProject(name: String?, path: String): Project? {
ApplicationManager.getApplication().assertIsDispatchThread()
return newProject(toCanonicalName(path), OpenProjectTask {
isNewProject = true
runConfigurators = false
projectName = name
})
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return runUnderModalProgressIfIsEdt { openProjectAsync(projectStoreBaseDir, options) }
}
final override suspend fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
val applicationEx = ApplicationManagerEx.getApplicationEx()
if (LOG.isDebugEnabled && !applicationEx.isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project as Project)) {
LOG.info("Project is already opened -> return null")
return null
}
if (!checkTrustedState(projectStoreBaseDir)) {
LOG.info("Project is not trusted -> return null")
return null
}
val isChildProcess = isChildProcessPath(PathManager.getSystemDir())
val shouldOpenInChildProcess = !isChildProcess && IS_PER_PROJECT_INSTANCE_ENABLED
|| isChildProcess && openProjects.isNotEmpty()
if (shouldOpenInChildProcess) {
try {
withContext(Dispatchers.IO) {
ProcessBuilder(openProjectInstanceCommand(projectStoreBaseDir, isChildProcess))
.redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.appendTo(PathManager.getLogDir().resolve("idea.log").toFile()))
.start()
.also {
LOG.info("Child process started, PID: ${it.pid()}")
}
}
withContext(Dispatchers.EDT) {
if (!isChildProcess) {
applicationEx.exit(true, true)
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Exception) {
LOG.error(e)
}
return null
}
val activity = StartUpMeasurer.startActivity("project opening preparation")
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects.last()
}
}
if (checkExistingProjectOnOpen(projectToClose, options, projectStoreBaseDir)) {
LOG.info("Project check is not succeeded -> return null")
return null
}
}
}
return doOpenAsync(options, projectStoreBaseDir, activity)
}
private suspend fun doOpenAsync(options: OpenProjectTask, projectStoreBaseDir: Path, activity: Activity): Project? {
val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) {
ProjectFrameAllocator(options)
}
else {
ProjectUiFrameAllocator(options, projectStoreBaseDir)
}
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
var module: Module? = null
var result: Project? = null
var reopeningEditorJob: Deferred<Job?>? = null
try {
frameAllocator.run { saveTemplateJob ->
activity.end()
val project = options.project ?: prepareProject(options, projectStoreBaseDir, saveTemplateJob)
result = project
// must be under try-catch to dispose project on beforeOpen or preparedToOpen callback failures
if (options.project == null) {
val beforeOpen = options.beforeOpen
if (beforeOpen != null && !beforeOpen(project)) {
throw CancellationException("beforeOpen callback returned false")
}
if (options.runConfigurators &&
(options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty()) ||
project.isLoadedFromCacheButHasNoModules()) {
module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(
baseDir = projectStoreBaseDir,
project = project,
newProject = options.isProjectCreatedWithWizard
)
options.preparedToOpen?.invoke(module!!)
}
}
reopeningEditorJob = async {
service<StartUpPerformanceService>().addActivityListener(project)
frameAllocator.projectLoaded(project)
}
if (!addToOpened(project)) {
throw CancellationException("project is already opened")
}
tracer.spanBuilder("open project")
.setAttribute(AttributeKey.stringKey("project"), project.name)
.useWithScope {
runInitProjectActivities(project)
}
}
}
catch (e: CancellationException) {
withContext(NonCancellable) {
result?.let { project ->
try {
withContext(Dispatchers.EDT) {
closeProject(project, saveProject = false, checkCanClose = false)
}
}
catch (secondException: Throwable) {
e.addSuppressed(secondException)
}
}
failedToOpenProject(frameAllocator = frameAllocator, exception = null, options = options)
}
throw e
}
catch (e: Throwable) {
result?.let { project ->
try {
withContext(Dispatchers.EDT) {
closeProject(project, saveProject = false, checkCanClose = false)
}
}
catch (secondException: Throwable) {
e.addSuppressed(secondException)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
throw e
}
LOG.error(e)
failedToOpenProject(frameAllocator = frameAllocator, exception = e, options = options)
return null
}
finally {
disableAutoSaveToken.finish()
}
val project = result!!
// wait for reopeningEditorJob
// 1. part of open project task
// 2. runStartupActivities can consume a lot of CPU and editor restoring can be delayed, but it is a bad UX
runActivity("editor reopening waiting") {
reopeningEditorJob?.await()?.join()
}
if (isRunStartUpActivitiesEnabled(project)) {
(StartupManager.getInstance(project) as StartupManagerImpl).runStartupActivities()
}
LifecycleUsageTriggerCollector.onProjectOpened(project)
options.callback?.projectOpened(project, module ?: ModuleManager.getInstance(project).modules[0])
return project
}
private suspend fun failedToOpenProject(frameAllocator: ProjectFrameAllocator, exception: Throwable?, options: OpenProjectTask) {
frameAllocator.projectNotLoaded(cannotConvertException = exception as? CannotConvertException)
try {
ApplicationManager.getApplication().messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
}
catch (secondException: Throwable) {
LOG.error(secondException)
}
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
}
/**
* Checks if the project path is trusted, and shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private suspend fun checkTrustedState(projectStoreBaseDir: Path): Boolean {
val trustedState = TrustedPaths.getInstance().getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
// the trusted state of this project path is already known => proceed with opening
return true
}
if (isProjectImplicitlyTrusted(projectStoreBaseDir)) {
return true
}
// check if the project trusted state could be known from the previous IDE version
val metaInfo = (RecentProjectsManager.getInstance() as RecentProjectsManagerBase).getProjectMetaInfo(projectStoreBaseDir)
val projectId = metaInfo?.projectWorkspaceId
val productWorkspaceFile = PathManager.getConfigDir().resolve("workspace").resolve("$projectId.xml")
if (projectId != null && productWorkspaceFile.exists()) {
// this project is in recent projects => it was opened on this computer before
// => most probably we already asked about its trusted state before
// the only exception is: the project stayed in the UNKNOWN state in the previous version because it didn't utilize any dangerous features
// in this case we will ask since no UNKNOWN state is allowed, but on a later stage, when we'll be able to look into the project-wide storage
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
override fun newProject(file: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(file)
val project = instantiateProject(file, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
runUnderModalProgressIfIsEdt {
initProject(
file = file,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = template,
isTrustCheckNeeded = false,
)
}
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
override suspend fun newProjectAsync(file: Path, options: OpenProjectTask): Project {
withContext(Dispatchers.IO) {
removeProjectConfigurationAndCaches(file)
}
val project = instantiateProject(file, options)
initProject(
file = file,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = if (options.useDefaultProjectAsTemplate) defaultProject else null,
isTrustCheckNeeded = false,
)
project.setTrusted(true)
return project
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startActivity("project instantiation")
val project = ProjectImpl(filePath = projectStoreBaseDir, projectName = options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private suspend fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path, saveTemplateJob: Job?): Project {
if (options.isNewProject) {
withContext(Dispatchers.IO) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
}
val project = instantiateProject(projectStoreBaseDir, options)
saveTemplateJob?.join()
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(file = projectStoreBaseDir,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = template,
isTrustCheckNeeded = false)
project.putUserData(PlatformProjectOpenProcessor.PROJECT_NEWLY_OPENED, true)
return project
}
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
conversionResult = runActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
throw CancellationException("ConversionResult.openingIsCanceled() returned true")
}
}
}
val project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(file = projectStoreBaseDir,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = null,
isTrustCheckNeeded = true)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
return project
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
private suspend fun checkExistingProjectOnOpen(projectToClose: Project, options: OpenProjectTask, projectDir: Path?): Boolean {
val isValidProject = projectDir != null && ProjectUtilCore.isValidProjectPath(projectDir)
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || GeneralSettings.getInstance().confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
when (withContext(Dispatchers.EDT) { ProjectUtil.confirmOpenOrAttachProject() }) {
-1 -> {
return true
}
GeneralSettings.OPEN_PROJECT_SAME_WINDOW -> {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
return true
}
}
GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH -> {
if (withContext(Dispatchers.EDT) { PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, options.callback) }) {
return true
}
}
}
}
else {
val mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH && projectDir != null &&
withContext(Dispatchers.EDT) { PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, options.callback) }) {
return true
}
val projectNameValue = options.projectName ?: projectDir?.fileName?.toString() ?: projectDir?.toString()
val exitCode = confirmOpenNewProject(options.copy(projectName = projectNameValue))
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
return true
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
return true
}
}
return false
}
private suspend fun closeAndDisposeKeepingFrame(project: Project): Boolean {
return withContext(Dispatchers.EDT) {
(WindowManager.getInstance() as WindowManagerImpl).withFrameReuseEnabled().use {
closeProject(project, checkCanClose = true)
}
}
}
}
private val tracer by lazy { TraceManager.getTracer("projectManager") }
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
return "$message (cause: ${message(e.cause ?: return message)})"
}
@Internal
@VisibleForTesting
fun CoroutineScope.runInitProjectActivities(project: Project) {
val traceContext = Context.current()
launch(traceContext.asContextElement()) {
(StartupManager.getInstance(project) as StartupManagerImpl).initProject(null)
}
val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue")
launchAndMeasure("projectOpened event executing", Dispatchers.EDT) {
waitEdtActivity.end()
tracer.spanBuilder("projectOpened event executing").setParent(traceContext).useWithScope {
@Suppress("DEPRECATION", "removal")
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
}
}
@Suppress("DEPRECATION")
val projectComponents = (project as ComponentManagerImpl)
.collectInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java)
if (projectComponents.isEmpty()) {
return
}
launchAndMeasure("projectOpened component executing", Dispatchers.EDT) {
for (component in projectComponents) {
try {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER)
component.projectOpened()
componentActivity.end()
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
private val LOG = logger<ProjectManagerImpl>()
private val LISTENERS_IN_PROJECT_KEY = Key.create<MutableList<ProjectManagerListener>>("LISTENERS_IN_PROJECT_KEY")
private val CLOSE_HANDLER_EP = ExtensionPointName<ProjectCloseHandler>("com.intellij.projectCloseHandler")
private fun getListeners(project: Project): List<ProjectManagerListener> {
return project.getUserData(LISTENERS_IN_PROJECT_KEY) ?: return emptyList()
}
private val publisher: ProjectManagerListener
get() = ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC)
private fun handleListenerError(e: Throwable, listener: ProjectManagerListener) {
if (e is ProcessCanceledException || e is CancellationException) {
throw e
}
else {
LOG.error("From the listener $listener (${listener.javaClass})", e)
}
}
private fun fireProjectClosing(project: Project) {
if (LOG.isDebugEnabled) {
LOG.debug("enter: fireProjectClosing()")
}
try {
publisher.projectClosing(project)
} catch (e: Throwable) {
LOG.warn("Failed to publish projectClosing(project) event", e)
}
}
private fun fireProjectClosed(project: Project) {
if (LOG.isDebugEnabled) {
LOG.debug("projectClosed")
}
LifecycleUsageTriggerCollector.onProjectClosed(project)
publisher.projectClosed(project)
@Suppress("DEPRECATION")
val projectComponents = (project as ComponentManagerImpl)
.collectInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java)
// see "why is called after message bus" in the fireProjectOpened
for (i in projectComponents.indices.reversed()) {
val component = projectComponents.get(i)
try {
component.projectClosed()
}
catch (e: Throwable) {
LOG.error(component.toString(), e)
}
}
}
private fun ensureCouldCloseIfUnableToSave(project: Project): Boolean {
val notificationManager = ApplicationManager.getApplication().getServiceIfCreated(NotificationsManager::class.java) ?: return true
val notifications = notificationManager.getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
return true
}
val message: @NlsContexts.DialogMessage StringBuilder = StringBuilder()
message.append("${ApplicationNamesInfo.getInstance().productName} was unable to save some project files," +
"\nare you sure you want to close this project anyway?")
message.append("\n\nRead-only files:\n")
var count = 0
val files = notifications.first().files
for (file in files) {
if (count == 10) {
message.append('\n').append("and ").append(files.size - count).append(" more").append('\n')
}
else {
message.append(file.path).append('\n')
count++
}
}
@Suppress("HardCodedStringLiteral")
return Messages.showYesNoDialog(project, message.toString(),
IdeUICustomization.getInstance().projectMessage("dialog.title.unsaved.project"),
Messages.getWarningIcon()) == Messages.YES
}
class UnableToSaveProjectNotification(project: Project, readOnlyFiles: List<VirtualFile>) : Notification("Project Settings",
IdeUICustomization.getInstance().projectMessage(
"notification.title.cannot.save.project"),
IdeBundle.message(
"notification.content.unable.to.save.project.files"),
NotificationType.ERROR) {
private var project: Project?
var files: List<VirtualFile>
init {
@Suppress("DEPRECATION")
setListener { notification, _ ->
val unableToSaveProjectNotification = notification as UnableToSaveProjectNotification
val p = unableToSaveProjectNotification.project
notification.expire()
if (p != null && !p.isDisposed) {
p.save()
}
}
this.project = project
files = readOnlyFiles
}
override fun expire() {
project = null
super.expire()
}
}
private fun toCanonicalName(filePath: String): Path {
val file = Path.of(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (ignore: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
/**
* Checks if the project was trusted using the previous API.
* Migrates the setting to the new API, shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private suspend fun checkOldTrustedStateAndMigrate(project: Project, projectStoreBaseDir: Path): Boolean {
val trustedPaths = TrustedPaths.getInstance()
val trustedState = trustedPaths.getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
return true
}
@Suppress("DEPRECATION")
val previousTrustedState = project.service<TrustedProjectSettings>().trustedState
if (previousTrustedState != ThreeState.UNSURE) {
// we were asking about this project in the previous IDE version => migrate
trustedPaths.setProjectPathTrusted(projectStoreBaseDir, previousTrustedState.toBoolean())
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
private suspend fun initProject(file: Path,
project: ProjectImpl,
isRefreshVfsNeeded: Boolean,
preloadServices: Boolean,
template: Project?,
isTrustCheckNeeded: Boolean) {
LOG.assertTrue(!project.isDefault)
try {
coroutineContext.ensureActive()
val registerComponentsActivity = createActivity(project) { "project ${StartUpMeasurer.Activities.REGISTER_COMPONENTS_SUFFIX}" }
project.registerComponents()
registerComponentsActivity?.end()
if (ApplicationManager.getApplication().isUnitTestMode) {
@Suppress("TestOnlyProblems")
for (listener in ProjectServiceContainerCustomizer.getEp().extensionList) {
listener.serviceRegistered(project)
}
}
coroutineContext.ensureActive()
project.componentStore.setPath(file, isRefreshVfsNeeded, template)
coroutineScope {
val isTrusted = async { !isTrustCheckNeeded || checkOldTrustedStateAndMigrate(project, file) }
projectInitListeners {
it.execute(project)
}
preloadServicesAndCreateComponents(project, preloadServices)
if (!isTrusted.await()) {
throw CancellationException("not trusted")
}
}
}
catch (initThrowable: Throwable) {
try {
withContext(Dispatchers.EDT + NonCancellable) {
ApplicationManager.getApplication().runWriteAction { Disposer.dispose(project) }
}
}
catch (disposeThrowable: Throwable) {
initThrowable.addSuppressed(disposeThrowable)
}
throw initThrowable
}
}
@Suppress("DuplicatedCode")
private suspend fun confirmOpenNewProject(options: OpenProjectTask): Int {
if (ApplicationManager.getApplication().isUnitTestMode) {
return GeneralSettings.OPEN_PROJECT_NEW_WINDOW
}
var mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
val message = if (options.projectName == null) {
IdeBundle.message("prompt.open.project.in.new.frame")
}
else {
IdeBundle.message("prompt.open.project.with.name.in.new.frame", options.projectName)
}
val openInExistingFrame = withContext(Dispatchers.EDT) {
if (options.isNewProject)
MessageDialogBuilder.yesNoCancel(IdeUICustomization.getInstance().projectMessage("title.new.project"), message)
.yesText(IdeBundle.message("button.existing.frame"))
.noText(IdeBundle.message("button.new.frame"))
.doNotAsk(ProjectNewWindowDoNotAskOption())
.guessWindowAndAsk()
else
MessageDialogBuilder.yesNoCancel(IdeUICustomization.getInstance().projectMessage("title.open.project"), message)
.yesText(IdeBundle.message("button.existing.frame"))
.noText(IdeBundle.message("button.new.frame"))
.doNotAsk(ProjectNewWindowDoNotAskOption())
.guessWindowAndAsk()
}
mode = when (openInExistingFrame) {
Messages.YES -> GeneralSettings.OPEN_PROJECT_SAME_WINDOW
Messages.NO -> GeneralSettings.OPEN_PROJECT_NEW_WINDOW
else -> Messages.CANCEL
}
if (mode != Messages.CANCEL) {
LifecycleUsageTriggerCollector.onProjectFrameSelected(mode)
}
}
return mode
}
private inline fun createActivity(project: ProjectImpl, message: () -> String): Activity? {
return if (!StartUpMeasurer.isEnabled() || project.isDefault) null else StartUpMeasurer.startActivity(message(), ActivityCategory.DEFAULT)
}
internal suspend inline fun projectInitListeners(crossinline executor: suspend (ProjectServiceContainerInitializedListener) -> Unit) {
val extensionArea = ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl
val ep = extensionArea
.getExtensionPoint<ProjectServiceContainerInitializedListener>("com.intellij.projectServiceContainerInitializedListener")
for (adapter in ep.sortedAdapters) {
val pluginDescriptor = adapter.pluginDescriptor
if (!isCorePlugin(pluginDescriptor)) {
LOG.error(PluginException("Plugin $pluginDescriptor is not approved to add ${ep.name}", pluginDescriptor.pluginId))
continue
}
try {
executor(adapter.createInstance(ep.componentManager) ?: continue)
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
internal fun isCorePlugin(descriptor: PluginDescriptor): Boolean {
val id = descriptor.pluginId
return id == PluginManagerCore.CORE_ID ||
// K/N Platform Deps is a repackaged Java plugin
id.idString == "com.intellij.kotlinNative.platformDeps"
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@Internal
interface ProjectServiceContainerInitializedListener {
/**
* Invoked after container configured.
*/
suspend fun execute(project: Project)
}
@TestOnly
interface ProjectServiceContainerCustomizer {
companion object {
@TestOnly
fun getEp(): ExtensionPointImpl<ProjectServiceContainerCustomizer> {
return (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint("com.intellij.projectServiceContainerCustomizer")
}
}
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceRegistered(project: Project)
} | apache-2.0 | 4a0e6841ebe55cfe072a0b1a12ec8848 | 35.422504 | 160 | 0.692479 | 5.1904 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/agenda/AgendaHeadersDecoration.kt | 3 | 5104 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.agenda
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.text.Layout.Alignment.ALIGN_CENTER
import android.text.StaticLayout
import android.text.TextPaint
import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.core.content.res.getColorOrThrow
import androidx.core.content.res.getDimensionOrThrow
import androidx.core.content.res.getDimensionPixelSizeOrThrow
import androidx.core.content.res.getResourceIdOrThrow
import androidx.core.graphics.withTranslation
import androidx.core.view.forEach
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.RecyclerView.State
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.model.Block
import com.google.samples.apps.iosched.shared.util.TimeUtils
import com.google.samples.apps.iosched.util.newStaticLayout
import kotlin.math.ceil
import org.threeten.bp.ZonedDateTime
/**
* A [RecyclerView.ItemDecoration] which draws sticky headers marking the days in a given list of
* [Block]s. It also inserts gaps between days.
*/
class AgendaHeadersDecoration(
context: Context,
blocks: List<Block>,
inConferenceTimeZone: Boolean
) : ItemDecoration() {
private val paint: TextPaint
private val textWidth: Int
private val decorHeight: Int
private val verticalBias: Float
init {
val attrs = context.obtainStyledAttributes(
R.style.Widget_IOSched_DateHeaders,
R.styleable.DateHeader
)
paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply {
color = attrs.getColorOrThrow(R.styleable.DateHeader_android_textColor)
textSize = attrs.getDimensionOrThrow(R.styleable.DateHeader_android_textSize)
try {
typeface = ResourcesCompat.getFont(
context,
attrs.getResourceIdOrThrow(R.styleable.DateHeader_android_fontFamily)
)
} catch (_: Exception) {
// ignore
}
}
textWidth = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_width)
val height = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_height)
val minHeight = ceil(paint.textSize).toInt()
decorHeight = Math.max(height, minHeight)
verticalBias = attrs.getFloat(R.styleable.DateHeader_verticalBias, 0.5f).coerceIn(0f, 1f)
attrs.recycle()
}
// Get the block index:day and create header layouts for each
private val daySlots: Map<Int, StaticLayout> =
indexAgendaHeaders(blocks).map {
it.first to createHeader(context, it.second, inConferenceTimeZone)
}.toMap()
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: State) {
val position = parent.getChildAdapterPosition(view)
outRect.top = if (daySlots.containsKey(position)) decorHeight else 0
}
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) {
val layoutManager = parent.layoutManager ?: return
val centerX = parent.width / 2f
parent.forEach { child ->
if (child.top < parent.height && child.bottom > 0) {
// Child is visible
val layout = daySlots[parent.getChildAdapterPosition(child)]
if (layout != null) {
val dx = centerX - (layout.width / 2)
val dy = layoutManager.getDecoratedTop(child) +
child.translationY +
// offset vertically within the space according to the bias
(decorHeight - layout.height) * verticalBias
canvas.withTranslation(x = dx, y = dy) {
layout.draw(this)
}
}
}
}
}
/**
* Create a header layout for the given [time]
*/
private fun createHeader(
context: Context,
time: ZonedDateTime,
inConferenceTimeZone: Boolean
): StaticLayout {
val labelRes = TimeUtils.getLabelResForTime(time, inConferenceTimeZone)
val text = context.getText(labelRes)
return newStaticLayout(text, paint, textWidth, ALIGN_CENTER, 1f, 0f, false)
}
}
| apache-2.0 | a4eda3d408a0f18c942b5f6b4b43b05e | 37.666667 | 97 | 0.681034 | 4.577578 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchExecutionSession.kt | 1 | 7683 | // 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.scratch.compile
import com.intellij.execution.configurations.JavaCommandLineState
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.TargetProgressIndicatorAdapter
import com.intellij.execution.target.TargetedCommandLine
import com.intellij.execution.target.local.LocalTargetEnvironmentRequest
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.core.KotlinCompilerIde
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.scratch.LOG
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.scratch.compile.KtScratchSourceFileProcessor.Result
import org.jetbrains.kotlin.idea.scratch.printDebugMessage
import org.jetbrains.kotlin.idea.util.JavaParametersBuilder
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import java.io.File
class KtScratchExecutionSession(
private val file: ScratchFile,
private val executor: KtCompilingExecutor
) {
companion object {
private const val TIMEOUT_MS = 30000
}
@Volatile
private var backgroundProcessIndicator: ProgressIndicator? = null
fun execute(callback: () -> Unit) {
val psiFile = file.ktScratchFile ?: return executor.errorOccurs(
KotlinJvmBundle.message("couldn.t.find.ktfile.for.current.editor"),
isFatal = true
)
val expressions = file.getExpressions()
if (!executor.checkForErrors(psiFile, expressions)) return
when (val result = runReadAction { KtScratchSourceFileProcessor().process(expressions) }) {
is Result.Error -> return executor.errorOccurs(result.message, isFatal = true)
is Result.OK -> {
LOG.printDebugMessage("After processing by KtScratchSourceFileProcessor:\n ${result.code}")
executeInBackground(KotlinJvmBundle.message("running.kotlin.scratch")) { indicator ->
backgroundProcessIndicator = indicator
val modifiedScratchSourceFile = createFileWithLightClassSupport(result, psiFile)
tryRunCommandLine(modifiedScratchSourceFile, psiFile, result, callback)
}
}
}
}
private fun executeInBackground(@NlsContexts.ProgressTitle title: String, block: (indicator: ProgressIndicator) -> Unit) {
object : Task.Backgroundable(file.project, title, true) {
override fun run(indicator: ProgressIndicator) = block.invoke(indicator)
}.queue()
}
private fun createFileWithLightClassSupport(result: Result.OK, psiFile: KtFile): KtFile =
runReadAction { KtPsiFactory.contextual(psiFile).createPhysicalFile("tmp.kt", result.code) }
private fun tryRunCommandLine(modifiedScratchSourceFile: KtFile, psiFile: KtFile, result: Result.OK, callback: () -> Unit) {
assert(backgroundProcessIndicator != null)
try {
runCommandLine(
file.project, modifiedScratchSourceFile, file.getExpressions(), psiFile, result,
backgroundProcessIndicator!!, callback
)
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
reportError(result, e, psiFile)
}
}
fun reportError(result: Result.OK, e: Throwable, psiFile: KtFile) {
LOG.printDebugMessage(result.code)
executor.errorOccurs(e.message ?: KotlinJvmBundle.message("couldn.t.compile.0", psiFile.name), e, isFatal = true)
}
private fun runCommandLine(
project: Project,
modifiedScratchSourceFile: KtFile,
expressions: List<ScratchExpression>,
psiFile: KtFile,
result: Result.OK,
indicator: ProgressIndicator,
callback: () -> Unit
) {
val tempDir = DumbService.getInstance(project).runReadActionInSmartMode(Computable {
compileFileToTempDir(modifiedScratchSourceFile, expressions)
}) ?: return
try {
val (environmentRequest, commandLine) = createCommandLine(psiFile, file.module, result.mainClassName, tempDir.path)
val environment = environmentRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
val commandLinePresentation = commandLine.getCommandPresentation(environment)
LOG.printDebugMessage(commandLinePresentation)
val processHandler = CapturingProcessHandler(environment.createProcess(commandLine, indicator), null, commandLinePresentation)
val executionResult = processHandler.runProcessWithProgressIndicator(indicator, TIMEOUT_MS)
when {
executionResult.isTimeout -> {
executor.errorOccurs(
KotlinJvmBundle.message(
"couldn.t.get.scratch.execution.result.stopped.by.timeout.0.ms",
TIMEOUT_MS
)
)
}
executionResult.isCancelled -> {
// ignore
}
else -> {
executor.parseOutput(executionResult, expressions)
}
}
} finally {
tempDir.delete()
callback()
}
}
fun stop() {
backgroundProcessIndicator?.cancel()
}
private fun compileFileToTempDir(psiFile: KtFile, expressions: List<ScratchExpression>): File? {
if (!executor.checkForErrors(psiFile, expressions)) return null
val tmpDir = FileUtil.createTempDirectory("compile", "scratch")
LOG.printDebugMessage("Temp output dir: ${tmpDir.path}")
KotlinCompilerIde(psiFile).compileToDirectory(tmpDir)
return tmpDir
}
private fun createCommandLine(originalFile: KtFile, module: Module?, mainClassName: String, tempOutDir: String): Pair<TargetEnvironmentRequest, TargetedCommandLine> {
val javaParameters = JavaParametersBuilder(originalFile.project)
.withSdkFrom(module, true)
.withMainClassName(mainClassName)
.build()
javaParameters.classPath.add(tempOutDir)
if (module != null) {
javaParameters.classPath.addAll(JavaParametersBuilder.getModuleDependencies(module))
}
ScriptConfigurationManager.getInstance(originalFile.project)
.getConfiguration(originalFile)?.let {
javaParameters.classPath.addAll(it.dependenciesClassPath.map { f -> f.absolutePath })
}
val wslConfiguration = JavaCommandLineState.checkCreateWslConfiguration(javaParameters.jdk)
val request = wslConfiguration?.createEnvironmentRequest(originalFile.project) ?: LocalTargetEnvironmentRequest()
return request to javaParameters.toCommandLine(request).build()
}
} | apache-2.0 | 95bb9501ce7dc1665f02a4fdf8f8c35a | 43.16092 | 170 | 0.695952 | 5.406756 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_news/model/AnnouncementBadge.kt | 1 | 1891 | package org.stepik.android.view.course_news.model
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import org.stepic.droid.R
enum class AnnouncementBadge(
@DrawableRes
val backgroundRes: Int,
@ColorRes
val textColorRes: Int,
@DrawableRes
val compoundDrawableRes: Int,
@StringRes
val textRes: Int
) {
COMPOSING(
backgroundRes = R.drawable.bg_announcement_composing,
textColorRes = R.color.color_on_surface_emphasis_medium,
compoundDrawableRes = R.drawable.ic_announcement_badge_composing,
textRes = R.string.course_news_composing_badge
),
SCHEDULED(
backgroundRes = R.drawable.bg_announcement_scheduled,
textColorRes = R.color.color_overlay_violet,
compoundDrawableRes = R.drawable.ic_announcement_badge_scheduled,
textRes = R.string.course_news_scheduled_badge
),
SENDING(
backgroundRes = R.drawable.bg_announcement_scheduled,
textColorRes = R.color.color_overlay_violet,
compoundDrawableRes = R.drawable.ic_announcement_badge_sending,
textRes = R.string.course_news_sending_badge
),
SENT(
backgroundRes = R.drawable.bg_announcement_sent,
textColorRes = R.color.color_overlay_green,
compoundDrawableRes = R.drawable.ic_announcement_badge_sent,
textRes = R.string.course_news_sent_badge
),
ON_EVENT(
backgroundRes = R.drawable.bg_announcement_on_event,
textColorRes = R.color.color_overlay_blue,
compoundDrawableRes = -1,
textRes = R.string.course_news_on_event_badge
),
ONE_TIME(
backgroundRes = R.drawable.bg_announcement_on_event,
textColorRes = R.color.color_overlay_blue,
compoundDrawableRes = -1,
textRes = R.string.course_news_one_time_badge
)
} | apache-2.0 | 410dd76eda1cf788125e4c3ce611b9a3 | 32.192982 | 73 | 0.688525 | 3.947808 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/archmodel/SyncRemoteStore.kt | 1 | 4618 | package com.nononsenseapps.feeder.archmodel
import com.nononsenseapps.feeder.crypto.AesCbcWithIntegrity
import com.nononsenseapps.feeder.db.room.FeedItemForReadMark
import com.nononsenseapps.feeder.db.room.ReadStatusSynced
import com.nononsenseapps.feeder.db.room.ReadStatusSyncedDao
import com.nononsenseapps.feeder.db.room.RemoteFeed
import com.nononsenseapps.feeder.db.room.RemoteFeedDao
import com.nononsenseapps.feeder.db.room.RemoteReadMark
import com.nononsenseapps.feeder.db.room.RemoteReadMarkDao
import com.nononsenseapps.feeder.db.room.SyncDevice
import com.nononsenseapps.feeder.db.room.SyncDeviceDao
import com.nononsenseapps.feeder.db.room.SyncRemote
import com.nononsenseapps.feeder.db.room.SyncRemoteDao
import com.nononsenseapps.feeder.db.room.generateDeviceName
import java.net.URL
import kotlinx.coroutines.flow.Flow
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.instance
import org.threeten.bp.Instant
import org.threeten.bp.temporal.ChronoUnit
class SyncRemoteStore(override val di: DI) : DIAware {
private val dao: SyncRemoteDao by instance()
private val readStatusDao: ReadStatusSyncedDao by instance()
private val remoteReadMarkDao: RemoteReadMarkDao by instance()
private val syncDeviceDao: SyncDeviceDao by instance()
private val remoteFeedDao: RemoteFeedDao by instance()
suspend fun getSyncRemote(): SyncRemote {
dao.getSyncRemote()?.let {
return it
}
return createDefaultSyncRemote()
}
fun getSyncRemoteFlow(): Flow<SyncRemote?> {
return dao.getSyncRemoteFlow()
}
suspend fun updateSyncRemote(syncRemote: SyncRemote) {
dao.update(syncRemote)
}
suspend fun updateSyncRemoteMessageTimestamp(timestamp: Instant) {
dao.updateLastMessageTimestamp(timestamp)
}
suspend fun deleteAllReadStatusSyncs() {
readStatusDao.deleteAll()
}
suspend fun deleteReadStatusSyncs(ids: List<Long>) {
readStatusDao.deleteReadStatusSyncs(ids)
}
fun getNextFeedItemWithoutSyncedReadMark(): Flow<FeedItemForReadMark?> {
return readStatusDao.getNextFeedItemWithoutSyncedReadMark()
}
fun getFlowOfFeedItemsWithoutSyncedReadMark(): Flow<List<FeedItemForReadMark>> {
return readStatusDao.getFlowOfFeedItemsWithoutSyncedReadMark()
}
suspend fun getFeedItemsWithoutSyncedReadMark(): List<FeedItemForReadMark> {
return readStatusDao.getFeedItemsWithoutSyncedReadMark()
}
suspend fun setSynced(feedItemId: Long) {
// Ignores duplicates
readStatusDao.insert(
ReadStatusSynced(
feed_item = feedItemId,
sync_remote = 1L,
)
)
}
suspend fun setNotSynced(feedItemId: Long) {
// Ignores duplicates
readStatusDao.deleteReadStatusSyncForItem(feedItemId)
}
suspend fun addRemoteReadMark(feedUrl: URL, articleGuid: String) {
// Ignores duplicates
remoteReadMarkDao.insert(
RemoteReadMark(
sync_remote = 1L,
feedUrl = feedUrl,
guid = articleGuid,
timestamp = Instant.now(),
)
)
}
suspend fun deleteStaleRemoteReadMarks(now: Instant) {
// 7 days ago
remoteReadMarkDao.deleteStaleRemoteReadMarks(now.minus(7, ChronoUnit.DAYS))
}
suspend fun getRemoteReadMarksReadyToBeApplied() =
remoteReadMarkDao.getRemoteReadMarksReadyToBeApplied()
suspend fun getGuidsWhichAreSyncedAsReadInFeed(feedUrl: URL) =
remoteReadMarkDao.getGuidsWhichAreSyncedAsReadInFeed(feedUrl = feedUrl)
suspend fun replaceWithDefaultSyncRemote() {
dao.replaceWithDefaultSyncRemote()
}
private suspend fun createDefaultSyncRemote(): SyncRemote {
val remote = SyncRemote(
id = 1L,
deviceName = generateDeviceName(),
secretKey = AesCbcWithIntegrity.generateKey().toString(),
)
dao.insert(remote)
return remote
}
fun getDevices(): Flow<List<SyncDevice>> {
return syncDeviceDao.getDevices()
}
suspend fun replaceDevices(devices: List<SyncDevice>) {
syncDeviceDao.replaceDevices(devices)
}
suspend fun getRemotelySeenFeeds(): List<URL> {
return remoteFeedDao.getRemotelySeenFeeds()
}
suspend fun replaceRemoteFeedsWith(remoteFeeds: List<RemoteFeed>) {
remoteFeedDao.replaceRemoteFeedsWith(remoteFeeds)
}
companion object {
private const val LOG_TAG = "FEEDER_SyncRemoteStore"
}
}
| gpl-3.0 | 507f865136f806696ba7b06bb3035bbd | 31.521127 | 84 | 0.711347 | 4.364839 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/testPanels.kt | 1 | 11682 | // 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("HardCodedStringLiteral")
package com.intellij.ui.layout
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.UIBundle
import com.intellij.ui.components.*
import java.awt.Dimension
import java.awt.GridLayout
import javax.swing.*
/**
* See [ShowcaseUiDslAction]
*/
fun labelRowShouldNotGrow(): JPanel {
return panel {
row("Create Android module") { CheckBox("FooBar module name foo")() }
row("Android module name:") { JTextField("input")() }
}
}
fun secondColumnSmallerPanel(): JPanel {
val selectForkButton = JButton("Select Other Fork")
val branchCombobox = ComboBox<String>()
val diffButton = JButton("Show Diff")
val titleTextField = JTextField()
val panel = panel {
row("Base fork:") {
JComboBox<String>(arrayOf())(growX, CCFlags.pushX)
selectForkButton(growX)
}
row("Base branch:") {
branchCombobox(growX, pushX)
diffButton(growX)
}
row("Title:") { titleTextField() }
row("Description:") {
scrollPane(JTextArea())
}
}
// test scrollPane
panel.preferredSize = Dimension(512, 256)
return panel
}
@Suppress("unused")
fun visualPaddingsPanelOnlyComboBox(): JPanel {
return panel {
row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) }
row("Combobox Editable:") {
val field = JComboBox<String>(arrayOf("one", "two"))
field.isEditable = true
field(growX)
}
}
}
@Suppress("unused")
fun visualPaddingsPanelOnlyButton(): JPanel {
return panel {
row("Button:") { button("label") {}.constraints(growX) }
}
}
@Suppress("unused")
fun visualPaddingsPanelOnlyLabeledScrollPane(): JPanel {
return panel {
row("Description:") {
scrollPane(JTextArea())
}
}
}
@Suppress("unused")
fun visualPaddingsPanelOnlyTextField(): JPanel {
return panel {
row("Text field:") { JTextField("text")() }
}
}
fun visualPaddingsPanel(): JPanel {
// we use growX to test right border
return panel {
row("Text field:") { JTextField("text")() }
row("Password:") { JPasswordField("secret")() }
row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) }
row("Combobox Editable:") {
val field = JComboBox<String>(arrayOf("one", "two"))
field.isEditable = true
field(growX)
}
row("Button:") { button("label") {}.constraints(growX) }
row("CheckBox:") { CheckBox("enabled")() }
row("RadioButton:") { JRadioButton("label")() }
row("Spinner:") { JBIntSpinner(0, 0, 7)() }
row("Text with browse:") { textFieldWithBrowseButton("File") }
// test text baseline alignment
row("All:") {
cell {
JTextField("t")()
JPasswordField("secret")()
JComboBox<String>(arrayOf("c1", "c2"))(growX)
button("b") {}
CheckBox("c")()
JRadioButton("rb")()
}
}
row("Scroll pane:") {
scrollPane(JTextArea("first line baseline equals to label"))
}
}
}
fun fieldWithGear(): JPanel {
return panel {
row("Database:") {
JTextField()()
gearButton()
}
row("Master Password:") {
JBPasswordField()()
}
}
}
fun fieldWithGearWithIndent(): JPanel {
return panel {
row {
row("Database:") {
JTextField()()
gearButton()
}
row("Master Password:") {
JBPasswordField()()
}
}
}
}
fun alignFieldsInTheNestedGrid(): JPanel {
return panel {
buttonGroup {
row {
RadioButton("In KeePass")()
row("Database:") {
JTextField()()
gearButton()
}
row("Master Password:") {
JBPasswordField()(comment = "Stored using weak encryption.")
}
}
}
}
}
fun noteRowInTheDialog(): JPanel {
val passwordField = JPasswordField()
return panel {
noteRow("Profiler requires access to the kernel-level API.\nEnter the sudo password to allow this. ")
row("Sudo password:") { passwordField() }
row { CheckBox(UIBundle.message("auth.remember.cb"), true)() }
noteRow("Should be an empty row above as a gap. <a href=''>Click me</a>.") {
System.out.println("Hello")
}
}
}
fun jbTextField(): JPanel {
val passwordField = JBPasswordField()
return panel {
noteRow("Enter credentials for bitbucket.org")
row("Username:") { JTextField("develar")() }
row("Password:") { passwordField() }
row {
JBCheckBox(UIBundle.message("auth.remember.cb"), true)()
}
}
}
fun cellPanel(): JPanel {
return panel {
row("Repository:") {
cell {
ComboBox<String>()(comment = "Use File -> Settings Repository... to configure")
JButton("Delete")()
}
}
row {
// need some pushx/grow component to test label cell grow policy if there is cell with several components
scrollPane(JTextArea())
}
}
}
fun commentAndPanel(): JPanel {
return panel {
row("Repository:") {
cell {
checkBox("Auto Sync", comment = "Use File -> Settings Repository... to configure")
}
}
row {
panel("Foo", JScrollPane(JTextArea()))
}
}
}
fun createLafTestPanel(): JPanel {
val spacing = createIntelliJSpacingConfiguration()
val panel = JPanel(GridLayout(0, 1, spacing.horizontalGap, spacing.verticalGap))
panel.add(JTextField("text"))
panel.add(JPasswordField("secret"))
panel.add(ComboBox<String>(arrayOf("one", "two")))
val field = ComboBox<String>(arrayOf("one", "two"))
field.isEditable = true
panel.add(field)
panel.add(JButton("label"))
panel.add(CheckBox("enabled"))
panel.add(JRadioButton("label"))
panel.add(JBIntSpinner(0, 0, 7))
panel.add(textFieldWithHistoryWithBrowseButton(null, "File", FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()))
return panel
}
fun withVerticalButtons(): JPanel {
return panel {
row {
label("<html>Merging branch <b>foo</b> into <b>bar</b>")
}
row {
scrollPane(JTextArea()).constraints(pushX)
cell(isVerticalFlow = true) {
button("Accept Yours") {}.constraints(growX)
button("Accept Theirs") {}.constraints(growX)
button("Merge ...") {}.constraints(growX)
}
}
}
}
fun withSingleVerticalButton(): JPanel {
return panel {
row {
label("<html>Merging branch <b>foo</b> into <b>bar</b>")
}
row {
scrollPane(JTextArea()).constraints(pushX)
cell(isVerticalFlow = true) {
button("Merge ...") {}.constraints(growX)
}
}
}
}
fun titledRows(): JPanel {
return panel {
titledRow("Async Profiler") {
row { browserLink("Async profiler README.md", "https://github.com/jvm-profiling-tools/async-profiler") }
row("Agent path:") { textFieldWithBrowseButton("").comment("If field is empty bundled agent will be used") }
row("Agent options:") { textFieldWithBrowseButton("").comment("Don't add output format (collapsed is used) or output file options") }
}
titledRow("Java Flight Recorder") {
row("JRE home:") {
textFieldWithBrowseButton("").comment("At least OracleJRE 9 or OpenJRE 11 is required to import dump")
}
}
}
}
fun hideableRow(): JPanel {
val dummyTextBinding = PropertyBinding({ "" }, {})
return panel {
row("Foo") {
textField(dummyTextBinding)
}
hideableRow("Bar") {
textField(dummyTextBinding)
}
}
}
fun spannedCheckbox(): JPanel {
return panel {
buttonGroup {
row {
RadioButton("In KeePass")()
row("Database:") {
// comment can lead to broken layout, so, test it
JTextField("test")(comment = "Stored using weak encryption. It is recommended to store on encrypted volume for additional security.")
}
row {
cell {
checkBox("Protect master password using PGP key")
val comboBox = ComboBox(arrayOf("Foo", "Bar"))
comboBox.isVisible = false
comboBox(growPolicy = GrowPolicy.MEDIUM_TEXT)
}
}
}
row {
RadioButton("Do not save, forget passwords after restart")()
}
}
}
}
fun checkboxRowsWithBigComponents(): JPanel {
return panel {
row {
CheckBox("Sample checkbox label")()
}
row {
CheckBox("Sample checkbox label")()
}
row {
CheckBox("Sample checkbox label")()
ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))()
}
row {
CheckBox("Sample checkbox label")()
}
row {
CheckBox("Sample checkbox label")()
ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))()
}
row {
CheckBox("Sample checkbox label")()
ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))()
}
row {
CheckBox("Sample checkbox label")()
JBTextField()()
}
row {
cell(isFullWidth = true) {
CheckBox("Sample checkbox label")()
}
}
row {
cell(isFullWidth = true) {
CheckBox("Sample checkbox label")()
JBTextField()()
}
}
row {
cell(isFullWidth = true) {
CheckBox("Sample checkbox label")()
comment("commentary")
}
}
}
}
// titledRows is not enough to test because component align depends on comment components, so, pure titledRow must be tested
fun titledRow(): JPanel {
return panel {
titledRow("Remote settings") {
row("Default notebook name:") { JTextField("")() }
row("Spark version:") { JTextField("")() }
}
}
}
fun sampleConfigurablePanel(): JPanel {
return panel {
titledRow("Settings") {
row { checkBox("Some test option") }
row { checkBox("Another test option") }
}
titledRow("Options") {
row { checkBox("Some test option") }
row {
buttonGroup("Radio group") {
row { radioButton("Option 1") }
row { radioButton("Option 2") }
}
}
row {
buttonGroup("Radio group") {
row { radioButton("Option 1", comment = "Comment for the Option 1") }
row { radioButton("Option 2") }
}
}
}
titledRow("Test") {
row("Header") { JTextField()() }
row("Longer Header") { checkBox("Some long description", comment = "Comment for the checkbox with longer header.") }
row("Header") { JPasswordField()() }
row("Header") { comboBox(DefaultComboBoxModel(arrayOf("Option 1", "Option 2")), { null }, {}) }
}
}
}
private data class TestOptions(var threadDumpDelay: Int, var enableLargeIndexing: Boolean, var largeIndexFilesCount: Int)
fun checkBoxFollowedBySpinner(): JPanel {
val testOptions = TestOptions(50, true, 100)
return panel {
row(label = "Thread dump capture delay (ms):") {
spinner(testOptions::threadDumpDelay, 50, 5000, 50)
}
row {
val c = checkBox("Create", testOptions::enableLargeIndexing).actsAsLabel()
spinner(testOptions::largeIndexFilesCount, 100, 1_000_000, 1_000)
.enableIf(c.selected)
label("files to start background indexing")
}
}
}
fun separatorAndComment() : JPanel {
return panel {
row("Label", separated = true) {
textField({ "abc" }, {}).comment("comment")
}
}
}
fun rowWithIndent(): JPanel {
return panel {
row("Zero") {
subRowIndent = 0
row("Bar 0") {
}
}
row("One") {
subRowIndent = 1
row("Bar 1") {
}
}
row("Two") {
subRowIndent = 2
row("Bar 2") {
}
}
}
} | apache-2.0 | b059cac76211fa8859d178644fb0bc5d | 24.620614 | 143 | 0.606831 | 4.194614 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/branch/DeepComparator.kt | 1 | 14786 | // 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 git4idea.branch
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.highlighters.MergeCommitsHighlighter
import com.intellij.vcs.log.ui.highlighters.VcsLogHighlighterFactory
import com.intellij.vcs.log.util.*
import com.intellij.vcs.log.visible.VisiblePack
import git4idea.GitBranch
import git4idea.GitNotificationIdsHolder.Companion.COULD_NOT_COMPARE_WITH_BRANCH
import git4idea.GitUtil
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import gnu.trove.TIntHashSet
import org.jetbrains.annotations.NonNls
import java.awt.Point
class DeepComparator(private val project: Project,
private val repositoryManager: GitRepositoryManager,
private val vcsLogData: VcsLogData,
private val ui: VcsLogUi,
parent: Disposable) : VcsLogHighlighter, Disposable {
private val storage
get() = vcsLogData.storage
private var progressIndicator: ProgressIndicator? = null
private var comparedBranch: String? = null
private var repositoriesWithCurrentBranches: Map<GitRepository, GitBranch>? = null
private var nonPickedCommits: TIntHashSet? = null
init {
Disposer.register(parent, this)
}
override fun getStyle(commitId: Int, commitDetails: VcsShortCommitDetails, isSelected: Boolean): VcsLogHighlighter.VcsCommitStyle {
if (nonPickedCommits == null || nonPickedCommits!!.contains(commitId)) return VcsLogHighlighter.VcsCommitStyle.DEFAULT
else return VcsCommitStyleFactory.foreground(MergeCommitsHighlighter.MERGE_COMMIT_FOREGROUND)
}
override fun update(dataPack: VcsLogDataPack, refreshHappened: Boolean) {
if (comparedBranch == null) { // no branch is selected => not interested in refresh events
return
}
val singleFilteredBranch = getComparedBranchFromFilters(dataPack.filters, dataPack.refs)
if (comparedBranch != singleFilteredBranch) {
val oldComparedBranch = comparedBranch
LOG.debug("Branch filter changed. Compared branch: $oldComparedBranch, filtered branch: $singleFilteredBranch")
stopTaskAndUnhighlight()
notifyUnhighlight(oldComparedBranch)
return
}
if (refreshHappened) {
stopTask()
// highlight again
val repositories = getRepositories(dataPack.logProviders, comparedBranch!!)
if (repositories == repositoriesWithCurrentBranches) {
// but not if current branch changed
startTask(dataPack)
}
else {
LOG.debug("Repositories with current branches changed. Actual:\n$repositories\nExpected:\n$repositoriesWithCurrentBranches")
unhighlight()
}
}
}
@RequiresEdt
fun startTask(dataPack: VcsLogDataPack, branchToCompare: String) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (comparedBranch != null) {
LOG.error("Already comparing with branch $comparedBranch")
return
}
val repositories = getRepositories(ui.dataPack.logProviders, branchToCompare)
if (repositories.isEmpty()) {
LOG.debug("Could not find suitable repositories for selected branch $comparedBranch")
return
}
comparedBranch = branchToCompare
repositoriesWithCurrentBranches = repositories
startTask(dataPack)
}
@RequiresEdt
fun stopTaskAndUnhighlight() {
ApplicationManager.getApplication().assertIsDispatchThread()
stopTask()
unhighlight()
}
@RequiresEdt
fun hasHighlightingOrInProgress(): Boolean {
ApplicationManager.getApplication().assertIsDispatchThread()
return comparedBranch != null
}
private fun startTask(dataPack: VcsLogDataPack) {
LOG.debug("Highlighting requested for $repositoriesWithCurrentBranches")
val task = MyTask(repositoriesWithCurrentBranches!!, dataPack, comparedBranch!!)
progressIndicator = BackgroundableProcessIndicator(task)
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, progressIndicator!!)
}
private fun stopTask() {
if (progressIndicator != null) {
progressIndicator!!.cancel()
progressIndicator = null
}
}
private fun unhighlight() {
nonPickedCommits = null
comparedBranch = null
repositoriesWithCurrentBranches = null
}
private fun getRepositories(providers: Map<VirtualFile, VcsLogProvider>,
branchToCompare: String): Map<GitRepository, GitBranch> {
return providers.keys.mapNotNull { repositoryManager.getRepositoryForRootQuick(it) }.filter { repository ->
repository.currentBranch != null &&
repository.branches.findBranchByName(branchToCompare) != null
}.associateWith { it.currentBranch!! }
}
private fun notifyUnhighlight(branch: String?) {
if (ui is VcsLogUiEx) {
val message = GitBundle.message("git.log.cherry.picked.highlighter.cancelled.message", branch)
val balloon = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, null,
MessageType.INFO.popupBackground, null)
.setFadeoutTime(5000)
.createBalloon()
val component = ui.table
balloon.show(RelativePoint(component, Point(component.width / 2, component.visibleRect.y)), Balloon.Position.below)
Disposer.register(this, balloon)
}
}
override fun dispose() {
stopTaskAndUnhighlight()
}
private inner class MyTask(private val repositoriesWithCurrentBranches: Map<GitRepository, GitBranch>,
vcsLogDataPack: VcsLogDataPack,
private val comparedBranch: String) :
Task.Backgroundable(project, GitBundle.message("git.log.cherry.picked.highlighter.process")) {
private val dataPack = (vcsLogDataPack as? VisiblePack)?.dataPack as? DataPack
private val collectedNonPickedCommits = TIntHashSet()
private var exception: VcsException? = null
override fun run(indicator: ProgressIndicator) {
try {
repositoriesWithCurrentBranches.forEach { (repo, currentBranch) ->
val commits = if (Registry.`is`("git.log.use.index.for.picked.commits.highlighting")) {
if (Registry.`is`("git.log.fast.picked.commits.highlighting")) {
getCommitsByIndexFast(repo.root, comparedBranch) ?: getCommitsByIndexReliable(repo.root, comparedBranch, currentBranch.name)
}
else {
getCommitsByIndexReliable(repo.root, comparedBranch, currentBranch.name)
}
}
else {
getCommitsByPatch(repo.root, comparedBranch, currentBranch.name)
}
TroveUtil.addAll(collectedNonPickedCommits, commits)
}
}
catch (e: VcsException) {
LOG.warn(e)
exception = e
}
}
override fun onFinished() {
progressIndicator = null
}
override fun onSuccess() {
if (exception != null) {
nonPickedCommits = null
VcsNotifier.getInstance(project).notifyError(COULD_NOT_COMPARE_WITH_BRANCH,
GitBundle.message("git.log.cherry.picked.highlighter.error.message", comparedBranch),
exception!!.message)
return
}
nonPickedCommits = collectedNonPickedCommits
}
private fun getCommitsByPatch(root: VirtualFile,
targetBranch: String,
sourceBranch: String): TIntHashSet {
return measureTimeMillis(root, "Getting non picked commits with git") {
getCommitsFromGit(root, targetBranch, sourceBranch)
}
}
private fun getCommitsByIndexReliable(root: VirtualFile, sourceBranch: String, targetBranch: String): TIntHashSet {
val resultFromGit = getCommitsByPatch(root, targetBranch, sourceBranch)
if (dataPack == null || !dataPack.isFull) return resultFromGit
val resultFromIndex = measureTimeMillis(root, "Getting non picked commits with index reliable") {
val sourceBranchRef = dataPack.refsModel.findBranch(sourceBranch, root) ?: return resultFromGit
val targetBranchRef = dataPack.refsModel.findBranch(GitUtil.HEAD, root) ?: return resultFromGit
getCommitsFromIndex(dataPack, root, sourceBranchRef, targetBranchRef, resultFromGit, true)
}
return resultFromIndex ?: resultFromGit
}
private fun getCommitsByIndexFast(root: VirtualFile, sourceBranch: String): TIntHashSet? {
if (!vcsLogData.index.isIndexed(root) || dataPack == null || !dataPack.isFull) return null
return measureTimeMillis(root, "Getting non picked commits with index fast") {
val sourceBranchRef = dataPack.refsModel.findBranch(sourceBranch, root) ?: return null
val targetBranchRef = dataPack.refsModel.findBranch(GitUtil.HEAD, root) ?: return null
val sourceBranchCommits = dataPack.subgraphDifference(sourceBranchRef, targetBranchRef, storage) ?: return null
getCommitsFromIndex(dataPack, root, sourceBranchRef, targetBranchRef, sourceBranchCommits, false)
}
}
@Throws(VcsException::class)
private fun getCommitsFromGit(root: VirtualFile,
currentBranch: String,
comparedBranch: String): TIntHashSet {
val handler = GitLineHandler(project, root, GitCommand.CHERRY)
handler.addParameters(currentBranch, comparedBranch) // upstream - current branch; head - compared branch
val pickedCommits = TIntHashSet()
handler.addLineListener { l, _ ->
var line = l
// + 645caac042ff7fb1a5e3f7d348f00e9ceea5c317
// - c3b9b90f6c26affd7e597ebf65db96de8f7e5860
if (line.startsWith("+")) {
try {
line = line.substring(2).trim { it <= ' ' }
val firstSpace = line.indexOf(' ')
if (firstSpace > 0) {
line = line.substring(0, firstSpace) // safety-check: take just the first word for sure
}
pickedCommits.add(storage.getCommitIndex(HashImpl.build(line), root))
}
catch (e: Exception) {
LOG.error("Couldn't parse line [$line]", e)
}
}
}
Git.getInstance().runCommandWithoutCollectingOutput(handler)
return pickedCommits
}
private fun getCommitsFromIndex(dataPack: DataPack?, root: VirtualFile,
sourceBranchRef: VcsRef, targetBranchRef: VcsRef,
sourceBranchCommits: TIntHashSet, reliable: Boolean): TIntHashSet? {
if (dataPack == null) return null
if (sourceBranchCommits.isEmpty) return sourceBranchCommits
if (!vcsLogData.index.isIndexed(root)) return null
val dataGetter = vcsLogData.index.dataGetter ?: return null
val targetBranchCommits = dataPack.subgraphDifference(targetBranchRef, sourceBranchRef, storage) ?: return null
if (targetBranchCommits.isEmpty) return sourceBranchCommits
val match = dataGetter.match(root, sourceBranchCommits, targetBranchCommits, reliable)
TroveUtil.removeAll(sourceBranchCommits, match)
if (!match.isEmpty) {
LOG.debug("Using index, detected ${match.size()} commits in ${sourceBranchRef.name}#${root.name}" +
" that were picked to the current branch" +
(if (reliable) " with different patch id but matching cherry-picked suffix"
else " with matching author, author time and message"))
}
return sourceBranchCommits
}
override fun toString(): String {
return "Task for '$comparedBranch' in $repositoriesWithCurrentBranches" //NON-NLS
}
}
class Factory : VcsLogHighlighterFactory {
override fun createHighlighter(logDataManager: VcsLogData, logUi: VcsLogUi): VcsLogHighlighter {
return getInstance(logDataManager.project, logDataManager, logUi)
}
override fun getId(): String {
return "CHERRY_PICKED_COMMITS" //NON-NLS
}
override fun getTitle(): String {
// this method is not used as there is a separate action and showMenuItem returns false
return GitBundle.message("action.Git.Log.DeepCompare.text")
}
override fun showMenuItem(): Boolean {
return false
}
}
companion object {
private val LOG = Logger.getInstance(DeepComparator::class.java)
@JvmStatic
fun getInstance(project: Project, dataProvider: VcsLogData, logUi: VcsLogUi): DeepComparator {
return ServiceManager.getService(project, DeepComparatorHolder::class.java).getInstance(dataProvider, logUi)
}
@JvmStatic
fun getComparedBranchFromFilters(filters: VcsLogFilterCollection, refs: VcsLogRefs): String? {
val singleFilteredBranch = VcsLogUtil.getSingleFilteredBranch(filters, refs)
if (singleFilteredBranch != null) return singleFilteredBranch
val rangeFilter = filters.get(VcsLogFilterCollection.RANGE_FILTER) ?: return null
return rangeFilter.ranges.singleOrNull()?.inclusiveRef
}
}
private inline fun <R> measureTimeMillis(root: VirtualFile, @NonNls actionName: String, block: () -> R): R {
val start = System.currentTimeMillis()
val result = block()
if (result != null) {
LOG.debug("$actionName took ${StopWatch.formatTime(System.currentTimeMillis() - start)} for ${root.name}")
}
return result
}
} | apache-2.0 | 9f256d0b46cb9668bc6f99e21f65ec06 | 40.304469 | 140 | 0.702895 | 4.82887 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/browse/BrowseProviderViewModel.kt | 1 | 4567 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.browse
import android.app.Application
import android.content.ContentUris
import android.database.ContentObserver
import android.net.Uri
import android.os.DeadObjectException
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.getInstalledProviders
import com.google.android.apps.muzei.util.ContentProviderClientCompat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class BrowseProviderViewModel(
application: Application,
savedStateHandle: SavedStateHandle
): AndroidViewModel(application) {
private val args = BrowseProviderFragmentArgs.fromSavedStateHandle(savedStateHandle)
val providerInfo = getInstalledProviders(application).debounce(1000L).map { providers ->
providers.firstOrNull { it.authority == args.contentUri.authority }
}
val client = providerInfo.map { providerInfo ->
providerInfo?.let {
val context = getApplication<Application>()
ContentProviderClientCompat.getClient(context, args.contentUri)
}
}
private fun getProviderArtwork(
contentProviderClient: ContentProviderClientCompat,
) = callbackFlow {
val context = getApplication<Application>()
val authority: String = args.contentUri.authority!!
var refreshJob: Job? = null
val refreshArt = {
refreshJob?.cancel()
refreshJob = launch {
try {
val list = mutableListOf<Artwork>()
contentProviderClient.query(args.contentUri)?.use { data ->
while(data.moveToNext() && isActive) {
val providerArtwork =
com.google.android.apps.muzei.api.provider.Artwork.fromCursor(data)
list.add(Artwork(ContentUris.withAppendedId(args.contentUri,
providerArtwork.id)).apply {
title = providerArtwork.title
byline = providerArtwork.byline
attribution = providerArtwork.attribution
providerAuthority = authority
})
}
}
send(list)
} catch (e: DeadObjectException) {
// Provider was updated out from underneath us
// so there's nothing more we can do here
}
}
}
val contentObserver = object : ContentObserver(null) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
refreshArt()
}
}
context.contentResolver.registerContentObserver(
args.contentUri,
true,
contentObserver)
refreshArt()
awaitClose {
context.contentResolver.unregisterContentObserver(contentObserver)
contentProviderClient.close()
}
}
val artwork = client.flatMapLatest { client ->
if (client != null) {
getProviderArtwork(client) }
else {
emptyFlow()
}
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1)
} | apache-2.0 | 63bd2777d7ecbae32e0a4c9c20c50034 | 37.711864 | 99 | 0.653821 | 5.398345 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/vendor/VendorAdapter.kt | 1 | 2519 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.vendor
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.databinding.VendorDetailsBinding
import com.vrem.wifianalyzer.vendor.model.VendorService
@OpenClass
internal class VendorAdapter(context: Context, private val vendorService: VendorService) :
ArrayAdapter<String>(context, R.layout.vendor_details, vendorService.findVendors()) {
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
val binding: Binding = view?.let { Binding(it) } ?: Binding(create(parent))
getItem(position)?.let {
binding.vendorName.text = it
binding.vendorMacs.text = vendorService.findMacAddresses(it).joinToString(", ")
}
return binding.root
}
fun update(filter: String) {
clear()
addAll(vendorService.findVendors(filter))
}
private fun create(parent: ViewGroup): VendorDetailsBinding =
VendorDetailsBinding.inflate(MainContext.INSTANCE.layoutInflater, parent, false)
private class Binding {
val root: View
val vendorName: TextView
val vendorMacs: TextView
constructor(binding: VendorDetailsBinding) {
root = binding.root
vendorName = binding.vendorName
vendorMacs = binding.vendorMacs
}
constructor(view: View) {
root = view
vendorName = view.findViewById(R.id.vendor_name)
vendorMacs = view.findViewById(R.id.vendor_macs)
}
}
} | gpl-3.0 | 32f0fb51a9afe753ed625a8b958bb876 | 34.492958 | 93 | 0.708615 | 4.411559 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/com/jchanghong/adapter/ListAdapterNote.kt | 2 | 3603 | package com.jchanghong.adapter
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.jchanghong.R
import com.jchanghong.model.Note
import com.jchanghong.utils.Tools
import com.jchanghong.utils.removeyam
import java.util.*
class ListAdapterNote(private val context: Context, items: List<Note>) : RecyclerView.Adapter<ListAdapterNote.ViewHolder>(), Filterable {
private var original_items = ArrayList<Note>()
private var filtered_items: List<Note> = ArrayList()
private val mFilter = ItemFilter()
private var onItemClickListener: OnItemClickListener? = null
inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var title: TextView = v.findViewById<View>(R.id.title) as TextView
var content: TextView = v.findViewById<View>(R.id.content) as TextView
var time: TextView = v.findViewById<View>(R.id.time) as TextView
var image: ImageView = v.findViewById<View>(R.id.image) as ImageView
var lyt_parent: LinearLayout = v.findViewById<View>(R.id.lyt_parent) as LinearLayout
}
fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
this.onItemClickListener = onItemClickListener
}
init {
original_items = items as ArrayList<Note>
filtered_items = items
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.row_note, parent, false)
// set the view's size, margins, paddings and layout parameters
val vh = ViewHolder(v)
return vh
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val n = filtered_items[position]
holder.title.text = n.tittle
holder.time.text = Tools.stringToDate(n.lastEdit)
holder.content.text = n.content.removeyam()
holder.image.setImageResource(Tools.StringToResId(n.category.icon, context))
(holder.image.background as GradientDrawable).setColor(Color.parseColor(n.category.color))
holder.lyt_parent.setOnClickListener { v -> onItemClickListener!!.onItemClick(v, n) }
}
override fun getItemCount(): Int {
return filtered_items.size
}
interface OnItemClickListener {
fun onItemClick(view: View, model: Note)
}
override fun getFilter(): Filter {
return mFilter
}
private inner class ItemFilter : Filter() {
override fun performFiltering(constraint: CharSequence): Filter.FilterResults {
val query = constraint.toString().toLowerCase()
val results = Filter.FilterResults()
val list = original_items
val result_list = ArrayList<Note>(list.size)
for (i in list.indices) {
val str_title = list[i].tittle
val str_content = list[i].content
if (str_title.toLowerCase().contains(query) || str_content.toLowerCase().contains(query)) {
result_list.add(list[i])
}
}
results.values = result_list
results.count = result_list.size
return results
}
override fun publishResults(constraint: CharSequence, results: Filter.FilterResults) {
filtered_items = results.values as List<Note>
notifyDataSetChanged()
}
}
}
| gpl-2.0 | d1f7f63832ac2f03318f753d5eb84ce8 | 33.980583 | 137 | 0.674716 | 4.554994 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/MuzeiWallpaperService.kt | 1 | 16393 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei
import android.annotation.SuppressLint
import android.app.WallpaperColors
import android.app.WallpaperManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.ViewConfiguration
import androidx.annotation.RequiresApi
import androidx.core.os.UserManagerCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import com.google.android.apps.muzei.featuredart.BuildConfig.FEATURED_ART_AUTHORITY
import com.google.android.apps.muzei.legacy.LegacySourceManager
import com.google.android.apps.muzei.notifications.NotificationUpdater
import com.google.android.apps.muzei.render.ImageLoader
import com.google.android.apps.muzei.render.MuzeiBlurRenderer
import com.google.android.apps.muzei.render.RealRenderController
import com.google.android.apps.muzei.render.RenderController
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.contentUri
import com.google.android.apps.muzei.room.openArtworkInfo
import com.google.android.apps.muzei.settings.EffectsLockScreenOpen
import com.google.android.apps.muzei.settings.Prefs
import com.google.android.apps.muzei.shortcuts.ArtworkInfoShortcutController
import com.google.android.apps.muzei.sync.ProviderManager
import com.google.android.apps.muzei.util.collectIn
import com.google.android.apps.muzei.wallpaper.LockscreenObserver
import com.google.android.apps.muzei.wallpaper.WallpaperAnalytics
import com.google.android.apps.muzei.wearable.WearableController
import com.google.android.apps.muzei.widget.WidgetUpdater
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.launch
import net.rbgrn.android.glwallpaperservice.GLWallpaperService
data class WallpaperSize(val width: Int, val height: Int)
val WallpaperSizeStateFlow = MutableStateFlow<WallpaperSize?>(null)
class MuzeiWallpaperService : GLWallpaperService(), LifecycleOwner {
companion object {
private const val TEMPORARY_FOCUS_DURATION_MILLIS: Long = 3000
private const val THREE_FINGER_TAP_INTERVAL_MS = 1000L
private const val MAX_ARTWORK_SIZE = 110 // px
}
private val wallpaperLifecycle = LifecycleRegistry(this)
private var unlockReceiver: BroadcastReceiver? = null
override fun onCreateEngine(): Engine {
return MuzeiWallpaperEngine()
}
@SuppressLint("InlinedApi")
override fun onCreate() {
super.onCreate()
with(wallpaperLifecycle) {
addObserver(WorkManagerInitializer.initializeObserver(this@MuzeiWallpaperService))
addObserver(LegacySourceManager.getInstance(this@MuzeiWallpaperService))
addObserver(NotificationUpdater(this@MuzeiWallpaperService))
addObserver(WearableController(this@MuzeiWallpaperService))
addObserver(WidgetUpdater(this@MuzeiWallpaperService))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
addObserver(ArtworkInfoShortcutController(this@MuzeiWallpaperService))
}
}
ProviderManager.getInstance(this).observe(this) { provider ->
if (provider == null) {
lifecycleScope.launch(NonCancellable) {
ProviderManager.select(this@MuzeiWallpaperService, FEATURED_ART_AUTHORITY)
}
}
}
if (UserManagerCompat.isUserUnlocked(this)) {
wallpaperLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
unlockReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
wallpaperLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
unregisterReceiver(this)
unlockReceiver = null
}
}
val filter = IntentFilter(Intent.ACTION_USER_UNLOCKED)
registerReceiver(unlockReceiver, filter)
}
}
override fun getLifecycle(): Lifecycle {
return wallpaperLifecycle
}
override fun onDestroy() {
if (unlockReceiver != null) {
unregisterReceiver(unlockReceiver)
}
wallpaperLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
super.onDestroy()
}
inner class MuzeiWallpaperEngine
: GLWallpaperService.GLEngine(),
LifecycleOwner,
DefaultLifecycleObserver,
RenderController.Callbacks,
MuzeiBlurRenderer.Callbacks {
private lateinit var renderer: MuzeiBlurRenderer
private lateinit var renderController: RenderController
private var currentArtwork: Bitmap? = null
private var validDoubleTap: Boolean = false
private var lastThreeFingerTap = 0L
private val engineLifecycle = LifecycleRegistry(this)
private var doubleTapTimeout: Job? = null
private val gestureListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onDoubleTap(e: MotionEvent): Boolean {
if (ArtDetailOpen.value) {
// The main activity is visible, so discard any double touches since focus
// should be forced on
return true
}
validDoubleTap = true // processed in onCommand/COMMAND_TAP
doubleTapTimeout?.cancel()
val timeout = ViewConfiguration.getDoubleTapTimeout().toLong()
doubleTapTimeout = lifecycleScope.launch {
delay(timeout)
queueEvent {
validDoubleTap = false
}
}
return true
}
}
private val gestureDetector: GestureDetector = GestureDetector(this@MuzeiWallpaperService,
gestureListener)
private var delayedBlur: Job? = null
override fun onCreate(surfaceHolder: SurfaceHolder) {
super<GLEngine>.onCreate(surfaceHolder)
renderer = MuzeiBlurRenderer(this@MuzeiWallpaperService, this,
false, isPreview)
renderController = RealRenderController(this@MuzeiWallpaperService,
renderer, this)
engineLifecycle.addObserver(renderController)
setEGLContextClientVersion(2)
setEGLConfigChooser(8, 8, 8, 0, 0, 0)
setRenderer(renderer)
renderMode = RENDERMODE_WHEN_DIRTY
requestRender()
engineLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
engineLifecycle.addObserver(WallpaperAnalytics(this@MuzeiWallpaperService))
engineLifecycle.addObserver(LockscreenObserver(this@MuzeiWallpaperService, this))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
val database = MuzeiDatabase.getInstance(this@MuzeiWallpaperService)
database.artworkDao().currentArtwork.filterNotNull().collectIn(this) { artwork ->
updateCurrentArtwork(artwork)
}
}
// Use the MuzeiWallpaperService's lifecycle to wait for the user to unlock
wallpaperLifecycle.addObserver(this)
setTouchEventsEnabled(true)
setOffsetNotificationsEnabled(true)
EffectsLockScreenOpen.collectIn(this) { isEffectsLockScreenOpen ->
renderController.onLockScreen = isEffectsLockScreenOpen
}
ArtDetailOpen.collectIn(this) { isArtDetailOpened ->
cancelDelayedBlur()
queueEvent { renderer.setIsBlurred(!isArtDetailOpened, true) }
}
ArtDetailViewport.getChanges().collectIn(this) {
requestRender()
}
}
override fun getLifecycle(): Lifecycle {
return engineLifecycle
}
override fun onStart(owner: LifecycleOwner) {
// The MuzeiWallpaperService only gets to ON_START when the user is unlocked
// At that point, we can proceed with the engine's lifecycle
// In preview mode, we only move to ON_START to avoid analytics events.
engineLifecycle.handleLifecycleEvent(if (isPreview)
Lifecycle.Event.ON_START else Lifecycle.Event.ON_RESUME)
}
@RequiresApi(Build.VERSION_CODES.O_MR1)
private suspend fun updateCurrentArtwork(artwork: Artwork) {
currentArtwork = ImageLoader.decode(
contentResolver, artwork.contentUri,
MAX_ARTWORK_SIZE / 2) ?: return
notifyColorsChanged()
}
@RequiresApi(Build.VERSION_CODES.O_MR1)
override fun onComputeColors(): WallpaperColors? =
currentArtwork?.run {
WallpaperColors.fromBitmap(this)
} ?: super.onComputeColors()
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
super.onSurfaceChanged(holder, format, width, height)
if (!isPreview) {
WallpaperSizeStateFlow.value = WallpaperSize(width, height)
}
renderController.reloadCurrentArtwork()
}
override fun onDestroy() {
wallpaperLifecycle.removeObserver(this)
engineLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
queueEvent {
renderer.destroy()
}
super<GLEngine>.onDestroy()
}
fun lockScreenVisibleChanged(isLockScreenVisible: Boolean) {
if (!EffectsLockScreenOpen.value) {
renderController.onLockScreen = isLockScreenVisible
}
}
override fun onVisibilityChanged(visible: Boolean) {
renderController.visible = visible
}
override fun onOffsetsChanged(
xOffset: Float,
yOffset: Float,
xOffsetStep: Float,
yOffsetStep: Float,
xPixelOffset: Int,
yPixelOffset: Int
) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset,
yPixelOffset)
renderer.setNormalOffsetX(xOffset)
}
override fun onZoomChanged(zoom: Float) {
super.onZoomChanged(zoom)
renderer.setZoom(zoom)
}
override fun onCommand(
action: String?,
x: Int,
y: Int,
z: Int,
extras: Bundle?,
resultRequested: Boolean
): Bundle? {
// validDoubleTap previously set in the gesture listener
if (WallpaperManager.COMMAND_TAP == action && validDoubleTap) {
val prefs = Prefs.getSharedPreferences(this@MuzeiWallpaperService)
val doubleTapValue = prefs.getString(Prefs.PREF_DOUBLE_TAP,
null) ?: Prefs.PREF_TAP_ACTION_TEMP
triggerTapAction(doubleTapValue, "gesture_double_tap")
// Reset the flag
validDoubleTap = false
}
return super.onCommand(action, x, y, z, extras, resultRequested)
}
private fun triggerTapAction(action: String, type: String) {
when (action) {
Prefs.PREF_TAP_ACTION_TEMP -> {
Firebase.analytics.logEvent("temp_disable_effects") {
param(FirebaseAnalytics.Param.CONTENT_TYPE, type)
}
// Temporarily toggle focused/blurred
queueEvent {
renderer.setIsBlurred(!renderer.isBlurred, false)
// Schedule a re-blur
delayedBlur()
}
}
Prefs.PREF_TAP_ACTION_NEXT -> {
lifecycleScope.launch(NonCancellable) {
Firebase.analytics.logEvent("next_artwork") {
param(FirebaseAnalytics.Param.CONTENT_TYPE, type)
}
LegacySourceManager.getInstance(this@MuzeiWallpaperService).nextArtwork()
}
}
Prefs.PREF_TAP_ACTION_VIEW_DETAILS -> {
lifecycleScope.launch(NonCancellable) {
val artwork = MuzeiDatabase
.getInstance(this@MuzeiWallpaperService)
.artworkDao()
.getCurrentArtwork()
artwork?.run {
Firebase.analytics.logEvent("artwork_info_open") {
param(FirebaseAnalytics.Param.CONTENT_TYPE, type)
}
openArtworkInfo(this@MuzeiWallpaperService)
}
}
}
}
}
override fun onTouchEvent(event: MotionEvent) {
super.onTouchEvent(event)
gestureDetector.onTouchEvent(event)
// Delay blur from temporary refocus while touching the screen
delayedBlur()
// See if there was a valid three finger tap
val now = SystemClock.elapsedRealtime()
val timeSinceLastThreeFingerTap = now - lastThreeFingerTap
if (event.pointerCount == 3
&& timeSinceLastThreeFingerTap > THREE_FINGER_TAP_INTERVAL_MS) {
lastThreeFingerTap = now
val prefs = Prefs.getSharedPreferences(this@MuzeiWallpaperService)
val threeFingerTapValue = prefs.getString(Prefs.PREF_THREE_FINGER_TAP,
null) ?: Prefs.PREF_TAP_ACTION_NONE
triggerTapAction(threeFingerTapValue, "gesture_three_finger")
}
}
private fun cancelDelayedBlur() {
delayedBlur?.cancel()
}
private fun delayedBlur() {
if (ArtDetailOpen.value || renderer.isBlurred) {
return
}
cancelDelayedBlur()
delayedBlur = lifecycleScope.launch {
delay(TEMPORARY_FOCUS_DURATION_MILLIS)
queueEvent {
renderer.setIsBlurred(isBlurred = true, artDetailMode = false)
}
}
}
override fun requestRender() {
if (renderController.visible) {
super.requestRender()
}
}
override fun queueEventOnGlThread(event: () -> Unit) {
queueEvent {
event()
}
}
}
} | apache-2.0 | a3e9b52b26f20c6491fc7ea10b825876 | 39.37931 | 100 | 0.625816 | 5.324131 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/log/LogSupport.kt | 1 | 6483 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.log
import slatekit.common.Ignore
import slatekit.common.newline
import java.io.PrintWriter
import java.io.StringWriter
/**
* Log methods with messages that are both eager and lazyily called via functions
* NOTE: This @Ignore attribute is used to avoid these methods in any meta/reflection processing
*/
interface LogSupport {
val logger: Logger?
/** =====================================================================
* Logging using string with optional args for formatting
*
* log.error("updating user {0}", user.id )
* ======================================================================
*/
@Ignore fun debug(msg: String?, vararg args:Any?) = log(LogLevel.Debug, null, msg, *args)
@Ignore fun info (msg: String?, vararg args:Any?) = log(LogLevel.Info , null, msg, *args)
@Ignore fun warn (msg: String?, vararg args:Any?) = log(LogLevel.Warn , null, msg, *args)
@Ignore fun error(msg: String?, vararg args:Any?) = log(LogLevel.Error, null, msg, *args)
@Ignore fun fatal(msg: String?, vararg args:Any?) = log(LogLevel.Fatal, null, msg, *args)
/** =====================================================================
* Logging using exceptions + messages
*
* log.error( ex, "upating user {0}", user.id )
* ======================================================================
*/
@Ignore fun debug(ex:Throwable?, msg: String?, vararg args:Any?) = log(LogLevel.Debug, ex, msg, *args)
@Ignore fun info (ex:Throwable?, msg: String?, vararg args:Any?) = log(LogLevel.Info , ex, msg, *args)
@Ignore fun warn (ex:Throwable?, msg: String?, vararg args:Any?) = log(LogLevel.Warn , ex, msg, *args)
@Ignore fun error(ex:Throwable?, msg: String?, vararg args:Any?) = log(LogLevel.Error, ex, msg, *args)
@Ignore fun fatal(ex:Throwable?, msg: String?, vararg args:Any?) = log(LogLevel.Fatal, ex, msg, *args)
/** =====================================================================
* Logging using exceptions only
*
* log.error( ex )
* ======================================================================
*/
@Ignore fun debug(ex:Throwable?) = log(LogLevel.Debug, ex, null)
@Ignore fun info (ex:Throwable?) = log(LogLevel.Info , ex, null)
@Ignore fun warn (ex:Throwable?) = log(LogLevel.Warn , ex, null)
@Ignore fun error(ex:Throwable?) = log(LogLevel.Error, ex, null)
@Ignore fun fatal(ex:Throwable?) = log(LogLevel.Fatal, ex, null)
/** =====================================================================
* Lazy logging
*
* log.error( "updating user" ) { " some expensive message to build" }
* ======================================================================
*/
@Ignore fun debug(msg: String? = null, callback: () -> String) = log(LogLevel.Debug, msg, callback)
@Ignore fun info (msg: String? = null, callback: () -> String) = log(LogLevel.Info , msg, callback)
@Ignore fun warn (msg: String? = null, callback: () -> String) = log(LogLevel.Warn , msg, callback)
@Ignore fun error(msg: String? = null, callback: () -> String) = log(LogLevel.Error, msg, callback)
@Ignore fun fatal(msg: String? = null, callback: () -> String) = log(LogLevel.Fatal, msg, callback)
/** =====================================================================
* Structured logging ( key-value pairs )
*
* log.error( "updating user", listOf( "user_id" to "abc123", "promo-code" to "xyz-111" ) )
* ======================================================================
*/
@Ignore fun debug(msg: String, pairs:List<Pair<String, Any?>>) = log(LogLevel.Debug, "$msg : ${format(pairs)}")
@Ignore fun info (msg: String, pairs:List<Pair<String, Any?>>) = log(LogLevel.Info , "$msg : ${format(pairs)}")
@Ignore fun warn (msg: String, pairs:List<Pair<String, Any?>>) = log(LogLevel.Warn , "$msg : ${format(pairs)}")
@Ignore fun error(msg: String, pairs:List<Pair<String, Any?>>) = log(LogLevel.Error, "$msg : ${format(pairs)}")
@Ignore fun fatal(msg: String, pairs:List<Pair<String, Any?>>) = log(LogLevel.Fatal, "$msg : ${format(pairs)}")
/**
* Logs an entry
* @param level
* @param msg
* @param ex
*/
@Ignore
fun log(level: LogLevel, ex: Throwable?, msg: String?, vararg args:Any?) {
var fmsg = msg
val hasMsg = !msg.isNullOrEmpty()
val hasArgs = args.isNotEmpty()
if(hasMsg && hasArgs) {
fmsg = format(msg ?: "", args)
}
log(level, fmsg, ex)
}
/**
* Logs key/value pairs
*/
@Ignore
fun log(level: LogLevel, ex:Throwable?, msg: String?, pairs:List<Pair<String,String>>) {
val info = pairs.joinToString { it -> it.first + "=" + it.second }
log(level, "$msg $info", ex)
}
/**
* Logs an entry
* @param level
* @param msg
* @param ex
*/
@Ignore
fun log(level: LogLevel, msg: String?, ex: Throwable? = null) {
val hasMsg = !msg.isNullOrEmpty()
val hasEx = ex != null
var fmsg = msg
if(!hasMsg && hasEx) fmsg = ex?.message
if(hasMsg && hasEx) fmsg += newline + ex?.message
logger?.let { l -> l.performLog(level, fmsg, ex) }
}
@Ignore
fun log(level: LogLevel, msg:String?, callback: () -> String) {
logger?.let { l -> l.performLog(level, msg, callback) }
}
fun trace(t:Throwable?):String {
val sw = StringWriter()
t?.printStackTrace(PrintWriter(sw))
val trace = sw.toString()
return trace
}
fun format(msg:String, args:Array<out Any?>):String = msg.format(*args)
/**
* Format key/value pairs into "structured value"
* e.g. a=1, b=2, c=3 etc for easier searches in logs
* NOTE: Logs can be configured to output JSON and/or provide structured arguments.
* This varies from logging provider so this is an easier text/classic only way to do ( for now )
*/
fun format(pairs:List<Pair<String, Any?>>):String {
return LogUtils.format(pairs)
}
}
| apache-2.0 | 557df53e26bace6e77edd6edd4abeb4e | 40.292994 | 115 | 0.546043 | 3.941033 | false | false | false | false |
byoutline/kickmaterial | app/src/main/java/com/byoutline/kickmaterial/utils/LUtils.kt | 1 | 2042 | /*
* Copyright 2014 Google Inc. 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
*
* 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.byoutline.kickmaterial.utils
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.os.Build
import android.support.annotation.AnimRes
import android.support.v4.view.animation.LinearOutSlowInInterpolator
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.Interpolator
import android.widget.ImageView
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class LUtils private constructor() {
companion object {
fun hasL() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
fun setStatusBarColor(activity: Activity, color: Int) {
if (!hasL()) return
activity.window.statusBarColor = color
}
fun toGrayscale(iv: ImageView) {
val matrix = ColorMatrix()
matrix.setSaturation(0f)
val filter = ColorMatrixColorFilter(matrix)
iv.colorFilter = filter
}
@JvmOverloads
fun loadAnimationWithLInterpolator(context: Context, @AnimRes animId: Int, interpolator: Interpolator = LinearOutSlowInInterpolator()): Animation {
val animation = AnimationUtils.loadAnimation(context, animId)
animation.interpolator = interpolator
return animation
}
}
}
| apache-2.0 | af63832e38f3cd953fe7e37c79afe349 | 33.033333 | 155 | 0.726249 | 4.640909 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/bridges/simpleTraitImpl.kt | 5 | 250 | interface A<T> {
fun foo(t: T) = "A"
}
class Z : A<String>
fun box(): String {
val z = Z()
val a: A<String> = z
return when {
z.foo("") != "A" -> "Fail #1"
a.foo("") != "A" -> "Fail #2"
else -> "OK"
}
}
| apache-2.0 | 57355fa6cd229ec20a424d2d13101b1f | 14.625 | 37 | 0.392 | 2.57732 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/statics/fields.kt | 2 | 639 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// FILE: Child.java
class Child extends Parent {
public static int b = 3;
public static int c = 4;
}
// FILE: Parent.java
class Parent {
public static int a = 1;
public static int b = 2;
}
// FILE: test.kt
fun box(): String {
if (Parent.a != 1) return "expected Parent.a == 1"
if (Parent.b != 2) return "expected Parent.b == 2"
if (Child.a != 1) return "expected Child.a == 1"
if (Child.b != 3) return "expected Child.b == 3"
if (Child.c != 4) return "expected Child.c == 4"
return "OK"
}
| apache-2.0 | 6440c7b2f3a16102af838649f671988a | 21.821429 | 72 | 0.610329 | 3.179104 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/objectToTopLevel/before/test.kt | 13 | 773 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object <caret>B {
fun test() {
X()
Y()
foo(bar)
//1.extFoo(1.extBar) // conflict
O.Y()
O.foo(O.bar)
with(O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
} | apache-2.0 | 8df4d6080b3faa5556730445effcd9b7 | 13.884615 | 75 | 0.376455 | 3.663507 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/text/parts/CodeTextPart.kt | 1 | 1958 | // 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.ui.text.parts
import com.intellij.ide.ui.text.StyledTextPaneUtils.drawRectangleAroundText
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import javax.swing.JTextPane
import javax.swing.text.StyleConstants
/**
* Text part that inserts the text using current editor font and draws the rounded rectangle around.
* @param addSpaceAround if true one space will be added before and after the provided [text].
* It is required because highlighting is wider than text bounds.
*/
@ApiStatus.Experimental
@ApiStatus.Internal
open class CodeTextPart(text: String, private val addSpaceAround: Boolean = false) : TextPart(text) {
var frameColor: Color = JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false)
init {
fontGetter = {
EditorColorsManager.getInstance().globalScheme.getFont(EditorFontType.PLAIN).deriveFont(JBFont.label().size2D)
}
editAttributes {
StyleConstants.setForeground(this, JBUI.CurrentTheme.Label.foreground())
}
}
override fun insertToTextPane(textPane: JTextPane, startOffset: Int): Int {
val textToInsert = if (addSpaceAround) "\u00A0$text\u00A0" else text
textPane.document.insertString(startOffset, textToInsert, attributes)
val endOffset = startOffset + textToInsert.length
val highlightStart = if (addSpaceAround) startOffset + 1 else startOffset
val highlightEnd = if (addSpaceAround) endOffset - 1 else endOffset
textPane.highlighter.addHighlight(highlightStart, highlightEnd) { g, _, _, _, c ->
c.drawRectangleAroundText(highlightStart, highlightEnd, g, frameColor, fill = false)
}
return endOffset
}
} | apache-2.0 | ab5dfcec528739f82271258a522d249c | 42.533333 | 120 | 0.77477 | 4.122105 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt | 1 | 5030 | package info.nightscout.androidaps.plugins.aps.loop
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.loop_fragment.*
import javax.inject.Inject
class LoopFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var dateUtil: DateUtil
private var disposable: CompositeDisposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.loop_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loop_run.setOnClickListener {
loop_lastrun.text = resourceHelper.gs(R.string.executing)
Thread { loopPlugin.invoke("Loop button", true) }.start()
}
}
@Synchronized
override fun onResume() {
super.onResume()
disposable += rxBus
.toObservable(EventLoopUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGUI()
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventLoopSetLastRunGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
clearGUI()
loop_lastrun?.text = it.text
}, { fabricPrivacy.logException(it) })
updateGUI()
sp.putBoolean(R.string.key_objectiveuseloop, true)
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
fun updateGUI() {
if (loop_request == null) return
loopPlugin.lastRun?.let {
loop_request?.text = it.request?.toSpanned() ?: ""
loop_constraintsprocessed?.text = it.constraintsProcessed?.toSpanned() ?: ""
loop_source?.text = it.source ?: ""
loop_lastrun?.text = dateUtil.dateAndTimeString(it.lastAPSRun)
?: ""
loop_smbrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest)
loop_smbexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact)
loop_tbrrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest)
loop_tbrexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBREnact)
loop_tbrsetbypump?.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml()) }
?: ""
loop_smbsetbypump?.text = it.smbSetByPump?.let { smbSetByPump -> HtmlHelper.fromHtml(smbSetByPump.toHtml()) }
?: ""
val constraints =
it.constraintsProcessed?.let { constraintsProcessed ->
val allConstraints = Constraint(0.0)
constraintsProcessed.rateConstraint?.let { rateConstraint -> allConstraints.copyReasons(rateConstraint) }
constraintsProcessed.smbConstraint?.let { smbConstraint -> allConstraints.copyReasons(smbConstraint) }
allConstraints.getMostLimitedReasons(aapsLogger)
} ?: ""
loop_constraints?.text = constraints
}
}
@Synchronized
private fun clearGUI() {
loop_request?.text = ""
loop_constraints?.text = ""
loop_constraintsprocessed?.text = ""
loop_source?.text = ""
loop_lastrun?.text = ""
loop_smbrequest_time?.text = ""
loop_smbexecution_time?.text = ""
loop_tbrrequest_time?.text = ""
loop_tbrexecution_time?.text = ""
loop_tbrsetbypump?.text = ""
loop_smbsetbypump?.text = ""
}
}
| agpl-3.0 | 17791ff6a2067ce331b4c3a5345bbdd3 | 40.229508 | 125 | 0.675944 | 4.631676 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/KotlinSourceMapCache.kt | 1 | 6202 | // 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.debugger
import com.intellij.openapi.compiler.CompilerPaths
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.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.isFile
import com.intellij.util.io.readBytes
import org.jetbrains.kotlin.caches.project.cacheByClass
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.codegen.inline.SMAPParser
import org.jetbrains.kotlin.idea.base.facet.implementingModules
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.util.caching.ConcurrentFactoryCache
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import java.io.IOException
import java.nio.file.Path
import java.util.*
@Service(Service.Level.PROJECT)
class KotlinSourceMapCache(private val project: Project) {
companion object {
private val LOG = Logger.getInstance(KotlinSourceMapCache::class.java)
fun getInstance(project: Project): KotlinSourceMapCache = project.service()
}
fun getSourceMap(file: VirtualFile, jvmName: JvmClassName): SMAP? {
val dependencies = arrayOf(
PsiModificationTracker.MODIFICATION_COUNT,
ProjectRootModificationTracker.getInstance(project)
)
data class Key(val path: String, val jvmName: JvmClassName)
val cache = project.cacheByClass(KotlinSourceMapCache::class.java, *dependencies) {
val storage = ContainerUtil.createConcurrentSoftValueMap<Key, Optional<SMAP>>()
ConcurrentFactoryCache(storage)
}
val key = Key(file.path, jvmName)
return cache.get(key) { Optional.ofNullable(findSourceMap(file, jvmName)) }.orElse(null)
}
private fun findSourceMap(file: VirtualFile, jvmName: JvmClassName): SMAP? {
val bytecode = when {
RootKindFilter.projectSources.matches(project, file) -> findCompiledModuleClass(file, jvmName)
RootKindFilter.librarySources.matches(project, file) -> findLibraryClass(jvmName)
else -> null
}
return bytecode?.let(::parseSourceMap)
}
private fun parseSourceMap(bytecode: ByteArray): SMAP? {
var debugInfo: String? = null
ClassReader(bytecode).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitSource(source: String?, debug: String?) {
debugInfo = debug
}
}, ClassReader.SKIP_FRAMES and ClassReader.SKIP_CODE)
return debugInfo?.let(SMAPParser::parseOrNull)
}
private fun findCompiledModuleClass(file: VirtualFile, jvmName: JvmClassName): ByteArray? {
val module = ProjectFileIndex.getInstance(project).getModuleForFile(file) ?: return null
findCompiledModuleClass(module, jvmName)?.let { return it }
for (implementingModule in module.implementingModules) {
findCompiledModuleClass(implementingModule, jvmName)?.let { return it }
}
return null
}
private fun findCompiledModuleClass(module: Module, jvmName: JvmClassName): ByteArray? {
for (outputRoot in CompilerPaths.getOutputPaths(arrayOf(module)).toList()) {
val path = Path.of(outputRoot, jvmName.internalName + ".class")
if (path.isFile()) {
try {
return path.readBytes()
} catch (e: IOException) {
LOG.debug("Can't read class file $jvmName", e)
return null
}
}
}
return null
}
private fun findLibraryClass(jvmName: JvmClassName): ByteArray? {
fun readFile(file: VirtualFile): ByteArray? {
try {
return file.contentsToByteArray(false)
} catch (e: IOException) {
LOG.debug("Can't read class file $jvmName", e)
return null
}
}
val classFileName = jvmName.internalName.substringAfterLast('/')
val fileFinder = VirtualFileFinderFactory.getInstance(project).create(GlobalSearchScope.allScope(project))
for (topLevelClassName in composeTopLevelClassNameVariants(jvmName)) {
val variantClassFile = fileFinder.findVirtualFileWithHeader(ClassId.fromString(topLevelClassName))
if (variantClassFile != null && topLevelClassName == jvmName.internalName) {
return readFile(variantClassFile)
}
val packageDir = variantClassFile?.parent
if (packageDir != null) {
val classFile = packageDir.findChild("$classFileName.class")
if (classFile != null) {
return readFile(classFile)
}
}
}
return null
}
// There might be classes with dollars in names (e.g. `class Foo$Bar {}`)
private fun composeTopLevelClassNameVariants(jvmName: JvmClassName): List<String> {
return buildList {
val jdiName = jvmName.internalName.replace('/', '.')
var index = jdiName.indexOf('$', startIndex = 1)
while (index >= 0) {
add(jdiName.take(index))
index = jdiName.indexOf('$', startIndex = index + 1)
}
add(jvmName.internalName)
}
}
} | apache-2.0 | 625ab5e06860194161d39a2b8e583c41 | 39.279221 | 120 | 0.680909 | 4.79289 | false | false | false | false |
bitsydarel/DBWeather | app/src/main/java/com/dbeginc/dbweather/launch/SplashFragment.kt | 1 | 2258 | /*
* Copyright (C) 2017 Darel Bitsy
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.dbeginc.dbweather.launch
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.dbeginc.dbweather.R
import com.dbeginc.dbweather.base.BaseFragment
import com.dbeginc.dbweather.databinding.FragmentSplashBinding
import com.dbeginc.dbweather.utils.utility.goToIntroScreen
import com.dbeginc.dbweather.utils.utility.goToMainScreen
/**
* A simple [Fragment] subclass.
*
*/
class SplashFragment : BaseFragment() {
private lateinit var binding: FragmentSplashBinding
private lateinit var timer: CountDownTimer
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_splash,
container,
false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
timer = object : CountDownTimer(3000, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
activity?.let {
if (preferences.get().isFirstLaunchOfApplication()) goToIntroScreen(container = it, layoutId = R.id.launchContent)
else goToMainScreen(currentScreen = it)
}
}
}
timer.start()
}
}
| gpl-3.0 | 28b35a14fd932a966d270d73bc8ee93e | 30.802817 | 134 | 0.686448 | 4.646091 | false | false | false | false |
550609334/Twobbble | app/src/main/java/com/twobbble/view/fragment/HomeFragment.kt | 1 | 4517 | package com.twobbble.view.fragment
import android.app.ActivityOptions
import android.app.Fragment
import android.app.FragmentManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v13.app.FragmentStatePagerAdapter
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.twobbble.R
import com.twobbble.event.OpenDrawerEvent
import com.twobbble.tools.log
import com.twobbble.tools.startSpeak
import com.twobbble.tools.toast
import com.twobbble.view.activity.SearchActivity
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.search_layout.*
import org.greenrobot.eventbus.EventBus
/**
* Created by liuzipeng on 2017/2/17.
*/
class HomeFragment : BaseFragment() {
val TITLE_RECENT = "RECENT"
val TITLE_POPULAR = "POPULAR"
val TITLE_FOLLOWING = "FOLLOWING"
private val mRecentFragment: ShotsFragment by lazy {
ShotsFragment.newInstance(ShotsFragment.RECENT)
}
private val mPopularFragment: ShotsFragment by lazy {
ShotsFragment.newInstance()
}
private val mFollowingFragment: FollowingFragment by lazy {
FollowingFragment()
}
private lateinit var mFragments: MutableList<Fragment>
private val mTitles: MutableList<String> by lazy {
mutableListOf(TITLE_POPULAR, TITLE_RECENT)
}
private var mPagerAdapter: PagerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
init()
return LayoutInflater.from(activity).inflate(R.layout.fragment_home, null)
}
override fun onBackPressed() {
hideSearchView()
}
private fun init() {
mFragments = arrayListOf(mPopularFragment, mRecentFragment)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
initView()
loadPager()
}
private fun initView() {
// Toolbar.inflateMenu(R.menu.search_menu)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
}
override fun onStart() {
super.onStart()
bindEvent()
}
override fun onResume() {
super.onResume()
}
private fun loadPager() {
mPagerAdapter = PagerAdapter(childFragmentManager)
mViewPager.adapter = mPagerAdapter
mTabLayout.setViewPager(mViewPager)
}
private fun bindEvent() {
Toolbar.setNavigationOnClickListener {
EventBus.getDefault().post(OpenDrawerEvent())
}
Toolbar.setOnMenuItemClickListener { menu ->
when (menu.itemId) {
R.id.mSearch -> mSearchLayout.showSearchView(Toolbar.width, {
isShowSearchBar = true
})
}
true
}
mBackBtn.setOnClickListener {
hideSearchView()
}
mSearchBtn.setOnClickListener {
search()
}
mVoiceBtn.setOnClickListener { startSpeak() }
mSearchEdit.setOnKeyListener { _, keycode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_DOWN) {//判断是否为点按下去触发的事件,如果不写,会导致该案件的事件被执行两次
when (keycode) {
KeyEvent.KEYCODE_ENTER -> search()
}
}
false
}
}
private fun hideSearchView() {
mSearchLayout.hideSearchView { isShowSearchBar = false }
}
private fun search() {
if (mSearchEdit.text != null && mSearchEdit.text.toString() != "") {
val intent = Intent(activity, SearchActivity::class.java)
intent.putExtra(SearchActivity.KEY_KEYWORD, mSearchEdit.text.toString())
startActivity(intent, ActivityOptions.
makeSceneTransitionAnimation(activity, mSearchLayout, "searchBar").toBundle())
}
}
//加inner标签才能访问外部对象
inner class PagerAdapter(fm: FragmentManager?) : FragmentStatePagerAdapter(fm) {
override fun getPageTitle(position: Int): CharSequence {
return mTitles[position]
}
override fun getItem(position: Int): Fragment = mFragments[position]
override fun getCount(): Int = mFragments.size
}
} | apache-2.0 | ba836a9f4dcf77ffeaa3dd1d331ad6d5 | 28.718121 | 116 | 0.660267 | 4.765339 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/LinearOrderInlayRenderer.kt | 1 | 4847 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.hints.InlayHintsUtils.produceUpdatedRootList
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationListener
import com.intellij.codeInsight.hints.presentation.withTranslated
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.util.SlowOperations
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.awt.*
import java.awt.event.MouseEvent
/**
* Renderer, that holds inside ordered list of [ConstrainedPresentation].
* Invariant: holds at least one presentation
*/
abstract class LinearOrderInlayRenderer<Constraint : Any>(
constrainedPresentations: Collection<ConstrainedPresentation<*, Constraint>>,
private val createPresentation: (List<ConstrainedPresentation<*, Constraint>>) -> InlayPresentation,
private val comparator: (ConstrainedPresentation<*, Constraint>) -> Int
) : PresentationContainerRenderer<Constraint> {
// Supposed to be changed rarely and rarely contains more than 1 element
private var presentations: List<ConstrainedPresentation<*, Constraint>> = SmartList(constrainedPresentations.sortedBy(comparator))
init {
assert(presentations.isNotEmpty())
}
private var cachedPresentation = createPresentation(presentations)
private var _listener: PresentationListener? = null
override fun addOrUpdate(new: List<ConstrainedPresentation<*, Constraint>>, editor: Editor, factory: InlayPresentationFactory) {
assert(new.isNotEmpty())
updateSorted(new.sortedBy(comparator), editor, factory)
}
override fun setListener(listener: PresentationListener) {
val oldListener = _listener
if (oldListener != null) {
cachedPresentation.removeListener(oldListener)
}
_listener = listener
cachedPresentation.addListener(listener)
}
private fun updateSorted(sorted: List<ConstrainedPresentation<*, Constraint>>,
editor: Editor,
factory: InlayPresentationFactory) {
// TODO [roman.ivanov] here can be handled 1 old to 1 new situation without complex algorithms and allocations
val tmp = produceUpdatedRootList(sorted, presentations, editor, factory)
val oldSize = dimension()
presentations = tmp
_listener?.let {
cachedPresentation.removeListener(it)
}
cachedPresentation = createPresentation(presentations)
_listener?.let {
cachedPresentation.addListener(it)
}
val newSize = dimension()
if (oldSize != newSize) {
cachedPresentation.fireSizeChanged(oldSize, newSize)
}
cachedPresentation.fireContentChanged(Rectangle(newSize))
}
private fun dimension() = Dimension(cachedPresentation.width, cachedPresentation.height)
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
g as Graphics2D
g.withTranslated(targetRegion.x, targetRegion.y) {
cachedPresentation.paint(g, effectsIn(textAttributes))
}
}
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
// TODO remove it when it will be clear how to solve it
return SlowOperations.allowSlowOperations(
ThrowableComputable<Int, Exception> { cachedPresentation.width })
}
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
return SlowOperations.allowSlowOperations(
ThrowableComputable<Int, Exception> { cachedPresentation.height })
}
// this should not be shown anywhere
override fun getContextMenuGroupId(inlay: Inlay<*>): String {
return "DummyActionGroup"
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
cachedPresentation.mouseClicked(event, translated)
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
cachedPresentation.mouseMoved(event, translated)
}
override fun mouseExited() {
cachedPresentation.mouseExited()
}
override fun toString(): String {
return cachedPresentation.toString()
}
@TestOnly
fun getConstrainedPresentations(): List<ConstrainedPresentation<*, Constraint>> = presentations
@ApiStatus.Internal
fun getCachedPresentation(): InlayPresentation = cachedPresentation
companion object {
fun effectsIn(attributes: TextAttributes): TextAttributes {
val result = TextAttributes()
result.effectType = attributes.effectType
result.effectColor = attributes.effectColor
return result
}
}
} | apache-2.0 | 5384947b5c1e7bdc9cf79c185af24b10 | 36.292308 | 158 | 0.758614 | 4.981501 | false | false | false | false |
hhariri/leanpub-plugin | src/main/kotlin/com/hadihariri/leanpub/LeanpubSettingsProvider.kt | 1 | 885 | package com.hadihariri.leanpub
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
@State(name = "LeanpubSettingsProvider", storages = arrayOf(
Storage(file = StoragePathMacros.PROJECT_FILE),
Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/leanpub.xml", scheme = StorageScheme.DIRECTORY_BASED)))
class LeanpubSettingsProvider : PersistentStateComponent<LeanpubSettingsProvider> {
var apikey = ""
var slug = ""
companion object {
fun create(project: Project) = ServiceManager.getService(project, LeanpubSettingsProvider::class.java)
}
override fun getState(): LeanpubSettingsProvider? {
return this
}
override fun loadState(state: LeanpubSettingsProvider?) {
this.apikey = state?.apikey ?: ""
this.slug = state?.slug ?: ""
}
} | mit | 75bd81cd1f43b70b8e0b14b8ed4245e6 | 31.814815 | 135 | 0.680226 | 4.68254 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/LineMatchingMethodVisitor.kt | 4 | 872 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import org.jetbrains.org.objectweb.asm.Label
abstract class LineMatchingMethodVisitor(
private val zeroBasedLineNumbers: ClosedRange<Int>
) : OpcodeReportingMethodVisitor() {
protected var lineMatches = false
protected var currentLine = 0
protected var lineEverMatched = false
override fun visitLineNumber(line: Int, start: Label) {
currentLine = line
lineMatches = zeroBasedLineNumbers.contains(line - 1)
if (lineMatches) {
lineEverMatched = true
}
}
override fun visitCode() {
lineEverMatched = false
lineMatches = false
currentLine = 0
}
}
| apache-2.0 | 82793b8acd9987ba43f602823bdf4e34 | 32.538462 | 158 | 0.705275 | 4.541667 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/object/fields2.kt | 4 | 975 | /*
* Copyright 2010-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 codegen.`object`.fields2
import kotlin.test.*
var global: Int = 0
get() {
println("Get global = $field")
return field
}
set(value) {
println("Set global = $value")
field = value
}
class TestClass {
var member: Int = 0
get() {
println("Get member = $field")
return field
}
set(value) {
println("Set member = $value")
field = value
}
}
@Test fun runTest1() {
global = 1
val test = TestClass()
test.member = 42
global = test.member
test.member = global
}
@ThreadLocal
val xInt = 42
@ThreadLocal
val xString = "42"
@ThreadLocal
val xAny = Any()
@Test fun runTest2() {
assertEquals(42, xInt)
assertEquals("42", xString)
assertTrue(xAny is Any)
}
| apache-2.0 | 495514fd6fbc1f44c4622a82cf374135 | 16.727273 | 101 | 0.572308 | 3.679245 | false | true | false | false |
androidx/androidx | compose/ui/ui-graphics/samples/src/main/java/androidx/compose/ui/graphics/samples/BrushSamples.kt | 3 | 2373 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun GradientBrushSample() {
Column(modifier = Modifier.fillMaxSize().wrapContentSize()) {
// Create a linear gradient that shows red in the top left corner
// and blue in the bottom right corner
val linear = Brush.linearGradient(listOf(Color.Red, Color.Blue))
Box(modifier = Modifier.size(120.dp).background(linear))
Spacer(modifier = Modifier.size(20.dp))
// Create a radial gradient centered about the drawing area that is green on
// the outer
// edge of the circle and magenta towards the center of the circle
val radial = Brush.radialGradient(listOf(Color.Green, Color.Magenta))
Box(modifier = Modifier.size(120.dp).background(radial))
Spacer(modifier = Modifier.size(20.dp))
// Create a radial gradient centered about the drawing area that is green on
// the outer
// edge of the circle and magenta towards the center of the circle
val sweep = Brush.sweepGradient(listOf(Color.Cyan, Color.Magenta))
Box(modifier = Modifier.size(120.dp).background(sweep))
}
} | apache-2.0 | 6d0075f12b4e438012ded3be5af5269a | 38.566667 | 84 | 0.743363 | 4.346154 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.