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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RP-Kit/RPKit | bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/command/group/GroupPrepareSwitchPriorityCommand.kt | 1 | 6632 | package com.rpkit.permissions.bukkit.command.group
import com.rpkit.core.service.Services
import com.rpkit.permissions.bukkit.RPKPermissionsBukkit
import com.rpkit.permissions.bukkit.group.RPKGroupService
import com.rpkit.permissions.bukkit.group.groups
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import net.md_5.bungee.api.ChatColor
import net.md_5.bungee.api.ChatColor.COLOR_CHAR
import net.md_5.bungee.api.chat.BaseComponent
import net.md_5.bungee.api.chat.ClickEvent
import net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND
import net.md_5.bungee.api.chat.HoverEvent
import net.md_5.bungee.api.chat.HoverEvent.Action.SHOW_TEXT
import net.md_5.bungee.api.chat.TextComponent
import net.md_5.bungee.api.chat.hover.content.Text
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class GroupPrepareSwitchPriorityCommand(private val plugin: RPKPermissionsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
val groupService = Services[RPKGroupService::class.java]
if (groupService == null) {
sender.sendMessage(plugin.messages.noGroupService)
return true
}
if (args.size < 2) {
sender.sendMessage(plugin.messages.groupPrepareSwitchPriorityUsage)
return true
}
val playerName = args[0]
val player = plugin.server.getPlayer(playerName)
if (player == null) {
sender.sendMessage(plugin.messages.groupViewInvalidPlayer)
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages.noMinecraftProfileService)
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(player)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages.noMinecraftProfileOther)
return true
}
val profile = minecraftProfile.profile
if (profile !is RPKProfile) {
sender.sendMessage(plugin.messages.noProfile)
return true
}
val group1 = args[1]
profile.groups.thenAccept getProfileGroups@{ profileGroups ->
profileGroups.forEach { group ->
val message = plugin.messages.groupViewItem.withParameters(group = group)
val messageComponents = mutableListOf<BaseComponent>()
var chatColor: ChatColor? = null
var chatFormat: ChatColor? = null
var messageBuffer = StringBuilder()
var i = 0
while (i < message.length) {
if (message[i] == COLOR_CHAR) {
appendComponent(messageComponents, messageBuffer, chatColor, chatFormat)
messageBuffer = StringBuilder()
if (message[i + 1] == 'x') {
chatColor =
ChatColor.of("#${message[i + 2]}${message[i + 4]}${message[i + 6]}${message[i + 8]}${message[i + 10]}${message[i + 12]}")
i += 13
} else {
val colorOrFormat = ChatColor.getByChar(message[i + 1])
if (colorOrFormat?.color != null) {
chatColor = colorOrFormat
chatFormat = null
}
if (colorOrFormat?.color == null) {
chatFormat = colorOrFormat
}
if (colorOrFormat == ChatColor.RESET) {
chatColor = null
chatFormat = null
}
i += 2
}
} else if (message.substring(
i,
(i + "\${reorder}".length).coerceAtMost(message.length)
) == "\${reorder}"
) {
val reorderButton = TextComponent("\u292d").also {
if (chatColor != null) {
it.color = chatColor
}
if (chatFormat != null) {
it.isObfuscated = chatFormat == ChatColor.MAGIC
it.isBold = chatFormat == ChatColor.BOLD
it.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH
it.isUnderlined = chatFormat == ChatColor.UNDERLINE
it.isItalic = chatFormat == ChatColor.ITALIC
}
}
reorderButton.hoverEvent =
HoverEvent(SHOW_TEXT, listOf(Text("Click to switch $group1 with ${group.name.value}")))
reorderButton.clickEvent =
ClickEvent(RUN_COMMAND, "/group switchpriority $playerName $group1 ${group.name.value}")
messageComponents.add(reorderButton)
i += "\${reorder}".length
} else {
messageBuffer.append(message[i++])
}
}
appendComponent(messageComponents, messageBuffer, chatColor, chatFormat)
sender.spigot().sendMessage(*messageComponents.toTypedArray())
}
}
return true
}
private fun appendComponent(
messageComponents: MutableList<BaseComponent>,
messageBuffer: StringBuilder,
chatColor: ChatColor?,
chatFormat: ChatColor?
) {
messageComponents.add(TextComponent(messageBuffer.toString()).also {
if (chatColor != null) {
it.color = chatColor
}
if (chatFormat != null) {
it.isObfuscated = chatFormat == ChatColor.MAGIC
it.isBold = chatFormat == ChatColor.BOLD
it.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH
it.isUnderlined = chatFormat == ChatColor.UNDERLINE
it.isItalic = chatFormat == ChatColor.ITALIC
}
})
}
} | apache-2.0 | 56d350c8b7ffce79b349fb104c3d7884 | 46.719424 | 153 | 0.544481 | 5.554439 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/database/table/RPKDrunkennessTable.kt | 1 | 4925 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.drinks.bukkit.database.table
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterId
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.drinks.bukkit.RPKDrinksBukkit
import com.rpkit.drinks.bukkit.database.create
import com.rpkit.drinks.bukkit.database.jooq.Tables.RPKIT_DRUNKENNESS
import com.rpkit.drinks.bukkit.drink.RPKDrunkenness
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level
import java.util.logging.Level.SEVERE
class RPKDrunkennessTable(private val database: Database, private val plugin: RPKDrinksBukkit) : Table {
private val cache = if (plugin.config.getBoolean("caching.rpkit_drunkenness.character_id.enabled")) {
database.cacheManager.createCache(
"rpk-drinks-bukkit.rpkit_drunkenness.character_id",
Int::class.javaObjectType,
RPKDrunkenness::class.java,
plugin.config.getLong("caching.rpkit_drunkenness.character_id.size")
)
} else {
null
}
fun insert(entity: RPKDrunkenness): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.insertInto(
RPKIT_DRUNKENNESS,
RPKIT_DRUNKENNESS.CHARACTER_ID,
RPKIT_DRUNKENNESS.DRUNKENNESS
)
.values(
characterId.value,
entity.drunkenness
)
.execute()
cache?.set(characterId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert drunkenness", exception)
throw exception
}
}
fun update(entity: RPKDrunkenness): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.update(RPKIT_DRUNKENNESS)
.set(RPKIT_DRUNKENNESS.DRUNKENNESS, entity.drunkenness)
.where(RPKIT_DRUNKENNESS.CHARACTER_ID.eq(characterId.value))
.execute()
cache?.set(characterId.value, entity)
}
}
operator fun get(character: RPKCharacter): CompletableFuture<RPKDrunkenness?> {
val characterId = character.id ?: return CompletableFuture.completedFuture(null)
if (cache?.containsKey(characterId.value) == true) {
return CompletableFuture.completedFuture(cache[characterId.value])
}
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_DRUNKENNESS.CHARACTER_ID,
RPKIT_DRUNKENNESS.DRUNKENNESS
)
.from(RPKIT_DRUNKENNESS)
.where(RPKIT_DRUNKENNESS.CHARACTER_ID.eq(characterId.value))
.fetchOne() ?: return@supplyAsync null
val drunkenness = RPKDrunkenness(
character,
result.get(RPKIT_DRUNKENNESS.DRUNKENNESS)
)
cache?.set(characterId.value, drunkenness)
return@supplyAsync drunkenness
}
}
fun delete(entity: RPKDrunkenness): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.deleteFrom(RPKIT_DRUNKENNESS)
.where(RPKIT_DRUNKENNESS.CHARACTER_ID.eq(characterId.value))
.execute()
cache?.remove(characterId.value)
}
}
fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_DRUNKENNESS)
.where(RPKIT_DRUNKENNESS.CHARACTER_ID.eq(characterId.value))
.execute()
cache?.removeMatching { it.character.id?.value == characterId.value }
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete drunkenness for character id", exception)
throw exception
}
} | apache-2.0 | 619fca0142adf816b08eb6857f607247 | 38.725806 | 105 | 0.649949 | 4.611423 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/ErrorReporter.kt | 1 | 5216 | package com.fwdekker.randomness
import com.intellij.ide.BrowserUtil
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.util.Consumer
import java.awt.Component
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
/**
* A report submitter that opens a pre-filled issue creation form on Randomness' GitHub repository.
*
* This class pertains to reports of exceptions that are not caught by the plugin and end up being shown to the user
* as a notification by the IDE.
*/
class ErrorReporter : ErrorReportSubmitter() {
/**
* Returns the text that is displayed in the button to report the error.
*
* @return the text that is displayed in the button to report the error
*/
override fun getReportActionText() = Bundle("reporter.report")
/**
* Submits the exception by opening the browser to create an issue on GitHub.
*
* @param events ignored
* @param additionalInfo additional information provided by the user
* @param parentComponent ignored
* @param consumer ignored
* @return `true`
*/
override fun submit(
events: Array<IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component,
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent))
object : Backgroundable(project, Bundle("reporter.opening")) {
override fun run(indicator: ProgressIndicator) {
BrowserUtil.open(getIssueUrl(additionalInfo))
consumer.consume(
SubmittedReportInfo(
"https://github.com/FWDekker/intellij-randomness/issues",
Bundle("reporter.issue"),
SubmittedReportInfo.SubmissionStatus.NEW_ISSUE
)
)
}
}.queue()
return true
}
/**
* Returns the privacy notice text.
*
* @return the privacy notice text
*/
override fun getPrivacyNoticeText() = Bundle("reporter.privacy_notice")
/**
* Constructs a URL to create an issue with [additionalInfo] that is below the maximum URL limit.
*
* @param additionalInfo additional information about the exception provided by the user
* @return a URL to create an issue with [additionalInfo] that is below the maximum URL limit
*/
fun getIssueUrl(additionalInfo: String?): String {
val baseUrl = "https://github.com/FWDekker/intellij-randomness/issues/new?body="
val additionalInfoSection = createMarkdownSection(
"Additional info",
if (additionalInfo.isNullOrBlank()) MORE_DETAIL_MESSAGE else additionalInfo
)
val stacktraceSection = createMarkdownSection(
"Stacktraces",
STACKTRACE_MESSAGE
)
val versionSection = createMarkdownSection(
"Version information",
getFormattedVersionInformation()
)
return URLEncoder.encode(additionalInfoSection + stacktraceSection + versionSection, StandardCharsets.UTF_8)
.replace("%2B", "+")
.let { baseUrl + it }
}
/**
* Creates a Markdown "section" containing the title in bold followed by the contents on the next line, finalized by
* two newlines.
*
* @param title the title of the section
* @param contents the contents of the section
* @return a Markdown "section" with the [title] and [contents]
*/
private fun createMarkdownSection(title: String, contents: String) = "**${title.trim()}**\n${contents.trim()}\n\n"
/**
* Returns version information on the user's environment as a Markdown-style list.
*
* @return version information on the user's environment as a Markdown-style list
*/
private fun getFormattedVersionInformation() =
"""
- Randomness version: ${pluginDescriptor?.version ?: "_Unknown_"}
- IDE version: ${ApplicationInfo.getInstance().apiVersion}
- Operating system: ${System.getProperty("os.name")}
- Java version: ${System.getProperty("java.version")}
""".trimIndent()
/**
* Holds constants.
*/
companion object {
/**
* Message asking the user to provide more information about the exception.
*/
const val MORE_DETAIL_MESSAGE =
"Please describe your issue in more detail here. What were you doing when the exception occurred?"
/**
* Message asking the user to provide stacktrace information.
*/
const val STACKTRACE_MESSAGE =
"Please paste the full stacktrace from the IDE's error popup below.\n```java\n\n```"
}
}
| mit | 5c7060a9885be80f2f969573d9c5cd57 | 36.797101 | 120 | 0.662002 | 5.005758 | false | false | false | false |
cketti/k-9 | app/ui/message-list-widget/src/main/java/app/k9mail/ui/widget/list/MessageListWidgetProvider.kt | 1 | 3426 | package app.k9mail.ui.widget.list
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import com.fsck.k9.activity.MessageCompose
import com.fsck.k9.activity.MessageList
import com.fsck.k9.activity.MessageList.Companion.intentDisplaySearch
import com.fsck.k9.helper.PendingIntentCompat.FLAG_IMMUTABLE
import com.fsck.k9.helper.PendingIntentCompat.FLAG_MUTABLE
import com.fsck.k9.search.SearchAccount.Companion.createUnifiedInboxAccount
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import com.fsck.k9.ui.R as UiR
open class MessageListWidgetProvider : AppWidgetProvider(), KoinComponent {
private val messageListWidgetManager: MessageListWidgetManager by inject()
override fun onEnabled(context: Context) {
messageListWidgetManager.onWidgetAdded()
}
override fun onDisabled(context: Context) {
messageListWidgetManager.onWidgetRemoved()
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
private fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
val views = RemoteViews(context.packageName, R.layout.message_list_widget_layout)
views.setTextViewText(R.id.folder, context.getString(UiR.string.integrated_inbox_title))
val intent = Intent(context, MessageListWidgetService::class.java)
views.setRemoteAdapter(R.id.listView, intent)
val viewAction = viewActionTemplatePendingIntent(context)
views.setPendingIntentTemplate(R.id.listView, viewAction)
val composeAction = composeActionPendingIntent(context)
views.setOnClickPendingIntent(R.id.new_message, composeAction)
val headerClickAction = viewUnifiedInboxPendingIntent(context)
views.setOnClickPendingIntent(R.id.top_controls, headerClickAction)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
private fun viewActionTemplatePendingIntent(context: Context): PendingIntent {
val intent = MessageList.actionDisplayMessageTemplateIntent(
context,
openInUnifiedInbox = true,
messageViewOnly = true
)
return PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_MUTABLE)
}
private fun viewUnifiedInboxPendingIntent(context: Context): PendingIntent {
val unifiedInboxAccount = createUnifiedInboxAccount()
val intent = intentDisplaySearch(
context = context,
search = unifiedInboxAccount.relatedSearch,
noThreading = true,
newTask = true,
clearTop = true
)
return PendingIntent.getActivity(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
}
private fun composeActionPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, MessageCompose::class.java).apply {
action = MessageCompose.ACTION_COMPOSE
}
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
}
}
| apache-2.0 | 761e28e42054d7f4c8f70709cf3bacca | 39.305882 | 114 | 0.744308 | 4.764951 | false | false | false | false |
dslomov/intellij-community | platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt | 2 | 7296 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.application.options.PathMacrosImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.StreamProvider
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.*
import com.intellij.util.SmartList
import com.intellij.util.xmlb.XmlSerializerUtil
import gnu.trove.THashMap
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.intellij.lang.annotations.Language
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.InputStream
import kotlin.properties.Delegates
class ApplicationStoreTest {
companion object {
ClassRule val projectRule = ProjectRule()
}
private val tempDirManager = TemporaryDirectory()
public Rule fun getTemporaryFolder(): TemporaryDirectory = tempDirManager
private val edtRule = EdtRule()
public Rule fun _edtRule(): EdtRule = edtRule
private var testAppConfig: VirtualFile by Delegates.notNull()
private var componentStore: MyComponentStore by Delegates.notNull()
public Before fun setUp() {
testAppConfig = tempDirManager.newVirtualDirectory()
componentStore = MyComponentStore(FileUtilRt.toSystemIndependentName(testAppConfig.getPath()))
}
public Test fun `stream provider save if several storages configured`() {
val component = SeveralStoragesConfigured()
val streamProvider = MyStreamProvider()
componentStore.storageManager.setStreamProvider(streamProvider)
componentStore.initComponent(component, false)
component.foo = "newValue"
componentStore.save(SmartList())
assertThat<String>(streamProvider.data.get(RoamingType.PER_USER)!!.get(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml"), equalTo("<application>\n" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"newValue\" />\n" + " </component>\n" + "</application>"))
}
public Test fun testLoadFromStreamProvider() {
val component = SeveralStoragesConfigured()
val streamProvider = MyStreamProvider()
val map = THashMap<String, String>()
map.put(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml", "<application>\n" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"newValue\" />\n" + " </component>\n" + "</application>")
streamProvider.data.put(RoamingType.PER_USER, map)
componentStore.storageManager.setStreamProvider(streamProvider)
componentStore.initComponent(component, false)
assertThat(component.foo, equalTo("newValue"))
}
public @Test @RunsInEdt fun `remove deprecated storage on write`() {
doRemoveDeprecatedStorageOnWrite(SeveralStoragesConfigured())
}
public @Test @RunsInEdt fun `remove deprecated storage on write 2`() {
doRemoveDeprecatedStorageOnWrite(ActualStorageLast())
}
private fun doRemoveDeprecatedStorageOnWrite(component: Foo) {
val oldFile = writeConfig("other.xml", "<application><component name=\"HttpConfigurable\"><option name=\"foo\" value=\"old\" /></component></application>")
writeConfig("proxy.settings.xml", "<application><component name=\"HttpConfigurable\"><option name=\"foo\" value=\"new\" /></component></application>")
componentStore.initComponent(component, false)
assertThat(component.foo, equalTo("new"))
component.foo = "new2"
componentStore.save(SmartList())
assertThat(oldFile.exists(), equalTo(false))
}
private fun writeConfig(fileName: String, Language("XML") data: String) = runWriteAction { testAppConfig.writeChild(fileName, data) }
private class MyStreamProvider : StreamProvider {
public val data: MutableMap<RoamingType, MutableMap<String, String>> = THashMap()
override fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
getMap(roamingType).put(fileSpec, String(content, 0, size, CharsetToolkit.UTF8_CHARSET))
}
private fun getMap(roamingType: RoamingType): MutableMap<String, String> {
var map = data.get(roamingType)
if (map == null) {
map = THashMap<String, String>()
data.put(roamingType, map)
}
return map
}
override fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? {
val data = getMap(roamingType).get(fileSpec) ?: return null
return ByteArrayInputStream(data.toByteArray())
}
override fun delete(fileSpec: String, roamingType: RoamingType) {
data.get(roamingType)?.remove(fileSpec)
}
}
class MyComponentStore(testAppConfigPath: String) : ComponentStoreImpl() {
override val storageManager = object : StateStorageManagerImpl("application") {
override fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? {
if (fileSpec == "${StoragePathMacros.APP_CONFIG}/${PathMacrosImpl.EXT_FILE_NAME}.xml") {
return null
}
return super.getMacroSubstitutor(fileSpec)
}
}
init {
setPath(testAppConfigPath)
}
override fun setPath(path: String) {
storageManager.addMacro(StoragePathMacros.APP_CONFIG, path)
}
override fun getMessageBus() = ApplicationManager.getApplication().getMessageBus()
}
abstract class Foo {
public var foo: String = "defaultValue"
}
State(name = "HttpConfigurable", storages = arrayOf(Storage(file = StoragePathMacros.APP_CONFIG + "/proxy.settings.xml"), Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml", deprecated = true)))
class SeveralStoragesConfigured : Foo(), PersistentStateComponent<SeveralStoragesConfigured> {
override fun getState(): SeveralStoragesConfigured? {
return this
}
override fun loadState(state: SeveralStoragesConfigured) {
XmlSerializerUtil.copyBean(state, this)
}
}
State(name = "HttpConfigurable", storages = arrayOf(Storage(file = "${StoragePathMacros.APP_CONFIG}/other.xml", deprecated = true), Storage(file = "${StoragePathMacros.APP_CONFIG}/proxy.settings.xml")))
class ActualStorageLast : Foo(), PersistentStateComponent<ActualStorageLast> {
override fun getState() = this
override fun loadState(state: ActualStorageLast) {
XmlSerializerUtil.copyBean(state, this)
}
}
}
fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data)
val VirtualFile.path: String
get() = getPath() | apache-2.0 | d81bf1cb58dcb82a7e599c421d19e6dc | 38.657609 | 296 | 0.740269 | 4.698004 | false | true | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/collections/operation/SortingSample.kt | 1 | 1969 | package tutorial.collections.operation
class Version(val major: Int, val minor: Int) : Comparable<Version> {
override fun compareTo(other: Version): Int {
if (this.major != other.major) {
return this.major - other.major
} else if (this.minor != other.minor) {
return this.minor - other.minor
} else return 0
}
}
fun main() {
println(Version(1, 2) > Version(1, 3)) // false
println(Version(2, 0) > Version(1, 5)) // true
val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator)) // [c, bb, aaa]
println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length })) // [c, bb, aaa]
val numbers = listOf("one", "two", "three", "four")
println("Sorted ascending: ${numbers.sorted()}") // Sorted ascending: [four, one, three, two]
println("Sorted descending: ${numbers.sortedDescending()}") // Sorted descending: [two, three, one, four]
println("Sorted by length ascending: ${numbers.sortedBy { it.length }}") // Sorted by length ascending: [one, two, four, three]
println("Sorted by the last letter descending: ${numbers.sortedByDescending { it.last() }}") // Sorted by the last letter descending: [four, two, one, three]
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length })}") // Sorted by length ascending: [one, two, four, three]
println(numbers.reversed()) // [four, three, two, one]
val reversedNumbers = numbers.asReversed()
println(reversedNumbers) // [four, three, two, one]
println(numbers) // [one, two, three, four]
val numbers2 = mutableListOf("one", "two", "three", "four")
val reversedNumbers2 = numbers2.asReversed()
println(reversedNumbers2) // [four, three, two, one]
numbers2.add("five")
println(reversedNumbers2) // [five, four, three, two, one]
println(numbers.shuffled())
} | bsd-2-clause | 98e081cc8cf12c00527d292d22bc57e2 | 44.813953 | 161 | 0.64906 | 3.764818 | false | false | false | false |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/gdx/PointSpriteParticleBatch.kt | 1 | 7763 | package xyz.jmullin.drifter.gdx
import com.badlogic.gdx.Application
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g3d.Material
import com.badlogic.gdx.graphics.g3d.Renderable
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute
import com.badlogic.gdx.graphics.g3d.attributes.DepthTestAttribute
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute.AlphaTest
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute
import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels
import com.badlogic.gdx.graphics.g3d.particles.ParticleShader
import com.badlogic.gdx.graphics.g3d.particles.ResourceData
import com.badlogic.gdx.graphics.g3d.particles.batches.BufferedParticleBatch
import com.badlogic.gdx.graphics.g3d.particles.renderers.PointSpriteControllerRenderData
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.Pool
open class PointSpriteParticleBatch @JvmOverloads constructor(
capacity: Int = 1000,
shaderConfig: ParticleShader.Config = ParticleShader.Config(ParticleShader.ParticleType.Point),
val srcBlend: Int,
val dstBlend: Int) : BufferedParticleBatch<PointSpriteControllerRenderData>(PointSpriteControllerRenderData::class.java) {
private var vertices: FloatArray = FloatArray(0)
var renderable: Renderable = Renderable()
init {
if (!pointSpritesEnabled) enablePointSprites()
allocRenderable()
ensureCapacity(capacity)
renderable.shader = ParticleShader(renderable, shaderConfig, "")
renderable.shader.init()
}
override fun allocParticlesData(capacity: Int) {
vertices = FloatArray(capacity * CPU_VERTEX_SIZE)
if (renderable.meshPart.mesh != null) renderable.meshPart.mesh.dispose()
renderable.meshPart.mesh = Mesh(false, capacity, 0, CPU_ATTRIBUTES)
}
protected fun allocRenderable() {
renderable = Renderable()
renderable.meshPart.primitiveType = GL20.GL_POINTS
renderable.meshPart.offset = 0
@Suppress("CAST_NEVER_SUCCEEDS")
renderable.material = Material(
BlendingAttribute(true, srcBlend, dstBlend, 0.5f),
FloatAttribute(AlphaTest, 0.05f),
DepthTestAttribute(GL20.GL_LEQUAL, false),
TextureAttribute.createDiffuse(null as? Texture)
)
}
var texture: Texture
get() {
val attribute = renderable.material.get(TextureAttribute.Diffuse) as TextureAttribute
return attribute.textureDescription.texture
}
set(texture) {
val attribute = renderable.material.get(TextureAttribute.Diffuse) as TextureAttribute
attribute.textureDescription.texture = texture
}
override fun flush(offsets: IntArray) {
var tp = 0
for (data in renderData) {
val scaleChannel = data.scaleChannel
val regionChannel = data.regionChannel
val positionChannel = data.positionChannel
val colorChannel = data.colorChannel
val rotationChannel = data.rotationChannel
var p = 0
while (p < data.controller.particles.size) {
val offset = offsets[tp] * CPU_VERTEX_SIZE
val regionOffset = p * regionChannel.strideSize
val positionOffset = p * positionChannel.strideSize
val colorOffset = p * colorChannel.strideSize
val rotationOffset = p * rotationChannel.strideSize
vertices[offset + CPU_POSITION_OFFSET] = positionChannel.data[positionOffset + ParticleChannels.XOffset]
vertices[offset + CPU_POSITION_OFFSET + 1] = positionChannel.data[positionOffset + ParticleChannels.YOffset]
vertices[offset + CPU_POSITION_OFFSET + 2] = positionChannel.data[positionOffset + ParticleChannels.ZOffset]
vertices[offset + CPU_COLOR_OFFSET] = colorChannel.data[colorOffset + ParticleChannels.RedOffset]
vertices[offset + CPU_COLOR_OFFSET + 1] = colorChannel.data[colorOffset + ParticleChannels.GreenOffset]
vertices[offset + CPU_COLOR_OFFSET + 2] = colorChannel.data[colorOffset + ParticleChannels.BlueOffset]
vertices[offset + CPU_COLOR_OFFSET + 3] = colorChannel.data[colorOffset + ParticleChannels.AlphaOffset]
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET] = scaleChannel.data[p * scaleChannel.strideSize]
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 1] = rotationChannel.data[rotationOffset + ParticleChannels.CosineOffset]
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 2] = rotationChannel.data[rotationOffset + ParticleChannels.SineOffset]
vertices[offset + CPU_REGION_OFFSET] = regionChannel.data[regionOffset + ParticleChannels.UOffset]
vertices[offset + CPU_REGION_OFFSET + 1] = regionChannel.data[regionOffset + ParticleChannels.VOffset]
vertices[offset + CPU_REGION_OFFSET + 2] = regionChannel.data[regionOffset + ParticleChannels.U2Offset]
vertices[offset + CPU_REGION_OFFSET + 3] = regionChannel.data[regionOffset + ParticleChannels.V2Offset]
++p
++tp
}
}
renderable.meshPart.size = bufferedParticlesCount
renderable.meshPart.mesh.setVertices(vertices, 0, bufferedParticlesCount * CPU_VERTEX_SIZE)
renderable.meshPart.update()
}
override fun getRenderables(renderables: Array<Renderable>, pool: Pool<Renderable>) {
if (bufferedParticlesCount > 0) renderables.add(pool.obtain().set(renderable))
}
override fun save(manager: AssetManager, resources: ResourceData<*>) {
val data = resources.createSaveData("pointSpriteBatch")
data.saveAsset(manager.getAssetFileName(texture), Texture::class.java)
}
override fun load(manager: AssetManager, resources: ResourceData<*>) {
val data = resources.getSaveData("pointSpriteBatch")
if (data != null) texture = manager.get(data.loadAsset()) as Texture
}
companion object {
private var pointSpritesEnabled = false
protected val sizeAndRotationUsage = 1 shl 9
protected val CPU_ATTRIBUTES = VertexAttributes(VertexAttribute(VertexAttributes.Usage.Position, 3,
ShaderProgram.POSITION_ATTRIBUTE), VertexAttribute(VertexAttributes.Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 4, "a_region"), VertexAttribute(sizeAndRotationUsage, 3,
"a_sizeAndRotation"))
protected val CPU_VERTEX_SIZE = (CPU_ATTRIBUTES.vertexSize / 4).toShort().toInt()
protected val CPU_POSITION_OFFSET = (CPU_ATTRIBUTES.findByUsage(VertexAttributes.Usage.Position).offset / 4).toShort().toInt()
protected val CPU_COLOR_OFFSET = (CPU_ATTRIBUTES.findByUsage(VertexAttributes.Usage.ColorUnpacked).offset / 4).toShort().toInt()
protected val CPU_REGION_OFFSET = (CPU_ATTRIBUTES.findByUsage(VertexAttributes.Usage.TextureCoordinates).offset / 4).toShort().toInt()
protected val CPU_SIZE_AND_ROTATION_OFFSET = (CPU_ATTRIBUTES.findByUsage(sizeAndRotationUsage).offset / 4).toShort().toInt()
private fun enablePointSprites() {
Gdx.gl.glEnable(GL20.GL_VERTEX_PROGRAM_POINT_SIZE)
if (Gdx.app.type == Application.ApplicationType.Desktop) {
Gdx.gl.glEnable(0x8861) // GL_POINT_OES
}
pointSpritesEnabled = true
}
}
} | mit | c118276424fcf1afc08d07641a8b6d70 | 51.459459 | 142 | 0.703594 | 4.388355 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/notification/NotificationWorker.kt | 1 | 5783 | package me.proxer.app.notification
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.rubengees.rxbus.RxBus
import me.proxer.app.news.NewsNotificationEvent
import me.proxer.app.news.NewsNotifications
import me.proxer.app.util.WorkerUtils
import me.proxer.app.util.data.PreferenceHelper
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.toInstantBP
import me.proxer.library.ProxerApi
import me.proxer.library.ProxerCall
import me.proxer.library.entity.notifications.NotificationInfo
import me.proxer.library.enums.NotificationFilter
import timber.log.Timber
import java.util.concurrent.TimeUnit
/**
* @author Ruben Gees
*/
class NotificationWorker(
context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
companion object {
private const val NAME = "NotificationWorker"
private val bus by safeInject<RxBus>()
private val workManager by safeInject<WorkManager>()
private val preferenceHelper by safeInject<PreferenceHelper>()
fun enqueueIfPossible(delay: Boolean = false) {
val areNotificationsEnabled = preferenceHelper.areNewsNotificationsEnabled ||
preferenceHelper.areAccountNotificationsEnabled
if (areNotificationsEnabled) {
enqueue(delay)
} else {
cancel()
}
}
fun cancel() {
workManager.cancelUniqueWork(NAME)
}
private fun enqueue(delay: Boolean) {
val interval = preferenceHelper.notificationsInterval * 1_000 * 60
val workRequest = PeriodicWorkRequestBuilder<NotificationWorker>(interval, TimeUnit.MILLISECONDS)
.apply { if (delay) setInitialDelay(interval, TimeUnit.MILLISECONDS) }
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15, TimeUnit.SECONDS)
.build()
workManager.enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.KEEP, workRequest)
}
}
private val api by safeInject<ProxerApi>()
private val storageHelper by safeInject<StorageHelper>()
private var currentCall: ProxerCall<*>? = null
override fun onStopped() {
currentCall?.cancel()
}
override fun doWork() = try {
val notificationInfo = when (storageHelper.isLoggedIn) {
true ->
api.notifications.notificationInfo()
.build()
.also { currentCall = it }
.execute()
false -> null
}
val areNewsNotificationsEnabled = preferenceHelper.areNewsNotificationsEnabled
val areAccountNotificationsEnabled = preferenceHelper.areAccountNotificationsEnabled
if (!isStopped && areNewsNotificationsEnabled && notificationInfo != null) {
fetchNews(applicationContext, notificationInfo)
}
if (!isStopped && areAccountNotificationsEnabled && notificationInfo != null) {
fetchAccountNotifications(applicationContext, notificationInfo)
}
Result.success()
} catch (error: Throwable) {
Timber.e(error)
if (WorkerUtils.shouldRetryForError(error)) {
Result.retry()
} else {
Result.failure()
}
}
private fun fetchNews(context: Context, notificationInfo: NotificationInfo?) {
val lastNewsDate = preferenceHelper.lastNewsDate
val newNews = when (notificationInfo?.newsAmount) {
0 -> emptyList()
else ->
api.notifications.news()
.page(0)
.limit(notificationInfo?.newsAmount ?: 100)
.build()
.also { currentCall = it }
.safeExecute()
.asSequence()
.filter { it.date.toInstantBP().isAfter(lastNewsDate) }
.sortedByDescending { it.date }
.toList()
}
newNews.firstOrNull()?.date?.toInstantBP()?.let {
if (!isStopped && it != lastNewsDate && !bus.post(NewsNotificationEvent())) {
NewsNotifications.showOrUpdate(context, newNews)
preferenceHelper.lastNewsDate = it
}
}
}
private fun fetchAccountNotifications(context: Context, notificationInfo: NotificationInfo) {
val lastNotificationsDate = storageHelper.lastNotificationsDate
val newNotifications = when (notificationInfo.notificationAmount) {
0 -> emptyList()
else ->
api.notifications.notifications()
.page(0)
.limit(notificationInfo.notificationAmount)
.filter(NotificationFilter.UNREAD)
.build()
.also { currentCall = it }
.safeExecute()
}
newNotifications.firstOrNull()?.date?.toInstantBP()?.let {
if (!isStopped && it != lastNotificationsDate && !bus.post(AccountNotificationEvent())) {
AccountNotifications.showOrUpdate(context, newNotifications)
storageHelper.lastNotificationsDate = it
}
}
}
}
| gpl-3.0 | 61583802f07e131a56785c3b7afeca57 | 34.697531 | 109 | 0.627356 | 5.476326 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/info/ProfileInfoFragment.kt | 1 | 3340 | package uk.co.appsbystudio.geoshare.friends.profile.info
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.fragment_profile_info.*
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.friends.manager.FriendsManager
import uk.co.appsbystudio.geoshare.utils.TrackingPreferencesHelper
import uk.co.appsbystudio.geoshare.utils.dialog.ShareOptions
class ProfileInfoFragment : Fragment(), ProfileInfoView {
lateinit var uid: String
private var presenter: ProfileInfoPresenter? = null
companion object {
fun newInstance(uid: String?) = ProfileInfoFragment().apply {
arguments = Bundle().apply {
putString("uid", uid)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.fragment_profile_info, container, false)
uid = arguments?.getString("uid").toString()
presenter = ProfileInfoPresenterImpl(this,
TrackingPreferencesHelper(context?.getSharedPreferences("tracking", Context.MODE_PRIVATE)),
ProfileInfoInteractorImpl())
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter?.updateCurrentLocation(uid)
presenter?.updateTrackingState(uid)
constraint_request_location_profile.setOnClickListener {
presenter?.requestLocation(uid)
}
constraint_share_location_profile.setOnClickListener {
presenter?.shareLocation(uid)
}
constraint_delete_location_profile.setOnClickListener {
presenter?.removeLocation(uid)
}
}
override fun setShareText(string: String) {
text_share_location_profile?.text = string
}
override fun setLocationItemText(address: LiveData<String>?, timestamp: String?) {
text_timestamp_profile?.text = timestamp
val observer = Observer<String> { t ->
text_location_profile.text = t
}
if (address == null) {
text_location_profile.text = getString(R.string.no_location)
}
address?.observe(this, observer)
}
override fun showShareDialog() {
val arguments = Bundle()
arguments.putString("name", FriendsManager.friendsMap[uid])
arguments.putString("friendId", uid)
arguments.putString("uid", FirebaseAuth.getInstance()?.currentUser?.uid)
val fragmentManager = activity?.fragmentManager
val friendDialog = ShareOptions()
friendDialog.arguments = arguments
friendDialog.show(fragmentManager, "location_dialog")
}
override fun deleteButtonVisibility(visible: Int) {
constraint_delete_location_profile?.visibility = visible
}
override fun showToast(error: String) {
Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
}
} | apache-2.0 | e85e5bde0ec317d67b2353619ee42414 | 32.079208 | 116 | 0.694611 | 4.819625 | false | false | false | false |
shantstepanian/obevo | obevo-db/src/main/java/com/gs/obevo/db/impl/core/DbDeployerAppContextImpl.kt | 1 | 15220 | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.gs.obevo.db.impl.core
import com.gs.obevo.api.appdata.Change
import com.gs.obevo.api.appdata.ChangeInput
import com.gs.obevo.api.appdata.ChangeKey
import com.gs.obevo.api.appdata.doc.TextMarkupDocumentSection
import com.gs.obevo.api.platform.*
import com.gs.obevo.db.api.appdata.DbEnvironment
import com.gs.obevo.db.api.platform.DbChangeType
import com.gs.obevo.db.api.platform.DbDeployerAppContext
import com.gs.obevo.db.api.platform.DbPlatform
import com.gs.obevo.db.impl.core.changeauditdao.NoOpChangeAuditDao
import com.gs.obevo.db.impl.core.changeauditdao.SameSchemaChangeAuditDao
import com.gs.obevo.db.impl.core.changeauditdao.SameSchemaDeployExecutionDao
import com.gs.obevo.db.impl.core.changetypes.*
import com.gs.obevo.db.impl.core.checksum.DbChecksumDao
import com.gs.obevo.db.impl.core.checksum.DbChecksumManager
import com.gs.obevo.db.impl.core.checksum.DbChecksumManagerImpl
import com.gs.obevo.db.impl.core.checksum.SameSchemaDbChecksumDao
import com.gs.obevo.db.impl.core.cleaner.DbEnvironmentCleaner
import com.gs.obevo.db.impl.core.envinfrasetup.EnvironmentInfraSetup
import com.gs.obevo.db.impl.core.envinfrasetup.NoOpEnvironmentInfraSetup
import com.gs.obevo.db.impl.core.jdbc.DataSourceFactory
import com.gs.obevo.db.impl.core.jdbc.SingleConnectionDataSource
import com.gs.obevo.db.impl.core.reader.BaselineTableChangeParser
import com.gs.obevo.db.impl.core.reader.PrepareDbChangeForDb
import com.gs.obevo.dbmetadata.api.DbMetadataManager
import com.gs.obevo.impl.ChangeTypeBehaviorRegistry
import com.gs.obevo.impl.ChangeTypeBehaviorRegistry.ChangeTypeBehaviorRegistryBuilder
import com.gs.obevo.impl.DeployerPlugin
import com.gs.obevo.impl.PrepareDbChange
import com.gs.obevo.impl.changepredicate.ChangeKeyPredicateBuilder
import com.gs.obevo.impl.context.AbstractDeployerAppContext
import com.gs.obevo.impl.reader.GetChangeType
import com.gs.obevo.util.CollectionUtil
import com.gs.obevo.util.inputreader.Credential
import org.apache.commons.lang3.Validate
import org.eclipse.collections.api.block.predicate.Predicate
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.impl.block.factory.Predicates
import org.eclipse.collections.impl.factory.Lists
import javax.sql.DataSource
abstract class DbDeployerAppContextImpl : AbstractDeployerAppContext<DbEnvironment, DbDeployerAppContext>(), DbDeployerAppContext {
private var strictSetupEnvInfra = DbDeployerAppContext.STRICT_SETUP_ENV_INFRA_DEFAULT
/**
* Renamed.
*
*/
val isFailOnSetupException: Boolean
@Deprecated("Renamed to {@link #isStrictSetupEnvInfra()}")
get() = isStrictSetupEnvInfra()
private val dbChecksumManager: DbChecksumManager
get() = this.singleton("getDbChecksumManager") {
DbChecksumManagerImpl(
dbMetadataManager,
dbChecksumDao,
env.physicalSchemas
)
}
private val tableSqlSuffix: String
get() = platform().getTableSuffixSql(env)
private val environmentCleaner: DbEnvironmentCleaner
get() = this.singleton("getEnvironmentCleaner") {
DbEnvironmentCleaner(env, sqlExecutor, dbMetadataManager,
changesetCreator, changeTypeBehaviorRegistry)
}
protected abstract val dataSourceFactory: DataSourceFactory
protected open val environmentInfraSetup: EnvironmentInfraSetup<*>
get() = NoOpEnvironmentInfraSetup()
open val csvStaticDataLoader: CsvStaticDataDeployer
get() = CsvStaticDataDeployer(env, this.sqlExecutor, managedDataSource,
this.dbMetadataManager, this.platform())
protected// reserve an extra connection for actions done on the regular DS and not the per-thread DS
val managedDataSource: DataSource
get() = this.singleton("getManagedDataSource") { dataSourceFactory.createDataSource(env, credential, numThreads + 1) }
/**
* Whether or not the context will force the environment creation by default. Will be false for most environment types,
* but we will enable it for the unit test DBs.
*/
protected open val isForceEnvCreation: Boolean
get() = false
private fun isStrictSetupEnvInfra(): Boolean {
return strictSetupEnvInfra
}
override fun setFailOnSetupException(failOnSetupException: Boolean): DbDeployerAppContext {
return setStrictSetupEnvInfra(failOnSetupException)
}
override fun setStrictSetupEnvInfra(strictSetupEnvInfra: Boolean): DbDeployerAppContext {
this.strictSetupEnvInfra = strictSetupEnvInfra
return this
}
override fun buildDbContext(): DbDeployerAppContext {
Validate.notNull(platform(), "dbType must be populated")
if (credential == null) {
if (this.env.defaultUserId != null && this.env.defaultPassword != null) {
credential = Credential(this.env.defaultUserId, this.env.defaultPassword)
} else {
throw IllegalArgumentException("Cannot build DB context without credential; was not passed in as argument, and no defaultUserId & defaultPassword specified in the environment")
}
}
validateChangeTypes(platform().changeTypes, changeTypeBehaviorRegistry)
// ensure that these values are initialized
changesetCreator
environmentCleaner
managedDataSource
return this
}
private fun validateChangeTypes(changeTypes: ImmutableList<ChangeType>, changeTypeBehaviorRegistry: ChangeTypeBehaviorRegistry) {
val unenrichedChangeTypes = changeTypes.reject { changeType -> changeTypeBehaviorRegistry.getChangeTypeBehavior(changeType.name) != null }
if (unenrichedChangeTypes.notEmpty()) {
throw IllegalStateException("The following change types were not enriched: $unenrichedChangeTypes")
}
CollectionUtil.verifyNoDuplicates(changeTypes, { changeType -> changeType.name }, "Not expecting multiple ChangeTypes with the same name")
}
protected fun platform(): DbPlatform {
return env.platform
}
protected fun simpleArtifactDeployer(): DbSimpleArtifactDeployer {
return DbSimpleArtifactDeployer(platform(), sqlExecutor)
}
override fun getChangeTypeBehaviors(): ChangeTypeBehaviorRegistryBuilder {
val builder = ChangeTypeBehaviorRegistry.newBuilder()
val staticDataPartition = platform().changeTypes.partition { it.name == ChangeType.STATICDATA_STR }
for (staticDataType in staticDataPartition.selected) {
val behavior = StaticDataChangeTypeBehavior(env, sqlExecutor, simpleArtifactDeployer(), csvStaticDataLoader)
builder.put(staticDataType.name, groupSemantic(), behavior)
}
val rerunnablePartition = staticDataPartition.rejected.partition { changeType -> changeType.isRerunnable }
for (rerunnableChange in rerunnablePartition.selected) {
if (rerunnableChange !is DbChangeType) {
throw IllegalArgumentException("Bad change type " + rerunnableChange.name + ":" + rerunnableChange)
}
val behavior = RerunnableDbChangeTypeBehavior(
env, rerunnableChange, sqlExecutor, simpleArtifactDeployer(), grantChangeParser(), graphEnricher(), platform(), dbMetadataManager)
builder.put(rerunnableChange.getName(), rerunnableSemantic(), behavior)
}
for (incrementalChange in rerunnablePartition.rejected) {
val behavior = IncrementalDbChangeTypeBehavior(
env, incrementalChange as DbChangeType, sqlExecutor, simpleArtifactDeployer(), grantChangeParser()
)
builder.put(incrementalChange.getName(), incrementalSemantic(), behavior)
}
return builder
}
protected fun grantChangeParser(): GrantChangeParser {
return GrantChangeParser(env, artifactTranslators)
}
override fun buildFileContext(): DbDeployerAppContext {
Validate.notNull(env.sourceDirs, "sourceDirs must be populated")
Validate.notNull(env.name, "name must be populated")
Validate.notNull(env.schemas, "schemas must be populated")
// initialize this variable here
inputReader
return this
}
override fun readChangesFromAudit(): ImmutableList<Change> {
return artifactDeployerDao.deployedChanges
}
override fun readChangesFromSource(): ImmutableList<ChangeInput> {
return readChangesFromSource(false)
}
override fun readChangesFromSource(useBaseline: Boolean): ImmutableList<ChangeInput> {
return inputReader.readInternal(getSourceReaderStrategy(getFileSourceParams(useBaseline)), MainDeployerArgs().useBaseline(useBaseline)) as ImmutableList<ChangeInput>
}
override fun readSource(deployerArgs: MainDeployerArgs) {
inputReader.readInternal(getSourceReaderStrategy(getFileSourceParams(false)), MainDeployerArgs().useBaseline(false))
}
override fun getDefaultFileSourceContext(): FileSourceContext {
val fkChangeType = platform().getChangeType(ChangeType.FOREIGN_KEY_STR)
val triggerChangeType = platform().getChangeType(ChangeType.TRIGGER_INCREMENTAL_OLD_STR)
val getChangeType = DbGetChangeType(fkChangeType, triggerChangeType)
val baselineTableChangeParser = BaselineTableChangeParser(fkChangeType, triggerChangeType)
return AbstractDeployerAppContext.ReaderContext(env, deployStatsTracker(), getChangeType, baselineTableChangeParser).defaultFileSourceContext
}
class DbGetChangeType(private val fkChangeType: ChangeType, private val triggerChangeType: ChangeType) : GetChangeType {
override fun getChangeType(section: TextMarkupDocumentSection, tableChangeType: ChangeType): ChangeType {
return if (section.isTogglePresent(TOGGLE_FK)) {
fkChangeType
} else {
if (section.isTogglePresent(TOGGLE_TRIGGER)) {
triggerChangeType
} else {
tableChangeType
}
}
}
companion object {
private val TOGGLE_FK = "FK"
private val TOGGLE_TRIGGER = "TRIGGER"
}
}
override fun getArtifactTranslators(): ImmutableList<PrepareDbChange<in DbEnvironment>> {
return this.singleton("getArtifactTranslators") {
Lists.mutable
.with<PrepareDbChange<in DbEnvironment>>(PrepareDbChangeForDb())
.withAll(this.env.dbTranslationDialect.additionalTranslators)
.toImmutable()
}
}
public override fun getArtifactDeployerDao(): ChangeAuditDao {
return this.singleton("getArtifactDeployerDao") {
if (env.isDisableAuditTracking) {
NoOpChangeAuditDao()
} else {
SameSchemaChangeAuditDao(env, sqlExecutor, dbMetadataManager, credential.username, deployExecutionDao, changeTypeBehaviorRegistry)
}
}
}
override fun getDbMetadataManager(): DbMetadataManager {
return this.singleton("getDbMetadataManager") {
val dbMetadataManager = platform().dbMetadataManager
dbMetadataManager.setDataSource(managedDataSource)
dbMetadataManager
}
}
override fun getDeployExecutionDao(): DeployExecutionDao {
return this.singleton("deployExecutionDao") {
SameSchemaDeployExecutionDao(
sqlExecutor,
dbMetadataManager,
platform(),
env.physicalSchemas,
tableSqlSuffix,
env,
changeTypeBehaviorRegistry
)
}
}
override fun getDbChecksumDao(): DbChecksumDao {
return this.singleton("getDbChecksumDao") {
SameSchemaDbChecksumDao(
sqlExecutor,
dbMetadataManager,
platform(),
env.physicalSchemas,
tableSqlSuffix,
changeTypeBehaviorRegistry
)
}
}
override fun getDeployerPlugin(): DeployerPlugin<*> {
return this.singleton("getDeployerPlugin") {
DbDeployer(
artifactDeployerDao, dbMetadataManager, sqlExecutor, deployStatsTracker(), dbChecksumManager, deployExecutionDao
)
}
}
override fun getDbChangeFilter(): Predicate<in ChangeKey> {
val disabledChangeTypeNames = this.env.dbTranslationDialect.disabledChangeTypeNames
if (disabledChangeTypeNames.isEmpty) {
return Predicates.alwaysTrue()
}
val disabledChangeTypePredicate = ChangeKeyPredicateBuilder.newBuilder().setChangeTypes(disabledChangeTypeNames).build()
return Predicates.not(disabledChangeTypePredicate) // we return the opposite of what is disabled
}
/**
* For backwards-compatibility, we keep this data source as a single connection for clients.
*/
override fun getDataSource(): DataSource {
return this.singleton("getDataSource") { SingleConnectionDataSource(dataSourceFactory.createDataSource(env, credential, 1)) }
}
override fun setupEnvInfra(): DbDeployerAppContext {
return setupEnvInfra(isStrictSetupEnvInfra())
}
override fun setupEnvInfra(strictSetupEnvInfra: Boolean): DbDeployerAppContext {
return setupEnvInfra(strictSetupEnvInfra, null)
}
override fun setupEnvInfra(strictSetupEnvInfra: Boolean, forceEnvCreation: Boolean?): DbDeployerAppContext {
val willForceCreation = isWillForceCreation(forceEnvCreation)
environmentInfraSetup.setupEnvInfra(strictSetupEnvInfra, willForceCreation)
return this
}
private fun isWillForceCreation(forceEnvCreation: Boolean?): Boolean {
return forceEnvCreation ?: if (env.forceEnvInfraSetup != null) {
env.forceEnvInfraSetup!!
} else {
isForceEnvCreation
}
}
override fun cleanEnvironment(): DbDeployerAppContextImpl {
environmentCleaner.cleanEnvironment(MainDeployerArgs.DEFAULT_NOPROMPT_VALUE_FOR_API)
return this
}
override fun cleanAndDeploy(): DbDeployerAppContextImpl {
cleanEnvironment()
deploy()
return this
}
override fun setupAndCleanAndDeploy(): DbDeployerAppContextImpl {
setupEnvInfra()
cleanAndDeploy()
return this
}
}
| apache-2.0 | c508387e43bf6a3dc96302f02fd96170 | 40.358696 | 192 | 0.706767 | 4.901771 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/fragment/BrowserFragment.kt | 1 | 36222 | /* 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.fragment
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityManager
import android.webkit.MimeTypeMap
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.preference.PreferenceManager
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mozilla.components.browser.state.selector.findTabOrCustomTab
import mozilla.components.browser.state.selector.privateTabs
import mozilla.components.browser.state.state.CustomTabConfig
import mozilla.components.browser.state.state.SessionState
import mozilla.components.browser.state.state.content.DownloadState
import mozilla.components.browser.state.state.createTab
import mozilla.components.concept.engine.HitResult
import mozilla.components.feature.app.links.AppLinksFeature
import mozilla.components.feature.contextmenu.ContextMenuFeature
import mozilla.components.feature.downloads.AbstractFetchDownloadService
import mozilla.components.feature.downloads.DownloadsFeature
import mozilla.components.feature.downloads.manager.FetchDownloadManager
import mozilla.components.feature.downloads.share.ShareDownloadFeature
import mozilla.components.feature.media.fullscreen.MediaSessionFullscreenFeature
import mozilla.components.feature.prompts.PromptFeature
import mozilla.components.feature.session.PictureInPictureFeature
import mozilla.components.feature.session.SessionFeature
import mozilla.components.feature.sitepermissions.SitePermissionsFeature
import mozilla.components.feature.tabs.WindowFeature
import mozilla.components.feature.top.sites.TopSitesConfig
import mozilla.components.feature.top.sites.TopSitesFeature
import mozilla.components.lib.crash.Crash
import mozilla.components.service.glean.private.NoExtras
import mozilla.components.support.base.feature.UserInteractionHandler
import mozilla.components.support.base.feature.ViewBoundFeatureWrapper
import mozilla.components.support.ktx.android.view.exitImmersiveMode
import mozilla.components.support.utils.Browsers
import org.mozilla.focus.GleanMetrics.Browser
import org.mozilla.focus.GleanMetrics.Downloads
import org.mozilla.focus.GleanMetrics.OpenWith
import org.mozilla.focus.GleanMetrics.TabCount
import org.mozilla.focus.GleanMetrics.TrackingProtection
import org.mozilla.focus.R
import org.mozilla.focus.activity.InstallFirefoxActivity
import org.mozilla.focus.activity.MainActivity
import org.mozilla.focus.browser.integration.BrowserMenuController
import org.mozilla.focus.browser.integration.BrowserToolbarIntegration
import org.mozilla.focus.browser.integration.FindInPageIntegration
import org.mozilla.focus.browser.integration.FullScreenIntegration
import org.mozilla.focus.contextmenu.ContextMenuCandidates
import org.mozilla.focus.databinding.FragmentBrowserBinding
import org.mozilla.focus.downloads.DownloadService
import org.mozilla.focus.engine.EngineSharedPreferencesListener
import org.mozilla.focus.ext.accessibilityManager
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.disableDynamicBehavior
import org.mozilla.focus.ext.enableDynamicBehavior
import org.mozilla.focus.ext.ifCustomTab
import org.mozilla.focus.ext.isCustomTab
import org.mozilla.focus.ext.requireComponents
import org.mozilla.focus.ext.settings
import org.mozilla.focus.ext.showAsFixed
import org.mozilla.focus.ext.titleOrDomain
import org.mozilla.focus.menu.browser.DefaultBrowserMenu
import org.mozilla.focus.open.OpenWithFragment
import org.mozilla.focus.session.ui.TabsPopup
import org.mozilla.focus.settings.permissions.permissionoptions.SitePermissionOptionsStorage
import org.mozilla.focus.settings.privacy.ConnectionDetailsPanel
import org.mozilla.focus.settings.privacy.TrackingProtectionPanel
import org.mozilla.focus.state.AppAction
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.topsites.DefaultTopSitesStorage.Companion.TOP_SITES_MAX_LIMIT
import org.mozilla.focus.topsites.DefaultTopSitesView
import org.mozilla.focus.utils.FocusSnackbar
import org.mozilla.focus.utils.FocusSnackbarDelegate
import org.mozilla.focus.utils.IntentUtils
import org.mozilla.focus.utils.StatusBarUtils
import java.net.URLEncoder
/**
* Fragment for displaying the browser UI.
*/
@Suppress("LargeClass", "TooManyFunctions")
class BrowserFragment :
BaseFragment(),
UserInteractionHandler,
AccessibilityManager.AccessibilityStateChangeListener {
private var _binding: FragmentBrowserBinding? = null
private val binding get() = _binding!!
private val findInPageIntegration = ViewBoundFeatureWrapper<FindInPageIntegration>()
private val fullScreenIntegration = ViewBoundFeatureWrapper<FullScreenIntegration>()
private var pictureInPictureFeature: PictureInPictureFeature? = null
internal val sessionFeature = ViewBoundFeatureWrapper<SessionFeature>()
private val promptFeature = ViewBoundFeatureWrapper<PromptFeature>()
private val contextMenuFeature = ViewBoundFeatureWrapper<ContextMenuFeature>()
private val downloadsFeature = ViewBoundFeatureWrapper<DownloadsFeature>()
private val shareDownloadFeature = ViewBoundFeatureWrapper<ShareDownloadFeature>()
private val windowFeature = ViewBoundFeatureWrapper<WindowFeature>()
private val appLinksFeature = ViewBoundFeatureWrapper<AppLinksFeature>()
private val topSitesFeature = ViewBoundFeatureWrapper<TopSitesFeature>()
private var sitePermissionsFeature = ViewBoundFeatureWrapper<SitePermissionsFeature>()
private var fullScreenMediaSessionFeature = ViewBoundFeatureWrapper<MediaSessionFullscreenFeature>()
private val toolbarIntegration = ViewBoundFeatureWrapper<BrowserToolbarIntegration>()
private var trackingProtectionPanel: TrackingProtectionPanel? = null
private lateinit var requestPermissionLauncher: ActivityResultLauncher<Array<String>>
private var tabsPopup: TabsPopup? = null
/**
* The ID of the tab associated with this fragment.
*/
private val tabId: String
get() = requireArguments().getString(ARGUMENT_SESSION_UUID)
?: throw IllegalAccessError("No session ID set on fragment")
/**
* The tab associated with this fragment.
*/
val tab: SessionState
get() = requireComponents.store.state.findTabOrCustomTab(tabId)
// Workaround for tab not existing temporarily.
?: createTab("about:blank")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions(),
) { permissionsResult ->
val grandResults = ArrayList<Int>()
permissionsResult.entries.forEach {
val isGranted = it.value
if (isGranted) {
grandResults.add(PackageManager.PERMISSION_GRANTED)
} else {
grandResults.add(PackageManager.PERMISSION_DENIED)
}
}
val feature = sitePermissionsFeature.get()
feature?.onPermissionsResult(
permissionsResult.keys.toTypedArray(),
grandResults.toIntArray(),
)
}
}
@Suppress("LongMethod", "ComplexMethod")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentBrowserBinding.inflate(inflater, container, false)
requireContext().accessibilityManager.addAccessibilityStateChangeListener(this)
return binding.root
}
@SuppressLint("VisibleForTests")
@Suppress("ComplexCondition", "LongMethod")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val components = requireComponents
findInPageIntegration.set(
FindInPageIntegration(
components.store,
binding.findInPage,
binding.engineView,
),
this,
view,
)
fullScreenIntegration.set(
FullScreenIntegration(
requireActivity(),
components.store,
tab.id,
components.sessionUseCases,
requireContext().settings,
binding.browserToolbar,
binding.statusBarBackground,
binding.engineView,
),
this,
view,
)
pictureInPictureFeature = PictureInPictureFeature(
store = components.store,
activity = requireActivity(),
crashReporting = components.crashReporter,
tabId = tabId,
)
contextMenuFeature.set(
ContextMenuFeature(
parentFragmentManager,
components.store,
ContextMenuCandidates.get(
requireContext(),
components.tabsUseCases,
components.contextMenuUseCases,
components.appLinksUseCases,
view,
FocusSnackbarDelegate(view),
tab.isCustomTab(),
),
binding.engineView,
requireComponents.contextMenuUseCases,
tabId,
additionalNote = { hitResult -> getAdditionalNote(hitResult) },
),
this,
view,
)
sessionFeature.set(
SessionFeature(
components.store,
components.sessionUseCases.goBack,
binding.engineView,
tab.id,
),
this,
view,
)
promptFeature.set(
PromptFeature(
fragment = this,
store = components.store,
customTabId = tryGetCustomTabId(),
fragmentManager = parentFragmentManager,
onNeedToRequestPermissions = { permissions ->
requestInPlacePermissions(permissions) { result ->
promptFeature.get()?.onPermissionsResult(
result.keys.toTypedArray(),
result.values.map {
when (it) {
true -> PackageManager.PERMISSION_GRANTED
false -> PackageManager.PERMISSION_DENIED
}
}.toIntArray(),
)
}
},
),
this,
view,
)
downloadsFeature.set(
DownloadsFeature(
requireContext().applicationContext,
components.store,
components.downloadsUseCases,
fragmentManager = childFragmentManager,
tabId = tabId,
downloadManager = FetchDownloadManager(
requireContext().applicationContext,
components.store,
DownloadService::class,
),
onNeedToRequestPermissions = { permissions ->
requestInPlacePermissions(permissions) { result ->
downloadsFeature.get()?.onPermissionsResult(
result.keys.toTypedArray(),
result.values.map {
when (it) {
true -> PackageManager.PERMISSION_GRANTED
false -> PackageManager.PERMISSION_DENIED
}
}.toIntArray(),
)
}
},
onDownloadStopped = { state, _, status ->
handleDownloadStopped(state, status)
},
),
this,
view,
)
shareDownloadFeature.set(
ShareDownloadFeature(
context = requireContext().applicationContext,
httpClient = components.client,
store = components.store,
tabId = tab.id,
),
this,
view,
)
appLinksFeature.set(
feature = AppLinksFeature(
requireContext(),
store = components.store,
sessionId = tabId,
fragmentManager = parentFragmentManager,
launchInApp = { requireContext().settings.openLinksInExternalApp },
loadUrlUseCase = requireContext().components.sessionUseCases.loadUrl,
),
owner = this,
view = view,
)
topSitesFeature.set(
feature = TopSitesFeature(
view = DefaultTopSitesView(requireComponents.appStore),
storage = requireComponents.topSitesStorage,
config = {
TopSitesConfig(
totalSites = TOP_SITES_MAX_LIMIT,
frecencyConfig = null,
providerConfig = null,
)
},
),
owner = this,
view = view,
)
customizeToolbar()
val customTabConfig = tab.ifCustomTab()?.config
if (customTabConfig != null) {
initialiseCustomTabUi(customTabConfig)
// TODO Add custom tabs window feature support
// We to add support for Custom Tabs here, however in order to send the window request
// back to us through the intent system, we need to register a unique schema that we
// can handle. For example, Fenix Nighlyt does this today with `fenix-nightly://`.
} else {
initialiseNormalBrowserUi()
windowFeature.set(
feature = WindowFeature(
store = components.store,
tabsUseCases = components.tabsUseCases,
),
owner = this,
view = view,
)
}
// Feature that handles MediaSession state changes
fullScreenMediaSessionFeature.set(
feature = MediaSessionFullscreenFeature(requireActivity(), requireComponents.store, tryGetCustomTabId()),
owner = this,
view = view,
)
setSitePermissions(view)
}
private fun setSitePermissions(rootView: View) {
sitePermissionsFeature.set(
feature = SitePermissionsFeature(
context = requireContext(),
fragmentManager = parentFragmentManager,
onNeedToRequestPermissions = { permissions ->
if (SitePermissionOptionsStorage(requireContext()).isSitePermissionNotBlocked(permissions)) {
requestPermissionLauncher.launch(permissions)
}
},
onShouldShowRequestPermissionRationale = {
// Since we don't request permissions this it will not be called
false
},
sitePermissionsRules = SitePermissionOptionsStorage(requireContext()).getSitePermissionsSettingsRules(),
sessionId = tabId,
store = requireComponents.store,
shouldShowDoNotAskAgainCheckBox = false,
),
owner = this,
view = rootView,
)
if (requireComponents.appStore.state.sitePermissionOptionChange) {
requireComponents.sessionUseCases.reload(tabId)
requireComponents.appStore.dispatch(AppAction.SitePermissionOptionChange(false))
}
}
override fun onAccessibilityStateChanged(enabled: Boolean) = when (enabled) {
false -> binding.browserToolbar.enableDynamicBehavior(requireContext(), binding.engineView)
true -> {
with(binding.browserToolbar) {
disableDynamicBehavior(binding.engineView)
showAsFixed(requireContext(), binding.engineView)
}
}
}
override fun onPictureInPictureModeChanged(enabled: Boolean) {
pictureInPictureFeature?.onPictureInPictureModeChanged(enabled)
if (lifecycle.currentState == Lifecycle.State.CREATED) {
onBackPressed()
}
}
private fun getAdditionalNote(hitResult: HitResult): String? {
return if ((hitResult is HitResult.IMAGE_SRC || hitResult is HitResult.IMAGE) &&
hitResult.src.isNotEmpty()
) {
getString(R.string.contextmenu_erased_images_note2, getString(R.string.app_name))
} else {
null
}
}
private fun customizeToolbar() {
val controller = BrowserMenuController(
requireComponents.sessionUseCases,
requireComponents.appStore,
requireComponents.store,
requireComponents.topSitesUseCases,
tabId,
::shareCurrentUrl,
::setShouldRequestDesktop,
::showAddToHomescreenDialog,
::showFindInPageBar,
::openSelectBrowser,
::openInBrowser,
)
if (tab.ifCustomTab()?.config == null) {
val browserMenu = DefaultBrowserMenu(
context = requireContext(),
appStore = requireComponents.appStore,
store = requireComponents.store,
isPinningSupported = ShortcutManagerCompat.isRequestPinShortcutSupported(
requireContext(),
),
onItemTapped = { controller.handleMenuInteraction(it) },
)
binding.browserToolbar.display.menuBuilder = browserMenu.menuBuilder
}
toolbarIntegration.set(
BrowserToolbarIntegration(
requireComponents.store,
toolbar = binding.browserToolbar,
fragment = this,
controller = controller,
customTabId = tryGetCustomTabId(),
customTabsUseCases = requireComponents.customTabsUseCases,
sessionUseCases = requireComponents.sessionUseCases,
onUrlLongClicked = ::onUrlLongClicked,
eraseActionListener = { erase(shouldEraseAllTabs = true) },
tabCounterListener = ::tabCounterListener,
),
owner = this,
view = binding.browserToolbar,
)
}
private fun initialiseNormalBrowserUi() {
if (!requireContext().settings.isAccessibilityEnabled()) {
binding.browserToolbar.enableDynamicBehavior(requireContext(), binding.engineView)
} else {
binding.browserToolbar.showAsFixed(requireContext(), binding.engineView)
}
}
private fun initialiseCustomTabUi(customTabConfig: CustomTabConfig) {
if (customTabConfig.enableUrlbarHiding && !requireContext().settings.isAccessibilityEnabled()) {
binding.browserToolbar.enableDynamicBehavior(requireContext(), binding.engineView)
} else {
binding.browserToolbar.showAsFixed(requireContext(), binding.engineView)
}
}
override fun onDestroyView() {
super.onDestroyView()
requireContext().accessibilityManager.removeAccessibilityStateChangeListener(this)
_binding = null
}
override fun onDestroy() {
super.onDestroy()
// This fragment might get destroyed before the user left immersive mode (e.g. by opening another URL from an
// app). In this case let's leave immersive mode now when the fragment gets destroyed.
requireActivity().exitImmersiveMode()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
promptFeature.withFeature { it.onActivityResult(requestCode, data, resultCode) }
}
@OptIn(DelicateCoroutinesApi::class)
private fun showCrashReporter(crash: Crash) {
val fragmentManager = requireActivity().supportFragmentManager
if (crashReporterIsVisible()) {
// We are already displaying the crash reporter
// No need to show another one.
return
}
val crashReporterFragment = CrashReporterFragment.create()
crashReporterFragment.onCloseTabPressed = { sendCrashReport ->
if (sendCrashReport) {
val crashReporter = requireComponents.crashReporter
GlobalScope.launch(Dispatchers.IO) { crashReporter.submitReport(crash) }
}
requireComponents.sessionUseCases.crashRecovery.invoke()
erase()
hideCrashReporter()
}
fragmentManager
.beginTransaction()
.addToBackStack(null)
.add(R.id.crash_container, crashReporterFragment, CrashReporterFragment.FRAGMENT_TAG)
.commit()
binding.crashContainer.isVisible = true
}
private fun hideCrashReporter() {
val fragmentManager = requireActivity().supportFragmentManager
val fragment = fragmentManager.findFragmentByTag(CrashReporterFragment.FRAGMENT_TAG)
?: return
fragmentManager
.beginTransaction()
.remove(fragment)
.commit()
binding.crashContainer.isVisible = false
}
fun crashReporterIsVisible(): Boolean = requireActivity().supportFragmentManager.let {
it.findFragmentByTag(CrashReporterFragment.FRAGMENT_TAG)?.isVisible ?: false
}
private fun handleDownloadStopped(
state: DownloadState,
status: DownloadState.Status,
) {
val extension =
MimeTypeMap.getFileExtensionFromUrl(URLEncoder.encode(state.filePath, "utf-8"))
when (status) {
DownloadState.Status.FAILED -> {
Downloads.downloadFailed.record(Downloads.DownloadFailedExtra(extension))
}
DownloadState.Status.PAUSED -> {
Downloads.downloadPaused.record(NoExtras())
}
DownloadState.Status.COMPLETED -> {
Downloads.downloadCompleted.record(NoExtras())
TelemetryWrapper.downloadDialogDownloadEvent(sentToDownload = true)
showDownloadCompletedSnackbar(state, extension)
}
else -> {
}
}
}
private fun showDownloadCompletedSnackbar(
state: DownloadState,
extension: String?,
) {
val snackbar = FocusSnackbar.make(
requireView(),
Snackbar.LENGTH_LONG,
)
snackbar.setText(
String.format(
requireContext().getString(R.string.download_snackbar_finished),
state.fileName,
),
)
snackbar.setAction(getString(R.string.download_snackbar_open)) {
val opened = AbstractFetchDownloadService.openFile(
applicationContext = requireContext().applicationContext,
download = state,
)
if (!opened) {
Toast.makeText(
context,
getString(
mozilla.components.feature.downloads.R.string.mozac_feature_downloads_open_not_supported1,
extension,
),
Toast.LENGTH_LONG,
).show()
}
Downloads.openButtonTapped.record(
Downloads.OpenButtonTappedExtra(fileExtension = extension, openSuccessful = opened),
)
}
snackbar.show()
}
private fun showAddToHomescreenDialog() {
val fragmentManager = childFragmentManager
if (fragmentManager.findFragmentByTag(AddToHomescreenDialogFragment.FRAGMENT_TAG) != null) {
// We are already displaying a homescreen dialog fragment (Probably a restored fragment).
// No need to show another one.
return
}
val requestDesktop = tab.content.desktopMode
val addToHomescreenDialogFragment = AddToHomescreenDialogFragment.newInstance(
tab.content.url,
tab.content.titleOrDomain,
tab.trackingProtection.enabled,
requestDesktop = requestDesktop,
)
try {
addToHomescreenDialogFragment.show(
fragmentManager,
AddToHomescreenDialogFragment.FRAGMENT_TAG,
)
} catch (e: IllegalStateException) {
// It can happen that at this point in time the activity is already in the background
// and onSaveInstanceState() has already been called. Fragment transactions are not
// allowed after that anymore. It's probably safe to guess that the user might not
// be interested in adding to homescreen now.
}
}
override fun onResume() {
super.onResume()
updateEngineColorScheme()
// Hide status bar background if the parent activity can be casted to MainActivity
(requireActivity() as? MainActivity)?.hideStatusBarBackground()
StatusBarUtils.getStatusBarHeight(binding.statusBarBackground) { statusBarHeight ->
binding.statusBarBackground.layoutParams.height = statusBarHeight
}
}
private fun updateEngineColorScheme() {
val preferredColorScheme = requireComponents.settings.getPreferredColorScheme()
if (requireComponents.engine.settings.preferredColorScheme != preferredColorScheme) {
requireComponents.engine.settings.preferredColorScheme = preferredColorScheme
requireComponents.sessionUseCases.reload()
}
}
override fun onStop() {
super.onStop()
tabsPopup?.dismiss()
trackingProtectionPanel?.hide()
}
override fun onHomePressed() = pictureInPictureFeature?.onHomePressed() ?: false
@Suppress("ComplexMethod", "ReturnCount")
override fun onBackPressed(): Boolean {
if (findInPageIntegration.onBackPressed()) {
return true
} else if (fullScreenIntegration.onBackPressed()) {
return true
} else if (sessionFeature.get()?.onBackPressed() == true) {
return true
} else if (tab.source is SessionState.Source.Internal.TextSelection) {
erase()
return true
} else {
if (tab.source is SessionState.Source.External || tab.isCustomTab()) {
Browser.backButtonPressed.record(
Browser.BackButtonPressedExtra("erase_to_external_app"),
)
TelemetryWrapper.eraseBackToAppEvent()
// This session has been started from a VIEW intent. Go back to the previous app
// immediately and erase the current browsing session.
erase()
// If there are no other sessions then we remove the whole task because otherwise
// the old session might still be partially visible in the app switcher.
if (requireComponents.store.state.privateTabs.isEmpty()) {
requireActivity().finishAndRemoveTask()
} else {
requireActivity().finish()
}
// We can't show a snackbar outside of the app. So let's show a toast instead.
Toast.makeText(context, R.string.feedback_erase_custom_tab, Toast.LENGTH_SHORT).show()
} else {
// Just go back to the home screen.
Browser.backButtonPressed.record(
Browser.BackButtonPressedExtra("erase_to_home"),
)
TelemetryWrapper.eraseBackToHomeEvent()
erase()
}
}
return true
}
fun erase(shouldEraseAllTabs: Boolean = false) {
if (shouldEraseAllTabs) {
requireComponents.appStore.dispatch(AppAction.NavigateUp(null))
requireComponents.tabsUseCases.removeAllTabs()
} else {
requireComponents.tabsUseCases.removeTab(tab.id)
requireComponents.appStore.dispatch(AppAction.NavigateUp(requireComponents.store.state.selectedTabId))
}
}
private fun shareCurrentUrl() {
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TEXT, tab.content.url)
val title = tab.content.title
if (title.isNotEmpty()) {
shareIntent.putExtra(Intent.EXTRA_SUBJECT, title)
}
TelemetryWrapper.shareEvent()
startActivity(
IntentUtils.getIntentChooser(
context = requireContext(),
intent = shareIntent,
chooserTitle = getString(R.string.share_dialog_title),
),
)
}
private fun openInBrowser() {
// Release the session from this view so that it can immediately be rendered by a different view
sessionFeature.get()?.release()
TelemetryWrapper.openFullBrowser()
requireComponents.customTabsUseCases.migrate(tab.id)
val intent = Intent(context, MainActivity::class.java)
intent.action = Intent.ACTION_MAIN
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
// Close this activity (and the task) since it is no longer displaying any session
val activity = activity
activity?.finishAndRemoveTask()
}
internal fun edit() {
requireComponents.appStore.dispatch(
AppAction.EditAction(tab.id),
)
}
private fun tabCounterListener() {
val openedTabs = requireComponents.store.state.tabs.size
tabsPopup = TabsPopup(binding.browserToolbar, requireComponents).also { currentTabsPopup ->
currentTabsPopup.showAsDropDown(
binding.browserToolbar,
0,
0,
Gravity.END,
)
}
TabCount.sessionButtonTapped.record(TabCount.SessionButtonTappedExtra(openedTabs))
TelemetryWrapper.openTabsTrayEvent()
}
private fun showFindInPageBar() {
findInPageIntegration.get()?.show(tab)
TelemetryWrapper.findInPageMenuEvent()
}
private fun openSelectBrowser() {
val browsers = Browsers.forUrl(requireContext(), tab.content.url)
val apps = browsers.installedBrowsers.filterNot { it.packageName == requireContext().packageName }
val store = if (browsers.hasFirefoxBrandedBrowserInstalled) {
null
} else {
InstallFirefoxActivity.resolveAppStore(requireContext())
}
val fragment = OpenWithFragment.newInstance(
apps.toTypedArray(),
tab.content.url,
store,
)
@Suppress("DEPRECATION")
fragment.show(requireFragmentManager(), OpenWithFragment.FRAGMENT_TAG)
OpenWith.listDisplayed.record(OpenWith.ListDisplayedExtra(apps.size))
TelemetryWrapper.openSelectionEvent()
}
internal fun closeCustomTab() {
requireComponents.customTabsUseCases.remove(tab.id)
requireActivity().finish()
}
private fun setShouldRequestDesktop(enabled: Boolean) {
if (enabled) {
PreferenceManager.getDefaultSharedPreferences(requireContext()).edit()
.putBoolean(
requireContext().getString(R.string.has_requested_desktop),
true,
).apply()
}
requireComponents.sessionUseCases.requestDesktopSite(enabled, tab.id)
}
fun showTrackingProtectionPanel() {
trackingProtectionPanel = TrackingProtectionPanel(
context = requireContext(),
tabUrl = tab.content.url,
isTrackingProtectionOn = tab.trackingProtection.ignoredOnTrackingProtection.not(),
isConnectionSecure = tab.content.securityInfo.secure,
blockedTrackersCount = requireContext().settings
.getTotalBlockedTrackersCount(),
toggleTrackingProtection = ::toggleTrackingProtection,
updateTrackingProtectionPolicy = { tracker, isEnabled ->
EngineSharedPreferencesListener(requireContext())
.updateTrackingProtectionPolicy(
source = EngineSharedPreferencesListener.ChangeSource.PANEL.source,
tracker = tracker,
isEnabled = isEnabled,
)
reloadCurrentTab()
},
showConnectionInfo = ::showConnectionInfo,
).also { currentEtp -> currentEtp.show() }
}
private fun reloadCurrentTab() {
requireComponents.sessionUseCases.reload(tab.id)
}
private fun showConnectionInfo() {
val connectionInfoPanel = ConnectionDetailsPanel(
context = requireContext(),
tabTitle = tab.content.title,
tabUrl = tab.content.url,
isConnectionSecure = tab.content.securityInfo.secure,
goBack = { trackingProtectionPanel?.show() },
)
trackingProtectionPanel?.hide()
connectionInfoPanel.show()
}
private fun toggleTrackingProtection(enable: Boolean) {
with(requireComponents) {
if (enable) {
trackingProtectionUseCases.removeException(tab.id)
} else {
trackingProtectionUseCases.addException(tab.id, persistInPrivateMode = true)
}
}
reloadCurrentTab()
TrackingProtection.hasEverChangedEtp.set(true)
TrackingProtection.trackingProtectionChanged.record(
TrackingProtection.TrackingProtectionChangedExtra(
isEnabled = enable,
),
)
}
private fun onUrlLongClicked(): Boolean {
val context = activity ?: return false
return if (tab.isCustomTab()) {
val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val uri = tab.content.url.toUri()
clipBoard.setPrimaryClip(ClipData.newRawUri("Uri", uri))
Toast.makeText(context, getString(R.string.custom_tab_copy_url_action), Toast.LENGTH_SHORT).show()
true
} else {
false
}
}
private fun tryGetCustomTabId() = if (tab.isCustomTab()) {
tab.id
} else {
null
}
fun handleTabCrash(crash: Crash) {
showCrashReporter(crash)
}
companion object {
const val FRAGMENT_TAG = "browser"
private const val ARGUMENT_SESSION_UUID = "sessionUUID"
fun createForTab(tabId: String): BrowserFragment {
val fragment = BrowserFragment()
fragment.arguments = Bundle().apply {
putString(ARGUMENT_SESSION_UUID, tabId)
}
return fragment
}
}
}
| mpl-2.0 | 4abb42a22522447660e08d34dd09f763 | 37.088328 | 120 | 0.630722 | 5.578623 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/setup/ScanForMeshNetworksFragment.kt | 1 | 3686 | package io.particle.mesh.ui.setup
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.particle.firmwareprotos.ctrl.mesh.Mesh.NetworkInfo
import io.particle.mesh.setup.flow.context.NetworkSetupType
import io.particle.android.common.easyDiffUtilCallback
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.BaseFlowFragment
import io.particle.mesh.ui.R
import io.particle.mesh.ui.inflateRow
import kotlinx.android.synthetic.main.fragment_scan_for_mesh_networks.*
import kotlinx.android.synthetic.main.p_scanformeshnetwork_row_select_mesh_network.view.*
class ScanForMeshNetworksFragment : BaseFlowFragment() {
private lateinit var adapter: ScannedMeshNetworksAdapter
private lateinit var meshNetworkScannerLD: LiveData<List<NetworkInfo>?>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_scan_for_mesh_networks, container, false)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
meshNetworkScannerLD = flowUiListener.mesh.getTargetDeviceVisibleMeshNetworksLD()
meshNetworkScannerLD.observe(
this,
Observer { onNetworksUpdated(it) }
)
adapter = ScannedMeshNetworksAdapter { onMeshNetworkSelected(it.meshNetworkInfo) }
recyclerView.adapter = adapter
action_create_new_network.setOnClickListener {
progressBar2.visibility = View.INVISIBLE
flowUiListener.mesh.updateNetworkSetupType(NetworkSetupType.AS_GATEWAY)
flowUiListener.mesh.onUserSelectedCreateNewNetwork()
}
action_create_new_network.isVisible = flowUiListener.mesh.showNewNetworkOptionInScanner
}
private fun onNetworksUpdated(networks: List<NetworkInfo>?) {
adapter.submitList(
networks?.asSequence()
?.map { ScannedMeshNetwork(it.name, it) }
?.sortedBy { it.name }
?.toList()
)
}
private fun onMeshNetworkSelected(networkInfo: NetworkInfo) {
flowUiListener?.mesh?.updateNetworkSetupType(NetworkSetupType.NODE_JOINER)
flowUiListener?.mesh?.updateSelectedMeshNetworkToJoin(networkInfo)
}
}
private data class ScannedMeshNetwork(
val name: String,
val meshNetworkInfo: NetworkInfo
)
private class ScannedMeshNetworkHolder(var rowRoot: View) : RecyclerView.ViewHolder(rowRoot) {
val rowLine1 = rowRoot.row_line_1
}
private class ScannedMeshNetworksAdapter(
private val onItemClicked: (ScannedMeshNetwork) -> Unit
) : ListAdapter<ScannedMeshNetwork, ScannedMeshNetworkHolder>(
easyDiffUtilCallback { deviceData: ScannedMeshNetwork -> deviceData.meshNetworkInfo }
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScannedMeshNetworkHolder {
return ScannedMeshNetworkHolder(
parent.inflateRow(R.layout.p_scanformeshnetwork_row_select_mesh_network)
)
}
override fun onBindViewHolder(holder: ScannedMeshNetworkHolder, position: Int) {
val item = getItem(position)
holder.rowLine1.text = item.name
holder.rowRoot.setOnClickListener { onItemClicked(item) }
}
}
| apache-2.0 | 52026c7632ad38269b485152384f1c56 | 35.137255 | 100 | 0.748508 | 4.6075 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day7.kt | 1 | 1523 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
typealias Baggage = Map<String, Map<String, Int>>
/**
* --- Day 7: Handy Haversacks ---
* https://adventofcode.com/2020/day/7
*/
class Day7 : Solver {
override fun solve(lines: List<String>): Result {
val allBags = parseBags(lines)
val resultA = allBags.keys.map { hasGoldenBag(it, allBags) }.count { it }
val resultB = countWithin("shiny gold", allBags) - 1
return Result("$resultA", "$resultB")
}
private val mainBagSplit = """(.+) bags contain (.+)""".toRegex()
private val numBagRegex = """(^\d+) (.+) bag(|s)""".toRegex()
private fun parseBags(lines: List<String>): Baggage {
val allBags = mutableMapOf<String, MutableMap<String, Int>>()
for (line in lines) {
val (bagKey, bagValue) = mainBagSplit.find(line)!!.destructured
allBags[bagKey] = mutableMapOf()
if (bagValue.trim() != "no other bags.") {
for (inside in bagValue.split(","))
numBagRegex.find(inside.trim())!!.destructured.let { (num, name) -> allBags[bagKey]!![name] = num.toInt() }
}
}
return allBags
}
// Part 1
private fun hasGoldenBag(col: String, bags: Baggage): Boolean {
for (bag in bags[col] ?: emptyMap()) if (bag.key == "shiny gold" || hasGoldenBag(bag.key, bags)) return true
return false;
}
// Part 2
private fun countWithin(col: String, bags: Baggage): Int =
(bags[col] ?: emptyMap()).map { countWithin(it.key, bags) * it.value }.sum() + 1
}
| apache-2.0 | c71fdf054c011035504844ffbb5972af | 33.613636 | 117 | 0.631648 | 3.219873 | false | false | false | false |
googlemaps/android-samples | snippets/app/src/gms/java/com/google/maps/example/kotlin/GroundOverlays.kt | 1 | 3718 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.maps.example.kotlin
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.GroundOverlayOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.maps.example.R
internal class GroundOverlays {
private lateinit var map: GoogleMap
private fun groundOverlays() {
// [START maps_android_ground_overlays_add]
val newarkLatLng = LatLng(40.714086, -74.228697)
val newarkMap = GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922))
.position(newarkLatLng, 8600f, 6500f)
map.addGroundOverlay(newarkMap)
// [END maps_android_ground_overlays_add]
// [START maps_android_ground_overlays_retain]
// Add an overlay to the map, retaining a handle to the GroundOverlay object.
val imageOverlay = map.addGroundOverlay(newarkMap)
// [END maps_android_ground_overlays_retain]
// [START maps_android_ground_overlays_remove]
imageOverlay?.remove()
// [END maps_android_ground_overlays_remove]
// [START maps_android_ground_overlays_change_image]
// Update the GroundOverlay with a new image of the same dimension
// [END maps_android_ground_overlays_remove]
// [START maps_android_ground_overlays_change_image]
// Update the GroundOverlay with a new image of the same dimension
imageOverlay?.setImage(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922))
// [END maps_android_ground_overlays_change_image]
// [START maps_android_ground_overlays_associate_data]
val sydneyGroundOverlay = map.addGroundOverlay(
GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.harbour_bridge))
.position(LatLng(-33.873, 151.206), 100f)
.clickable(true)
)
sydneyGroundOverlay?.tag = "Sydney"
// [END maps_android_ground_overlays_associate_data]
}
private fun positionImageLocation() {
// [START maps_android_ground_overlays_position_image_location]
val newarkMap = GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922))
.anchor(0f, 1f)
.position(LatLng(40.714086, -74.228697), 8600f, 6500f)
// [END maps_android_ground_overlays_position_image_location]
}
private fun positionImageBounds() {
// [START maps_android_ground_overlays_position_image_bounds]
val newarkBounds = LatLngBounds(
LatLng(40.712216, -74.22655), // South west corner
LatLng(40.773941, -74.12544) // North east corner
)
val newarkMap = GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922))
.positionFromBounds(newarkBounds)
// [END maps_android_ground_overlays_position_image_bounds]
}
}
| apache-2.0 | 88f2bb80fdc25311253723211b800a3a | 41.735632 | 95 | 0.68908 | 4.085714 | false | false | false | false |
kjpublic01/groupie | example/src/main/java/com/xwray/groupie/example/MainActivity.kt | 1 | 9490 | package com.xwray.groupie.example
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.xwray.groupie.*
import com.xwray.groupie.example.core.InfiniteScrollListener
import com.xwray.groupie.example.core.Prefs
import com.xwray.groupie.example.core.SettingsActivity
import com.xwray.groupie.example.core.decoration.CarouselItemDecoration
import com.xwray.groupie.example.core.decoration.DebugItemDecoration
import com.xwray.groupie.example.core.decoration.SwipeTouchCallback
import com.xwray.groupie.example.item.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
val INSET_TYPE_KEY = "inset_type"
val INSET = "inset"
class MainActivity : AppCompatActivity() {
private val groupAdapter = GroupAdapter<ViewHolder>() //TODO get rid of this parameter
private lateinit var groupLayoutManager: GridLayoutManager
private lateinit var prefs: Prefs
private var gray: Int = 0
private var betweenPadding: Int = 0
private lateinit var rainbow200: IntArray
private lateinit var rainbow500: IntArray
private val infiniteLoadingSection = Section(HeaderItem(R.string.infinite_loading))
private var swipeSection = Section(HeaderItem(R.string.swipe_to_delete))
// Normally there's no need to hold onto a reference to this list, but for demonstration
// purposes, we'll shuffle this list and post an update periodically
private lateinit var updatableItems: ArrayList<UpdatableItem>
// Hold a reference to the updating group, so we can, well, update it
private var updatingGroup = UpdatingGroup()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
prefs = Prefs.get(this)
gray = ContextCompat.getColor(this, R.color.background)
betweenPadding = resources.getDimensionPixelSize(R.dimen.padding_small)
rainbow200 = resources.getIntArray(R.array.rainbow_200)
rainbow500 = resources.getIntArray(R.array.rainbow_500)
groupAdapter.apply {
setOnItemClickListener(onItemClickListener)
setOnItemLongClickListener(onItemLongClickListener)
spanCount = 12
}
populateAdapter()
groupLayoutManager = GridLayoutManager(this, groupAdapter.spanCount).apply {
spanSizeLookup = groupAdapter.spanSizeLookup
}
recycler_view.apply {
layoutManager = groupLayoutManager
addItemDecoration(HeaderItemDecoration(gray, betweenPadding))
addItemDecoration(InsetItemDecoration(gray, betweenPadding))
addItemDecoration(DebugItemDecoration(context))
adapter = groupAdapter
addOnScrollListener(object : InfiniteScrollListener(groupLayoutManager) {
override fun onLoadMore(currentPage: Int) {
val color = rainbow200[currentPage % rainbow200.size]
for (i in 0..4) {
infiniteLoadingSection.add(CardItem(color))
}
}
})
}
ItemTouchHelper(touchCallback).attachToRecyclerView(recycler_view)
fab.setOnClickListener { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) }
prefs.registerListener(onSharedPrefChangeListener)
}
private fun populateAdapter() {
// Full bleed item
val fullBleedItemSection = Section(HeaderItem(R.string.full_bleed_item))
fullBleedItemSection.add(FullBleedCardItem(R.color.purple_200))
groupAdapter.add(fullBleedItemSection)
// Update in place group
val updatingSection = Section()
val onShuffleClicked = View.OnClickListener {
val shuffled = ArrayList(updatableItems)
Collections.shuffle(shuffled)
updatingGroup.update(shuffled)
// You can also do this by forcing a change with payload
recycler_view.post { recycler_view.invalidateItemDecorations() }
}
val updatingHeader = HeaderItem(
R.string.updating_group,
R.string.updating_group_subtitle,
R.drawable.shuffle,
onShuffleClicked)
updatingSection.setHeader(updatingHeader)
updatableItems = ArrayList<UpdatableItem>()
for (i in 1..12) {
updatableItems.add(UpdatableItem(rainbow200[i], i))
}
updatingGroup.update(updatableItems)
updatingSection.add(updatingGroup)
groupAdapter.add(updatingSection)
// Expandable group
val expandableHeaderItem = ExpandableHeaderItem(R.string.expanding_group, R.string.expanding_group_subtitle)
val expandableGroup = ExpandableGroup(expandableHeaderItem)
for (i in 0..1) {
expandableGroup.add(CardItem(rainbow200[1]))
}
groupAdapter.add(expandableGroup)
// Columns
val columnSection = Section(HeaderItem(R.string.vertical_columns))
val columnGroup = makeColumnGroup()
columnSection.add(columnGroup)
groupAdapter.add(columnSection)
// Group showing even spacing with multiple columns
val multipleColumnsSection = Section(HeaderItem(R.string.multiple_columns))
for (i in 0..11) {
multipleColumnsSection.add(SmallCardItem(rainbow200[5]))
}
groupAdapter.add(multipleColumnsSection)
// Swipe to delete (with add button in header)
for (i in 0..2) {
swipeSection.add(SwipeToDeleteItem(rainbow200[6]))
}
groupAdapter.add(swipeSection)
// Horizontal carousel
val carouselSection = Section(HeaderItem(R.string.carousel, R.string.carousel_subtitle))
val carouselItem = makeCarouselItem()
carouselSection.add(carouselItem)
groupAdapter.add(carouselSection)
// Update with payload
val updateWithPayloadSection = Section(HeaderItem(R.string.update_with_payload, R.string.update_with_payload_subtitle))
rainbow500.indices.forEach { i ->
updateWithPayloadSection.add(HeartCardItem(rainbow200[i], i.toLong(), { item, favorite ->
// Pretend to make a network request
handler.postDelayed({
// Network request was successful!
item.setFavorite(favorite)
item.notifyChanged(FAVORITE)
}, 1000)
}))
}
groupAdapter.add(updateWithPayloadSection)
// Infinite loading section
groupAdapter.add(infiniteLoadingSection)
}
private fun makeColumnGroup(): ColumnGroup {
val columnItems = ArrayList<ColumnItem>()
for (i in 1..5) {
// First five items are red -- they'll end up in a vertical column
columnItems.add(ColumnItem(rainbow200[0], i))
}
for (i in 6..10) {
// Next five items are pink
columnItems.add(ColumnItem(rainbow200[1], i))
}
return ColumnGroup(columnItems)
}
private fun makeCarouselItem(): CarouselItem {
val carouselDecoration = CarouselItemDecoration(gray, betweenPadding)
val carouselAdapter = GroupAdapter<ViewHolder>()
for (i in 0..29) {
carouselAdapter.add(CarouselCardItem(rainbow200[7]))
}
return CarouselItem(carouselDecoration, carouselAdapter)
}
private val onItemClickListener = OnItemClickListener { item, view ->
if (item is CardItem) {
val cardItem = item
if (!TextUtils.isEmpty(cardItem.text)) {
Toast.makeText(this@MainActivity, cardItem.text, Toast.LENGTH_SHORT).show()
}
}
}
private val onItemLongClickListener = OnItemLongClickListener { item, view ->
if (item is CardItem) {
if (!item.text.isNullOrBlank()) {
Toast.makeText(this@MainActivity, "Long clicked: " + item.text!!, Toast.LENGTH_SHORT).show()
return@OnItemLongClickListener true
}
}
false
}
override fun onDestroy() {
prefs.unregisterListener(onSharedPrefChangeListener)
super.onDestroy()
}
private val touchCallback = object : SwipeTouchCallback(gray) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val item = groupAdapter.getItem(viewHolder.adapterPosition)
// Change notification to the adapter happens automatically when the section is
// changed.
swipeSection.remove(item)
}
}
private val onSharedPrefChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, s ->
// This is pretty evil, try not to do this
groupAdapter.notifyDataSetChanged()
}
private val handler = Handler()
}
| mit | 3118d20ad125b85dce1f1b7692908064 | 38.053498 | 136 | 0.671865 | 4.947862 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/setup/BaseConfigurationFinder.kt | 1 | 3667 | /*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui.setup
import android.content.Context
import com.etesync.syncadapter.HttpClient
import com.etesync.syncadapter.journalmanager.Crypto
import com.etesync.syncadapter.journalmanager.Exceptions
import com.etesync.syncadapter.journalmanager.JournalAuthenticator
import com.etesync.syncadapter.log.StringHandler
import com.etesync.syncadapter.model.CollectionInfo
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import java.io.IOException
import java.io.Serializable
import java.net.URI
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
class BaseConfigurationFinder(protected val context: Context, protected val credentials: LoginCredentials) {
protected val log: Logger
protected val logBuffer = StringHandler()
protected var httpClient: OkHttpClient
init {
log = Logger.getLogger("syncadapter.BaseConfigurationFinder")
log.level = Level.FINEST
log.addHandler(logBuffer)
httpClient = HttpClient.create(context, log)
}
fun findInitialConfiguration(): Configuration {
var failed = false
val cardDavConfig = findInitialConfiguration(CollectionInfo.Type.ADDRESS_BOOK)
val calDavConfig = findInitialConfiguration(CollectionInfo.Type.CALENDAR)
val authenticator = JournalAuthenticator(httpClient, HttpUrl.get(credentials.uri!!)!!)
var authtoken: String? = null
try {
authtoken = authenticator.getAuthToken(credentials.userName, credentials.password)
} catch (e: Exceptions.HttpException) {
log.warning(e.message)
failed = true
} catch (e: IOException) {
log.warning(e.message)
failed = true
}
return Configuration(
credentials.uri,
credentials.userName, authtoken,
cardDavConfig, calDavConfig,
logBuffer.toString(), failed
)
}
protected fun findInitialConfiguration(service: CollectionInfo.Type): Configuration.ServiceInfo {
// put discovered information here
val config = Configuration.ServiceInfo()
log.info("Finding initial " + service.toString() + " service configuration")
return config
}
// data classes
class Configuration
// We have to use URI here because HttpUrl is not serializable!
(val url: URI, val userName: String, val authtoken: String?, val cardDAV: ServiceInfo, val calDAV: ServiceInfo, val logs: String, val isFailed: Boolean) : Serializable {
var rawPassword: String? = null
var password: String? = null
var keyPair: Crypto.AsymmetricKeyPair? = null
var error: Throwable? = null
class ServiceInfo : Serializable {
val collections: Map<String, CollectionInfo> = HashMap()
override fun toString(): String {
return "BaseConfigurationFinder.Configuration.ServiceInfo(collections=" + this.collections + ")"
}
}
override fun toString(): String {
return "BaseConfigurationFinder.Configuration(url=" + this.url + ", userName=" + this.userName + ", keyPair=" + this.keyPair + ", cardDAV=" + this.cardDAV + ", calDAV=" + this.calDAV + ", error=" + this.error + ", failed=" + this.isFailed + ")"
}
}
}
| gpl-3.0 | 1e69550293ef77bfba83bda3868649ce | 34.921569 | 256 | 0.686681 | 4.73385 | false | true | false | false |
JimSeker/ui | Dialogs/DialogViewModelDemo_kt/app/src/main/java/edu/cs4730/dialogviewmodeldemo_kt/myDialogFragment.kt | 1 | 2505 | package edu.cs4730.dialogviewmodeldemo_kt
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
class myDialogFragment : DialogFragment() {
/**
* Instead of using onCreateView, we use the onCreateDialog
* This uses the ID above to determine which dialog to build.
*
*
* Uses the Viewmodel to send back information.
*/
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val id = requireArguments().getInt("id")
val mViewModel = ViewModelProvider(requireActivity())[DataViewModel::class.java]
var dialog: Dialog? = null
val builder: AlertDialog.Builder
when (id) {
DIALOG_TYPE_ID -> {
val items = arrayOf(
"Remove Walls", "Add Walls",
"Add/Remove Objects", "Add/Remove Score"
)
builder = AlertDialog.Builder(requireActivity())
builder.setTitle("Choose Type:")
builder.setSingleChoiceItems(
items, -1
) { dialog, item ->
dialog.dismiss() //the dismiss is needed here or the dialog stays showing.
mViewModel.setItem1(items[item])
}
dialog = builder.create()
}
DIALOG_GAMEOVER_ID -> {
builder = AlertDialog.Builder(requireActivity())
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton(
"Yes"
) { dialog, id -> mViewModel.setYesNo(true) }
.setNegativeButton(
"No"
) { dialog, id -> mViewModel.setYesNo(false) }
dialog = builder.create()
}
}
return dialog!!
}
companion object {
const val DIALOG_TYPE_ID = 0
const val DIALOG_GAMEOVER_ID = 1
/**
* Create an instance of this fragment. Uses the "ID numbers" above to determine which
* dialog box to display.
*/
fun newInstance(id: Int): myDialogFragment {
val frag = myDialogFragment()
val args = Bundle()
args.putInt("id", id)
frag.arguments = args
return frag
}
}
}
| apache-2.0 | 5264a93e451dfe2b75438b4cc41e15cc | 34.785714 | 95 | 0.542116 | 5.229645 | false | false | false | false |
http4k/http4k | http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/client/OAuthUserCredentialsTest.kt | 1 | 1820 | package org.http4k.security.oauth.client
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Credentials
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import org.http4k.security.OAuthProviderConfig
import org.junit.jupiter.api.Test
class OAuthUserCredentialsTest {
private val config = OAuthProviderConfig(Uri.of("http://auth"), "/authorize", "/", Credentials("hello", "world"))
@Test
fun `auths with correct form`() {
val app = ClientFilters.OAuthUserCredentials(
config,
Credentials("user", "password"),
scopes = listOf("someactivity.write", "someactivity.read")
).then { req: Request -> Response(Status.OK).body(req.bodyString()) }
assertThat(
app(Request(Method.POST, "")).bodyString(),
equalTo(
"grant_type=password" +
"&client_id=hello" +
"&client_secret=world" +
"&username=user" +
"&password=password" +
"&scope=someactivity.write+someactivity.read"
)
)
}
@Test
fun `omits scope if not provided`() {
val app = ClientFilters.OAuthUserCredentials(
config,
Credentials("user", "password"),
scopes = emptyList()
).then { req: Request -> Response(Status.OK).body(req.bodyString()) }
assertThat(
app(Request(Method.POST, "")).bodyString(),
equalTo("grant_type=password&client_id=hello&client_secret=world&username=user&password=password")
)
}
}
| apache-2.0 | 033df827744b9de79b4003e29cc03558 | 34.686275 | 117 | 0.62033 | 4.155251 | false | true | false | false |
Gu3pardo/PasswordSafe-AndroidClient | mobile/src/main/java/guepardoapps/passwordsafe/services/accounts/AccountService.kt | 1 | 3770 | package guepardoapps.passwordsafe.services.accounts
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import guepardoapps.passwordsafe.common.Constants
import guepardoapps.passwordsafe.models.accounts.Account
import guepardoapps.passwordsafe.models.shared.OtpUpdate
import guepardoapps.passwordsafe.repositories.AccountRepository
import guepardoapps.usbkeyboard.services.IUsbKeyboardService
import io.reactivex.subjects.PublishSubject
@ExperimentalUnsignedTypes
internal class AccountService(
private val context: Context,
private val usbKeyboardService: IUsbKeyboardService,
argumentOne: Array<Int>,
argumentTwo: Array<Int>,
passphrase: String) : IAccountService {
private var accountRepository: AccountRepository = AccountRepository(context, argumentOne, argumentTwo, passphrase)
override val accountListPublishSubject = PublishSubject.create<MutableList<Account>>()!!
override val otpProgressPublishSubject = PublishSubject.create<OtpUpdate>()!!
private val otpProgressHandler: Handler = Handler()
private val otpProgressRunnable: Runnable = object : Runnable {
override fun run() {
val progress = ((System.currentTimeMillis() / 1000) % 30).toInt()
otpProgressPublishSubject.onNext(OtpUpdate(progress, progress == 0))
otpProgressHandler.postDelayed(this, 1000)
}
}
private var isDisposed = false
init {
otpProgressHandler.post(otpProgressRunnable)
}
override fun get(decrypt: Boolean): MutableList<Account> {
val list = accountRepository.getList(decrypt)
accountListPublishSubject.onNext(list)
return list
}
override fun create(account: Account): Long {
val addResult = accountRepository.add(account)
get()
return addResult
}
override fun update(account: Account): Int {
val updateResult = accountRepository.update(account)
get()
return updateResult
}
override fun delete(id: String): Int {
val deleteEntry = get().find { x -> x.id == id } ?: return -1
val deleteResult = accountRepository.delete(deleteEntry)
get()
return deleteResult
}
override fun updatePasswordData(context: Context, argumentOne: Array<Int>, argumentTwo: Array<Int>, passphrase: String) {
accountRepository = AccountRepository(context, argumentOne, argumentTwo, passphrase)
}
override fun sendUserName(account: Account) {
usbKeyboardService.sendText(account.userName)
}
override fun sendPassphrase(account: Account) {
usbKeyboardService.sendText(account.passPhrase)
}
override fun openUrl(account: Account) {
var url = account.url
if (!url.startsWith(Constants.Web.HttpPrefix)) {
url = "${Constants.Web.HttpPrefix}$url"
} else if (!url.startsWith(Constants.Web.HttpsPrefix)) {
url = "${Constants.Web.HttpsPrefix}$url"
}
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
override fun sendUrl(account: Account) {
usbKeyboardService.sendText(account.url)
}
override fun login(account: Account, browser: String) {
usbKeyboardService.sendText(account.userName)
usbKeyboardService.sendText("tab")
usbKeyboardService.sendText(account.passPhrase)
usbKeyboardService.sendText("enter")
}
override fun eraseData() {
accountRepository.erase()
}
override fun isDisposed(): Boolean {
return isDisposed
}
override fun dispose() {
otpProgressHandler.removeCallbacks(otpProgressRunnable)
isDisposed = true
}
} | mit | 34345aeb24a8e257321eef8305f87dbc | 32.078947 | 125 | 0.698674 | 4.851995 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/network/Parser.kt | 1 | 20523 | package im.fdx.v2ex.network
import im.fdx.v2ex.model.NotificationModel
import im.fdx.v2ex.network.Parser.Source.*
import im.fdx.v2ex.ui.topic.Reply
import im.fdx.v2ex.ui.main.Comment
import im.fdx.v2ex.ui.main.Topic
import im.fdx.v2ex.ui.member.Member
import im.fdx.v2ex.ui.member.MemberReplyModel
import im.fdx.v2ex.ui.node.Node
import im.fdx.v2ex.utils.TimeUtil
import im.fdx.v2ex.utils.extensions.fullUrl
import im.fdx.v2ex.utils.extensions.getNum
import im.fdx.v2ex.utils.extensions.logd
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import java.util.*
import java.util.regex.Pattern
class Parser(private val htmlStr: String) {
private val doc: Document = Jsoup.parse(htmlStr)
fun parseTopicLists(source: Source): List<Topic> {
val topics = ArrayList<Topic>()
//用okhttp模拟登录的话获取不到Content内容,必须再一步。
val body = doc.body()
val items = when (source) {
FROM_HOME, FROM_MEMBER -> body.getElementsByClass("cell item")
FROM_NODE -> body.getElementsByAttributeValueStarting("class", "cell from")
else -> null
}
if (items != null) {
for (item in items) {
val topicModel = Topic()
val title = item.getElementsByClass("item_title")?.first()?.text()?:""
val linkWithReply = item.getElementsByClass("item_title")?.first()
?.getElementsByTag("a")?.first()?.attr("href")?:""
val replies = Integer.parseInt(linkWithReply.split("reply".toRegex())[1])
val regex = Regex("(?<=/t/)\\d+")
val id: String = regex.find(linkWithReply)?.value ?: return emptyList()
val nodeModel = Node()
when (source) {
FROM_HOME, FROM_MEMBER -> {
// <a class="node" href="/go/career">职场话题</a>
val nodeTitle = item.getElementsByClass("node")?.text()
val nodeName = item.getElementsByClass("node")?.attr("href")?.substring(4)
nodeModel.title = nodeTitle?:""
nodeModel.name = nodeName?:""
}
// <a href="/member/wineway">
// <img src="//v2" class="avatar" ></a>
FROM_NODE -> {
val strHeader = body.getElementsByClass("node_header")?.first()?.text()?:""
var nodeTitle = ""
if (strHeader.contains("›")) {
nodeTitle = strHeader.split("›".toRegex())[1].split(" ".toRegex())[1].trim { it <= ' ' }
}
val elements = doc.head().getElementsByTag("script")
val script = elements.last()
//注意,script 的tag 不含 text。
val strScript = script.html()
val nodeName = strScript.split("\"".toRegex())[1]
nodeModel.title = nodeTitle
nodeModel.name = nodeName
}
else -> {
}
}
val memberModel = Member()
// <a href="/member/wineway">
// <img src="//v2" class="avatar" border="0" align="default" style="max-width: 48px; max-height: 48px;"></a>
// val username = item.getElementsByTag("a").first().attr("href").substring(8)
val username = Regex("(?<=/member/)\\w+").find(item.html())?.value?:""
val avatarLarge = item.getElementsByClass("avatar")?.attr("src")?.replace("large", "normal")?:""
memberModel.username = username
memberModel.avatar_normal = avatarLarge
// FROM_HOME • <strong><a href="/member/nodwang">nodwang</a></strong> • 2 分钟前 • 最后回复来自
// FROM_NODE • 6 小时 15 分钟前 • 最后回复来自
val created = when (source) {
FROM_HOME, FROM_MEMBER -> {
val smallItem = item.getElementsByClass("topic_info")?.first()?.ownText()?:""
when {
smallItem.contains("最后回复") -> TimeUtil.toUtcTime(smallItem.split("•")[2])
else -> -1L
}
}
FROM_NODE -> {
val smallItem = item.getElementsByClass("topic_info")?.first()?.ownText()?:""
when {
smallItem.contains("最后回复") -> TimeUtil.toUtcTime(smallItem.split("•")[1])
else -> -1L
}
}
else -> 0L
}
topicModel.node = nodeModel
topicModel.replies = replies
topicModel.content = ""
topicModel.content_rendered = ""
topicModel.title = title
topicModel.member = memberModel
topicModel.id = id
topicModel.created = created
topics.add(topicModel)
}
}
return topics
}
fun getAllNode(): MutableList<Node> {
val allNodes = mutableListOf<Node>()
val body = doc.body()
val boxes: Elements? = body?.getElementsByClass("box")
boxes?.filterIndexed { index, _ -> index > 0 }?.forEach {
val title = it.getElementsByClass("header")?.first()?.ownText()?:""
val nodeElements = it.getElementsByClass("inner")?.first()?.getElementsByClass("item_node")
if (nodeElements != null) {
for (item in nodeElements) {
val node = Node()
val name = item.attr("href").replace("/go/", "")
node.name = name
node.title = item.text()
node.category = title
allNodes.add(node)
}
}
}
return allNodes
}
fun getMember(): Member {
val rightbar = doc.getElementById("Rightbar").getElementsByClass("cell").first()
val avatarUrl = rightbar?.getElementsByTag("img")?.first()?.attr("src")?:""
val username = rightbar?.getElementsByTag("img")?.first()?.attr("alt")?:""
val memberModel = Member()
memberModel.username = username
memberModel.avatar_normal = avatarUrl
return memberModel
}
fun getTotalPageInMember() = Regex("(?<=全部回复第\\s\\d\\s页 / 共 )\\d+").find(htmlStr)?.value?.toInt() ?: 0
fun getOneNode(): Node {
val nodeModel = Node()
// Document html = Jsoup.parse(response);
val body = doc.body()
val header = body.getElementsByClass("node_header").first()
val contentElement = header.getElementsByClass("node_info").first().getElementsByTag("span").last()
val content = contentElement.text()
val number = header.getElementsByTag("strong").first().text()
val strTitle = header.getElementsByClass("node_info").first().ownText().trim()
if (header.getElementsByTag("img").first() != null) {
val avatarLarge = header.getElementsByTag("img").first().attr("src")
nodeModel.avatar_normal = avatarLarge.replace("xxlarge", "normal")
}
val elements = doc.head().getElementsByTag("script")
val script = elements.last()
//注意,script 的tag 不含 text。
val strScript = script.html()
val nodeName = strScript.split("\"".toRegex())[1]
nodeModel.name = nodeName
nodeModel.title = strTitle
nodeModel.topics = Integer.parseInt(number)
nodeModel.header = content
return nodeModel
}
fun isNodeFollowed() = Regex("unfavorite/node/\\d{1,8}\\?once=").containsMatchIn(htmlStr)
// /favorite/node/557?once=46345
fun getOnce(): String? = Regex("favorite/node/\\d{1,8}\\?once=\\d{1,10}").find(htmlStr)?.value
fun getOnceNum() = doc.getElementsByAttributeValue("name", "once").first()?.attr("value") ?: "0"
fun getOnceNum2() = Regex("(?<=<input type=\"hidden\" name=\"once\" value=\")(\\d+)").find(htmlStr)?.value
fun isTopicFavored(): Boolean {
val p = Pattern.compile("un(?=favorite/topic/\\d{1,10}\\?t=)")
val matcher = p.matcher(doc.outerHtml())
return matcher.find()
}
fun isTopicThanked(): Boolean {
val p = Pattern.compile("thankTopic\\(\\d{1,10}")
val matcher = p.matcher(doc.outerHtml())
return !matcher.find()
}
fun isIgnored(): Boolean {
val p = Pattern.compile("un(?=ignore/topic/\\d{1,10})")
val matcher = p.matcher(doc.outerHtml())
return matcher.find()
}
fun getPageValue(): IntArray {
//注释的是移动端的方法
// val currentPage: Int = doc.getElementsByClass("page_current")?.first()?.ownText()?.toIntOrNull()?: -1
// val totalPage: Int = doc.getElementsByClass("page_normal")?.first()?.ownText()?.toIntOrNull()?:-1
val currentPage: Int
val totalPage: Int
val pageInput = doc.getElementsByClass("page_input").first() ?: return intArrayOf(-1, -1)
currentPage = (pageInput.attr("value")).toIntOrNull()?:-1
totalPage = (pageInput.attr("max")).toIntOrNull()?:-1
return intArrayOf(currentPage, totalPage)
}
fun parseToNode(): ArrayList<Node> {
val nodeModels = ArrayList<Node>()
val items = doc.getElementById("my-nodes").children()
for (item in items) {
val nodeModel = Node()
val id = item.attr("id").substring(2)
nodeModel.id = id
val title = item.getElementsByClass("fav-node-name").first().ownText().trim()
nodeModel.title = title
val name = item.attr("href").replace("/go/", "")
nodeModel.name = name
val num = item.getElementsByTag("span")[1].ownText().trim()
nodeModel.topics = Integer.parseInt(num)
val imageUrl = item.getElementsByTag("img").first().attr("src")
nodeModel.avatar_normal = imageUrl
nodeModels.add(nodeModel)
}
return nodeModels
}
fun getReplies(): ArrayList<Reply> {
val replyModels = ArrayList<Reply>()
val items = doc.getElementsByAttributeValueStarting("id", "r_")
for (item in items) {
// <div id="r_4157549" class="cell">
val id = item.id().substring(2)
val replyModel = Reply()
val memberModel = Member()
val avatar = item.getElementsByClass("avatar").attr("src")
val username = item.getElementsByTag("strong").first().getElementsByAttributeValueStarting("href", "/member/").first().text()
memberModel.avatar_normal = avatar
memberModel.username = username
val thanksOriginal = item.getElementsByClass("small fade")?.first()?.ownText()?:""
val thanks = thanksOriginal.trim().toIntOrNull()?:0
val thanked = item.getElementsByClass("thank_area thanked").first()
replyModel.isThanked = thanked != null && "感谢已发送" == thanked.text()
val createdOriginal = item.getElementsByClass("ago").text()
val replyContent = item.getElementsByClass("reply_content").first()
replyModel.created = TimeUtil.toUtcTime(createdOriginal)
replyModel.member = memberModel
replyModel.thanks = thanks
replyModel.id = id
replyModel.content = replyContent.text()
replyModel.content_rendered = replyContent.html().fullUrl()
replyModels.add(replyModel)
}
return replyModels
}
fun getVerifyCode(): String? {
// <a href="/favorite/topic/349111?t=eghsuwetutngpadqplmlnmbndvkycaft" class="tb">加入收藏</a>
val p = Pattern.compile("(?<=favorite/topic/\\d{1,10}\\?t=)\\w+")
val matcher = p.matcher(htmlStr)
return if (matcher.find()) {
matcher.group()
} else
null
}
fun parseResponseToTopic(topicId: String): Topic {
val topicModel = Topic(topicId)
val title = doc.getElementsByTag("h1").first().text()
val contentElementOrg = doc.getElementsByClass("topic_content").first()
val commentsEle = doc.getElementsByClass("subtle")
val comments = commentsEle.map {
Comment().apply {
this.title = it.getElementsByClass("fade").text().split("·")[0].trim()
created = TimeUtil.toUtcTime(it.getElementsByClass("fade").text().split("·")[1].trim())
content = it.getElementsByClass("topic_content").html()
}
}
topicModel.comments = comments.toMutableList()
val preElems = contentElementOrg?.select("pre")
if (preElems != null) {
for (elem in preElems) {
elem.html(elem.html().replace("\n", "<br/>")/*.replace(" ", " ")*/)
}
}
val content = contentElementOrg?.text() ?: ""
topicModel.content = content
val contentRendered = contentElementOrg?.html() ?: ""
topicModel.content_rendered = contentRendered.fullUrl()
val headerTopic = doc.getElementById("Main").getElementsByClass("header").first()
val elementsByClass = headerTopic.getElementsByClass("gray")
val createdUnformed = elementsByClass.first().ownText() // · 44 分钟前用 iPhone 发布 · 192 次点击
// · 54 天前 · 36030 次点击
// · 9 小时 6 分钟前 via Android · 1036 次点击
val created = TimeUtil.toUtcTime(createdUnformed)
var replyNum = ""
val grays = doc.getElementsByClass("gray")
var hasReply = false
for (gray in grays) {
if (gray.text().contains("回复") && gray.text().contains("•")) {
val wholeText = gray.text()
val index = wholeText.indexOf("回复")
replyNum = wholeText.substring(0, index - 1).trim()
if (replyNum.isNotEmpty()) {
hasReply = true
}
break
}
}
val replies = when {
hasReply -> Integer.parseInt(replyNum)
else -> 0
}
val member = Member()
val username = headerTopic
.getElementsByAttributeValueStarting("href", "/member/").text()
member.username = username
val largeAvatar = headerTopic
.getElementsByClass("avatar").attr("src")
member.avatar_normal = largeAvatar
val nodeElement = headerTopic
.getElementsByAttributeValueStarting("href", "/go/").first()
val nodeName = nodeElement.attr("href").replace("/go/", "")
val nodeTitle = nodeElement.text()
val nodeModel = Node()
nodeModel.name = nodeName
nodeModel.title = nodeTitle
topicModel.member = member //done
topicModel.replies = replies //done
topicModel.created = created //done
topicModel.title = title //done
topicModel.node = nodeModel//done
return topicModel
}
fun getUserReplies(): List<MemberReplyModel> {
val list = mutableListOf<MemberReplyModel>()
val elements = doc.getElementsByAttributeValue("id", "Main")?.first()?.getElementsByClass("box")?.first()
elements?.let {
for (e in elements.getElementsByClass("dock_area")) {
val model = MemberReplyModel()
val titleElement = e.getElementsByAttributeValueContaining("href", "/t/").first()
val title = titleElement.text()
val fakeId = titleElement.attr("href").removePrefix("/t/")
val create = e.getElementsByClass("fade").first().ownText()
model.topic.title = title
model.topic.id = fakeId.split("#")[0]
model.create = TimeUtil.toUtcTime(create)
val contentElement: Element? = e.nextElementSibling()
val content = contentElement?.getElementsByClass("reply_content")?.first()
model.content = content?.html()
list.add(model)
}
}
return list
}
// <input type="number" class="page_input" autocomplete="off" value="1" min="1" max="8"
fun getTotalPageForTopics() = Regex("(?<=max=\")\\d{1,8}").find(htmlStr)?.value?.toInt() ?: 0
fun getErrorMsg(): String {
logd(htmlStr)
val message = doc.getElementsByClass("problem") ?: return "未知错误"
return message.text().trim()
}
fun parseDailyOnce(): String? {
val onceElement = doc.getElementsByAttributeValue("value", "领取 X 铜币").first()
?: return null
// location.href = '/mission/daily/redeem?once=83270';
val onceOriginal = onceElement.attr("onClick")
return onceOriginal.getNum()
}
fun parseToNotifications(): List<NotificationModel> {
val body = doc.body()
val items = body.getElementsByAttributeValueStarting("id", "n_") ?: return emptyList()
val notificationModels = ArrayList<NotificationModel>()
for (item in items) {
val notification = NotificationModel()
val notificationId = item.attr("id").substring(2)
notification.id = notificationId
val contentElement = item.getElementsByClass("payload").first()
val content = when {
contentElement != null -> contentElement.text()
else -> "" //
}
notification.content = content //1/6
val time = item.getElementsByClass("snow").first().text()
notification.time = time// 2/6
//member model
val memberElement = item.getElementsByTag("a").first()
val username = memberElement.attr("href").replace("/member/", "")
val avatarUrl = memberElement.getElementsByClass("avatar").first().attr("src")
val memberModel = Member()
memberModel.username = username
memberModel.avatar_normal = avatarUrl
notification.member = memberModel // 3/6
val topicModel = Topic()
val topicElement = item.getElementsByClass("fade").first()
// <a href="/t/348757#reply1">交互式《线性代数》学习资料</a>
val href = topicElement.getElementsByAttributeValueStarting("href", "/t/").first().attr("href")
topicModel.title = topicElement.getElementsByAttributeValueStarting("href", "/t/").first().text()
val p = Pattern.compile("(?<=/t/)\\d+(?=#)")
val matcher = p.matcher(href)
if (matcher.find()) {
val topicId = matcher.group()
topicModel.id = topicId
}
val p2 = Pattern.compile("(?<=reply)d+\\b")
val matcher2 = p2.matcher(href)
if (matcher2.find()) {
val replies = matcher2.group()
notification.replyPosition = replies
}
notification.topic = topicModel //4/6
val originalType = topicElement.ownText()
notification.type =
when {
originalType.contains("感谢了你在主题") ->
"感谢了你:"
originalType.contains("回复了你")
-> "回复了你:"
originalType.contains("提到了你")
-> "提到了你:"
originalType.contains("收藏了你发布的主题")
-> "收藏了你发布的主题:"
else -> originalType
}
notificationModels.add(notification)
}
return notificationModels
}
enum class Source {
FROM_HOME, FROM_NODE, FROM_MEMBER, FROM_SEARCH
}
} | apache-2.0 | b12804d33e32025f2522e3d62093bb5e | 37.857143 | 137 | 0.548567 | 4.423516 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-serde/src/main/kotlin/com/octaldata/serde/json/JsonSerde.kt | 1 | 3784 | package com.octaldata.serde.json
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.BigIntegerNode
import com.fasterxml.jackson.databind.node.BinaryNode
import com.fasterxml.jackson.databind.node.BooleanNode
import com.fasterxml.jackson.databind.node.DecimalNode
import com.fasterxml.jackson.databind.node.DoubleNode
import com.fasterxml.jackson.databind.node.FloatNode
import com.fasterxml.jackson.databind.node.IntNode
import com.fasterxml.jackson.databind.node.LongNode
import com.fasterxml.jackson.databind.node.MissingNode
import com.fasterxml.jackson.databind.node.NullNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.ShortNode
import com.fasterxml.jackson.databind.node.TextNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.octaldata.domain.structure.Schema
import com.octaldata.domain.structure.Value
object JsonSerde : Serde {
private val mapper = jacksonObjectMapper()
override fun decode(bytes: ByteArray): SerdeResult {
return runCatching { mapper.readTree(bytes) }.fold(
{ runCatching { fromNode(it) }.fold({ SerdeResult.Success(it.second) }, { SerdeResult.Error(it) }) },
{ SerdeResult.Unsupported }
)
}
private fun fromNode(node: JsonNode): Pair<Schema, Value?> = when (node) {
is ArrayNode -> fromArrayNode(node).let { Pair(it.schema, it) }
is BinaryNode -> Schema.Bytes to Value.Bytes(node.binaryValue())
is BooleanNode -> Schema.Bool to Value.Bool(node.booleanValue())
is DecimalNode -> node.decimalValue().let {
val schema = Schema.Decimal(Schema.Precision(it.precision()), Schema.Scale(it.scale()))
val value = Value.Decimal(node.decimalValue())
Pair(schema, value)
}
is BigIntegerNode -> node.decimalValue().let {
val schema = Schema.Decimal(Schema.Precision(it.precision()), Schema.Scale(it.scale()))
val value = Value.Decimal(node.decimalValue())
Pair(schema, value)
}
is DoubleNode -> Schema.Float64 to Value.Float64(node.doubleValue())
is FloatNode -> Schema.Float32 to Value.Float64(node.floatValue().toDouble())
is IntNode -> Schema.Int32 to Value.Int64(node.intValue().toLong())
is LongNode -> Schema.Int64 to Value.Int64(node.longValue())
is NullNode -> Schema.Utf8 to null
is ObjectNode -> fromObjectNode(node)
is ShortNode -> Schema.Int16 to Value.Int64(node.shortValue().toLong())
is TextNode -> Schema.Utf8 to Value.Utf8(node.textValue())
is MissingNode -> Schema.Utf8 to null
else -> error("Unsupported node type ${node::class}")
}
private fun fromObjectNode(node: ObjectNode): Pair<Schema.Struct, Value.Struct> {
val (fields, values) = node.fields().asSequence().toList().map { (name, n) ->
val (schema, value) = fromNode(n)
val field = Schema.Field(name, schema, true) // json always allows nulls
Pair(field, value)
}.unzip()
val schema = Schema.Struct(null, fields)
return Pair(schema, Value.Struct(schema, values))
}
private fun fromArrayNode(node: ArrayNode): Value.Array {
val elements = node.elements().asSequence().toList()
if (elements.isEmpty()) return Value.Array(Schema.Array(Schema.Utf8), emptyList())
val nodes = elements.map { fromNode(it) }
// we don't know what the schema of the array will be, and json doesn't enforce the
// structure anyway, we so will need to look at the first element and just use that
val elementSchema = nodes.firstOrNull()?.first
return Value.Array(Schema.Array(elementSchema ?: Schema.Utf8), nodes.map { it.second })
}
} | apache-2.0 | 5b37ec55ebac1e1a663698f67867ecf2 | 47.525641 | 110 | 0.713002 | 4 | false | false | false | false |
SergeySave/SpaceGame | core/src/com/sergey/spacegame/common/lua/SpaceGameLuaLib.kt | 1 | 18421 | package com.sergey.spacegame.common.lua
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.ComponentMapper
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.graphics.Color
import com.sergey.spacegame.common.SpaceGame
import com.sergey.spacegame.common.ecs.component.HealthComponent
import com.sergey.spacegame.common.ecs.component.MessageComponent
import com.sergey.spacegame.common.ecs.component.OrderComponent
import com.sergey.spacegame.common.ecs.component.ParticleComponent
import com.sergey.spacegame.common.ecs.component.PositionComponent
import com.sergey.spacegame.common.ecs.component.RotationComponent
import com.sergey.spacegame.common.ecs.component.RotationVelocityComponent
import com.sergey.spacegame.common.ecs.component.ShipComponent
import com.sergey.spacegame.common.ecs.component.SizeComponent
import com.sergey.spacegame.common.ecs.component.TagComponent
import com.sergey.spacegame.common.ecs.component.VelocityComponent
import com.sergey.spacegame.common.ecs.component.VisualComponent
import com.sergey.spacegame.common.ecs.component.WeaponComponent
import com.sergey.spacegame.common.event.BeginLevelEvent
import com.sergey.spacegame.common.event.EventHandle
import com.sergey.spacegame.common.event.LuaDelayEvent
import com.sergey.spacegame.common.game.Level
import com.sergey.spacegame.common.game.Objective
import com.sergey.spacegame.common.game.orders.BuildBuildingOrder
import com.sergey.spacegame.common.game.orders.BuildShipOrder
import com.sergey.spacegame.common.game.orders.FaceOrder
import com.sergey.spacegame.common.game.orders.IOrder
import com.sergey.spacegame.common.game.orders.MoveOrder
import com.sergey.spacegame.common.game.orders.StopOrder
import com.sergey.spacegame.common.game.orders.TimeMoveOrder
import com.sergey.spacegame.common.util.Quadruple
import org.luaj.vm2.LuaTable
import org.luaj.vm2.LuaValue
import org.luaj.vm2.Varargs
import org.luaj.vm2.lib.OneArgFunction
import org.luaj.vm2.lib.ThreeArgFunction
import org.luaj.vm2.lib.TwoArgFunction
import org.luaj.vm2.lib.VarArgFunction
import org.luaj.vm2.lib.ZeroArgFunction
import org.luaj.vm2.lib.jse.CoerceJavaToLua
import org.luaj.vm2.lib.jse.CoerceLuaToJava
import java.util.HashSet
/**
* A singleton object representing the LUA library for the game
*
* @author sergeys
*/
object SpaceGameLuaLib : TwoArgFunction() {
private lateinit var currLevel: Level
//All the order classes accessable to LUA
private val ORDERS = HashSet<Class<out IOrder>>()
//All of the components accessable to LUA
private val COMPONENTS = HashSet<Quadruple<String, ComponentMapper<*>, () -> Component, List<String>>>()
init {
ORDERS.add(BuildShipOrder::class.java)
ORDERS.add(BuildBuildingOrder::class.java)
ORDERS.add(FaceOrder::class.java)
ORDERS.add(MoveOrder::class.java)
ORDERS.add(TimeMoveOrder::class.java)
ORDERS.add(StopOrder::class.java)
COMPONENTS.add(Quadruple("position", PositionComponent.MAPPER, { PositionComponent() }, listOf("pos", "p")))
COMPONENTS.add(Quadruple("rotation", RotationComponent.MAPPER, { RotationComponent() }, listOf("rot", "r")))
COMPONENTS.add(Quadruple("rotationVelocity", RotationVelocityComponent.MAPPER, { RotationVelocityComponent() }, listOf("rotVel", "rotV", "rV")))
COMPONENTS.add(Quadruple("size", SizeComponent.MAPPER, { SizeComponent() }, listOf("s")))
COMPONENTS.add(Quadruple("velocity", VelocityComponent.MAPPER, { VelocityComponent() }, listOf("vel", "v")))
COMPONENTS.add(Quadruple("ship", ShipComponent.MAPPER, { ShipComponent() }, listOf()))
COMPONENTS.add(Quadruple("health", HealthComponent.MAPPER, { HealthComponent() }, listOf("h")))
COMPONENTS.add(Quadruple("particle", PositionComponent.MAPPER, { ParticleComponent(System.currentTimeMillis()) }, listOf("prtl")))
COMPONENTS.add(Quadruple("visual", VisualComponent.MAPPER, { VisualComponent("") }, listOf("vis")))
}
override fun call(modName: LuaValue, env: LuaValue): LuaValue {
env.apply {
set("postDelayEvent", lFuncU { millis, id, parameter ->
SpaceGame.getInstance().dispatchDelayedEvent(millis.checklong(), LuaDelayEvent(id, parameter))
})
//Objectives
set("addObjective", lFuncU { id, title, description ->
currLevel.objectives.add(Objective(id.checkjstring(), title.checkjstring(), description.checkjstring(), false))
})
set("getObjective", lFunc { id ->
currLevel.objectives
.find { (id1) -> id1 == id.checkjstring() }
.let { obj -> CoerceJavaToLua.coerce(obj) } ?: NIL
})
set("removeObjective", lFuncU({ objective ->
currLevel.objectives.remove(CoerceLuaToJava.coerce(objective, Objective::class.java) as Objective)
}))
//Money
set("getPlayer1Money", lFunc { -> LuaValue.valueOf(currLevel.player1.money) })
set("setPlayer1Money", lFuncU { money -> currLevel.player1.money = money.checkdouble() })
set("getPlayer2Money", lFunc { -> LuaValue.valueOf(currLevel.player2.money) })
set("setPlayer2Money", lFuncU { money -> currLevel.player2.money = money.checkdouble() })
//ECS Helper
set("getTag", lFunc { entity ->
val entity1 = CoerceLuaToJava.coerce(entity, Entity::class.java) as Entity
TagComponent.MAPPER.get(entity1)?.let { tag -> LuaValue.valueOf(tag.tag) } ?: NIL
})
set("spawnEntity", lFunc { entityName ->
val entity = currLevel.entities[entityName.checkjstring()]!!.createEntity(currLevel)
currLevel.ecs.addEntity(entity)
CoerceJavaToLua.coerce(entity)
})
set("removeEntity", lFuncU { entity ->
val jEntity = CoerceLuaToJava.coerce(entity, Entity::class.java) as Entity
currLevel.ecs.removeEntity(jEntity)
if (HealthComponent.MAPPER.has(jEntity)) {
//Deregister it as a target
HealthComponent.MAPPER.get(jEntity).health = 0.0
}
})
set("addOrder", lFuncU { entityLua, order, className ->
val entity = CoerceLuaToJava.coerce(entityLua, Entity::class.java) as Entity
val orderComp: OrderComponent
if (OrderComponent.MAPPER.has(entity)) {
orderComp = OrderComponent.MAPPER.get(entity)
} else {
orderComp = OrderComponent()
entity.add(orderComp)
}
val orderObj = CoerceLuaToJava.coerce(order, CoerceLuaToJava.coerce(className, Class::class.java) as Class<*>) as IOrder
orderComp.addOrder(orderObj)
})
set("spawnParticle", object : VarArgFunction() {
override fun invoke(args: Varargs): Varargs {
if (args == LuaValue.NONE || args.narg() != 8) {
return argerror("spawnParticle needs 8 arguments")
}
val imageName = args.arg(1).checkjstring()
val x = args.arg(2).checkdouble().toFloat()
val y = args.arg(3).checkdouble().toFloat()
val w = args.arg(4).checkdouble().toFloat()
val h = args.arg(5).checkdouble().toFloat()
val vx = args.arg(6).checkdouble().toFloat()
val vy = args.arg(7).checkdouble().toFloat()
val life = args.arg(8).checklong()
val entity = currLevel.ecs.newEntity()
entity.add(VisualComponent(imageName))
entity.add(PositionComponent(x, y))
entity.add(SizeComponent(w, h))
entity.add(VelocityComponent(vx, vy))
entity.add(ParticleComponent(System.currentTimeMillis() + life))
currLevel.ecs.addEntity(entity)
return CoerceJavaToLua.coerce(entity)
}
})
//Lua Global data
val dataTable = LuaTable()
for (i in 0..9) {
dataTable.set("get" + i, lFunc { -> currLevel.luaStores[i] })
dataTable.set("set" + i, lFuncU { v -> currLevel.luaStores[i] = v })
}
set("data", dataTable)
//Orders
val ordersTable = LuaTable()
for (clazz in ORDERS) {
ordersTable.set(clazz.simpleName, CoerceJavaToLua.coerce(clazz))
}
set("orders", ordersTable)
//Components
val components = LuaTable()
for ((name, mapper, constructor, aliases) in COMPONENTS) {
val component = LuaTable()
component.set("has", lFunc { entity -> LuaValue.valueOf(mapper.has(CoerceLuaToJava.coerce(entity, Entity::class.java) as Entity)) })
component.set("get", lFunc { entity -> CoerceJavaToLua.coerce(mapper.get(CoerceLuaToJava.coerce(entity, Entity::class.java) as Entity)) })
component.set("new", lFunc { -> CoerceJavaToLua.coerce(constructor()) })
components.set(name, component)
for (alias in aliases) {
val aliasEntry = components.get(alias)
if (aliasEntry == null || aliasEntry == NIL) {
components.set(alias, component)
}
}
}
set("component", components)
//Audio
set("playSound", object : VarArgFunction() {
override fun invoke(args: Varargs): Varargs {
if (args == LuaValue.NONE || args.narg() == 0) {
return argerror("Play sound needs at least one argument")
}
try {
when (args.narg()) {
1 -> currLevel.playSound(args.arg1().checkjstring())
2 -> currLevel.playSound(args.arg1().checkjstring(), args.arg(2).checkdouble().toFloat())
3 -> currLevel.playSound(args.arg1().checkjstring(), args.arg(2).checkdouble().toFloat(), args.arg(3).checkdouble().toFloat())
4 -> currLevel.playSound(args.arg1().checkjstring(), args.arg(2).checkdouble().toFloat(), args.arg(3).checkdouble().toFloat(), args.arg(4).checkdouble().toFloat())
}
} catch (e: NullPointerException) {
System.err.println("Unable to play sound: \"${args.arg1().checkjstring()}\". Sound not found.")
}
return NIL
}
})
//Messages
set("sendMessage", lFuncU { imageL, messageL, timeL ->
val textureName = imageL.checkjstring()
val region = SpaceGame.getInstance().context.getRegion(textureName)
val message = messageL.checkjstring()
val millis = (timeL.checkdouble() * 1000).toLong() + System.currentTimeMillis()
val entity = currLevel.ecs.newEntity()
entity.add(MessageComponent(textureName, region, message, millis))
currLevel.ecs.addEntity(entity)
})
//Viewport
val viewport = LuaTable().apply {
set("setControllable", lFuncU { isControllable ->
currLevel.viewport.viewportControllable = isControllable.checkboolean()
})
set("isControllable", lFunc { ->
LuaValue.valueOf(currLevel.viewport.viewportControllable)
})
set("setX", lFuncU { x ->
currLevel.viewport.viewportX = x.checkdouble().toFloat()
})
set("getX", lFunc { ->
LuaValue.valueOf(currLevel.viewport.viewportX.toDouble())
})
set("setY", lFuncU { y ->
currLevel.viewport.viewportY = y.checkdouble().toFloat()
})
set("getY", lFunc { ->
LuaValue.valueOf(currLevel.viewport.viewportY.toDouble())
})
set("setWidth", lFuncU { w ->
currLevel.viewport.viewportWidth = w.checkdouble().toFloat()
})
set("getWidth", lFunc { ->
LuaValue.valueOf(currLevel.viewport.viewportWidth.toDouble())
})
set("setHeight", lFuncU { h ->
currLevel.viewport.viewportHeight = h.checkdouble().toFloat()
})
set("getHeight", lFunc { ->
LuaValue.valueOf(currLevel.viewport.viewportHeight.toDouble())
})
set("setHiddenUI", lFuncU { isHidden ->
currLevel.viewport.hiddenUI = isHidden.checkboolean()
})
set("getHiddenUI", lFunc { ->
LuaValue.valueOf(currLevel.viewport.hiddenUI)
})
}
set("viewport", viewport)
//Is controllable
set("setControllable", lFuncU { isControllable ->
currLevel.isControllable = isControllable.checkboolean()
})
set("isControllable", lFunc { ->
LuaValue.valueOf(currLevel.isControllable)
})
//Switch levels
set("switchLevel", lFuncU { level ->
if (level == LuaValue.NIL) {
SpaceGame.getInstance().dispatchDelayedRunnable(0) {
SpaceGame.getInstance().clearDelayedEventsNow()
currLevel.deinit()
currLevel.viewport.close()
}
} else {
val levelString = level.checkjstring()
if (levelString.startsWith("internal://")) {
SpaceGame.getInstance().dispatchDelayedRunnable(0) {
SpaceGame.getInstance().clearDelayedEventsNow()
currLevel.deinit()
val newLevel = Level.getLevelFromInternalPath(levelString.substring(11))
currLevel.viewport.setLevel(newLevel)
}
} else {
SpaceGame.getInstance().dispatchDelayedRunnable(0) {
SpaceGame.getInstance().clearDelayedEventsNow()
currLevel.deinit()
val newLevel = Level.getLevelFromAbsolutePath("${currLevel.parentDirectory}/$levelString")
currLevel.viewport.setLevel(newLevel)
}
}
}
})
set("colorToFloat", object : VarArgFunction() {
override fun invoke(args: Varargs): Varargs {
if (args == LuaValue.NONE || (args.narg() != 3 && args.narg() != 4)) {
return argerror("colorToFloat needs 3 or 4 arguments")
}
val r = args.arg(1).checkint()
val g = args.arg(2).checkint()
val b = args.arg(3).checkint()
val a = if (args.narg() == 4) args.arg(4).checkint() else 255
return LuaValue.valueOf(Color.toFloatBits(r, g, b, a).toDouble())
}
})
set("randomizeWeaponTimers", lFuncU { e, mtv ->
val entity = CoerceLuaToJava.coerce(e, Entity::class.java) as Entity
val maxTimerVal = mtv.checkdouble().toFloat()
WeaponComponent.MAPPER.get(entity)?.let { weaponComp ->
for (i in 0 until weaponComp.timers.size) {
weaponComp.timers[i] = currLevel.random.nextFloat() * maxTimerVal
}
}
})
}
return NIL
}
@EventHandle
fun onLevelStart(event: BeginLevelEvent) {
currLevel = event.level
}
private inline fun lFuncU(crossinline body: () -> Unit) = object : ZeroArgFunction() {
override fun call(): LuaValue {
body(); return NIL
}
}
private inline fun lFunc(crossinline body: () -> LuaValue) = object : ZeroArgFunction() {
override fun call(): LuaValue = body()
}
private inline fun lFuncU(crossinline body: (LuaValue) -> Unit) = object : OneArgFunction() {
override fun call(v: LuaValue): LuaValue {
body(v); return NIL
}
}
private inline fun lFunc(crossinline body: (LuaValue) -> LuaValue) = object : OneArgFunction() {
override fun call(v: LuaValue): LuaValue = body(v)
}
private inline fun lFuncU(crossinline body: (LuaValue, LuaValue) -> Unit) = object : TwoArgFunction() {
override fun call(v1: LuaValue, v2: LuaValue): LuaValue {
body(v1, v2); return NIL
}
}
private inline fun lFunc(crossinline body: (LuaValue, LuaValue) -> LuaValue) = object : TwoArgFunction() {
override fun call(v1: LuaValue, v2: LuaValue): LuaValue = body(v1, v2)
}
private inline fun lFuncU(crossinline body: (LuaValue, LuaValue, LuaValue) -> Unit) = object : ThreeArgFunction() {
override fun call(v1: LuaValue, v2: LuaValue, v3: LuaValue): LuaValue {
body(v1, v2, v3); return NIL
}
}
private inline fun lFunc(
crossinline body: (LuaValue, LuaValue, LuaValue) -> LuaValue) = object : ThreeArgFunction() {
override fun call(v1: LuaValue, v2: LuaValue, v3: LuaValue): LuaValue = body(v1, v2, v3)
}
}
| mit | c1ec8380bcada35b31cf0e7ddd1028cb | 47.349081 | 191 | 0.565496 | 4.476549 | false | false | false | false |
aleksey-zhidkov/jeb-k | src/main/kotlin/jeb/cfg/Parser.kt | 1 | 3071 | package jeb.cfg
import jeb.util.Try
import java.util.*
object Parser {
fun parse(input: String): Try<Json.Object> = Try.Success(parseObject(Scanner(input)))
private fun parseObject(input: Scanner): Json.Object {
input.expect('{')
val fields = LinkedHashSet<Pair<String, Json<*>>>()
val firstField: Pair<String, Json<*>>? = when (input.current()) {
'\"' -> parseField(input)
'}' -> null
else -> throw ParseException("Unexpected char: ${input.current()}")
}
if (firstField != null) {
fields.add(firstField)
while (input.swallow(',')) {
fields.add(parseField(input))
}
}
input.expect('}')
return Json.Object(fields.toMap(LinkedHashMap()))
}
private fun parseField(input: Scanner): Pair<String, Json<*>> {
val name = parseStringLiteral(input)
input.expect(':')
val value = parseValue(input)
return Pair(name.value, value)
}
private fun parseValue(input: Scanner): Json<*> {
val value = when (input.current()) {
'"' -> parseStringLiteral(input)
'{' -> parseObject(input)
'[' -> parseArray(input)
in '0' .. '9' -> parseInteger(input)
't', 'f' -> parseSymbol(input)
else -> throw ParseException("Unexpected input: ${input.current()}")
}
return value
}
private fun parseSymbol(input: Scanner): Json.Boolean {
val buffer = StringBuilder()
while (input.current().isLetter()) {
buffer.append(input.scan())
}
return when (buffer.toString()) {
"true" -> Json.True
"false" -> Json.False
else -> throw ParseException("Unknown symbol: $buffer")
}
}
private fun parseInteger(input: Scanner): Json.Integer {
val buffer = StringBuilder()
while (input.current() in '0' .. '9') {
buffer.append(input.scan())
}
return Json.Integer(buffer.toString().toInt())
}
private fun parseArray(input: Scanner): Json.Array {
input.expect('[')
val items = ArrayList<Json<*>>()
if (input.swallow(']')) {
return Json.Array(items)
}
items.add(parseValue(input))
while (input.swallow(',')) {
items.add(parseValue(input))
}
input.expect(']')
return Json.Array(items)
}
private fun parseStringLiteral(input: Scanner): Json.String {
input.expect('\"')
val buffer = StringBuilder()
while (true) {
val c = input.scan()
if (c == '"') {
if (buffer.last() != '\\') {
input.back(1)
} else {
buffer[buffer.length - 1] = c
}
break
} else {
buffer.append(c)
}
}
input.expect('"')
return Json.String(buffer.toString())
}
} | apache-2.0 | 0cab1eb761c690108768e2638c0bcdd1 | 27.71028 | 89 | 0.508955 | 4.529499 | false | false | false | false |
alyphen/guildford-game-jam-2016 | core/src/main/kotlin/com/seventh_root/guildfordgamejam/system/ColorCollectionSystem.kt | 1 | 1178 | package com.seventh_root.guildfordgamejam.system
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.graphics.Color
import com.seventh_root.guildfordgamejam.component.*
class ColorCollectionSystem: IteratingSystem(Family.all(GrappleComponent::class.java, ColorComponent::class.java, PositionComponent::class.java).get()) {
val playerFamily: Family = Family.all(PlayerComponent::class.java, PositionComponent::class.java, CollectedColorsComponent::class.java).get()
override fun processEntity(entity: Entity, deltaTime: Float) {
val player = engine.getEntitiesFor(playerFamily).firstOrNull()
if (player != null) {
if (position.get(player).x == position.get(entity).x && position.get(player).y == position.get(entity).y) {
if (color.get(entity).color != Color.WHITE) {
if (!collectedColors.get(player).colors.contains(color.get(entity).color)) {
collectedColors.get(player).colors.add(color.get(entity).color)
}
}
}
}
}
} | apache-2.0 | 3f1714517167a488e25055e9a2d3dc37 | 50.26087 | 153 | 0.683362 | 4.252708 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/extensions/ImageView.kt | 1 | 10124 | package com.boardgamegeek.extensions
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.view.setMargins
import androidx.palette.graphics.Palette
import com.boardgamegeek.R
import com.boardgamegeek.io.Adapter
import com.boardgamegeek.util.PaletteTransformation
import com.boardgamegeek.util.RemoteConfig
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import timber.log.Timber
import java.util.*
fun ImageView.setOrClearColorFilter(@ColorInt color: Int) {
if (color == Color.TRANSPARENT) clearColorFilter() else setColorFilter(color)
}
/**
* Call back from loading an image.
*/
interface ImageLoadCallback {
fun onSuccessfulImageLoad(palette: Palette?)
fun onFailedImageLoad()
}
/**
* Loads the URL into an ImageView, triggering a callback with the palette for the loaded image. If the URL appears to be for the same image, no
* placeholder or fade animation is shown.
*/
fun ImageView.loadUrl(url: String?, callback: ImageLoadCallback? = null) {
val tag = getTag(R.id.image)
val isSameImage = tag != null && tag == url?.getImageId()
val requestCreator = Picasso.with(context)
.load(url.ensureHttpsScheme())
.transform(PaletteTransformation.instance())
if (isSameImage) {
requestCreator.noFade().noPlaceholder()
}
requestCreator.into(this, object : Callback {
override fun onSuccess() {
setTag(R.id.image, url?.getImageId())
callback?.onSuccessfulImageLoad(PaletteTransformation.getPalette((drawable as BitmapDrawable).bitmap))
}
override fun onError() {
callback?.onFailedImageLoad()
}
})
}
/**
* Loads an image into the [android.widget.ImageView] by attempting various sizes and image formats. Applies
* fit/center crop and will load a [androidx.palette.graphics.Palette].
*/
suspend fun ImageView.safelyLoadImage(imageId: Int, callback: ImageLoadCallback? = null) {
if (imageId <= 0) {
Timber.i("Not attempting to fetch invalid image ID of 0 or negative [%s].", imageId)
return
}
RemoteConfig.fetch()
if (RemoteConfig.getBoolean(RemoteConfig.KEY_FETCH_IMAGE_WITH_API)) {
try {
val response = Adapter.createGeekdoApi().image(imageId)
loadImages(callback, response.images.medium.url, response.images.small.url, *imageId.createImageUrls().toTypedArray())
} catch (e: Exception) {
loadImages(callback, *imageId.createImageUrls().toTypedArray())
}
} else {
loadImages(callback, *imageId.createImageUrls().toTypedArray())
}
}
/**
* Loads an image into the [android.widget.ImageView] by attempting various sizes. Applies fit/center crop and
* will load a [androidx.palette.graphics.Palette].
*/
suspend fun ImageView.safelyLoadImage(imageUrl: String, thumbnailUrl: String, heroImageUrl: String? = "", callback: ImageLoadCallback? = null) {
RemoteConfig.fetch()
if (heroImageUrl?.isNotEmpty() == true) {
loadImages(callback, heroImageUrl, thumbnailUrl, imageUrl)
} else if (RemoteConfig.getBoolean(RemoteConfig.KEY_FETCH_IMAGE_WITH_API)) {
val imageId = imageUrl.getImageId()
if (imageId > 0) {
try {
val response = Adapter.createGeekdoApi().image(imageId)
loadImages(callback, response.images.medium.url, response.images.small.url, thumbnailUrl, imageUrl)
} catch (e: Exception) {
loadImages(callback, thumbnailUrl, imageUrl)
}
} else {
loadImages(callback, thumbnailUrl, imageUrl)
}
} else {
loadImages(callback, thumbnailUrl, imageUrl)
}
}
fun ImageView.loadImages(callback: ImageLoadCallback?, vararg urls: String) {
safelyLoadImage(LinkedList(urls.toList()), callback)
}
/**
* Loads an image into the [android.widget.ImageView] by attempting each URL in the [java.util.Queue]
* until one is successful. Applies fit/center crop and will load a [androidx.palette.graphics.Palette].
*/
private fun ImageView.safelyLoadImage(imageUrls: Queue<String>, callback: ImageLoadCallback?) {
// Attempt to load 1) the URL saved as a tag to this ImageView or 2) the next URL in the queue. If this URL fails, recursively call this to
// attempt to load the next URL. Signal a failure if the queue empties before successfully loading a URL.
var url: String? = null
val savedUrl = getTag(R.id.url) as String?
if (savedUrl?.isNotBlank() == true) {
if (imageUrls.contains(savedUrl)) {
url = savedUrl
} else {
setTag(R.id.url, null)
}
}
if (url == null) {
do {
val polledUrl = imageUrls.poll()
if (polledUrl == null) {
callback?.onFailedImageLoad()
return
} else {
url = polledUrl
}
} while (url.isNullOrBlank())
}
if (url.isNullOrEmpty()) {
callback?.onFailedImageLoad()
return
}
val imageUrl = url
Picasso.with(context)
.load(imageUrl.ensureHttpsScheme())
.transform(PaletteTransformation.instance())
.into(this, object : Callback {
override fun onSuccess() {
setTag(R.id.url, imageUrl)
callback?.onSuccessfulImageLoad(PaletteTransformation.getPalette((drawable as BitmapDrawable).bitmap))
}
override fun onError() {
safelyLoadImage(imageUrls, callback)
}
})
}
/**
* Loads the URL into an ImageView, centering and fitting it into the image. If the URL appears to be for the same image, no placeholder or fade
* animation is shown.
*/
fun ImageView.loadThumbnail(imageUrl: String?, @DrawableRes errorResId: Int = R.drawable.thumbnail_image_empty) {
val tag = getTag(R.id.image)
val isSameImage = tag != null && tag == imageUrl?.getImageId()
val requestCreator = Picasso.with(context)
.load(imageUrl.ensureHttpsScheme())
.error(errorResId)
.fit()
.centerCrop()
if (isSameImage) {
requestCreator.noFade().noPlaceholder()
} else {
requestCreator.placeholder(errorResId).noFade()
}
requestCreator.into(this, object : Callback {
override fun onSuccess() {
setTag(R.id.url, imageUrl)
}
override fun onError() {
}
})
}
/**
* Loads the URL into an ImageView, centering and fitting it into the image. Always shows the fade animation (and it faster for that).
*/
fun ImageView.loadThumbnailInList(imageUrl: String?, @DrawableRes errorResId: Int = R.drawable.thumbnail_image_empty) {
Picasso.with(context)
.load(imageUrl.ensureHttpsScheme())
.placeholder(errorResId)
.error(errorResId)
.fit()
.centerCrop()
.into(this)
}
suspend fun ImageView.loadThumbnail(imageId: Int) {
if (imageId <= 0) {
Timber.i("Not attempting to fetch invalid image ID of 0 or negative [%s].", imageId)
return
}
RemoteConfig.fetch()
if (RemoteConfig.getBoolean(RemoteConfig.KEY_FETCH_IMAGE_WITH_API)) {
try {
val response = Adapter.createGeekdoApi().image(imageId)
loadThumbnails(response.images.small.url, *imageId.createImageUrls().toTypedArray())
} catch (e: Exception) {
loadThumbnails(*imageId.createImageUrls().toTypedArray())
}
} else {
loadThumbnails(*imageId.createImageUrls().toTypedArray())
}
}
private fun ImageView.loadThumbnails(vararg urls: String) {
safelyLoadThumbnail(LinkedList(urls.toList()))
}
private fun ImageView.safelyLoadThumbnail(imageUrls: Queue<String>) {
var url: String? = null
while (url.isNullOrEmpty() && imageUrls.isNotEmpty()) {
url = imageUrls.poll()
}
val imageUrl = url
Picasso.with(context)
.load(imageUrl.ensureHttpsScheme())
.placeholder(R.drawable.thumbnail_image_empty)
.error(R.drawable.thumbnail_image_empty)
.fit()
.centerCrop()
.into(this, object : Callback {
override fun onSuccess() {
}
override fun onError() {
safelyLoadThumbnail(imageUrls)
}
})
}
fun Int.createImageUrls(): List<String> {
val imageUrlPrefix = "https://cf.geekdo-images.com/images/pic"
return listOf("$imageUrlPrefix$this.jpg", "$imageUrlPrefix$this.png")
}
fun ImageView.setOrClearColorViewValue(color: Int, disabled: Boolean = false) {
if (color != Color.TRANSPARENT) {
setColorViewValue(color, disabled)
} else {
setImageDrawable(null)
}
}
fun ImageView.setColorViewValue(color: Int, disabled: Boolean = false) {
val colorChoiceDrawable = drawable as? GradientDrawable ?: GradientDrawable().apply {
shape = GradientDrawable.OVAL
}
if (disabled) {
colorChoiceDrawable.colors = if (color.isColorDark()) {
intArrayOf(Color.WHITE, color)
} else {
intArrayOf(color, Color.BLACK)
}
} else {
colorChoiceDrawable.setColor(color)
}
colorChoiceDrawable.setStroke(
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, resources.displayMetrics).toInt(),
color.darkenColor()
)
setImageDrawable(colorChoiceDrawable)
}
/**
* Create an ImageView that is a small circle, useful for showing a color.
*/
fun Context.createSmallCircle(): ImageView {
val size = resources.getDimensionPixelSize(R.dimen.color_circle_diameter_small)
val view = ImageView(this)
view.layoutParams = LinearLayout.LayoutParams(size, size).apply {
setMargins(resources.getDimensionPixelSize(R.dimen.color_circle_diameter_small_margin))
}
return view
}
| gpl-3.0 | 4c826fe84fea10115e17bd3e1183b6fb | 34.031142 | 144 | 0.663868 | 4.337618 | false | false | false | false |
jamieadkins95/Roach | buildSrc/src/main/java/Libs.kt | 1 | 2965 | object Libs {
const val gradle_plugin = "com.android.tools.build:gradle:${Versions.gradle_plugin}"
const val kotlin_plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
const val google_services_plugin = "com.google.gms:google-services:${Versions.google_services_plugin}"
const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}"
const val firebase = "com.google.firebase:firebase-core:${Versions.firebase_core}"
const val firebase_storage = "com.google.firebase:firebase-storage:${Versions.firebase_storage}"
const val firebase_messaging = "com.google.firebase:firebase-messaging:${Versions.firebase_messaging}"
const val firebase_firestore = "com.google.firebase:firebase-firestore:${Versions.firebase_firestore}"
const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
const val retrofit_rxjava_adapter = "com.squareup.retrofit2:adapter-rxjava2:${Versions.retrofit}"
const val retrofit_gson_coverter = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}"
const val rxjava = "io.reactivex.rxjava2:rxjava:${Versions.rxjava}"
const val rxandroid = "io.reactivex.rxjava2:rxandroid:${Versions.rxandroid}"
const val rxpreferences = "com.f2prateek.rx.preferences2:rx-preferences:${Versions.rxpreferences}"
const val gson = "com.google.code.gson:gson:${Versions.gson}"
const val glide = "com.github.bumptech.glide:glide:${Versions.glide}"
const val glide_compiler = "com.github.bumptech.glide:compiler:${Versions.glide}"
const val nytimes_store_cache = "com.nytimes.android:cache3:${Versions.nytimes_store}"
const val timber = "com.jakewharton.timber:timber:${Versions.timber}"
const val junit = "junit:junit:${Versions.junit}"
const val mockito = "org.mockito:mockito-core:${Versions.mockito}"
const val mockito_kotlin = "com.nhaarman:mockito-kotlin:${Versions.mockito_kotlin}"
const val dagger = "com.google.dagger:dagger:${Versions.dagger}"
const val dagger_support = "com.google.dagger:dagger-android-support:${Versions.dagger}"
const val dagger_processor = "com.google.dagger:dagger-android-processor:${Versions.dagger}"
const val dagger_compiler = "com.google.dagger:dagger-compiler:${Versions.dagger}"
const val javaxAnnotation = "javax.annotation:javax.annotation-api:${Versions.javaxAnnotation}"
const val javaxInject = "javax.inject:javax.inject:${Versions.javaxInject}"
const val groupie = "com.xwray:groupie:${Versions.groupie}"
const val groupie_extensions = "com.xwray:groupie-kotlin-android-extensions:${Versions.groupie}"
const val appcompat = "androidx.appcompat:appcompat:1.0.2"
const val material = "com.google.android.material:material:1.0.0"
const val card_view = "androidx.cardview:cardview:1.0.0"
const val constraint_layout = "androidx.constraintlayout:constraintlayout:2.0.0-beta2"
const val custom_tabs = "androidx.browser:browser:1.0.0"
}
| apache-2.0 | f95d477e3c896fecdf4a8d95c5e7ce7e | 79.135135 | 106 | 0.748398 | 3.845655 | false | false | false | false |
verhoevenv/kotlin-koans | src/ii_collections/_16_FlatMap.kt | 1 | 367 | package ii_collections
fun example() {
val result = listOf("abc", "12").flatMap { it.toList() }
result == listOf('a', 'b', 'c', '1', '2')
}
val Customer.orderedProducts: Set<Product> get() = this.orders.flatMap { it.products }.toSet()
val Shop.allOrderedProducts: Set<Product> get() = this.customers.flatMap { it.orders }.flatMap { it.products }.toSet()
| mit | 9af97691e127a0edcbcb0e35c569dfaa | 29.583333 | 118 | 0.656676 | 3.398148 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/utilities/FixtureCompetitionHelper.kt | 1 | 3169 | package com.bravelocation.yeltzlandnew.utilities
enum class FixtureCompetition {
League, FACup, FATrophy, CharityShield, Friendly, WorcesterSeniorCup, BhamSeniorCup, LeagueCup, Playoff, Other
}
internal object FixtureCompetitionHelper {
fun competition(opponent: String) : FixtureCompetition {
// Do we have a bracket in the name
val startBracketPos = opponent.indexOf("(")
if (startBracketPos > 0) {
val afterBracketSubstring = opponent.substring(startBracketPos + 1)
return if (afterBracketSubstring.startsWith(prefix = "FAC")) {
FixtureCompetition.FACup
} else if (afterBracketSubstring.startsWith(prefix = "FAT")) {
FixtureCompetition.FATrophy
} else if (afterBracketSubstring.startsWith(prefix = "CS")) {
FixtureCompetition.CharityShield
} else if (afterBracketSubstring.startsWith(prefix = "F")) {
FixtureCompetition.Friendly
} else if (afterBracketSubstring.startsWith(prefix = "WSC")) {
FixtureCompetition.WorcesterSeniorCup
} else if (afterBracketSubstring.startsWith(prefix = "BSC")) {
FixtureCompetition.BhamSeniorCup
} else if (afterBracketSubstring.startsWith(prefix = "LC")) {
FixtureCompetition.LeagueCup
} else if (afterBracketSubstring.startsWith(prefix = "PO")) {
FixtureCompetition.Playoff
} else {
FixtureCompetition.Other
}
}
return FixtureCompetition.League
}
fun competitionName(opponent: String) : String {
return when (competition(opponent)) {
FixtureCompetition.FACup -> "FA Cup"
FixtureCompetition.FATrophy -> "FA Trophy"
FixtureCompetition.CharityShield -> "Charity Shield"
FixtureCompetition.Friendly -> "Friendly"
FixtureCompetition.WorcesterSeniorCup -> "Worcester Senior"
FixtureCompetition.BhamSeniorCup -> "B'ham Senior"
FixtureCompetition.League -> "League"
FixtureCompetition.LeagueCup -> "League Cup"
FixtureCompetition.Playoff -> "Playoff"
FixtureCompetition.Other -> "Other"
}
}
fun competitionNameWithRound(opponent: String) : String {
val competitionName = competitionName(opponent)
round(opponent = opponent)?.let { round ->
return "$competitionName $round"
}
return competitionName
}
private fun round(opponent: String) : String? {
// Do we have a brackets in the name
val startBracketPos = opponent.indexOf("(")
val endBracketPos = opponent.indexOf(")")
if (startBracketPos > 0 && endBracketPos > 0 && endBracketPos > startBracketPos) {
val competitionSubstring = opponent.substring(startBracketPos + 1, endIndex = endBracketPos)
val competitionParts = competitionSubstring.split(" ")
if (competitionParts.count() > 1) {
return competitionParts[1]
}
}
return null
}
} | mit | d6bb0c83fdb493be550f3a153feb51f8 | 38.135802 | 114 | 0.624487 | 4.708767 | false | false | false | false |
rickshory/VegNab | app/src/main/java/com/rickshory/vegnab/roomdb/VNRoomDatabase.kt | 1 | 2462 | package com.rickshory.vegnab.roomdb
import android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.rickshory.vegnab.roomdb.daos.VisitDao
import com.rickshory.vegnab.roomdb.entities.Visit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
//import org.koin.dsl.context.Context
@Database(entities = arrayOf(Visit::class), version = 1)
public abstract class VNRoomDatabase: RoomDatabase() {
private val TAG = this::class.java.simpleName
abstract fun visitDao(): VisitDao
companion object {
@Volatile
private var INSTANCE: VNRoomDatabase? = null
fun getDatabase(context: Context,
scope: CoroutineScope
): VNRoomDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) { // if existing, lock
// else create instance
val instance = Room.databaseBuilder(
context.applicationContext,
VNRoomDatabase::class.java,
"VN_database"
).addCallback(VNDatabaseCallback(scope)).build()
INSTANCE = instance
return instance
}
}
}
private class VNDatabaseCallback(
private val scope: CoroutineScope
) : RoomDatabase.Callback() {
private val TAG = this::class.java.simpleName
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
INSTANCE?.let { database ->
scope.launch(Dispatchers.IO) {
populateDatabase(database.visitDao())
}
}
}
fun populateDatabase(visitDao: VisitDao) {
visitDao.deleteAll()
Log.d(TAG, "adding record 1 to database")
var visit = Visit(1, "tstVis", "test of Visit entry")
visitDao.insert(visit)
Log.d(TAG, "adding record 2 to database")
visit = Visit(2, "secondVis", "another test")
visitDao.insert(visit)
Log.d(TAG, "adding record 3 to database")
visit = Visit(3, "addlVis", "yet more")
visitDao.insert(visit)
}
}
}
| gpl-3.0 | ca1a6df0eda32a0454fe01e3eb8d132b | 30.164557 | 65 | 0.601543 | 4.79922 | false | false | false | false |
aglne/mycollab | mycollab-server-runner/src/main/java/com/mycollab/installation/servlet/InstallationServlet.kt | 1 | 5941 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.installation.servlet
import com.mycollab.core.UserInvalidInputException
import com.mycollab.core.utils.FileUtils
import com.mycollab.template.FreemarkerFactory
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.StringWriter
import java.nio.file.FileSystems
import java.nio.file.Files
import java.sql.DriverManager
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author MyCollab Ltd.
* @since 4.1
*/
class InstallationServlet : HttpServlet() {
@Throws(ServletException::class, IOException::class)
override fun doPost(request: HttpServletRequest, response: HttpServletResponse) {
LOG.info("Try to install MyCollab")
val out = response.writer
val siteName = request.getParameter("sitename")
val serverAddress = request.getParameter("serverAddress")
val databaseName = request.getParameter("databaseName")
val dbUserName = request.getParameter("dbUserName")
val dbPassword = request.getParameter("dbPassword")
val databaseServer = request.getParameter("databaseServer")
val smtpUserName = request.getParameter("smtpUserName")
val smtpPassword = request.getParameter("smtpPassword")
val smtpHost = request.getParameter("smtpHost")
val smtpPort = request.getParameter("smtpPort")
val tls = request.getParameter("tls")
val ssl = request.getParameter("ssl")
val dbUrl = "jdbc:mysql://$databaseServer/$databaseName?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&rewriteBatchedStatements=true&useCompression=true&useServerPrepStmts=false&verifyServerCertificate=false&useSSL=false&allowPublicKeyRetrieval=true"
// try {
// Class.forName("com.mysql.jdbc.Driver")
// } catch (e: ClassNotFoundException) {
// LOG.error("Can not load mysql driver", e)
// return
// }
try {
DriverManager.getConnection(dbUrl, dbUserName, dbPassword).use { connection ->
LOG.debug("Check database config")
connection.metaData
}
} catch (e: Exception) {
val rootCause = if (e.cause == null) e.message else e.cause
out.write("Cannot establish connection to database. Make sure your inputs are correct. Root cause is $rootCause")
LOG.error("Can not connect database", e)
return
}
val mailServerPort = try {
Integer.parseInt(smtpPort)
} catch (e: Exception) {
0
}
val isStartTls = java.lang.Boolean.parseBoolean(tls)
val isSsl = java.lang.Boolean.parseBoolean(ssl)
try {
InstallUtils.checkSMTPConfig(smtpHost, mailServerPort, smtpUserName, smtpPassword, true, isStartTls, isSsl)
} catch (e: UserInvalidInputException) {
LOG.warn("Cannot authenticate mail server successfully. Make sure your inputs are correct.")
}
val templateContext = mutableMapOf("sitename" to siteName, "serveraddress" to serverAddress,
"dbUrl" to dbUrl, "dbUser" to dbUserName, "dbPassword" to dbPassword,
"smtpAddress" to smtpHost, "smtpPort" to mailServerPort, "smtpUserName" to smtpUserName,
"smtpPassword" to smtpPassword, "smtpTLSEnable" to tls, "smtpSSLEnable" to ssl,
"mailNotify" to smtpUserName)
val confFolder = FileUtils.getDesireFile(FileUtils.userFolder, "config", "src/main/config")
if (confFolder == null) {
out.write("Can not write the settings to the file system. You should check our knowledge base article at " + "http://support.mycollab.com/topic/994098-/ to solve this issue.")
return
}
if (!Files.isWritable(FileSystems.getDefault().getPath(confFolder.absolutePath))) {
out.write("The folder ${confFolder.absolutePath} has no write permission with the current user." +
" You should set the write permission for MyCollab process for this folder. You should check our knowledge base article at http://support.mycollab.com/topic/994098-/ to solve this issue.")
return
}
try {
val writer = StringWriter()
val template = FreemarkerFactory.template("application.properties.ftl")
template.process(templateContext, writer)
val outStream = FileOutputStream(File(confFolder, "application.properties"))
outStream.write(writer.toString().toByteArray())
outStream.flush()
outStream.close()
} catch (e: Exception) {
LOG.error("Error while set up MyCollab", e)
out.write("Can not write the settings to the file system. You should check our knowledge base article at http://support.mycollab.com/topic/994098-/ to solve this issue.")
}
}
companion object {
private const val serialVersionUID = 1L
private val LOG = LoggerFactory.getLogger(InstallationServlet::class.java)
}
}
| agpl-3.0 | 356ba72e7864cffad17f1261bbf96e27 | 44.692308 | 270 | 0.682155 | 4.510251 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/festival/adapter/FestivalAdapter.kt | 1 | 1920 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.main.fragments.festival.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.pickth.gachi.R
import com.pickth.gachi.util.OnFestivalClickListener
class FestivalAdapter: RecyclerView.Adapter<FestivalViewHolder>(), FestivalAdapterContract.View, FestivalAdapterContract.Model {
private var items = ArrayList<Festival>()
var mOnFestivalClickListener: OnFestivalClickListener?= null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): FestivalViewHolder {
val itemView = LayoutInflater
.from(parent?.context)
.inflate(R.layout.item_main_festival, parent, false)
return FestivalViewHolder(itemView, mOnFestivalClickListener)
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: FestivalViewHolder?, position: Int) {
holder?.onBind(items[position], position)
}
override fun setItemClickListener(clickListener: OnFestivalClickListener) {
mOnFestivalClickListener = clickListener
}
override fun addItem(item: Festival) {
items.add(item)
notifyItemInserted(itemCount - 1)
}
override fun getItem(position: Int): Festival = items[position]
} | apache-2.0 | 88c7885212e9cd990dd5c8227deaf1f2 | 34.574074 | 128 | 0.740625 | 4.423963 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/alarms/edit/EditAlarmViewModel.kt | 1 | 2539 | package be.florien.anyflow.feature.alarms.edit
import androidx.lifecycle.MutableLiveData
import be.florien.anyflow.data.view.Alarm
import be.florien.anyflow.feature.BaseViewModel
import be.florien.anyflow.feature.alarms.AlarmsSynchronizer
import javax.inject.Inject
class EditAlarmViewModel : BaseViewModel() {
val isRepeating: MutableLiveData<Boolean> = MutableLiveData(false)
val time: MutableLiveData<Int> = MutableLiveData()
val monday: MutableLiveData<Boolean> = MutableLiveData()
val tuesday: MutableLiveData<Boolean> = MutableLiveData()
val wednesday: MutableLiveData<Boolean> = MutableLiveData()
val thursday: MutableLiveData<Boolean> = MutableLiveData()
val friday: MutableLiveData<Boolean> = MutableLiveData()
val saturday: MutableLiveData<Boolean> = MutableLiveData()
val sunday: MutableLiveData<Boolean> = MutableLiveData()
@Inject
lateinit var alarmsSynchronizer: AlarmsSynchronizer
var alarm: Alarm? = null
set(value) {
if (value != null) {
field = value
isRepeating.value = value.isRepeating
time.value = value.minute + (value.hour * 60)
monday.value = value.daysToTrigger[0]
tuesday.value = value.daysToTrigger[1]
wednesday.value = value.daysToTrigger[2]
thursday.value = value.daysToTrigger[3]
friday.value = value.daysToTrigger[4]
saturday.value = value.daysToTrigger[5]
sunday.value = value.daysToTrigger[6]
}
}
suspend fun editAlarm() {
val newAlarm = Alarm(alarm?.id ?: 0L, (time.value ?: 0) / 60, (time.value ?: 0) % 60, isRepeating.value ?: false, listOf(
monday.value ?: false && isRepeating.value ?: false,
tuesday.value ?: false && isRepeating.value ?: false,
wednesday.value ?: false && isRepeating.value ?: false,
thursday.value ?: false && isRepeating.value ?: false,
friday.value ?: false && isRepeating.value ?: false,
saturday.value ?: false && isRepeating.value ?: false,
sunday.value ?: false && isRepeating.value ?: false,
), alarm?.active ?: false)
if (newAlarm != alarm) {
alarmsSynchronizer.updateAlarm(newAlarm)
}
}
suspend fun deleteAlarm() {
val alarmNullSafe = alarm
if (alarmNullSafe != null)
alarmsSynchronizer.deleteAlarm(alarmNullSafe)
}
} | gpl-3.0 | 257bb463acef87cdb4634b7e765212f2 | 42.050847 | 129 | 0.632532 | 4.745794 | false | false | false | false |
tag-them/metoothanks | app/src/main/java/org/itiswednesday/metoothanks/items/Item.kt | 1 | 2695 | package org.itiswednesday.metoothanks.items
import android.graphics.*
import android.view.MenuItem
import org.itiswednesday.metoothanks.CanvasView
import org.itiswednesday.metoothanks.EDGE_WIDTH
import org.itiswednesday.metoothanks.PointPair
abstract class Item(val canvas: CanvasView, width: Int, height: Int) {
open var left = 0
set(value) {
if (value < right - EDGE_WIDTH) field = value
}
open var top = 0
set(value) {
if (value < bottom - EDGE_WIDTH) field = value
}
open var right = width
set(value) {
if (value > left + EDGE_WIDTH) field = value
}
open var bottom = height
set(value) {
if (value > top + EDGE_WIDTH) field = value
}
val width: Int
get() = right - left
val height: Int
get() = bottom - top
protected val paint = Paint()
val bounds: RectF
get() = RectF(Rect(left, top, right, bottom))
abstract val itemMenuID: Int
abstract fun handleMenuItemClick(item: MenuItem): Boolean
abstract fun draw(canvas: Canvas)
fun touched(touchX: Int, touchY: Int): Boolean = touchX in left..right && touchY in top..bottom
fun move(x: Int, y: Int) {
right = x + (right - left)
bottom = y + (bottom - top)
left = x
top = y
}
open fun resize(pointers: PointPair, pointersGrip: PointPair, pointersGripDistance: PointPair) {
for (index in 0..1) {
if (pointersGrip[index].x in 0..(left + width / 2))
left = pointers[index].x - pointersGripDistance[index].x
else
right = pointers[index].x + pointersGripDistance[index].x
if (pointersGrip[index].y in 0..(top + height / 2))
top = pointers[index].y - pointersGripDistance[index].y
else
bottom = pointers[index].y + pointersGripDistance[index].y
}
}
open fun resize(pointers: PointPair, pointersGrip: PointPair, originalBounds: RectF) {
val gripLeftRatio: Float = pointers.closer.x.toFloat() / pointersGrip.closer.x.toFloat()
left = (originalBounds.left * gripLeftRatio).toInt()
val gripRightRatio: Float = pointers.further.x.toFloat() / pointersGrip.further.x.toFloat()
right = (originalBounds.right * gripRightRatio).toInt()
val gripTopRatio = pointers.closer.y.toFloat() / pointersGrip.closer.y.toFloat()
top = (originalBounds.top * gripTopRatio).toInt()
val gripBottomRatio = pointers.further.y.toFloat() / pointersGrip.further.y.toFloat()
bottom = (originalBounds.bottom * gripBottomRatio).toInt()
}
} | mpl-2.0 | 191944071939ed34421bcaaf02953e81 | 32.7 | 100 | 0.618553 | 3.861032 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/auth/ldap/config/LdapUserDBConfig.kt | 1 | 2486 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.auth.ldap.config
import com.unboundid.ldap.sdk.Filter
import com.unboundid.ldap.sdk.LDAPException
import svnserver.auth.UserDB
import svnserver.auth.ldap.LdapUserDB
import svnserver.config.UserDBConfig
import svnserver.context.SharedContext
import java.nio.file.Path
/**
* @author Marat Radchenko <[email protected]>
*/
class LdapUserDBConfig constructor(
/**
* This is a URL whose format is defined by the JNDI provider.
* It is usually an LDAP URL that specifies the domain name of the directory server to connect to,
* and optionally the port number and distinguished name (DN) of the required root naming context.
*/
var connectionUrl: String = "ldap://localhost:389/ou=groups,dc=mycompany,dc=com",
/**
* Bind configuration.
*/
var bind: LdapBind = LdapBindANONYMOUS.instance,
/**
* Common part of search filter.
*/
private var searchFilter: String = "",
/**
* LDAP attribute, containing user login.
*/
var loginAttribute: String = "sAMAccountName",
/**
* LDAP attribute, containing user name.
*/
var nameAttribute: String = "name",
/**
* LDAP attribute, containing user email.
*/
var emailAttribute: String = "mail",
ldapCertPem: Path? = null,
/**
* Maximum LDAP connections.
*/
var maxConnections: Int = 10,
/**
* Email addresses suffix for users without LDAP email.
* If empty - don't generate emails.
*/
var fakeMailSuffix: String = ""
) : UserDBConfig {
/**
* Certificate for validation LDAP server with SSL connection.
*/
var ldapCertPem: String? = ldapCertPem?.toString()
@Throws(Exception::class)
override fun create(context: SharedContext): UserDB {
return LdapUserDB(context, this)
}
@Throws(LDAPException::class)
fun createSearchFilter(username: String): Filter {
val filter = Filter.createEqualityFilter(loginAttribute, username)
return if (searchFilter.isEmpty()) filter else Filter.createANDFilter(Filter.create(searchFilter), filter)
}
}
| gpl-2.0 | efc4aea5f70348f81ce7dd01b4393921 | 32.146667 | 114 | 0.686243 | 4.022654 | false | true | false | false |
soywiz/korge | korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/SkeletonData.kt | 1 | 9122 | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.esotericsoftware.spine
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
/** Stores the setup pose and all of the stateless data for a skeleton.
*
*
* See [Data objects](http://esotericsoftware.com/spine-runtime-architecture#Data-objects) in the Spine Runtimes
* Guide. */
class SkeletonData {
// ---
/** The skeleton's name, which by default is the name of the skeleton data file, if possible.
* @return May be null.
*/
/** @param name May be null.
*/
var name: String? = null
// --- Bones.
/** The skeleton's bones, sorted parent first. The root bone is always the first bone. */
val bones: FastArrayList<BoneData> = FastArrayList<BoneData>() // Ordered parents first.
// --- Slots.
/** The skeleton's slots. */
val slots: FastArrayList<SlotData> = FastArrayList<SlotData>() // Setup pose draw order.
/** All skins, including the default skin. */
val skins: FastArrayList<Skin> = FastArrayList<Skin>()
// --- Skins.
/** The skeleton's default skin. By default this skin contains all attachments that were not in a skin in Spine.
*
*
* See [Skeleton.getAttachment].
* @return May be null.
*/
/** @param defaultSkin May be null.
*/
lateinit var defaultSkin: Skin
/** The skeleton's events. */
val events: FastArrayList<EventData> = FastArrayList()
// --- Animations.
/** The skeleton's animations. */
val animations: FastArrayList<Animation> = FastArrayList()
// --- IK constraints
/** The skeleton's IK constraints. */
val ikConstraints: FastArrayList<IkConstraintData> = FastArrayList()
// --- Transform constraints
/** The skeleton's transform constraints. */
val transformConstraints: FastArrayList<TransformConstraintData> = FastArrayList()
// --- Path constraints
/** The skeleton's path constraints. */
val pathConstraints: FastArrayList<PathConstraintData> = FastArrayList()
/** The X coordinate of the skeleton's axis aligned bounding box in the setup pose. */
var x: Float = 0.toFloat()
/** The Y coordinate of the skeleton's axis aligned bounding box in the setup pose. */
var y: Float = 0.toFloat()
/** The width of the skeleton's axis aligned bounding box in the setup pose. */
var width: Float = 0.toFloat()
/** The height of the skeleton's axis aligned bounding box in the setup pose. */
var height: Float = 0.toFloat()
/** The Spine version used to export the skeleton data, or null. */
/** @param version May be null.
*/
var version: String? = null
/** The skeleton data hash. This value will change if any of the skeleton data has changed.
* @return May be null.
*/
/** @param hash May be null.
*/
var hash: String? = null
// Nonessential.
/** The dopesheet FPS in Spine. Available only when nonessential data was exported. */
var fps = 30f
/** The path to the images directory as defined in Spine. Available only when nonessential data was exported.
* @return May be null.
*/
/** @param imagesPath May be null.
*/
var imagesPath: String? = null
/** The path to the audio directory as defined in Spine. Available only when nonessential data was exported.
* @return May be null.
*/
/** @param audioPath May be null.
*/
var audioPath: String? = null
/** Finds a bone by comparing each bone's name. It is more efficient to cache the results of this method than to call it
* multiple times.
* @return May be null.
*/
fun findBone(boneName: String?): BoneData? {
val bones = this.bones
var i = 0
val n = bones.size
while (i < n) {
val bone = bones[i]
if (bone.name == boneName) return bone
i++
}
return null
}
/** Finds a slot by comparing each slot's name. It is more efficient to cache the results of this method than to call it
* multiple times.
* @return May be null.
*/
fun findSlot(slotName: String?): SlotData? {
val slots = this.slots
var i = 0
val n = slots.size
while (i < n) {
val slot = slots[i]
if (slot.name == slotName) return slot
i++
}
return null
}
/** Finds a skin by comparing each skin's name. It is more efficient to cache the results of this method than to call it
* multiple times.
* @return May be null.
*/
fun findSkin(skinName: String?): Skin? {
skins.fastForEach { skin ->
if (skin.name == skinName) return skin
}
return null
}
// --- Events.
/** Finds an event by comparing each events's name. It is more efficient to cache the results of this method than to call it
* multiple times.
* @return May be null.
*/
fun findEvent(eventDataName: String?): EventData? {
events.fastForEach { eventData ->
if (eventData.name == eventDataName) return eventData
}
return null
}
/** Finds an animation by comparing each animation's name. It is more efficient to cache the results of this method than to
* call it multiple times.
* @return May be null.
*/
fun findAnimation(animationName: String): Animation? {
val animations = this.animations
var i = 0
val n = animations.size
while (i < n) {
val animation = animations[i]
if (animation.name == animationName) return animation
i++
}
return null
}
/** Finds an IK constraint by comparing each IK constraint's name. It is more efficient to cache the results of this method
* than to call it multiple times.
* @return May be null.
*/
fun findIkConstraint(constraintName: String?): IkConstraintData? {
val ikConstraints = this.ikConstraints
var i = 0
val n = ikConstraints.size
while (i < n) {
val constraint = ikConstraints[i]
if (constraint.name == constraintName) return constraint
i++
}
return null
}
/** Finds a transform constraint by comparing each transform constraint's name. It is more efficient to cache the results of
* this method than to call it multiple times.
* @return May be null.
*/
fun findTransformConstraint(constraintName: String?): TransformConstraintData? {
val transformConstraints = this.transformConstraints
var i = 0
val n = transformConstraints.size
while (i < n) {
val constraint = transformConstraints[i]
if (constraint.name == constraintName) return constraint
i++
}
return null
}
/** Finds a path constraint by comparing each path constraint's name. It is more efficient to cache the results of this method
* than to call it multiple times.
* @return May be null.
*/
fun findPathConstraint(constraintName: String?): PathConstraintData? {
val pathConstraints = this.pathConstraints
var i = 0
val n = pathConstraints.size
while (i < n) {
val constraint = pathConstraints[i]
if (constraint.name == constraintName) return constraint
i++
}
return null
}
override fun toString(): String = name ?: super.toString()
}
| apache-2.0 | cacdc0e4f552469a00e10ba017137e31 | 35.488 | 130 | 0.638237 | 4.531545 | false | false | false | false |
apixandru/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/FirstStart.kt | 1 | 9976 | /*
* 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.testGuiFramework.impl
import com.intellij.ide.PrivacyPolicy
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.fixtures.JDialogFixture
import com.intellij.testGuiFramework.impl.FirstStart.Utils.button
import com.intellij.testGuiFramework.impl.FirstStart.Utils.dialog
import com.intellij.testGuiFramework.impl.FirstStart.Utils.radioButton
import com.intellij.testGuiFramework.launcher.ide.IdeType
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.core.SmartWaitRobot
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.fixture.JButtonFixture
import org.fest.swing.fixture.JCheckBoxFixture
import org.fest.swing.fixture.JRadioButtonFixture
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import java.awt.Component
import java.awt.Container
import java.awt.Frame
import java.io.File
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import javax.swing.JButton
import javax.swing.JCheckBox
import javax.swing.JDialog
import javax.swing.JRadioButton
import kotlin.concurrent.thread
/**
* could be used only to initialize IDEA configuration for the first start. Please do not start it with GuiTestCase runner.
*/
abstract class FirstStart(val ideType: IdeType) {
private val FIRST_START_ROBOT_THREAD = "First Start Robot Thread"
protected val LOG = Logger.getInstance(this.javaClass.name)
val myRobot: Robot
val robotThread: Thread = thread(start = false, name = FIRST_START_ROBOT_THREAD) {
try {
completeFirstStart()
}
catch (e: Exception) {
when (e) {
is ComponentLookupException -> {
takeScreenshot(e)
}
is WaitTimedOutError -> {
takeScreenshot(e)
throw exceptionWithHierarchy(e)
}
else -> throw e
}
}
}
private fun takeScreenshot(e: Throwable) {
ScreenshotOnFailure.takeScreenshotOnFailure(e, "FirstStartFailed")
}
private fun exceptionWithHierarchy(e: Throwable): Throwable {
return Exception("Hierarchy log: ${ScreenshotOnFailure.getHierarchy()}", e)
}
// should be initialized before IDE has been started
private val newConfigFolder: Boolean by lazy {
if (ApplicationManager.getApplication() != null) throw Exception(
"Cannot get status (new or not) of config folder because IDE has been already started")
!File(PathManager.getConfigPath()).exists() || System.getProperty("intellij.first.ide.session") == "true"
}
init {
myRobot = SmartWaitRobot()
LOG.info("Starting separated thread: '$FIRST_START_ROBOT_THREAD' to complete initial installation")
robotThread.start()
}
companion object {
var DEFAULT_TIMEOUT: Long = GuiTestCase().defaultTimeout
fun guessIdeAndStartRobot() {
val firstStartClass = System.getProperty("idea.gui.test.first.start.class")
val firstStart = Class.forName(firstStartClass).newInstance() as FirstStart
firstStart.completeInstallation()
}
}
protected abstract fun completeFirstStart()
private fun awtIsNotStarted()
= !(Thread.getAllStackTraces().keys.any { thread -> thread.name.toLowerCase().contains("awt") })
private val checkIsFrameFunction: (Frame) -> Boolean
get() {
val checkIsFrame: (Frame) -> Boolean = { frame ->
frame.javaClass.simpleName == "FlatWelcomeFrame"
&& frame.isShowing
&& frame.isEnabled
}
return checkIsFrame
}
protected fun waitWelcomeFrameAndClose() {
waitWelcomeFrame()
LOG.info("Closing Welcome Frame")
val welcomeFrame = Frame.getFrames().find(checkIsFrameFunction)
myRobot.close(welcomeFrame!!)
Pause.pause(object : Condition("Welcome Frame is gone") {
override fun test(): Boolean {
if (Frame.getFrames().any { checkIsFrameFunction(it) }) myRobot.close(welcomeFrame)
return false
}
}, Timeout.timeout(180, TimeUnit.SECONDS))
}
protected fun waitWelcomeFrame() {
LOG.info("Waiting for a Welcome Frame")
Pause.pause(object : Condition("Welcome Frame to show up") {
override fun test() = Frame.getFrames().any { checkIsFrameFunction(it) }
}, Timeout.timeout(180, TimeUnit.SECONDS))
}
protected fun acceptAgreement() {
if (!needToShowAgreement()) return
with(myRobot) {
val policyAgreementTitle = "Privacy Policy Agreement"
try {
LOG.info("Waiting for '$policyAgreementTitle' dialog")
with(JDialogFixture.findByPartOfTitle(myRobot, policyAgreementTitle, Timeout.timeout(2, TimeUnit.MINUTES))) {
LOG.info("Accept '$policyAgreementTitle' dialog")
button("Accept").click()
}
}
catch (e: WaitTimedOutError) {
LOG.error("'$policyAgreementTitle' dialog hasn't been shown. Check registry...")
}
}
}
protected fun completeInstallation() {
if (!needToShowCompleteInstallation()) return
with(myRobot) {
val title = "Complete Installation"
LOG.info("Waiting for '$title' dialog")
dialog(title)
LOG.info("Click OK on 'Do not import settings'")
radioButton("Do not import settings").select()
button("OK").click()
}
}
protected fun customizeIde(ideName: String = ideType.name) {
if (!needToShowCustomizeWizard()) return
with(myRobot) {
val title = "Customize $ideName"
LOG.info("Waiting for '$title' dialog")
dialog(title)
val buttonText = "Skip All and Set Defaults"
LOG.info("Click '$buttonText'")
button(buttonText).click()
}
}
protected fun needToShowAgreement(): Boolean {
val policy = PrivacyPolicy.getContent()
return !PrivacyPolicy.isVersionAccepted(policy.getFirst())
}
protected fun needToShowCompleteInstallation(): Boolean {
return newConfigFolder
}
protected fun needToShowCustomizeWizard(): Boolean {
return (newConfigFolder && !ConfigImportHelper.isConfigImported())
}
object Utils {
fun Robot.dialog(title: String? = null, timeoutSeconds: Long = DEFAULT_TIMEOUT): JDialogFixture {
val jDialog = waitUntilFound(this, null, JDialog::class.java, timeoutSeconds) { dialog ->
if (title != null) dialog.title == title else true
}
return JDialogFixture(this, jDialog)
}
fun Robot.radioButton(text: String, timeoutSeconds: Long = DEFAULT_TIMEOUT): JRadioButtonFixture {
val jRadioButton = waitUntilFound(this, null, JRadioButton::class.java, timeoutSeconds) { radioButton ->
radioButton.text == text && radioButton.isShowing && radioButton.isEnabled
}
return JRadioButtonFixture(this, jRadioButton)
}
fun Robot.button(text: String, timeoutSeconds: Long = DEFAULT_TIMEOUT): JButtonFixture {
val jButton = waitUntilFound(this, null, JButton::class.java, timeoutSeconds) { button ->
button.isShowing && button.text == text
}
return JButtonFixture(this, jButton)
}
fun Robot.checkbox(text: String, timeoutSeconds: Long = DEFAULT_TIMEOUT): JCheckBoxFixture {
val jCheckBox = waitUntilFound(this, null, JCheckBox::class.java, timeoutSeconds) { checkBox ->
checkBox.text == text && checkBox.isShowing && checkBox.isEnabled
}
return JCheckBoxFixture(this, jCheckBox)
}
fun <ComponentType : Component> waitUntilFound(myRobot: Robot,
container: Container?,
componentClass: Class<ComponentType>,
timeoutSeconds: Long,
matcher: (ComponentType) -> Boolean): ComponentType {
return waitUntilFound(myRobot, container, object : GenericTypeMatcher<ComponentType>(componentClass) {
override fun isMatching(cmp: ComponentType): Boolean = matcher(cmp)
}, Timeout.timeout(timeoutSeconds, TimeUnit.SECONDS))
}
fun <T : Component> waitUntilFound(robot: Robot,
root: Container?,
matcher: GenericTypeMatcher<T>,
timeout: Timeout): T {
val reference = AtomicReference<T>()
Pause.pause(object : Condition("Find component using " + matcher.toString()) {
override fun test(): Boolean {
val finder = robot.finder()
val allFound = if (root != null) finder.findAll(root, matcher) else finder.findAll(matcher)
if (allFound.size == 1) {
reference.set(allFound.first())
}
else if (allFound.size > 1) {
// Only allow a single component to be found, otherwise you can get some really confusing
// test failures; the matcher should pick a specific enough instance
throw Exception("Found more than one " + matcher.supportedType().simpleName + " which matches the criteria: " + allFound)
}
return allFound.size == 1
}
}, timeout)
return reference.get()
}
}
}
| apache-2.0 | 2589b229bd4e3f59d9a2f29a2e9c6add | 36.503759 | 133 | 0.68344 | 4.755005 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/HeadingCollector.kt | 1 | 4016 | package com.telenav.osv.data.collector.phonedata.collector
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.HeadingObject
import com.telenav.osv.data.collector.datatype.datatypes.ThreeAxesObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
/**
* HeadingCollector class collects for all three physical axes (X, Y, Z)
*/
class HeadingCollector(phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler), SensorEventListener {
private var sensorManager: SensorManager? = null
private var isSensorRegistered = false
private var mGravity: FloatArray? = FloatArray(3)
private val mHeadingMatrixIn = FloatArray(16)
private val mHeadingValues = FloatArray(3)
fun registerHeadingListener(context: Context, frequency: Int) {
if (!isSensorRegistered) {
sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
var magneticSensor: Sensor? = null
var gravitySensor: Sensor? = null
if (sensorManager != null) {
magneticSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
gravitySensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
}
if (magneticSensor != null && gravitySensor != null) {
sensorManager!!.registerListener(this, magneticSensor, frequency, notifyHandler)
sensorManager!!.registerListener(this, gravitySensor, frequency, notifyHandler)
isSensorRegistered = true
setUpFrequencyFilter(frequency)
} else {
sendSensorUnavailabilityStatus(HeadingObject(LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE))
}
}
}
fun unregisterListener() {
if (sensorManager != null && isSensorRegistered) {
sensorManager!!.unregisterListener(this)
isSensorRegistered = false
}
}
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
mGravity = event.values
} else {
if (mGravity != null && event.values != null) {
val success = SensorManager.getRotationMatrix(mHeadingMatrixIn, null, mGravity, event.values)
if (success) {
// This method is used in order to map device coordinates to word coordinates (ex: portrait/landscape)
SensorManager.remapCoordinateSystem(mHeadingMatrixIn, SensorManager.AXIS_X, SensorManager.AXIS_Z, mHeadingMatrixIn)
SensorManager.getOrientation(mHeadingMatrixIn, mHeadingValues)
mHeadingValues[0] = Math.toDegrees(mHeadingValues[0].toDouble()).toFloat()
mHeadingValues[1] = Math.toDegrees(mHeadingValues[1].toDouble()).toFloat()
mHeadingValues[2] = Math.toDegrees(mHeadingValues[2].toDouble()).toFloat()
mHeadingValues[0] = if (mHeadingValues[0] >= 0) mHeadingValues[0] else mHeadingValues[0] + 360
val headingObject: ThreeAxesObject = HeadingObject(LibraryUtil.PHONE_SENSOR_READ_SUCCESS)
headingObject.setxValue(mHeadingValues[1]) // heading pitch
headingObject.setyValue(mHeadingValues[2]) // heading roll
headingObject.setzValue(mHeadingValues[0]) // heading azimuth. When this value is 0 the device points to north
determineTimestamp(event.timestamp, headingObject)
}
}
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
// No implementation needed
}
} | lgpl-3.0 | 52ac4ff595fff701d26037ef55db6ac5 | 51.168831 | 160 | 0.675299 | 4.903541 | false | false | false | false |
panpf/sketch | sketch-compose/src/main/java/com/github/panpf/sketch/compose/internal/AsyncImageScaleDecider.kt | 1 | 1581 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.compose.internal
import com.github.panpf.sketch.resize.Scale
import com.github.panpf.sketch.resize.ScaleDecider
/**
* Just to show that it's [ScaleDecider] from AsyncImage
*/
class AsyncImageScaleDecider(val wrapped: ScaleDecider) : ScaleDecider {
override val key: String
get() = wrapped.key
override fun get(
imageWidth: Int,
imageHeight: Int,
resizeWidth: Int,
resizeHeight: Int
): Scale {
return wrapped.get(imageWidth, imageHeight, resizeWidth, resizeHeight)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AsyncImageScaleDecider) return false
if (wrapped != other.wrapped) return false
return true
}
override fun hashCode(): Int {
return wrapped.hashCode()
}
override fun toString(): String {
return "AsyncImageScaleDecider($wrapped)"
}
} | apache-2.0 | 157723eecfb8cc95eac1d7570ebaefd8 | 29.423077 | 78 | 0.689437 | 4.367403 | false | false | false | false |
chaseberry/Sprint | src/main/kotlin/edu/csh/chase/sprint/websockets/BasicWebSocket.kt | 1 | 1672 | package edu.csh.chase.sprint.websockets
import edu.csh.chase.sprint.*
import edu.csh.chase.sprint.parameters.UrlParameters
import okhttp3.Headers
import okhttp3.OkHttpClient
import okio.ByteString
import java.io.IOException
class BasicWebSocket(request: Request,
private val callbacks: WebSocketCallbacks,
client: OkHttpClient,
retries: BackoffTimeout = BackoffTimeout.Exponential(500, 2, 300000L, 5),
autoConnect: Boolean = false) : WebSocket(request, client, retries, autoConnect) {
constructor(url: String,
client: OkHttpClient = Sprint.webSocketClient,
callbacks: WebSocketCallbacks,
urlParameters: UrlParameters? = null,
headers: Headers.Builder = Headers.Builder(),
extraData: Any? = null,
retries: BackoffTimeout = BackoffTimeout.Exponential(500, 2, 300000L, 5),
autoConnect: Boolean = false) : this(getRequest(url, urlParameters, headers, extraData), callbacks,
client, retries, autoConnect)
override fun onConnect(response: Response) {
callbacks.onConnect(response)
}
override fun onDisconnect(disconnectCode: Int, reason: String?) {
callbacks.onDisconnect(disconnectCode, reason)
}
override fun onError(exception: IOException, response: Response?) {
callbacks.onError(exception, response)
}
override fun messageReceived(message: String) {
callbacks.messageReceived(message)
}
override fun messageReceived(message: ByteString) {
callbacks.messageReceived(message)
}
} | apache-2.0 | 0d87dc88a8030d6033d9fb48c95dee64 | 36.177778 | 115 | 0.66567 | 4.846377 | false | false | false | false |
BilledTrain380/sporttag-psa | app/shared/src/test/kotlin/ch/schulealtendorf/psa/shared/reporting/ranking/PsaRankingManagerTest.kt | 1 | 10590 | package ch.schulealtendorf.psa.shared.reporting.ranking
import ch.schulealtendorf.psa.dto.group.SimpleGroupDto
import ch.schulealtendorf.psa.dto.participation.BirthdayDto
import ch.schulealtendorf.psa.dto.participation.CompetitorDto
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.TownDto
import ch.schulealtendorf.psa.dto.participation.athletics.BALLWURF
import ch.schulealtendorf.psa.dto.participation.athletics.BALLZIELWURF
import ch.schulealtendorf.psa.dto.participation.athletics.DisciplineDto
import ch.schulealtendorf.psa.dto.participation.athletics.ResultDto
import ch.schulealtendorf.psa.dto.participation.athletics.SCHNELLLAUF
import ch.schulealtendorf.psa.dto.participation.athletics.SEILSPRINGEN
import ch.schulealtendorf.psa.dto.participation.athletics.UnitDto
import ch.schulealtendorf.psa.dto.participation.athletics.WEITSPRUNG
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import java.time.LocalDate
@Tag("unit-test")
internal class PsaRankingManagerTest {
private lateinit var rankingManager: PsaRankingManager
companion object {
private const val FIRST_RANK = "1. rank"
private const val SECOND_RANK = "2. rank"
private const val THIRD_RANK = "3. rank"
}
@BeforeEach
internal fun beforeEach() {
rankingManager = PsaRankingManager()
}
@Nested
internal inner class DisciplineGroupRanking {
private val firstRankWithResults = competitorDtoOf(surname = FIRST_RANK, results = createHighestResult())
private val thirdRankWithResults = competitorDtoOf(surname = THIRD_RANK, results = createLowestResults())
@Test
internal fun createRanking() {
val competitors = listOf(
thirdRankWithResults.copy(),
competitorDtoOf(surname = FIRST_RANK, results = createHighestResult()),
competitorDtoOf(surname = SECOND_RANK, results = createMiddleResults())
)
val ranking = rankingManager.createDisciplineGroupRanking(competitors)
val expected = listOf(FIRST_RANK, SECOND_RANK, THIRD_RANK)
assertThat(ranking.map { it.surname }).isEqualTo(expected)
}
@Test
internal fun createRankingWhenSamePoints() {
val competitors = listOf(
thirdRankWithResults.copy(),
firstRankWithResults.copy(),
firstRankWithResults.copy(),
firstRankWithResults.copy()
)
val ranking = rankingManager.createDisciplineGroupRanking(competitors)
assertThat(ranking[0].rank).isEqualTo(1)
assertThat(ranking[1].rank).isEqualTo(1)
assertThat(ranking[2].rank).isEqualTo(1)
assertThat(ranking[3].rank).isEqualTo(4)
}
private fun createLowestResults(): List<ResultDto> {
return listOf(
schnelllaufWithPoints(100),
ballwurfWithPoints(100),
weitsprungWithPoints(100)
)
}
private fun createMiddleResults(): List<ResultDto> {
return listOf(
schnelllaufWithPoints(200),
ballwurfWithPoints(200),
weitsprungWithPoints(200)
)
}
private fun createHighestResult(): List<ResultDto> {
return listOf(
schnelllaufWithPoints(300),
ballwurfWithPoints(300),
weitsprungWithPoints(300)
)
}
}
@Nested
internal inner class DisciplineRankingDto {
@Test
internal fun createRanking() {
val competitors = listOf(
competitorDtoOf(surname = THIRD_RANK, results = listOf(ballzielwurfWithPoints(100))),
competitorDtoOf(surname = FIRST_RANK, results = listOf(ballzielwurfWithPoints(300))),
competitorDtoOf(surname = SECOND_RANK, results = listOf(ballzielwurfWithPoints(200)))
)
val discipline = DisciplineDto(
name = BALLZIELWURF,
unit = UnitDto(name = "", factor = 0),
hasDistance = false,
hasTrials = false
)
val ranking = rankingManager.createDisciplineRanking(competitors, discipline)
val expected = listOf(FIRST_RANK, SECOND_RANK, THIRD_RANK)
assertThat(ranking.map { it.surname }).isEqualTo(expected)
}
@Test
internal fun createRankingWhenSamePoints() {
val firstRank = competitorDtoOf(
surname = FIRST_RANK,
results = listOf(ballzielwurfWithPoints(100))
)
val competitors = listOf(
competitorDtoOf(surname = "3. Rank", results = listOf(ballzielwurfWithPoints(50))),
firstRank.copy(),
firstRank.copy(),
firstRank.copy()
)
val discipline = DisciplineDto(
name = BALLZIELWURF,
unit = UnitDto(name = "", factor = 0),
hasDistance = false,
hasTrials = false
)
val ranking = rankingManager.createDisciplineRanking(competitors, discipline)
assertThat(ranking[0].rank).isEqualTo(1)
assertThat(ranking[1].rank).isEqualTo(1)
assertThat(ranking[2].rank).isEqualTo(1)
assertThat(ranking[3].rank).isEqualTo(4)
}
}
@Nested
internal inner class TotalRanking {
@Test
internal fun createRanking() {
val weitsprung = weitsprungWithPoints(100)
val seilspringen = seilspringenWithPoints(300)
val competitors = listOf(
competitorDtoOf(
surname = THIRD_RANK,
results = listOf(
weitsprung.copy(),
ballwurfWithPoints(100),
seilspringenWithPoints(100)
)
),
competitorDtoOf(
surname = FIRST_RANK,
results = listOf(
weitsprung.copy(),
ballwurfWithPoints(200),
seilspringen.copy()
)
),
competitorDtoOf(
surname = SECOND_RANK,
results = listOf(
weitsprung.copy(),
ballwurfWithPoints(150),
seilspringen.copy()
)
)
)
val ranking = rankingManager.createTotalRanking(competitors)
assertThat(ranking[0].total).isEqualTo(500)
assertThat(ranking[0].deletedResult).isEqualTo(100)
val expected = listOf(FIRST_RANK, SECOND_RANK, THIRD_RANK)
assertThat(ranking.map { it.surname }).isEqualTo(expected)
}
@Test
internal fun createRankingWhenSamePoints() {
val firstRankResults = listOf(
weitsprungWithPoints(100),
ballwurfWithPoints(200),
seilspringenWithPoints(300)
)
val firstRank = competitorDtoOf(surname = FIRST_RANK, results = firstRankResults)
val competitors = listOf(
competitorDtoOf(
surname = THIRD_RANK,
results = listOf(
weitsprungWithPoints(100),
ballwurfWithPoints(100),
seilspringenWithPoints(100)
)
),
firstRank.copy(),
firstRank.copy(),
firstRank.copy()
)
val ranking = rankingManager.createTotalRanking(competitors)
assertThat(ranking[0].rank).isEqualTo(1)
assertThat(ranking[1].rank).isEqualTo(1)
assertThat(ranking[2].rank).isEqualTo(1)
assertThat(ranking[3].rank).isEqualTo(4)
}
}
private fun competitorDtoOf(
id: Int = 1,
startNumber: Int = 1,
surname: String = "",
prename: String = "",
gender: GenderDto = GenderDto.MALE,
birthday: BirthdayDto = BirthdayDto.ofDate(LocalDate.MIN),
absent: Boolean = false,
address: String = "",
zip: String = "",
town: String = "",
group: String = "",
results: List<ResultDto> = listOf()
): CompetitorDto {
val resultMap = results
.map { it.discipline.name to it }
.toMap()
return CompetitorDto(
startnumber = startNumber,
results = resultMap,
id = id,
surname = surname,
prename = prename,
gender = gender,
birthday = birthday,
isAbsent = absent,
address = address,
town = TownDto(
zip = zip,
name = town
),
group = SimpleGroupDto(
name = group,
coach = ""
)
)
}
private fun schnelllaufWithPoints(points: Int): ResultDto {
return resultDtoOf(points = points, discipline = SCHNELLLAUF)
}
private fun ballwurfWithPoints(points: Int): ResultDto {
return resultDtoOf(points = points, discipline = BALLWURF)
}
private fun weitsprungWithPoints(points: Int): ResultDto {
return resultDtoOf(points = points, discipline = WEITSPRUNG)
}
private fun ballzielwurfWithPoints(points: Int): ResultDto {
return resultDtoOf(points = points, discipline = BALLZIELWURF)
}
private fun seilspringenWithPoints(points: Int): ResultDto {
return resultDtoOf(points = points, discipline = SEILSPRINGEN)
}
private fun resultDtoOf(
id: Int = 1,
value: Long = 0,
points: Int = 0,
discipline: String = ""
): ResultDto {
return ResultDto(
id = id,
value = value,
points = points,
distance = "",
discipline = DisciplineDto(
name = discipline,
unit = UnitDto(name = "", factor = 0),
hasTrials = false,
hasDistance = false
)
)
}
}
| gpl-3.0 | c2d1d336431a8467a6fd6408eb33bec4 | 33.383117 | 113 | 0.569877 | 4.548969 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/twitter/GetHomeTimelineTask.kt | 1 | 4863 | /*
* 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.task.twitter
import android.content.Context
import android.net.Uri
import org.mariotaku.ktextension.addTo
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.Mastodon
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.annotation.FilterScope
import de.vanita5.twittnuker.annotation.ReadPositionTag
import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.extractFanfouHashtags
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.fragment.HomeTimelineFragment
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.task.GetTimelineResult
import de.vanita5.twittnuker.provider.TwidereDataStore.Statuses
import de.vanita5.twittnuker.util.ErrorInfoStore
import de.vanita5.twittnuker.util.sync.TimelineSyncManager
class GetHomeTimelineTask(context: Context) : GetStatusesTask(context) {
override val contentUri: Uri = Statuses.CONTENT_URI
override val filterScopes: Int = FilterScope.HOME
override val errorInfoKey: String = ErrorInfoStore.KEY_HOME_TIMELINE
private val profileImageSize = context.getString(R.string.profile_image_size)
@Throws(MicroBlogException::class)
override fun getStatuses(account: AccountDetails, paging: Paging): GetTimelineResult<ParcelableStatus> {
when (account.type) {
AccountType.MASTODON -> {
val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java)
val timeline = mastodon.getHomeTimeline(paging)
return GetTimelineResult(account, timeline.map {
it.toParcelable(account)
}, timeline.flatMap { status ->
val mapResult = mutableListOf(status.account.toParcelable(account))
status.reblog?.account?.toParcelable(account)?.addTo(mapResult)
return@flatMap mapResult
}, timeline.flatMap { status ->
status.tags?.map { it.name }.orEmpty()
})
}
else -> {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
val timeline = microBlog.getHomeTimeline(paging)
val statuses = timeline.map {
it.toParcelable(account, profileImageSize)
}
val hashtags = if (account.type == AccountType.FANFOU) statuses.flatMap { status ->
return@flatMap status.extractFanfouHashtags()
} else timeline.flatMap { status ->
status.entities?.hashtags?.map { it.text }.orEmpty()
}
return GetTimelineResult(account, statuses, timeline.flatMap { status ->
val mapResult = mutableListOf(status.user.toParcelable(account,
profileImageSize = profileImageSize))
status.retweetedStatus?.user?.toParcelable(account,
profileImageSize = profileImageSize)?.addTo(mapResult)
status.quotedStatus?.user?.toParcelable(account,
profileImageSize = profileImageSize)?.addTo(mapResult)
return@flatMap mapResult
}, hashtags)
}
}
}
override fun syncFetchReadPosition(manager: TimelineSyncManager, accountKeys: Array<UserKey>) {
val tag = HomeTimelineFragment.getTimelineSyncTag(accountKeys)
manager.fetchSingle(ReadPositionTag.HOME_TIMELINE, tag)
}
} | gpl-3.0 | 9de537b78c68673a977596c3d808d707 | 46.223301 | 108 | 0.697101 | 4.791133 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/Tasks/dszipDownloadTask.kt | 1 | 4159 | package com.example.chadrick.datalabeling.Tasks
import android.os.AsyncTask
import android.util.Log
import com.example.chadrick.datalabeling.Models.DataSet
import com.example.chadrick.datalabeling.Models.ServerInfo
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
/**
* Created by chadrick on 17. 12. 4.
*/
class dszipDownloadTask(param_dataset: DataSet,
param_successCallback: () -> Unit,
param_errorCallback: () -> Unit,
param_unzipcompletecallback: () -> Unit,
param_progressUIupdate: (Int) -> Unit
) : AsyncTask<String, Integer, String>() {
val dataset: DataSet = param_dataset
val successCallback: () -> Unit = param_successCallback
val errorCallback: () -> Unit = param_errorCallback
val unzipcompleteCallback: () -> Unit = param_unzipcompletecallback
val progressUIupdate: (Int) -> Unit = param_progressUIupdate
lateinit var unziptask: unziptask
companion object {
val TAG: String = this.javaClass.simpleName
}
override fun doInBackground(vararg p0: String?): String {
val url: URL = URL(ServerInfo.instance.serveraddress + "/download/dszip" + "?id=" + dataset.id.toString())
val outputpath: File = File(dataset.zipfilestr)
if (!outputpath.exists()) {
outputpath.parentFile.mkdirs()
outputpath.createNewFile()
} else {
outputpath.delete()
outputpath.createNewFile()
}
val output = FileOutputStream(outputpath)
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
if (connection.responseCode != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "download attempt fail. " + connection.responseMessage)
return "Error : " + connection.responseMessage
}
val filelength = connection.contentLength
val input = connection.inputStream
var data = ByteArray(4096)
var total: Long = 0
var count: Int = 0
while (true) {
count = input.read(data)
if (count == -1) {
break
}
if (isCancelled) {
input.close()
return "cancelled"
}
total += count
// publishing the progress....
if (filelength > 0)
// only if total length is known
{
publishProgress((total * 100 / filelength).toInt() as Integer)
}
output.write(data, 0, count)
}
input?.close()
output?.close()
connection?.disconnect()
Log.d(TAG, "download finished")
return "success"
}
override fun onProgressUpdate(vararg values: Integer?) {
super.onProgressUpdate(*values)
// should update the progresscircle later on
Log.d(TAG, "updated progress=" + values[0])
progressUIupdate(values[0] as Int)
}
override fun onPostExecute(result: String?) {
// super.onPostExecute(result)
if (result!!.contains("Error")) {
//TODO: should create callback method for error case, and successfull download case
errorCallback()
} else {
successCallback()
}
//unzip the file
val zipfile = File(dataset.zipfilestr)
unziptask = unziptask(zipfile, unzipcompleteCallback)
unziptask.execute()
}
fun isFinished(): Boolean {
// just because this asynctask(DownloadTask) is finished(onPostExecute finished)
// doesn't mean that the actuall downloading and unzipping process is finished
// this is all finished when the unzipTask is finished for good.
try {
unziptask?.let {
return unziptask.status == AsyncTask.Status.FINISHED
}
} catch ( e: UninitializedPropertyAccessException ){
return false
}
return false
}
} | mit | cdecb1aa6e6bb98eaef48ff59d8f2562 | 28.503546 | 114 | 0.59774 | 4.731513 | false | false | false | false |
ivanTrogrlic/LeagueStats | app/src/main/java/com/ivantrogrlic/leaguestats/main/summoner/SummonerActivity.kt | 1 | 2271 | package com.ivantrogrlic.leaguestats.main.summoner
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v7.app.AppCompatActivity
import com.ivantrogrlic.leaguestats.LeagueStatsApplication
import com.ivantrogrlic.leaguestats.R
import com.ivantrogrlic.leaguestats.main.home.HomeFragment
import com.ivantrogrlic.leaguestats.model.Summoner
import com.ivantrogrlic.leaguestats.web.getProfileIconUrl
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.summoner_screen.*
import org.parceler.Parcels.unwrap
/**
* Created by ivanTrogrlic on 19/07/2017.
*/
class SummonerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.summoner_screen)
tabLayout.addTab(tabLayout.newTab().setText(R.string.ranks_title))
tabLayout.addTab(tabLayout.newTab().setText(R.string.matches_title))
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
val summoner = unwrap<Summoner>(intent.getParcelableExtra(HomeFragment.SUMMONER_KEY))
val adapter = SummonerScreenAdapter(supportFragmentManager, summoner)
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))
tabLayout.addOnTabSelectedListener(tabSelectedListener())
setupSummonerView(summoner)
}
override fun onDestroy() {
super.onDestroy()
tabLayout.clearOnTabSelectedListeners()
}
private fun tabSelectedListener() =
object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
}
private fun setupSummonerView(summoner: Summoner) {
Picasso.with(this).load(getProfileIconUrl(summoner.profileIconId)).into(summoner_icon)
summoner_name.text = summoner.name
summoner_level.text = resources.getString(R.string.summoner_level, summoner.summonerLevel)
}
}
| apache-2.0 | 417b58835d6cebdad90a166fef254258 | 34.484375 | 98 | 0.721708 | 4.144161 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/PhysicsSystem.kt | 1 | 2219 | package com.teamwizardry.librarianlib.glitter.test.systems
import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding
import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule
import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule
import net.minecraft.entity.Entity
import net.minecraft.util.Identifier
object PhysicsSystem : TestSystem(Identifier("liblib-glitter-test:physics")) {
override fun configure() {
val position = bind(3)
val previousPosition = bind(3)
val velocity = bind(3)
val color = bind(4)
updateModules.add(
BasicPhysicsUpdateModule(
position = position,
previousPosition = previousPosition,
velocity = velocity,
enableCollision = true,
gravity = ConstantBinding(0.02),
bounciness = ConstantBinding(0.8),
friction = ConstantBinding(0.02),
damping = ConstantBinding(0.01)
)
)
renderModules.add(
SpriteRenderModule.build(
Identifier("minecraft", "textures/item/clay_ball.png"),
position,
)
.previousPosition(previousPosition)
.color(color)
.size(0.2)
.build()
)
}
override fun spawn(player: Entity) {
val eyePos = player.getCameraPosVec(1f)
val look = player.rotationVector
val spawnDistance = 2
val spawnVelocity = 0.2
this.addParticle(
200,
// position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// previous position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// velocity
look.x * spawnVelocity,
look.y * spawnVelocity,
look.z * spawnVelocity,
// color
Math.random(),
Math.random(),
Math.random(),
1.0
)
}
} | lgpl-3.0 | c1d52f38b3c8d517cc4a80149b776f05 | 31.173913 | 78 | 0.561514 | 4.975336 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/CustomAttributes.kt | 2 | 1951 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.psi.ext.getQueryAttributes
import org.rust.lang.core.psi.ext.name
/**
* `#![register_attr()]` and `#![register_tool()]` crate-root attributes
*/
data class CustomAttributes(
val customAttrs: Set<String>,
val customTools: Set<String>,
) {
companion object {
val EMPTY: CustomAttributes = CustomAttributes(emptySet(), emptySet())
fun fromCrate(crate: Crate): CustomAttributes {
val project = crate.project
return CachedValuesManager.getManager(project).getCachedValue(crate) {
CachedValueProvider.Result.create(doGetFromCrate(crate), crate.rustStructureModificationTracker)
}
}
private fun doGetFromCrate(crate: Crate): CustomAttributes {
val rootMod = crate.rootMod ?: return EMPTY
return fromRootModule(rootMod, crate)
}
private fun fromRootModule(rootMod: RsFile, crate: Crate): CustomAttributes {
val attrs = mutableSetOf<String>()
val tools = mutableSetOf<String>()
for (meta in rootMod.getQueryAttributes(crate).metaItems) {
when (meta.name) {
"register_attr" -> collectMetaItemArgNames(meta, attrs::add)
"register_tool" -> collectMetaItemArgNames(meta, tools::add)
}
}
return CustomAttributes(attrs, tools)
}
private inline fun collectMetaItemArgNames(meta: RsMetaItem, collector: (String) -> Unit) {
for (attr in meta.metaItemArgs?.metaItemList.orEmpty()) {
attr.name?.let { collector(it) }
}
}
}
}
| mit | 5dbe884dd73f018879f6d11887d84e97 | 34.472727 | 112 | 0.636597 | 4.404063 | false | false | false | false |
brianwernick/RecyclerExt | library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/DelegatedHeaderAdapter.kt | 1 | 6656 | /*
* Copyright (C) 2017 - 2020 Brian Wernick
*
* 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.devbrackets.android.recyclerext.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.devbrackets.android.recyclerext.adapter.delegate.DelegateApi
import com.devbrackets.android.recyclerext.adapter.delegate.DelegateCore
import com.devbrackets.android.recyclerext.adapter.delegate.ViewHolderBinder
import com.devbrackets.android.recyclerext.adapter.header.HeaderApi
/**
* A [RecyclerView.Adapter] that handles delegating the creation and binding of
* [RecyclerView.ViewHolder]s with [ViewHolderBinder]s
* to allow for dynamic lists
*/
abstract class DelegatedHeaderAdapter<T> : HeaderAdapter<ViewHolder, ViewHolder>(), DelegateApi<T> {
protected var headerDelegateCore: DelegateCore<T, ViewHolder> = DelegateCore(HeaderDelegateApi(), this)
protected var childDelegateCore: DelegateCore<T, ViewHolder> = DelegateCore(ChildDelegateApi(), this)
override fun onCreateHeaderViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return headerDelegateCore.onCreateViewHolder(parent, viewType)
}
override fun onCreateChildViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return childDelegateCore.onCreateViewHolder(parent, viewType)
}
override fun onBindHeaderViewHolder(holder: ViewHolder, firstChildPosition: Int) {
headerDelegateCore.onBindViewHolder(holder, firstChildPosition)
}
override fun onBindChildViewHolder(holder: ViewHolder, childPosition: Int) {
childDelegateCore.onBindViewHolder(holder, childPosition)
}
override fun onViewRecycled(holder: ViewHolder) {
val delegateCore = if (core.isHeader(holder.adapterPosition)) headerDelegateCore else childDelegateCore
delegateCore.onViewRecycled(holder)
}
override fun onFailedToRecycleView(holder: ViewHolder): Boolean {
val delegateCore = if (core.isHeader(holder.adapterPosition)) headerDelegateCore else childDelegateCore
return delegateCore.onFailedToRecycleView(holder)
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
val delegateCore = if (core.isHeader(holder.adapterPosition)) headerDelegateCore else childDelegateCore
delegateCore.onViewAttachedToWindow(holder)
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
val delegateCore = if (core.isHeader(holder.adapterPosition)) headerDelegateCore else childDelegateCore
delegateCore.onViewDetachedFromWindow(holder)
}
/**
* Registers the `binder` to handle creating and binding the headers of type
* `viewType`. If a [ViewHolderBinder] has already been specified
* for the `viewType` then the value will be overwritten with `binder`
*
* @param viewType The type of view the [ViewHolderBinder] handles
* @param binder The [ViewHolderBinder] to handle creating and binding views
*/
fun <B: ViewHolderBinder<T, *>> registerHeaderViewHolderBinder(viewType: Int, binder: B) {
val headerViewType = viewType or HeaderApi.HEADER_VIEW_TYPE_MASK
headerDelegateCore.registerViewHolderBinder(headerViewType, binder as ViewHolderBinder<T, ViewHolder>)
}
/**
* Registers the `binder` to handle creating and binding the children of type
* `viewType`. If a [ViewHolderBinder] has already been specified
* for the `viewType` then the value will be overwritten with `binder`
*
* @param viewType The type of view the [ViewHolderBinder] handles
* @param binder The [ViewHolderBinder] to handle creating and binding views
*/
fun <B: ViewHolderBinder<T, *>> registerChildViewHolderBinder(viewType: Int, binder: B) {
val childViewType = viewType and HeaderApi.HEADER_VIEW_TYPE_MASK.inv()
childDelegateCore.registerViewHolderBinder(childViewType, binder as ViewHolderBinder<T, ViewHolder>)
}
/**
* Registers the `binder` to handle creating and binding the views that aren't
* handled by any binders registered with [.registerHeaderViewHolderBinder].
* If a [ViewHolderBinder] has already been specified as the default then the value will be
* overwritten with `binder`
*
* @param binder The [ViewHolderBinder] to handle creating and binding default views
*/
fun <B: ViewHolderBinder<T, *>> registerDefaultHeaderViewHolderBinder(binder: B?) {
headerDelegateCore.registerDefaultViewHolderBinder(binder as ViewHolderBinder<T, ViewHolder>)
}
/**
* Registers the `binder` to handle creating and binding the views that aren't
* handled by any binders registered with [.registerChildViewHolderBinder].
* If a [ViewHolderBinder] has already been specified as the default then the value will be
* overwritten with `binder`
*
* @param binder The [ViewHolderBinder] to handle creating and binding default views
*/
fun <B: ViewHolderBinder<T, *>> registerDefaultViewHolderBinder(binder: B?) {
childDelegateCore.registerDefaultViewHolderBinder(binder as ViewHolderBinder<T, ViewHolder>)
}
protected inner class HeaderDelegateApi : DelegateApi<T> {
override fun getItem(position: Int): T {
return [email protected](position)
}
override fun getItemViewType(adapterPosition: Int): Int {
if (adapterPosition < 0 || adapterPosition >= headerData.adapterPositionItemMap.size()) {
return 0
}
val item = headerData.adapterPositionItemMap[adapterPosition]
return if (item != null) {
item.itemViewType and HeaderApi.HEADER_VIEW_TYPE_MASK.inv()
} else 0
}
}
protected inner class ChildDelegateApi : DelegateApi<T> {
override fun getItem(position: Int): T {
return [email protected](position)
}
override fun getItemViewType(adapterPosition: Int): Int {
if (adapterPosition < 0 || adapterPosition >= headerData.adapterPositionItemMap.size()) {
return 0
}
val item = headerData.adapterPositionItemMap[adapterPosition]
return if (item != null) {
item.itemViewType and HeaderApi.HEADER_VIEW_TYPE_MASK.inv()
} else 0
}
}
} | apache-2.0 | 1258311bc47f0bbac120bc0ca918d77c | 42.227273 | 107 | 0.758113 | 4.635097 | false | false | false | false |
deva666/anko | anko/library/static/supportV4/src/Support.kt | 2 | 2008 | /*
* Copyright 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.
*/
@file:Suppress("unused")
package org.jetbrains.anko.support.v4
import android.support.v4.app.Fragment
import android.view.View
import org.jetbrains.anko.internals.AnkoInternals
import org.jetbrains.anko.*
import org.jetbrains.anko.internals.AnkoInternals.createAnkoContext
inline fun <reified T : View> Fragment.find(id: Int): T = view?.findViewById(id) as T
inline fun <reified T : View> Fragment.findOptional(id: Int): T? = view?.findViewById(id) as? T
fun Fragment.UI(init: AnkoContext<Fragment>.() -> Unit) = createAnkoContext(activity, init)
inline fun <T: Any> Fragment.configuration(
screenSize: ScreenSize? = null,
density: ClosedRange<Int>? = null,
language: String? = null,
orientation: Orientation? = null,
long: Boolean? = null,
fromSdk: Int? = null,
sdk: Int? = null,
uiMode: UiMode? = null,
nightMode: Boolean? = null,
rightToLeft: Boolean? = null,
smallestWidth: Int? = null,
init: () -> T
): T? {
val act = activity
return if (act != null) {
if (AnkoInternals.testConfiguration(act, screenSize, density, language, orientation, long,
fromSdk, sdk, uiMode, nightMode, rightToLeft, smallestWidth)) init() else null
}
else null
}
fun <T: Fragment> T.withArguments(vararg params: Pair<String, Any>): T {
setArguments(bundleOf(*params))
return this
}
| apache-2.0 | 59adcc9cef994a100a1848ee14573371 | 34.22807 | 98 | 0.687251 | 3.891473 | false | false | false | false |
odd-poet/kotlin-expect | src/main/kotlin/net/oddpoet/expect/Literalizer.kt | 1 | 3922 | package net.oddpoet.expect
import java.time.temporal.Temporal
import java.util.*
import kotlin.reflect.KClass
/**
* Object to literal.
*
* it will be used to print an object as part of assertion message.
*
* IMPORTANT:
* Literalizer is only used internally(by companion object).
* So user cannot register own custom literalizer.
*
* @author Yunsang Choi
*/
interface Literalizer<T> {
fun literal(value: T): String
companion object Registry {
private val list = mutableListOf<TypedLiteralizer<*>>()
init {
// register built-in literalizers.
// the order of those is important!
register(Int::class) { "$it" }
register(Long::class) { "${it}L" }
register(Double::class) { "$it" }
register(Float::class) { "${it}f" }
register(Char::class) { "'${unescape(it.toString())}'" }
register(String::class) { "\"${unescape(it)}\"" }
register(Regex::class) { "/$it/" }
register(Boolean::class) { "$it" }
register(Throwable::class) { "${it::class.qualifiedName}(message=${literal(it.message)})" }
register(Array<Any?>::class) {
it.map { literal(it) }.joinToStringAutoWrap(separator = ",", prefix = "[", postfix = "]")
}
register(ByteArray::class) {
it.joinToString(separator = " ", prefix = "[", postfix = "]") { byte ->
String.format("0x%02X", byte)
}
}
register(Collection::class) {
it.map { literal(it) }
.joinToStringAutoWrap(separator = ",", prefix = "${it::class.simpleName}(", postfix = ")")
}
register(Map::class) {
it.map { "${literal(it.key)}:${literal(it.value)}" }
.joinToStringAutoWrap(separator = ",", prefix = "${it::class.simpleName}{", postfix = "}")
}
register(ClosedRange::class) { "(${literal(it.start)}, ${literal(it.endInclusive)})" }
// time
register(Temporal::class) { "${it.javaClass.simpleName}<$it>" }
register(Date::class) { "Date<$it>" }
}
fun literal(value: Any?): String {
return value?.let {
list.firstOrNull { it.type.isInstance(value) }
?.literal(value)
?: it.toString() // no literalizer for given value.
} ?: "null"
}
fun <T : Any> register(type: KClass<T>, literalizer: Literalizer<T>) {
list.add(TypedLiteralizer(type, literalizer))
}
fun <T : Any> register(type: KClass<T>, block: (T) -> String) {
register(type, object : Literalizer<T> {
override fun literal(value: T): String = block(value)
})
}
private fun List<String>.joinToStringAutoWrap(separator: String, prefix: String, postfix: String): String {
return if (this.sumBy { it.length } > 80) {
joinToString(separator + "\n\t", prefix + "\n\t", "\n" + postfix)
} else {
joinToString(separator, prefix, postfix)
}
}
private fun unescape(string: String) =
string.replace("\\", "\\\\")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
internal class TypedLiteralizer<T : Any>(
val type: KClass<T>,
private val literalizer: Literalizer<T>
) : Literalizer<Any> {
override fun literal(value: Any): String {
if (!type.isInstance(value)) {
throw IllegalArgumentException("wrong type! : $value")
}
@Suppress("UNCHECKED_CAST")
return literalizer.literal(value as T)
}
}
}
}
| apache-2.0 | db1a30e3d91d2f3e08f74eca4bce2431 | 36.711538 | 115 | 0.511219 | 4.367483 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/util/delegates.kt | 1 | 1085 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import kotlin.reflect.KProperty
class NullableDelegate<T>(supplier: () -> T?) {
private var field: T? = null
private var func: (() -> T?)? = supplier
private val lock = Lock()
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
var f = field
if (f != null) {
return f
}
synchronized(lock) {
f = field
if (f != null) {
return f
}
f = func!!()
// Don't hold on to the supplier after it's used and returned a value
if (f != null) {
field = f
func = null
}
}
return f
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
this.field = value
}
private class Lock
}
fun <T> nullable(supplier: () -> T?): NullableDelegate<T> = NullableDelegate(supplier)
| mit | 90012520298732dbc46f6b08917f4866 | 19.865385 | 86 | 0.517051 | 4.189189 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/base/DrawerActivity.kt | 1 | 2960 | package me.proxer.app.base
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import com.google.android.material.appbar.AppBarLayout
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import kotterknife.bindView
import me.proxer.app.MainActivity
import me.proxer.app.R
import me.proxer.app.auth.LoginDialog
import me.proxer.app.auth.LogoutDialog
import me.proxer.app.notification.NotificationActivity
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.profile.settings.ProfileSettingsActivity
import me.proxer.app.util.wrapper.MaterialDrawerWrapper
import me.proxer.app.util.wrapper.MaterialDrawerWrapper.AccountItem
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
@Suppress("UnnecessaryAbstractClass")
abstract class DrawerActivity : BaseActivity() {
protected open val contentView
get() = R.layout.activity_default
protected var drawer by Delegates.notNull<MaterialDrawerWrapper>()
private set
protected open val isRootActivity = false
protected open val isMainActivity = false
open val toolbar: Toolbar by bindView(R.id.toolbar)
open val appbar: AppBarLayout by bindView(R.id.appbar)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(contentView)
setSupportActionBar(toolbar)
drawer = MaterialDrawerWrapper(this, toolbar, savedInstanceState, isRootActivity, isMainActivity).also {
it.itemClickSubject
.autoDisposable(this.scope())
.subscribe { item -> handleDrawerItemClick(item) }
it.accountClickSubject
.autoDisposable(this.scope())
.subscribe { item -> handleAccountItemClick(item) }
}
storageHelper.isLoggedInObservable
.autoDisposable(this.scope())
.subscribe { drawer.refreshHeader(this) }
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
drawer.saveInstanceState(outState)
}
override fun onBackPressed() {
if (!drawer.onBackPressed()) {
super.onBackPressed()
}
}
protected open fun handleDrawerItemClick(item: MaterialDrawerWrapper.DrawerItem) {
MainActivity.navigateToSection(this, item)
}
protected open fun handleAccountItemClick(item: AccountItem) = when (item) {
AccountItem.GUEST, AccountItem.LOGIN -> LoginDialog.show(this)
AccountItem.LOGOUT -> LogoutDialog.show(this)
AccountItem.USER -> showProfilePage()
AccountItem.NOTIFICATIONS -> NotificationActivity.navigateTo(this)
AccountItem.PROFILE_SETTINGS -> ProfileSettingsActivity.navigateTo(this)
}
private fun showProfilePage() = storageHelper.user?.let { (_, id, name, image) ->
ProfileActivity.navigateTo(this, id, name, image, null)
}
}
| gpl-3.0 | e041cb320125d4b30e5b327d90385878 | 33.418605 | 112 | 0.72027 | 4.728435 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/blogs/articles/list/BlogsArticlesPresenter.kt | 2 | 2751 | package ru.fantlab.android.ui.modules.blogs.articles.list
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.BlogArticles
import ru.fantlab.android.data.dao.response.BlogArticlesResponse
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getBlogArticlesPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class BlogsArticlesPresenter : BasePresenter<BlogsArticlesMvp.View>(),
BlogsArticlesMvp.Presenter {
private var blogId: Int = -1
private var page: Int = 1
private var lastPage: Int = Integer.MAX_VALUE
private var previousTotal: Int = 0
override fun onCallApi(page: Int, parameter: Int?): Boolean {
if (page == 1) {
lastPage = Integer.MAX_VALUE
sendToView { it.getLoadMore().reset() }
}
setCurrentPage(page)
if (page > lastPage || lastPage == 0) {
sendToView { it.hideProgress() }
return false
}
blogId = parameter ?: -1
getArticles(false)
return true
}
override fun getArticles(force: Boolean) {
makeRestCall(
getBlogsInternal(force).toObservable(),
Consumer { (articles, lastPage) -> sendToView {
this.lastPage = lastPage
it.getLoadMore().setTotalPagesCount(lastPage)
it.onNotifyAdapter(articles, page)
} }
)
}
private fun getBlogsInternal(force: Boolean) =
getBlogsFromServer()
.onErrorResumeNext { throwable ->
if (!force) {
getBlogsFromDb()
} else {
throw throwable
}
}
private fun getBlogsFromServer(): Single<Pair<ArrayList<BlogArticles.Article>, Int>> =
DataManager.getBlogArticles(blogId, page, 25)
.map { getArticles(it) }
private fun getBlogsFromDb(): Single<Pair<ArrayList<BlogArticles.Article>, Int>> =
DbProvider.mainDatabase
.responseDao()
.get(getBlogArticlesPath(blogId, page, 25))
.map { it.response }
.map { BlogArticlesResponse.Deserializer().deserialize(it) }
.map { this.getArticles(it) }
private fun getArticles(response: BlogArticlesResponse): Pair<ArrayList<BlogArticles.Article>, Int> = response.articles.items to response.articles.last
override fun getCurrentPage(): Int = page
override fun getPreviousTotal(): Int = previousTotal
override fun setCurrentPage(page: Int) {
this.page = page
}
override fun setPreviousTotal(previousTotal: Int) {
this.previousTotal = previousTotal
}
override fun onItemClick(position: Int, v: View?, item: BlogArticles.Article) {
sendToView { it.onItemClicked(item) }
}
override fun onItemLongClick(position: Int, v: View?, item: BlogArticles.Article) {
sendToView { it.onItemLongClicked(position, v, item) }
}
} | gpl-3.0 | 031651eabc9e88a30fe8776d7ad73a99 | 29.577778 | 152 | 0.730643 | 3.619737 | false | false | false | false |
hpedrorodrigues/GZMD | app/src/main/kotlin/com/hpedrorodrigues/gzmd/dagger/GizmodoApplication.kt | 1 | 1986 | /*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.dagger
import android.app.Application
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.core.CrashlyticsCore
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.Tracker
import com.hpedrorodrigues.gzmd.BuildConfig
import com.hpedrorodrigues.gzmd.R
import io.fabric.sdk.android.Fabric
class GizmodoApplication : Application() {
var tracker: Tracker? = null
private val isDebug = BuildConfig.DEBUG
companion object {
@JvmStatic lateinit var graph: GizmodoComponent
}
override fun onCreate() {
super.onCreate()
val core = CrashlyticsCore.Builder().disabled(isDebug).build()
Fabric.with(this, Crashlytics.Builder().core(core).build())
graph = DaggerGizmodoComponent.builder().gizmodoModule(GizmodoModule(this)).build()
graph.inject(this)
}
fun tracker(): Tracker {
synchronized(this) {
if (tracker == null) {
val analytics = GoogleAnalytics.getInstance(this)
analytics.appOptOut = isDebug
tracker = analytics.newTracker(R.xml.global_tracker)
tracker?.enableAdvertisingIdCollection(true)
}
return tracker!!
}
}
fun component(): GizmodoComponent {
return graph
}
} | apache-2.0 | 709a598fd83505015f95ba0ae17dbcd4 | 28.220588 | 91 | 0.694361 | 4.452915 | false | false | false | false |
REDNBLACK/advent-of-code2016 | src/main/kotlin/day09/Advent9.kt | 1 | 4141 | package day09
import parseInput
/**
--- Day 9: Explosives in Cyberspace ---
Wandering around a secure area, you come across a datalink port to a new part of the network.
After briefly scanning it for interesting files, you find one file in particular that catches your attention.
It's compressed with an experimental format, but fortunately, the documentation for the format is nearby.
The format compresses a sequence of characters. Whitespace is ignored. To indicate that some sequence should be repeated,
a marker is added to the file, like (10x2).
To decompress this marker, take the subsequent 10 characters and repeat them 2 times.
Then, continue reading the file after the repeated data. The marker itself is not included in the decompressed output.
If parentheses or other characters appear within the data referenced by a marker,
that's okay - treat it like normal data, not a marker, and then resume looking for markers after the decompressed section.
For example:
ADVENT contains no markers and decompresses to itself with no changes, resulting in a decompressed length of 6.
A(1x5)BC repeats only the B a total of 5 times, becoming ABBBBBC for a decompressed length of 7.
(3x3)XYZ becomes XYZXYZXYZ for a decompressed length of 9.
A(2x2)BCD(2x2)EFG doubles the BC and EF, becoming ABCBCDEFEFG for a decompressed length of 11.
(6x1)(1x3)A simply becomes (1x3)A - the (1x3) looks like a marker, but because it's within a data section of another marker, it is not treated any differently from the A that comes after it. It has a decompressed length of 6.
X(8x2)(3x3)ABCY becomes X(3x3)ABC(3x3)ABCY (for a decompressed length of 18), because the decompressed data from the (8x2) marker (the (3x3)ABC) is skipped and not processed further.
What is the decompressed length of the file (your puzzle input)? Don't count whitespace.
--- Part Two ---
Apparently, the file actually uses version two of the format.
In version two, the only difference is that markers within decompressed data are decompressed. This, the documentation explains, provides much more substantial compression capabilities, allowing many-gigabyte files to be stored in only a few kilobytes.
For example:
(3x3)XYZ still becomes XYZXYZXYZ, as the decompressed section contains no markers.
X(8x2)(3x3)ABCY becomes XABCABCABCABCABCABCY, because the decompressed data from the (8x2) marker is then further decompressed, thus triggering the (3x3) marker twice for a total of six ABC sequences.
(27x12)(20x12)(13x14)(7x10)(1x12)A decompresses into a string of A repeated 241920 times.
(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN becomes 445 characters long.
Unfortunately, the computer you brought probably doesn't have enough memory to actually decompress the file; you'll have to come up with another way to get its decompressed length.
What is the decompressed length of the file using this improved format?
*/
fun main(args: Array<String>) {
println(calculateLength("A(1x5)BC") == 7L)
println(calculateLength("(3x3)XYZ") == 9L)
println(calculateLength("A(2x2)BCD(2x2)EFG") == 11L)
println(calculateLength("(6x1)(1x3)A") == 6L)
println(calculateLength("X(8x2)(3x3)ABCY") == 18L)
val input = parseInput("day9-input.txt").trim()
println(calculateLength(input))
println(calculateLength(input, true))
}
data class Operation(val pos: Int, val i: Int, val offset: Int, val factor: Int)
fun calculateLength(s: String, part2: Boolean = false): Long {
val o = parseOperation(s) ?: return s.length.toLong()
val calculated = if (part2) calculateLength(s.substring(o.i, o.i + o.offset), part2) else o.offset.toLong()
return s.substring(1..o.pos).length.toLong() +
calculated * o.factor +
calculateLength(s.substring(o.i + o.offset, s.length), part2)
}
private fun parseOperation(input: String): Operation? {
val pattern = Regex("""\((\d+)x(\d+)\)""")
val (x, offset, multiplier) = pattern.find(input)?.groupValues ?: return null
val pos = input.indexOf(x)
return Operation(pos = pos, i = pos + x.length, offset = offset.toInt(), factor = multiplier.toInt())
}
| mit | 8b959751dc1f4031ac23b6f220587bc2 | 52.089744 | 252 | 0.749336 | 3.616594 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/admin/ShardInfoCommand.kt | 1 | 1343 | package xyz.gnarbot.gnar.commands.admin
import com.google.common.collect.Lists
import xyz.gnarbot.gnar.commands.*
import java.util.*
@Command(
aliases = ["shards", "shard", "shardinfo"],
description = "Get shard information."
)
@BotInfo(
id = 48,
admin = true,
category = Category.NONE
)
class ShardInfoCommand : CommandExecutor() {
override fun execute(context: Context, label: String, args: Array<String>) {
context.send().text("```prolog\n ID | STATUS | PING | GUILDS | USERS | REQUESTS | VC\n```").queue()
Lists.partition(context.bot.shardManager.shards, 20).forEach {
val joiner = StringJoiner("\n", "```prolog\n", "```")
it.forEach {
joiner.add(
"%3d | %9.9s | %7.7s | %6d | %6d | ---- WIP | %3d".format(
it.shardInfo.shardId,
it.status,
"${it.gatewayPing}ms",
it.guildCache.size(),
it.userCache.size(),
context.bot.players.registry.values.count { m -> m.guild.jda == it }
)
)
}
context.send().text(joiner.toString()).queue()
}
}
} | mit | 9e90fde04b29005b3977616d800a4b27 | 32.6 | 115 | 0.478779 | 4.170807 | false | false | false | false |
mike-neck/kuickcheck | core/src/main/kotlin/org/mikeneck/kuickcheck/prediction/SingleParam.kt | 1 | 2610 | /*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.prediction
import org.mikeneck.kuickcheck.Checker
import org.mikeneck.kuickcheck.Generator
import org.mikeneck.kuickcheck.KuickCheck
interface SingleParameterPrediction<T> {
fun satisfy(predicate: (T) -> Boolean): Checker<T>
fun whenever(condition: (T) -> Boolean): SingleParameterPrediction<T>
}
internal fun <T> singleParameterPrediction(generator: Generator<T>): SingleParameterPrediction<T> =
SingleParamPrediction(generator)
class SingleParamPrediction<T>
(val generator: Generator<T>, val repeatTime: Int = KuickCheck.DEFAULT_REPEAT)
: SingleParameterPrediction<T> {
override fun satisfy(predicate: (T) -> Boolean): Checker<T> {
return object: Checker<T> {
override val repeat: Int = repeatTime
override fun testData(): T = generator.invoke()
override fun consume(p: T): Boolean = predicate.invoke(p)
}
}
override fun whenever(condition: (T) -> Boolean): SingleParameterPrediction<T> =
SingleFilteredParamPrediction(generator, condition, repeatTime)
}
class SingleFilteredParamPrediction<T>
(val generator: Generator<T>, val condition: (T) -> Boolean, val repeatTime: Int = KuickCheck.DEFAULT_REPEAT)
: SingleParameterPrediction<T> {
override fun satisfy(predicate: (T) -> Boolean): Checker<T> {
return object: Checker<T> {
override fun testData(): T {
while (true) {
val t: T = generator.invoke()
if (condition.invoke(t)) return t
}
}
override fun consume(p: T): Boolean = predicate.invoke(p)
override val repeat: Int = repeatTime
}
}
override fun whenever(condition: (T) -> Boolean): SingleParameterPrediction<T> {
val con: (T) -> Boolean = {t ->
this.condition.invoke(t) && condition.invoke(t)
}
return SingleFilteredParamPrediction(this.generator, con, this.repeatTime)
}
}
| apache-2.0 | 76d3d8fb9be40b46cd9a9f2cd12dcf04 | 36.826087 | 109 | 0.67318 | 4.182692 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/graphs/NodeWrapper.kt | 1 | 700 | package org.jetbrains.kotlinx.jupyter.api.graphs
import org.jetbrains.kotlinx.jupyter.api.graphs.labels.TextLabel
/**
* Use [NodeWrapper] if [T] cannot implement [GraphNode] itself for some reason
*/
abstract class NodeWrapper<T>(val value: T) : GraphNode<T> {
override val label: Label get() = TextLabel(value.toString())
override val inNodes get() = listOf<GraphNode<T>>()
override val outNodes get() = listOf<GraphNode<T>>()
override val biNodes get() = listOf<GraphNode<T>>()
override fun equals(other: Any?): Boolean {
return other is NodeWrapper<*> && other.value == this.value
}
override fun hashCode(): Int {
return value.hashCode()
}
}
| apache-2.0 | ac8eeb45f878e9143a8c5c9d059f1d65 | 30.818182 | 79 | 0.68 | 3.932584 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/assets/federatedcompute/SmartSelectAnalyticsPolicy_FederatedCompute.kt | 1 | 2423 | /*
* Copyright 2021 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
*
* 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.libraries.pcc.policies.federatedcompute
/** SmartSelect policy for federated analytics. */
val SmartSelectAnalyticsPolicy_FederatedCompute =
flavoredPolicies(
name = "SmartSelectAnalyticsPolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To make improvements to the platform Smart Select service - for example, understand selection usage.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics.
"""
.trimIndent()
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 2000, minSecAggRoundSize = 500) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(
PERSISTED_SMART_SELECT_SELECTION_EVENT_ENTITY_GENERATED_DTD,
maxAge = Duration.ofDays(14)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"entityType" { rawUsage(UsageType.ANY) }
"leftContext" { rawUsage(UsageType.ANY) }
"entityText" { rawUsage(UsageType.ANY) }
"rightContext" { rawUsage(UsageType.ANY) }
"numOfEntityTokens" { rawUsage(UsageType.ANY) }
"userAction" { rawUsage(UsageType.ANY) }
"widgetType" { rawUsage(UsageType.ANY) }
"originApp" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"destinationApp" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
}
}
| apache-2.0 | f0a36998720a06928809b54a0bb019ba | 35.164179 | 106 | 0.713991 | 4.258348 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt | 3 | 6046 | package info.nightscout.androidaps.plugins.pump.insight.utils
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert
import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertCategory
import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertType
import java.text.DecimalFormat
fun getAlertCode(alertType: AlertType) = MainApp.gs(when (alertType) {
AlertType.REMINDER_01 -> R.string.alert_r1_code
AlertType.REMINDER_02 -> R.string.alert_r2_code
AlertType.REMINDER_03 -> R.string.alert_r3_code
AlertType.REMINDER_04 -> R.string.alert_r4_code
AlertType.REMINDER_07 -> R.string.alert_r7_code
AlertType.WARNING_31 -> R.string.alert_w31_code
AlertType.WARNING_32 -> R.string.alert_w32_code
AlertType.WARNING_33 -> R.string.alert_w33_code
AlertType.WARNING_34 -> R.string.alert_w34_code
AlertType.WARNING_36 -> R.string.alert_w36_code
AlertType.WARNING_38 -> R.string.alert_w38_code
AlertType.WARNING_39 -> R.string.alert_w39_code
AlertType.MAINTENANCE_20 -> R.string.alert_m20_code
AlertType.MAINTENANCE_21 -> R.string.alert_m21_code
AlertType.MAINTENANCE_22 -> R.string.alert_m22_code
AlertType.MAINTENANCE_23 -> R.string.alert_m23_code
AlertType.MAINTENANCE_24 -> R.string.alert_m24_code
AlertType.MAINTENANCE_25 -> R.string.alert_m25_code
AlertType.MAINTENANCE_26 -> R.string.alert_m26_code
AlertType.MAINTENANCE_27 -> R.string.alert_m27_code
AlertType.MAINTENANCE_28 -> R.string.alert_m28_code
AlertType.MAINTENANCE_29 -> R.string.alert_m29_code
AlertType.MAINTENANCE_30 -> R.string.alert_m30_code
AlertType.ERROR_6 -> R.string.alert_e6_code
AlertType.ERROR_10 -> R.string.alert_e10_code
AlertType.ERROR_13 -> R.string.alert_e13_code
})
fun getAlertTitle(alertType: AlertType) = MainApp.gs(when (alertType) {
AlertType.REMINDER_01 -> R.string.alert_r1_title
AlertType.REMINDER_02 -> R.string.alert_r2_title
AlertType.REMINDER_03 -> R.string.alert_r3_title
AlertType.REMINDER_04 -> R.string.alert_r4_title
AlertType.REMINDER_07 -> R.string.alert_r7_title
AlertType.WARNING_31 -> R.string.alert_w31_title
AlertType.WARNING_32 -> R.string.alert_w32_title
AlertType.WARNING_33 -> R.string.alert_w33_title
AlertType.WARNING_34 -> R.string.alert_w34_title
AlertType.WARNING_36 -> R.string.alert_w36_title
AlertType.WARNING_38 -> R.string.alert_w38_title
AlertType.WARNING_39 -> R.string.alert_w39_title
AlertType.MAINTENANCE_20 -> R.string.alert_m20_title
AlertType.MAINTENANCE_21 -> R.string.alert_m21_title
AlertType.MAINTENANCE_22 -> R.string.alert_m22_title
AlertType.MAINTENANCE_23 -> R.string.alert_m23_title
AlertType.MAINTENANCE_24 -> R.string.alert_m24_title
AlertType.MAINTENANCE_25 -> R.string.alert_m25_title
AlertType.MAINTENANCE_26 -> R.string.alert_m26_title
AlertType.MAINTENANCE_27 -> R.string.alert_m27_title
AlertType.MAINTENANCE_28 -> R.string.alert_m28_title
AlertType.MAINTENANCE_29 -> R.string.alert_m29_title
AlertType.MAINTENANCE_30 -> R.string.alert_m30_title
AlertType.ERROR_6 -> R.string.alert_e6_title
AlertType.ERROR_10 -> R.string.alert_e10_title
AlertType.ERROR_13 -> R.string.alert_e13_title
})
fun getAlertDescription(alert: Alert): String? {
val decimalFormat = DecimalFormat("##0.00")
val hours = alert.tbrDuration / 60
val minutes = alert.tbrDuration - hours * 60
return when (alert.alertType!!) {
AlertType.REMINDER_01 -> null
AlertType.REMINDER_02 -> null
AlertType.REMINDER_03 -> null
AlertType.REMINDER_04 -> null
AlertType.REMINDER_07 -> MainApp.gs(R.string.alert_r7_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong()))
AlertType.WARNING_31 -> MainApp.gs(R.string.alert_w31_description, decimalFormat.format(alert.cartridgeAmount))
AlertType.WARNING_32 -> MainApp.gs(R.string.alert_w32_description)
AlertType.WARNING_33 -> MainApp.gs(R.string.alert_w33_description)
AlertType.WARNING_34 -> MainApp.gs(R.string.alert_w34_description)
AlertType.WARNING_36 -> MainApp.gs(R.string.alert_w36_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong()))
AlertType.WARNING_38 -> MainApp.gs(R.string.alert_w38_description, decimalFormat.format(alert.programmedBolusAmount), decimalFormat.format(alert.deliveredBolusAmount))
AlertType.WARNING_39 -> null
AlertType.MAINTENANCE_20 -> MainApp.gs(R.string.alert_m20_description)
AlertType.MAINTENANCE_21 -> MainApp.gs(R.string.alert_m21_description)
AlertType.MAINTENANCE_22 -> MainApp.gs(R.string.alert_m22_description)
AlertType.MAINTENANCE_23 -> MainApp.gs(R.string.alert_m23_description)
AlertType.MAINTENANCE_24 -> MainApp.gs(R.string.alert_m24_description)
AlertType.MAINTENANCE_25 -> MainApp.gs(R.string.alert_m25_description)
AlertType.MAINTENANCE_26 -> MainApp.gs(R.string.alert_m26_description)
AlertType.MAINTENANCE_27 -> MainApp.gs(R.string.alert_m27_description)
AlertType.MAINTENANCE_28 -> MainApp.gs(R.string.alert_m28_description)
AlertType.MAINTENANCE_29 -> MainApp.gs(R.string.alert_m29_description)
AlertType.MAINTENANCE_30 -> MainApp.gs(R.string.alert_m30_description)
AlertType.ERROR_6 -> MainApp.gs(R.string.alert_e6_description)
AlertType.ERROR_10 -> MainApp.gs(R.string.alert_e10_description)
AlertType.ERROR_13 -> MainApp.gs(R.string.alert_e13_description)
}
}
fun getAlertIcon(alertCategory: AlertCategory) = when (alertCategory) {
AlertCategory.ERROR -> R.drawable.ic_error
AlertCategory.MAINTENANCE -> R.drawable.ic_maintenance
AlertCategory.WARNING -> R.drawable.ic_warning
AlertCategory.REMINDER -> R.drawable.ic_reminder
} | agpl-3.0 | 306973dc546f1bcc4e6af56a2913b47f | 55.514019 | 188 | 0.728415 | 3.334804 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/data/ApiClient.kt | 1 | 9678 | package com.habitrpg.wearos.habitica.data
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import com.habitrpg.common.habitica.BuildConfig
import com.habitrpg.common.habitica.api.HostConfig
import com.habitrpg.common.habitica.api.Server
import com.habitrpg.common.habitica.models.auth.UserAuth
import com.habitrpg.common.habitica.models.auth.UserAuthSocial
import com.habitrpg.shared.habitica.models.responses.ErrorResponse
import com.habitrpg.wearos.habitica.managers.AppStateManager
import com.habitrpg.wearos.habitica.models.NetworkResult
import com.habitrpg.wearos.habitica.models.WearableHabitResponse
import com.habitrpg.wearos.habitica.models.tasks.Task
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter
import retrofit2.Response
import retrofit2.Retrofit
import java.io.File
import java.util.GregorianCalendar
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ApiClient @Inject constructor(
private val converter: Converter.Factory,
private val hostConfig: HostConfig,
private val appStateManager: AppStateManager,
private val context: Context
) {
val userID: String
get() = hostConfig.userID
private lateinit var retrofitAdapter: Retrofit
// I think we don't need the ApiClientImpl anymore we could just use ApiService
private lateinit var apiService: ApiService
init {
buildRetrofit()
}
private fun hasNetwork(context: Context): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
return when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_USB) -> true
else -> false
}
}
private fun buildRetrofit() {
val logging = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY
}
val userAgent = System.getProperty("http.agent")
val calendar = GregorianCalendar()
val timeZone = calendar.timeZone
val timezoneOffset = -TimeUnit.MINUTES.convert(
timeZone.getOffset(calendar.timeInMillis).toLong(),
TimeUnit.MILLISECONDS
)
val cacheSize = (5 * 1024 * 1024).toLong()
val cache = Cache(File(context.cacheDir, "http_cache"), cacheSize)
val client = OkHttpClient.Builder()
.cache(cache)
.addInterceptor(logging)
.addInterceptor { chain ->
val request = chain.request()
if (request.header("Cache-Control")?.isNotBlank() == true) {
return@addInterceptor chain.proceed(request)
}
var cacheControl = CacheControl.Builder()
cacheControl = if (request.method == "GET") {
if (hasNetwork(context)) {
cacheControl.maxAge(1, TimeUnit.MINUTES)
} else {
appStateManager.isAppConnected.value = false
cacheControl.maxAge(1, TimeUnit.DAYS)
}
} else {
if (!hasNetwork(context)) {
appStateManager.isAppConnected.value = false
}
cacheControl.noCache()
.noStore()
}
val response = chain.proceed(request.newBuilder().header(
"Cache-Control",
cacheControl.build().toString()
).build())
val responseBuilder = response.newBuilder()
responseBuilder.header("was-cached", (response.networkResponse == null).toString())
if (request.method == "GET") {
val userID = response.request.header("x-api-user") ?: request.header("x-api-user")
if (response.code == 504 || (userID != null && userID != hostConfig.userID)) {
// Cache miss. Network might be down, but retry call without cache to be sure.
response.close()
chain.proceed(request.newBuilder()
.header("Cache-Control", "no-cache")
.build())
} else {
responseBuilder
.header("Cache-Control", request.header("Cache-Control") ?: "")
.build()
}
} else {
responseBuilder.build()
}
}
.addNetworkInterceptor { chain ->
val original = chain.request()
var builder: Request.Builder = original.newBuilder()
if (this.hostConfig.hasAuthentication()) {
builder = builder
.header("x-api-key", this.hostConfig.apiKey)
.header("x-api-user", this.hostConfig.userID)
}
builder = builder.header("x-client", "habitica-android")
.header("x-user-timezoneOffset", timezoneOffset.toString())
if (userAgent != null) {
builder = builder.header("user-agent", userAgent)
}
if (BuildConfig.STAGING_KEY.isNotEmpty()) {
builder = builder.header("Authorization", "Basic " + BuildConfig.STAGING_KEY)
}
val request = builder.method(original.method, original.body)
.removeHeader("Pragma")
.build()
chain.proceed(request)
}
.readTimeout(2400, TimeUnit.SECONDS)
.build()
val server = Server(this.hostConfig.address)
retrofitAdapter = Retrofit.Builder()
.client(client)
.baseUrl(server.toString())
.addConverterFactory(converter)
.build()
this.apiService = retrofitAdapter.create(ApiService::class.java)
}
fun updateAuthenticationCredentials(userID: String?, apiToken: String?) {
this.hostConfig.userID = userID ?: ""
this.hostConfig.apiKey = apiToken ?: ""
}
private val adapter: JsonAdapter<ErrorResponse>? = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory()).build().adapter(ErrorResponse::class.java).lenient()
private suspend fun <T: Any> process(call: suspend () -> Response<WearableHabitResponse<T>>): NetworkResult<T> {
val response: Response<WearableHabitResponse<T>> = call.invoke()
val wasCached = response.headers()["was-cached"] == "true"
return if (!response.isSuccessful) {
appStateManager.isAppConnected.value = false
if (response.code() == 504) {
NetworkResult.Error(Exception(), !wasCached)
} else {
response.errorBody()?.string()?.let {
val errorResponse = adapter?.fromJson(it)
throw(java.lang.Exception(errorResponse?.message))
}
throw(java.lang.Exception(response.message()))
}
} else {
val body = response.body()
if (body?.data != null) {
appStateManager.isAppConnected.value = true
NetworkResult.Success(body.data!!, !wasCached)
} else {
NetworkResult.Error(Exception("response.body() can't be null"), !wasCached)
}
}
}
suspend fun getUser(forced: Boolean = false) = if (forced) {
process { apiService.getUserForced() }
} else {
process { apiService.getUser() }
}
suspend fun updateUser(data: Map<String, Any>) = process { apiService.updateUser(data) }
suspend fun sleep() = process { apiService.sleep() }
suspend fun revive() = process { apiService.revive() }
suspend fun loginLocal(auth: UserAuth) = process { apiService.connectLocal(auth) }
suspend fun loginSocial(auth: UserAuthSocial) = process { apiService.connectSocial(auth) }
suspend fun addPushDevice(data: Map<String, String>) = process { apiService.addPushDevice(data) }
suspend fun removePushDevice(id: String) = process { apiService.removePushDevice(id) }
suspend fun runCron() = process { apiService.runCron() }
suspend fun getTasks(forced: Boolean = false) = if (forced) {
process { apiService.getTasksForced() }
} else {
process { apiService.getTasks() }
}
suspend fun scoreTask(id: String, direction: String) =
process { apiService.scoreTask(id, direction) }
suspend fun createTask(task: Task) = process { apiService.createTask(task) }
fun hasAuthentication() = hostConfig.hasAuthentication()
} | gpl-3.0 | 677149daafda6201178b4eb4811a55f1 | 41.451754 | 116 | 0.60653 | 5.053786 | false | true | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/upload/UploadService.kt | 1 | 4057 | package de.westnordost.streetcomplete.data.upload
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import de.westnordost.osmapi.common.errors.OsmAuthorizationException
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.streetcomplete.ApplicationConstants
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.data.download.tiles.DownloadedTilesDao
import de.westnordost.streetcomplete.data.user.UserController
import de.westnordost.streetcomplete.util.enclosingTile
/** Collects and uploads all changes the user has done: notes he left, comments he left on existing
* notes and quests he answered */
class UploadService : IntentService(TAG) {
@Inject internal lateinit var uploaders: List<Uploader>
@Inject internal lateinit var versionIsBannedChecker: VersionIsBannedChecker
@Inject internal lateinit var userController: UserController
@Inject internal lateinit var downloadedTilesDB: DownloadedTilesDao
private val binder = Interface()
// listeners
private val uploadedChangeRelay = object : OnUploadedChangeListener {
override fun onUploaded(questType: String, at: LatLon) {
progressListener?.onProgress(true)
}
override fun onDiscarded(questType: String, at: LatLon) {
invalidateArea(at)
progressListener?.onProgress(false)
}
}
private var isUploading: Boolean = false
private var progressListener: UploadProgressListener? = null
private val cancelState = AtomicBoolean(false)
private val bannedInfo: BannedInfo by lazy { versionIsBannedChecker.get() }
init {
Injector.applicationComponent.inject(this)
}
override fun onCreate() {
super.onCreate()
cancelState.set(false)
}
override fun onBind(intent: Intent): IBinder {
return binder
}
override fun onDestroy() {
cancelState.set(true)
super.onDestroy()
}
override fun onHandleIntent(intent: Intent?) {
if (cancelState.get()) return
isUploading = true
progressListener?.onStarted()
try {
val banned = bannedInfo
if (banned is IsBanned) {
throw VersionBannedException(banned.reason)
}
// let's fail early in case of no authorization
if (!userController.isLoggedIn) {
throw OsmAuthorizationException(401, "Unauthorized", "User is not authorized")
}
Log.i(TAG, "Starting upload")
for (uploader in uploaders) {
if (cancelState.get()) return
uploader.uploadedChangeListener = uploadedChangeRelay
uploader.upload(cancelState)
}
} catch (e: Exception) {
Log.e(TAG, "Unable to upload", e)
progressListener?.onError(e)
}
isUploading = false
progressListener?.onFinished()
Log.i(TAG, "Finished upload")
}
private fun invalidateArea(pos: LatLon) {
// called after a conflict. If there is a conflict, the user is not the only one in that
// area, so best invalidate all downloaded quests here and redownload on next occasion
val tile = pos.enclosingTile(ApplicationConstants.QUEST_TILE_ZOOM)
downloadedTilesDB.remove(tile)
}
/** Public interface to classes that are bound to this service */
inner class Interface : Binder() {
fun setProgressListener(listener: UploadProgressListener?) {
progressListener = listener
}
val isUploadInProgress: Boolean get() = isUploading
}
companion object {
fun createIntent(context: Context): Intent {
return Intent(context, UploadService::class.java)
}
private const val TAG = "Upload"
}
}
| gpl-3.0 | 35b25ffae7e04e48aad5361f8a136b64 | 30.944882 | 99 | 0.677348 | 4.923544 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/group/copy/YankGroup.kt | 1 | 6235 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.group.copy
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.helper.EditorHelper
import org.jetbrains.annotations.Contract
import java.util.*
import kotlin.math.min
class YankGroup {
/**
* This yanks the text moved over by the motion command argument.
*
* @param editor The editor to yank from
* @param context The data context
* @param count The number of times to yank
* @param rawCount The actual count entered by the user
* @param argument The motion command argument
* @return true if able to yank the text, false if not
*/
fun yankMotion(editor: Editor, context: DataContext, count: Int, rawCount: Int, argument: Argument): Boolean {
val motion = argument.motion ?: return false
val caretModel = editor.caretModel
val ranges = ArrayList<Pair<Int, Int>>(caretModel.caretCount)
val startOffsets = HashMap<Caret, Int>(caretModel.caretCount)
for (caret in caretModel.allCarets) {
val motionRange = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, true)
?: continue
assert(motionRange.size() == 1)
ranges.add(motionRange.startOffset to motionRange.endOffset)
startOffsets[caret] = motionRange.normalize().startOffset
}
val type = SelectionType.fromCommandFlags(motion.flags)
val range = getTextRange(ranges, type)
val selectionType = if (type == SelectionType.CHARACTER_WISE && range.isMultiple) SelectionType.BLOCK_WISE else type
return yankRange(editor, range, selectionType, startOffsets)
}
/**
* This yanks count lines of text
*
* @param editor The editor to yank from
* @param count The number of lines to yank
* @return true if able to yank the lines, false if not
*/
fun yankLine(editor: Editor, count: Int): Boolean {
val caretModel = editor.caretModel
val ranges = ArrayList<Pair<Int, Int>>(caretModel.caretCount)
for (caret in caretModel.allCarets) {
val start = VimPlugin.getMotion().moveCaretToLineStart(editor, caret)
val end = min(VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, count - 1, true) + 1, EditorHelper.getFileSize(editor, true))
if (end == -1) continue
ranges.add(start to end)
}
val range = getTextRange(ranges, SelectionType.LINE_WISE)
return yankRange(editor, range, SelectionType.LINE_WISE, null)
}
/**
* This yanks a range of text
*
* @param editor The editor to yank from
* @param range The range of text to yank
* @param type The type of yank
* @return true if able to yank the range, false if not
*/
fun yankRange(editor: Editor, range: TextRange?, type: SelectionType, moveCursor: Boolean): Boolean {
range ?: return false
val selectionType = if (type == SelectionType.CHARACTER_WISE && range.isMultiple) SelectionType.BLOCK_WISE else type
if (type == SelectionType.LINE_WISE) {
for (i in 0 until range.size()) {
if (editor.offsetToLogicalPosition(range.startOffsets[i]).column != 0) {
range.startOffsets[i] = EditorHelper.getLineStartForOffset(editor, range.startOffsets[i])
}
if (editor.offsetToLogicalPosition(range.endOffsets[i]).column != 0) {
range.endOffsets[i] = (EditorHelper.getLineEndForOffset(editor, range.endOffsets[i]) + 1).coerceAtMost(EditorHelper.getFileSize(editor))
}
}
}
val caretModel = editor.caretModel
val rangeStartOffsets = range.startOffsets
val rangeEndOffsets = range.endOffsets
return if (moveCursor) {
val startOffsets = HashMap<Caret, Int>(caretModel.caretCount)
if (type == SelectionType.BLOCK_WISE) {
startOffsets[caretModel.primaryCaret] = range.normalize().startOffset
} else {
val carets = caretModel.allCarets
for (i in carets.indices) {
startOffsets[carets[i]] = TextRange(rangeStartOffsets[i], rangeEndOffsets[i]).normalize().startOffset
}
}
yankRange(editor, range, selectionType, startOffsets)
} else {
yankRange(editor, range, selectionType, null)
}
}
@Contract("_, _ -> new")
private fun getTextRange(ranges: List<Pair<Int, Int>>, type: SelectionType): TextRange {
val size = ranges.size
val starts = IntArray(size)
val ends = IntArray(size)
if (type == SelectionType.LINE_WISE) {
starts[size - 1] = ranges[size - 1].first
ends[size - 1] = ranges[size - 1].second
for (i in 0 until size - 1) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second - 1
}
} else {
for (i in 0 until size) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second
}
}
return TextRange(starts, ends)
}
private fun yankRange(editor: Editor, range: TextRange, type: SelectionType,
startOffsets: Map<Caret, Int>?): Boolean {
startOffsets?.forEach { caret, offset -> MotionGroup.moveCaret(editor, caret, offset) }
return VimPlugin.getRegister().storeText(editor, range, type, false)
}
}
| gpl-2.0 | c2e0d6a10a977c684b3934c8900ce346 | 36.560241 | 146 | 0.693023 | 4.193006 | false | false | false | false |
deltaDNA/android-sdk | library/src/test/java/com/deltadna/android/sdk/net/RequestBodyTest.kt | 1 | 2082 | /*
* Copyright (c) 2016 deltaDNA Ltd. 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.deltadna.android.sdk.net
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.json.JSONObject
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.OutputStream
import java.net.HttpURLConnection
@RunWith(JUnit4::class)
class RequestBodyTest {
@Test
fun ctor() {
val type = "type"
val content = byteArrayOf(0)
val uut = RequestBody(type, content)
assertThat(uut.type).isEqualTo(type)
assertThat(uut.content).isEqualTo(content)
}
@Test
fun fill() {
val uut = RequestBody("type", byteArrayOf(0))
val conn = mock<HttpURLConnection>()
val os = mock<OutputStream>()
whenever(conn.outputStream).thenReturn(os)
uut.fill(conn)
verify(conn).setFixedLengthStreamingMode(eq(uut.content.size))
verify(conn).setRequestProperty(eq("Content-Type"), eq(uut.type))
verify(os).write(eq(uut.content))
}
@Test
fun json() {
val uut = RequestBody.json(JSONObject().put("field", 1))
assertThat(uut.type).isEqualTo("application/json; charset=utf-8")
assertThat(uut.content).isEqualTo("{\"field\":1}".toByteArray(charset("UTF-8")))
}
}
| apache-2.0 | 1c5527e40d47096852728bb079ce6c9d | 31.030769 | 88 | 0.683477 | 4.082353 | false | true | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/InsertIfNewByTimestampTherapyEventTransaction.kt | 1 | 1286 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TherapyEvent
class InsertIfNewByTimestampTherapyEventTransaction(
val therapyEvent: TherapyEvent
) : Transaction<InsertIfNewByTimestampTherapyEventTransaction.TransactionResult>() {
constructor(timestamp: Long, type: TherapyEvent.Type, duration: Long = 0, note: String? = null, enteredBy: String? = null, glucose: Double? = null, glucoseType: TherapyEvent.MeterType? = null, glucoseUnit: TherapyEvent.GlucoseUnit) :
this(TherapyEvent(timestamp = timestamp, type = type, duration = duration, note = note, enteredBy = enteredBy, glucose = glucose, glucoseType = glucoseType, glucoseUnit = glucoseUnit))
override fun run(): TransactionResult {
val result = TransactionResult()
val current = database.therapyEventDao.findByTimestamp(therapyEvent.type, therapyEvent.timestamp)
if (current == null) {
database.therapyEventDao.insertNewEntry(therapyEvent)
result.inserted.add(therapyEvent)
} else result.existing.add(therapyEvent)
return result
}
class TransactionResult {
val inserted = mutableListOf<TherapyEvent>()
val existing = mutableListOf<TherapyEvent>()
}
} | agpl-3.0 | 53e22ce8e993630f6719e44f23776852 | 46.666667 | 237 | 0.738725 | 5.023438 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt | 1 | 1008 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageType
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding
data class PairMessage(
val sequenceNumber: Byte,
val source: Id,
val destination: Id,
private val keys: Array<String>,
private val payloads: Array<ByteArray>,
val messagePacket: MessagePacket = MessagePacket(
type = MessageType.PAIRING,
source = source,
destination = destination,
payload = StringLengthPrefixEncoding.formatKeys(
keys,
payloads,
),
sequenceNumber = sequenceNumber,
sas = true // TODO: understand why this is true for PairMessages
)
)
| agpl-3.0 | d5f8481eb8a09343e8887e8bc64a8c0c | 39.32 | 106 | 0.737103 | 4.363636 | false | false | false | false |
notsyncing/lightfur | lightfur-entity/src/main/kotlin/io/github/notsyncing/lightfur/entity/events/EntityEventDispatcher.kt | 1 | 984 | package io.github.notsyncing.lightfur.entity.events
import io.github.notsyncing.lightfur.DataSession
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
object EntityEventDispatcher {
private var handlerResolver: EntityEventHandlerResolver? = null
fun dispatch(db: DataSession<*, *, *>, event: EntityEvent) = future {
if (handlerResolver == null) {
throw UnsupportedOperationException("You must specify a ${EntityEventHandlerResolver::class.java} " +
"to be able to dispatch entity events!")
}
val handlers = handlerResolver!!.resolve(event::class.java) as List<EntityEventHandler<EntityEvent>>
for (handler in handlers) {
handler.handle(db, event).await()
}
}
fun dispatch(db: DataSession<*, *, *>, events: Collection<EntityEvent>) = future {
for (e in events) {
dispatch(db, e).await()
}
}
} | gpl-3.0 | 0091dadfd3c10c86b4ff7e50e223d940 | 34.178571 | 113 | 0.666667 | 4.619718 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper-Okhttp/src/main/java/com/prateekj/snooper/okhttp/SnooperInterceptor.kt | 1 | 2174 | package com.prateekj.snooper.okhttp
import com.prateekj.snooper.AndroidSnooper
import com.prateekj.snooper.networksnooper.model.HttpCall
import com.prateekj.snooper.utils.Logger
import java.io.IOException
import java.util.HashMap
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import okhttp3.ResponseBody.create
class SnooperInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val response: Response
val responseBody: String
val request = chain.request()
val builder = HttpCall.Builder()
.withUrl(request.url().toString())
.withPayload(getRequestBody(request))
.withMethod(request.method())
.withRequestHeaders(headers(request.headers()))
try {
response = chain.proceed(request)
responseBody = response.body().string()
} catch (e: Exception) {
val httpCall = builder.withError(e.toString()).build()
AndroidSnooper.instance.record(httpCall)
throw e
}
val httpCall = builder.withResponseBody(responseBody)
.withStatusCode(response.code())
.withStatusText(response.message())
.withResponseHeaders(headers(response.headers())).build()
AndroidSnooper.instance.record(httpCall)
return response.newBuilder().body(create(response.body().contentType(), responseBody))
.build()
}
private fun headers(headers: Headers): Map<String, List<String>> {
val extractedHeaders = HashMap<String, List<String>>()
for (headerName in headers.names()) {
extractedHeaders[headerName] = headers.values(headerName)
}
return extractedHeaders
}
private fun getRequestBody(request: Request): String {
try {
val copy = request.newBuilder().build()
val buffer = Buffer()
if (copy.body() == null) {
return ""
}
copy.body().writeTo(buffer)
return buffer.readUtf8()
} catch (e: IOException) {
Logger.e(TAG, "couldn't retrieve request body", e)
return ""
}
}
companion object {
val TAG = SnooperInterceptor::class.java.simpleName
}
}
| apache-2.0 | f56d4f892577ebe0d43e6ddd32489cbb | 27.605263 | 90 | 0.697792 | 4.287968 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/main/kotlin/app/ss/media/di/PlaybackModule.kt | 1 | 3541 | /*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.media.di
import android.content.ComponentName
import android.content.Context
import app.ss.lessons.data.repository.media.MediaRepository
import app.ss.media.playback.AudioFocusHelperImpl
import app.ss.media.playback.AudioQueueManager
import app.ss.media.playback.AudioQueueManagerImpl
import app.ss.media.playback.MediaNotifications
import app.ss.media.playback.MediaNotificationsImpl
import app.ss.media.playback.PlaybackConnection
import app.ss.media.playback.PlaybackConnectionImpl
import app.ss.media.playback.players.AudioPlayer
import app.ss.media.playback.players.AudioPlayerImpl
import app.ss.media.playback.players.SSAudioPlayer
import app.ss.media.playback.players.SSAudioPlayerImpl
import app.ss.media.playback.service.MusicService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object PlaybackModule {
@Provides
@Singleton
fun provideMediaNotifications(
@ApplicationContext context: Context
): MediaNotifications = MediaNotificationsImpl(
context
)
@Provides
@Singleton
fun provideAudioPlayer(
@ApplicationContext context: Context,
okHttpClient: OkHttpClient
): AudioPlayer = AudioPlayerImpl(
context,
okHttpClient
)
@Provides
@Singleton
fun provideSSPlayer(
@ApplicationContext context: Context,
player: AudioPlayer,
repository: MediaRepository,
queueManager: AudioQueueManager
): SSAudioPlayer = SSAudioPlayerImpl(
context,
player,
audioFocusHelper = AudioFocusHelperImpl(context),
queueManager = queueManager,
repository = repository
)
@Provides
@Singleton
fun playbackConnection(
@ApplicationContext context: Context,
audioPlayer: AudioPlayer
): PlaybackConnection = PlaybackConnectionImpl(
context = context,
serviceComponent = ComponentName(context, MusicService::class.java),
audioPlayer = audioPlayer
)
@Provides
@Singleton
fun provideQueueManager(
repository: MediaRepository
): AudioQueueManager = AudioQueueManagerImpl(
repository = repository
)
}
| mit | 8144392c2f9ec104d517fd4c9e67829b | 33.378641 | 80 | 0.753742 | 4.759409 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinJsModuleConfigurator.kt | 2 | 3720 | // 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.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.DummyLibraryProperties
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.base.platforms.JsStdlibDetectionUtil
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.framework.JSLibraryStdDescription
import org.jetbrains.kotlin.idea.framework.JSLibraryType
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor
import org.jetbrains.kotlin.js.JavaScript
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
open class KotlinJsModuleConfigurator : KotlinWithLibraryConfigurator<DummyLibraryProperties>() {
override val name: String
get() = NAME
override val targetPlatform: TargetPlatform
get() = JsPlatforms.defaultJsPlatform
override val presentableText: String
get() = KotlinJvmBundle.message("language.name.javascript")
override fun isConfigured(module: Module) = hasKotlinJsRuntimeInScope(module)
override val libraryName: String
get() = JSLibraryStdDescription.LIBRARY_NAME
override val dialogTitle: String
get() = JSLibraryStdDescription.DIALOG_TITLE
override val messageForOverrideDialog: String
get() = JSLibraryStdDescription.JAVA_SCRIPT_LIBRARY_CREATION
override val libraryJarDescriptor: LibraryJarDescriptor get() = LibraryJarDescriptor.JS_STDLIB_JAR
override val libraryMatcher: (Library, Project) -> Boolean = { library, project ->
JsStdlibDetectionUtil.hasJavaScriptStdlibJar(library, project)
}
override val libraryType: LibraryType<DummyLibraryProperties> get() = JSLibraryType.getInstance()
override val libraryProperties: DummyLibraryProperties
get() = DummyLibraryProperties.INSTANCE
companion object {
const val NAME = JavaScript.LOWER_NAME
}
/**
* Migrate pre-1.1.3 projects which didn't have explicitly specified kind for JS libraries.
*/
override fun findAndFixBrokenKotlinLibrary(module: Module, collector: NotificationMessageCollector): Library? {
val allLibraries = mutableListOf<LibraryEx>()
var brokenStdlib: Library? = null
for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) {
val library = (orderEntry as? LibraryOrderEntry)?.library as? LibraryEx ?: continue
allLibraries.add(library)
if (JsStdlibDetectionUtil.hasJavaScriptStdlibJar(library, module.project, ignoreKind = true) && library.kind == null) {
brokenStdlib = library
}
}
if (brokenStdlib != null) {
runWriteAction {
for (library in allLibraries.filter { it.kind == null }) {
library.modifiableModel.apply {
kind = KotlinJavaScriptLibraryKind
commit()
}
}
}
collector.addMessage(KotlinJvmBundle.message("updated.javascript.libraries.in.module.0", module.name))
}
return brokenStdlib
}
}
| apache-2.0 | 775c171e90167a883baafad90c35563b | 41.758621 | 131 | 0.732527 | 5.116919 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ExtensionContainerExtensions.kt | 3 | 4161 | /*
* Copyright 2016 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 org.gradle.kotlin.dsl
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.plugins.ExtensionContainer
import kotlin.reflect.KProperty
/**
* Looks for the extension of a given name. If none found it will throw an exception.
*
* @param name extension name
* @return extension
* @throws [UnknownDomainObjectException] When the given extension is not found.
*
* @see [ExtensionContainer.getByName]
*/
operator fun ExtensionContainer.get(name: String): Any =
getByName(name)
/**
* Looks for the extension of a given name and casts it to the expected type [T].
*
* If none found it will throw an [UnknownDomainObjectException].
* If the extension is found but cannot be cast to the expected type it will throw an [IllegalStateException].
*
* @param name extension name
* @return extension, never null
* @throws [UnknownDomainObjectException] When the given extension is not found.
* @throws [IllegalStateException] When the given extension cannot be cast to the expected type.
*/
@Suppress("extension_shadowed_by_member")
inline fun <reified T : Any> ExtensionContainer.getByName(name: String) =
getByName(name).let {
it as? T
?: throw IllegalStateException(
"Element '$name' of type '${it::class.java.name}' from container '$this' cannot be cast to '${T::class.qualifiedName}'."
)
}
/**
* Delegated property getter that locates extensions.
*/
inline operator fun <reified T : Any> ExtensionContainer.getValue(thisRef: Any?, property: KProperty<*>): T =
getByName<T>(property.name)
/**
* Adds a new extension to this container.
*
* @param T the public type of the added extension
* @param name the name of the extension
* @param extension the extension instance
*
* @throws IllegalArgumentException When an extension with the given name already exists.
*
* @see [ExtensionContainer.add]
* @since 5.0
*/
@Suppress("extension_shadowed_by_member")
inline fun <reified T : Any> ExtensionContainer.add(name: String, extension: T) {
add(typeOf<T>(), name, extension)
}
/**
* Creates and adds a new extension to this container.
*
* @param T the instance type of the new extension
* @param name the extension's name
* @param constructionArguments construction arguments
* @return the created instance
*
* @see [ExtensionContainer.create]
* @since 5.0
*/
inline fun <reified T : Any> ExtensionContainer.create(name: String, vararg constructionArguments: Any): T =
create(name, T::class.java, *constructionArguments)
/**
* Looks for the extension of a given type.
*
* @param T the extension type
* @return the extension
* @throws UnknownDomainObjectException when no matching extension can be found
*
* @see [ExtensionContainer.getByType]
* @since 5.0
*/
inline fun <reified T : Any> ExtensionContainer.getByType(): T =
getByType(typeOf<T>())
/**
* Looks for the extension of a given type.
*
* @param T the extension type
* @return the extension or null if not found
*
* @see [ExtensionContainer.findByType]
* @since 5.0
*/
inline fun <reified T : Any> ExtensionContainer.findByType(): T? =
findByType(typeOf<T>())
/**
* Looks for the extension of the specified type and configures it with the supplied action.
*
* @param T the extension type
* @param action the configuration action
*
* @see [ExtensionContainer.configure]
* @since 5.0
*/
inline fun <reified T : Any> ExtensionContainer.configure(noinline action: T.() -> Unit) {
configure(typeOf<T>(), action)
}
| apache-2.0 | f56bacab2f164a663183a311255f7c8f | 29.372263 | 136 | 0.717376 | 4.119802 | false | false | false | false |
ingokegel/intellij-community | platform/service-container/src/com/intellij/serviceContainer/ComponentManagerImpl.kt | 1 | 60539 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.serviceContainer
import com.intellij.diagnostic.*
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.idea.AppMode.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.components.*
import com.intellij.openapi.components.ServiceDescriptor.PreloadMode
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IComponentStoreOwner
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.*
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.util.ArrayUtil
import com.intellij.util.childScope
import com.intellij.util.messages.*
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.messages.impl.MessageBusImpl
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.picocontainer.ComponentAdapter
import org.picocontainer.PicoContainer
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.reflect.Constructor
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicReference
internal val LOG = logger<ComponentManagerImpl>()
private val constructorParameterResolver = ConstructorParameterResolver()
private val methodLookup = MethodHandles.lookup()
private val emptyConstructorMethodType = MethodType.methodType(Void.TYPE)
@ApiStatus.Internal
abstract class ComponentManagerImpl(
internal val parent: ComponentManagerImpl?,
setExtensionsRootArea: Boolean = parent == null
) : ComponentManager, Disposable.Parent, MessageBusOwner, UserDataHolderBase(), PicoContainer, ComponentManagerEx, IComponentStoreOwner {
protected enum class ContainerState {
PRE_INIT, COMPONENT_CREATED, DISPOSE_IN_PROGRESS, DISPOSED, DISPOSE_COMPLETED
}
companion object {
@JvmField
@Volatile
@ApiStatus.Internal
var mainScope: CoroutineScope? = null
@ApiStatus.Internal
@JvmField val fakeCorePluginDescriptor = DefaultPluginDescriptor(PluginManagerCore.CORE_ID, null)
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@ApiStatus.Internal
@JvmField val badWorkspaceComponents: Set<String> = java.util.Set.of(
"jetbrains.buildServer.codeInspection.InspectionPassRegistrar",
"jetbrains.buildServer.testStatus.TestStatusPassRegistrar",
"jetbrains.buildServer.customBuild.lang.gutterActions.CustomBuildParametersGutterActionsHighlightingPassRegistrar",
)
// not as file level function to avoid scope cluttering
@ApiStatus.Internal
fun createAllServices(componentManager: ComponentManagerImpl, exclude: Set<String>) {
for (o in componentManager.componentKeyToAdapter.values) {
if (o !is ServiceComponentAdapter) {
continue
}
val implementation = o.descriptor.serviceImplementation
try {
if (implementation == "org.jetbrains.plugins.groovy.mvc.MvcConsole") {
// NPE in RunnerContentUi.setLeftToolbar
continue
}
if (implementation == "org.jetbrains.plugins.grails.lang.gsp.psi.gsp.impl.gtag.GspTagDescriptorService") {
// requires a read action
continue
}
if (exclude.contains(implementation)) {
invokeAndWaitIfNeeded {
o.getInstance<Any>(componentManager, null)
}
}
else {
o.getInstance<Any>(componentManager, null)
}
}
catch (e: Throwable) {
LOG.error("Cannot create $implementation", e)
}
}
}
}
private val componentKeyToAdapter = ConcurrentHashMap<Any, ComponentAdapter>()
private val componentAdapters = LinkedHashSetWrapper<MyComponentAdapter>()
private val serviceInstanceHotCache = ConcurrentHashMap<Class<*>, Any?>()
protected val containerState = AtomicReference(ContainerState.PRE_INIT)
protected val containerStateName: String
get() = containerState.get().name
private val _extensionArea by lazy { ExtensionsAreaImpl(this) }
private var messageBus: MessageBusImpl? = null
private var handlingInitComponentError = false
@Volatile
private var isServicePreloadingCancelled = false
private var componentConfigCount = -1
@Suppress("LeakingThis")
internal val serviceParentDisposable = Disposer.newDisposable("services of ${javaClass.name}@${System.identityHashCode(this)}")
protected open val isLightServiceSupported = parent?.parent == null
protected open val isMessageBusSupported = parent?.parent == null
protected open val isComponentSupported = true
protected open val isExtensionSupported = true
@Volatile
internal var componentContainerIsReadonly: String? = null
private val coroutineScope: CoroutineScope? = when {
parent == null -> mainScope?.childScope(Dispatchers.Default) ?: CoroutineScope(SupervisorJob())
parent.parent == null -> parent.coroutineScope!!.childScope()
else -> null
}
@Suppress("MemberVisibilityCanBePrivate")
fun getCoroutineScope(): CoroutineScope = coroutineScope ?: throw RuntimeException("Module doesn't have coroutineScope")
override val componentStore: IComponentStore
get() = getService(IComponentStore::class.java)!!
init {
if (setExtensionsRootArea) {
Extensions.setRootArea(_extensionArea)
}
}
@Deprecated("Use ComponentManager API", level = DeprecationLevel.ERROR)
final override fun getPicoContainer(): PicoContainer {
checkState()
return this
}
private fun registerAdapter(componentAdapter: ComponentAdapter, pluginDescriptor: PluginDescriptor?) {
if (componentKeyToAdapter.putIfAbsent(componentAdapter.componentKey, componentAdapter) != null) {
val error = "Key ${componentAdapter.componentKey} duplicated"
if (pluginDescriptor == null) {
throw PluginException.createByClass(error, null, componentAdapter.javaClass)
}
else {
throw PluginException(error, null, pluginDescriptor.pluginId)
}
}
}
fun forbidGettingServices(reason: String): AccessToken {
val token = object : AccessToken() {
override fun finish() {
componentContainerIsReadonly = null
}
}
componentContainerIsReadonly = reason
return token
}
private fun checkState() {
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
}
final override fun getMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
val messageBus = messageBus
if (messageBus == null || !isMessageBusSupported) {
LOG.error("Do not use module level message bus")
return getOrCreateMessageBusUnderLock()
}
return messageBus
}
fun getDeprecatedModuleLevelMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
return messageBus ?: getOrCreateMessageBusUnderLock()
}
final override fun getExtensionArea(): ExtensionsAreaImpl {
if (!isExtensionSupported) {
error("Extensions aren't supported")
}
return _extensionArea
}
fun registerComponents() {
registerComponents(modules = PluginManagerCore.getPluginSet().getEnabledModules(),
app = getApplication(),
precomputedExtensionModel = null,
listenerCallbacks = null)
}
open fun registerComponents(modules: List<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel?,
listenerCallbacks: MutableList<in Runnable>?) {
val activityNamePrefix = activityNamePrefix()
var newComponentConfigCount = 0
var map: ConcurrentMap<String, MutableList<ListenerDescriptor>>? = null
val isHeadless = app == null || app.isHeadlessEnvironment
val isUnitTestMode = app?.isUnitTestMode ?: false
var activity = activityNamePrefix?.let { StartUpMeasurer.startActivity("${it}service and ep registration") }
// register services before registering extensions because plugins can access services in their
// extensions which can be invoked right away if the plugin is loaded dynamically
val extensionPoints = if (precomputedExtensionModel == null) HashMap(extensionArea.extensionPoints) else null
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
val containerDescriptor = getContainerDescriptor(module)
registerServices(containerDescriptor.services, module)
newComponentConfigCount += registerComponents(module, containerDescriptor, isHeadless)
containerDescriptor.listeners?.let { listeners ->
var m = map
if (m == null) {
m = ConcurrentHashMap()
map = m
}
for (listener in listeners) {
if ((isUnitTestMode && !listener.activeInTestMode) || (isHeadless && !listener.activeInHeadlessMode)) {
continue
}
if (listener.os != null && !isSuitableForOs(listener.os)) {
continue
}
listener.pluginDescriptor = module
m.computeIfAbsent(listener.topicClassName) { ArrayList() }.add(listener)
}
}
if (extensionPoints != null) {
containerDescriptor.extensionPoints?.let {
ExtensionsAreaImpl.createExtensionPoints(it, this, extensionPoints, module)
}
}
}
}
if (activity != null) {
activity = activity.endAndStart("${activityNamePrefix}extension registration")
}
if (precomputedExtensionModel == null) {
val immutableExtensionPoints = if (extensionPoints!!.isEmpty()) Collections.emptyMap() else java.util.Map.copyOf(extensionPoints)
extensionArea.setPoints(immutableExtensionPoints)
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
module.registerExtensions(immutableExtensionPoints, getContainerDescriptor(module), listenerCallbacks)
}
}
}
else {
registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel, listenerCallbacks)
}
activity?.end()
if (componentConfigCount == -1) {
componentConfigCount = newComponentConfigCount
}
// app - phase must be set before getMessageBus()
if (parent == null && !LoadingState.COMPONENTS_REGISTERED.isOccurred /* loading plugin on the fly */) {
StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_REGISTERED)
}
// ensure that messageBus is created, regardless of lazy listeners map state
if (isMessageBusSupported) {
val messageBus = getOrCreateMessageBusUnderLock()
map?.let {
(messageBus as MessageBusEx).setLazyListeners(it)
}
}
}
private fun registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel: PrecomputedExtensionModel,
listenerCallbacks: MutableList<in Runnable>?) {
assert(extensionArea.extensionPoints.isEmpty())
val n = precomputedExtensionModel.pluginDescriptors.size
if (n == 0) {
return
}
val result = HashMap<String, ExtensionPointImpl<*>>(precomputedExtensionModel.extensionPointTotalCount)
for (i in 0 until n) {
ExtensionsAreaImpl.createExtensionPoints(precomputedExtensionModel.extensionPoints[i],
this,
result,
precomputedExtensionModel.pluginDescriptors[i])
}
val immutableExtensionPoints = java.util.Map.copyOf(result)
extensionArea.setPoints(immutableExtensionPoints)
for ((name, pairs) in precomputedExtensionModel.nameToExtensions) {
val point = immutableExtensionPoints.get(name) ?: continue
for ((pluginDescriptor, list) in pairs) {
if (!list.isEmpty()) {
point.registerExtensions(list, pluginDescriptor, listenerCallbacks)
}
}
}
}
private fun registerComponents(pluginDescriptor: IdeaPluginDescriptor, containerDescriptor: ContainerDescriptor, headless: Boolean): Int {
var count = 0
for (descriptor in (containerDescriptor.components ?: return 0)) {
var implementationClassName = descriptor.implementationClass
if (headless && descriptor.headlessImplementationClass != null) {
if (descriptor.headlessImplementationClass.isEmpty()) {
continue
}
implementationClassName = descriptor.headlessImplementationClass
}
if (descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
if (!isComponentSuitable(descriptor)) {
continue
}
val componentClassName = descriptor.interfaceClass ?: descriptor.implementationClass!!
try {
registerComponent(
interfaceClassName = componentClassName,
implementationClassName = implementationClassName,
config = descriptor,
pluginDescriptor = pluginDescriptor,
)
count++
}
catch (e: Throwable) {
handleInitComponentError(e, componentClassName, pluginDescriptor.pluginId)
}
}
return count
}
fun createInitOldComponentsTask(): (() -> Unit)? {
if (componentAdapters.getImmutableSet().isEmpty()) {
return null
}
return {
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
}
}
@Suppress("DuplicatedCode")
@Deprecated(message = "Use createComponents")
protected fun createComponents() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@Suppress("DuplicatedCode")
protected suspend fun createComponentsNonBlocking() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstanceAsync<Any>(this, keyClass = null).await()
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@TestOnly
fun registerComponentImplementation(key: Class<*>, implementation: Class<*>, shouldBeRegistered: Boolean) {
checkState()
val oldAdapter = componentKeyToAdapter.remove(key) as MyComponentAdapter?
if (shouldBeRegistered) {
LOG.assertTrue(oldAdapter != null)
}
serviceInstanceHotCache.remove(key)
val pluginDescriptor = oldAdapter?.pluginDescriptor ?: DefaultPluginDescriptor("test registerComponentImplementation")
val newAdapter = MyComponentAdapter(componentKey = key,
implementationClassName = implementation.name,
pluginDescriptor = pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(),
implementationClass = implementation)
componentKeyToAdapter.put(key, newAdapter)
if (oldAdapter == null) {
componentAdapters.add(newAdapter)
}
else {
componentAdapters.replace(oldAdapter, newAdapter)
}
}
@TestOnly
fun <T : Any> replaceComponentInstance(componentKey: Class<T>, componentImplementation: T, parentDisposable: Disposable?) {
checkState()
val oldAdapter = componentKeyToAdapter.get(componentKey) as MyComponentAdapter
val implClass = componentImplementation::class.java
val newAdapter = MyComponentAdapter(componentKey = componentKey,
implementationClassName = implClass.name,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(value = componentImplementation),
implementationClass = implClass)
componentKeyToAdapter.put(componentKey, newAdapter)
componentAdapters.replace(oldAdapter, newAdapter)
serviceInstanceHotCache.remove(componentKey)
if (parentDisposable != null) {
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (componentImplementation is Disposable && !Disposer.isDisposed(componentImplementation)) {
Disposer.dispose(componentImplementation)
}
componentKeyToAdapter.put(componentKey, oldAdapter)
componentAdapters.replace(newAdapter, oldAdapter)
serviceInstanceHotCache.remove(componentKey)
}
}
}
private fun registerComponent(
interfaceClassName: String,
implementationClassName: String?,
config: ComponentConfig,
pluginDescriptor: IdeaPluginDescriptor,
) {
val interfaceClass = pluginDescriptor.classLoader.loadClass(interfaceClassName)
val options = config.options
if (config.overrides) {
unregisterComponent(interfaceClass) ?: throw PluginException("$config does not override anything", pluginDescriptor.pluginId)
}
// implementationClass == null means we want to unregister this component
if (implementationClassName == null) {
return
}
if (options != null && java.lang.Boolean.parseBoolean(options.get("workspace")) &&
!badWorkspaceComponents.contains(implementationClassName)) {
LOG.error("workspace option is deprecated (implementationClass=$implementationClassName)")
}
val adapter = MyComponentAdapter(interfaceClass, implementationClassName, pluginDescriptor, this, CompletableDeferred(), null)
registerAdapter(adapter, adapter.pluginDescriptor)
componentAdapters.add(adapter)
}
open fun getApplication(): Application? {
return if (parent == null || this is Application) this as Application else parent.getApplication()
}
protected fun registerServices(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) {
checkState()
val app = getApplication()!!
for (descriptor in services) {
if (!isServiceSuitable(descriptor) || descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
// Allow to re-define service implementations in plugins.
// Empty serviceImplementation means we want to unregister service.
val key = descriptor.getInterface()
if (descriptor.overrides && componentKeyToAdapter.remove(key) == null) {
throw PluginException("Service $key doesn't override anything", pluginDescriptor.pluginId)
}
// empty serviceImplementation means we want to unregister service
val implementation = when {
descriptor.testServiceImplementation != null && app.isUnitTestMode -> descriptor.testServiceImplementation
descriptor.headlessImplementation != null && app.isHeadlessEnvironment -> descriptor.headlessImplementation
else -> descriptor.serviceImplementation
}
if (implementation != null) {
val componentAdapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this)
val existingAdapter = componentKeyToAdapter.putIfAbsent(key, componentAdapter)
if (existingAdapter != null) {
throw PluginException("Key $key duplicated; existingAdapter: $existingAdapter; descriptor: ${descriptor.implementation}; app: $app; current plugin: ${pluginDescriptor.pluginId}", pluginDescriptor.pluginId)
}
}
}
}
internal fun handleInitComponentError(error: Throwable, componentClassName: String, pluginId: PluginId) {
if (handlingInitComponentError) {
return
}
handlingInitComponentError = true
try {
// not logged but thrown PluginException means some fatal error
if (error is StartupAbortedException || error is ProcessCanceledException || error is PluginException) {
throw error
}
var effectivePluginId = pluginId
if (effectivePluginId == PluginManagerCore.CORE_ID) {
effectivePluginId = PluginManagerCore.getPluginDescriptorOrPlatformByClassName(componentClassName)?.pluginId
?: PluginManagerCore.CORE_ID
}
throw PluginException("Fatal error initializing '$componentClassName'", error, effectivePluginId)
}
finally {
handlingInitComponentError = false
}
}
internal fun initializeComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) {
if (serviceDescriptor == null || !isPreInitialized(component)) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
componentStore.initComponent(component, serviceDescriptor, pluginId)
}
}
protected open fun isPreInitialized(component: Any): Boolean {
return component is PathMacroManager || component is IComponentStore || component is MessageBusFactory
}
protected abstract fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor
final override fun <T : Any> getComponent(key: Class<T>): T? {
assertComponentsSupported()
checkState()
val adapter = getComponentAdapter(key)
if (adapter == null) {
checkCanceledIfNotInClassInit()
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(key.name, this, ProgressManager.getGlobalProgressIndicator())
}
return null
}
if (adapter is ServiceComponentAdapter) {
LOG.error("$key it is a service, use getService instead of getComponent")
}
if (adapter is BaseComponentAdapter) {
if (parent != null && adapter.componentManager !== this) {
LOG.error("getComponent must be called on appropriate container (current: $this, expected: ${adapter.componentManager})")
}
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
adapter.throwAlreadyDisposedError(this, ProgressManager.getGlobalProgressIndicator())
}
return adapter.getInstance(adapter.componentManager, key)
}
else {
@Suppress("UNCHECKED_CAST")
return adapter.getComponentInstance(this) as T
}
}
final override fun <T : Any> getService(serviceClass: Class<T>): T? {
// `computeIfAbsent` cannot be used because of recursive update
@Suppress("UNCHECKED_CAST")
var result = serviceInstanceHotCache.get(serviceClass) as T?
if (result == null) {
result = doGetService(serviceClass, true) ?: return postGetService(serviceClass, createIfNeeded = true)
serviceInstanceHotCache.putIfAbsent(serviceClass, result)
}
return result
}
final override suspend fun <T : Any> getServiceAsync(keyClass: Class<T>): Deferred<T> {
return getServiceAsyncIfDefined(keyClass) ?: throw RuntimeException("service is not defined for key ${keyClass.name}")
}
suspend fun <T : Any> getServiceAsyncIfDefined(keyClass: Class<T>): Deferred<T>? {
val key = keyClass.name
val adapter = componentKeyToAdapter.get(key) ?: return null
if (adapter !is ServiceComponentAdapter) {
throw RuntimeException("$adapter is not a service (key=$key)")
}
return adapter.getInstanceAsync(componentManager = this, keyClass = keyClass)
}
protected open fun <T : Any> postGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? = null
final override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? {
@Suppress("UNCHECKED_CAST")
var result = serviceInstanceHotCache.get(serviceClass) as T?
if (result != null) {
return result
}
result = doGetService(serviceClass, createIfNeeded = false)
if (result == null) {
return postGetService(serviceClass, createIfNeeded = false)
}
else {
serviceInstanceHotCache.putIfAbsent(serviceClass, result)
return result
}
}
protected open fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val key = serviceClass.name
val adapter = componentKeyToAdapter.get(key)
if (adapter is ServiceComponentAdapter) {
if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(adapter.toString(), this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
return adapter.getInstance(this, serviceClass, createIfNeeded)
}
else if (adapter is LightServiceComponentAdapter) {
if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(adapter.toString(), this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
@Suppress("UNCHECKED_CAST")
return adapter.getComponentInstance(null) as T
}
if (isLightServiceSupported && isLightService(serviceClass)) {
return if (createIfNeeded) getOrCreateLightService(serviceClass) else null
}
checkCanceledIfNotInClassInit()
// if the container is fully disposed, all adapters may be removed
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
if (!createIfNeeded) {
return null
}
throwAlreadyDisposedError(serviceClass.name, this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
if (parent != null) {
val result = parent.doGetService(serviceClass, createIfNeeded)
if (result != null) {
LOG.error("$key is registered as application service, but requested as project one")
return result
}
}
if (isLightServiceSupported && !serviceClass.isInterface && !Modifier.isFinal(serviceClass.modifiers) &&
serviceClass.isAnnotationPresent(Service::class.java)) {
throw PluginException.createByClass("Light service class $serviceClass must be final", null, serviceClass)
}
val result = getComponent(serviceClass) ?: return null
PluginException.logPluginError(LOG,
"$key requested as a service, but it is a component - " +
"convert it to a service or change call to " +
if (parent == null) "ApplicationManager.getApplication().getComponent()" else "project.getComponent()",
null, serviceClass)
return result
}
private fun <T : Any> getOrCreateLightService(serviceClass: Class<T>): T {
checkThatCreatingOfLightServiceIsAllowed(serviceClass)
synchronized(serviceClass) {
val adapter = componentKeyToAdapter.get(serviceClass.name) as LightServiceComponentAdapter?
if (adapter != null) {
@Suppress("UNCHECKED_CAST")
return adapter.getComponentInstance(null) as T
}
LoadingState.COMPONENTS_REGISTERED.checkOccurred()
var result: T? = null
if (ProgressIndicatorProvider.getGlobalProgressIndicator() == null) {
result = createLightService(serviceClass)
}
else {
ProgressManager.getInstance().executeNonCancelableSection {
result = createLightService(serviceClass)
}
}
result!!.let {
registerAdapter(LightServiceComponentAdapter(it), pluginDescriptor = null)
return it
}
}
}
private fun checkThatCreatingOfLightServiceIsAllowed(serviceClass: Class<*>) {
if (isDisposed) {
throwAlreadyDisposedError("light service ${serviceClass.name}", this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
// assertion only for non-platform plugins
val classLoader = serviceClass.classLoader
if (classLoader is PluginAwareClassLoader && !isGettingServiceAllowedDuringPluginUnloading(classLoader.pluginDescriptor)) {
componentContainerIsReadonly?.let {
val error = AlreadyDisposedException(
"Cannot create light service ${serviceClass.name} because container in read-only mode (reason=$it, container=$this"
)
throw if (ProgressIndicatorProvider.getGlobalProgressIndicator() == null) error else ProcessCanceledException(error)
}
}
}
@Synchronized
private fun getOrCreateMessageBusUnderLock(): MessageBus {
var messageBus = this.messageBus
if (messageBus != null) {
return messageBus
}
messageBus = getApplication()!!.getService(MessageBusFactory::class.java).createMessageBus(this, parent?.messageBus) as MessageBusImpl
if (StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener { topic, messageName, handler, duration ->
if (!StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener(null)
return@setMessageDeliveryListener
}
logMessageBusDelivery(topic, messageName, handler, duration)
}
}
registerServiceInstance(MessageBus::class.java, messageBus, fakeCorePluginDescriptor)
this.messageBus = messageBus
return messageBus
}
protected open fun logMessageBusDelivery(topic: Topic<*>, messageName: String, handler: Any, duration: Long) {
val loader = handler.javaClass.classLoader
val pluginId = if (loader is PluginAwareClassLoader) loader.pluginId.idString else PluginManagerCore.CORE_ID.idString
StartUpMeasurer.addPluginCost(pluginId, "MessageBus", duration)
}
/**
* Use only if approved by core team.
*/
fun registerComponent(key: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean) {
assertComponentsSupported()
checkState()
val adapter = MyComponentAdapter(key, implementation.name, pluginDescriptor, this, CompletableDeferred(), implementation)
if (override) {
overrideAdapter(adapter, pluginDescriptor)
componentAdapters.replace(adapter)
}
else {
registerAdapter(adapter, pluginDescriptor)
componentAdapters.add(adapter)
}
}
private fun overrideAdapter(adapter: ComponentAdapter, pluginDescriptor: PluginDescriptor) {
val componentKey = adapter.componentKey
if (componentKeyToAdapter.put(componentKey, adapter) == null) {
componentKeyToAdapter.remove(componentKey)
throw PluginException("Key $componentKey doesn't override anything", pluginDescriptor.pluginId)
}
}
/**
* Use only if approved by core team.
*/
fun registerService(serviceInterface: Class<*>,
implementation: Class<*>,
pluginDescriptor: PluginDescriptor,
override: Boolean,
preloadMode: PreloadMode = PreloadMode.FALSE) {
checkState()
val descriptor = ServiceDescriptor(serviceInterface.name, implementation.name, null, null, false,
null, preloadMode, null, null)
val adapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this, implementation)
if (override) {
overrideAdapter(adapter, pluginDescriptor)
}
else {
registerAdapter(adapter, pluginDescriptor)
}
serviceInstanceHotCache.remove(serviceInterface)
}
/**
* Use only if approved by core team.
*/
fun <T : Any> registerServiceInstance(serviceInterface: Class<T>, instance: T, pluginDescriptor: PluginDescriptor) {
val serviceKey = serviceInterface.name
checkState()
val descriptor = ServiceDescriptor(serviceKey, instance.javaClass.name, null, null, false,
null, PreloadMode.FALSE, null, null)
componentKeyToAdapter.put(serviceKey, ServiceComponentAdapter(descriptor = descriptor,
pluginDescriptor = pluginDescriptor,
componentManager = this,
implementationClass = instance.javaClass,
deferred = CompletableDeferred(value = instance)))
serviceInstanceHotCache.put(serviceInterface, instance)
}
@Suppress("DuplicatedCode")
@TestOnly
fun <T : Any> replaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
checkState()
if (isLightService(serviceInterface)) {
val adapter = LightServiceComponentAdapter(instance)
val key = adapter.componentKey
componentKeyToAdapter.put(key, adapter)
Disposer.register(parentDisposable) {
componentKeyToAdapter.remove(key)
serviceInstanceHotCache.remove(serviceInterface)
}
serviceInstanceHotCache.put(serviceInterface, instance)
}
else {
val key = serviceInterface.name
val oldAdapter = componentKeyToAdapter.get(key) as ServiceComponentAdapter
val newAdapter = ServiceComponentAdapter(descriptor = oldAdapter.descriptor,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
implementationClass = oldAdapter.getImplementationClass(),
deferred = CompletableDeferred(value = instance))
componentKeyToAdapter.put(key, newAdapter)
serviceInstanceHotCache.put(serviceInterface, instance)
@Suppress("DuplicatedCode")
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (instance is Disposable && !Disposer.isDisposed(instance)) {
Disposer.dispose(instance)
}
componentKeyToAdapter.put(key, oldAdapter)
serviceInstanceHotCache.remove(serviceInterface)
}
}
}
@TestOnly
fun unregisterService(serviceInterface: Class<*>) {
val key = serviceInterface.name
when (val adapter = componentKeyToAdapter.remove(key)) {
null -> error("Trying to unregister $key service which is not registered")
!is ServiceComponentAdapter -> error("$key service should be registered as a service, but was ${adapter::class.java}")
}
serviceInstanceHotCache.remove(serviceInterface)
}
@Suppress("DuplicatedCode")
fun <T : Any> replaceRegularServiceInstance(serviceInterface: Class<T>, instance: T) {
checkState()
val key = serviceInterface.name
val oldAdapter = componentKeyToAdapter.get(key) as ServiceComponentAdapter
val newAdapter = ServiceComponentAdapter(descriptor = oldAdapter.descriptor,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
implementationClass = oldAdapter.getImplementationClass(),
deferred = CompletableDeferred(value = instance))
componentKeyToAdapter.put(key, newAdapter)
serviceInstanceHotCache.put(serviceInterface, instance)
(oldAdapter.getInitializedInstance() as? Disposable)?.let(Disposer::dispose)
serviceInstanceHotCache.put(serviceInterface, instance)
}
private fun <T : Any> createLightService(serviceClass: Class<T>): T {
val startTime = StartUpMeasurer.getCurrentTime()
val pluginId = (serviceClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID
val result = instantiateClass(serviceClass, pluginId)
if (result is Disposable) {
Disposer.register(serviceParentDisposable, result)
}
initializeComponent(result, null, pluginId)
StartUpMeasurer.addCompletedActivity(startTime, serviceClass, getActivityCategory(isExtension = false), pluginId.idString)
return result
}
final override fun <T : Any> loadClass(className: String, pluginDescriptor: PluginDescriptor): Class<T> {
@Suppress("UNCHECKED_CAST")
return doLoadClass(className, pluginDescriptor) as Class<T>
}
final override fun <T : Any> instantiateClass(aClass: Class<T>, pluginId: PluginId): T {
checkCanceledIfNotInClassInit()
try {
if (parent == null) {
@Suppress("UNCHECKED_CAST")
return MethodHandles.privateLookupIn(aClass, methodLookup).findConstructor(aClass, emptyConstructorMethodType).invoke() as T
}
else {
val constructors: Array<Constructor<*>> = aClass.declaredConstructors
var constructor = if (constructors.size > 1) {
// see ConfigurableEP - prefer constructor that accepts our instance
constructors.firstOrNull { it.parameterCount == 1 && it.parameterTypes[0].isAssignableFrom(javaClass) }
}
else {
null
}
if (constructor == null) {
constructors.sortBy { it.parameterCount }
constructor = constructors.first()
}
constructor.isAccessible = true
@Suppress("UNCHECKED_CAST")
if (constructor.parameterCount == 1) {
return constructor.newInstance(getActualContainerInstance()) as T
}
else {
@Suppress("UNCHECKED_CAST")
return MethodHandles.privateLookupIn(aClass, methodLookup).unreflectConstructor(constructor).invoke() as T
}
}
}
catch (e: Throwable) {
if (e is InvocationTargetException) {
val targetException = e.targetException
if (targetException is ControlFlowException) {
throw targetException
}
}
else if (e is ControlFlowException) {
throw e
}
throw PluginException("Cannot create class ${aClass.name} (classloader=${aClass.classLoader})", e, pluginId)
}
}
protected open fun getActualContainerInstance(): ComponentManager = this
final override fun <T : Any> instantiateClassWithConstructorInjection(aClass: Class<T>, key: Any, pluginId: PluginId): T {
return instantiateUsingPicoContainer(aClass, key, pluginId, this, constructorParameterResolver)
}
internal open val isGetComponentAdapterOfTypeCheckEnabled: Boolean
get() = true
final override fun <T : Any> instantiateClass(className: String, pluginDescriptor: PluginDescriptor): T {
val pluginId = pluginDescriptor.pluginId
try {
@Suppress("UNCHECKED_CAST")
return instantiateClass(doLoadClass(className, pluginDescriptor) as Class<T>, pluginId)
}
catch (e: Throwable) {
when {
e is PluginException || e is ExtensionNotApplicableException || e is ProcessCanceledException -> throw e
e.cause is NoSuchMethodException || e.cause is IllegalArgumentException -> {
throw PluginException("Class constructor must not have parameters: $className", e, pluginId)
}
else -> throw PluginException(e, pluginDescriptor.pluginId)
}
}
}
final override fun createListener(descriptor: ListenerDescriptor): Any {
val pluginDescriptor = descriptor.pluginDescriptor
val aClass = try {
doLoadClass(descriptor.listenerClassName, pluginDescriptor)
}
catch (e: Throwable) {
throw PluginException("Cannot create listener ${descriptor.listenerClassName}", e, pluginDescriptor.pluginId)
}
return instantiateClass(aClass, pluginDescriptor.pluginId)
}
final override fun logError(error: Throwable, pluginId: PluginId) {
if (error is ProcessCanceledException || error is ExtensionNotApplicableException) {
throw error
}
LOG.error(createPluginExceptionIfNeeded(error, pluginId))
}
final override fun createError(error: Throwable, pluginId: PluginId): RuntimeException {
return when (val effectiveError: Throwable = if (error is InvocationTargetException) error.targetException else error) {
is ProcessCanceledException, is ExtensionNotApplicableException, is PluginException -> effectiveError as RuntimeException
else -> PluginException(effectiveError, pluginId)
}
}
final override fun createError(message: String, pluginId: PluginId) = PluginException(message, pluginId)
final override fun createError(message: String,
error: Throwable?,
pluginId: PluginId,
attachments: MutableMap<String, String>?): RuntimeException {
return PluginException(message, error, pluginId, attachments?.map { Attachment(it.key, it.value) } ?: emptyList())
}
open fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) {
checkState()
if (!services.isEmpty()) {
val store = componentStore
for (service in services) {
val adapter = (componentKeyToAdapter.remove(service.`interface`) ?: continue) as ServiceComponentAdapter
val instance = adapter.getInitializedInstance() ?: continue
if (instance is Disposable) {
Disposer.dispose(instance)
}
store.unloadComponent(instance)
}
}
if (isLightServiceSupported) {
val store = componentStore
val iterator = componentKeyToAdapter.values.iterator()
while (iterator.hasNext()) {
val adapter = iterator.next() as? LightServiceComponentAdapter ?: continue
val instance = adapter.getComponentInstance(null)
if ((instance.javaClass.classLoader as? PluginAwareClassLoader)?.pluginId == pluginId) {
if (instance is Disposable) {
Disposer.dispose(instance)
}
store.unloadComponent(instance)
iterator.remove()
}
}
}
serviceInstanceHotCache.clear()
}
open fun activityNamePrefix(): String? = null
fun preloadServices(modules: List<IdeaPluginDescriptorImpl>,
activityPrefix: String,
syncScope: CoroutineScope,
onlyIfAwait: Boolean = false) {
val asyncScope = coroutineScope!!
for (plugin in modules) {
for (service in getContainerDescriptor(plugin).services) {
if (!isServiceSuitable(service) || (service.os != null && !isSuitableForOs(service.os))) {
continue
}
val scope: CoroutineScope = when (service.preload) {
PreloadMode.TRUE -> if (onlyIfAwait) null else asyncScope
PreloadMode.NOT_HEADLESS -> if (onlyIfAwait || getApplication()!!.isHeadlessEnvironment) null else asyncScope
PreloadMode.NOT_LIGHT_EDIT -> if (onlyIfAwait || isLightEdit()) null else asyncScope
PreloadMode.AWAIT -> syncScope
PreloadMode.FALSE -> null
else -> throw IllegalStateException("Unknown preload mode ${service.preload}")
} ?: continue
if (isServicePreloadingCancelled) {
return
}
scope.launch {
val activity = StartUpMeasurer.startActivity("${service.`interface`} preloading")
val job = preloadService(service) ?: return@launch
if (scope === syncScope) {
job.join()
activity.end()
}
else {
job.invokeOnCompletion { activity.end() }
}
}
}
}
postPreloadServices(modules, activityPrefix, syncScope, onlyIfAwait)
}
protected open fun postPreloadServices(modules: List<IdeaPluginDescriptorImpl>,
activityPrefix: String,
syncScope: CoroutineScope,
onlyIfAwait: Boolean) {
}
@OptIn(ExperimentalCoroutinesApi::class)
protected open suspend fun preloadService(service: ServiceDescriptor): Job? {
val adapter = componentKeyToAdapter.get(service.getInterface()) as ServiceComponentAdapter? ?: return null
val deferred = adapter.getInstanceAsync<Any>(componentManager = this, keyClass = null)
if (deferred.isCompleted) {
val instance = deferred.getCompleted()
val implClass = instance.javaClass
// well, we don't know the interface class, so, we cannot add any service to a hot cache
if (Modifier.isFinal(implClass.modifiers)) {
serviceInstanceHotCache.putIfAbsent(implClass, instance)
}
}
return deferred
}
override fun isDisposed(): Boolean {
return containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS
}
final override fun beforeTreeDispose() {
stopServicePreloading()
ApplicationManager.getApplication().assertIsWriteThread()
if (!(containerState.compareAndSet(ContainerState.COMPONENT_CREATED, ContainerState.DISPOSE_IN_PROGRESS) ||
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.DISPOSE_IN_PROGRESS))) {
// disposed in a recommended way using ProjectManager
return
}
// disposed directly using Disposer.dispose()
// we don't care that state DISPOSE_IN_PROGRESS is already set,
// and exceptions because of that possible - use ProjectManager to close and dispose project.
startDispose()
}
fun startDispose() {
stopServicePreloading()
Disposer.disposeChildren(this) { true }
val messageBus = messageBus
// There is a chance that someone will try to connect to the message bus and will get NPE because of disposed connection disposable,
// because the container state is not yet set to DISPOSE_IN_PROGRESS.
// So, 1) dispose connection children 2) set state DISPOSE_IN_PROGRESS 3) dispose connection
messageBus?.disposeConnectionChildren()
containerState.set(ContainerState.DISPOSE_IN_PROGRESS)
messageBus?.disposeConnection()
}
override fun dispose() {
if (!containerState.compareAndSet(ContainerState.DISPOSE_IN_PROGRESS, ContainerState.DISPOSED)) {
throw IllegalStateException("Expected current state is DISPOSE_IN_PROGRESS, but actual state is ${containerState.get()} ($this)")
}
coroutineScope?.cancel("ComponentManagerImpl.dispose is called")
// dispose components and services
Disposer.dispose(serviceParentDisposable)
// release references to the service instances
componentKeyToAdapter.clear()
componentAdapters.clear()
serviceInstanceHotCache.clear()
messageBus?.let {
// Must be after disposing of serviceParentDisposable, because message bus disposes child buses, so, we must dispose all services first.
// For example, service ModuleManagerImpl disposes modules; each module, in turn, disposes module's message bus (child bus of application).
Disposer.dispose(it)
this.messageBus = null
}
if (!containerState.compareAndSet(ContainerState.DISPOSED, ContainerState.DISPOSE_COMPLETED)) {
throw IllegalStateException("Expected current state is DISPOSED, but actual state is ${containerState.get()} ($this)")
}
componentConfigCount = -1
}
fun stopServicePreloading() {
isServicePreloadingCancelled = true
}
@Deprecated("Deprecated in Java")
@Suppress("DEPRECATION")
final override fun getComponent(name: String): BaseComponent? {
checkState()
for (componentAdapter in componentKeyToAdapter.values) {
if (componentAdapter is MyComponentAdapter) {
val instance = componentAdapter.getInitializedInstance()
if (instance is BaseComponent && name == instance.componentName) {
return instance
}
}
}
return null
}
final override fun <T : Any> getServiceByClassName(serviceClassName: String): T? {
checkState()
val adapter = componentKeyToAdapter.get(serviceClassName) as ServiceComponentAdapter?
return adapter?.getInstance(this, keyClass = null)
}
open fun isServiceSuitable(descriptor: ServiceDescriptor): Boolean {
return descriptor.client == null
}
protected open fun isComponentSuitable(componentConfig: ComponentConfig): Boolean {
val options = componentConfig.options ?: return true
return !java.lang.Boolean.parseBoolean(options.get("internal")) || ApplicationManager.getApplication().isInternal
}
final override fun getDisposed(): Condition<*> = Condition<Any?> { isDisposed }
fun processInitializedComponentsAndServices(processor: (Any) -> Unit) {
for (adapter in componentKeyToAdapter.values) {
if (adapter is BaseComponentAdapter) {
processor(adapter.getInitializedInstance() ?: continue)
}
else if (adapter is LightServiceComponentAdapter) {
processor(adapter.getComponentInstance(null))
}
}
}
fun processAllImplementationClasses(processor: (componentClass: Class<*>, plugin: PluginDescriptor?) -> Unit) {
for (adapter in componentKeyToAdapter.values) {
if (adapter is ServiceComponentAdapter) {
val aClass = try {
adapter.getImplementationClass()
}
catch (e: Throwable) {
// well, the component is registered, but the required jar is not added to the classpath (community edition or junior IDE)
LOG.warn(e)
continue
}
processor(aClass, adapter.pluginDescriptor)
}
else {
val pluginDescriptor = if (adapter is BaseComponentAdapter) adapter.pluginDescriptor else null
if (pluginDescriptor != null) {
val aClass = try {
adapter.componentImplementation
}
catch (e: Throwable) {
LOG.warn(e)
continue
}
processor(aClass, pluginDescriptor)
}
}
}
}
internal fun getComponentAdapter(keyClass: Class<*>): ComponentAdapter? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.get(keyClass) ?: componentKeyToAdapter.get(keyClass.name)
return if (adapter == null && parent != null) parent.getComponentAdapter(keyClass) else adapter
}
fun unregisterComponent(componentKey: Class<*>): ComponentAdapter? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.remove(componentKey) ?: return null
componentAdapters.remove(adapter as MyComponentAdapter)
serviceInstanceHotCache.remove(componentKey)
return adapter
}
final override fun getComponentInstance(componentKey: Any): Any? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.get(componentKey)
?: if (componentKey is Class<*>) componentKeyToAdapter.get(componentKey.name) else null
return if (adapter == null) parent?.getComponentInstance(componentKey) else adapter.getComponentInstance(this)
}
final override fun getComponentInstanceOfType(componentType: Class<*>): Any? {
throw UnsupportedOperationException("Do not use getComponentInstanceOfType()")
}
@TestOnly
fun registerComponentInstance(key: Class<*>, instance: Any) {
check(getApplication()!!.isUnitTestMode)
assertComponentsSupported()
val implClass = instance::class.java
val newAdapter = MyComponentAdapter(componentKey = key,
implementationClassName = implClass.name,
pluginDescriptor = fakeCorePluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(value = instance),
implementationClass = implClass)
if (componentKeyToAdapter.putIfAbsent(newAdapter.componentKey, newAdapter) != null) {
throw IllegalStateException("Key ${newAdapter.componentKey} duplicated")
}
componentAdapters.add(newAdapter)
}
private fun assertComponentsSupported() {
if (!isComponentSupported) {
error("components aren't support")
}
}
// project level extension requires Project as constructor argument, so, for now, constructor injection is disabled only for app level
final override fun isInjectionForExtensionSupported() = parent != null
internal fun getComponentAdapterOfType(componentType: Class<*>): ComponentAdapter? {
componentKeyToAdapter.get(componentType)?.let {
return it
}
for (adapter in componentAdapters.getImmutableSet()) {
val descendant = adapter.componentImplementation
if (componentType === descendant || componentType.isAssignableFrom(descendant)) {
return adapter
}
}
return null
}
fun <T : Any> processInitializedComponents(aClass: Class<T>, processor: (T, PluginDescriptor) -> Unit) {
// we must use instances only from our adapter (could be service or something else).
for (adapter in componentAdapters.getImmutableSet()) {
val component = adapter.getInitializedInstance()
if (component != null && aClass.isAssignableFrom(component.javaClass)) {
@Suppress("UNCHECKED_CAST")
processor(component as T, adapter.pluginDescriptor)
}
}
}
fun <T : Any> collectInitializedComponents(aClass: Class<T>): List<T> {
// we must use instances only from our adapter (could be service or something else).
val result = mutableListOf<T>()
for (adapter in componentAdapters.getImmutableSet()) {
val component = adapter.getInitializedInstance()
if (component != null && aClass.isAssignableFrom(component.javaClass)) {
@Suppress("UNCHECKED_CAST")
result.add(component as T)
}
}
return result
}
final override fun getActivityCategory(isExtension: Boolean): ActivityCategory {
return when {
parent == null -> if (isExtension) ActivityCategory.APP_EXTENSION else ActivityCategory.APP_SERVICE
parent.parent == null -> if (isExtension) ActivityCategory.PROJECT_EXTENSION else ActivityCategory.PROJECT_SERVICE
else -> if (isExtension) ActivityCategory.MODULE_EXTENSION else ActivityCategory.MODULE_SERVICE
}
}
final override fun hasComponent(componentKey: Class<*>): Boolean {
val adapter = componentKeyToAdapter.get(componentKey) ?: componentKeyToAdapter.get(componentKey.name)
return adapter != null || (parent != null && parent.hasComponent(componentKey))
}
@Deprecated(message = "Use extensions", level = DeprecationLevel.ERROR)
final override fun <T : Any> getComponents(baseClass: Class<T>): Array<T> {
checkState()
val result = mutableListOf<T>()
for (componentAdapter in componentAdapters.getImmutableSet()) {
val implementationClass = componentAdapter.getImplementationClass()
if (baseClass === implementationClass || baseClass.isAssignableFrom(implementationClass)) {
val instance = componentAdapter.getInstance<T>(componentManager = this, keyClass = null, createIfNeeded = false)
if (instance != null) {
result.add(instance)
}
}
}
return ArrayUtil.toObjectArray(result, baseClass)
}
final override fun isSuitableForOs(os: ExtensionDescriptor.Os): Boolean {
return when (os) {
ExtensionDescriptor.Os.mac -> SystemInfoRt.isMac
ExtensionDescriptor.Os.linux -> SystemInfoRt.isLinux
ExtensionDescriptor.Os.windows -> SystemInfoRt.isWindows
ExtensionDescriptor.Os.unix -> SystemInfoRt.isUnix
ExtensionDescriptor.Os.freebsd -> SystemInfoRt.isFreeBSD
else -> throw IllegalArgumentException("Unknown OS '$os'")
}
}
}
/**
* A linked hash set that's copied on write operations.
*/
private class LinkedHashSetWrapper<T : Any> {
private val lock = Any()
@Volatile
private var immutableSet: Set<T>? = null
private var synchronizedSet = LinkedHashSet<T>()
fun add(element: T) {
synchronized(lock) {
if (!synchronizedSet.contains(element)) {
copySyncSetIfExposedAsImmutable().add(element)
}
}
}
fun remove(element: T) {
synchronized(lock) { copySyncSetIfExposedAsImmutable().remove(element) }
}
fun replace(old: T, new: T) {
synchronized(lock) {
val set = copySyncSetIfExposedAsImmutable()
set.remove(old)
set.add(new)
}
}
private fun copySyncSetIfExposedAsImmutable(): LinkedHashSet<T> {
if (immutableSet != null) {
immutableSet = null
synchronizedSet = LinkedHashSet(synchronizedSet)
}
return synchronizedSet
}
fun replace(element: T) {
synchronized(lock) {
val set = copySyncSetIfExposedAsImmutable()
set.remove(element)
set.add(element)
}
}
fun clear() {
synchronized(lock) {
immutableSet = null
synchronizedSet = LinkedHashSet()
}
}
fun getImmutableSet(): Set<T> {
var result = immutableSet
if (result == null) {
synchronized(lock) {
result = immutableSet
if (result == null) {
// Expose the same set as immutable. It should never be modified again. Next add/remove operations will copy synchronizedSet
result = Collections.unmodifiableSet(synchronizedSet)
immutableSet = result
}
}
}
return result!!
}
}
private fun createPluginExceptionIfNeeded(error: Throwable, pluginId: PluginId): RuntimeException {
return if (error is PluginException) error else PluginException(error, pluginId)
}
fun handleComponentError(t: Throwable, componentClassName: String?, pluginId: PluginId?) {
if (t is StartupAbortedException) {
throw t
}
val app = ApplicationManager.getApplication()
if (app != null && app.isUnitTestMode) {
throw t
}
var effectivePluginId = pluginId
if (effectivePluginId == null || PluginManagerCore.CORE_ID == effectivePluginId) {
if (componentClassName != null) {
effectivePluginId = PluginManager.getPluginByClassNameAsNoAccessToClass(componentClassName)
}
}
if (effectivePluginId != null && PluginManagerCore.CORE_ID != effectivePluginId) {
throw StartupAbortedException("Fatal error initializing plugin $effectivePluginId", PluginException(t, effectivePluginId))
}
else {
throw StartupAbortedException("Fatal error initializing '$componentClassName'", t)
}
}
private fun doLoadClass(name: String, pluginDescriptor: PluginDescriptor): Class<*> {
// maybe null in unit tests
val classLoader = pluginDescriptor.pluginClassLoader ?: ComponentManagerImpl::class.java.classLoader
if (classLoader is PluginAwareClassLoader) {
return classLoader.tryLoadingClass(name, true) ?: throw ClassNotFoundException("$name $classLoader")
}
else {
return classLoader.loadClass(name)
}
}
private class LightServiceComponentAdapter(private val initializedInstance: Any) : ComponentAdapter {
override fun getComponentKey(): String = initializedInstance.javaClass.name
override fun getComponentImplementation() = initializedInstance.javaClass
override fun getComponentInstance(container: PicoContainer?) = initializedInstance
override fun toString() = componentKey
}
private inline fun executeRegisterTask(mainPluginDescriptor: IdeaPluginDescriptorImpl,
crossinline task: (IdeaPluginDescriptorImpl) -> Unit) {
task(mainPluginDescriptor)
executeRegisterTaskForOldContent(mainPluginDescriptor, task)
} | apache-2.0 | 8fe9926ec4a76fd830a94da3ca85db20 | 38.007732 | 215 | 0.694148 | 5.243288 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ArrayInitializerConversion.kt | 6 | 4081 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.toArgumentList
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.*
import org.jetbrains.kotlin.resolve.ArrayFqNames
class ArrayInitializerConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
var newElement = element
if (element is JKJavaNewArray) {
val primitiveArrayType = element.type.type as? JKJavaPrimitiveType
val arrayConstructorName =
if (primitiveArrayType != null)
ArrayFqNames.PRIMITIVE_TYPE_TO_ARRAY[PrimitiveType.valueOf(primitiveArrayType.jvmPrimitiveType.name)]!!.asString()
else
ArrayFqNames.ARRAY_OF_FUNCTION.asString()
val typeArguments =
if (primitiveArrayType == null) JKTypeArgumentList(listOf(element::type.detached()))
else JKTypeArgumentList()
newElement = JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.$arrayConstructorName"),
element.initializer.also { element.initializer = emptyList() }.toArgumentList(),
typeArguments
)
} else if (element is JKJavaNewEmptyArray) {
newElement = buildArrayInitializer(
element.initializer.also { element.initializer = emptyList() }, element.type.type
)
}
return recurse(newElement)
}
private fun buildArrayInitializer(dimensions: List<JKExpression>, type: JKType): JKExpression {
if (dimensions.size == 1) {
return if (type !is JKJavaPrimitiveType) {
JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.arrayOfNulls"),
JKArgumentList(dimensions[0]),
JKTypeArgumentList(listOf(JKTypeElement(type)))
)
} else {
JKNewExpression(
symbolProvider.provideClassSymbol(type.arrayFqName()),
JKArgumentList(dimensions[0]),
JKTypeArgumentList(emptyList())
)
}
}
if (dimensions[1] !is JKStubExpression) {
val arrayType = dimensions.drop(1).fold(type) { currentType, _ ->
JKJavaArrayType(currentType)
}
return JKNewExpression(
symbolProvider.provideClassSymbol("kotlin.Array"),
JKArgumentList(
dimensions[0],
JKLambdaExpression(
JKExpressionStatement(buildArrayInitializer(dimensions.subList(1, dimensions.size), type)),
emptyList()
)
),
JKTypeArgumentList(listOf(JKTypeElement(arrayType)))
)
}
var resultType = JKClassType(
symbolProvider.provideClassSymbol(type.arrayFqName()),
if (type is JKJavaPrimitiveType) emptyList() else listOf(type),
Nullability.Default
)
for (i in 0 until dimensions.size - 2) {
resultType = JKClassType(
symbolProvider.provideClassSymbol(StandardNames.FqNames.array.toSafe()),
listOf(resultType),
Nullability.Default
)
}
return JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.arrayOfNulls"),
JKArgumentList(dimensions[0]),
JKTypeArgumentList(listOf(JKTypeElement(resultType)))
)
}
}
| apache-2.0 | 8f944b9eb91fcaf2234ad69124453d02 | 43.846154 | 158 | 0.617496 | 5.805121 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineActionHandler.kt | 1 | 2749 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.inline
import com.intellij.lang.Language
import com.intellij.lang.findUsages.DescriptiveNameUtil
import com.intellij.lang.refactoring.InlineActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtElement
abstract class KotlinInlineActionHandler : InlineActionHandler() {
override fun isEnabledForLanguage(language: Language) = language == KotlinLanguage.INSTANCE
final override fun canInlineElement(element: PsiElement): Boolean {
val kotlinElement = unwrapKotlinElement(element) ?: return false
return canInlineKotlinElement(kotlinElement)
}
final override fun inlineElement(project: Project, editor: Editor?, element: PsiElement) {
val kotlinElement = unwrapKotlinElement(element) ?: error("Kotlin element not found")
KotlinInlineRefactoringFUSCollector.log(elementFrom = kotlinElement, languageTo = KotlinLanguage.INSTANCE, isCrossLanguage = false)
inlineKotlinElement(project, editor, kotlinElement)
}
override fun getActionName(element: PsiElement?): String = refactoringName
abstract fun canInlineKotlinElement(element: KtElement): Boolean
abstract fun inlineKotlinElement(project: Project, editor: Editor?, element: KtElement)
abstract val refactoringName: @NlsContexts.DialogTitle String
open val helpId: String? = null
fun showErrorHint(project: Project, editor: Editor?, @NlsContexts.DialogMessage message: String) {
CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId)
}
fun checkSources(project: Project, editor: Editor?, declaration: KtElement): Boolean = !declaration.containingKtFile.isCompiled.also {
if (it) {
val declarationName = DescriptiveNameUtil.getDescriptiveName(declaration)
showErrorHint(
project,
editor,
KotlinBundle.message("error.hint.text.cannot.inline.0.from.a.decompiled.file", declarationName)
)
}
}
}
private fun unwrapKotlinElement(element: PsiElement): KtElement? {
val ktElement = element.unwrapped as? KtElement
return ktElement?.navigationElement as? KtElement ?: ktElement
}
| apache-2.0 | 5b05c1988e57985f9d5adfd25b2a9eb4 | 46.396552 | 158 | 0.76355 | 4.865487 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SortModifiersInspection.kt | 1 | 3942 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotation
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.addRemoveModifier.sortModifiers
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class SortModifiersInspection : AbstractApplicabilityBasedInspection<KtModifierList>(
KtModifierList::class.java
), CleanupLocalInspectionTool {
override fun isApplicable(element: KtModifierList): Boolean {
val modifiers = element.modifierKeywordTokens()
if (modifiers.isEmpty()) return false
val sortedModifiers = sortModifiers(modifiers)
if (modifiers == sortedModifiers && !element.modifiersBeforeAnnotations()) return false
return true
}
override fun inspectionHighlightRangeInElement(element: KtModifierList): TextRange? {
val modifierElements = element.allChildren.toList()
val startElement = modifierElements.firstOrNull { it.node.elementType is KtModifierKeywordToken } ?: return null
val endElement = modifierElements.lastOrNull { it.node.elementType is KtModifierKeywordToken } ?: return null
return TextRange(startElement.startOffset, endElement.endOffset).shiftLeft(element.startOffset)
}
override fun inspectionText(element: KtModifierList) =
if (element.modifiersBeforeAnnotations()) KotlinBundle.message("modifiers.should.follow.annotations") else KotlinBundle.message("non.canonical.modifiers.order")
override val defaultFixText get() = KotlinBundle.message("sort.modifiers")
override fun applyTo(element: KtModifierList, project: Project, editor: Editor?) {
val owner = element.parent as? KtModifierListOwner ?: return
val sortedModifiers = sortModifiers(element.modifierKeywordTokens())
val existingModifiers = sortedModifiers.filter { owner.hasModifier(it) }
existingModifiers.forEach { owner.removeModifier(it) }
// We add visibility / modality modifiers after all others,
// because they can be redundant or not depending on others (e.g. override)
existingModifiers
.partition { it in KtTokens.VISIBILITY_MODIFIERS || it in KtTokens.MODALITY_MODIFIERS }
.let { it.second + it.first }
.forEach { owner.addModifier(it) }
}
private fun KtModifierList.modifierKeywordTokens(): List<KtModifierKeywordToken> {
return allChildren.mapNotNull { it.node.elementType as? KtModifierKeywordToken }.toList()
}
private fun KtModifierList.modifiersBeforeAnnotations(): Boolean {
val modifierElements = this.allChildren.toList()
var modifiersBeforeAnnotations = false
var seenModifiers = false
for (modifierElement in modifierElements) {
if (modifierElement.node.elementType is KtModifierKeywordToken) {
seenModifiers = true
} else if (seenModifiers && (modifierElement is KtAnnotationEntry || modifierElement is KtAnnotation)) {
modifiersBeforeAnnotations = true
}
}
return modifiersBeforeAnnotations
}
}
| apache-2.0 | 7314e14075530b64017e07502e20b438 | 51.56 | 168 | 0.755454 | 5.186842 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/UselessCallOnNotNullInspection.kt | 1 | 4188 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.collections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.quickfix.ReplaceWithDotCallFix
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.util.getType
class UselessCallOnNotNullInspection : AbstractUselessCallInspection() {
override val uselessFqNames = mapOf(
"kotlin.collections.orEmpty" to deleteConversion,
"kotlin.sequences.orEmpty" to deleteConversion,
"kotlin.text.orEmpty" to deleteConversion,
"kotlin.text.isNullOrEmpty" to Conversion("isEmpty"),
"kotlin.text.isNullOrBlank" to Conversion("isBlank"),
"kotlin.collections.isNullOrEmpty" to Conversion("isEmpty")
)
override val uselessNames = uselessFqNames.keys.toShortNames()
override fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
context: BindingContext,
conversion: Conversion
) {
val newName = conversion.replacementName
val safeExpression = expression as? KtSafeQualifiedExpression
val notNullType = expression.receiverExpression.isNotNullType(context)
val defaultRange =
TextRange(expression.operationTokenNode.startOffset, calleeExpression.endOffset).shiftRight(-expression.startOffset)
if (newName != null && (notNullType || safeExpression != null)) {
val fixes = listOf(RenameUselessCallFix(newName)) + listOfNotNull(safeExpression?.let {
IntentionWrapper(ReplaceWithDotCallFix(safeExpression))
})
val descriptor = holder.manager.createProblemDescriptor(
expression,
defaultRange,
KotlinBundle.message("call.on.not.null.type.may.be.reduced"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
*fixes.toTypedArray()
)
holder.registerProblem(descriptor)
} else if (notNullType) {
val descriptor = holder.manager.createProblemDescriptor(
expression,
defaultRange,
KotlinBundle.message("useless.call.on.not.null.type"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
RemoveUselessCallFix()
)
holder.registerProblem(descriptor)
} else if (safeExpression != null) {
holder.registerProblem(
safeExpression.operationTokenNode.psi,
KotlinBundle.message("this.call.is.useless.with"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(ReplaceWithDotCallFix(safeExpression))
)
}
}
private fun KtExpression.isNotNullType(context: BindingContext): Boolean {
val type = getType(context) ?: return false
val dataFlowValueFactory = getResolutionFacade().dataFlowValueFactory
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, findModuleDescriptor())
val stableNullability = context.getDataFlowInfoBefore(this).getStableNullability(dataFlowValue)
return !stableNullability.canBeNull()
}
}
| apache-2.0 | 0376870c9afd4e2a77fb5949e51d341a | 47.137931 | 158 | 0.716094 | 5.328244 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/model/LyricsModel.kt | 1 | 810 | package com.kelsos.mbrc.model
import com.kelsos.mbrc.data.LyricsPayload
import com.kelsos.mbrc.events.bus.RxBus
import com.kelsos.mbrc.events.ui.LyricsUpdatedEvent
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LyricsModel
@Inject
constructor(private val bus: RxBus) {
var lyrics: String = ""
set(value) {
if (field == value) {
return
}
field = value.replace("<p>", "\r\n")
.replace("<br>", "\n")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("&", "&")
.replace("<p>", "\r\n")
.replace("<br>", "\n")
.trim { it <= ' ' }
bus.post(LyricsUpdatedEvent(field))
}
var status: Int = LyricsPayload.NOT_FOUND
}
| gpl-3.0 | 0dc220231b2efa9a9ef1616e8d322ec2 | 22.823529 | 51 | 0.565432 | 3.552632 | false | false | false | false |
hermantai/samples | android/jetpack/PlayDataBinding/app/src/main/java/com/gmail/htaihm/playdatabinding/MainActivity.kt | 1 | 1160 | package com.gmail.htaihm.playdatabinding
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
/**
* Reference: http://imakeanapp.com/android-jetpack-data-binding/
*
* Demo: data binding, binding adapters, observables
*/
class MainActivity : AppCompatActivity(), HeroesAdapter.OnHeroClickListener {
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.heroes_list)
recyclerView.layoutManager = LinearLayoutManager(this)
val repository = HeroesRepository.getInstance(applicationContext)
val heroes = repository.fetchHeroes()
val adapter = HeroesAdapter(heroes, this)
recyclerView.adapter = adapter
}
override fun onHeroClick(hero: Hero) {
Log.d("MainActivity", "Clicked Hero: ${hero.name}")
startActivity(HeroActivity.createIntent(this, hero.id))
}
}
| apache-2.0 | 2344602636c0c6c194461e5d24cf0a94 | 30.351351 | 77 | 0.738793 | 4.444444 | false | false | false | false |
WeAreFrancis/auth-service | src/main/kotlin/com/wearefrancis/auth/security/UserPermissionEvaluator.kt | 1 | 2114 | package com.wearefrancis.auth.security
import com.wearefrancis.auth.domain.User
import com.wearefrancis.auth.repository.UserRepository
import org.springframework.security.access.PermissionEvaluator
import org.springframework.security.core.Authentication
import java.io.Serializable
import java.util.*
class UserPermissionEvaluator(
private val userRepository: UserRepository
): PermissionEvaluator {
override fun hasPermission(authentication: Authentication?, targetDomainObject: Any?, permission: Any?): Boolean {
throw UnsupportedOperationException()
}
override fun hasPermission(
authentication: Authentication?, targetId: Serializable?, targetType: String?, permission: Any?
): Boolean {
val currentUser = when (authentication?.principal) {
is User -> authentication.principal as User
else -> null
}
return when (targetType) {
USER_TARGET_TYPE -> when (permission) {
CHANGE_ROLE_PERMISSION -> currentUser!!.role == User.Role.SUPER_ADMIN
&& currentUser.id != targetId
CREATE_PERMISSION -> currentUser == null
|| currentUser.role in User.Role.ADMIN..User.Role.SUPER_ADMIN
DELETE_PERMISSION -> currentUser!!.id == targetId
|| currentUser.role == User.Role.SUPER_ADMIN
ENABLE_PERMISSION -> currentUser!!.role in User.Role.ADMIN..User.Role.SUPER_ADMIN
LOCK_PERMISSION -> currentUser!!.role in User.Role.ADMIN..User.Role.SUPER_ADMIN
&& currentUser.id != targetId
&& !userRepository.existsByIdAndRole(targetId as UUID, User.Role.SUPER_ADMIN)
UPDATE_PERMISSION -> currentUser!!.id == targetId
|| currentUser.role in User.Role.ADMIN..User.Role.SUPER_ADMIN
else -> throw IllegalArgumentException("Invalid permission: $permission")
}
else -> throw IllegalArgumentException("Invalid target type: $targetType")
}
}
} | apache-2.0 | 6221e4a5dcb27994121f822427c26a22 | 48.186047 | 118 | 0.640019 | 5.392857 | false | false | false | false |
spinnaker/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RestartStageHandlerTest.kt | 1 | 19263 | /*
* Copyright 2017 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.q.handler
import com.netflix.spinnaker.orca.DefaultStageResolver
import com.netflix.spinnaker.orca.NoOpTaskImplementationResolver
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.RestartStage
import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.buildAfterStages
import com.netflix.spinnaker.orca.q.buildBeforeStages
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.pending.PendingExecutionService
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.orca.q.stageWithNestedSynthetics
import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.atLeast
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import java.time.temporal.ChronoUnit.HOURS
import java.time.temporal.ChronoUnit.MINUTES
import kotlin.collections.contains
import kotlin.collections.filter
import kotlin.collections.first
import kotlin.collections.flatMap
import kotlin.collections.forEach
import kotlin.collections.listOf
import kotlin.collections.map
import kotlin.collections.mapOf
import kotlin.collections.set
import kotlin.collections.setOf
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.test.web.client.ExpectedCount.once
import rx.Observable
object RestartStageHandlerTest : SubjectSpek<RestartStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val pendingExecutionService: PendingExecutionService = mock()
val clock = fixedClock()
subject(GROUP) {
RestartStageHandler(
queue,
repository,
DefaultStageDefinitionBuilderFactory(
DefaultStageResolver(
StageDefinitionBuildersProvider(
listOf(
singleTaskStage,
stageWithSyntheticBefore,
stageWithNestedSynthetics
)
)
)
),
pendingExecutionService,
clock
)
}
fun resetMocks() = reset(queue, repository)
ExecutionStatus
.values()
.filter { !it.isComplete && it != NOT_STARTED }
.forEach { incompleteStatus ->
describe("trying to restart a $incompleteStatus stage") {
val pipeline = pipeline {
application = "foo"
status = RUNNING
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
stage {
refId = "1"
singleTaskStage.plan(this)
status = incompleteStatus
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "[email protected]")
beforeGroup {
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not modify the stage status") {
verify(repository, never()).store(any())
}
it("does not run the stage") {
verify(queue, never()).push(any<StartStage>())
}
// TODO: should probably queue some kind of error
}
}
setOf(TERMINAL, SUCCEEDED).forEach { stageStatus ->
describe("restarting a $stageStatus stage") {
val pipeline = pipeline {
application = "foo"
status = stageStatus
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
stage {
refId = "2"
requisiteStageRefIds = listOf("1")
stageWithNestedSynthetics.plan(this)
stageWithNestedSynthetics.buildAfterStages(this)
status = stageStatus
startTime = clock.instant().minus(59, MINUTES).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
context["exception"] = "o noes"
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("2").id, "[email protected]")
beforeGroup {
stageWithSyntheticBefore.plan(pipeline.stageByRef("2>1"))
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("resets the stage's status") {
verify(repository).storeStage(
check {
assertThat(it.id).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(NOT_STARTED)
assertThat(it.startTime).isNull()
assertThat(it.endTime).isNull()
}
)
}
it("removes the stage's tasks") {
verify(repository).storeStage(
check {
assertThat(it.tasks).isEmpty()
}
)
}
it("adds restart details to the stage context") {
verify(repository).storeStage(
check {
assertThat(it.context.keys).doesNotContain("exception")
assertThat(it.context["restartDetails"]).isEqualTo(
mapOf(
"restartedBy" to "[email protected]",
"restartTime" to clock.millis(),
"previousException" to "o noes"
)
)
}
)
}
it("removes the stage's synthetic stages") {
pipeline
.stages
.filter { it.parentStageId == message.stageId }
.map(StageExecution::getId)
.forEach {
verify(repository).removeStage(pipeline, it)
}
}
val nestedSyntheticStageIds = pipeline
.stages
.filter { it.parentStageId == message.stageId }
.map(StageExecution::getId)
it("removes the nested synthetic stages") {
assertThat(nestedSyntheticStageIds).isNotEmpty
pipeline
.stages
.filter { it.parentStageId in nestedSyntheticStageIds }
.map(StageExecution::getId)
.forEach {
verify(repository).removeStage(pipeline, it)
}
}
it("does not affect preceding stages' synthetic stages") {
setOf(pipeline.stageByRef("1").id)
.flatMap { stageId -> pipeline.stages.filter { it.parentStageId == stageId } }
.map { it.id }
.forEach {
verify(repository, never()).removeStage(any(), eq(it))
}
}
it("marks the execution as running") {
assertThat(pipeline.status).isEqualTo(RUNNING)
verify(repository).updateStatus(pipeline)
}
it("runs the stage") {
verify(queue).push(
check<StartStage> {
assertThat(it.executionType).isEqualTo(message.executionType)
assertThat(it.executionId).isEqualTo(message.executionId)
assertThat(it.application).isEqualTo(message.application)
assertThat(it.stageId).isEqualTo(message.stageId)
}
)
}
}
}
describe("restarting a SUCCEEDED stage with downstream stages") {
val pipeline = pipeline {
application = "foo"
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
singleTaskStage.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
stage {
refId = "2"
requisiteStageRefIds = listOf("1")
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(59, MINUTES).toEpochMilli()
endTime = clock.instant().minus(58, MINUTES).toEpochMilli()
}
stage {
refId = "3"
requisiteStageRefIds = listOf("2")
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(58, MINUTES).toEpochMilli()
endTime = clock.instant().minus(57, MINUTES).toEpochMilli()
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "[email protected]")
beforeGroup {
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("removes downstream stages' tasks") {
val downstreamStageIds = setOf("2", "3").map { pipeline.stageByRef(it).id }
argumentCaptor<StageExecutionImpl>().apply {
verify(repository, atLeast(2)).storeStage(capture())
downstreamStageIds.forEach {
assertThat(allValues.map { it.id }).contains(it)
}
allValues.forEach {
assertThat(it.tasks).isEmpty()
}
}
}
it("removes downstream stages' synthetic stages") {
setOf("2", "3")
.map { pipeline.stageByRef(it).id }
.flatMap { stageId -> pipeline.stages.filter { it.parentStageId == stageId } }
.map { it.id }
.forEach {
verify(repository).removeStage(pipeline, it)
}
}
}
describe("restarting a SUCCEEDED stage with a downstream join") {
val pipeline = pipeline {
application = "foo"
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
singleTaskStage.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
stage {
refId = "2"
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(59, MINUTES).toEpochMilli()
endTime = clock.instant().minus(58, MINUTES).toEpochMilli()
}
stage {
refId = "3"
requisiteStageRefIds = listOf("1", "2")
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(59, MINUTES).toEpochMilli()
endTime = clock.instant().minus(58, MINUTES).toEpochMilli()
}
stage {
refId = "4"
requisiteStageRefIds = listOf("3")
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(58, MINUTES).toEpochMilli()
endTime = clock.instant().minus(57, MINUTES).toEpochMilli()
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "[email protected]")
beforeGroup {
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("removes join stages' tasks") {
val downstreamStageIds = setOf("1", "3", "4").map { pipeline.stageByRef(it).id }
argumentCaptor<StageExecutionImpl>().apply {
verify(repository, times(3)).storeStage(capture())
assertThat(allValues.map { it.id }).isEqualTo(downstreamStageIds)
allValues.forEach {
assertThat(it.tasks).isEmpty()
}
}
}
it("removes join stages' synthetic stages") {
setOf("3", "4")
.map { pipeline.stageByRef(it).id }
.flatMap { stageId -> pipeline.stages.filter { it.parentStageId == stageId } }
.map { it.id }
.forEach {
verify(repository).removeStage(pipeline, it)
}
}
}
describe("restarting a synthetic stage restarts its parent") {
val pipeline = pipeline {
application = "foo"
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
stageWithSyntheticBefore.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
}
val syntheticStage = pipeline.stages.first { it.parentStageId == pipeline.stageByRef("1").id }
val message = RestartStage(pipeline.type, pipeline.id, "foo", syntheticStage.id, "[email protected]")
beforeGroup {
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("removes the original synthetic stage") {
verify(repository).removeStage(pipeline, syntheticStage.id)
}
it("runs the parent stage") {
verify(queue).push(
check<StartStage> {
assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1").id)
assertThat(it.stageId).isNotEqualTo(syntheticStage.id)
assertThat(it.stageId).isNotEqualTo(message.stageId)
assertThat(it.executionType).isEqualTo(message.executionType)
assertThat(it.executionId).isEqualTo(message.executionId)
assertThat(it.application).isEqualTo(message.application)
}
)
}
}
describe("restarting a SUCCEEDED stage that should queue") {
val pipeline = pipeline {
pipelineConfigId = "bar"
application = "foo"
status = SUCCEEDED
isLimitConcurrent = true
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
singleTaskStage.plan(this)
status = SUCCEEDED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "[email protected]")
beforeGroup {
val runningPipeline = pipeline {
pipelineConfigId = pipeline.pipelineConfigId
application = "foo"
status = RUNNING
}
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
whenever(repository.retrievePipelinesForPipelineConfigId(
pipeline.pipelineConfigId,
ExecutionRepository.ExecutionCriteria().setPageSize(2).setStatuses(RUNNING))) doReturn Observable.from(listOf(runningPipeline))
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("queues restart message") {
verify(pendingExecutionService).enqueue(pipeline.pipelineConfigId, message)
verify(queue, never()).push(any<StartStage>())
}
it("updates the pieline status to NOT_STARTED") {
assertThat(pipeline.status).isEqualTo(NOT_STARTED)
verify(repository).updateStatus(pipeline)
}
}
describe("restarting a NOT_STARTED execution does not queue") {
val pipeline = pipeline {
pipelineConfigId = "bar"
application = "foo"
status = NOT_STARTED
isLimitConcurrent = true
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(30, MINUTES).toEpochMilli()
stage {
refId = "1"
singleTaskStage.plan(this)
status = NOT_STARTED
startTime = clock.instant().minus(1, HOURS).toEpochMilli()
endTime = clock.instant().minus(59, MINUTES).toEpochMilli()
}
}
val message = RestartStage(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "[email protected]")
beforeGroup {
val runningPipeline = pipeline {
pipelineConfigId = pipeline.pipelineConfigId
application = "foo"
status = RUNNING
}
whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline
whenever(repository.retrievePipelinesForPipelineConfigId(
pipeline.pipelineConfigId,
ExecutionRepository.ExecutionCriteria().setPageSize(2).setStatuses(RUNNING))) doReturn Observable.from(listOf(runningPipeline))
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not queue any messages") {
verify(pendingExecutionService, never()).enqueue(pipeline.pipelineConfigId, message)
verify(queue, never()).push(any<StartStage>())
}
}
})
fun StageDefinitionBuilder.plan(stage: StageExecution) {
stage.type = type
buildTasks(stage, NoOpTaskImplementationResolver())
buildBeforeStages(stage)
}
| apache-2.0 | 3ca2804f5c214ffef4678c1449a599d0 | 34.023636 | 135 | 0.66215 | 4.665294 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/rate/RatePopupScheduler.kt | 1 | 1477 | package io.ipoli.android.common.rate
import android.preference.PreferenceManager
import com.evernote.android.job.Job
import com.evernote.android.job.JobRequest
import io.ipoli.android.Constants
import io.ipoli.android.common.view.asThemedWrapper
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.launch
import java.util.*
/**
* Created by Venelin Valkov <[email protected]>
* on 11/15/17.
*/
class RatePopupJob : Job() {
override fun onRunJob(params: Params): Result {
val pm = PreferenceManager.getDefaultSharedPreferences(context)
val shouldShowRateDialog = pm.getBoolean(Constants.KEY_SHOULD_SHOW_RATE_DIALOG, true)
val appRun = pm.getInt(Constants.KEY_APP_RUN_COUNT, 0)
val shouldShowRandom = Random().nextBoolean()
if (!shouldShowRateDialog || appRun <= 2 || !shouldShowRandom) {
return Result.SUCCESS
}
val c = context.asThemedWrapper()
GlobalScope.launch(Dispatchers.Main) {
RatePopup().show(c)
}
return Result.SUCCESS
}
companion object {
const val TAG = "job_rate_tag"
}
}
interface RatePopupScheduler {
fun schedule()
}
class AndroidRatePopupScheduler : RatePopupScheduler {
override fun schedule() {
JobRequest.Builder(RatePopupJob.TAG)
.setExact(5000)
.build()
.schedule()
}
} | gpl-3.0 | 63cd4b8e5d48dba86482df52fc50053e | 26.37037 | 93 | 0.689912 | 4.232092 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/inheritance/before/otherusage/main.kt | 12 | 1311 | package otheruse
import javapackage.one.JavaClassOne
fun a() {
JavaClassOne().a()
val d = JavaClassOne()
d.a()
d.let {
it.a()
}
d.also {
it.a()
}
with(d) {
a()
}
with(d) out@{
with(4) {
[email protected]()
}
}
}
fun a2() {
val d: JavaClassOne? = null
d?.a()
d?.let {
it.a()
}
d?.also {
it.a()
}
with(d) {
this?.a()
}
with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a3() {
val d: JavaClassOne? = null
val a1 = d?.a()
val a2 = d?.let {
it.a()
}
val a3 = d?.also {
it.a()
}
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a4() {
val d: JavaClassOne? = null
d?.a()?.dec()
val a2 = d?.let {
it.a()
}
a2?.toLong()
d?.also {
it.a()
}?.a()?.and(4)
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun JavaClassOne.b(): Int? = a()
fun JavaClassOne.c(): Int = this.a()
fun d(d: JavaClassOne) = d.a()
| apache-2.0 | f55090fd6fdc94863390bf985d521549 | 11.605769 | 52 | 0.369947 | 2.913333 | false | false | false | false |
jk1/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/slicer/GroovySliceProvider.kt | 3 | 3814 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.slicer
import com.intellij.ide.util.treeView.AbstractTreeStructure
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.slicer.*
import com.intellij.util.CommonProcessors
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
class GroovySliceProvider : SliceLanguageSupportProvider, SliceUsageTransformer {
object GroovySliceLeafEquality : SliceLeafEquality() {
override fun substituteElement(element: PsiElement): PsiElement = element.getGroovyReferenceTargetOrThis()
}
companion object {
private fun PsiElement.getGroovyReferenceTargetOrThis() = (this as? GrReferenceElement<*>)?.resolve() ?: this
fun getInstance(): GroovySliceProvider = LanguageSlicing.INSTANCE.forLanguage(GroovyLanguage) as GroovySliceProvider
}
override fun getExpressionAtCaret(atCaret: PsiElement?, dataFlowToThis: Boolean): PsiElement? {
val element = PsiTreeUtil.getParentOfType(atCaret, GrExpression::class.java, GrVariable::class.java)
if (dataFlowToThis && element is GrLiteral) return null
return element
}
override fun getElementForDescription(element: PsiElement): PsiElement = (element as? GrReferenceElement<*>)?.resolve() ?: element
override fun getRenderer(): GroovySliceUsageCellRenderer = GroovySliceUsageCellRenderer()
override fun createRootUsage(element: PsiElement, params: SliceAnalysisParams): SliceUsage {
return GroovySliceUsage(element, params)
}
override fun transform(sliceUsage: SliceUsage): Collection<SliceUsage>? {
if (sliceUsage is GroovySliceUsage) return null
val element = sliceUsage.element
val parent = sliceUsage.parent
if (sliceUsage.params.dataFlowToThis && element is GrMethod) {
return CommonProcessors.CollectProcessor<SliceUsage>().apply {
GroovySliceUsage.processMethodReturnValues(element, parent, this)
}.results
}
if (!(element is GrExpression || element is GrVariable)) return null
val parentUsage = sliceUsage.parent
val newUsage = if (parentUsage != null) GroovySliceUsage(element, parentUsage) else GroovySliceUsage(element, sliceUsage.params)
return listOf(newUsage)
}
fun createLeafAnalyzer(): SliceLeafAnalyzer = SliceLeafAnalyzer(GroovySliceLeafEquality, this)
override fun startAnalyzeLeafValues(structure: AbstractTreeStructure, finalRunnable: Runnable) {
createLeafAnalyzer().startAnalyzeValues(structure, finalRunnable)
}
override fun startAnalyzeNullness(structure: AbstractTreeStructure, finalRunnable: Runnable) {
}
override fun registerExtraPanelActions(group: DefaultActionGroup, builder: SliceTreeBuilder) {
if (builder.dataFlowToThis) {
group.add(GroupByLeavesAction(builder))
}
}
} | apache-2.0 | c7cd092721b62617901d3d637c940980 | 41.865169 | 132 | 0.786576 | 4.803526 | false | false | false | false |
KotlinBy/bkug.by | data/src/main/kotlin/by/bkug/data/Meetup8.kt | 1 | 2835 | package by.bkug.data
import org.intellij.lang.annotations.Language
@Language("markdown")
val meetup8 = """
Встреча нашего сообщества состоится 21 февраля, в [Space](http://eventspace.by).
## Программа:
### Приветственный кофе (18:40 - 19:00)
Вас ждут печеньки, чай и кофе.
### Ktor.io - Руслан Ибрагимов (19:00 - 19:40)
Когда речь заходит о Котлине, то многие считают что его ниша это Android. Немудрено, ведь больше всего шума именно вокруг него. А пока Kotlin хайпит на Android, JetBrains спокойно разрабатывает Ktor - фреймворк для написания асинхронных веб приложений. В своем докладе я расскажу про архитектуру и устройство ktor, написание клиента и сервера, а также покрою вопрос тестирования.
<img class="circle_150" src="https://bkug.by/wp-content/uploads/2017/12/ruslan_ibragimov.jpg" alt="Руслан Ибрагимов" />
Руслан Ибрагимов, full-stack разработчик, [ObjectStyle](https://www.objectstyle.com/).
### Kotlin/Native - Сергей Крюков (20:00 - 20:40)
Не все слышали, что вот уже почти год, как команда Kotlin работает над возможностью компиляции Kotlin в нативный исполняемый код. Да-да, никакой виртуальной машины!
В этом докладе я постараюсь приоткрыть завесу над этим направлением развития нашего любимого языка.
<img class="circle_150" src="https://bkug.by/wp-content/uploads/2017/12/siarhei_krukau.jpg" alt="Сергей Крюков" />
Сергей Крюков, пишет на Java чтобы оплачивать счета. Играется с Kotlin чтобы отдохнуть от этого.
* **Дата проведения**: 21 февраля
* **Время**: 19:00–21:00
* **Место проведения**: ул. Октябрьская, 16А – EventSpace. Парковка и вход через ул. Октябрьскую, 10б.
Для участия во встрече необходима предварительная [регистрация](https://goo.gl/forms/lApULtR32N17ZZe22).
Митап пройдет при поддержке [cyber • Fund](http://company.cyber.fund/).
[](http://company.cyber.fund/)
[huge_it_maps id="2"]
""".trimIndent()
| gpl-3.0 | f0e6f4c7e3db6c12e9bf17b19cf6013f | 42.066667 | 379 | 0.75645 | 2.160535 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Compression.kt | 1 | 7930 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.plugins.compression
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.util.logging.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
internal val LOGGER = KtorSimpleLogger("io.ktor.server.plugins.compression.Compression")
/**
* The default minimal content size to compress.
*/
internal const val DEFAULT_MINIMAL_COMPRESSION_SIZE: Long = 200L
private object ContentEncoding : Hook<suspend ContentEncoding.Context.(ApplicationCall) -> Unit> {
class Context(private val pipelineContext: PipelineContext<Any, ApplicationCall>) {
fun transformBody(block: (OutgoingContent) -> OutgoingContent?) {
val transformedContent = block(pipelineContext.subject as OutgoingContent)
if (transformedContent != null) {
pipelineContext.subject = transformedContent
}
}
}
override fun install(
pipeline: ApplicationCallPipeline,
handler: suspend Context.(ApplicationCall) -> Unit
) {
pipeline.sendPipeline.intercept(ApplicationSendPipeline.ContentEncoding) {
handler(Context(this), call)
}
}
}
/**
* A plugin that provides the capability to compress a response body.
* You can use different compression algorithms, including `gzip` and `deflate`,
* specify the required conditions for compressing data (such as a content type or response size),
* or even compress data based on specific request parameters.
*
* The example below shows how to compress JavaScript content using `gzip` with the specified priority:
* ```kotlin
* install(Compression) {
* gzip {
* priority = 0.9
* matchContentType(ContentType.Application.JavaScript)
* }
* }
* ```
*
* You can learn more from [Compression](https://ktor.io/docs/compression.html).
*/
public val Compression: RouteScopedPlugin<CompressionConfig> = createRouteScopedPlugin(
"Compression",
::CompressionConfig
) {
if (pluginConfig.encoders.none()) {
pluginConfig.default()
}
val options = pluginConfig.buildOptions()
val comparator = compareBy<Pair<CompressionEncoderConfig, HeaderValue>>(
{ it.second.quality },
{ it.first.priority }
).reversed()
on(ContentEncoding) { call ->
val acceptEncodingRaw = call.request.acceptEncoding()
if (acceptEncodingRaw == null) {
LOGGER.trace("Skip compression because no accept encoding provided.")
return@on
}
if (call.isCompressionSuppressed()) {
LOGGER.trace("Skip compression because it is suppressed.")
return@on
}
val encoders = parseHeaderValue(acceptEncodingRaw)
.filter { it.value == "*" || it.value in options.encoders }
.flatMap { header ->
when (header.value) {
"*" -> options.encoders.values.map { it to header }
else -> options.encoders[header.value]?.let { listOf(it to header) } ?: emptyList()
}
}
.sortedWith(comparator)
.map { it.first }
if (encoders.isEmpty()) {
LOGGER.trace("Skip compression because no encoders provided.")
return@on
}
transformBody { message ->
if (message is CompressedResponse) {
LOGGER.trace("Skip compression because it's already compressed.")
return@transformBody null
}
if (options.conditions.any { !it(call, message) }) {
LOGGER.trace("Skip compression because preconditions doesn't meet.")
return@transformBody null
}
val encodingHeader = message.headers[HttpHeaders.ContentEncoding]
if (encodingHeader != null) {
LOGGER.trace("Skip compression because content is already encoded.")
return@transformBody null
}
val encoderOptions = encoders.firstOrNull { encoder -> encoder.conditions.all { it(call, message) } }
if (encoderOptions == null) {
LOGGER.trace("Skip compression because no suitable encoder found.")
return@transformBody null
}
LOGGER.trace("Encoding body using ${encoderOptions.name}.")
return@transformBody when (message) {
is OutgoingContent.ReadChannelContent -> CompressedResponse(
message,
{ message.readFrom() },
encoderOptions.name,
encoderOptions.encoder
)
is OutgoingContent.WriteChannelContent -> {
CompressedWriteResponse(
message,
encoderOptions.name,
encoderOptions.encoder
)
}
is OutgoingContent.ByteArrayContent -> CompressedResponse(
message,
{ ByteReadChannel(message.bytes()) },
encoderOptions.name,
encoderOptions.encoder
)
is OutgoingContent.NoContent -> null
is OutgoingContent.ProtocolUpgrade -> null
}
}
}
}
private class CompressedResponse(
val original: OutgoingContent,
val delegateChannel: () -> ByteReadChannel,
val encoding: String,
val encoder: CompressionEncoder
) : OutgoingContent.ReadChannelContent() {
override fun readFrom() = encoder.compress(delegateChannel())
override val headers by lazy(LazyThreadSafetyMode.NONE) {
Headers.build {
appendFiltered(original.headers) { name, _ -> !name.equals(HttpHeaders.ContentLength, true) }
append(HttpHeaders.ContentEncoding, encoding)
}
}
override val contentType: ContentType? get() = original.contentType
override val status: HttpStatusCode? get() = original.status
override val contentLength: Long?
get() = original.contentLength?.let { encoder.predictCompressedLength(it) }?.takeIf { it >= 0 }
override fun <T : Any> getProperty(key: AttributeKey<T>) = original.getProperty(key)
override fun <T : Any> setProperty(key: AttributeKey<T>, value: T?) = original.setProperty(key, value)
}
private class CompressedWriteResponse(
val original: WriteChannelContent,
val encoding: String,
val encoder: CompressionEncoder
) : OutgoingContent.WriteChannelContent() {
override val headers by lazy(LazyThreadSafetyMode.NONE) {
Headers.build {
appendFiltered(original.headers) { name, _ -> !name.equals(HttpHeaders.ContentLength, true) }
append(HttpHeaders.ContentEncoding, encoding)
}
}
override val contentType: ContentType? get() = original.contentType
override val status: HttpStatusCode? get() = original.status
override val contentLength: Long?
get() = original.contentLength?.let { encoder.predictCompressedLength(it) }?.takeIf { it >= 0 }
override fun <T : Any> getProperty(key: AttributeKey<T>) = original.getProperty(key)
override fun <T : Any> setProperty(key: AttributeKey<T>, value: T?) = original.setProperty(key, value)
override suspend fun writeTo(channel: ByteWriteChannel) {
coroutineScope {
encoder.compress(channel, coroutineContext).use {
original.writeTo(this)
}
}
}
}
private fun ApplicationCall.isCompressionSuppressed() = SuppressionAttribute in attributes
| apache-2.0 | 4a495b8cedc208c5744afec036eb0741 | 36.761905 | 118 | 0.631904 | 4.946974 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/api/contentRegion.kt | 2 | 1899 | package imgui.api
import glm_.vec2.Vec2
import imgui.ImGui.contentRegionMaxAbs
// Content region
// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
interface contentRegion {
/** == GetContentRegionMax() - GetCursorPos()
*
* ~GetContentRegionAvail */
val contentRegionAvail: Vec2
get() = g.currentWindow!!.run { contentRegionMaxAbs - dc.cursorPos }
/** current content boundaries (typically window boundaries including scrolling, or current column boundaries), in
* windows coordinates
* FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
* ~GetContentRegionMax */
val contentRegionMax: Vec2
/** ~GetContentRegionMax */
get() {
val window = g.currentWindow!!
val mx = window.contentRegionRect.max - window.pos
if (window.dc.currentColumns != null || g.currentTable != null)
mx.x = window.workRect.max.x - window.pos.x
return mx
}
/** content boundaries min (roughly (0,0)-Scroll), in window coordinates
* ~GetWindowContentRegionMin */
val windowContentRegionMin: Vec2
get() = g.currentWindow!!.run { contentRegionRect.min - pos }
/** content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(),
* in window coordinates
* ~GetWindowContentRegionMax */
val windowContentRegionMax: Vec2
get() = g.currentWindow!!.run { contentRegionRect.max - pos }
/** ~GetWindowContentRegionWidth */
val windowContentRegionWidth: Float
get() = g.currentWindow!!.contentRegionRect.width
} | mit | a4953de9cd009c8a5e2596c2530ed4a4 | 41.222222 | 168 | 0.681411 | 4.375576 | false | false | false | false |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/fragment/generator/RegisterDialogFragment.kt | 1 | 1953 | package moe.pine.emoji.fragment.generator
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import com.squareup.otto.Subscribe
import moe.pine.emoji.R
import moe.pine.emoji.model.event.EmojiRegisteredEvent
import moe.pine.emoji.util.eventBus
import moe.pine.emoji.view.generator.RegisterDialogView
/**
* Fragment for register emoji
* Created by pine on May 13, 2017.
*/
class RegisterDialogFragment : DialogFragment() {
companion object {
private val PREVIEW_URI_KEY = "previewUri"
private val DOWNLOAD_URI_KEY = "downloadUri"
fun newInstance(previewUri: String, downloadUri: String): RegisterDialogFragment {
val fragment = RegisterDialogFragment()
val arguments = Bundle()
arguments.putString(PREVIEW_URI_KEY, previewUri)
arguments.putString(DOWNLOAD_URI_KEY, downloadUri)
fragment.arguments = arguments
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.eventBus.register(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val inflater = LayoutInflater.from(this.context)
val view = inflater.inflate(R.layout.dialog_register, null, false) as RegisterDialogView
view.previewUri = this.arguments!!.getString(PREVIEW_URI_KEY)
view.downloadUri = this.arguments!!.getString(DOWNLOAD_URI_KEY)
view.fragment = this
val dialog = AlertDialog.Builder(this.activity)
.setView(view)
.create()
return dialog
}
override fun onDestroyView() {
this.eventBus.unregister(this)
super.onDestroyView()
}
@Subscribe
fun onEmojiRegistered(event: EmojiRegisteredEvent) {
this.dismiss()
}
} | mit | d1ec65ac032f64505a1fe9f4772d108f | 31.566667 | 96 | 0.691244 | 4.552448 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/api/parametersStacks.kt | 1 | 11705 | package imgui.api
import glm_.f
import glm_.i
import glm_.max
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.contentRegionMaxAbs
import imgui.ImGui.currentWindow
import imgui.ImGui.defaultFont
import imgui.ImGui.popItemFlag
import imgui.ImGui.pushItemFlag
import imgui.ImGui.style
import imgui.font.Font
import imgui.internal.*
import imgui.internal.classes.ColorMod
import imgui.internal.classes.StyleMod
import imgui.internal.sections.NextItemDataFlag
import imgui.internal.sections.has
import imgui.internal.sections.or
import imgui.internal.sections.wo
import imgui.internal.sections.ItemFlag as If
// Parameters stacks (shared)
interface parametersStacks {
/** use NULL as a shortcut to push default font */
fun pushFont(font: Font = defaultFont) {
font.setCurrent()
g.fontStack.push(font)
g.currentWindow!!.drawList.pushTextureId(font.containerAtlas.texID)
}
fun popFont() {
g.currentWindow!!.drawList.popTextureId()
g.fontStack.pop()
(g.fontStack.lastOrNull() ?: defaultFont).setCurrent()
}
/** FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store
* the in-flight colors as ImU32
*
* modify a style color. always use this if you modify the style after NewFrame(). */
fun pushStyleColor(idx: Col, col: Int) {
val backup = ColorMod(idx, style.colors[idx])
g.colorStack.push(backup)
g.style.colors[idx] = col.vec4
}
fun pushStyleColor(idx: Col, col: Vec4) {
val backup = ColorMod(idx, style.colors[idx])
g.colorStack.push(backup)
style.colors[idx] = col
}
fun popStyleColor(count: Int = 1) = repeat(count) {
val backup = g.colorStack.pop()
style.colors[backup.col] put backup.backupValue
}
/** It'll throw error if wrong correspondence between idx and value type
* GStyleVarInfo
*
* modify a style float variable. always use this if you modify the style after NewFrame().
* modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). */
fun pushStyleVar(idx: StyleVar, value: Any) {
g.styleVarStack.push(StyleMod(idx).also {
when (idx) {
StyleVar.Alpha -> {
it.floats[0] = style.alpha
style.alpha = value as Float
}
StyleVar.WindowPadding -> {
style.windowPadding to it.floats
style.windowPadding put (value as Vec2)
}
StyleVar.WindowRounding -> {
it.floats[0] = style.windowRounding
style.windowRounding = value as Float
}
StyleVar.WindowBorderSize -> {
it.floats[0] = style.windowBorderSize
style.windowBorderSize = value as Float
}
StyleVar.WindowMinSize -> {
style.windowMinSize to it.ints
style.windowMinSize put (value as Vec2i)
}
StyleVar.WindowTitleAlign -> {
style.windowTitleAlign to it.floats
style.windowTitleAlign put (value as Vec2)
}
StyleVar.ChildRounding -> {
it.floats[0] = style.childRounding
style.childRounding = value as Float
}
StyleVar.ChildBorderSize -> {
it.floats[0] = style.childBorderSize
style.childBorderSize = value as Float
}
StyleVar.PopupRounding -> {
it.floats[0] = style.popupRounding
style.popupRounding = value as Float
}
StyleVar.PopupBorderSize -> {
it.floats[0] = style.popupBorderSize
style.popupBorderSize = value as Float
}
StyleVar.FramePadding -> {
style.framePadding to it.floats
style.framePadding put (value as Vec2)
}
StyleVar.FrameRounding -> {
it.floats[0] = style.frameRounding
style.frameRounding = value as Float
}
StyleVar.FrameBorderSize -> {
it.floats[0] = style.frameBorderSize
style.frameBorderSize = value as Float
}
StyleVar.ItemSpacing -> {
style.itemSpacing to it.floats
style.itemSpacing put (value as Vec2)
}
StyleVar.ItemInnerSpacing -> {
style.itemInnerSpacing to it.floats
style.itemInnerSpacing put (value as Vec2)
}
StyleVar.IndentSpacing -> {
it.floats[0] = style.indentSpacing
style.indentSpacing = value as Float
}
StyleVar.CellPadding -> {
style.cellPadding to it.floats
style.cellPadding put (value as Vec2)
}
StyleVar.ScrollbarSize -> {
it.floats[0] = style.scrollbarSize
style.scrollbarSize = value as Float
}
StyleVar.ScrollbarRounding -> {
it.floats[0] = style.scrollbarRounding
style.scrollbarRounding = value as Float
}
StyleVar.GrabMinSize -> {
it.floats[0] = style.grabMinSize
style.grabMinSize = value as Float
}
StyleVar.GrabRounding -> {
it.floats[0] = style.grabRounding
style.grabRounding = value as Float
}
StyleVar.TabRounding -> {
it.floats[0] = style.tabRounding
style.tabRounding = value as Float
}
StyleVar.ButtonTextAlign -> {
style.buttonTextAlign to it.floats
style.buttonTextAlign put (value as Vec2)
}
StyleVar.SelectableTextAlign -> {
style.selectableTextAlign to it.floats
style.selectableTextAlign put (value as Vec2)
}
}
})
}
fun popStyleVar(count: Int = 1) = repeat(count) {
val backup = g.styleVarStack.pop()
when (backup.idx) {
StyleVar.Alpha -> style.alpha = backup.floats[0]
StyleVar.WindowPadding -> style.windowPadding put backup.floats
StyleVar.WindowRounding -> style.windowRounding = backup.floats[0]
StyleVar.WindowBorderSize -> style.windowBorderSize = backup.floats[0]
StyleVar.WindowMinSize -> style.windowMinSize put backup.ints
StyleVar.WindowTitleAlign -> style.windowTitleAlign put backup.floats
StyleVar.ChildRounding -> style.childRounding = backup.floats[0]
StyleVar.ChildBorderSize -> style.childBorderSize = backup.floats[0]
StyleVar.PopupRounding -> style.popupRounding = backup.floats[0]
StyleVar.PopupBorderSize -> style.popupBorderSize = backup.floats[0]
StyleVar.FrameBorderSize -> style.frameBorderSize = backup.floats[0]
StyleVar.FramePadding -> style.framePadding put backup.floats
StyleVar.FrameRounding -> style.frameRounding = backup.floats[0]
StyleVar.ItemSpacing -> style.itemSpacing put backup.floats
StyleVar.ItemInnerSpacing -> style.itemInnerSpacing put backup.floats
StyleVar.IndentSpacing -> style.indentSpacing = backup.floats[0]
StyleVar.ScrollbarSize -> style.scrollbarSize = backup.floats[0]
StyleVar.ScrollbarRounding -> style.scrollbarRounding = backup.floats[0]
StyleVar.GrabMinSize -> style.grabMinSize = backup.floats[0]
StyleVar.GrabRounding -> style.grabRounding = backup.floats[0]
StyleVar.TabRounding -> style.tabRounding = backup.floats[0]
StyleVar.ButtonTextAlign -> style.buttonTextAlign put backup.floats
StyleVar.SelectableTextAlign -> style.selectableTextAlign put backup.floats
}
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
fun pushAllowKeyboardFocus(allowKeyboardFocus: Boolean) = pushItemFlag(If.NoTabStop.i, !allowKeyboardFocus)
fun popAllowKeyboardFocus() = popItemFlag()
/** in 'repeat' mode, Button*() functions return repeated true in a typematic manner
* (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to
* tell if the button is held in the current frame. */
fun pushButtonRepeat(repeat: Boolean) = pushItemFlag(If.ButtonRepeat.i, repeat)
fun popButtonRepeat() = popItemFlag()
// Parameters stacks (current window)
/** push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the
* right of window (so -FLT_MIN always align width to the right side). 0.0f = default to ~2/3 of windows width, */
fun pushItemWidth(itemWidth: Int) = pushItemWidth(itemWidth.f)
fun pushItemWidth(itemWidth: Float) {
currentWindow.apply {
dc.itemWidth = if (itemWidth == 0f) itemWidthDefault else itemWidth
dc.itemWidthStack.push(dc.itemWidth)
}
g.nextItemData.flags = g.nextItemData.flags wo NextItemDataFlag.HasWidth
}
fun popItemWidth() {
with(currentWindow) {
dc.itemWidthStack.pop()
dc.itemWidth = if (dc.itemWidthStack.empty()) itemWidthDefault else dc.itemWidthStack.last()
}
}
/** set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the
* right of window (so -FLT_MIN always align width to the right side) */
fun setNextItemWidth(itemWidth: Float) {
g.nextItemData.flags = g.nextItemData.flags or NextItemDataFlag.HasWidth
g.nextItemData.width = itemWidth
}
/** Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
* The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
*
* width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
*
* ~ GetNextItemWidth */
fun calcItemWidth(): Float {
val window = g.currentWindow!!
var w = when {
g.nextItemData.flags has NextItemDataFlag.HasWidth -> g.nextItemData.width
else -> window.dc.itemWidth
}
if (w < 0f) {
val regionMaxX = contentRegionMaxAbs.x
w = 1f max (regionMaxX - window.dc.cursorPos.x + w)
}
return floor(w)
}
/** push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column);
* > 0.0f: wrap at 'wrapLocalPosX' position in window local space */
fun pushTextWrapPos(wrapLocalPosX: Float = 0f) = with(currentWindow.dc) {
textWrapPos = wrapLocalPosX
textWrapPosStack.push(wrapLocalPosX)
}
fun popTextWrapPos() = with(currentWindow.dc) {
textWrapPosStack.pop()
textWrapPos = textWrapPosStack.lastOrNull() ?: -1f
}
} | mit | 07a074a01a9a4e79e40083557cb197f2 | 42.195572 | 141 | 0.597352 | 4.493282 | false | false | false | false |
fyookball/electrum | android/app/src/main/java/org/electroncash/electroncash3/Transactions.kt | 1 | 5231 | package org.electroncash.electroncash3
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.observe
import com.chaquo.python.Kwarg
import com.chaquo.python.PyObject
import kotlinx.android.synthetic.main.transaction_detail.*
import kotlinx.android.synthetic.main.transactions.*
import kotlin.math.roundToInt
class TransactionsFragment : Fragment(R.layout.transactions), MainFragment {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setupVerticalList(rvTransactions)
rvTransactions.adapter = TransactionsAdapter(activity!!)
TriggerLiveData().apply {
addSource(daemonUpdate)
addSource(settings.getString("base_unit"))
}.observe(viewLifecycleOwner, { refresh() })
btnSend.setOnClickListener {
try {
showDialog(activity!!, SendDialog())
} catch (e: ToastException) { e.show() }
}
btnRequest.setOnClickListener { newRequest(activity!!) }
}
fun refresh() {
val wallet = daemonModel.wallet
(rvTransactions.adapter as TransactionsAdapter).submitList(
if (wallet == null) null else TransactionsList(wallet))
}
}
class TransactionsList(wallet: PyObject, addr: PyObject? = null)
: AbstractList<TransactionModel>() {
val history = wallet.callAttr("export_history",
Kwarg("domain", if (addr == null) null else arrayOf(addr)),
Kwarg("decimal_point", unitPlaces)).asList()
override val size
get() = history.size
override fun get(index: Int) =
TransactionModel(history.get(index).asMap())
}
class TransactionsAdapter(val activity: FragmentActivity)
: BoundAdapter<TransactionModel>(R.layout.transaction_list) {
override fun onBindViewHolder(holder: BoundViewHolder<TransactionModel>, position: Int) {
super.onBindViewHolder(holder, position)
holder.itemView.setOnClickListener {
val txid = holder.item.get("txid")
val tx = daemonModel.wallet!!.get("transactions")!!.callAttr("get", txid)
if (tx == null) { // Can happen during wallet sync.
toast(R.string.Transaction_not, Toast.LENGTH_SHORT)
} else {
showDialog(activity, TransactionDialog(txid))
}
}
}
}
class TransactionModel(val txExport: Map<PyObject, PyObject>) {
fun get(key: String) = txExport.get(PyObject.fromJava(key))!!.toString()
fun getIcon(): Drawable {
return ContextCompat.getDrawable(
app,
if (get("value")[0] == '+') R.drawable.ic_add_24dp
else R.drawable.ic_remove_24dp)!!
}
fun getConfirmationsStr(): String {
val confirmations = Integer.parseInt(get("confirmations"))
return when {
confirmations <= 0 -> ""
else -> app.resources.getQuantityString(R.plurals.confirmation,
confirmations, confirmations)
}
}
}
class TransactionDialog() : AlertDialogFragment() {
constructor(txid: String) : this() {
arguments = Bundle().apply { putString("txid", txid) }
}
val wallet by lazy { daemonModel.wallet!! }
val txid by lazy { arguments!!.getString("txid")!! }
val tx by lazy { wallet.get("transactions")!!.callAttr("get", txid)!! }
val txInfo by lazy { wallet.callAttr("get_tx_info", tx).asList() }
override fun onBuildDialog(builder: AlertDialog.Builder) {
builder.setView(R.layout.transaction_detail)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, {_, _ ->
setDescription(txid, etDescription.text.toString())
})
}
override fun onShowDialog() {
btnExplore.setOnClickListener { exploreTransaction(activity!!, txid) }
btnCopy.setOnClickListener { copyToClipboard(txid, R.string.transaction_id) }
tvTxid.text = txid
val timestamp = txInfo.get(8)?.toLong()
tvTimestamp.text = if (timestamp == null || timestamp == 0L) getString(R.string.Unknown)
else libUtil.callAttr("format_time", timestamp).toString()
tvStatus.text = txInfo.get(1)!!.toString()
val size = tx.callAttr("estimated_size").toInt()
tvSize.text = getString(R.string.bytes, size)
val fee = txInfo.get(5)?.toLong()
if (fee == null) {
tvFee.text = getString(R.string.Unknown)
} else {
val feeSpb = (fee.toDouble() / size.toDouble()).roundToInt()
tvFee.text = String.format("%s (%s)",
getString(R.string.sat_byte, feeSpb),
formatSatoshisAndUnit(fee))
}
}
override fun onFirstShowDialog() {
etDescription.setText(txInfo.get(2)!!.toString())
}
} | mit | 2f4d482445bcf54b7e6b4130e446a4ac | 35.333333 | 96 | 0.625311 | 4.463311 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/ui/season/SeasonDetailPresenter.kt | 1 | 2642 | package com.ashish.movieguide.ui.season
import com.ashish.movieguide.R
import com.ashish.movieguide.data.interactors.TVShowInteractor
import com.ashish.movieguide.data.models.FullDetailContent
import com.ashish.movieguide.data.models.SeasonDetail
import com.ashish.movieguide.di.scopes.ActivityScope
import com.ashish.movieguide.ui.base.detail.fulldetail.FullDetailContentPresenter
import com.ashish.movieguide.utils.extensions.getFormattedMediumDate
import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider
import java.util.ArrayList
import javax.inject.Inject
/**
* Created by Ashish on Jan 07.
*/
@ActivityScope
class SeasonDetailPresenter @Inject constructor(
private val tvShowInteractor: TVShowInteractor,
schedulerProvider: BaseSchedulerProvider
) : FullDetailContentPresenter<SeasonDetail, SeasonDetailView>(schedulerProvider) {
private var seasonNumber: Int = 1
fun setSeasonNumber(seasonNumber: Int) {
this.seasonNumber = seasonNumber
}
override fun getDetailContent(id: Long) = tvShowInteractor.getFullSeasonDetail(id, seasonNumber)
override fun showDetailContent(fullDetailContent: FullDetailContent<SeasonDetail>) {
super.showDetailContent(fullDetailContent)
getView()?.apply {
hideProgress()
val seasonDetail = fullDetailContent.detailContent
showItemList(seasonDetail?.episodes) { showEpisodeList(it) }
}
}
override fun getContentList(fullDetailContent: FullDetailContent<SeasonDetail>): List<String> {
val contentList = ArrayList<String>()
fullDetailContent.detailContent?.apply {
val omdbDetail = fullDetailContent.omdbDetail
contentList.apply {
add(overview ?: "")
add(omdbDetail?.Rated ?: "")
add(omdbDetail?.Awards ?: "")
add(seasonNumber.toString())
add(episodes?.size.toString())
add(airDate.getFormattedMediumDate())
add(omdbDetail?.Production ?: "")
add(omdbDetail?.Country ?: "")
add(omdbDetail?.Language ?: "")
}
}
return contentList
}
override fun getBackdropImages(detailContent: SeasonDetail) = detailContent.images?.backdrops
override fun getPosterImages(detailContent: SeasonDetail) = detailContent.images?.posters
override fun getVideos(detailContent: SeasonDetail) = detailContent.videos
override fun getCredits(detailContent: SeasonDetail) = detailContent.credits
override fun getErrorMessageId() = R.string.error_load_season_detail
} | apache-2.0 | 2fe6399601ffb15844347020f43bb1f2 | 37.304348 | 100 | 0.713096 | 5.022814 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/ec2/src/main/kotlin/com/kotlin/ec2/DeleteSecurityGroup.kt | 1 | 1749 | // snippet-sourcedescription:[DeleteSecurityGroup.kt demonstrates how to delete an Amazon Elastic Compute Cloud (Amazon EC2) Security Group.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon EC2]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.ec2
// snippet-start:[ec2.kotlin.delete_security_group.import]
import aws.sdk.kotlin.services.ec2.Ec2Client
import aws.sdk.kotlin.services.ec2.model.DeleteSecurityGroupRequest
import kotlin.system.exitProcess
// snippet-end:[ec2.kotlin.delete_security_group.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<groupId>
Where:
groupId - A security group id that you can obtain from the AWS Management Console (for example, sg-xxxxxx1c0b65785c3).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val groupId = args[0]
deleteEC2SecGroup(groupId)
}
// snippet-start:[ec2.kotlin.delete_security_group.main]
suspend fun deleteEC2SecGroup(groupIdVal: String) {
val request = DeleteSecurityGroupRequest {
groupId = groupIdVal
}
Ec2Client { region = "us-west-2" }.use { ec2 ->
ec2.deleteSecurityGroup(request)
println("Successfully deleted Security Group with id $groupIdVal")
}
}
// snippet-end:[ec2.kotlin.delete_security_group.main]
| apache-2.0 | 1b651ef129d89bea7fea58a9fa0099d1 | 29.232143 | 141 | 0.689537 | 3.777538 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/adapters/header/ExpandableListAdapter.kt | 1 | 4890 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.base.adapters.header
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import de.dreier.mytargets.R
import de.dreier.mytargets.databinding.ItemHeaderExpandableBinding
import de.dreier.mytargets.shared.models.IIdProvider
import de.dreier.mytargets.utils.multiselector.ExpandableHeaderBindingHolder
import de.dreier.mytargets.utils.multiselector.ItemBindingHolder
typealias PartitionDelegate<PARENT, CHILD> = (CHILD) -> PARENT
abstract class ExpandableListAdapter<P : IIdProvider, C : IIdProvider>(
partitionDelegate: PartitionDelegate<P, C>,
headerComparator: Comparator<P>, childComparator: Comparator<C>
) : HeaderListAdapterBase<P, C, ExpandableHeaderHolder<P, C>>(
partitionDelegate,
headerComparator,
childComparator
) {
var expandedIds: List<Long>
get() = headersList
.filter { it.expanded }
.map { it.item.id }
set(expanded) {
headersList.indices
.map { headersList[it] }
.forEach { it.expanded = expanded.contains(it.item.id) }
}
override fun onBindViewHolder(viewHolder: ItemBindingHolder<IIdProvider>, position: Int) {
super.onBindViewHolder(viewHolder, position)
if (viewHolder is ExpandableHeaderBindingHolder<*>) {
val header = getHeaderForPosition(position)
(viewHolder as ExpandableHeaderBindingHolder<*>)
.setExpandOnClickListener(
View.OnClickListener { expandOrCollapse(header) },
header.expanded
)
}
}
override fun getItemPosition(item: C): Int {
var pos = 0
for (header in headersList) {
if (header.totalItemCount < 1) {
continue
}
pos++
if (header.totalItemCount == 1) {
continue
}
for (child in header.children) {
if (child == item) {
return pos
}
pos++
}
}
return -1
}
fun ensureItemIsExpanded(item: C) {
val parentHolder = getHeaderHolderForChild(item)
val pos = getHeaderIndex(parentHolder)
if (pos >= 0 && !headersList[pos].expanded) {
expandOrCollapse(headersList[pos])
}
}
private fun expandOrCollapse(header: ExpandableHeaderHolder<P, C>) {
val childLength = header.children.size
if (!header.expanded) {
notifyItemRangeInserted(getAbsolutePosition(header) + 1, childLength)
} else {
notifyItemRangeRemoved(getAbsolutePosition(header) + 1, childLength)
}
header.expanded = !header.expanded
}
override fun setList(list: List<C>) {
val oldExpanded = expandedIds
fillChildMap(list)
expandedIds = oldExpanded
notifyDataSetChanged()
}
fun setList(children: List<C>, opened: Boolean) {
fillChildMap(children)
expandAll(opened)
notifyDataSetChanged()
}
private fun expandAll(expanded: Boolean) {
for (header in headersList) {
header.expanded = expanded
}
}
fun expandFirst() {
if (!headersList[0].expanded) {
expandOrCollapse(headersList[0])
}
}
private fun getAbsolutePosition(h: ExpandableHeaderHolder<P, C>): Int {
val headerIndex = getHeaderIndex(h)
return (0 until headerIndex).sumBy { headersList[it].totalItemCount }
}
override fun getHeaderHolder(
parent: P,
childComparator: Comparator<C>
): ExpandableHeaderHolder<P, C> {
return ExpandableHeaderHolder(parent, childComparator)
}
override fun getTopLevelViewHolder(parent: ViewGroup): HeaderViewHolder<P> {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_header_expandable, parent, false)
return HeaderViewHolder(itemView)
}
class HeaderViewHolder<P> internal constructor(itemView: View) :
ExpandableHeaderBindingHolder<P>(itemView, R.id.expand_collapse) {
private val binding = ItemHeaderExpandableBinding.bind(itemView)
override fun bindItem(item: P) {
binding.header.text = item.toString()
}
}
}
| gpl-2.0 | 7ffb07bcb0730417a3d22109f5aa0f64 | 31.6 | 94 | 0.639673 | 4.657143 | false | false | false | false |
swissonid/Tracker | app/src/main/kotlin/ch/swissonid/tracker/services/tracker/TrackerServiceImpl.kt | 1 | 3624 | package ch.swissonid.tracker.services.tracker
import android.location.Location
import android.os.Bundle
import android.util.Log
import ch.swissonid.tracker.TrackerApp
import ch.swissonid.tracker.model.Point
import ch.swissonid.tracker.toPoint
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
class TrackerServiceImpl(context : TrackerApp) : TrackerService
, GoogleApiClient.ConnectionCallbacks
, GoogleApiClient.OnConnectionFailedListener
, LocationListener {
override fun getLastPosition(): Point {
return getLastLocation().toPoint()
}
override fun removeErrorListener(errorListener: TrackerService.OnError) {
throw UnsupportedOperationException()
}
override fun addErrorListener(errorListener: TrackerService.OnError) {
throw UnsupportedOperationException()
}
private val mGoogleApiClient : GoogleApiClient
private var mLocationRequest: LocationRequest = createLocationRequest()
private var mLocationListeners : MutableList<TrackerService.OnLocationChangeListener> = arrayListOf()
private val TAG = TrackerServiceImpl::class.java.name
init {
mGoogleApiClient = GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
}
override fun onConnected(bundle: Bundle?) {
Log.d(TAG, "Successful connected")
startTracking()
}
private fun getLastLocation(): Location {
return LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
}
override fun onConnectionSuspended(p0: Int) {
throw UnsupportedOperationException()
}
override fun onConnectionFailed(result: ConnectionResult?) {
if(result?.hasResolution()!!){
Log.e(TAG, "Connection failed with solution");
}else{
Log.e(TAG, "Connection failed without solution");
}
}
override fun startTracking() {
if(!mGoogleApiClient.isConnected){
mGoogleApiClient.connect()
}else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
}
}
override fun stopTracking() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this)
}
override fun onLocationChanged(location: Location?) {
if(location == null) return
Log.d(TAG, "NEW LOCATION: "+location.toString())
val point = location.toPoint()
mLocationListeners.forEach { it.onLocationChange(point) }
}
override fun addLocationChangeListener(listener: TrackerService.OnLocationChangeListener) {
mLocationListeners.add(listener)
}
override fun removeLocationChangeListener(listener: TrackerService.OnLocationChangeListener) {
mLocationListeners.remove(listener)
}
protected fun createLocationRequest() : LocationRequest {
var request = LocationRequest()
request.setInterval(5000)
request.setFastestInterval(1000)
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
return request
}
} | apache-2.0 | 3498ed44e4705fb497980e93046f539f | 31.954545 | 105 | 0.681291 | 5.54977 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationOnlyHandler2.kt | 1 | 3043 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.findAllTargets
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction.isKeywordUnderCaret
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction.underModalProgress
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.navigation.NavigationTarget
import com.intellij.navigation.chooseTarget
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiFile
object GotoDeclarationOnlyHandler2 : CodeInsightActionHandler {
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration")
val targets = try {
underModalProgress(project, "Resolving Reference...") {
findAllTargets(project, editor, file)
}
}
catch (e: IndexNotReadyException) {
DumbService.getInstance(project).showDumbModeNotification("Navigation is not available here during index update")
return
}
if (targets.isEmpty()) {
notifyCantGoAnywhere(project, editor, file)
}
else {
chooseTarget(project, editor, CodeInsightBundle.message("declaration.navigation.title"), targets.toList()) {
gotoTarget(project, editor, file, it)
}
}
}
private fun notifyCantGoAnywhere(project: Project, editor: Editor, file: PsiFile) {
if (!isKeywordUnderCaret(project, file, editor.caretModel.offset)) {
HintManager.getInstance().showErrorHint(editor, "Cannot find declaration to go to")
}
}
private fun gotoTarget(project: Project, editor: Editor, file: PsiFile, target: NavigationTarget) {
val navigatable = target.navigatable ?: return
if (navigateInCurrentEditor(project, editor, file, navigatable)) {
return
}
if (navigatable.canNavigate()) {
navigatable.navigate(true)
}
}
private fun navigateInCurrentEditor(project: Project, editor: Editor, file: PsiFile, target: Navigatable): Boolean {
if (!editor.isDisposed && target is OpenFileDescriptor && target.file == file.virtualFile) {
executeCommand {
IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation()
target.navigateIn(editor)
}
return true
}
return false
}
}
| apache-2.0 | e12d2c044aae1712baa10038a25bb307 | 39.039474 | 140 | 0.767663 | 4.739875 | false | false | false | false |
paplorinc/intellij-community | plugins/changeReminder/src/com/jetbrains/changeReminder/commit/handle/ChangeReminderCheckinHandler.kt | 1 | 5750 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.commit.handle
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PairConsumer
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.util.VcsLogUtil.findBranch
import com.jetbrains.changeReminder.*
import com.jetbrains.changeReminder.commit.handle.ui.ChangeReminderDialog
import com.jetbrains.changeReminder.plugin.UserSettings
import com.jetbrains.changeReminder.predict.PredictedFile
import com.jetbrains.changeReminder.predict.PredictionProvider
import com.jetbrains.changeReminder.repository.FilesHistoryProvider
import com.jetbrains.changeReminder.stats.ChangeReminderData
import com.jetbrains.changeReminder.stats.ChangeReminderEvent
import com.jetbrains.changeReminder.stats.logEvent
import java.util.function.Consumer
import kotlin.system.measureTimeMillis
class ChangeReminderCheckinHandler(private val panel: CheckinProjectPanel,
private val dataManager: VcsLogData,
private val dataGetter: IndexDataGetter) : CheckinHandler() {
companion object {
private val LOG = Logger.getInstance(ChangeReminderCheckinHandler::class.java)
}
private val project: Project = panel.project
private val changeListManager = ChangeListManager.getInstance(project)
private val userSettings = ServiceManager.getService(UserSettings::class.java)
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent {
return BooleanCommitOption(
panel,
"Predict forgotten files",
true,
{ userSettings.isTurnedOn },
Consumer { userSettings.isTurnedOn = it }
)
}
private fun getPredictedFiles(files: Collection<FilePath>, root: VirtualFile, isAmend: Boolean, threshold: Double): List<PredictedFile> {
val repository = FilesHistoryProvider(project, root, dataGetter)
val filesSet = files.toMutableSet()
if (isAmend) {
val ref = findBranch(dataManager.dataPack.refsModel, root, "HEAD")
if (ref != null) {
val hash = ref.commitHash.asString()
processCommitsFromHashes(project, root, listOf(hash)) { commit ->
filesSet.addAll(commit.changedFilePaths())
}
}
}
if (filesSet.size > 25) {
return emptyList()
}
return PredictionProvider(minProb = threshold)
.predictForgottenFiles(repository.getFilesHistory(filesSet))
.toPredictedFiles(changeListManager)
}
private fun getPredictedFiles(rootFiles: Map<VirtualFile, Collection<FilePath>>,
isAmend: Boolean,
threshold: Double): List<PredictedFile> =
rootFiles.mapNotNull { (root, files) ->
if (dataManager.index.isIndexed(root)) {
getPredictedFiles(files, root, isAmend, threshold)
}
else {
null
}
}.flatten()
override fun beforeCheckin(executor: CommitExecutor?, additionalDataConsumer: PairConsumer<Any, Any>?): ReturnResult {
try {
val rootFiles = panel.getGitRootFiles(project)
if (!userSettings.isTurnedOn || rootFiles.size > 25) {
logEvent(project, ChangeReminderEvent.PLUGIN_DISABLED)
return ReturnResult.COMMIT
}
val isAmend = panel.isAmend()
val threshold = userSettings.threshold
val (executionTime, predictedFiles) = measureSupplierTimeMillis {
ProgressManager.getInstance()
.runProcessWithProgressSynchronously(
ThrowableComputable<List<PredictedFile>, Exception> {
getPredictedFiles(rootFiles, isAmend, threshold)
},
"Calculating whether something should be added to this commit",
true,
project
)
}
logEvent(project, ChangeReminderEvent.PREDICTION_CALCULATED, ChangeReminderData.EXECUTION_TIME, executionTime)
if (predictedFiles.isEmpty()) {
logEvent(project, ChangeReminderEvent.NOT_SHOWED)
return ReturnResult.COMMIT
}
val dialog = ChangeReminderDialog(project, predictedFiles)
val showDialogTime = measureTimeMillis {
dialog.show()
}
logEvent(project, ChangeReminderEvent.DIALOG_CLOSED, ChangeReminderData.SHOW_DIALOG_TIME, showDialogTime)
return if (dialog.exitCode == 1) {
logEvent(project, ChangeReminderEvent.COMMIT_CANCELED)
userSettings.updateState(UserSettings.Companion.UserAction.CANCEL)
ReturnResult.CANCEL
}
else {
logEvent(project, ChangeReminderEvent.COMMITTED_ANYWAY)
userSettings.updateState(UserSettings.Companion.UserAction.COMMIT)
ReturnResult.COMMIT
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Unexpected problem with ChangeReminder prediction", e)
return ReturnResult.COMMIT
}
}
} | apache-2.0 | b1986661de6c8536fd1e15903901ab95 | 39.216783 | 140 | 0.729739 | 4.835997 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/features/bookmarks/BookmarkPresenter.kt | 1 | 3008 | package de.ph1b.audiobook.features.bookmarks
import de.ph1b.audiobook.data.Bookmark
import de.ph1b.audiobook.data.Chapter
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.data.repo.BookmarkRepo
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.mvp.Presenter
import de.ph1b.audiobook.persistence.pref.Pref
import de.ph1b.audiobook.playback.PlayStateManager
import de.ph1b.audiobook.playback.PlayerController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.UUID
import javax.inject.Inject
import javax.inject.Named
/**
* Presenter for the bookmark MVP
*/
class BookmarkPresenter @Inject constructor(
@Named(PrefKeys.CURRENT_BOOK)
private val currentBookIdPref: Pref<UUID>,
private val repo: BookRepository,
private val bookmarkRepo: BookmarkRepo,
private val playStateManager: PlayStateManager,
private val playerController: PlayerController
) : Presenter<BookmarkView>() {
var bookId: UUID = UUID.randomUUID()
private val bookmarks = ArrayList<Bookmark>()
private val chapters = ArrayList<Chapter>()
override fun onAttach(view: BookmarkView) {
val book = repo.bookById(bookId) ?: return
GlobalScope.launch(Dispatchers.Main) {
bookmarks.clear()
bookmarks.addAll(bookmarkRepo.bookmarks(book))
chapters.clear()
chapters.addAll(book.content.chapters)
if (attached) renderView()
}
}
fun deleteBookmark(id: Long) {
GlobalScope.launch(Dispatchers.Main) {
bookmarkRepo.deleteBookmark(id)
bookmarks.removeAll { it.id == id }
renderView()
}
}
fun selectBookmark(id: Long) {
val bookmark = bookmarks.find { it.id == id }
?: return
val wasPlaying = playStateManager.playState == PlayStateManager.PlayState.PLAYING
currentBookIdPref.value = bookId
playerController.changePosition(bookmark.time, bookmark.mediaFile)
if (wasPlaying) {
playerController.play()
}
view.finish()
}
fun editBookmark(id: Long, newTitle: String) {
GlobalScope.launch(Dispatchers.Main) {
bookmarks.find { it.id == id }?.let {
val withNewTitle = it.copy(
title = newTitle,
id = Bookmark.ID_UNKNOWN
)
bookmarkRepo.deleteBookmark(it.id)
val newBookmark = bookmarkRepo.addBookmark(withNewTitle)
val index = bookmarks.indexOfFirst { bookmarkId -> bookmarkId.id == id }
bookmarks[index] = newBookmark
if (attached) renderView()
}
}
}
fun addBookmark(name: String) {
GlobalScope.launch(Dispatchers.Main) {
val book = repo.bookById(bookId) ?: return@launch
val title = if (name.isEmpty()) book.content.currentChapter.name else name
val addedBookmark = bookmarkRepo.addBookmarkAtBookPosition(book, title)
bookmarks.add(addedBookmark)
if (attached) renderView()
}
}
private fun renderView() {
view.render(bookmarks, chapters)
}
}
| lgpl-3.0 | b052a7a455dd653a88180ab16ebd02d7 | 28.490196 | 85 | 0.71609 | 4.171983 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SimpleChildAbstractEntityImpl.kt | 1 | 9007 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleChildAbstractEntityImpl(val dataSource: SimpleChildAbstractEntityData) : SimpleChildAbstractEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTINLIST_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeAbstractEntity::class.java,
SimpleAbstractEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false)
val connections = listOf<ConnectionId>(
PARENTINLIST_CONNECTION_ID,
)
}
override val parentInList: CompositeAbstractEntity
get() = snapshot.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SimpleChildAbstractEntityData?) : ModifiableWorkspaceEntityBase<SimpleChildAbstractEntity>(), SimpleChildAbstractEntity.Builder {
constructor() : this(SimpleChildAbstractEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleChildAbstractEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTINLIST_CONNECTION_ID, this) == null) {
error("Field SimpleAbstractEntity#parentInList should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] == null) {
error("Field SimpleAbstractEntity#parentInList should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleChildAbstractEntity
this.entitySource = dataSource.entitySource
if (parents != null) {
this.parentInList = parents.filterIsInstance<CompositeAbstractEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentInList: CompositeAbstractEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity
}
else {
this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTINLIST_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] = value
}
changedProperty.add("parentInList")
}
override fun getEntityData(): SimpleChildAbstractEntityData = result ?: super.getEntityData() as SimpleChildAbstractEntityData
override fun getEntityClass(): Class<SimpleChildAbstractEntity> = SimpleChildAbstractEntity::class.java
}
}
class SimpleChildAbstractEntityData : WorkspaceEntityData<SimpleChildAbstractEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SimpleChildAbstractEntity> {
val modifiable = SimpleChildAbstractEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleChildAbstractEntity {
return getCached(snapshot) {
val entity = SimpleChildAbstractEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleChildAbstractEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleChildAbstractEntity(entitySource) {
this.parentInList = parents.filterIsInstance<CompositeAbstractEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(CompositeAbstractEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleChildAbstractEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleChildAbstractEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | d31dac487657213d1384e251805d5101 | 37.491453 | 169 | 0.705895 | 5.339063 | false | false | false | false |
spacecowboy/Feeder | app/src/androidTest/java/com/nononsenseapps/feeder/crypto/AesCbcWithIntegrityTest.kt | 1 | 820 | package com.nononsenseapps.feeder.crypto
import kotlin.test.assertEquals
import org.junit.Test
class AesCbcWithIntegrityTest {
@Test
fun generateKeyAndEncryptDecrypt() {
val originalMessage = "Hello Crypto"
val key = AesCbcWithIntegrity.generateKey()
val encryptedMessage = AesCbcWithIntegrity.encryptString(originalMessage, key)
val decryptedMessage = AesCbcWithIntegrity.decryptString(encryptedMessage, key)
assertEquals(originalMessage, decryptedMessage)
}
@Test
fun generateKeyAndEncodeDecodeKey() {
val originalKey = AesCbcWithIntegrity.generateKey()
val encodedKey = AesCbcWithIntegrity.encodeKey(originalKey)
val decodedKey = AesCbcWithIntegrity.decodeKey(encodedKey)
assertEquals(originalKey, decodedKey)
}
}
| gpl-3.0 | 896aa442da10928e963063fa8539fc1c | 29.37037 | 87 | 0.741463 | 4.530387 | false | true | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/flow/sharing/ShareInFusionTest.kt | 1 | 1930 | /*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.test.*
class ShareInFusionTest : TestBase() {
/**
* Test perfect fusion for operators **after** [shareIn].
*/
@Test
fun testOperatorFusion() = runTest {
val sh = emptyFlow<Int>().shareIn(this, SharingStarted.Eagerly)
assertTrue(sh !is MutableSharedFlow<*>) // cannot be cast to mutable shared flow!!!
assertSame(sh, (sh as Flow<*>).cancellable())
assertSame(sh, (sh as Flow<*>).flowOn(Dispatchers.Default))
assertSame(sh, sh.buffer(Channel.RENDEZVOUS))
coroutineContext.cancelChildren()
}
@Test
fun testFlowOnContextFusion() = runTest {
val flow = flow {
assertEquals("FlowCtx", currentCoroutineContext()[CoroutineName]?.name)
emit("OK")
}.flowOn(CoroutineName("FlowCtx"))
assertEquals("OK", flow.shareIn(this, SharingStarted.Eagerly, 1).first())
coroutineContext.cancelChildren()
}
/**
* Tests that `channelFlow { ... }.buffer(x)` works according to the [channelFlow] docs, and subsequent
* application of [shareIn] does not leak upstream.
*/
@Test
fun testChannelFlowBufferShareIn() = runTest {
expect(1)
val flow = channelFlow {
// send a batch of 10 elements using [offer]
for (i in 1..10) {
assertTrue(trySend(i).isSuccess) // offer must succeed, because buffer
}
send(0) // done
}.buffer(10) // request a buffer of 10
// ^^^^^^^^^ buffer stays here
val shared = flow.shareIn(this, SharingStarted.Eagerly)
shared
.takeWhile { it > 0 }
.collect { i -> expect(i + 1) }
finish(12)
}
}
| apache-2.0 | 9c6c2a13bb8370c38635a86358737cb4 | 33.464286 | 107 | 0.606736 | 4.477958 | false | true | false | false |
crispab/codekvast | product/server/stress-tester/src/main/java/io.codekvast.stress_tester/StressTester.kt | 1 | 2483 | /*
* Copyright (c) 2015-2022 Hallin Information Technology AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.codekvast.stress_tester
import io.codekvast.common.messaging.EventService
import io.codekvast.common.messaging.model.AgentPolledEvent
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.Instant
import java.time.temporal.ChronoUnit
/**
* @author [email protected]
*/
@Component
class StressTester(private val eventService: EventService) {
val logger = LoggerFactory.getLogger(javaClass)!!
var count = 0
var firstTime = true
var startedAt = Instant.now()
@Scheduled(fixedRateString = "\${codekvast.stress-tester.eventRateMillis}")
fun sendSampleAgentPolledEvent() {
val oldName = Thread.currentThread().name
try {
Thread.currentThread().name = "Codekvast StressTester"
if (firstTime) {
logger.info("StressTester started")
firstTime = false
}
eventService.send(AgentPolledEvent.sample())
if (++count % 100 == 0) {
logger.info("Sent {} events {} after start", count, Duration.between(startedAt, Instant.now()).truncatedTo(ChronoUnit.SECONDS))
}
} finally {
Thread.currentThread().name = oldName
}
}
}
| mit | 66d2e61376bc470f65389ec60c226722 | 37.796875 | 143 | 0.714458 | 4.572744 | false | true | false | false |
zdary/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRCreateInfoComponentFactory.kt | 1 | 22004 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create
import com.intellij.CommonBundle
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.push.PushSpec
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase
import com.intellij.openapi.progress.util.ProgressWrapper
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.messages.MessagesService
import com.intellij.openapi.util.NlsActions
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextArea
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.EventDispatcher
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import git4idea.GitLocalBranch
import git4idea.GitRemoteBranch
import git4idea.GitStandardRemoteBranch
import git4idea.GitVcs
import git4idea.push.GitPushOperation
import git4idea.push.GitPushSource
import git4idea.push.GitPushSupport
import git4idea.push.GitPushTarget
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import git4idea.validators.GitRefNameValidator
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.ui.*
import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRMetadataPanelFactory
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabComponentController
import org.jetbrains.plugins.github.ui.util.DisableableDocument
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.SingleValueModel
import org.jetbrains.plugins.github.util.CollectionDelta
import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager
import org.jetbrains.plugins.github.util.GithubGitHelper
import org.jetbrains.plugins.github.util.successOnEdt
import java.awt.Component
import java.awt.Container
import java.awt.event.ActionEvent
import java.util.concurrent.CompletableFuture
import javax.swing.*
import javax.swing.text.Document
internal class GHPRCreateInfoComponentFactory(private val project: Project,
private val settings: GithubPullRequestsProjectUISettings,
private val repositoriesManager: GHProjectRepositoriesManager,
private val dataContext: GHPRDataContext,
private val viewController: GHPRToolWindowTabComponentController) {
fun create(directionModel: GHPRCreateDirectionModel,
titleDocument: Document,
descriptionDocument: DisableableDocument,
metadataModel: GHPRCreateMetadataModel,
commitsCountModel: SingleValueModel<Int?>,
existenceCheckLoadingModel: GHIOExecutorLoadingModel<GHPRIdentifier?>,
createLoadingModel: GHCompletableFutureLoadingModel<GHPullRequestShort>): JComponent {
val progressIndicator = ListenableProgressIndicator()
val existenceCheckProgressIndicator = ListenableProgressIndicator()
val createAction = CreateAction(directionModel, titleDocument, descriptionDocument, metadataModel, false, createLoadingModel,
progressIndicator, GithubBundle.message("pull.request.create.action"))
val createDraftAction = CreateAction(directionModel, titleDocument, descriptionDocument, metadataModel, true, createLoadingModel,
progressIndicator, GithubBundle.message("pull.request.create.draft.action"))
val cancelAction = object : AbstractAction(CommonBundle.getCancelButtonText()) {
override fun actionPerformed(e: ActionEvent?) {
val discard = Messages.showYesNoDialog(project,
GithubBundle.message("pull.request.create.discard.message"),
GithubBundle.message("pull.request.create.discard.title"),
GithubBundle.message("pull.request.create.discard.approve"),
CommonBundle.getCancelButtonText(), Messages.getWarningIcon())
if (discard == Messages.NO) return
progressIndicator.cancel()
viewController.viewList()
viewController.resetNewPullRequestView()
createLoadingModel.future = null
existenceCheckLoadingModel.reset()
}
}
InfoController(directionModel, existenceCheckLoadingModel, existenceCheckProgressIndicator, createAction, createDraftAction)
val directionSelector = GHPRCreateDirectionComponentFactory(repositoriesManager, directionModel).create().apply {
border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM),
JBUI.Borders.empty(7, 8, 8, 8))
}
val titleField = JBTextArea(titleDocument).apply {
background = UIUtil.getListBackground()
border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM),
JBUI.Borders.empty(8))
emptyText.text = GithubBundle.message("pull.request.create.title")
lineWrap = true
}.also {
GHUIUtil.overrideUIDependentProperty(it) {
font = UIUtil.getLabelFont()
}
GHUIUtil.registerFocusActions(it)
}
val descriptionField = JBTextArea(descriptionDocument).apply {
background = UIUtil.getListBackground()
border = JBUI.Borders.empty(8, 8, 0, 8)
emptyText.text = GithubBundle.message("pull.request.create.description")
lineWrap = true
}.also {
GHUIUtil.overrideUIDependentProperty(it) {
font = UIUtil.getLabelFont()
}
GHUIUtil.registerFocusActions(it)
}
descriptionDocument.addAndInvokeEnabledStateListener {
descriptionField.isEnabled = descriptionDocument.enabled
}
val descriptionPane = JBScrollPane(descriptionField,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER).apply {
isOpaque = false
border = IdeBorderFactory.createBorder(SideBorder.BOTTOM)
}
val metadataPanel = GHPRMetadataPanelFactory(metadataModel, dataContext.avatarIconsProvider).create().apply {
border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM),
JBUI.Borders.empty(8))
}
val createButton = JBOptionButton(createAction, arrayOf(createDraftAction))
val cancelButton = JButton(cancelAction)
val actionsPanel = JPanel(HorizontalLayout(JBUIScale.scale(8))).apply {
add(createButton)
add(cancelButton)
}
val statusPanel = JPanel(VerticalLayout(8, SwingConstants.LEFT)).apply {
border = JBUI.Borders.empty(8)
add(createNoChangesWarningLabel(directionModel, commitsCountModel))
add(createErrorLabel(createLoadingModel))
add(createErrorLabel(existenceCheckLoadingModel))
add(createErrorAlreadyExistsLabel(existenceCheckLoadingModel))
add(createLoadingLabel(existenceCheckLoadingModel, existenceCheckProgressIndicator))
add(createLoadingLabel(createLoadingModel, progressIndicator))
add(actionsPanel)
}
return JPanel(null).apply {
background = UIUtil.getListBackground()
layout = MigLayout(LC().gridGap("0", "0").insets("0").fill().flowY())
isFocusCycleRoot = true
focusTraversalPolicy = object : LayoutFocusTraversalPolicy() {
override fun getDefaultComponent(aContainer: Container?): Component {
return if (aContainer == this@apply) titleField
else super.getDefaultComponent(aContainer)
}
}
add(directionSelector, CC().growX().pushX().minWidth("0"))
add(titleField, CC().growX().pushX().minWidth("0"))
add(descriptionPane, CC().grow().push().minWidth("0"))
add(metadataPanel, CC().growX().pushX())
add(statusPanel, CC().growX().pushX())
}
}
private inner class InfoController(private val directionModel: GHPRCreateDirectionModel,
private val existenceCheckLoadingModel: GHIOExecutorLoadingModel<GHPRIdentifier?>,
private val existenceCheckProgressIndicator: ListenableProgressIndicator,
private val createAction: AbstractAction,
private val createDraftAction: AbstractAction) {
init {
directionModel.addAndInvokeDirectionChangesListener(::update)
existenceCheckLoadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingCompleted() {
update()
}
})
directionModel.addAndInvokeDirectionChangesListener {
val baseBranch = directionModel.baseBranch
val headRepo = directionModel.headRepo
val headBranch = findCurrentRemoteHead(directionModel)
if (baseBranch == null || headRepo == null || headBranch == null) existenceCheckLoadingModel.reset()
else existenceCheckLoadingModel.load(ProgressWrapper.wrap(existenceCheckProgressIndicator)) {
dataContext.creationService.findPullRequest(it, baseBranch, headRepo, headBranch)
}
}
update()
}
private fun update() {
val enabled = directionModel.let {
it.baseBranch != null && it.headRepo != null && it.headBranch != null &&
(findCurrentRemoteHead(it) == null || (existenceCheckLoadingModel.resultAvailable && existenceCheckLoadingModel.result == null))
}
createAction.isEnabled = enabled
createDraftAction.isEnabled = enabled
}
private fun findCurrentRemoteHead(directionModel: GHPRCreateDirectionModel): GitRemoteBranch? {
val headRepo = directionModel.headRepo ?: return null
val headBranch = directionModel.headBranch ?: return null
if (headBranch is GitRemoteBranch) return headBranch
else headBranch as GitLocalBranch
val gitRemote = headRepo.gitRemote
return GithubGitHelper.findPushTarget(gitRemote.repository, gitRemote.remote, headBranch)?.branch
}
}
private inner class CreateAction(private val directionModel: GHPRCreateDirectionModel,
private val titleDocument: Document, private val descriptionDocument: DisableableDocument,
private val metadataModel: GHPRCreateMetadataModel,
private val draft: Boolean,
private val loadingModel: GHCompletableFutureLoadingModel<GHPullRequestShort>,
private val progressIndicator: ProgressIndicator,
@NlsActions.ActionText name: String) : AbstractAction(name) {
override fun actionPerformed(e: ActionEvent?) {
val baseBranch = directionModel.baseBranch ?: return
val headRepo = directionModel.headRepo ?: return
val headBranch = directionModel.headBranch ?: return
val reviewers = metadataModel.reviewers
val assignees = metadataModel.assignees
val labels = metadataModel.labels
loadingModel.future = if (headBranch is GitRemoteBranch) {
CompletableFuture.completedFuture(headBranch)
}
else {
findOrPushRemoteBranch(progressIndicator,
headRepo.gitRemote.repository,
headRepo.gitRemote.remote,
headBranch as GitLocalBranch)
}.thenCompose { remoteHeadBranch ->
dataContext.creationService
.createPullRequest(progressIndicator, baseBranch, headRepo, remoteHeadBranch,
titleDocument.text, descriptionDocument.text, draft)
.thenCompose { adjustReviewers(it, reviewers) }
.thenCompose { adjustAssignees(it, assignees) }
.thenCompose { adjustLabels(it, labels) }
.successOnEdt {
if (!progressIndicator.isCanceled) {
viewController.viewPullRequest(it)
settings.recentNewPullRequestHead = headRepo.repository
viewController.resetNewPullRequestView()
}
it
}
}
}
private fun findOrPushRemoteBranch(progressIndicator: ProgressIndicator,
repository: GitRepository,
remote: GitRemote,
localBranch: GitLocalBranch): CompletableFuture<GitRemoteBranch> {
val gitPushSupport = DvcsUtil.getPushSupport(GitVcs.getInstance(project)) as? GitPushSupport
?: return CompletableFuture.failedFuture(ProcessCanceledException())
val existingPushTarget = GithubGitHelper.findPushTarget(repository, remote, localBranch)
if (existingPushTarget != null) {
val localHash = repository.branches.getHash(localBranch)
val remoteHash = repository.branches.getHash(existingPushTarget.branch)
if (localHash == remoteHash) return CompletableFuture.completedFuture(existingPushTarget.branch)
}
val pushTarget = existingPushTarget
?: inputPushTarget(repository, remote, localBranch)
?: return CompletableFuture.failedFuture(ProcessCanceledException())
val future = CompletableFuture<GitRemoteBranch>()
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
object : Task.Backgroundable(repository.project, DvcsBundle.message("push.process.pushing"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DvcsBundle.message("push.process.pushing")
val pushSpec = PushSpec(GitPushSource.create(localBranch), pushTarget)
val pushResult = GitPushOperation(repository.project, gitPushSupport, mapOf(repository to pushSpec), null, false, false)
.execute().results[repository] ?: error("Missing push result")
check(pushResult.error == null) {
GithubBundle.message("pull.request.create.push.failed", pushResult.error.orEmpty())
}
}
override fun onSuccess() {
future.complete(pushTarget.branch)
}
override fun onThrowable(error: Throwable) {
future.completeExceptionally(error)
}
override fun onCancel() {
future.completeExceptionally(ProcessCanceledException())
}
}, progressIndicator)
return future
}
private fun inputPushTarget(repository: GitRepository, remote: GitRemote, localBranch: GitLocalBranch): GitPushTarget? {
val branchName = MessagesService.getInstance().showInputDialog(repository.project, null,
GithubBundle.message("pull.request.create.input.remote.branch.name"),
GithubBundle.message("pull.request.create.input.remote.branch.title"),
null, localBranch.name, null, null,
GithubBundle.message("pull.request.create.input.remote.branch.comment",
localBranch.name, remote.name))
?: return null
//always set tracking
return GitPushTarget(GitStandardRemoteBranch(remote, GitRefNameValidator.getInstance().cleanUpBranchName(branchName)), true)
}
private fun adjustReviewers(pullRequest: GHPullRequestShort, reviewers: List<GHPullRequestRequestedReviewer>)
: CompletableFuture<GHPullRequestShort> {
return if (reviewers.isNotEmpty()) {
dataContext.detailsService.adjustReviewers(ProgressWrapper.wrap(progressIndicator), pullRequest,
CollectionDelta(emptyList(), reviewers))
.thenApply { pullRequest }
}
else CompletableFuture.completedFuture(pullRequest)
}
private fun adjustAssignees(pullRequest: GHPullRequestShort, assignees: List<GHUser>)
: CompletableFuture<GHPullRequestShort> {
return if (assignees.isNotEmpty()) {
dataContext.detailsService.adjustAssignees(ProgressWrapper.wrap(progressIndicator), pullRequest,
CollectionDelta(emptyList(), assignees))
.thenApply { pullRequest }
}
else CompletableFuture.completedFuture(pullRequest)
}
private fun adjustLabels(pullRequest: GHPullRequestShort, labels: List<GHLabel>)
: CompletableFuture<GHPullRequestShort> {
return if (labels.isNotEmpty()) {
dataContext.detailsService.adjustLabels(ProgressWrapper.wrap(progressIndicator), pullRequest,
CollectionDelta(emptyList(), labels))
.thenApply { pullRequest }
}
else CompletableFuture.completedFuture(pullRequest)
}
}
private fun createErrorAlreadyExistsLabel(loadingModel: GHSimpleLoadingModel<GHPRIdentifier?>): JComponent {
val label = JLabel(AllIcons.Ide.FatalError).apply {
foreground = UIUtil.getErrorForeground()
text = GithubBundle.message("pull.request.create.already.exists")
}
val link = ActionLink(GithubBundle.message("pull.request.create.already.exists.view")) {
loadingModel.result?.let(viewController::viewPullRequest)
}
val panel = JPanel(HorizontalLayout(10)).apply {
add(label)
add(link)
}
fun update() {
panel.isVisible = loadingModel.resultAvailable && loadingModel.result != null
}
loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = update()
override fun onLoadingCompleted() = update()
})
update()
return panel
}
companion object {
private val Document.text: String get() = getText(0, length)
private fun createNoChangesWarningLabel(directionModel: GHPRCreateDirectionModel,
commitsCountModel: SingleValueModel<Int?>): JComponent {
val label = JLabel(AllIcons.General.Warning)
fun update() {
val commits = commitsCountModel.value
label.isVisible = commits == 0
val base = directionModel.baseBranch?.name.orEmpty()
val head = directionModel.headBranch?.name.orEmpty()
label.text = GithubBundle.message("pull.request.create.no.changes", base, head)
}
commitsCountModel.addValueChangedListener(::update)
commitsCountModel.addAndInvokeValueChangedListener(::update)
return label
}
private fun createErrorLabel(loadingModel: GHLoadingModel): JLabel {
val label = JLabel(AllIcons.Ide.FatalError).apply {
foreground = UIUtil.getErrorForeground()
}
fun update() {
label.isVisible = loadingModel.error != null
label.text = loadingModel.error?.message
}
loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = update()
override fun onLoadingCompleted() = update()
})
update()
return label
}
private fun createLoadingLabel(loadingModel: GHLoadingModel, progressIndicator: ListenableProgressIndicator): JLabel {
val label = JLabel(AnimatedIcon.Default())
fun updateVisible() {
label.isVisible = loadingModel.loading
}
loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = updateVisible()
override fun onLoadingCompleted() = updateVisible()
})
updateVisible()
progressIndicator.addAndInvokeListener {
label.text = progressIndicator.text
}
return label
}
private class ListenableProgressIndicator : AbstractProgressIndicatorExBase(), StandardProgressIndicator {
private val eventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
override fun isReuseable() = true
override fun onProgressChange() = invokeAndWaitIfNeeded { eventDispatcher.multicaster.eventOccurred() }
fun addAndInvokeListener(listener: () -> Unit) = SimpleEventListener.addAndInvokeListener(eventDispatcher, listener)
override fun cancel() = super.cancel()
override fun isCanceled() = super.isCanceled()
}
}
} | apache-2.0 | a3da2bb057002a26f1faa6bb5b5d8a37 | 47.683628 | 140 | 0.685921 | 5.542569 | false | false | false | false |
zdary/intellij-community | plugins/git4idea/src/git4idea/stash/ui/GitUnstashAsDialog.kt | 3 | 3725 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.stash.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.ui.layout.*
import com.intellij.vcs.branch.BranchPresentation
import git4idea.GitUtil
import git4idea.i18n.GitBundle
import git4idea.ui.StashInfo
import git4idea.validators.validateName
import javax.swing.JComponent
import javax.swing.event.DocumentEvent
internal class GitUnstashAsDialog(private val project: Project, val stashInfo: StashInfo) : DialogWrapper(project) {
private val branchTextField = JBTextField()
private val popStashCheckbox = JBCheckBox(GitBundle.message("unstash.pop.stash")).apply {
toolTipText = GitBundle.message("unstash.pop.stash.tooltip")
}
private val keepIndexCheckbox = JBCheckBox(GitBundle.message("unstash.reinstate.index")).apply {
toolTipText = GitBundle.message("unstash.reinstate.index.tooltip")
}
var popStash: Boolean = false
private set
var keepIndex: Boolean = false
private set
var branch: String = ""
private set
init {
title = GitBundle.message("stash.unstash.changes.in.root.dialog.title", stashInfo.root.presentableName)
init()
branchTextField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
onBranchChanged()
}
})
popStashCheckbox.addActionListener { onPopStashChanged() }
updateOkButtonText()
}
override fun createCenterPanel(): JComponent {
return panel {
row(GitBundle.message("stash.unstash.changes.current.branch.label")) {
label(CurrentBranchComponent.getCurrentBranch(project, stashInfo.root)?.let { BranchPresentation.getPresentableText(it) } ?: "")
}
row(GitBundle.message("unstash.branch.label")) {
branchTextField().withBinding(JBTextField::getText, JBTextField::setText,
PropertyBinding({ branch }, { value -> branch = value})
).withValidationOnInput {
if (it.text.isBlank()) return@withValidationOnInput null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(stashInfo.root)
?: return@withValidationOnInput null
validateName(listOf(repository), it.text)
}.focused()
}
row {
popStashCheckbox().withBinding(
JBCheckBox::isSelected, JBCheckBox::setSelected,
PropertyBinding({ popStash }, { value -> popStash = value }),
)
}
row {
keepIndexCheckbox().withBinding(
JBCheckBox::isSelected, JBCheckBox::setSelected,
PropertyBinding({ keepIndex }, { value -> keepIndex = value }),
)
}
}
}
private fun onBranchChanged() {
updateEnabled()
updateOkButtonText()
}
private fun onPopStashChanged() {
updateOkButtonText()
}
private fun updateEnabled() {
val hasBranch = branchTextField.text.isNotBlank()
popStashCheckbox.isEnabled = !hasBranch
keepIndexCheckbox.isEnabled = !hasBranch
}
private fun updateOkButtonText() {
val buttonText = when {
branchTextField.text.isNotBlank() -> {
GitBundle.message("unstash.button.branch")
}
popStashCheckbox.isSelected -> GitBundle.message("unstash.button.pop")
else -> GitBundle.message("unstash.button.apply")
}
setOKButtonText(buttonText)
}
}
| apache-2.0 | 9dcf1c49bd4fc01c661b04cee668da17 | 35.165049 | 140 | 0.70604 | 4.53163 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.