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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acristescu/GreenfieldTemplate | app/src/main/java/io/zenandroid/greenfield/feed/FeedActivity.kt | 1 | 5679 | package io.zenandroid.greenfield.feed
import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.appcompat.widget.SearchView
import android.widget.Toast
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
import io.zenandroid.greenfield.R
import io.zenandroid.greenfield.base.BaseActivity
import io.zenandroid.greenfield.dagger.Injector
import io.zenandroid.greenfield.model.Image
import io.zenandroid.greenfield.service.FlickrService
import kotlinx.android.synthetic.main.activity_feed.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions
import javax.inject.Inject
/**
* Created by alex on 25/01/2018.
*/
@RuntimePermissions
class FeedActivity : BaseActivity(), FeedContract.View {
private lateinit var presenter: FeedContract.Presenter
private val adapter = FeedImageAdapter()
@Inject lateinit var flickrService: FlickrService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Injector.get().inject(this)
setContentView(R.layout.activity_feed)
setSupportActionBar(toolbar)
supportActionBar?.setTitle(R.string.public_images)
recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recycler.adapter = adapter
swipeRefreshLayout.setOnRefreshListener { presenter.onRefresh() }
adapter.browseImageClicks().subscribe { image -> presenter.onBrowseImage(image) }
adapter.shareImageClicks().subscribe { image -> presenter.onShareImage(image) }
adapter.saveImageClicks().subscribe { image -> presenter.onSaveImage(image) }
presenter = FeedPresenter(this, flickrService)
searchView.maxWidth = Integer.MAX_VALUE
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
presenter.onSearch(query)
return true
}
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
sort.setOnClickListener { onSortClicked() }
}
override fun onResume() {
super.onResume()
presenter.subscribe()
}
override fun onPause() {
super.onPause()
presenter.unsubscribe()
}
override fun showImages(items: List<Image>) {
adapter.setImageList(items)
}
override fun closeSearchBox() {
searchView.onActionViewCollapsed()
}
override fun setSubTitle(subtitle: String) {
supportActionBar?.subtitle = subtitle
}
override fun browseURL(link: String) {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
startActivity(browserIntent)
}
override fun loadImageFromURL(url: String, target: Target) {
Picasso.get()
.load(url)
.into(target)
}
override fun saveBitmapToGallery(bitmap: Bitmap, title: String, description: String) {
saveBitmapToGalleryImplWithPermissionCheck(bitmap, title, description)
}
override fun sendEmail(url: String) {
val TO = arrayOf("")
val CC = arrayOf("")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.data = Uri.parse("mailto:")
emailIntent.type = "text/plain"
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject))
emailIntent.putExtra(Intent.EXTRA_TEXT, url)
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO)
emailIntent.putExtra(Intent.EXTRA_CC, CC)
startActivity(Intent.createChooser(emailIntent, getString(R.string.send_mail)))
}
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
internal fun saveBitmapToGalleryImpl(bitmap: Bitmap, title: String, description: String) {
val path = MediaStore.Images.Media.insertImage(contentResolver, bitmap, title, description)
if (path == null) {
showErrorMessage("Save failed")
} else {
Toast.makeText(this, "Saved under $path", Toast.LENGTH_LONG).show()
}
}
@OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
internal fun showPermissionDeniedMessage() {
showErrorMessage("Cannot save image because permission request was rejected")
}
private fun onSortClicked() {
val d = AlertDialog.Builder(this)
.setTitle("Select sorting")
.setItems(arrayOf("Date Published", "Date Taken")) { _, position ->
when (position) {
0 -> presenter.onSortBy(FeedContract.SortCriterion.PUBLISHED)
1 -> presenter.onSortBy(FeedContract.SortCriterion.TAKEN)
}
}
.create()
d.show()
}
override fun showProgressDialog() {
swipeRefreshLayout.isRefreshing = true
}
override fun dismissProgressDialog() {
swipeRefreshLayout.isRefreshing = false
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// NOTE: delegate the permission handling to generated function
onRequestPermissionsResult(requestCode, grantResults)
}
}
| apache-2.0 | 8ae77c308b2987088f65e59a2f307558 | 34.49375 | 115 | 0.688854 | 4.990334 | false | false | false | false |
ifabijanovic/swtor-holonet | android/app/src/main/java/com/ifabijanovic/holonet/forum/data/ForumCategoryRepository.kt | 1 | 4386 | package com.ifabijanovic.holonet.forum.data
import com.ifabijanovic.holonet.app.model.Settings
import com.ifabijanovic.holonet.forum.language.ForumLanguage
import com.ifabijanovic.holonet.forum.model.ForumCategory
import com.ifabijanovic.holonet.forum.model.ForumMaintenanceException
import com.ifabijanovic.holonet.helper.StringHelper
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
/**
* Created by feb on 20/03/2017.
*/
interface ForumCategoryRepository {
fun categories(language: ForumLanguage): Observable<List<ForumCategory>>
fun categories(language: ForumLanguage, parent: ForumCategory): Observable<List<ForumCategory>>
}
class DefaultForumCategoryRepository(parser: ForumParser, service: ForumService, settings: Settings): ForumRepositoryBase(parser, service, settings), ForumCategoryRepository {
override fun categories(language: ForumLanguage): Observable<List<ForumCategory>> {
val localizedSettings = this.localizedSettings(language)
return this.categories(localizedSettings.pathPrefix, localizedSettings.rootCategoryId)
}
override fun categories(language: ForumLanguage, parent: ForumCategory): Observable<List<ForumCategory>> {
val localizedSettings = this.localizedSettings(language)
return this.categories(localizedSettings.pathPrefix, parent.id)
}
private fun categories(language: String, categoryId: Int): Observable<List<ForumCategory>> {
return this.service
.category(language, categoryId)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map { html ->
val items = this.parse(html)
if (items.isEmpty() && this.isMaintenance(html)) {
throw ForumMaintenanceException()
}
return@map items
}
}
private fun parse(html: String): List<ForumCategory> {
val items = mutableListOf<ForumCategory>()
Jsoup.parse(html)
.select(".forumCategory > .subForum")
.mapNotNullTo(items) { this.parseCategory(it) }
return items.toList()
}
private fun parseCategory(element: Element): ForumCategory? {
// Id & Title
val titleElement = element.select(".resultTitle > a")?.first()
val idString = this.parser.linkParameter(titleElement, this.settings.categoryQueryParam)
var id: Int?
try {
id = idString?.toInt()
} catch (e: Exception) {
id = null
}
val title = titleElement?.text()
// Icon
var iconUrl: String? = null
val thumbElement = element.select(".thumbBackground")?.first()
if (thumbElement != null) {
val iconStyle = thumbElement.attr("style")
if (iconStyle != null) {
val startString = "url("
val start = iconStyle.indexOf(startString, 0, true)
val end = iconStyle.indexOf(")", 0, true)
iconUrl = iconStyle.substring(start + startString.count(), end)
}
}
// Description
val description = element.select(".resultText")?.first()?.text()
// Stats & Last post
var stats: String? = null
var lastPost: String? = null
val subTextElements = element.select(".resultSubText")
if (subTextElements.size > 0) {
stats = subTextElements[0].text()
}
if (subTextElements.size > 1) {
lastPost = subTextElements[1].text()
}
if (id == null) { return null }
if (title == null) { return null }
val finalTitle = StringHelper(title).stripNewLinesAndTabs().trimSpaces().collapseMultipleSpaces().value
val finalDescription = if (description != null) StringHelper(description).trimSpaces().value else null
val finalStats = if (stats != null) StringHelper(stats).stripNewLinesAndTabs().trimSpaces().collapseMultipleSpaces().value else null
val finalLastPost = if (lastPost != null) StringHelper(lastPost).stripNewLinesAndTabs().trimSpaces().collapseMultipleSpaces().value else null
return ForumCategory(id, iconUrl, finalTitle, finalDescription, finalStats, finalLastPost)
}
}
| gpl-3.0 | 2a29a80c7482ae1a10832fb69a274390 | 39.990654 | 175 | 0.652303 | 4.64127 | false | false | false | false |
vnesek/nmote-jwt-issuer | src/main/kotlin/com/nmote/jwti/model/App.kt | 1 | 2495 | /*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.model
import com.fasterxml.jackson.annotation.JsonInclude
import io.jsonwebtoken.JwtParser
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import java.security.Key
import java.util.*
import java.util.regex.Pattern
import javax.crypto.spec.SecretKeySpec
class Client {
var expiresIn: Long? = null
lateinit var clientId: String
lateinit var clientSecret: String
var success: String = "/login-success"
var failure: String = "/login-failure"
var roles: Set<String> = emptySet()
}
@JsonInclude(JsonInclude.Include.NON_NULL)
data class AppData(
val id: String,
val audience: String?,
val roles: Set<String>
)
class App {
lateinit var id: String
var clients: MutableMap<String, Client> = mutableMapOf()
lateinit var audience: String
var roleForEmail: Map<String, Pattern> = mutableMapOf()
lateinit var secret: String
val roles: Set<String> get() = roleForEmail.keys
val key: Key by lazy {
val (id, encoded) = secret.split(':', limit = 2)
val algorithm = SignatureAlgorithm.valueOf(id)
val decoded = Base64.getDecoder().decode(encoded)
SecretKeySpec(decoded, algorithm.jcaName)
}
val algorithm: SignatureAlgorithm by lazy {
SignatureAlgorithm.valueOf(secret.substringBefore(':'))
}
fun rolesFor(email: Iterable<String>): Set<String> {
val result = mutableSetOf<String>()
roleForEmail.filterValues { it.matchesAny(email) }.mapTo(result, Map.Entry<String, *>::key)
return result
}
val parser: JwtParser by lazy { Jwts.parser().setSigningKey(key) }
fun toAppData() = AppData(id, audience, roles)
}
private fun Pattern.matchesAny(input: Iterable<String>): Boolean {
val matcher = matcher("")
return input.find { matcher.reset(it).matches() } != null
} | apache-2.0 | 27e0bc3c662fb599069df1a554b0aa6c | 29.072289 | 99 | 0.697796 | 4.024194 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UClass.kt | 1 | 3147 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiClass
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A class wrapper to be used in [UastVisitor].
*/
interface UClass : UDeclaration, PsiClass {
override val psi: PsiClass
override fun getQualifiedName(): String?
/**
* Returns a [UClass] wrapper of the superclass of this class, or null if this class is [java.lang.Object].
*/
override fun getSuperClass(): UClass? {
val superClass = psi.superClass ?: return null
return getUastContext().convertWithParent(superClass)
}
val uastSuperTypes: List<UTypeReferenceExpression>
/**
* Returns [UDeclaration] wrappers for the class declarations.
*/
val uastDeclarations: List<UDeclaration>
override fun getFields(): Array<UField> =
psi.fields.map { getLanguagePlugin().convert<UField>(it, this) }.toTypedArray()
override fun getInitializers(): Array<UClassInitializer> =
psi.initializers.map { getLanguagePlugin().convert<UClassInitializer>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> =
psi.methods.map { getLanguagePlugin().convert<UMethod>(it, this) }.toTypedArray()
override fun getInnerClasses(): Array<UClass> =
psi.innerClasses.map { getLanguagePlugin().convert<UClass>(it, this) }.toTypedArray()
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitClass(this)) return
annotations.acceptList(visitor)
uastDeclarations.acceptList(visitor)
visitor.afterVisitClass(this)
}
override fun asRenderString() = buildString {
append(psi.renderModifiers())
val kind = when {
psi.isAnnotationType -> "annotation"
psi.isInterface -> "interface"
psi.isEnum -> "enum"
else -> "class"
}
append(kind).append(' ').append(psi.name)
val superTypes = uastSuperTypes
if (superTypes.isNotEmpty()) {
append(" : ")
append(superTypes.joinToString { it.asRenderString() })
}
appendln(" {")
uastDeclarations.forEachIndexed { index, declaration ->
appendln(declaration.asRenderString().withMargin)
}
append("}")
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitClass(this, data)
}
interface UAnonymousClass : UClass, PsiAnonymousClass {
override val psi: PsiAnonymousClass
} | apache-2.0 | 8595a697738cff095a7c8ab138f93951 | 31.791667 | 109 | 0.719415 | 4.401399 | false | false | false | false |
getsentry/raven-java | sentry/src/test/java/io/sentry/HubTest.kt | 1 | 42476 | package io.sentry
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.argWhere
import com.nhaarman.mockitokotlin2.check
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doThrow
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.hints.SessionEndHint
import io.sentry.hints.SessionStartHint
import io.sentry.protocol.SentryId
import io.sentry.protocol.SentryTransaction
import io.sentry.protocol.User
import io.sentry.test.callMethod
import java.io.File
import java.nio.file.Files
import java.util.Queue
import java.util.UUID
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.test.fail
class HubTest {
private lateinit var file: File
@BeforeTest
fun `set up`() {
file = Files.createTempDirectory("sentry-disk-cache-test").toAbsolutePath().toFile()
}
@AfterTest
fun shutdown() {
file.deleteRecursively()
Sentry.close()
}
@Test
fun `when no dsn available, ctor throws illegal arg`() {
val ex = assertFailsWith<IllegalArgumentException> { Hub(SentryOptions()) }
assertEquals("Hub requires a DSN to be instantiated. Considering using the NoOpHub is no DSN is available.", ex.message)
}
@Ignore("Sentry static class is registering integrations")
@Test
fun `when a root hub is initialized, integrations are registered`() {
val integrationMock = mock<Integration>()
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
options.addIntegration(integrationMock)
val expected = HubAdapter.getInstance()
Hub(options)
verify(integrationMock).register(expected, options)
}
@Test
fun `when hub is cloned, integrations are not registered`() {
val integrationMock = mock<Integration>()
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
options.addIntegration(integrationMock)
// val expected = HubAdapter.getInstance()
val hub = Hub(options)
// verify(integrationMock).register(expected, options)
hub.clone()
verifyNoMoreInteractions(integrationMock)
}
@Test
fun `when hub is cloned, scope changes are isolated`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val hub = Hub(options)
var firstScope: Scope? = null
hub.configureScope {
firstScope = it
it.setTag("hub", "a")
}
var cloneScope: Scope? = null
val clone = hub.clone()
clone.configureScope {
cloneScope = it
it.setTag("hub", "b")
}
assertEquals("a", firstScope!!.tags["hub"])
assertEquals("b", cloneScope!!.tags["hub"])
}
@Test
fun `when hub is initialized, breadcrumbs are capped as per options`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.maxBreadcrumbs = 5
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
(1..10).forEach { _ -> sut.addBreadcrumb(Breadcrumb(), null) }
var actual = 0
sut.configureScope {
actual = it.breadcrumbs.size
}
assertEquals(options.maxBreadcrumbs, actual)
}
@Test
fun `when beforeBreadcrumb returns null, crumb is dropped`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.beforeBreadcrumb = SentryOptions.BeforeBreadcrumbCallback { _: Breadcrumb, _: Any? -> null }
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
sut.addBreadcrumb(Breadcrumb(), null)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
assertEquals(0, breadcrumbs!!.size)
}
@Test
fun `when beforeBreadcrumb modifies crumb, crumb is stored modified`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
val expected = "expected"
options.beforeBreadcrumb = SentryOptions.BeforeBreadcrumbCallback { breadcrumb: Breadcrumb, _: Any? -> breadcrumb.message = expected; breadcrumb; }
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val crumb = Breadcrumb()
crumb.message = "original"
sut.addBreadcrumb(crumb)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
assertEquals(expected, breadcrumbs!!.first().message)
}
@Test
fun `when beforeBreadcrumb is null, crumb is stored`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.beforeBreadcrumb = null
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val expected = Breadcrumb()
sut.addBreadcrumb(expected)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
assertEquals(expected, breadcrumbs!!.single())
}
@Test
fun `when beforeSend throws an exception, breadcrumb adds an entry to the data field with exception message`() {
val exception = Exception("test")
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.beforeBreadcrumb = SentryOptions.BeforeBreadcrumbCallback { _: Breadcrumb, _: Any? -> throw exception }
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val actual = Breadcrumb()
sut.addBreadcrumb(actual)
assertEquals("test", actual.data["sentry:message"])
}
@Test
fun `when initialized, lastEventId is empty`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
assertEquals(SentryId.EMPTY_ID, sut.lastEventId)
}
@Test
fun `when addBreadcrumb is called on disabled client, no-op`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
sut.close()
sut.addBreadcrumb(Breadcrumb())
assertTrue(breadcrumbs!!.isEmpty())
}
@Test
fun `when addBreadcrumb is called with message and category, breadcrumb object has values`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
sut.addBreadcrumb("message", "category")
assertEquals("message", breadcrumbs!!.single().message)
assertEquals("category", breadcrumbs!!.single().category)
}
@Test
fun `when addBreadcrumb is called with message, breadcrumb object has value`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
var breadcrumbs: Queue<Breadcrumb>? = null
sut.configureScope { breadcrumbs = it.breadcrumbs }
sut.addBreadcrumb("message", "category")
assertEquals("message", breadcrumbs!!.single().message)
assertEquals("category", breadcrumbs!!.single().category)
}
@Test
fun `when flush is called on disabled client, no-op`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.flush(1000)
verify(mockClient, never()).flush(1000)
}
@Test
fun `when flush is called, client flush gets called`() {
val (sut, mockClient) = getEnabledHub()
sut.flush(1000)
verify(mockClient).flush(1000)
}
//region captureEvent tests
@Test
fun `when captureEvent is called and event is null, lastEventId is empty`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
sut.callMethod("captureEvent", SentryEvent::class.java, null)
assertEquals(SentryId.EMPTY_ID, sut.lastEventId)
}
@Test
fun `when captureEvent is called on disabled client, do nothing`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.captureEvent(SentryEvent())
verify(mockClient, never()).captureEvent(any(), any())
}
@Test
fun `when captureEvent is called with a valid argument, captureEvent on the client should be called`() {
val (sut, mockClient) = getEnabledHub()
val event = SentryEvent()
val hint = { }
sut.captureEvent(event, hint)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
@Test
fun `when captureEvent is called on disabled hub, lastEventId does not get overwritten`() {
val (sut, mockClient) = getEnabledHub()
whenever(mockClient.captureEvent(any(), any(), anyOrNull())).thenReturn(SentryId(UUID.randomUUID()))
val event = SentryEvent()
val hint = { }
sut.captureEvent(event, hint)
val lastEventId = sut.lastEventId
sut.close()
sut.captureEvent(event, hint)
assertEquals(lastEventId, sut.lastEventId)
}
@Test
fun `when captureEvent is called and session tracking is disabled, it should not capture a session`() {
val (sut, mockClient) = getEnabledHub()
val event = SentryEvent()
val hint = { }
sut.captureEvent(event, hint)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
verify(mockClient, never()).captureSession(any(), any())
}
@Test
fun `when captureEvent is called but no session started, it should not capture a session`() {
val (sut, mockClient) = getEnabledHub()
val event = SentryEvent()
val hint = { }
sut.captureEvent(event, hint)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
verify(mockClient, never()).captureSession(any(), any())
}
@Test
fun `when captureEvent is called and event has exception which has been previously attached with span context, sets span context to the event`() {
val (sut, mockClient) = getEnabledHub()
val exception = RuntimeException()
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(exception, span, "tx-name")
val event = SentryEvent(exception)
val hint = { }
sut.captureEvent(event, hint)
assertEquals(span.spanContext, event.contexts.trace)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
@Test
fun `when captureEvent is called and event has exception which root cause has been previously attached with span context, sets span context to the event`() {
val (sut, mockClient) = getEnabledHub()
val rootCause = RuntimeException()
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(rootCause, span, "tx-name")
val event = SentryEvent(RuntimeException(rootCause))
val hint = { }
sut.captureEvent(event, hint)
assertEquals(span.spanContext, event.contexts.trace)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
@Test
fun `when captureEvent is called and event has exception which non-root cause has been previously attached with span context, sets span context to the event`() {
val (sut, mockClient) = getEnabledHub()
val rootCause = RuntimeException()
val exceptionAssignedToSpan = RuntimeException(rootCause)
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(exceptionAssignedToSpan, span, "tx-name")
val event = SentryEvent(RuntimeException(exceptionAssignedToSpan))
val hint = { }
sut.captureEvent(event, hint)
assertEquals(span.spanContext, event.contexts.trace)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
@Test
fun `when captureEvent is called and event has exception which has been previously attached with span context and trace context already set, does not set new span context to the event`() {
val (sut, mockClient) = getEnabledHub()
val exception = RuntimeException()
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(exception, span, "tx-name")
val event = SentryEvent(exception)
val originalSpanContext = SpanContext("op")
event.contexts.trace = originalSpanContext
val hint = { }
sut.captureEvent(event, hint)
assertEquals(originalSpanContext, event.contexts.trace)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
@Test
fun `when captureEvent is called and event has exception which has not been previously attached with span context, does not set new span context to the event`() {
val (sut, mockClient) = getEnabledHub()
val event = SentryEvent(RuntimeException())
val hint = { }
sut.captureEvent(event, hint)
assertNull(event.contexts.trace)
verify(mockClient).captureEvent(eq(event), any(), eq(hint))
}
//endregion
//region captureMessage tests
@Test
fun `when captureMessage is called and event is null, lastEventId is empty`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
sut.callMethod("captureMessage", String::class.java, null)
assertEquals(SentryId.EMPTY_ID, sut.lastEventId)
}
@Test
fun `when captureMessage is called on disabled client, do nothing`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.captureMessage("test")
verify(mockClient, never()).captureMessage(any(), any())
}
@Test
fun `when captureMessage is called with a valid message, captureMessage on the client should be called`() {
val (sut, mockClient) = getEnabledHub()
sut.captureMessage("test")
verify(mockClient).captureMessage(any(), any(), any())
}
@Test
fun `when captureMessage is called, level is INFO by default`() {
val (sut, mockClient) = getEnabledHub()
sut.captureMessage("test")
verify(mockClient).captureMessage(eq("test"), eq(SentryLevel.INFO), any())
}
//endregion
//region captureException tests
@Test
fun `when captureException is called and exception is null, lastEventId is empty`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
sut.callMethod("captureException", Throwable::class.java, null)
assertEquals(SentryId.EMPTY_ID, sut.lastEventId)
}
@Test
fun `when captureException is called on disabled client, do nothing`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.captureException(Throwable())
verify(mockClient, never()).captureEvent(any(), any(), any())
}
@Test
fun `when captureException is called with a valid argument and hint, captureEvent on the client should be called`() {
val (sut, mockClient) = getEnabledHub()
sut.captureException(Throwable(), Object())
verify(mockClient).captureEvent(any(), any(), any())
}
@Test
fun `when captureException is called with a valid argument but no hint, captureEvent on the client should be called`() {
val (sut, mockClient) = getEnabledHub()
sut.captureException(Throwable())
verify(mockClient).captureEvent(any(), any(), isNull())
}
@Test
fun `when captureException is called with an exception which has been previously attached with span context, span context should be set on the event before capturing`() {
val (sut, mockClient) = getEnabledHub()
val throwable = Throwable()
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(throwable, span, "tx-name")
sut.captureException(throwable)
verify(mockClient).captureEvent(check {
assertEquals(span.spanContext, it.contexts.trace)
assertEquals("tx-name", it.transaction)
}, any(), anyOrNull())
}
@Test
fun `when captureException is called with an exception which has not been previously attached with span context, span context should not be set on the event before capturing`() {
val (sut, mockClient) = getEnabledHub()
val span = mock<Span>()
whenever(span.spanContext).thenReturn(SpanContext("op"))
sut.setSpanContext(Throwable(), span, "tx-name")
sut.captureException(Throwable())
verify(mockClient).captureEvent(check {
assertNull(it.contexts.trace)
}, any(), anyOrNull())
}
//endregion
//region captureUserFeedback tests
@Test
fun `when captureUserFeedback is called it is forwarded to the client`() {
val (sut, mockClient) = getEnabledHub()
sut.captureUserFeedback(userFeedback)
verify(mockClient).captureUserFeedback(check {
assertEquals(userFeedback.eventId, it.eventId)
assertEquals(userFeedback.email, it.email)
assertEquals(userFeedback.name, it.name)
assertEquals(userFeedback.comments, it.comments)
})
}
@Test
fun `when captureUserFeedback is called on disabled client, do nothing`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.captureUserFeedback(userFeedback)
verify(mockClient, never()).captureUserFeedback(any())
}
@Test
fun `when captureUserFeedback is called and client throws, don't crash`() {
val (sut, mockClient) = getEnabledHub()
whenever(mockClient.captureUserFeedback(any())).doThrow(IllegalArgumentException(""))
sut.captureUserFeedback(userFeedback)
}
private val userFeedback: UserFeedback get() {
val eventId = SentryId("c2fb8fee2e2b49758bcb67cda0f713c7")
return UserFeedback(eventId).apply {
name = "John"
email = "[email protected]"
comments = "comment"
}
}
//endregion
//region close tests
@Test
fun `when close is called on disabled client, do nothing`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
sut.close()
verify(mockClient).close() // 1 to close, but next one wont be recorded
}
@Test
fun `when close is called and client is alive, close on the client should be called`() {
val (sut, mockClient) = getEnabledHub()
sut.close()
verify(mockClient).close()
}
//endregion
//region withScope tests
@Test
fun `when withScope is called on disabled client, do nothing`() {
val (sut) = getEnabledHub()
val scopeCallback = mock<ScopeCallback>()
sut.close()
sut.withScope(scopeCallback)
verify(scopeCallback, never()).run(any())
}
@Test
fun `when withScope is called with alive client, run should be called`() {
val (sut) = getEnabledHub()
val scopeCallback = mock<ScopeCallback>()
sut.withScope(scopeCallback)
verify(scopeCallback).run(any())
}
//endregion
//region configureScope tests
@Test
fun `when configureScope is called on disabled client, do nothing`() {
val (sut) = getEnabledHub()
val scopeCallback = mock<ScopeCallback>()
sut.close()
sut.configureScope(scopeCallback)
verify(scopeCallback, never()).run(any())
}
@Test
fun `when configureScope is called with alive client, run should be called`() {
val (sut) = getEnabledHub()
val scopeCallback = mock<ScopeCallback>()
sut.configureScope(scopeCallback)
verify(scopeCallback).run(any())
}
//endregion
@Test
fun `when integration is registered, hub is enabled`() {
val mock = mock<Integration>()
var options: SentryOptions? = null
// init main hub and make it enabled
Sentry.init {
it.addIntegration(mock)
it.dsn = "https://[email protected]/proj"
it.cacheDirPath = file.absolutePath
it.setSerializer(mock())
options = it
}
doAnswer {
val hub = it.arguments[0] as IHub
assertTrue(hub.isEnabled)
}.whenever(mock).register(any(), eq(options!!))
verify(mock).register(any(), eq(options!!))
}
//region setLevel tests
@Test
fun `when setLevel is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
hub.setLevel(SentryLevel.INFO)
assertNull(scope?.level)
}
@Test
fun `when setLevel is called, level is set`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.setLevel(SentryLevel.INFO)
assertEquals(SentryLevel.INFO, scope?.level)
}
//endregion
//region setTransaction tests
@Test
fun `when setTransaction is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
hub.setTransaction("test")
assertNull(scope?.transactionName)
}
@Test
fun `when setTransaction is called, and transaction is not set, transaction name is changed`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.setTransaction("test")
assertEquals("test", scope?.transactionName)
}
@Test
fun `when setTransaction is called, and transaction is set, transaction name is changed`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
val tx = hub.startTransaction("test", "op")
hub.configureScope { it.setTransaction(tx) }
assertEquals("test", scope?.transactionName)
}
//endregion
//region setUser tests
@Test
fun `when setUser is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
hub.setUser(User())
assertNull(scope?.user)
}
@Test
fun `when setUser is called, user is set`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
val user = User()
hub.setUser(user)
assertEquals(user, scope?.user)
}
//endregion
//region setFingerprint tests
@Test
fun `when setFingerprint is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
val fingerprint = listOf("abc")
hub.setFingerprint(fingerprint)
assertEquals(0, scope?.fingerprint?.count())
}
@Test
fun `when setFingerprint is called with null parameter, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.callMethod("setFingerprint", List::class.java, null)
assertEquals(0, scope?.fingerprint?.count())
}
@Test
fun `when setFingerprint is called, fingerprint is set`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
val fingerprint = listOf("abc")
hub.setFingerprint(fingerprint)
assertEquals(1, scope?.fingerprint?.count())
}
//endregion
//region clearBreadcrumbs tests
@Test
fun `when clearBreadcrumbs is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.addBreadcrumb(Breadcrumb())
assertEquals(1, scope?.breadcrumbs?.count())
hub.close()
hub.clearBreadcrumbs()
assertEquals(1, scope?.breadcrumbs?.count())
}
@Test
fun `when clearBreadcrumbs is called, clear breadcrumbs`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.addBreadcrumb(Breadcrumb())
assertEquals(1, scope?.breadcrumbs?.count())
hub.clearBreadcrumbs()
assertEquals(0, scope?.breadcrumbs?.count())
}
//endregion
//region setTag tests
@Test
fun `when setTag is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
hub.setTag("test", "test")
assertEquals(0, scope?.tags?.count())
}
@Test
fun `when setTag is called with null parameters, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.callMethod("setTag", parameterTypes = arrayOf(String::class.java, String::class.java), null, null)
assertEquals(0, scope?.tags?.count())
}
@Test
fun `when setTag is called, tag is set`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.setTag("test", "test")
assertEquals(1, scope?.tags?.count())
}
//endregion
//region setExtra tests
@Test
fun `when setExtra is called on disabled client, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.close()
hub.setExtra("test", "test")
assertEquals(0, scope?.extras?.count())
}
@Test
fun `when setExtra is called with null parameters, do nothing`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.callMethod("setExtra", parameterTypes = arrayOf(String::class.java, String::class.java), null, null)
assertEquals(0, scope?.extras?.count())
}
@Test
fun `when setExtra is called, extra is set`() {
val hub = generateHub()
var scope: Scope? = null
hub.configureScope {
scope = it
}
hub.setExtra("test", "test")
assertEquals(1, scope?.extras?.count())
}
//endregion
//region captureEnvelope tests
@Test
fun `when captureEnvelope is called and envelope is null, throws IllegalArgumentException`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
try {
sut.callMethod("captureEnvelope", SentryEnvelope::class.java, null)
fail()
} catch (e: Exception) {
assertTrue(e.cause is java.lang.IllegalArgumentException)
}
}
@Test
fun `when captureEnvelope is called on disabled client, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.close()
sut.captureEnvelope(SentryEnvelope(SentryId(UUID.randomUUID()), null, setOf()))
verify(mockClient, never()).captureEnvelope(any(), any())
}
@Test
fun `when captureEnvelope is called with a valid envelope, captureEnvelope on the client should be called`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
val envelope = SentryEnvelope(SentryId(UUID.randomUUID()), null, setOf())
sut.captureEnvelope(envelope)
verify(mockClient).captureEnvelope(any(), anyOrNull())
}
//endregion
//region startSession tests
@Test
fun `when startSession is called on disabled client, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.close()
sut.startSession()
verify(mockClient, never()).captureSession(any(), any())
}
@Test
fun `when startSession is called, starts a session`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.startSession()
verify(mockClient).captureSession(any(), argWhere { it is SessionStartHint })
}
@Test
fun `when startSession is called and there's a session, stops it and starts a new one`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.startSession()
sut.startSession()
verify(mockClient).captureSession(any(), argWhere { it is SessionEndHint })
verify(mockClient, times(2)).captureSession(any(), argWhere { it is SessionStartHint })
}
//endregion
//region endSession tests
@Test
fun `when endSession is called on disabled client, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.close()
sut.endSession()
verify(mockClient, never()).captureSession(any(), any())
}
@Test
fun `when endSession is called and session tracking is disabled, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.endSession()
verify(mockClient, never()).captureSession(any(), any())
}
@Test
fun `when endSession is called, end a session`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.startSession()
sut.endSession()
verify(mockClient).captureSession(any(), argWhere { it is SessionStartHint })
verify(mockClient).captureSession(any(), argWhere { it is SessionEndHint })
}
@Test
fun `when endSession is called and there's no session, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.release = "0.0.1"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.endSession()
verify(mockClient, never()).captureSession(any(), any())
}
//endregion
//region captureTransaction tests
@Test
fun `when captureTransaction is called on disabled client, do nothing`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.close()
sut.captureTransaction(SentryTransaction(SentryTracer(TransactionContext("name", "op"), mock())), null)
verify(mockClient, never()).captureTransaction(any(), any(), any())
}
@Test
fun `when captureTransaction and transaction is sampled, captureTransaction on the client should be called`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.captureTransaction(SentryTransaction(SentryTracer(TransactionContext("name", "op", true), mock())), null)
verify(mockClient).captureTransaction(any(), any(), eq(null))
}
@Test
fun `when captureTransaction and transaction is not sampled, captureTransaction on the client should be called`() {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
sut.captureTransaction(SentryTransaction(SentryTracer(TransactionContext("name", "op", false), mock())), null)
verify(mockClient, times(0)).captureTransaction(any(), any(), eq(null))
}
//endregion
//region startTransaction tests
@Test
fun `when startTransaction, creates transaction`() {
val hub = generateHub()
val contexts = TransactionContext("name", "op")
val transaction = hub.startTransaction(contexts)
assertTrue(transaction is SentryTracer)
assertEquals(contexts, transaction.root.spanContext)
}
@Test
fun `when startTransaction with bindToScope set to false, transaction is not attached to the scope`() {
val hub = generateHub()
hub.startTransaction("name", "op", false)
hub.configureScope {
assertNull(it.span)
}
}
@Test
fun `when startTransaction without bindToScope set, transaction is not attached to the scope`() {
val hub = generateHub()
hub.startTransaction("name", "op")
hub.configureScope {
assertNull(it.span)
}
}
@Test
fun `when startTransaction with bindToScope set to true, transaction is attached to the scope`() {
val hub = generateHub()
val transaction = hub.startTransaction("name", "op", true)
hub.configureScope {
assertEquals(transaction, it.span)
}
}
@Test
fun `when startTransaction and no tracing sampling is configured, event is not sampled`() {
val hub = generateHub(Sentry.OptionsConfiguration {
it.tracesSampleRate = 0.0
})
val transaction = hub.startTransaction("name", "op")
assertFalse(transaction.isSampled!!)
}
@Test
fun `when startTransaction with parent sampled and no traces sampler provided, transaction inherits sampling decision`() {
val hub = generateHub()
val transactionContext = TransactionContext("name", "op")
transactionContext.parentSampled = true
val transaction = hub.startTransaction(transactionContext)
assertNotNull(transaction)
assertNotNull(transaction.isSampled)
assertTrue(transaction.isSampled!!)
}
@Test
fun `Hub should close the sentry executor processor on close call`() {
val executor = mock<ISentryExecutorService>()
val options = SentryOptions().apply {
dsn = "https://[email protected]/proj"
cacheDirPath = file.absolutePath
executorService = executor
}
val sut = Hub(options)
sut.close()
verify(executor).close(any())
}
@Test
fun `when tracesSampleRate and tracesSampler are not set on SentryOptions, startTransaction returns NoOp`() {
val hub = generateHub(Sentry.OptionsConfiguration {
it.tracesSampleRate = null
it.tracesSampler = null
})
val transaction = hub.startTransaction(TransactionContext("name", "op", true))
assertTrue(transaction is NoOpTransaction)
}
//endregion
//region startTransaction tests
@Test
fun `when traceHeaders and no transaction is active, traceHeaders are null`() {
val hub = generateHub()
assertNull(hub.traceHeaders())
}
@Test
fun `when traceHeaders and there is an active transaction, traceHeaders are not null`() {
val hub = generateHub()
val tx = hub.startTransaction("aTransaction", "op")
hub.configureScope { it.setTransaction(tx) }
assertNotNull(hub.traceHeaders())
}
//endregion
//region getSpan tests
@Test
fun `when there is no active transaction, getSpan returns null`() {
val hub = generateHub()
assertNull(hub.getSpan())
}
@Test
fun `when there is active transaction bound to the scope, getSpan returns active transaction`() {
val hub = generateHub()
val tx = hub.startTransaction("aTransaction", "op")
hub.configureScope { it.setTransaction(tx) }
assertEquals(tx, hub.getSpan())
}
@Test
fun `when there is active span within a transaction bound to the scope, getSpan returns active span`() {
val hub = generateHub()
val tx = hub.startTransaction("aTransaction", "op")
hub.configureScope { it.setTransaction(tx) }
hub.configureScope { it.setTransaction(tx) }
val span = tx.startChild("op")
assertEquals(span, hub.span)
}
// endregion
//region setSpanContext
@Test
fun `associates span context with throwable`() {
val (hub, mockClient) = getEnabledHub()
val transaction = hub.startTransaction("aTransaction", "op")
val span = transaction.startChild("op")
val exception = RuntimeException()
hub.setSpanContext(exception, span, "tx-name")
hub.captureEvent(SentryEvent(exception))
verify(mockClient).captureEvent(check {
assertEquals(span.spanContext, it.contexts.trace)
}, anyOrNull(), anyOrNull())
}
@Test
fun `returns null when no span context associated with throwable`() {
val hub = generateHub() as Hub
assertNull(hub.getSpanContext(RuntimeException()))
}
// endregion
private fun generateHub(optionsConfiguration: Sentry.OptionsConfiguration<SentryOptions>? = null): IHub {
val options = SentryOptions().apply {
dsn = "https://[email protected]/proj"
cacheDirPath = file.absolutePath
setSerializer(mock())
tracesSampleRate = 1.0
}
optionsConfiguration?.configure(options)
return Hub(options)
}
private fun getEnabledHub(): Pair<Hub, ISentryClient> {
val options = SentryOptions()
options.cacheDirPath = file.absolutePath
options.dsn = "https://[email protected]/proj"
options.setSerializer(mock())
options.tracesSampleRate = 1.0
val sut = Hub(options)
val mockClient = mock<ISentryClient>()
sut.bindClient(mockClient)
return Pair(sut, mockClient)
}
}
| bsd-3-clause | 859a7558496c517dc8e74975e1298045 | 32.445669 | 192 | 0.629744 | 4.551163 | false | true | false | false |
MaTriXy/gradle-play-publisher-1 | play/android-publisher/src/test/kotlin/com/github/triplet/gradle/androidpublisher/internal/DefaultTrackManagerTest.kt | 1 | 38151 | package com.github.triplet.gradle.androidpublisher.internal
import com.github.triplet.gradle.androidpublisher.ReleaseStatus
import com.google.api.services.androidpublisher.model.LocalizedText
import com.google.api.services.androidpublisher.model.Track
import com.google.api.services.androidpublisher.model.TrackRelease
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.`when`
import org.mockito.Mockito.any
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
class DefaultTrackManagerTest {
private val mockPublisher = mock(InternalPlayPublisher::class.java)
private val tracks: TrackManager = DefaultTrackManager(mockPublisher, "edit-id")
@Test
fun `Standard build with completed release creates new track`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(888L, 777L)
assertThat(trackCaptor.value.releases.single().userFraction).isNull()
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Standard build uses default release status when unspecified`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = null,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().setTrack("alpha"))
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
}
@Test
fun `Standard build configures user fraction when unspecified for inProgress release`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.IN_PROGRESS,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().setTrack("alpha"))
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().status).isEqualTo("inProgress")
assertThat(trackCaptor.value.releases.single().userFraction).isEqualTo(0.1)
}
@Test
fun `Standard build with rollout release creates new release`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.IN_PROGRESS,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "alpha"
releases = listOf(TrackRelease().apply {
status = "completed"
versionCodes = listOf(666)
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(2)
assertThat(trackCaptor.value.releases.first().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.first().versionCodes).containsExactly(666L)
assertThat(trackCaptor.value.releases.last().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.last().status).isEqualTo("inProgress")
assertThat(trackCaptor.value.releases.last().versionCodes).containsExactly(888L, 777L)
assertThat(trackCaptor.value.releases.last().userFraction).isEqualTo(.88)
assertThat(trackCaptor.value.releases.last().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.last().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.last().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.last().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Standard build with rollout release overwrites existing rollout release`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.IN_PROGRESS,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "alpha"
releases = listOf(
TrackRelease().apply {
status = "inProgress"
versionCodes = listOf(666)
},
TrackRelease().apply {
status = "completed"
versionCodes = listOf(555)
}
)
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(2)
assertThat(trackCaptor.value.releases.first().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.first().versionCodes).containsExactly(555L)
assertThat(trackCaptor.value.releases.last().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.last().status).isEqualTo("inProgress")
assertThat(trackCaptor.value.releases.last().versionCodes).containsExactly(888L, 777L)
assertThat(trackCaptor.value.releases.last().userFraction).isEqualTo(.88)
assertThat(trackCaptor.value.releases.last().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.last().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.last().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.last().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Skipped commit build with completed release creates new track when none already exists`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = true,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply { track = "alpha" })
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(777L, 888L)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().userFraction).isNull()
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Skipped commit build with completed release updates existing track when found`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = true,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "alpha"
releases = listOf(TrackRelease().apply {
status = "completed"
versionCodes = listOf(666)
releaseNotes = listOf(LocalizedText().apply {
language = "lang2"
text = "notes2"
})
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(666L, 777L, 888L)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().userFraction).isNull()
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(2)
assertThat(trackCaptor.value.releases.single().releaseNotes.first().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.first().text)
.isEqualTo("notes1")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().language)
.isEqualTo("lang2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().text)
.isEqualTo("notes2")
}
@Test
fun `Skipped commit build with existing completed release merges release notes`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = true,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1-2"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
releases = listOf(TrackRelease().apply {
status = "completed"
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1"
text = "notes1-1"
},
LocalizedText().apply {
language = "lang2"
text = "notes2"
}
)
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(2)
assertThat(trackCaptor.value.releases.single().releaseNotes.first().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.first().text)
.isEqualTo("notes1-2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().language)
.isEqualTo("lang2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().text)
.isEqualTo("notes2")
}
@Test
fun `Skipped commit build with existing params keeps them if no new ones are specified`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = true,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.DRAFT,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
releases = listOf(TrackRelease().apply {
status = "draft"
name = "foobar"
userFraction = 789.0
inAppUpdatePriority = 599
versionCodes = listOf(3, 4, 5)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1"
text = "notes1"
}
)
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("foobar")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("draft")
assertThat(trackCaptor.value.releases.single().userFraction).isEqualTo(789.0)
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(599)
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(3L, 4L, 5L, 888L)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Skipped commit build with different release statuses creates new release`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = true,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.DRAFT,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "alpha"
releases = listOf(TrackRelease().apply {
status = "completed"
versionCodes = listOf(666)
releaseNotes = listOf(LocalizedText().apply {
language = "lang2"
text = "notes2"
})
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(2)
assertThat(trackCaptor.value.releases.first().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.first().versionCodes).containsExactly(666L)
assertThat(trackCaptor.value.releases.first().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.first().releaseNotes.single().language)
.isEqualTo("lang2")
assertThat(trackCaptor.value.releases.first().releaseNotes.single().text)
.isEqualTo("notes2")
assertThat(trackCaptor.value.releases.last().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.last().status).isEqualTo("draft")
assertThat(trackCaptor.value.releases.last().userFraction).isNull()
assertThat(trackCaptor.value.releases.last().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.last().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.last().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.last().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Track update uses existing release notes when no local ones are available`() {
val config = TrackManager.UpdateConfig(
trackName = "alpha",
versionCodes = listOf(888),
didPreviousBuildSkipCommit = false,
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
releases = listOf(TrackRelease().apply {
status = "completed"
versionCodes = listOf(1, 2)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1-1"
text = "notes1-1"
}
)
}, TrackRelease().apply {
status = "inProgress"
versionCodes = listOf(3)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1-2"
text = "notes1-2"
},
LocalizedText().apply {
language = "lang2"
text = "notes2"
}
)
})
})
tracks.update(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(2)
assertThat(trackCaptor.value.releases.single().releaseNotes.first().language)
.isEqualTo("lang1-2")
assertThat(trackCaptor.value.releases.single().releaseNotes.first().text)
.isEqualTo("notes1-2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().language)
.isEqualTo("lang2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().text)
.isEqualTo("notes2")
}
@Test
fun `findHighestTrack returns null on empty tracks`() {
`when`(mockPublisher.listTracks(any())).thenReturn(emptyList())
val max = tracks.findHighestTrack()
assertThat(max).isNull()
}
@Test
fun `findHighestTrack returns first track on null releases`() {
`when`(mockPublisher.listTracks(any())).thenReturn(listOf(Track(), Track()))
val max = tracks.findHighestTrack()
assertThat(max).isEqualTo(Track())
}
@Test
fun `findHighestTrack succeeds with multi track, multi release, multi version code`() {
`when`(mockPublisher.listTracks(any())).thenReturn(listOf(
Track().apply {
track = "a"
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(5, 4, 8, 7)
},
TrackRelease().apply {
versionCodes = listOf(85, 7, 36, 5)
}
)
},
Track().apply {
track = "b"
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(49, 5875, 385, 9, 73, 294, 867)
},
TrackRelease().apply {
versionCodes = listOf(5, 4, 8, 7)
},
TrackRelease().apply {
versionCodes = listOf(85, 7, 36, 5)
}
)
}
))
val max = tracks.findHighestTrack()
assertThat(max).isNotNull()
assertThat(max!!.track).isEqualTo("b")
}
@Test
fun `getReleaseNotes returns empty notes on empty tracks`() {
`when`(mockPublisher.listTracks(any())).thenReturn(emptyList())
val notes = tracks.getReleaseNotes()
assertThat(notes).isEmpty()
}
@Test
fun `getReleaseNotes returns empty notes on null release notes`() {
`when`(mockPublisher.listTracks(any())).thenReturn(listOf(
Track().setTrack("alpha"), Track().setTrack("production")))
val notes = tracks.getReleaseNotes()
assertThat(notes).containsExactly(
"alpha", emptyList<LocalizedText>(),
"production", emptyList<LocalizedText>()
)
}
@Test
fun `getReleaseNotes returns note on single track`() {
`when`(mockPublisher.listTracks(any())).thenReturn(listOf(Track().apply {
track = "alpha"
releases = listOf(
TrackRelease().apply {
releaseNotes = listOf(
LocalizedText().setLanguage("en-US").setText("foobar"))
}
)
}))
val notes = tracks.getReleaseNotes()
assertThat(notes).containsExactly(
"alpha", listOf(LocalizedText().setLanguage("en-US").setText("foobar"))
)
}
@Test
fun `getReleaseNotes returns notes on multiple tracks`() {
`when`(mockPublisher.listTracks(any())).thenReturn(listOf(Track().apply {
track = "alpha"
releases = listOf(
TrackRelease().apply {
releaseNotes = listOf(
LocalizedText().setLanguage("en-US").setText("foobar"))
}
)
}, Track().apply {
track = "production"
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(123)
releaseNotes = listOf(
LocalizedText().setLanguage("en-US").setText("foobar old"),
LocalizedText().setLanguage("fr-FR").setText("foobar french")
)
},
TrackRelease().apply {
versionCodes = listOf(321)
releaseNotes = listOf(
LocalizedText().setLanguage("en-US").setText("foobar new"))
}
)
}))
val notes = tracks.getReleaseNotes()
assertThat(notes).containsExactly(
"alpha", listOf(LocalizedText().setLanguage("en-US").setText("foobar")),
"production", listOf(LocalizedText().setLanguage("en-US").setText("foobar new"))
)
}
@Test
fun `Promoting tracks with no active releases fails`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
releases = listOf(TrackRelease())
})
assertThrows<IllegalStateException> {
tracks.promote(config)
}
verify(mockPublisher, never()).updateTrack(any(), any())
}
@Test
fun `Promoting track applies updates from params`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.IN_PROGRESS,
userFraction = .88,
updatePriority = 3,
releaseNotes = mapOf("lang1" to "notes1"),
retainableArtifacts = listOf(777),
releaseName = "relname"
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "internal"
releases = listOf(
TrackRelease().apply {
versionCodes = listOf(3)
}
)
})
tracks.promote(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(3L, 777L)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("relname")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("inProgress")
assertThat(trackCaptor.value.releases.single().userFraction).isEqualTo(.88)
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(3)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Promoting track with conflicting releases keeps newest one`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "internal"
releases = listOf(
TrackRelease().apply {
status = "completed"
versionCodes = listOf(4)
},
TrackRelease().apply {
status = "inProgress"
versionCodes = listOf(5)
},
TrackRelease().apply {
status = "draft"
versionCodes = listOf(3)
}
)
})
tracks.promote(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(5L)
}
@Test
fun `Promoting track keeps existing values if params aren't specified`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = null,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "internal"
releases = listOf(TrackRelease().apply {
status = "completed"
name = "foobar"
userFraction = 789.0
inAppUpdatePriority = 599
versionCodes = listOf(3, 4, 5)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1"
text = "notes1"
}
)
})
})
tracks.promote(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().name).isEqualTo("foobar")
assertThat(trackCaptor.value.releases.single().status).isEqualTo("completed")
assertThat(trackCaptor.value.releases.single().userFraction).isEqualTo(789.0)
assertThat(trackCaptor.value.releases.single().inAppUpdatePriority).isEqualTo(599)
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(3L, 4L, 5L)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes.single().language)
.isEqualTo("lang1")
assertThat(trackCaptor.value.releases.single().releaseNotes.single().text)
.isEqualTo("notes1")
}
@Test
fun `Promoting from different track updates track name`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "internal"
releases = listOf(TrackRelease().apply { versionCodes = listOf(2) })
})
tracks.promote(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.track).isEqualTo("alpha")
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().versionCodes).containsExactly(2L)
}
@Test
fun `Promoting track uses existing release notes when no local ones are available`() {
val config = TrackManager.PromoteConfig(
promoteTrackName = "alpha",
fromTrackName = "internal",
base = TrackManager.BaseConfig(
releaseStatus = ReleaseStatus.COMPLETED,
userFraction = null,
updatePriority = null,
releaseNotes = null,
retainableArtifacts = null,
releaseName = null
)
)
`when`(mockPublisher.getTrack(any(), any())).thenReturn(Track().apply {
track = "internal"
releases = listOf(TrackRelease().apply {
status = "completed"
versionCodes = listOf(1, 2)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1-1"
text = "notes1-1"
}
)
}, TrackRelease().apply {
status = "inProgress"
versionCodes = listOf(3)
releaseNotes = listOf(
LocalizedText().apply {
language = "lang1-2"
text = "notes1-2"
},
LocalizedText().apply {
language = "lang2"
text = "notes2"
}
)
})
})
tracks.promote(config)
val trackCaptor = ArgumentCaptor.forClass(Track::class.java)
verify(mockPublisher).updateTrack(eq("edit-id"), trackCaptor.capture())
assertThat(trackCaptor.value.releases).hasSize(1)
assertThat(trackCaptor.value.releases.single().releaseNotes).hasSize(2)
assertThat(trackCaptor.value.releases.single().releaseNotes.first().language)
.isEqualTo("lang1-2")
assertThat(trackCaptor.value.releases.single().releaseNotes.first().text)
.isEqualTo("notes1-2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().language)
.isEqualTo("lang2")
assertThat(trackCaptor.value.releases.single().releaseNotes.last().text)
.isEqualTo("notes2")
}
}
| mit | 6487cf59832a2312f7613c583b9b0a7a | 43.054273 | 102 | 0.55705 | 5.250619 | false | true | false | false |
google/dagger | java/dagger/hilt/android/plugin/main/src/main/kotlin/dagger/hilt/android/plugin/HiltGradlePlugin.kt | 2 | 23227 | /*
* Copyright (C) 2020 The Dagger 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 dagger.hilt.android.plugin
import com.android.build.api.instrumentation.FramesComputationMode
import com.android.build.api.instrumentation.InstrumentationScope
import com.android.build.gradle.AppExtension
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.LibraryExtension
import com.android.build.gradle.TestExtension
import com.android.build.gradle.TestedExtension
import com.android.build.gradle.api.AndroidBasePlugin
import dagger.hilt.android.plugin.task.AggregateDepsTask
import dagger.hilt.android.plugin.task.HiltTransformTestClassesTask
import dagger.hilt.android.plugin.util.AggregatedPackagesTransform
import dagger.hilt.android.plugin.util.ComponentCompat
import dagger.hilt.android.plugin.util.CopyTransform
import dagger.hilt.android.plugin.util.SimpleAGPVersion
import dagger.hilt.android.plugin.util.capitalize
import dagger.hilt.android.plugin.util.getAndroidComponentsExtension
import dagger.hilt.android.plugin.util.getKaptConfigName
import dagger.hilt.android.plugin.util.getSdkPath
import dagger.hilt.processor.internal.optionvalues.GradleProjectType
import java.io.File
import javax.inject.Inject
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.attributes.Attribute
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.process.CommandLineArgumentProvider
import org.gradle.util.GradleVersion
import org.objectweb.asm.Opcodes
/**
* A Gradle plugin that checks if the project is an Android project and if so, registers a
* bytecode transformation.
*
* The plugin also passes an annotation processor option to disable superclass validation for
* classes annotated with `@AndroidEntryPoint` since the registered transform by this plugin will
* update the superclass.
*/
class HiltGradlePlugin @Inject constructor(
val providers: ProviderFactory
) : Plugin<Project> {
override fun apply(project: Project) {
var configured = false
project.plugins.withType(AndroidBasePlugin::class.java) {
configured = true
configureHilt(project)
}
project.afterEvaluate {
check(configured) {
// Check if configuration was applied, if not inform the developer they have applied the
// plugin to a non-android project.
"The Hilt Android Gradle plugin can only be applied to an Android project."
}
verifyDependencies(it)
}
}
private fun configureHilt(project: Project) {
val hiltExtension = project.extensions.create(
HiltExtension::class.java, "hilt", HiltExtensionImpl::class.java
)
configureDependencyTransforms(project)
configureCompileClasspath(project, hiltExtension)
if (SimpleAGPVersion.ANDROID_GRADLE_PLUGIN_VERSION < SimpleAGPVersion(4, 2)) {
// Configures bytecode transform using older APIs pre AGP 4.2
configureBytecodeTransform(project, hiltExtension)
} else {
// Configures bytecode transform using AGP 4.2 ASM pipeline.
configureBytecodeTransformASM(project, hiltExtension)
}
configureAggregatingTask(project, hiltExtension)
configureProcessorFlags(project, hiltExtension)
}
// Configures Gradle dependency transforms.
private fun configureDependencyTransforms(project: Project) = project.dependencies.apply {
registerTransform(CopyTransform::class.java) { spec ->
// Java/Kotlin library projects offer an artifact of type 'jar'.
spec.from.attribute(ARTIFACT_TYPE_ATTRIBUTE, "jar")
// Android library projects (with or without Kotlin) offer an artifact of type
// 'android-classes', which AGP can offer as a jar.
spec.from.attribute(ARTIFACT_TYPE_ATTRIBUTE, "android-classes")
spec.to.attribute(ARTIFACT_TYPE_ATTRIBUTE, DAGGER_ARTIFACT_TYPE_VALUE)
}
registerTransform(CopyTransform::class.java) { spec ->
// File Collection dependencies might be an artifact of type 'directory', e.g. when
// adding as a dep the destination directory of the JavaCompile task.
spec.from.attribute(ARTIFACT_TYPE_ATTRIBUTE, "directory")
spec.to.attribute(ARTIFACT_TYPE_ATTRIBUTE, DAGGER_ARTIFACT_TYPE_VALUE)
}
registerTransform(AggregatedPackagesTransform::class.java) { spec ->
spec.from.attribute(ARTIFACT_TYPE_ATTRIBUTE, DAGGER_ARTIFACT_TYPE_VALUE)
spec.to.attribute(ARTIFACT_TYPE_ATTRIBUTE, AGGREGATED_HILT_ARTIFACT_TYPE_VALUE)
}
}
private fun configureCompileClasspath(project: Project, hiltExtension: HiltExtension) {
val androidExtension = project.baseExtension() ?: error("Android BaseExtension not found.")
androidExtension.forEachRootVariant { variant ->
configureVariantCompileClasspath(project, hiltExtension, androidExtension, variant)
}
}
// Invokes the [block] function for each Android variant that is considered a Hilt root, where
// dependencies are aggregated and components are generated.
private fun BaseExtension.forEachRootVariant(
@Suppress("DEPRECATION") block: (variant: com.android.build.gradle.api.BaseVariant) -> Unit
) {
when (this) {
is AppExtension -> {
// For an app project we configure the app variant and both androidTest and unitTest
// variants, Hilt components are generated in all of them.
applicationVariants.all { block(it) }
testVariants.all { block(it) }
unitTestVariants.all { block(it) }
}
is LibraryExtension -> {
// For a library project, only the androidTest and unitTest variant are configured since
// Hilt components are not generated in a library.
testVariants.all { block(it) }
unitTestVariants.all { block(it) }
}
is TestExtension -> {
applicationVariants.all { block(it) }
}
else -> error("Hilt plugin does not know how to configure '$this'")
}
}
private fun configureVariantCompileClasspath(
project: Project,
hiltExtension: HiltExtension,
androidExtension: BaseExtension,
@Suppress("DEPRECATION") variant: com.android.build.gradle.api.BaseVariant
) {
if (
!hiltExtension.enableExperimentalClasspathAggregation || hiltExtension.enableAggregatingTask
) {
// Option is not enabled, don't configure compile classpath. Note that the option can't be
// checked earlier (before iterating over the variants) since it would have been too early for
// the value to be populated from the build file.
return
}
if (
androidExtension.lintOptions.isCheckReleaseBuilds &&
SimpleAGPVersion.ANDROID_GRADLE_PLUGIN_VERSION < SimpleAGPVersion(7, 0)
) {
// Sadly we have to ask users to disable lint when enableExperimentalClasspathAggregation is
// set to true and they are not in AGP 7.0+ since Lint will cause issues during the
// configuration phase. See b/158753935 and b/160392650
error(
"Invalid Hilt plugin configuration: When 'enableExperimentalClasspathAggregation' is " +
"enabled 'android.lintOptions.checkReleaseBuilds' has to be set to false unless " +
"com.android.tools.build:gradle:7.0.0+ is used."
)
}
if (
listOf(
"android.injected.build.model.only", // Sent by AS 1.0 only
"android.injected.build.model.only.advanced", // Sent by AS 1.1+
"android.injected.build.model.only.versioned", // Sent by AS 2.4+
"android.injected.build.model.feature.full.dependencies", // Sent by AS 2.4+
"android.injected.build.model.v2", // Sent by AS 4.2+
).any {
// forUseAtConfigurationTime() is deprecated in 7.4 and later:
// https://docs.gradle.org/current/userguide/upgrading_version_7.html#changes_7.4
if (GradleVersion.version(project.gradle.gradleVersion) < GradleVersion.version("7.4.0")) {
@Suppress("DEPRECATION")
providers.gradleProperty(it).forUseAtConfigurationTime().isPresent
} else {
providers.gradleProperty(it).isPresent
}
}
) {
// Do not configure compile classpath when AndroidStudio is building the model (syncing)
// otherwise it will cause a freeze.
return
}
@Suppress("DEPRECATION") // Older variant API is deprecated
val runtimeConfiguration = if (variant is com.android.build.gradle.api.TestVariant) {
// For Android test variants, the tested runtime classpath is used since the test app has
// tested dependencies removed.
variant.testedVariant.runtimeConfiguration
} else {
variant.runtimeConfiguration
}
val artifactView = runtimeConfiguration.incoming.artifactView { view ->
view.attributes.attribute(ARTIFACT_TYPE_ATTRIBUTE, DAGGER_ARTIFACT_TYPE_VALUE)
view.componentFilter { identifier ->
// Filter out the project's classes from the aggregated view since this can cause
// issues with Kotlin internal members visibility. b/178230629
if (identifier is ProjectComponentIdentifier) {
identifier.projectName != project.name
} else {
true
}
}
}
// CompileOnly config names don't follow the usual convention:
// <Variant Name> -> <Config Name>
// debug -> debugCompileOnly
// debugAndroidTest -> androidTestDebugCompileOnly
// debugUnitTest -> testDebugCompileOnly
// release -> releaseCompileOnly
// releaseUnitTest -> testReleaseCompileOnly
@Suppress("DEPRECATION") // Older variant API is deprecated
val compileOnlyConfigName = when (variant) {
is com.android.build.gradle.api.TestVariant ->
"androidTest${variant.name.substringBeforeLast("AndroidTest").capitalize()}CompileOnly"
is com.android.build.gradle.api.UnitTestVariant ->
"test${variant.name.substringBeforeLast("UnitTest").capitalize()}CompileOnly"
else ->
"${variant.name}CompileOnly"
}
project.dependencies.add(compileOnlyConfigName, artifactView.files)
}
@Suppress("UnstableApiUsage") // ASM Pipeline APIs
private fun configureBytecodeTransformASM(project: Project, hiltExtension: HiltExtension) {
var warnAboutLocalTestsFlag = false
fun registerTransform(androidComponent: ComponentCompat) {
if (hiltExtension.enableTransformForLocalTests && !warnAboutLocalTestsFlag) {
project.logger.warn(
"The Hilt configuration option 'enableTransformForLocalTests' is no longer necessary " +
"when com.android.tools.build:gradle:4.2.0+ is used."
)
warnAboutLocalTestsFlag = true
}
androidComponent.transformClassesWith(
classVisitorFactoryImplClass = AndroidEntryPointClassVisitor.Factory::class.java,
scope = InstrumentationScope.PROJECT
) { params ->
val classesDir =
File(project.buildDir, "intermediates/javac/${androidComponent.name}/classes")
params.additionalClassesDir.set(classesDir)
}
androidComponent.setAsmFramesComputationMode(
FramesComputationMode.COMPUTE_FRAMES_FOR_INSTRUMENTED_METHODS
)
}
getAndroidComponentsExtension(project).onAllVariants { registerTransform(it) }
}
private fun configureBytecodeTransform(project: Project, hiltExtension: HiltExtension) {
val androidExtension = project.baseExtension() ?: error("Android BaseExtension not found.")
androidExtension::class.java.getMethod(
"registerTransform",
Class.forName("com.android.build.api.transform.Transform"),
Array<Any>::class.java
).invoke(androidExtension, AndroidEntryPointTransform(), emptyArray<Any>())
// Create and configure a task for applying the transform for host-side unit tests. b/37076369
project.testedExtension()?.unitTestVariants?.all { unitTestVariant ->
HiltTransformTestClassesTask.create(
project = project,
unitTestVariant = unitTestVariant,
extension = hiltExtension
)
}
}
private fun configureAggregatingTask(project: Project, hiltExtension: HiltExtension) {
val androidExtension = project.baseExtension() ?: error("Android BaseExtension not found.")
androidExtension.forEachRootVariant { variant ->
configureVariantAggregatingTask(project, hiltExtension, androidExtension, variant)
}
}
private fun configureVariantAggregatingTask(
project: Project,
hiltExtension: HiltExtension,
androidExtension: BaseExtension,
@Suppress("DEPRECATION") variant: com.android.build.gradle.api.BaseVariant
) {
if (!hiltExtension.enableAggregatingTask) {
// Option is not enabled, don't configure aggregating task.
return
}
val hiltCompileConfiguration = project.configurations.create(
"hiltCompileOnly${variant.name.capitalize()}"
).apply {
isCanBeConsumed = false
isCanBeResolved = true
}
// Add the JavaCompile task classpath and output dir to the config, the task's classpath
// will contain:
// * compileOnly dependencies
// * KAPT and Kotlinc generated bytecode
// * R.jar
// * Tested classes if the variant is androidTest
project.dependencies.add(
hiltCompileConfiguration.name,
project.files(variant.javaCompileProvider.map { it.classpath })
)
project.dependencies.add(
hiltCompileConfiguration.name,
project.files(variant.javaCompileProvider.map {it.destinationDirectory.get() })
)
fun getInputClasspath(artifactAttributeValue: String) =
mutableListOf<Configuration>().apply {
@Suppress("DEPRECATION") // Older variant API is deprecated
if (variant is com.android.build.gradle.api.TestVariant) {
add(variant.testedVariant.runtimeConfiguration)
}
add(variant.runtimeConfiguration)
add(hiltCompileConfiguration)
}.map { configuration ->
configuration.incoming.artifactView { view ->
view.attributes.attribute(ARTIFACT_TYPE_ATTRIBUTE, artifactAttributeValue)
}.files
}.let {
project.files(*it.toTypedArray())
}
val aggregatingTask = project.tasks.register(
"hiltAggregateDeps${variant.name.capitalize()}",
AggregateDepsTask::class.java
) {
it.compileClasspath.setFrom(getInputClasspath(AGGREGATED_HILT_ARTIFACT_TYPE_VALUE))
it.outputDir.set(
project.file(project.buildDir.resolve("generated/hilt/component_trees/${variant.name}/"))
)
@Suppress("DEPRECATION") // Older variant API is deprecated
it.testEnvironment.set(
variant is com.android.build.gradle.api.TestVariant ||
variant is com.android.build.gradle.api.UnitTestVariant ||
androidExtension is com.android.build.gradle.TestExtension
)
it.crossCompilationRootValidationDisabled.set(
hiltExtension.disableCrossCompilationRootValidation
)
if (SimpleAGPVersion.ANDROID_GRADLE_PLUGIN_VERSION >= SimpleAGPVersion(7, 1)) {
it.asmApiVersion.set(Opcodes.ASM9)
}
}
val componentClasses = project.files(
project.buildDir.resolve("intermediates/hilt/component_classes/${variant.name}/")
)
val componentsJavaCompileTask = project.tasks.register(
"hiltJavaCompile${variant.name.capitalize()}",
JavaCompile::class.java
) { compileTask ->
compileTask.source = aggregatingTask.map { it.outputDir.asFileTree }.get()
// Configure the input classpath based on Java 9 compatibility, specifically for Java 9 the
// android.jar is now included in the input classpath instead of the bootstrapClasspath.
// See: com/android/build/gradle/tasks/JavaCompileUtils.kt
val mainBootstrapClasspath =
variant.javaCompileProvider.map { it.options.bootstrapClasspath ?: project.files() }.get()
if (
JavaVersion.current().isJava9Compatible &&
androidExtension.compileOptions.targetCompatibility.isJava9Compatible
) {
compileTask.classpath =
getInputClasspath(DAGGER_ARTIFACT_TYPE_VALUE).plus(mainBootstrapClasspath)
// Copies argument providers from original task, which should contain the JdkImageInput
variant.javaCompileProvider.get().let { originalCompileTask ->
originalCompileTask.options.compilerArgumentProviders.forEach {
compileTask.options.compilerArgumentProviders.add(it)
}
}
compileTask.options.compilerArgs.add("-XDstringConcat=inline")
} else {
compileTask.classpath = getInputClasspath(DAGGER_ARTIFACT_TYPE_VALUE)
compileTask.options.bootstrapClasspath = mainBootstrapClasspath
}
compileTask.destinationDirectory.set(componentClasses.singleFile)
compileTask.options.apply {
annotationProcessorPath = project.configurations.create(
"hiltAnnotationProcessor${variant.name.capitalize()}"
).also { config ->
config.isCanBeConsumed = false
config.isCanBeResolved = true
// Add user annotation processor configuration, so that SPI plugins and other processors
// are discoverable.
val apConfigurations: List<Configuration> = mutableListOf<Configuration>().apply {
add(variant.annotationProcessorConfiguration)
project.configurations.findByName(getKaptConfigName(variant))?.let { add(it) }
}
config.extendsFrom(*apConfigurations.toTypedArray())
// Add hilt-compiler even though it might be in the AP configurations already.
project.dependencies.add(config.name, "com.google.dagger:hilt-compiler:$HILT_VERSION")
}
generatedSourceOutputDirectory.set(
project.file(
project.buildDir.resolve("generated/hilt/component_sources/${variant.name}/")
)
)
if (
JavaVersion.current().isJava8Compatible &&
androidExtension.compileOptions.targetCompatibility.isJava8Compatible
) {
compilerArgs.add("-parameters")
}
compilerArgs.add("-Adagger.fastInit=enabled")
compilerArgs.add("-Adagger.hilt.internal.useAggregatingRootProcessor=false")
compilerArgs.add("-Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true")
encoding = androidExtension.compileOptions.encoding
}
compileTask.sourceCompatibility =
androidExtension.compileOptions.sourceCompatibility.toString()
compileTask.targetCompatibility =
androidExtension.compileOptions.targetCompatibility.toString()
}
componentClasses.builtBy(componentsJavaCompileTask)
variant.registerPostJavacGeneratedBytecode(componentClasses)
}
private fun getAndroidJar(project: Project, compileSdkVersion: String) =
project.files(File(project.getSdkPath(), "platforms/$compileSdkVersion/android.jar"))
private fun configureProcessorFlags(project: Project, hiltExtension: HiltExtension) {
val androidExtension = project.baseExtension() ?: error("Android BaseExtension not found.")
androidExtension.defaultConfig.javaCompileOptions.annotationProcessorOptions.apply {
// Pass annotation processor flag to enable Dagger's fast-init, the best mode for Hilt.
argument("dagger.fastInit", "enabled")
// Pass annotation processor flag to disable @AndroidEntryPoint superclass validation.
argument("dagger.hilt.android.internal.disableAndroidSuperclassValidation", "true")
val projectType = when (androidExtension) {
is AppExtension -> GradleProjectType.APP
is LibraryExtension -> GradleProjectType.LIBRARY
is TestExtension -> GradleProjectType.TEST
else -> error("Hilt plugin does not know how to configure '$this'")
}
argument("dagger.hilt.android.internal.projectType", projectType.toString())
// Pass certain annotation processor flags via a CommandLineArgumentProvider so that plugin
// options defined in the extension are populated from the user's build file. Checking the
// option too early would make it seem like it is never set.
compilerArgumentProvider(
// Suppress due to https://docs.gradle.org/7.2/userguide/validation_problems.html#implementation_unknown
@Suppress("ObjectLiteralToLambda")
object : CommandLineArgumentProvider {
override fun asArguments() = mutableListOf<String>().apply {
// Pass annotation processor flag to disable the aggregating processor if aggregating
// task is enabled.
if (hiltExtension.enableAggregatingTask) {
add("-Adagger.hilt.internal.useAggregatingRootProcessor=false")
}
// Pass annotation processor flag to disable cross compilation root validation.
// The plugin option duplicates the processor flag because it is an input of the
// aggregating task.
if (hiltExtension.disableCrossCompilationRootValidation) {
add("-Adagger.hilt.disableCrossCompilationRootValidation=true")
}
}
}
)
}
}
private fun verifyDependencies(project: Project) {
// If project is already failing, skip verification since dependencies might not be resolved.
if (project.state.failure != null) {
return
}
val dependencies = project.configurations.flatMap { configuration ->
configuration.dependencies.map { dependency -> dependency.group to dependency.name }
}
if (!dependencies.contains(LIBRARY_GROUP to "hilt-android")) {
error(missingDepError("$LIBRARY_GROUP:hilt-android"))
}
if (
!dependencies.contains(LIBRARY_GROUP to "hilt-android-compiler") &&
!dependencies.contains(LIBRARY_GROUP to "hilt-compiler")
) {
error(missingDepError("$LIBRARY_GROUP:hilt-compiler"))
}
}
private fun Project.baseExtension(): BaseExtension?
= extensions.findByType(BaseExtension::class.java)
private fun Project.testedExtension(): TestedExtension?
= extensions.findByType(TestedExtension::class.java)
companion object {
val ARTIFACT_TYPE_ATTRIBUTE = Attribute.of("artifactType", String::class.java)
const val DAGGER_ARTIFACT_TYPE_VALUE = "jar-for-dagger"
const val AGGREGATED_HILT_ARTIFACT_TYPE_VALUE = "aggregated-jar-for-hilt"
const val LIBRARY_GROUP = "com.google.dagger"
val missingDepError: (String) -> String = { depCoordinate ->
"The Hilt Android Gradle plugin is applied but no $depCoordinate dependency was found."
}
}
}
| apache-2.0 | 053ab3b9ae4c27262ac454a164cfc7f3 | 43.926499 | 112 | 0.715417 | 4.641687 | false | true | false | false |
itasyurt/kex | src/test/kotlin/org/itasyurt/kotlin/kex/serializer/TestSerializers.kt | 1 | 1617 | package org.itasyurt.kotlin.kex.serializer
import org.itasyurt.kotlin.kex.field.*
/**
* Created by itasyurt on 19/06/2017.
*/
open class CommentSerializer() : BaseSerializer<Comment>() {
override fun initFields(fields: MutableMap<String, Field>) {
fields["text"] = SourceField(Comment::text)
}
}
class CommentWithOwnerUserSerializer() : CommentSerializer() {
override fun initFields(fields: MutableMap<String, Field>) {
super.initFields(fields)
fields["owner"] = NestedRelatedField(OwnerSerializer::class, Comment::owner)
}
}
class CommentWithLengthSerializer() : CommentSerializer() {
override fun initFields(fields: MutableMap<String, Field>) {
super.initFields(fields)
fields["contentLength"] = MethodField(this::getContentLength)
}
fun getContentLength(c: Comment) = c.text?.length
}
class CommentTextUpperSerializer() : BaseSerializer<Comment>() {
override fun initFields(fields: MutableMap<String, Field>) {
fields["textUpper"] = MethodField(this::textToUpper)
}
private fun textToUpper(c: Comment): Any? {
return c.text?.toUpperCase()
}
}
class OwnerSerializer() : BaseSerializer<User>() {
override fun initFields(fields: MutableMap<String, Field>) {
fields["username"] = SourceField(User::username)
}
}
class PostSerializer() : BaseSerializer<Post>() {
override fun initFields(fields: MutableMap<String, Field>) {
fields["content"] = SourceField(Post::content)
fields["comments"] = NestedCollectionField(CommentSerializer::class, Post::comments)
}
}
| apache-2.0 | 25d0bff6b184c1b715ec0ab577dc7439 | 26.40678 | 92 | 0.690785 | 3.953545 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/tracer/TraceableElementCopyFilter.kt | 1 | 1017 | package org.evomaster.core.search.tracer
/**
* created by manzh on 2019-09-06
*
* this is used to decide applicable copy filter for [Traceable]
*/
abstract class TraceableElementCopyFilter (val name : String) {
companion object{
/**
* without tracking
*/
val NONE = object : TraceableElementCopyFilter("NONE"){
}
/**
* with tracking
*/
val WITH_TRACK = object : TraceableElementCopyFilter("WITH_TRACK"){
}
/**
* with tracking
*/
val WITH_ONLY_EVALUATED_RESULT = object : TraceableElementCopyFilter("WITH_ONLY_EVALUATED_RESULT"){
}
/**
* with deep tracking, i.e., tracking nested TraceableElement
*/
val DEEP_TRACK = object : TraceableElementCopyFilter("DEEP_TRACK"){
}
}
/**
* check if accept the [element] is applicable with the copy filter
*/
open fun accept(element : Any): Boolean = element is Traceable
} | lgpl-3.0 | 5fd9bce37d0ac644de05c6bd2b366ee5 | 23.238095 | 108 | 0.583088 | 4.52 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | core/commonMain/src/implementations/persistentOrderedMap/PersistentOrderedMapContentViews.kt | 1 | 1806 | /*
* Copyright 2016-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.txt file.
*/
package kotlinx.collections.immutable.implementations.persistentOrderedMap
import kotlinx.collections.immutable.ImmutableCollection
import kotlinx.collections.immutable.ImmutableSet
internal class PersistentOrderedMapEntries<K, V>(private val map: PersistentOrderedMap<K, V>) : ImmutableSet<Map.Entry<K, V>>, AbstractSet<Map.Entry<K, V>>() {
override val size: Int get() = map.size
override fun contains(element: Map.Entry<K, V>): Boolean {
// TODO: Eliminate this check after KT-30016 gets fixed.
if ((element as Any?) !is Map.Entry<*, *>) return false
return map[element.key]?.let { candidate -> candidate == element.value }
?: (element.value == null && map.containsKey(element.key))
}
override fun iterator(): Iterator<Map.Entry<K, V>> {
return PersistentOrderedMapEntriesIterator(map)
}
}
internal class PersistentOrderedMapKeys<K, V>(private val map: PersistentOrderedMap<K, V>) : ImmutableSet<K>, AbstractSet<K>() {
override val size: Int
get() = map.size
override fun contains(element: K): Boolean {
return map.containsKey(element)
}
override fun iterator(): Iterator<K> {
return PersistentOrderedMapKeysIterator(map)
}
}
internal class PersistentOrderedMapValues<K, V>(private val map: PersistentOrderedMap<K, V>) : ImmutableCollection<V>, AbstractCollection<V>() {
override val size: Int
get() = map.size
override fun contains(element: V): Boolean {
return map.containsValue(element)
}
override fun iterator(): Iterator<V> {
return PersistentOrderedMapValuesIterator(map)
}
} | apache-2.0 | 116310e47c01e0bd10ddae335c59e451 | 35.14 | 159 | 0.693798 | 4.104545 | false | false | false | false |
ibinti/intellij-community | plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaDecompiler.kt | 9 | 11593 | /*
* 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.java.decompiler
import com.intellij.execution.filters.LineNumbersMapping
import com.intellij.icons.AllIcons
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DefaultProjectFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.psi.PsiJavaModule
import com.intellij.psi.PsiPackage
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.compiled.ClassFileDecompilers
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.ui.Gray
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences
import org.jetbrains.java.decompiler.main.extern.IResultSaver
import java.awt.BorderLayout
import java.io.File
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.jar.Manifest
import javax.swing.BorderFactory
import javax.swing.JComponent
import javax.swing.JEditorPane
class IdeaDecompiler : ClassFileDecompilers.Light() {
companion object {
const val BANNER = "//\n// Source code recreated from a .class file by IntelliJ IDEA\n// (powered by Fernflower decompiler)\n//\n\n"
private val LEGAL_NOTICE_KEY = "decompiler.legal.notice.accepted"
private fun getOptions(): Map<String, Any> {
val project = DefaultProjectFactory.getInstance().defaultProject
val options = CodeStyleSettingsManager.getInstance(project).currentSettings.getIndentOptions(JavaFileType.INSTANCE)
val indent = StringUtil.repeat(" ", options.INDENT_SIZE)
return mapOf(
IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
IFernflowerPreferences.REMOVE_BRIDGE to "1",
IFernflowerPreferences.LITERALS_AS_IS to "1",
IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
IFernflowerPreferences.BANNER to BANNER,
IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
IFernflowerPreferences.INDENT_STRING to indent,
IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")
}
}
private val myLogger = lazy { IdeaLogger() }
private val myOptions = lazy { getOptions() }
private val myFutures = ContainerUtil.newConcurrentMap<VirtualFile, Future<CharSequence>>()
@Volatile private var myLegalNoticeAccepted = false
init {
myLegalNoticeAccepted = ApplicationManager.getApplication().isUnitTestMode || PropertiesComponent.getInstance().isValueSet(LEGAL_NOTICE_KEY)
if (!myLegalNoticeAccepted) {
intercept()
}
}
private fun intercept() {
val app = ApplicationManager.getApplication()
val connection = app.messageBus.connect(app)
connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, object : FileEditorManagerListener.Before.Adapter() {
override fun beforeFileOpened(source: FileEditorManager, file: VirtualFile) {
if (!myLegalNoticeAccepted && file.fileType === StdFileTypes.CLASS && ClassFileDecompilers.find(file) === this@IdeaDecompiler) {
myFutures.put(file, app.executeOnPooledThread(Callable<CharSequence> { decompile(file) }))
val dialog = LegalNoticeDialog(source.project, file)
dialog.show()
when (dialog.exitCode) {
DialogWrapper.OK_EXIT_CODE -> {
PropertiesComponent.getInstance().setValue(LEGAL_NOTICE_KEY, true)
myLegalNoticeAccepted = true
app.invokeLater({
RefreshQueue.getInstance().processSingleEvent(
VFileContentChangeEvent(this@IdeaDecompiler, file, file.modificationStamp, -1, false))
})
connection.disconnect()
}
LegalNoticeDialog.DECLINE_EXIT_CODE -> {
myFutures.remove(file)?.cancel(true)
PluginManagerCore.disablePlugin("org.jetbrains.java.decompiler")
ApplicationManagerEx.getApplicationEx().restart(true)
}
LegalNoticeDialog.POSTPONE_EXIT_CODE -> {
myFutures.remove(file)?.cancel(true)
}
}
}
}
})
}
override fun accepts(file: VirtualFile): Boolean = true
override fun getText(file: VirtualFile): CharSequence =
if (myLegalNoticeAccepted) myFutures.remove(file)?.get() ?: decompile(file)
else ClsFileImpl.decompile(file)
private fun decompile(file: VirtualFile): CharSequence {
if (PsiPackage.PACKAGE_INFO_CLS_FILE == file.name || PsiJavaModule.MODULE_INFO_CLS_FILE == file.name) {
return ClsFileImpl.decompile(file)
}
val indicator = ProgressManager.getInstance().progressIndicator
if (indicator != null) {
indicator.text = IdeaDecompilerBundle.message("decompiling.progress", file.name)
}
try {
val mask = "${file.nameWithoutExtension}$"
val files = mapOf(file.path to file) +
file.parent.children.filter { it.nameWithoutExtension.startsWith(mask) && it.fileType === StdFileTypes.CLASS }.map { it.path to it }
val options = HashMap(myOptions.value)
if (Registry.`is`("decompiler.use.line.mapping")) {
options.put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1")
}
if (Registry.`is`("decompiler.dump.original.lines")) {
options.put(IFernflowerPreferences.DUMP_ORIGINAL_LINES, "1")
}
val provider = MyBytecodeProvider(files)
val saver = MyResultSaver()
val decompiler = BaseDecompiler(provider, saver, options, myLogger.value)
files.keys.forEach { path -> decompiler.addSpace(File(path), true) }
decompiler.decompileContext()
val mapping = saver.myMapping
if (mapping != null) {
file.putUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY, ExactMatchLineNumbersMapping(mapping))
}
return saver.myResult
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
if (ApplicationManager.getApplication().isUnitTestMode) {
throw AssertionError(file.url, e)
}
else {
throw ClassFileDecompilers.Light.CannotDecompileException(e)
}
}
}
private class MyBytecodeProvider(private val files: Map<String, VirtualFile>) : IBytecodeProvider {
override fun getBytecode(externalPath: String, internalPath: String?): ByteArray {
val path = FileUtil.toSystemIndependentName(externalPath)
val file = files[path] ?: throw AssertionError(path + " not in " + files.keys)
return file.contentsToByteArray(false)
}
}
private class MyResultSaver : IResultSaver {
var myResult = ""
var myMapping: IntArray? = null
override fun saveClassFile(path: String, qualifiedName: String, entryName: String, content: String, mapping: IntArray?) {
if (myResult.isEmpty()) {
myResult = content
myMapping = mapping
}
}
override fun saveFolder(path: String) { }
override fun copyFile(source: String, path: String, entryName: String) { }
override fun createArchive(path: String, archiveName: String, manifest: Manifest) { }
override fun saveDirEntry(path: String, archiveName: String, entryName: String) { }
override fun copyEntry(source: String, path: String, archiveName: String, entry: String) { }
override fun saveClassEntry(path: String, archiveName: String, qualifiedName: String, entryName: String, content: String) { }
override fun closeArchive(path: String, archiveName: String) { }
}
private class ExactMatchLineNumbersMapping(private val mapping: IntArray) : LineNumbersMapping {
@Suppress("LoopToCallChain")
override fun bytecodeToSource(line: Int): Int {
for (i in mapping.indices step 2) {
if (mapping[i] == line) {
return mapping[i + 1]
}
}
return -1
}
@Suppress("LoopToCallChain")
override fun sourceToBytecode(line: Int): Int {
for (i in mapping.indices step 2) {
if (mapping[i + 1] == line) {
return mapping[i]
}
}
return -1
}
}
private class LegalNoticeDialog(project: Project, file: VirtualFile) : DialogWrapper(project) {
companion object {
val POSTPONE_EXIT_CODE = DialogWrapper.CANCEL_EXIT_CODE
val DECLINE_EXIT_CODE = DialogWrapper.NEXT_USER_EXIT_CODE
}
private var myMessage: JEditorPane? = null
init {
title = IdeaDecompilerBundle.message("legal.notice.title", StringUtil.last(file.path, 40, true))
setOKButtonText(IdeaDecompilerBundle.message("legal.notice.action.accept"))
setCancelButtonText(IdeaDecompilerBundle.message("legal.notice.action.postpone"))
init()
pack()
}
override fun createCenterPanel(): JComponent? {
val iconPanel = JBPanel<JBPanel<*>>(BorderLayout())
iconPanel.add(JBLabel(AllIcons.General.WarningDialog), BorderLayout.NORTH)
val message = JEditorPane()
myMessage = message
message.editorKit = UIUtil.getHTMLEditorKit()
message.isEditable = false
message.preferredSize = JBUI.size(500, 100)
message.border = BorderFactory.createLineBorder(Gray._200)
message.text = "<div style='margin:5px;'>${IdeaDecompilerBundle.message("legal.notice.text")}</div>"
val panel = JBPanel<JBPanel<*>>(BorderLayout(JBUI.scale(10), 0))
panel.add(iconPanel, BorderLayout.WEST)
panel.add(message, BorderLayout.CENTER)
return panel
}
override fun createActions() =
arrayOf(okAction, DialogWrapperExitAction(IdeaDecompilerBundle.message("legal.notice.action.reject"), DECLINE_EXIT_CODE), cancelAction)
override fun getPreferredFocusedComponent() = myMessage
}
} | apache-2.0 | 33d2f23c7f75b8c17f5516ee9476d704 | 39.256944 | 144 | 0.718882 | 4.539154 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/messenger/MessagesEndpoint.kt | 2 | 1823 | package me.proxer.library.api.messenger
import me.proxer.library.ProxerCall
import me.proxer.library.api.Endpoint
import me.proxer.library.entity.messenger.Message
/**
* Endpoint for retrieving the user's messages.
*
* Four types of this request exist:
* 1) [conferenceId] = 0 and [messageId] = 0: Returns the last messages of the user from all conferences.
* 2) [conferenceId] = 0 and [messageId] != 0: Returns the last messages before that of the passed [messageId] from all
* conferences.
* 3) [conferenceId] != 0 and [messageId] = 0: Returns the last messages of the conference, specified by the passed
* [conferenceId].
* 4) [conferenceId] != 0 and message != 0: Returns the last messages before that of the passed [messageId] of the
* conference, specified by the passed [conferenceId].
*
* Moreover the [markAsRead] parameter controls if the conference should be marked as read in the cases 3) and 4).
*
* @author Ruben Gees
*/
class MessagesEndpoint internal constructor(private val internalApi: InternalApi) : Endpoint<List<Message>> {
private var conferenceId: String? = null
private var messageId: String? = null
private var markAsRead: Boolean? = null
/**
* Sets the conference id of the conference to load.
*/
fun conferenceId(conferenceId: String?) = this.apply { this.conferenceId = conferenceId }
/**
* Sets the message id to load from.
*/
fun messageId(messageId: String?) = this.apply { this.messageId = messageId }
/**
* Sets if the conference should be marked as read. Defaults to true.
*/
fun markAsRead(markAsRead: Boolean? = true) = this.apply { this.markAsRead = markAsRead }
override fun build(): ProxerCall<List<Message>> {
return internalApi.messages(conferenceId, messageId, markAsRead)
}
}
| gpl-3.0 | 4019caa5135dbce67c27016b29d8cf03 | 37.787234 | 119 | 0.707625 | 4.269321 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/database/SgShow2.kt | 1 | 4627 | package com.battlelancer.seriesguide.shows.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.battlelancer.seriesguide.provider.SeriesGuideContract.SgShow2Columns
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows
import com.battlelancer.seriesguide.shows.tools.NextEpisodeUpdater
import com.battlelancer.seriesguide.shows.tools.ShowStatus
@Entity(
tableName = "sg_show",
indices = [
Index(SgShow2Columns.TMDB_ID),
Index(SgShow2Columns.TVDB_ID)
]
)
data class SgShow2(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = SgShow2Columns._ID) val id: Long = 0,
@ColumnInfo(name = SgShow2Columns.TMDB_ID) val tmdbId: Int?,
@ColumnInfo(name = SgShow2Columns.TVDB_ID) val tvdbId: Int?,
@ColumnInfo(name = SgShow2Columns.SLUG) val slug: String? = "",
@ColumnInfo(name = SgShow2Columns.TRAKT_ID) val traktId: Int? = 0,
/**
* Ensure this is NOT null (enforced through database constraint).
*/
@ColumnInfo(name = SgShow2Columns.TITLE) val title: String = "",
@ColumnInfo(name = SgShow2Columns.TITLE_NOARTICLE) val titleNoArticle: String?,
@ColumnInfo(name = SgShow2Columns.OVERVIEW) val overview: String? = "",
/**
* Local release time. Encoded as integer (hhmm).
*
* <pre>
* Example: 2035
* Default: -1
* </pre>
*/
@ColumnInfo(name = SgShow2Columns.RELEASE_TIME) val releaseTime: Int?,
/**
* Local release week day. Encoded as integer.
* <pre>
* Range: 1-7
* Daily: 0
* Default: -1
* </pre>
*/
@ColumnInfo(name = SgShow2Columns.RELEASE_WEEKDAY) val releaseWeekDay: Int?,
@ColumnInfo(name = SgShow2Columns.RELEASE_COUNTRY) val releaseCountry: String?,
@ColumnInfo(name = SgShow2Columns.RELEASE_TIMEZONE) val releaseTimeZone: String?,
@ColumnInfo(name = SgShow2Columns.FIRST_RELEASE) val firstRelease: String?,
@ColumnInfo(name = SgShow2Columns.GENRES) val genres: String? = "",
@ColumnInfo(name = SgShow2Columns.NETWORK) val network: String? = "",
@ColumnInfo(name = SgShow2Columns.IMDBID) val imdbId: String? = "",
@ColumnInfo(name = SgShow2Columns.RATING_GLOBAL) val ratingGlobal: Double?,
@ColumnInfo(name = SgShow2Columns.RATING_VOTES) val ratingVotes: Int?,
@ColumnInfo(name = SgShow2Columns.RATING_USER) val ratingUser: Int? = 0,
@ColumnInfo(name = SgShow2Columns.RUNTIME) val runtime: Int? = 0,
@ColumnInfo(name = SgShow2Columns.STATUS) val status: Int? = ShowStatus.UNKNOWN,
@ColumnInfo(name = SgShow2Columns.CONTENTRATING) val contentRating: String? = "",
@ColumnInfo(name = SgShow2Columns.NEXTEPISODE) val nextEpisode: String? = "",
@ColumnInfo(name = SgShow2Columns.POSTER) val poster: String? = "",
@ColumnInfo(name = SgShow2Columns.POSTER_SMALL) val posterSmall: String? = "",
@ColumnInfo(name = SgShow2Columns.NEXTAIRDATEMS) val nextAirdateMs: Long? = NextEpisodeUpdater.UNKNOWN_NEXT_RELEASE_DATE,
@ColumnInfo(name = SgShow2Columns.NEXTTEXT) val nextText: String? = "",
@ColumnInfo(name = SgShow2Columns.LASTUPDATED) val lastUpdatedMs: Long,
@ColumnInfo(name = SgShow2Columns.LASTEDIT) val lastEditedSec: Long = 0,
@ColumnInfo(name = SgShow2Columns.LASTWATCHEDID) val lastWatchedEpisodeId: Long = 0,
@ColumnInfo(name = SgShow2Columns.LASTWATCHED_MS) val lastWatchedMs: Long = 0,
@ColumnInfo(name = SgShow2Columns.LANGUAGE) val language: String? = "",
@ColumnInfo(name = SgShow2Columns.UNWATCHED_COUNT) val unwatchedCount: Int = UNKNOWN_UNWATCHED_COUNT,
@ColumnInfo(name = SgShow2Columns.FAVORITE) var favorite: Boolean = false,
@ColumnInfo(name = SgShow2Columns.HIDDEN) var hidden: Boolean = false,
@ColumnInfo(name = SgShow2Columns.NOTIFY) var notify: Boolean = true,
@ColumnInfo(name = SgShow2Columns.HEXAGON_MERGE_COMPLETE) val hexagonMergeComplete: Boolean = true
) {
val releaseTimeOrDefault: Int
get() = releaseTime ?: -1
val firstReleaseOrDefault: String
get() = firstRelease ?: ""
val releaseWeekDayOrDefault: Int
get() = releaseWeekDay ?: -1
val statusOrUnknown: Int
get() = status ?: ShowStatus.UNKNOWN
val ratingGlobalOrZero: Double
get() = ratingGlobal ?: 0.0
val ratingVotesOrZero: Int
get() = ratingVotes ?: 0
companion object {
/**
* Used if the number of remaining episodes to watch for a show is not (yet) known.
*
* @see Shows.UNWATCHED_COUNT
*/
const val UNKNOWN_UNWATCHED_COUNT = -1
}
}
| apache-2.0 | 7e88638f1cc53c4de014203b1e08ed63 | 46.214286 | 125 | 0.699373 | 3.884971 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/location/Locations.kt | 1 | 735 | package com.rpkit.core.bukkit.location
import com.rpkit.core.location.RPKBlockLocation
import com.rpkit.core.location.RPKLocation
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.block.Block
fun RPKLocation.toBukkitLocation() = Bukkit.getWorld(world)?.let { world ->
Location(world, x, y, z, yaw, pitch)
}
fun Location.toRPKLocation() = RPKLocation(
world?.name ?: Bukkit.getWorlds()[0].name, x, y, z, yaw, pitch
)
fun RPKBlockLocation.toBukkitBlock() = Bukkit.getWorld(world)?.getBlockAt(x, y, z)
fun Location.toRPKBlockLocation() = RPKBlockLocation(
world?.name ?: Bukkit.getWorlds()[0].name, blockX, blockY, blockZ
)
fun Block.toRPKBlockLocation() = RPKBlockLocation(
world.name, x, y, z
) | apache-2.0 | ddda2fd02cb0b9900f24185dd2efdbab | 28.44 | 82 | 0.744218 | 3.418605 | false | false | false | false |
rori-dev/lunchbox | backend-spring-kotlin/src/test/kotlin/lunchbox/domain/resolvers/LunchResolverGesundheitszentrumTest.kt | 1 | 44566 | package lunchbox.domain.resolvers /* ktlint-disable max-line-length */
import com.fasterxml.jackson.module.kotlin.readValue
import io.mockk.mockk
import lunchbox.domain.models.LunchOffer
import lunchbox.domain.models.LunchProvider.GESUNDHEITSZENTRUM
import lunchbox.domain.resolvers.LunchResolverGesundheitszentrum.Wochenplan
import lunchbox.domain.resolvers.LunchResolverGesundheitszentrum.WochenplanWithImageId
import lunchbox.util.date.DateValidator
import lunchbox.util.facebook.FacebookGraphApi
import lunchbox.util.facebook.Image
import lunchbox.util.facebook.Posts
import lunchbox.util.html.HtmlParser
import lunchbox.util.html.HtmlRenderer
import lunchbox.util.json.createObjectMapper
import lunchbox.util.ocr.OcrClient
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldContain
import org.amshove.kluent.shouldHaveSize
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.net.URL
class LunchResolverGesundheitszentrumTest {
private val graphApi = mockk<FacebookGraphApi>()
private val ocrClient = mockk<OcrClient>()
private val htmlRenderer = object : HtmlRenderer {
override fun render(url: URL): String = url.readText() // example files are pre-rendered
}
private val htmlParser = HtmlParser(htmlRenderer)
private fun resolver() = LunchResolverGesundheitszentrum(DateValidator.alwaysValid(), graphApi, htmlParser, ocrClient)
private val providerId = GESUNDHEITSZENTRUM.id
private val objectMapper = createObjectMapper()
@Nested
inner class GraphApi {
@Test
fun `resolve Wochenplaene for posts of 2015-07-05`() {
val content = readFileContent("/menus/gesundheitszentrum/graphapi/2015-07-05_posts.json")
val posts = objectMapper.readValue<Posts>(content)
val wochenplaene = resolver().parseWochenplaeneByGraphApi(posts.data)
wochenplaene shouldContain WochenplanWithImageId(date("2015-07-06"), "723372204440300")
wochenplaene shouldContain WochenplanWithImageId(date("2015-06-22"), "715616615215859")
wochenplaene shouldContain WochenplanWithImageId(date("2015-06-15"), "712691465508374")
}
@Test
fun `resolve Wochenplaene for posts of 2017-07-24`() {
val content = readFileContent("/menus/gesundheitszentrum/graphapi/2017-07-24_posts.json")
val posts = objectMapper.readValue<Posts>(content)
val wochenplaene = resolver().parseWochenplaeneByGraphApi(posts.data)
wochenplaene shouldContain WochenplanWithImageId(date("2017-07-24"), "1214480778662771")
wochenplaene shouldContain WochenplanWithImageId(date("2017-07-17"), "1208020239308825")
wochenplaene shouldContain WochenplanWithImageId(date("2017-07-10"), "1204499422994240")
}
@Test
fun `resolve double-imaged Wochenplan for posts of 2016-04-25`() {
val content = readFileContent("/menus/gesundheitszentrum/graphapi/2016-04-25_posts.json")
val posts = objectMapper.readValue<Posts>(content)
val wochenplaene = resolver().parseWochenplaeneByGraphApi(posts.data)
wochenplaene shouldContain WochenplanWithImageId(date("2016-04-25"), "855667961210723")
}
@Test
fun `resolve URL for image of 2015-07-05`() {
val content = readFileContent("/menus/gesundheitszentrum/graphapi/2015-07-05_image.json")
val image = objectMapper.readValue<Image>(content)
val url = resolver().parseImageLink(image)
url shouldBeEqualTo URL("https://scontent.xx.fbcdn.net/hphotos-xtp1/t31.0-8/11709766_723372204440300_7573791609611941912_o.jpg")
}
@Test
fun `resolve URL for image of 2017-07-24`() {
val content = readFileContent("/menus/gesundheitszentrum/graphapi/2017-07-24_image.json")
val image = objectMapper.readValue<Image>(content)
val url = resolver().parseImageLink(image)
url shouldBeEqualTo URL("https://scontent.xx.fbcdn.net/v/t31.0-8/20233053_1214480778662771_9100409891617048289_o.jpg?oh=a50f5058410183e8a5c631e82919f473&oe=5A09D7B9")
}
}
@Nested
inner class HtmlParsing {
@Test
fun `resolve Wochenplaene for posts of 2019-09-16`() {
val url = javaClass.getResource("/menus/gesundheitszentrum/html/2019-09-16_posts.html")
val wochenplaene = resolver().parseWochenplaeneByHtml(url)
wochenplaene shouldHaveSize 2
wochenplaene shouldContain Wochenplan(date("2019-09-16"), URL("https://scontent-ber1-1.xx.fbcdn.net/v/t1.0-9/70243813_2176643935779779_1905631810474213376_o.jpg?_nc_cat=106&_nc_oc=AQnOmbEvG5WngTMx4RqIMiGBD4jDftJMUMYi2M5uwa3Nu3QAJUdseNXbSEr1Iejl_Ds&_nc_ht=scontent-ber1-1.xx&oh=e40ce027618fa63a5b7f4971fc02b83d&oe=5E06EF54"))
wochenplaene shouldContain Wochenplan(date("2019-09-09"), URL("https://scontent-ber1-1.xx.fbcdn.net/v/t1.0-9/69761025_2164731656971007_4787155769139134464_o.jpg?_nc_cat=101&_nc_oc=AQlqnbM_DBfJ-eB1mBQK48kb8M3UWtjmyGo1knDG-9caTgaJAPraVhT6ZuHcff7_5P0&_nc_ht=scontent-ber1-1.xx&oh=77d585b271943105b09845d3ed23c00b&oe=5DF4A077"))
}
@Test
fun `resolve Wochenplaene for posts of 2019-09-23`() {
val url = javaClass.getResource("/menus/gesundheitszentrum/html/2019-09-23_posts.html")
val wochenplaene = resolver().parseWochenplaeneByHtml(url)
wochenplaene shouldHaveSize 2
wochenplaene shouldContain Wochenplan(date("2019-09-23"), URL("https://scontent-ber1-1.xx.fbcdn.net/v/t1.0-9/70741530_2188809777896528_1685416184234639360_o.jpg?_nc_cat=104&_nc_oc=AQn0voSe6PW2bpXJhANweSiOIyLcrYb0G-NmImMtPJ6Ka4swX6GfSG-Eudtb4LkGCe8&_nc_ht=scontent-ber1-1.xx&oh=be84961d17026c68fc74c1ecf23b2396&oe=5DF929A9"))
wochenplaene shouldContain Wochenplan(date("2019-09-16"), URL("https://scontent-ber1-1.xx.fbcdn.net/v/t1.0-9/70243813_2176643935779779_1905631810474213376_o.jpg?_nc_cat=106&_nc_oc=AQnlw8UTdf_EHJa-WZ3OfYWP7TyOyahpP-xMOhEj_-x_78veJsYvEmYT68pImua8XLA&_nc_ht=scontent-ber1-1.xx&oh=00559a3cb8d8df7486d84dc607a7c2b0&oe=5E2E7C54"))
}
}
@Test
fun `resolve offers for week of 2015-06-22`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2015-06-22.jpg.txt")
val week = weekOf("2015-06-22")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Wirsingkohleintopf", "", week.monday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Riesenkrakauer mit Sauerkraut und Salzkartoffeln", "", week.monday, euro("4.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Steak \"au four\" mit Buttererbsen und Kroketten", "", week.monday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Tortellini mit Tomatensauce", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Germknödel mit Vanillesauce und Mohn", "", week.tuesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Jägerschnitzel (panierte Jagdwurst) mit Tomatensauce und Nudeln", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllter Schweinerücken mit Gemüse und Salzkartoffeln", "", week.tuesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eier-Spinatragout mit Petersilienkartoffeln", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Vegetarisches Chili", "", week.wednesday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schmorkohl mit Hackfleisch und Salzkartoffeln", "", week.wednesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprikahähnchenkeule mit Gemüse und Salzkartoffeln", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schollenfilet mit Gemüsereis", "", week.wednesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pichelsteiner Gemüseeintopf", "", week.thursday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinegeschnetzeltes mit Pilzen dazu Reis", "", week.thursday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gebratenes Putensteak mit Champignons-Rahmsauce und Spätzle", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Nudel-Gemüse-Auflauf", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Brühreis", "", week.friday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hühnerfrikassee mit Champignons, Spargel und Reis", "", week.friday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Holzfällersteak mit geschmorten Zwiebeln, Pilzen und Bratkartoffeln", "", week.friday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kräuterrüherei mit Kartoffelpüree", "", week.friday, euro("3.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2015-06-29`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2015-06-29.jpg.txt")
val week = weekOf("2015-06-29")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Bunter Gemüseeintopf", "", week.monday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Boulette mit Mischgemüse und Kartoffelpüree", "", week.monday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinekammbraten mit Rotkohl und Klöße", "", week.monday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta mit Pilzrahmsauce", "", week.monday, euro("3.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Grießbrei mit roten Früchten", "", week.tuesday, euro("2.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Blutwurst mit Sauerkraut und Salzkartoffeln", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinerollbraten mit grünen Bohnen und Salzkartoffeln", "", week.tuesday, euro("4.50"), emptySet(), providerId) // OCR erkennt Preis falsch
offers shouldContain LunchOffer(0, "Pilzragout mit Semmelknödel", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Minestrone", "", week.wednesday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllte Paprikaschote mit Tomatensauce und Reis", "", week.wednesday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenbrust mit Wirsingrahmgemüse und Salzkartoffeln", "", week.wednesday, euro("4.70"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pangasiusfilet mit Honig-Senf-Dillrahmsauce dazu Salzkartoffeln", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Feuertopf (Kidneybohnen, grüne Bohnen, Jagdwurst)", "", week.thursday, euro("2.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprikasahnegulasch mit Nudeln", "", week.thursday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rieseneisbein mit Sauerkraut und Salzkartoffeln", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Tomaten-Zucchini-Auflauf mit Mozzarella überbacken", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Porreeeintopf", "", week.friday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hackbraten mit Mischgemüse und Salzkartoffeln", "", week.friday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Wildgulasch mit Rotkohl und Klöße", "", week.friday, euro("4.50"), emptySet(), providerId) // OCR erkennt Preis falsch
offers shouldContain LunchOffer(0, "Matjestopf mit Bohnensalat und Kräuterkartoffeln", "", week.friday, euro("4.20"), emptySet(), providerId)
}
@Test
fun `resolve offers for badly OCR-able plan of week of 2015-06-15`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2015-06-15.jpg.txt")
val week = weekOf("2015-06-15")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Vegetarische Linsensuppe mit Vollkornbrötchen", "", week.monday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Ofenfrischer Leberkäs mit einem Setzei, Zwiebelsauce und Kartoffelpüree", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinekammsteak mit Rahmchampions, dazu Pommes frites", "", week.monday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rührei mit Sauce \"Funghi\" und Kartoffelpüree", "", week.monday, euro("3.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Milchreis mit Zucker und Zimt", "", week.tuesday, euro("3.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "2 Setzeier (außer Haus Rührei) mit Spinat und Salzkartoffeln", "", week.tuesday, euro("3.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gemischtes Gulasch aus Rind und Schwein dazu Nudeln", "", week.tuesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta mit Blattspinat, Tomaten und Reibekäse (analog)", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gulaschsuppe", "", week.wednesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "2 Bifteki mit Zigeunersauce und Reis", "", week.wednesday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rinderbraten mit Rotkohl und Klößen", "", week.wednesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Forelle \"Müllerin Art\" mit zerlassener Butter und Salzkartoffeln", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kohlrabieintopf", "", week.thursday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pfefferfleisch mit Buttergemüse dazu Reis", "", week.thursday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinekammsteak mit Rahmchampions, dazu Pommes frites", "", week.thursday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Tomaten-Zucchini-Auflauf", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Ungarischer Sauerkrauttopf", "", week.friday, euro("2.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Cevapcici mit Zigeunersauce und Reis", "", week.friday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenschnitzel \"Wiener Art\" mit Pfefferrahmsauce, Gemüse und Kroketten", "", week.friday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Sahnehering mit Bratkartoffeln", "", week.friday, euro("3.70"), emptySet(), providerId)
}
@Test
fun `resolve offers for short week of 2015-07-06`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2015-07-06.jpg.txt")
val week = weekOf("2015-07-06")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 16
offers shouldContain LunchOffer(0, "Serbischer Bohneneintopf", "", week.monday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rostbratwurst mit Sauerkraut und Kartoffelpüree", "", week.monday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Thüringer Rostbrätl mit geschmorten Zwiebeln und Bratkartoffeln", "", week.monday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gebackener Camembert mit Preiselbeeren, 1/2 Birne und Baguette", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hefeklöße mit Früchten", "", week.tuesday, euro("3.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta \"Schuta\" (Hackfleisch und Paprika) auf Nudeln", "", week.tuesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Rinderroulade mit Rotkohl und Klößen", "", week.tuesday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllte Paprika (vegetarisch) mit Vollkornreis und Salat", "", week.tuesday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gelber Erbseneintopf", "", week.wednesday, euro("2.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Königsberger Klopse mit Kapernsauce und Salzkartoffeln", "", week.wednesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Lachs mit Makkaroni und Möhren-Sellerie-Salat", "", week.wednesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Mexikanischer Nudelauflauf", "", week.wednesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Reitersuppe (Hackfleisch, grüne Bohnen, Champignons, Paprika)", "", week.thursday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Chinapfanne mit Reis", "", week.thursday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gemischtes Gulasch aus Rind und Schwein dazu Nudeln", "", week.thursday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Blumenkohl-Gratin", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers.filter { it.day == week.friday } shouldHaveSize 0
}
@Test
fun `resolve offers for week of 2015-07-27`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2015-07-27.jpg.txt")
val week = weekOf("2015-07-27")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Kartoffelsuppe mit Wiener", "", week.monday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweineleber mit Zwiebelsauce und Kartoffelpüree", "", week.monday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchen \"Cordon Bleu\" ;Pfefferrahmsauce, Gemüse und Kroketten", "", week.monday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllte Kartoffeltaschen mit Tomatensauce", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Germknödel mit Vanillesauce und Mohn", "", week.tuesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprikasahnegulasch mit Nudeln", "", week.tuesday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllter Schweinerücken mit Gemüse und Salzkartoffeln", "", week.tuesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Vegetarische Paprikaschote mit Vollkornreis und Salat", "", week.tuesday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gulaschsuppe", "", week.wednesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schmorkohl mit Hackfleisch und Salzkartoffeln", "", week.wednesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pangasius mit Honig-Senf-Dillrahmsauce und Salzkartoffeln", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Brokkoli-Auflauf", "", week.wednesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Käse-Lauch-Suppe", "", week.thursday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hühnerfrikassee mit Champignons, Spargel und Reis", "", week.thursday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Steak \"au four\" mit Buttererbsen und Kroketten", "", week.thursday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta mit Blattspinat, Tomaten und Reibekäse", "", week.thursday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Fischtopf", "", week.friday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinegeschnetzeltes mit Pilzen und Reis", "", week.friday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Holzfällersteak mit geschmorten Zwiebeln und Bratkartoffeln", "", week.friday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kräuterrührei mit Kartoffelpüree", "", week.friday, euro("3.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2016-04-04`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2016-04-04.jpg.txt")
val week = weekOf("2016-04-04")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 21
offers shouldContain LunchOffer(0, "Käse-Hackfleisch-Lauch-Suppe", "", week.monday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "\"Jägerschnitzel\"(panierte Jagdwurst), Tomatensauce und Nudeln", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenstreifen in Rucolasauce und Tomatenmakkaroni", "", week.monday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunte Reispfanne mit Gemüse", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Kartoffelpuffer mit Apfelmus und Zucker", "", week.tuesday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hackroulade mit Sahnesauce, Gemüse und Salzkartoffeln", "", week.tuesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putengeschnetzeltes mit Champignons dazu Spätzle", "", week.tuesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Frühlingsrolle mit Asiagemüse und Reis", "", week.tuesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Brühnudeln", "", week.wednesday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Matjestopf mit Kräuterkartoffeln und Bohnensalat", "", week.wednesday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gebratenes Pangasiusfilet mit Kräutersauce und Salzkartoffeln", "", week.wednesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gebackener Camembert mit 1/2 Birne, Preiselbeeren und Baguette", "", week.wednesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kokos-Curry-Suppe mit Hühnerfleisch", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinegulasch mit Nudeln", "", week.thursday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Curryhuhn mit Makkaroni", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kräuterrührei mit Pilzrahmsauce und Kartoffelpüree", "", week.thursday, euro("3.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rieseneisbein mit Erbspüree, Sauerkraut, und Salzkartoffeln", "", week.thursday, euro("5.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Chili con Carne", "", week.friday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Wurstgulasch mit Nudeln", "", week.friday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Tiroler Eiersalat (Mais, Champignons, Spargel) dazu Bratkartoffeln", "", week.friday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinekammbraten mit Rotkohl und Salzkartoffeln", "", week.friday, euro("4.50"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2016-04-11`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2016-04-11.jpg.txt")
val week = weekOf("2016-04-11")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Kokos-Curry-Suppe mit Hühnerfleisch", "", week.monday, euro("2.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schichtkohl mit Hackfleisch und Salzkartoffeln", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinemedaillons mit Pfeffersauce und Kroketten", "", week.monday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Brokkoli in Käse-Sahne-Sauce und Nudeln", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Eierkuchen mit Apfelmus und Zucker", "", week.tuesday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta Schuta (Hackfleisch und Paprika) und Nudeln", "", week.tuesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kasselerbraten mit Sauerkraut dazu Salzkartoffeln", "", week.tuesday, euro("4.70"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rührei mit Sauce Funghi dazu Kartoffelpüree", "", week.tuesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Möhren-Zucchini-Eintopf", "", week.wednesday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Boulette mit Champignonrahm dazu Kartoffelpüree", "", week.wednesday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Seelachs in Eihülle auf Lauch-Tomatengemüse dazu Reis", "", week.wednesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Makkaroni mit Blattspinat, Tomaten und Reibekäse", "", week.wednesday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffelsuppe mit Wiener", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Blutwurst mit Sauerkraut und Salzkartoffeln", "", week.thursday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenkeule mit Gemüsereis", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Spaghetti \"all Arrabiata\" (scharf)", "", week.thursday, euro("3.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bauerntopf (Hackfleisch, Kartoffel, Paprika)", "", week.friday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Böhmisches Bierfleisch mit Semmelknödel", "", week.friday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinekammsteak mit Letcho und Reis", "", week.friday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eierfrikassee mit Salzkartoffeln", "", week.friday, euro("4.00"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2016-04-18`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2016-04-18.jpg.txt")
val week = weekOf("2016-04-18")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 20
offers shouldContain LunchOffer(0, "Hausgemachte Soljanka", "", week.monday, euro("2.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gemischter Gulasch mit Rotkohl und Kartoffeln", "", week.monday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Nudel-Broccoli-Auflauf", "", week.monday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Steak \"au four\" mit Würzfleisch überbacken dazu Gemüse und Pommes Frites", "", week.monday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Germknödel mit Vanillesauce und Mohn", "", week.tuesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Cevapcici mit Zigeunersauce dazu Reis", "", week.tuesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Champignonpfanne mit Kartoffelpüree", "", week.tuesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchen \"Cordon Bleu\" mit Pfeffersauce dazu Gemüse Kroketten", "", week.tuesday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunter Gemüse Eintopf", "", week.wednesday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gemüseschnitzel mit Sauce Hollandaise und Kartoffelpüree", "", week.wednesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "2 Rinderbouletten mit Ratatouille dazu Reis", "", week.wednesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schollenfilet mit Gemüsereis", "", week.wednesday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rosenkohleintopf", "", week.thursday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprikasahnegulasch mit Nudeln", "", week.thursday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Zucchinie-Tomaten Auflauf mit Mozzarella überbacken", "", week.thursday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Westfälischer Pfeffer Potthast (Rindfleisch) mit Rote Bete Salat dazu Salzkartoffeln", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Reitersuppe (Hackfleisch, grüne Bohnen, Chmapignons, Paprika)", "", week.friday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweineleber mit Zwiebelsauce dazu Kartoffelpüree", "", week.friday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllte Kartoffeltaschen mit Tomatensauce", "", week.friday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchengeschnetzeltes \"Gyros Art\" dazu Tzatziki und Reis", "", week.friday, euro("4.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2016-04-25`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2016-04-25.jpg.txt")
val week = weekOf("2016-04-25")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "Schwedische Fischsuppe mit Apfelstückchen", "", week.monday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Chinapfanne mit Geflügelfleisch dazu Reis", "", week.monday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Maultaschen auf Blattspinat dazu Käsesauce", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweineschnitzel \"Jäger Art\" mit Champignons und Waldpilzen in Rahm dazu Pommes Frites", "", week.monday, euro("4.70"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Grießbrei mit warmen Schattenmorellen", "", week.tuesday, euro("3.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schnitzeltag", "", week.tuesday, euro("5.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Tomatensuppe mit Sahnehäubchen", "", week.wednesday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Sahnehering mit Salzkartoffeln", "", week.wednesday, euro("3.70"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunte Reispfanne mit Gemüse", "", week.wednesday, euro("3.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinerahmgeschnetzeltes mit Spätzle", "", week.wednesday, euro("4.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kohlrabieintopf", "", week.thursday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pfefferfleisch mit Buttererbsen und Salzkarttofeln", "", week.thursday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gnocci mit Pilzrahmsauce und Parmesan", "", week.thursday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchen mit Mozzarellakruste und Curryreis", "", week.thursday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Brühnudeln", "", week.friday, euro("2.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Klopse \"Napoli\" mit Tomatensauce und Reis", "", week.friday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Asiatisches Wokgericht mit Cashewkernen dazu Reis", "", week.friday, euro("4.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Forelle \"Müllerin\" mit zerlassener Butter und Petersilienkartoffeln", "", week.friday, euro("4.90"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2016-05-09`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2016-05-09.jpg.txt")
val week = weekOf("2016-05-09")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 21
offers shouldContain LunchOffer(0, "Ofenfrischer Leberkäse mit Zwiebelsauce dazu Kartoffelpürree", "", week.wednesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rieseneisbein mit Sauerkraut dazu Salzkartoffeln", "", week.thursday, euro("5.10"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2017-07-24`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2017-07-24.jpg.txt")
val week = weekOf("2017-07-24")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "Scharfes Kartoffel-Paprika-Curry", "", week.tuesday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gelbe Erbseneintopf", "", week.friday, euro("2.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2017-07-31`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2017-07-31.jpg.txt")
val week = weekOf("2017-07-31")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 19
offers shouldContain LunchOffer(0, "Möhren-Zucchini-Eintopf", "", week.friday, euro("2.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kasselerkammbraten mit Sauerkraut und Salzkartoffeln", "", week.friday, euro("4.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2019-08-05`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2019-08-05.jpg.txt")
val week = weekOf("2019-08-05")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "Saarländische Kartoffelsuppe", "", week.monday, euro("3.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kräuterrührei mit Pilzrahmsauce und Kartoffelpüree", "", week.monday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Wurstgulasch mit Nudeln", "", week.monday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenbrust \"Melba\" Orangensauce und Kroketten", "", week.monday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Milchreis mit Zucker und Zimt", "", week.tuesday, euro("3.10"), emptySet(), providerId) // OCR erkennt Preis falsch
offers shouldContain LunchOffer(0, "Schupfnudeln mit Gorgonzolasauce", "", week.tuesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schmorkohl mit Hackfleisch und Salzkartoffeln", "", week.tuesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Westfälischer Pfefferpotthast (Rindfleisch) mit Rote Bete dazu Salzkartoffeln", "", week.tuesday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pichelsteiner Gemüseeintopf", "", week.wednesday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta mit Tomaten-Sugo, Oliven und Ruccola", "", week.wednesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Boulette mit Champignonrahm dazu Kartoffelpüree", "", week.wednesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Seelachs in Eihülle auf Lauch-Tomatengemüse dazu Reis", "", week.wednesday, euro("5.00"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Feuertopf (Kidneybohnen, grüne Bohnen, Jagdwurst)", "", week.thursday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Spinat Auflauf", "", week.thursday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Böhmisches Bierfleisch mit Semmelknödel", "", week.thursday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "\"Mailänder\" Käseschnitzel (Schweineschnitzel in Käse-Eihülle) mit Tomatensauce und Nudeln", "", week.thursday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Karotteneintopf", "", week.friday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinerahmgeschnetzeltes mit Champignons und Spätzle", "", week.friday, euro("5.00"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2019-09-09`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2019-09-09.jpg.txt")
val week = weekOf("2019-09-09")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "Kohlrabieintopf", "", week.monday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Frühlingsrolle mit süß-sauer Sauce dazu Reis", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Spaghetti \"Carbonara\" mit Schinken", "", week.monday, euro("4.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putenragout \"Provencial\" mit Champignon, Tomaten und Kräuter dazu Reis", "", week.monday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Germknödel mit Vanillesauce und Mohn", "", week.tuesday, euro("3.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Blumenkohl überbacken mit Sc.Hollandaise und Salzkartoffeln", "", week.tuesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprikasahnegulasch mit Nudeln", "", week.tuesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchen mit Mozzarellakruste und Curryreis", "", week.tuesday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Brühreis", "", week.wednesday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gebackener Camembert mit 1/2 Birne, Preiselbeeren und Baguette", "", week.wednesday, euro("4.10"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hausgemachte Boulette mit Champignonrahm dazu Kartoffelpüree", "", week.wednesday, euro("4.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Seelachs gebraten mit Mandelbutter dazu Brokkoli und Salzkartoffeln", "", week.wednesday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Käse-Hackfleisch-Lauch-Suppe", "", week.thursday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pasta mit Tomaten-Sugo, Oliven und Ruccola", "", week.thursday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "2 Currywürste mit Curryketchup und Pommes Frites", "", week.thursday, euro("4.80"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rindergeschnetzeltes \"Art Stroganoff\" mit Reis", "", week.thursday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Vegetarischer Linseneintopf mit einem Vollkornbrötchen", "", week.friday, euro("3.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Holzfällersteak mit Schmorzwiebeln dazu Bratkartoffeln", "", week.friday, euro("5.00"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2019-09-16`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2019-09-16.jpg.txt")
val week = weekOf("2019-09-16")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "Porreeeintopf", "", week.monday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Allgäuer-Gemüse-Käse-Salat", "", week.monday, euro("4.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Lasagne \"Bolognaise\" mit Pizza Mix", "", week.monday, euro("4.70"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putenbrustbraten mit Buttergemüse und Salzkartoffeln", "", week.monday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Milchreis mit Zucker und Zimt", "", week.tuesday, euro("3.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kartoffel-Brokkoli-Auflauf mit Feta und Sonnenblumenkernen", "", week.tuesday, euro("4.40"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Wurstgulasch mit Nudeln", "", week.tuesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Cevapcici mit Zigeunersauce dazu Reis", "", week.tuesday, euro("4.90"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Weißkohleintopf", "", week.wednesday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eierfrikasse mit Salzkartoffeln", "", week.wednesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Blutwurst mit Sauerkraut und Salzkartoffeln", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Matjestopf mit Kräuterkartoffeln und Bohnensalat", "", week.wednesday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Karotteneintopf", "", week.thursday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gefüllte Kartoffeltaschen mit Käse-Lauchsauce", "", week.thursday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Pfefferfleisch mit Buttererbsen und Reis", "", week.thursday, euro("4.60"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweineschnitzel \"Bolognaiser Art\" mit Hackfleischsauce überbacken dazu Pommes Frites", "", week.thursday, euro("5.20"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Linseneintopf", "", week.friday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "1/2 Hähnchen mit Pommes frites", "", week.friday, euro("4.80"), emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2019-09-23`() {
val text = readFileContent("/menus/gesundheitszentrum/ocr/2019-09-23.jpg.txt")
val week = weekOf("2019-09-23")
val offers = resolver().resolveOffersFromText(week.monday, text)
offers shouldHaveSize 18
offers shouldContain LunchOffer(0, "4/2 Eier mit Remouladensauce dazu Bratkartoffeln", "", week.wednesday, euro("4.30"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Reitersuppe (Hackfleisch, grüne Bohnen, Champignons, Paprika)", "", week.thursday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Möhren-Zucchini-Eintopf", "", week.friday, euro("3.50"), emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinesteak mit Waldpilzsauce und Rosmarinkartoffeln", "", week.friday, euro("5.20"), emptySet(), providerId)
}
private fun readFileContent(path: String): String {
val url = javaClass.getResource(path)
return url.readText(Charsets.UTF_8)
}
}
| mit | 000f510de19315cc953bb20b513098ae | 75.39759 | 330 | 0.732692 | 3.253463 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/AppKeySettingsPanel.kt | 1 | 2146 | package cn.yiiguxing.plugin.translate.ui
import cn.yiiguxing.plugin.translate.AppKeySettings
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.ui.UI.fillX
import cn.yiiguxing.plugin.translate.ui.UI.migLayout
import cn.yiiguxing.plugin.translate.ui.UI.wrap
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.components.JBTextField
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import javax.swing.Icon
import javax.swing.JLabel
import javax.swing.JPanel
class AppKeySettingsPanel(logoImage: Icon, appKeyLink: String, val appKeySettings: AppKeySettings) : JPanel() {
private val appIdField: JBTextField = JBTextField()
private val appKeyField: JBPasswordField = JBPasswordField()
private val logo: JLabel = JLabel(logoImage)
private val getApiKeyLink: ActionLink =
ActionLink(message("settings.link.getAppKey"), AllIcons.Ide.Link, AllIcons.Ide.Link) {
BrowserUtil.browse(appKeyLink)
}
init {
layout = migLayout()
minimumSize = JBUI.size(300, 0)
logo.border = JBUI.Borders.empty(10, 0, 18, 0)
add(logo, wrap().span(2).alignX("50%"))
val gap = JBUIScale.scale(8).toString()
add(JLabel(message("settings.label.appId")))
add(appIdField, fillX().gapLeft(gap).wrap())
add(JLabel(message("settings.label.appPrivateKey")))
add(appKeyField, fillX().gapLeft(gap).wrap())
getApiKeyLink.border = JBUI.Borders.empty(10, 0, 0, 0)
add(getApiKeyLink, wrap().span(2))
}
private var appKey: String?
get() = appKeyField.password
?.takeIf { it.isNotEmpty() }
?.let { String(it) }
?: ""
set(value) {
appKeyField.text = if (value.isNullOrEmpty()) null else value
}
fun reset() {
appIdField.text = appKeySettings.appId
appKey = appKeySettings.getAppKey()
}
fun apply() {
appKeySettings.appId = appIdField.text
appKeySettings.setAppKey(appKey)
}
} | mit | 4ecf09a0adf237115f83189aafc25242 | 32.546875 | 111 | 0.681733 | 3.952118 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/Game.kt | 1 | 9703 | package org.luxons.sevenwonders.engine
import org.luxons.sevenwonders.engine.boards.Board
import org.luxons.sevenwonders.engine.boards.Table
import org.luxons.sevenwonders.engine.cards.Card
import org.luxons.sevenwonders.engine.cards.Decks
import org.luxons.sevenwonders.engine.cards.Hands
import org.luxons.sevenwonders.engine.converters.toHandCards
import org.luxons.sevenwonders.engine.converters.toPlayedMove
import org.luxons.sevenwonders.engine.converters.toTableState
import org.luxons.sevenwonders.engine.data.LAST_AGE
import org.luxons.sevenwonders.engine.effects.SpecialAbility
import org.luxons.sevenwonders.engine.moves.Move
import org.luxons.sevenwonders.engine.moves.resolve
import org.luxons.sevenwonders.model.*
import org.luxons.sevenwonders.model.cards.CardBack
import org.luxons.sevenwonders.model.cards.HandCard
import org.luxons.sevenwonders.model.score.ScoreBoard
class Game internal constructor(
val id: Long,
private val settings: Settings,
boards: List<Board>,
private val decks: Decks,
) {
private val table: Table = Table(boards)
private val players: List<Player> = boards.map { SimplePlayer(it.playerIndex, table) }
private val discardedCards: MutableList<Card> = mutableListOf()
private val preparedMoves: MutableMap<Int, Move> = mutableMapOf()
private var currentTurnInfo: List<PlayerTurnInfo> = emptyList()
private var hands: Hands = Hands(emptyList())
private var militaryConflictsResolved = false
init {
startNewAge()
}
private fun startNewAge() {
militaryConflictsResolved = false
table.increaseCurrentAge()
hands = decks.deal(table.currentAge, players.size)
startNewTurn()
}
private fun startNewTurn() {
val newTableState = table.toTableState()
currentTurnInfo = players.map { player ->
val hand = hands.createHand(player)
val action = determineAction(hand, player.board)
createPlayerTurnInfo(player, action, hand, newTableState)
}
}
private fun startPlayDiscardedTurn() {
val newTableState = table.toTableState()
currentTurnInfo = players.map { player ->
val action = when {
player.board.hasSpecial(SpecialAbility.PLAY_DISCARDED) -> Action.PLAY_FREE_DISCARDED
else -> Action.WAIT
}
createPlayerTurnInfo(player, action, null, newTableState)
}
}
private fun createPlayerTurnInfo(player: Player, action: Action, hand: List<HandCard>?, newTableState: TableState) =
PlayerTurnInfo(
playerIndex = player.index,
table = newTableState,
action = action,
hand = hand,
preparedMove = preparedMoves[player.index]?.toPlayedMove(),
discardedCards = discardedCards.toHandCards(player, true).takeIf { action == Action.PLAY_FREE_DISCARDED },
neighbourGuildCards = table.getNeighbourGuildCards(player.index).toHandCards(player, true),
)
private fun startEndGameTurn() {
// some player may need to do additional stuff
startNewTurn()
val allDone = currentTurnInfo.all { it.action == Action.WAIT }
if (!allDone) {
return // we play the last turn like a normal one
}
val scoreBoard = computeScore()
currentTurnInfo = currentTurnInfo.map {
it.copy(action = Action.WATCH_SCORE, scoreBoard = scoreBoard)
}
}
/**
* Returns information for each player about the current turn.
*/
fun getCurrentTurnInfo(): List<PlayerTurnInfo> = currentTurnInfo
private fun determineAction(hand: List<HandCard>, board: Board): Action = when {
endOfGameReached() -> when {
board.hasSpecial(SpecialAbility.COPY_GUILD) && board.copiedGuild == null -> determineCopyGuildAction(board)
else -> Action.WAIT
}
hand.size == 1 && board.hasSpecial(SpecialAbility.PLAY_LAST_CARD) -> Action.PLAY_LAST
hand.size == 2 && board.hasSpecial(SpecialAbility.PLAY_LAST_CARD) -> Action.PLAY_2
hand.isEmpty() -> Action.WAIT
else -> Action.PLAY
}
private fun determineCopyGuildAction(board: Board): Action {
val neighbourGuildCards = table.getNeighbourGuildCards(board.playerIndex)
return if (neighbourGuildCards.isEmpty()) Action.WAIT else Action.PICK_NEIGHBOR_GUILD
}
/**
* Prepares the given [move] for the player at the given [playerIndex].
*
* @return the back of the card that is prepared on the table
*/
fun prepareMove(playerIndex: Int, move: PlayerMove): CardBack {
val card = move.findCard()
val context = PlayerContext(playerIndex, table, hands[playerIndex])
val resolvedMove = move.type.resolve(move, card, context, discardedCards)
preparedMoves[playerIndex] = resolvedMove
return card.back
}
private fun PlayerMove.findCard() = when (type) {
MoveType.PLAY_FREE_DISCARDED -> discardedCards.first { it.name == cardName }
else -> decks.getCard(table.currentAge, cardName)
}
fun unprepareMove(playerIndex: Int) {
preparedMoves.remove(playerIndex)
}
/**
* Returns true if all players that had to do something have [prepared their move][prepareMove]. This means we are
* ready to [play the current turn][playTurn].
*/
fun allPlayersPreparedTheirMove(): Boolean {
val nbExpectedMoves = currentTurnInfo.count { it.action !== Action.WAIT }
return preparedMoves.size == nbExpectedMoves
}
/**
* Plays all the [prepared moves][prepareMove] for the current turn.
*
* An exception will be thrown if some players had not prepared their moves (unless these players had nothing to
* do). To avoid this, please check if everyone is ready using [allPlayersPreparedTheirMove].
*/
fun playTurn() {
makeMoves()
if (shouldStartPlayDiscardedTurn()) {
startPlayDiscardedTurn()
} else if (endOfAgeReached()) {
executeEndOfAgeEvents()
if (endOfGameReached()) {
startEndGameTurn()
} else {
startNewAge()
}
} else {
rotateHandsIfRelevant()
startNewTurn()
}
}
private fun makeMoves() {
val moves = getMovesToPerform()
// all cards from this turn need to be placed before executing any effect
// because effects depending on played cards need to take the ones from the current turn into account too
placePreparedCards(moves)
// same goes for the discarded cards during the last turn, which should be available for special actions
if (hands.maxOneCardRemains()) {
discardLastCardsOfHands()
}
activatePlayedCards(moves)
table.lastPlayedMoves = moves
preparedMoves.clear()
}
private fun getMovesToPerform(): List<Move> =
currentTurnInfo.filter { it.action !== Action.WAIT }.map { getMoveToPerformFor(it.playerIndex) }
private fun getMoveToPerformFor(playerIndex: Int) =
preparedMoves[playerIndex] ?: throw MissingPreparedMoveException(playerIndex)
private fun endOfAgeReached(): Boolean = hands.isEmpty
private fun executeEndOfAgeEvents() {
// this is necessary because this method is actually called twice in the 3rd age if someone has CPY_GUILD
// TODO we should instead manage the game's state machine in a better way to avoid stuff like this
if (!militaryConflictsResolved) {
table.resolveMilitaryConflicts()
militaryConflictsResolved = true
}
}
fun endOfGameReached(): Boolean = endOfAgeReached() && table.currentAge == LAST_AGE
private fun shouldStartPlayDiscardedTurn(): Boolean {
val boardsWithPlayDiscardedAbility = table.boards.filter { it.hasSpecial(SpecialAbility.PLAY_DISCARDED) }
if (boardsWithPlayDiscardedAbility.isEmpty()) {
return false
}
if (discardedCards.isEmpty()) {
// it was wasted for this turn, no discarded card to play
boardsWithPlayDiscardedAbility.forEach { it.removeSpecial(SpecialAbility.PLAY_DISCARDED) }
return false
}
return true
}
private fun rotateHandsIfRelevant() {
// we don't rotate hands if some player can play his last card (with the special ability)
if (!hands.maxOneCardRemains()) {
hands = hands.rotate(table.handRotationDirection)
}
}
private fun placePreparedCards(playedMoves: List<Move>) {
playedMoves.forEach { move ->
move.place(discardedCards, settings)
hands = hands.remove(move.playerContext.index, move.card)
}
}
private fun discardLastCardsOfHands() =
table.boards.filterNot { it.hasSpecial(SpecialAbility.PLAY_LAST_CARD) }.forEach { discardHand(it.playerIndex) }
private fun discardHand(playerIndex: Int) {
val hand = hands[playerIndex]
discardedCards.addAll(hand)
hands = hands.clearHand(playerIndex)
}
private fun activatePlayedCards(playedMoves: List<Move>) =
playedMoves.forEach { it.activate(discardedCards, settings) }
/**
* Computes the score for all players.
*/
private fun computeScore(): ScoreBoard =
ScoreBoard(table.boards.map { it.computeScore(players[it.playerIndex]) }.sortedDescending())
private class MissingPreparedMoveException(playerIndex: Int) :
IllegalStateException("Player $playerIndex has not prepared his move")
}
| mit | e0222414c487cf61722d51ce93cc6a77 | 38.125 | 120 | 0.670514 | 4.47349 | false | false | false | false |
square/kotlinpoet | kotlinpoet/src/main/java/com/squareup/kotlinpoet/Util.kt | 1 | 9248 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.kotlinpoet
import com.squareup.kotlinpoet.CodeBlock.Companion.isPlaceholder
import java.util.Collections
internal object NullAppendable : Appendable {
override fun append(charSequence: CharSequence) = this
override fun append(charSequence: CharSequence, start: Int, end: Int) = this
override fun append(c: Char) = this
}
internal fun <K, V> Map<K, V>.toImmutableMap(): Map<K, V> =
Collections.unmodifiableMap(LinkedHashMap(this))
internal fun <T> Collection<T>.toImmutableList(): List<T> =
Collections.unmodifiableList(ArrayList(this))
internal fun <T> Collection<T>.toImmutableSet(): Set<T> =
Collections.unmodifiableSet(LinkedHashSet(this))
internal inline fun <reified T : Enum<T>> Collection<T>.toEnumSet(): Set<T> =
enumValues<T>().filterTo(mutableSetOf(), this::contains)
internal fun requireNoneOrOneOf(modifiers: Set<KModifier>, vararg mutuallyExclusive: KModifier) {
val count = mutuallyExclusive.count(modifiers::contains)
require(count <= 1) {
"modifiers $modifiers must contain none or only one of ${mutuallyExclusive.contentToString()}"
}
}
internal fun requireNoneOf(modifiers: Set<KModifier>, vararg forbidden: KModifier) {
require(forbidden.none(modifiers::contains)) {
"modifiers $modifiers must contain none of ${forbidden.contentToString()}"
}
}
internal fun <T> T.isOneOf(t1: T, t2: T, t3: T? = null, t4: T? = null, t5: T? = null, t6: T? = null) =
this == t1 || this == t2 || this == t3 || this == t4 || this == t5 || this == t6
internal fun <T> Collection<T>.containsAnyOf(vararg t: T) = t.any(this::contains)
// see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6
internal fun characterLiteralWithoutSingleQuotes(c: Char) = when {
c == '\b' -> "\\b" // \u0008: backspace (BS)
c == '\t' -> "\\t" // \u0009: horizontal tab (HT)
c == '\n' -> "\\n" // \u000a: linefeed (LF)
c == '\r' -> "\\r" // \u000d: carriage return (CR)
c == '\"' -> "\"" // \u0022: double quote (")
c == '\'' -> "\\'" // \u0027: single quote (')
c == '\\' -> "\\\\" // \u005c: backslash (\)
c.isIsoControl -> String.format("\\u%04x", c.code)
else -> c.toString()
}
internal fun escapeCharacterLiterals(s: String) = buildString {
for (c in s) append(characterLiteralWithoutSingleQuotes(c))
}
private val Char.isIsoControl: Boolean
get() {
return this in '\u0000'..'\u001F' || this in '\u007F'..'\u009F'
}
/** Returns the string literal representing `value`, including wrapping double quotes. */
internal fun stringLiteralWithQuotes(
value: String,
isInsideRawString: Boolean = false,
isConstantContext: Boolean = false,
): String {
if (!isConstantContext && '\n' in value) {
val result = StringBuilder(value.length + 32)
result.append("\"\"\"\n|")
var i = 0
while (i < value.length) {
val c = value[i]
if (value.regionMatches(i, "\"\"\"", 0, 3)) {
// Don't inadvertently end the raw string too early
result.append("\"\"\${'\"'}")
i += 2
} else if (c == '\n') {
// Add a '|' after newlines. This pipe will be removed by trimMargin().
result.append("\n|")
} else if (c == '$' && !isInsideRawString) {
// Escape '$' symbols with ${'$'}.
result.append("\${\'\$\'}")
} else {
result.append(c)
}
i++
}
// If the last-emitted character wasn't a margin '|', add a blank line. This will get removed
// by trimMargin().
if (!value.endsWith("\n")) result.append("\n")
result.append("\"\"\".trimMargin()")
return result.toString()
} else {
val result = StringBuilder(value.length + 32)
// using pre-formatted strings allows us to get away with not escaping symbols that would
// normally require escaping, e.g. "foo ${"bar"} baz"
if (isInsideRawString) result.append("\"\"\"") else result.append('"')
for (c in value) {
// Trivial case: single quote must not be escaped.
if (c == '\'') {
result.append("'")
continue
}
// Trivial case: double quotes must be escaped.
if (c == '\"' && !isInsideRawString) {
result.append("\\\"")
continue
}
// Trivial case: $ signs must be escaped.
if (c == '$' && !isInsideRawString) {
result.append("\${\'\$\'}")
continue
}
// Default case: just let character literal do its work.
result.append(if (isInsideRawString) c else characterLiteralWithoutSingleQuotes(c))
// Need to append indent after linefeed?
}
if (isInsideRawString) result.append("\"\"\"") else result.append('"')
return result.toString()
}
}
internal fun CodeBlock.ensureEndsWithNewLine() = if (isEmpty()) this else with(toBuilder()) {
val lastFormatPart = trim().formatParts.last()
if (lastFormatPart.isPlaceholder && args.isNotEmpty()) {
val lastArg = args.last()
if (lastArg is String) {
args[args.size - 1] = lastArg.trimEnd('\n') + '\n'
}
} else {
formatParts[formatParts.lastIndexOf(lastFormatPart)] = lastFormatPart.trimEnd('\n')
formatParts += "\n"
}
return@with build()
}
private val IDENTIFIER_REGEX =
(
"((\\p{gc=Lu}+|\\p{gc=Ll}+|\\p{gc=Lt}+|\\p{gc=Lm}+|\\p{gc=Lo}+|\\p{gc=Nl}+)+" +
"\\d*" +
"\\p{gc=Lu}*\\p{gc=Ll}*\\p{gc=Lt}*\\p{gc=Lm}*\\p{gc=Lo}*\\p{gc=Nl}*)" +
"|" +
"(`[^\n\r`]+`)"
)
.toRegex()
internal val String.isIdentifier get() = IDENTIFIER_REGEX.matches(this)
// https://kotlinlang.org/docs/reference/keyword-reference.html
private val KEYWORDS = setOf(
// Hard keywords
"as",
"break",
"class",
"continue",
"do",
"else",
"false",
"for",
"fun",
"if",
"in",
"interface",
"is",
"null",
"object",
"package",
"return",
"super",
"this",
"throw",
"true",
"try",
"typealias",
"typeof",
"val",
"var",
"when",
"while",
// Soft keywords
"by",
"catch",
"constructor",
"delegate",
"dynamic",
"field",
"file",
"finally",
"get",
"import",
"init",
"param",
"property",
"receiver",
"set",
"setparam",
"where",
// Modifier keywords
"actual",
"abstract",
"annotation",
"companion",
"const",
"crossinline",
"data",
"enum",
"expect",
"external",
"final",
"infix",
"inline",
"inner",
"internal",
"lateinit",
"noinline",
"open",
"operator",
"out",
"override",
"private",
"protected",
"public",
"reified",
"sealed",
"suspend",
"tailrec",
"value",
"vararg",
// These aren't keywords anymore but still break some code if unescaped. https://youtrack.jetbrains.com/issue/KT-52315
"header",
"impl",
// Other reserved keywords
"yield",
)
private const val ALLOWED_CHARACTER = '$'
private const val UNDERSCORE_CHARACTER = '_'
internal val String.isKeyword get() = this in KEYWORDS
internal val String.hasAllowedCharacters get() = this.any { it == ALLOWED_CHARACTER }
internal val String.allCharactersAreUnderscore get() = this.all { it == UNDERSCORE_CHARACTER }
// https://github.com/JetBrains/kotlin/blob/master/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/checkers/JvmSimpleNameBacktickChecker.kt
private val ILLEGAL_CHARACTERS_TO_ESCAPE = setOf('.', ';', '[', ']', '/', '<', '>', ':', '\\')
private fun String.failIfEscapeInvalid() {
require(!any { it in ILLEGAL_CHARACTERS_TO_ESCAPE }) {
"Can't escape identifier $this because it contains illegal characters: " +
ILLEGAL_CHARACTERS_TO_ESCAPE.intersect(this.toSet()).joinToString("")
}
}
internal fun String.escapeIfNecessary(validate: Boolean = true): String = escapeIfNotJavaIdentifier()
.escapeIfKeyword()
.escapeIfHasAllowedCharacters()
.escapeIfAllCharactersAreUnderscore()
.apply { if (validate) failIfEscapeInvalid() }
private fun String.alreadyEscaped() = startsWith("`") && endsWith("`")
private fun String.escapeIfKeyword() = if (isKeyword && !alreadyEscaped()) "`$this`" else this
private fun String.escapeIfHasAllowedCharacters() = if (hasAllowedCharacters && !alreadyEscaped()) "`$this`" else this
private fun String.escapeIfAllCharactersAreUnderscore() = if (allCharactersAreUnderscore && !alreadyEscaped()) "`$this`" else this
private fun String.escapeIfNotJavaIdentifier(): String {
return if ((
!Character.isJavaIdentifierStart(first()) ||
drop(1).any { !Character.isJavaIdentifierPart(it) }
) &&
!alreadyEscaped()
) {
"`$this`".replace(' ', '·')
} else {
this
}
}
internal fun String.escapeSegmentsIfNecessary(delimiter: Char = '.') = split(delimiter)
.filter { it.isNotEmpty() }
.joinToString(delimiter.toString()) { it.escapeIfNecessary() }
| apache-2.0 | c6724b14140a841532f38a2b768e20bc | 29.120521 | 151 | 0.63599 | 3.617762 | false | false | false | false |
ohmae/CdsExtractor | src/main/java/net/mm2d/cdsextractor/MainWindow.kt | 1 | 9142 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.cdsextractor
import io.reactivex.schedulers.Schedulers
import net.mm2d.android.upnp.AvControlPointManager
import net.mm2d.android.upnp.cds.MediaServer
import net.mm2d.android.upnp.cds.MsControlPoint
import net.mm2d.android.upnp.cds.MsControlPoint.MsDiscoveryListener
import net.mm2d.log.Logger
import net.mm2d.log.Senders
import java.awt.BorderLayout
import java.awt.Color
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.swing.*
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreeSelectionModel
/**
* @author [大前良介(OHMAE Ryosuke)](mailto:[email protected])
*/
class MainWindow private constructor() : JFrame() {
private var currentDirectory: File? = null
private lateinit var tree: JTree
private lateinit var textField: JTextField
private lateinit var button: JButton
private lateinit var rootNode: DefaultMutableTreeNode
private lateinit var controlPointManager: AvControlPointManager
private lateinit var msControlPoint: MsControlPoint
private var loading: Boolean = false
private var cancel: Boolean = false
private val zipEntrySet = HashSet<String>()
private val executor: ExecutorService = Executors.newCachedThreadPool()
private val selectedServer: MediaServer?
get() = (tree.lastSelectedPathComponent as? DefaultMutableTreeNode)?.userObject as? MediaServer
init {
title = "CDS Extractor"
setSize(300, 500)
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
setUpUi()
isVisible = true
setUpControlPoint()
}
private fun setUpUi() {
rootNode = DefaultMutableTreeNode("Device")
tree = JTree(rootNode, true)
tree.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
val scrollPane = JScrollPane(tree)
contentPane.add(scrollPane, BorderLayout.CENTER)
tree.addTreeSelectionListener {
val server = selectedServer
button.isEnabled = server != null
textField.text = server?.friendlyName ?: ""
}
textField = JTextField()
textField.horizontalAlignment = JTextField.CENTER
textField.background = Color.WHITE
contentPane.add(textField, BorderLayout.SOUTH)
button = JButton("保存")
button.isEnabled = false
button.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
contentPane.add(button, BorderLayout.NORTH)
}
private fun setUpControlPoint() {
controlPointManager = AvControlPointManager()
msControlPoint = controlPointManager.msControlPoint
msControlPoint.setMsDiscoveryListener(object : MsDiscoveryListener {
override fun onDiscover(server: MediaServer) {
updateTree()
}
override fun onLost(server: MediaServer) {
updateTree()
}
private fun updateTree() {
rootNode.removeAllChildren()
for (server in msControlPoint.deviceList) {
rootNode.add(DefaultMutableTreeNode(server).also { it.allowsChildren = false })
}
(tree.model as DefaultTreeModel).reload()
}
})
controlPointManager.initialize(emptyList())
controlPointManager.start()
executor.execute {
while (!executor.isShutdown) {
controlPointManager.search()
Thread.sleep(3000)
}
}
addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
executor.shutdown()
controlPointManager.stop()
controlPointManager.terminate()
}
})
}
private fun onClick() {
if (loading) {
cancel = true
return
}
val server = selectedServer ?: return
currentDirectory = selectSaveDirectory(server.friendlyName)
if (currentDirectory == null) {
return
}
cancel = false
loading = true
button.text = "キャンセル"
textField.background = Color.YELLOW
tree.isEnabled = false
executor.execute {
zipEntrySet.clear()
val fineName = File(currentDirectory, toFileNameString(server.friendlyName) + ".zip")
ZipOutputStream(FileOutputStream(fineName)).use { zos ->
saveDescription(zos, server)
dumpAllDir(zos, server)
}
zipEntrySet.clear()
textField.background = Color.WHITE
textField.text = "完了"
button.text = "保存"
tree.isEnabled = true
loading = false
}
}
private fun selectSaveDirectory(title: String): File? {
val chooser = JFileChooser(currentDirectory).also {
it.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
it.dialogTitle = "「$title」の保存先フォルダを選択"
}
val selected = chooser.showSaveDialog(this)
return if (selected == JFileChooser.APPROVE_OPTION) chooser.selectedFile else null
}
private fun saveDescription(
zos: ZipOutputStream,
server: MediaServer
) {
val device = server.device
val base = toFileNameString(server.friendlyName) + "/description"
writeZipEntry(zos, makePath(base, device.friendlyName), device.description)
for (service in device.serviceList) {
writeZipEntry(zos, makePath(base, service.serviceId), service.description)
}
}
@Throws(IOException::class)
private fun makePath(
base: String,
name: String?
): String = makeUniquePath(base + "/" + toFileNameString(name!!), ".xml")
@Throws(IOException::class)
private fun makePath(
base: String,
name: String?,
suffix: String
): String = makeUniquePath(base + "/" + toFileNameString(name!!), "$suffix.xml")
@Throws(IOException::class)
private fun makeUniquePath(
body: String,
suffix: String
): String {
val defaultPath = body + suffix
if (zipEntrySet.add(defaultPath)) {
return defaultPath
}
for (i in 0 until Integer.MAX_VALUE) {
val path = "$body$$$i$suffix"
if (zipEntrySet.add(path)) {
return path
}
}
throw IOException()
}
@Throws(IOException::class)
private fun writeZipEntry(
zos: ZipOutputStream,
path: String,
data: String
) {
kotlin.runCatching {
zos.putNextEntry(ZipEntry(path))
zos.write(data.toByteArray(StandardCharsets.UTF_8))
zos.closeEntry()
}
}
private fun toFileNameString(name: String): String {
return name.replace("[\\\\/:*?\"<>|]".toRegex(), "_")
}
private fun dumpAllDir(
zos: ZipOutputStream,
server: MediaServer
) {
val base = toFileNameString(server.friendlyName) + "/cds"
val idList = LinkedList<String>()
var count = 1
idList.addFirst("0")
while (!cancel) {
val id = idList.pollFirst() ?: return
server.browse(id)
.subscribeOn(Schedulers.trampoline())
.subscribe({ result ->
result.list.forEach {
if (it.isContainer) {
idList.addLast(it.objectId)
count++
}
}
textField.text = (count - idList.size).toString() + "/" + count
val start = result.start
val end = start + result.number - 1
if (start == 0 && result.number == result.total) {
writeZipEntry(zos, makePath(base, id), result.description)
} else {
writeZipEntry(zos, makePath(base, id, "(${start}-${end})"), result.description)
}
}, {})
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
Logger.setLogLevel(Logger.VERBOSE)
Logger.setSender(Senders.create())
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
MainWindow()
}
}
}
| mit | 67e5935ba0b7bb80f023a53e8d2ecbfc | 33.12782 | 103 | 0.604759 | 4.899083 | false | false | false | false |
usommerl/kotlin-koans | src/ii_collections/_22_Fold_.kt | 2 | 603 | package ii_collections
fun example9() {
val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult })
result == 24
}
// The same as
fun whatFoldDoes(): Int {
var result = 1
listOf(1, 2, 3, 4).forEach { element -> result = element * result}
return result
}
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
// Return the set of products ordered by every customer
return customers.fold(allOrderedProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})
}
| mit | 35458ab25fd9333e175327039996a124 | 27.714286 | 92 | 0.666667 | 3.915584 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/exoplayer/HandlerDispatchingExoPlayer.kt | 1 | 17461 | package com.lasthopesoftware.bluewater.client.playback.exoplayer
import android.os.Handler
import android.os.Looper
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ShuffleOrder
import com.google.android.exoplayer2.source.TrackGroupArray
import com.google.android.exoplayer2.trackselection.TrackSelectionArray
import com.google.android.exoplayer2.trackselection.TrackSelector
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.queued.MessageWriter
class HandlerDispatchingExoPlayer(private val innerPlayer: ExoPlayer, private val handler: Handler) : PromisingExoPlayer {
override fun getAudioComponent(): Promise<ExoPlayer.AudioComponent?> =
LoopedInPromise(
MessageWriter { innerPlayer.audioComponent },
handler)
override fun getVideoComponent(): Promise<ExoPlayer.VideoComponent?> =
LoopedInPromise(
MessageWriter { innerPlayer.videoComponent },
handler)
override fun getTextComponent(): Promise<ExoPlayer.TextComponent?> =
LoopedInPromise(
MessageWriter { innerPlayer.textComponent },
handler)
override fun getMetadataComponent(): Promise<ExoPlayer.MetadataComponent?> =
LoopedInPromise(
MessageWriter { innerPlayer.metadataComponent },
handler)
override fun getDeviceComponent(): Promise<ExoPlayer.DeviceComponent?> =
LoopedInPromise(
MessageWriter { innerPlayer.deviceComponent },
handler)
override fun getApplicationLooper(): Promise<Looper> =
LoopedInPromise(
MessageWriter { innerPlayer.applicationLooper },
handler)
override fun addListener(listener: Player.Listener): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addListener(listener)
this
},
handler)
override fun removeListener(listener: Player.Listener): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.removeListener(listener)
this
},
handler)
override fun setMediaItems(mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItems(mediaItems)
this
},
handler)
override fun setMediaItems(mediaItems: MutableList<MediaItem>, resetPosition: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItems(mediaItems, resetPosition)
this
},
handler)
override fun setMediaItems(mediaItems: MutableList<MediaItem>, startWindowIndex: Int, startPositionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItems(mediaItems, startWindowIndex, startPositionMs)
this
},
handler)
override fun setMediaItem(mediaItem: MediaItem): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItem(mediaItem)
this
},
handler)
override fun setMediaItem(mediaItem: MediaItem, startPositionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItem(mediaItem, startPositionMs)
this
},
handler)
override fun setMediaItem(mediaItem: MediaItem, resetPosition: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaItem(mediaItem, resetPosition)
this
},
handler)
override fun addMediaItem(mediaItem: MediaItem): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaItem(mediaItem)
this
},
handler)
override fun addMediaItem(index: Int, mediaItem: MediaItem): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaItem(index, mediaItem)
this
},
handler)
override fun addMediaItems(mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaItems(mediaItems)
this
},
handler)
override fun addMediaItems(index: Int, mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaItems(index, mediaItems)
this
},
handler)
override fun moveMediaItem(currentIndex: Int, newIndex: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.moveMediaItem(currentIndex, newIndex)
this
},
handler)
override fun moveMediaItems(fromIndex: Int, toIndex: Int, newIndex: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.moveMediaItems(fromIndex, toIndex, newIndex)
this
},
handler)
override fun removeMediaItem(index: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.removeMediaItem(index)
this
},
handler)
override fun removeMediaItems(fromIndex: Int, toIndex: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.removeMediaItems(fromIndex, toIndex)
this
},
handler)
override fun clearMediaItems(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.clearMediaItems()
this
},
handler)
override fun prepare(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.prepare()
this
},
handler)
override fun getPlaybackState(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.playbackState },
handler)
override fun getPlaybackSuppressionReason(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.playbackSuppressionReason },
handler)
override fun isPlaying(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isPlaying },
handler)
override fun getPlayerError(): Promise<ExoPlaybackException?> =
LoopedInPromise(
MessageWriter { innerPlayer.playerError },
handler)
override fun play(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.play()
this
},
handler)
override fun pause(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.pause()
this
},
handler)
override fun setPlayWhenReady(playWhenReady: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.playWhenReady = playWhenReady
this
},
handler)
override fun getPlayWhenReady(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.playWhenReady },
handler)
override fun setRepeatMode(repeatMode: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.repeatMode = repeatMode
this
},
handler)
override fun getRepeatMode(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.repeatMode },
handler)
override fun setShuffleModeEnabled(shuffleModeEnabled: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.shuffleModeEnabled = shuffleModeEnabled
this
},
handler)
override fun getShuffleModeEnabled(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.shuffleModeEnabled },
handler)
override fun isLoading(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isLoading },
handler)
override fun seekToDefaultPosition(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekToDefaultPosition()
this
},
handler)
override fun seekToDefaultPosition(windowIndex: Int): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekToDefaultPosition(windowIndex)
this
},
handler)
override fun seekTo(positionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekTo(positionMs)
this
},
handler)
override fun seekTo(windowIndex: Int, positionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekTo(windowIndex, positionMs)
this
},
handler)
override fun hasPreviousWindow(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.hasPreviousWindow() },
handler)
override fun seekToPreviousWindow(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekToPreviousWindow()
this
},
handler)
override fun hasNextWindow(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.hasNextWindow() },
handler)
override fun seekToNextWindow(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.seekToNextWindow()
this
},
handler)
override fun setPlaybackParameters(playbackParameters: PlaybackParameters): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.playbackParameters = playbackParameters
this
},
handler)
override fun getPlaybackParameters(): Promise<PlaybackParameters> =
LoopedInPromise(
MessageWriter { innerPlayer.playbackParameters },
handler)
override fun stop(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.stop()
this
},
handler)
override fun release(): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.release()
this
},
handler)
override fun getRendererCount(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.rendererCount },
handler)
override fun getRendererType(index: Int): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.getRendererType(index) },
handler)
override fun getTrackSelector(): Promise<TrackSelector?> =
LoopedInPromise(
MessageWriter { innerPlayer.trackSelector },
handler)
override fun getCurrentTrackGroups(): Promise<TrackGroupArray> =
LoopedInPromise(
MessageWriter { innerPlayer.currentTrackGroups },
handler)
override fun getCurrentTrackSelections(): Promise<TrackSelectionArray> =
LoopedInPromise(
MessageWriter { innerPlayer.currentTrackSelections },
handler)
override fun getCurrentManifest(): Promise<Any?> =
LoopedInPromise(
MessageWriter { innerPlayer.currentManifest },
handler)
override fun getCurrentTimeline(): Promise<Timeline> =
LoopedInPromise(
MessageWriter { innerPlayer.currentTimeline },
handler)
override fun getCurrentPeriodIndex(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.currentPeriodIndex },
handler)
override fun getCurrentWindowIndex(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.currentWindowIndex },
handler)
override fun getNextWindowIndex(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.nextWindowIndex },
handler)
override fun getPreviousWindowIndex(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.previousWindowIndex },
handler)
override fun getCurrentMediaItem(): Promise<MediaItem?> =
LoopedInPromise(
MessageWriter { innerPlayer.currentMediaItem },
handler)
override fun getMediaItemCount(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.mediaItemCount },
handler)
override fun getMediaItemAt(index: Int): Promise<MediaItem> =
LoopedInPromise(
MessageWriter { innerPlayer.getMediaItemAt(index) },
handler)
override fun getDuration(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.duration },
handler)
override fun getCurrentPosition(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.currentPosition },
handler)
override fun getBufferedPosition(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.bufferedPosition },
handler)
override fun getBufferedPercentage(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.bufferedPercentage },
handler)
override fun getTotalBufferedDuration(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.totalBufferedDuration },
handler)
override fun isCurrentWindowDynamic(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isCurrentWindowDynamic },
handler)
override fun isCurrentWindowLive(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isCurrentWindowLive },
handler)
override fun getCurrentLiveOffset(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.currentLiveOffset },
handler)
override fun isCurrentWindowSeekable(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isCurrentWindowSeekable },
handler)
override fun isPlayingAd(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.isPlayingAd },
handler)
override fun getCurrentAdGroupIndex(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.currentAdGroupIndex },
handler)
override fun getCurrentAdIndexInAdGroup(): Promise<Int> =
LoopedInPromise(
MessageWriter { innerPlayer.currentAdIndexInAdGroup },
handler)
override fun getContentDuration(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.contentDuration },
handler)
override fun getContentPosition(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.contentPosition },
handler)
override fun getContentBufferedPosition(): Promise<Long> =
LoopedInPromise(
MessageWriter { innerPlayer.contentBufferedPosition },
handler)
override fun getPlaybackLooper(): Promise<Looper> =
LoopedInPromise(
MessageWriter { innerPlayer.playbackLooper },
handler)
override fun setMediaSources(mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSources(mediaSources)
this
},
handler)
override fun setMediaSources(mediaSources: MutableList<MediaSource>, resetPosition: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSources(mediaSources, resetPosition)
this
},
handler)
override fun setMediaSources(mediaSources: MutableList<MediaSource>, startWindowIndex: Int, startPositionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSources(mediaSources, startWindowIndex, startPositionMs)
this
},
handler)
override fun setMediaSource(mediaSource: MediaSource): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSource(mediaSource)
this
},
handler)
override fun setMediaSource(mediaSource: MediaSource, startPositionMs: Long): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSource(mediaSource, startPositionMs)
this
},
handler)
override fun setMediaSource(mediaSource: MediaSource, resetPosition: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setMediaSource(mediaSource, resetPosition)
this
},
handler)
override fun addMediaSource(mediaSource: MediaSource): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaSource(mediaSource)
this
},
handler)
override fun addMediaSource(index: Int, mediaSource: MediaSource): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaSource(index, mediaSource)
this
},
handler)
override fun addMediaSources(mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaSources(mediaSources)
this
},
handler)
override fun addMediaSources(index: Int, mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.addMediaSources(index, mediaSources)
this
},
handler)
override fun setShuffleOrder(shuffleOrder: ShuffleOrder): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setShuffleOrder(shuffleOrder)
this
},
handler)
override fun createMessage(target: PlayerMessage.Target): Promise<PlayerMessage> =
LoopedInPromise(
MessageWriter { innerPlayer.createMessage(target) },
handler)
override fun setSeekParameters(seekParameters: SeekParameters?): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setSeekParameters(seekParameters)
this
},
handler)
override fun getSeekParameters(): Promise<SeekParameters> =
LoopedInPromise(
MessageWriter { innerPlayer.seekParameters },
handler)
override fun setForegroundMode(foregroundMode: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.setForegroundMode(foregroundMode)
this
},
handler)
override fun setPauseAtEndOfMediaItems(pauseAtEndOfMediaItems: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems
this
},
handler)
override fun getPauseAtEndOfMediaItems(): Promise<Boolean> =
LoopedInPromise(
MessageWriter { innerPlayer.pauseAtEndOfMediaItems },
handler)
override fun experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled: Boolean): Promise<PromisingExoPlayer> =
LoopedInPromise(
MessageWriter {
innerPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled)
this
},
handler)
}
| lgpl-3.0 | 9e1ada18d37973f5b9dd6d83632b5f26 | 26.197819 | 146 | 0.758949 | 4.31562 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/network/gson/GsonNull.kt | 1 | 2221 | package mil.nga.giat.mage.network.gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
fun JsonReader.nextStringOrNull(): String? {
return if (peek() == JsonToken.NULL) {
nextNull()
null
} else {
nextString()
}
}
fun JsonReader.nextLongOrNull(): Long? {
return if (peek() == JsonToken.NULL) {
nextNull()
null
} else {
nextLong()
}
}
fun JsonReader.nextDoubleOrNull(): Double? {
return if (peek() == JsonToken.NULL) {
nextNull()
null
} else {
nextDouble()
}
}
fun JsonReader.nextBooleanOrNull(): Boolean? {
return if (peek() == JsonToken.NULL) {
nextNull()
null
} else {
nextBoolean()
}
}
fun JsonReader.nextNumberOrNull(): Number? {
return if (peek() == JsonToken.NULL) {
nextNull()
null
} else {
val value = nextString()
try {
value.toLong()
} catch (e: NumberFormatException) {
try {
val asDouble = value.toDouble()
if ((asDouble.isInfinite() || asDouble.isNaN()) && !isLenient) {
null
} else asDouble
} catch(e: NumberFormatException) {
null
}
}
}
}
fun JsonElement.asJsonObjectOrNull(): JsonObject? {
return if (isJsonObject) asJsonObject else null
}
fun JsonElement.asStringOrNull(): String? {
return if (isJsonNull) null else asString
}
fun JsonElement.asIntOrNull(): Int? {
return if (isJsonNull) null else {
if (asJsonPrimitive.isNumber) asInt else null
}
}
fun JsonElement.asLongOrNull(): Long? {
return if (isJsonNull) null else {
if (asJsonPrimitive.isNumber) asLong else null
}
}
fun JsonElement.asDoubleOrNull(): Double? {
return if (isJsonNull) null else {
if (asJsonPrimitive.isNumber) asDouble else null
}
}
fun JsonElement.asFloatOrNull(): Float? {
return if (isJsonNull) null else {
if (asJsonPrimitive.isNumber) asFloat else null
}
}
fun JsonElement.asBooleanOrNull(): Boolean? {
return if (isJsonNull) null else {
if (asJsonPrimitive.isBoolean) asBoolean else null
}
} | apache-2.0 | a00ea39ab35f7c2f76dd9b1bff73f3ce | 21 | 76 | 0.627195 | 4.120594 | false | false | false | false |
tgirard12/kotlin-talk | talk/src/main/kotlin/com/tgirard12/kotlintalk/09_Object.kt | 1 | 842 | package com.tgirard12.kotlintalk
import android.view.View
// Object expression : Beter anonymous inner classes
object Singleton {
val name = "Singleton"
}
// Singleton depuis une interface ou une class
object Singleton2 : View.OnClickListener {
override fun onClick(v: View?) {
println("View.onClick")
}
}
open class Part1(val code: String)
interface Part2
fun main(args: Array<String>) {
println(Singleton.name)
// Singleton 2
println(Singleton2.onClick(null))
// Part1 et part 2
// Create just un object to encapsule some results
// Same synthax for the inner classes
val obj = object : Part1("o"), Part2 {
val second = "s"
}
println(obj.javaClass)
val gps = object {
val lat = 10.3
val long = 5.7
}
println("${gps.lat}, ${gps.long}")
} | apache-2.0 | 72474793ebc0782f3cac971783861d9b | 18.604651 | 54 | 0.64133 | 3.66087 | false | false | false | false |
JackParisi/DroidBox | droidbox/src/main/java/com/github/giacomoparisi/droidbox/utility/DroidDateUtils.kt | 1 | 1814 | package com.github.giacomoparisi.droidbox.utility
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Giacomo Parisi on 08/02/18.
* https://github.com/giacomoParisi
*/
fun formatDateString(date: String? = null,
placeholder: String? = null,
errorPlaceholder: String? = null,
originalFormat: String? = null,
targetFormat: String? = null,
originalLocale: Locale? = null,
targetLocale: Locale? = null): String? {
if (!originalFormat.isNullOrEmpty() && !targetFormat.isNullOrEmpty() && !date.isNullOrEmpty()) {
try {
val originalDateFormat = SimpleDateFormat(
originalFormat,
originalLocale ?: Locale.getDefault())
val targetDateFormat = SimpleDateFormat(
targetFormat,
targetLocale ?: Locale.getDefault())
val originalDate = originalDateFormat.parse(date)
return targetDateFormat.format(originalDate)
} catch (error: ParseException) {
return if (!placeholder.isNullOrEmpty()) {
errorPlaceholder
} else if (!date.isNullOrEmpty()) {
date
} else {
""
}
}
} else if (!placeholder.isNullOrEmpty()) {
return placeholder
} else if (!date.isNullOrEmpty()) {
return date
} else {
return ""
}
}
fun toDate(date: String, format: String, locale: Locale? = null): Date? {
val dateFormat = SimpleDateFormat(format, locale ?: Locale.getDefault())
return try {
dateFormat.parse(date)
} catch (e: ParseException) {
null
}
}
| apache-2.0 | 7603f58d9248e86d5423854a5a3957c6 | 30.275862 | 100 | 0.560088 | 5.081232 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/spotify/SpotifyAuthInterceptor.kt | 1 | 4062 | package com.baulsupp.okurl.services.spotify
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.moshi
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.queryMapValue
import com.baulsupp.okurl.secrets.Secrets
import com.baulsupp.okurl.services.spotify.model.ErrorResponse
import com.baulsupp.okurl.util.ClientException
import okhttp3.Credentials
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class SpotifyAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition = Oauth2ServiceDefinition(
"api.spotify.com", "Spotify API", "spotify",
"https://developer.spotify.com/web-api/endpoint-reference/",
"https://developer.spotify.com/my-applications/"
)
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val clientId = Secrets.prompt("Spotify Client Id", "spotify.clientId", "", false)
val clientSecret = Secrets.prompt("Spotify Client Secret", "spotify.clientSecret", "", true)
val scopes = Secrets.promptArray(
"Scopes", "spotify.scopes",
listOf(
"playlist-read-private",
"playlist-read-collaborative",
"playlist-modify-public",
"playlist-modify-private",
"streaming",
"ugc-image-upload",
"user-follow-modify",
"user-follow-read",
"user-library-read",
"user-library-modify",
"user-read-private",
"user-read-birthdate",
"user-read-email",
"user-top-read"
)
)
return SpotifyAuthFlow.login(client, outputHandler, clientId, clientSecret, scopes)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
return BaseUrlCompleter(UrlList.fromResource(name())!!, hosts(credentialsStore), completionVariableCache)
}
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials {
return ValidatedCredentials(
client.queryMapValue<String>(
"https://api.spotify.com/v1/me",
TokenValue(credentials), "display_name"
)
)
}
override fun errorMessage(ce: ClientException): String {
if (ce.code == 401) {
try {
val message = ce.responseMessage
return moshi.adapter(ErrorResponse::class.java).fromJson(message)!!.error.message
} catch (e: Exception) {
// ignore
}
}
return super.errorMessage(ce)
}
override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? {
val tokenUrl = "https://accounts.spotify.com/api/token"
val body = FormBody.Builder()
.add("refresh_token", credentials.refreshToken!!)
.add("grant_type", "refresh_token")
.build()
val request = Request.Builder().header(
"Authorization",
Credentials.basic(credentials.clientId!!, credentials.clientSecret!!)
)
.url(tokenUrl)
.method("POST", body)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
responseMap["refresh_token"] as String?, credentials.clientId,
credentials.clientSecret
)
}
}
| apache-2.0 | c88f2376bd27414d27cb1691c386e56c | 31.238095 | 109 | 0.718858 | 4.386609 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/tileentity/TileEntity.kt | 2 | 4259 | package com.cout970.magneticraft.misc.tileentity
import com.cout970.magneticraft.api.energy.IElectricNode
import com.cout970.magneticraft.api.energy.IElectricNodeHandler
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.api.heat.IHeatNodeHandler
import com.cout970.magneticraft.api.internal.energy.ElectricConnection
import com.cout970.magneticraft.api.internal.heat.HeatConnection
import com.cout970.magneticraft.registry.fromTile
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import com.cout970.magneticraft.systems.tileentities.TileBase
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
import net.minecraftforge.common.capabilities.Capability
/**
* Created by cout970 on 2017/02/20.
*/
fun World.shouldTick(pos: BlockPos, time: Int): Boolean {
return (totalWorldTime + pos.hashCode()) % time == 0L
}
fun IModuleContainer.shouldTick(ticks: Int): Boolean {
return (world.totalWorldTime + pos.hashCode()) % ticks == 0L
}
inline fun <reified T : TileEntity> World.getTile(pos: BlockPos): T? {
val tile = getTileEntity(pos)
return tile as? T
}
fun <T> IBlockAccess.getCap(cap: Capability<T>?, pos: BlockPos, side: EnumFacing?): T? {
val tile = getTileEntity(pos) ?: return null
return cap?.fromTile(tile, side)
}
inline fun <reified T> TileBase.getModule(): T? = container.modules.find { it is T } as? T
inline fun <reified T> IBlockAccess.getModule(pos: BlockPos): T? {
val tile = getTile<TileBase>(pos)
return tile?.getModule<T>()
}
inline fun <reified T : TileEntity> IBlockAccess.getTile(pos: BlockPos): T? {
val tile = getTileEntity(pos)
return tile as? T
}
operator fun Pair<BlockPos, BlockPos>.contains(pos: BlockPos): Boolean {
return pos.x >= first.x && pos.x <= second.x &&
pos.y >= first.y && pos.y <= second.y &&
pos.z >= first.z && pos.z <= second.z
}
@Suppress("LoopToCallChain")
fun World.getTileEntitiesIn(start: BlockPos, end: BlockPos,
filter: (TileEntity) -> Boolean = { true }): List<TileEntity> {
val list = mutableListOf<TileEntity>()
for (x in start.x..end.x step 16) {
for (z in start.z..end.z step 16) {
val chunk = getChunkFromChunkCoords(x shr 4, z shr 4)
for ((pos, tile) in chunk.tileEntityMap) {
if (!tile.isInvalid && pos in (start to end) && filter.invoke(tile)) {
list.add(tile)
}
}
}
}
return list
}
fun tryConnect(thisHandler: IElectricNodeHandler, thisNode: IElectricNode,
otherHandler: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean {
if (canConnect(thisHandler, thisNode, otherHandler, otherNode, side)) {
val connection = ElectricConnection(thisNode, otherNode)
thisHandler.addConnection(connection, side, true)
otherHandler.addConnection(connection, side?.opposite, false)
return true
}
return false
}
fun canConnect(thisHandler: IElectricNodeHandler, thisNode: IElectricNode,
otherHandler: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean {
return thisHandler.canConnect(thisNode, otherHandler, otherNode, side) &&
otherHandler.canConnect(otherNode, thisHandler, thisNode, side?.opposite)
}
fun tryConnect(thisHandler: IHeatNodeHandler, thisNode: IHeatNode,
otherHandler: IHeatNodeHandler, otherNode: IHeatNode, side: EnumFacing) {
if (canConnect(thisHandler, thisNode, otherHandler, otherNode, side)) {
val connection = HeatConnection(thisNode, otherNode)
thisHandler.addConnection(connection, side, true)
otherHandler.addConnection(connection, side.opposite, false)
}
}
fun canConnect(thisHandler: IHeatNodeHandler, thisNode: IHeatNode,
otherHandler: IHeatNodeHandler, otherNode: IHeatNode, side: EnumFacing): Boolean {
return thisHandler.canConnect(thisNode, otherHandler, otherNode, side) &&
otherHandler.canConnect(otherNode, thisHandler, thisNode, side.opposite)
} | gpl-2.0 | 4656e128fbff4af30abec8005ba22f87 | 36.368421 | 106 | 0.710495 | 3.918123 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/icons/patchers/IconPathPatchers.kt | 1 | 2073 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.icons.patchers
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.XCollection
import com.thoughtworks.xstream.annotations.XStreamAlias
import java.util.Collections
/** Icon path patchers. */
@XStreamAlias("iconPathPatchers")
class IconPathPatchers {
/** File Icon Patchers. */
@Property
@XCollection
@XStreamAlias("filePatchers")
val filePatchers: Set<FileIconsPatcher> = emptySet()
get() = Collections.unmodifiableSet(field)
/** Glyph Icon Patchers. */
@Property
@XCollection
@XStreamAlias("glyphPatchers")
val glyphPatchers: Set<GlyphIconsPatcher> = emptySet()
get() = Collections.unmodifiableSet(field)
/** UI Icon Patchers. */
@Property
@XCollection
@XStreamAlias("iconPatchers")
val iconPatchers: Set<UIIconsPatcher> = emptySet()
get() = Collections.unmodifiableSet(field)
}
| mit | 6511f501c52f14e21c262f218bb142d6 | 36.017857 | 82 | 0.748673 | 4.162651 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/icons/svgpatchers/BigIconsPatcher.kt | 1 | 3756 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.icons.svgpatchers
import com.intellij.util.io.DigestUtil
import com.mallowigi.config.AtomFileIconsConfig
import org.w3c.dom.Element
import java.nio.charset.StandardCharsets
import javax.swing.UIManager
/** Big icons patcher. */
class BigIconsPatcher : SvgPatcher {
private var customIconSize = REGULAR
private var customLineHeight = REGULAR
private var defaultRowHeight = UIManager.getInt(ROW_HEIGHT)
private var hasCustomLineHeight = false
private var hasCustomSize = false
override fun digest(): ByteArray? {
val hasher = DigestUtil.sha512()
hasher.update(hasCustomSize.toString().toByteArray(StandardCharsets.UTF_8))
hasher.update(hasCustomLineHeight.toString().toByteArray(StandardCharsets.UTF_8))
hasher.update(customIconSize.toString().toByteArray(StandardCharsets.UTF_8))
hasher.update(customLineHeight.toString().toByteArray(StandardCharsets.UTF_8))
return hasher.digest()
}
override fun patch(svg: Element, path: String?): Unit = patchSizes(svg)
override fun priority(): Int = 97
override fun refresh(): Unit = refreshSizes()
private fun patchSizes(svg: Element) {
val isBig = svg.getAttribute(SvgPatcher.BIG)
val customFontSize = AtomFileIconsConfig.instance.customIconSize.toString()
val hasCustomSize = AtomFileIconsConfig.instance.hasCustomIconSize
val size = if (hasCustomSize) customFontSize else REGULAR
if (isBig == SvgPatcher.TRUE) {
svg.setAttribute(SvgPatcher.WIDTH, size.toString())
svg.setAttribute(SvgPatcher.HEIGHT, size.toString())
}
}
private fun refreshSizes() {
hasCustomSize = AtomFileIconsConfig.instance.hasCustomIconSize
hasCustomLineHeight = AtomFileIconsConfig.instance.hasCustomLineHeight
customIconSize = AtomFileIconsConfig.instance.customIconSize
customLineHeight = AtomFileIconsConfig.instance.customLineHeight
updateRowHeight()
}
private fun updateRowHeight() {
val extraHeight = if (hasCustomSize) defaultRowHeight + customIconSize - MIN_SIZE else defaultRowHeight
val customRowHeight = if (hasCustomLineHeight) customLineHeight else extraHeight
val materialHeight = UIManager.getInt(MATERIAL_ROW_HEIGHT)
if (materialHeight != 0) {
UIManager.put(ROW_HEIGHT, materialHeight)
} else {
UIManager.put(ROW_HEIGHT, customRowHeight)
}
}
companion object {
private const val MIN_SIZE = 12
private const val REGULAR = 16
private const val ROW_HEIGHT = "Tree.rowHeight"
private const val MATERIAL_ROW_HEIGHT = "Tree.materialRowHeight"
}
}
| mit | d3c50c787ad0438d6219d31af081c4f4 | 38.125 | 107 | 0.755325 | 4.466112 | false | true | false | false |
astromme/classify-handwritten-characters | android/app/src/main/java/com/dokibo/characterclassification/MainActivity.kt | 1 | 5812 | package com.dokibo.characterclassification
import android.graphics.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.dokibo.characterclassification.databinding.ActivityMainBinding
import com.dokibo.characterclassification.ml.TrainedModel
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.io.InputStream
import java.lang.Exception
import java.lang.Float.min
import java.nio.ByteBuffer
import kotlin.streams.toList
fun resizedBitmapWithPadding(bitmap: Bitmap, newWidth: Int, newHeight: Int) : Bitmap {
val scale = min(newWidth.toFloat() / bitmap.width, newHeight.toFloat() / bitmap.height)
val scaledWidth = scale * bitmap.width
val scaledHeight = scale * bitmap.height
val matrix = Matrix()
matrix.postScale(scale, scale)
matrix.postTranslate(
(newWidth - scaledWidth) / 2f,
(newHeight - scaledHeight) / 2f
)
val outputBitmap = Bitmap.createBitmap(newWidth, newHeight, bitmap.config)
outputBitmap.eraseColor(Color.WHITE)
Canvas(outputBitmap).drawBitmap(
bitmap,
matrix,
null
)
return outputBitmap
}
private const val MODEL_IMAGE_WIDTH = 48
private const val MODEL_IMAGE_HEIGHT = 48
private const val NUM_CHANNELS = 3
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var inputFeature0: TensorBuffer
private lateinit var model: TrainedModel
private lateinit var byteBuffer: ByteBuffer
private lateinit var charactersIndex: List<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
binding.undoButton.setOnClickListener {
binding.drawCharacterView.undoStroke()
}
binding.drawCharacterView.setOnDrawingUpdatedListener {
bitmap ->
runModelAndUpdateText(bitmap)
}
setContentView(binding.root)
initializeModel()
val zhongImageBitmap =
BitmapFactory.decodeResource(applicationContext.resources, R.drawable.zhong)
runModelAndUpdateText(zhongImageBitmap)
}
fun initializeModel() {
// TODO convert this to a proper interface/class
val ins: InputStream = resources.openRawResource(
resources.getIdentifier(
"characters",
"raw", packageName
)
)
charactersIndex = ins.bufferedReader(Charsets.UTF_8).lines().toList()
byteBuffer = ByteBuffer.allocate(MODEL_IMAGE_WIDTH * MODEL_IMAGE_HEIGHT * NUM_CHANNELS * Float.SIZE_BYTES)
model = TrainedModel.newInstance(applicationContext)
inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, MODEL_IMAGE_WIDTH, MODEL_IMAGE_HEIGHT, NUM_CHANNELS), DataType.FLOAT32)
}
fun runModelAndUpdateText(bitmap: Bitmap) {
val resizedBitmap = resizedBitmapWithPadding(bitmap, MODEL_IMAGE_WIDTH, MODEL_IMAGE_HEIGHT)
for (y in 0 until resizedBitmap.height) {
for (x in 0 until resizedBitmap.width) {
val color = resizedBitmap.getPixel(x, y)
val grayscale = (Color.blue(color) + Color.red(color) + Color.green(color)) / 3
val floatGrayscaleInverted = 1 - grayscale.toFloat() / 255.0F
Log.d("Main", "y,x: $y,$x = $grayscale -> ${floatGrayscaleInverted}")
if (NUM_CHANNELS == 1) {
byteBuffer.putFloat(y * MODEL_IMAGE_WIDTH + x, floatGrayscaleInverted)
} else if (NUM_CHANNELS == 3) {
byteBuffer.putFloat(y * (MODEL_IMAGE_WIDTH * 3) + (x * 3) + 0, floatGrayscaleInverted)
byteBuffer.putFloat(y * (MODEL_IMAGE_WIDTH * 3) + (x * 3) + 1, floatGrayscaleInverted)
byteBuffer.putFloat(y * (MODEL_IMAGE_WIDTH * 3) + (x * 3) + 2, floatGrayscaleInverted)
if (y < 2) {
Log.d("Main", "y: $y, x: $x, pos: ${y * (MODEL_IMAGE_WIDTH * 3) + (x * 3)}, $floatGrayscaleInverted")
}
} else {
throw Exception("unhandled number of channels")
}
}
}
binding.imageView.setImageBitmap(resizedBitmap)
Log.d("Main", "inputFeature0: ${inputFeature0.buffer.capacity()}, byteBuffer: ${byteBuffer.capacity()}")
// Creates inputs for reference.
inputFeature0.loadBuffer(byteBuffer)
// Runs model inference and gets result.
val outputs = model.process(inputFeature0)
val outputFeature0 = outputs.outputFeature0AsTensorBuffer
val n = 10
// contains value and the original index pos
// TODO pull this out into a class
val topN = ArrayList<Pair<Float, Int>>()
for (i in 0 until outputFeature0.flatSize) {
if (topN.size < n) {
topN.add(Pair(outputFeature0.floatArray[i], i))
topN.sortBy { it.first }
} else if (outputFeature0.floatArray[i] > topN[0].first) {
topN.removeAt(0)
topN.add(Pair(outputFeature0.floatArray[i], i))
topN.sortBy { it.first }
}
}
Log.d("Main", topN.reversed().toString())
var results = ""
topN.reversed().forEachIndexed { index, pair ->
results += "${index+1}: ${charactersIndex[pair.second]} (${pair.first})\n"
}
binding.textView.text = results
}
override fun onDestroy() {
super.onDestroy()
model.close()
}
} | mit | 0f42bcfec3eb67aae4076d6f3a1b672b | 35.33125 | 138 | 0.638507 | 4.366642 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/views/CustomFontTextView.kt | 1 | 1151 | package app.lawnchair.ui.preferences.views
import android.content.Context
import androidx.appcompat.widget.AppCompatTextView
import app.lawnchair.font.FontCache
import app.lawnchair.ui.util.ViewPool
import app.lawnchair.util.runOnMainThread
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class CustomFontTextView(context: Context) : AppCompatTextView(context), ViewPool.Recyclable {
private var job: Job? = null
fun setFont(font: FontCache.Font) {
reset()
val fontCache = FontCache.INSTANCE.get(context)
@Suppress("EXPERIMENTAL_API_USAGE")
typeface = fontCache.getLoadedFont(font)?.typeface
job = scope.launch {
val typeface = fontCache.getTypeface(font)
runOnMainThread { setTypeface(typeface) }
}
}
override fun onRecycled() {
reset()
}
private fun reset() {
job?.cancel()
job = null
typeface = null
}
companion object {
private val scope = CoroutineScope(CoroutineName("CustomFontTextView"))
}
}
| gpl-3.0 | a3f57134ebcd06718f8f0c9212fdaad6 | 27.073171 | 94 | 0.699392 | 4.56746 | false | false | false | false |
google-developer-training/android-basics-kotlin-mars-photos-app | app/src/main/java/com/example/android/marsphotos/BindingAdapters.kt | 1 | 2579 | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.marsphotos
import android.view.View
import android.widget.ImageView
import androidx.core.net.toUri
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.android.marsphotos.network.MarsPhoto
import com.example.android.marsphotos.overview.MarsApiStatus
import com.example.android.marsphotos.overview.PhotoGridAdapter
/**
* Updates the data shown in the [RecyclerView].
*/
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<MarsPhoto>?) {
val adapter = recyclerView.adapter as PhotoGridAdapter
adapter.submitList(data)
}
/**
* Uses the Coil library to load an image by URL into an [ImageView]
*/
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
imgView.load(imgUri) {
placeholder(R.drawable.loading_animation)
error(R.drawable.ic_broken_image)
}
}
}
/**
* This binding adapter displays the [MarsApiStatus] of the network request in an image view. When
* the request is loading, it displays a loading_animation. If the request has an error, it
* displays a broken image to reflect the connection error. When the request is finished, it
* hides the image view.
*/
@BindingAdapter("marsApiStatus")
fun bindStatus(statusImageView: ImageView, status: MarsApiStatus) {
when (status) {
MarsApiStatus.LOADING -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.loading_animation)
}
MarsApiStatus.ERROR -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.ic_connection_error)
}
MarsApiStatus.DONE -> {
statusImageView.visibility = View.GONE
}
}
}
| apache-2.0 | 11a21a29e2f1586d3e013003ab865c41 | 34.328767 | 99 | 0.72121 | 4.193496 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UITableViewCell_Contents.kt | 1 | 5809 | package com.yy.codex.uikit
import android.content.Context
import android.view.MotionEvent
import com.yy.codex.foundation.lets
/**
* Created by cuiminghui on 2017/3/9.
*/
internal fun UITableViewCell._initControls() {
_initBackgroundView()
addSubview(backgroundView)
_initSelectedBackgroundView()
addSubview(selectedBackgroundView)
_initAccessoryView()
addSubview(_accessoryView)
_initContentView()
addSubview(contentView)
_initEditingView()
addSubview(_editingView)
_initSeparatorLine()
addSubview(_separatorLine)
}
internal fun UITableViewCell._updateAppearance() {
_updateSeparatorLineStyle()
_updateSeparatorLineHiddenState()
_updateAccessoryView()
_enableEditingView()
_updateFrames()
}
internal fun UITableViewCell._updateFrames() {
contentView.frame = CGRect(_editingMovement(), 0.0, frame.width, frame.height)
backgroundView.frame = CGRect(_editingMovement(), 0.0, frame.width, frame.height)
selectedBackgroundView.frame = CGRect(_editingMovement(), 0.0, frame.width, frame.height)
(separatorInset ?: (nextResponder as? UITableView)?.separatorInset ?: UIEdgeInsets.zero)?.let {
_separatorLine.frame = CGRect(it.left, frame.height - 2.0, frame.width - it.left - it.right + _editingMovement(), 2.0)
}
_accessoryView.frame = CGRect(frame.width - _accessoryView.frame.width + _editingMovement(), 0.0, _accessoryView.frame.width, frame.height)
_accessoryView.subviews.firstOrNull()?.let {
it.frame = it.frame.setY((frame.height - it.frame.height) / 2.0)
}
_editingView.frame = CGRect(frame.width + _editingMovement(), 0.0 , Math.max(0.0, -_editingMovement() + 1.0), frame.height)
}
private fun UITableViewCell._editingMovement(): Double {
if (_editingPanGesture?.state == UIGestureRecognizerState.Began || _editingPanGesture?.state == UIGestureRecognizerState.Changed) {
return Math.ceil(_editingPanGesture?.translation()?.x ?: 0.0)
}
else if (editing) {
return -_editingView.contentWidth
}
return 0.0
}
/**
* ContentView
*/
private fun UITableViewCell._initContentView() {
contentView = UIView(context)
}
/**
* BackgroundView
*/
private fun UITableViewCell._initBackgroundView() {
backgroundView = UIView(context)
backgroundView.constraint = UIConstraint.full()
backgroundView.setBackgroundColor(UIColor.whiteColor)
}
/**
* SelectedBackgroundView
*/
private fun UITableViewCell._initSelectedBackgroundView() {
selectedBackgroundView = UIView(context)
selectedBackgroundView.constraint = UIConstraint.full()
selectedBackgroundView.alpha = 0.0f
selectedBackgroundView.setBackgroundColor(UIColor(0xd9, 0xd9, 0xd9))
}
internal fun UITableViewCell._resetSelectedBackgroundViewState() {
selectedBackgroundView.alpha = if (cellSelected || cellHighlighted) 1.0f else 0.0f
}
/**
* AccessoryView
*/
private fun UITableViewCell._initAccessoryView() {
_accessoryView = UIView(context)
}
private fun UITableViewCell._updateAccessoryView() {
lets(_tableView, _indexPath) { _tableView, _indexPath ->
_tableView.delegate()?.accessoryTypeForRow(_tableView, _indexPath)?.let {
accessoryType = it
}
}
}
internal fun UITableViewCell._resetAccessoryView(accessoryType: UITableViewCell.AccessoryType) {
when (accessoryType) {
UITableViewCell.AccessoryType.None -> {
accessoryView = null
}
UITableViewCell.AccessoryType.DisclosureIndicator -> {
val imageView = UIImageView(context)
imageView.image = UIImage("iVBORw0KGgoAAAANSUhEUgAAAFoAAABaBAMAAADKhlwxAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAwUExURUdwTMzMzNra2sjIzMjIzMfHzMnJzMfHzMjIzsjIzf///8fHzOLi4sfHzMjIzMfHzAy8PhMAAAAPdFJOUwAKB7+1/V/7VF0Eqwmyp9PtpQYAAABuSURBVFjD7datDYBAAIPRKgIIwgi3Ah7FIijmQDIBEoFGMgBDgS83wtXwk/TTzdMFnHPuGy1BGBd9J6xnXkGgyXQ8i2sBH2jc+A/xKa7b1HE+kmet0I1p02/QlUKjPAQa2AQ64rtAA6svg3PugW6LboLTwj02WgAAAABJRU5ErkJggg==", 3.0)
imageView.frame = CGRect(0, 0, 30, 30)
accessoryView = imageView
}
UITableViewCell.AccessoryType.Checkmark -> {
val checkmarkButton = UIButton(context)
checkmarkButton.setImage(UIImage("iVBORw0KGgoAAAANSUhEUgAAAFoAAABaAgMAAABFxqmRAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAMUExURUdwTBV/+xd/+xV++0vg/PkAAAADdFJOUwCAQLcpHQUAAAB3SURBVEjH7ZOxDcAgDATtNB7DGYURskGWSM+KDEOLPgscRbog8eUVJ+sEZnt7y++Y8CjMszGvHbFrsH7CU+ypaqxX+bn+nOgf1vtgfaigPtVQn+p4fWjg9S7dGKdKGCfFcUIcx/WtvSW3t+D25n3ylK/9y/eW3wvxMknyMSaeYAAAAABJRU5ErkJggg==", 3.0), UIControl.State.Normal)
checkmarkButton.frame = CGRect(0, 0, 30, 30)
accessoryView = checkmarkButton
}
}
}
/**
* Separator
*/
private fun UITableViewCell._initSeparatorLine() {
_separatorLine = UIPixelLine(context)
_separatorLine.color = UIColor(0xc8, 0xc7, 0xcc)
_separatorLine.contentInsets = UIEdgeInsets(0.0, 0.0, 1.0, 0.0)
}
internal fun UITableViewCell._updateSeparatorLineHiddenState() {
if (_tableView?._requestNextPointCell(this) == null) {
_separatorLine.hidden = true
return
}
_separatorLine.hidden = selectionStyle == UITableViewCell.SelectionStyle.Gray && (cellSelected || cellHighlighted || _nextCellSelected)
}
private fun UITableViewCell._updateSeparatorLineStyle() {
(separatorStyle ?: (nextResponder as? UITableView)?.separatorStyle ?: UITableViewCell.SeparatorStyle.SingleLine)?.let {
when (it) {
UITableViewCell.SeparatorStyle.None -> _separatorLine.alpha = 0.0f
UITableViewCell.SeparatorStyle.SingleLine -> _separatorLine.alpha = 1.0f
}
}
((nextResponder as? UITableView)?.separatorColor ?: UIColor(0xc8, 0xc7, 0xcc))?.let {
_separatorLine.color = it
}
}
| gpl-3.0 | a819c5da0487c166c735c95fafa57051 | 36.477419 | 426 | 0.727836 | 3.486795 | false | false | false | false |
lgou2w/MoonLakeLauncher | src/main/kotlin/com/minecraft/moonlake/launcher/svg/MuiResourceSVGGlyph.kt | 1 | 4032 | /*
* Copyright (C) 2017 The MoonLake 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.launcher.svg
import com.minecraft.moonlake.launcher.layout.MuiStackPane
import javafx.beans.property.*
import javafx.geometry.Insets
import javafx.scene.input.MouseEvent
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
class MuiResourceSVGGlyph: MuiStackPane {
/**************************************************************************
*
* Private Member
*
**************************************************************************/
private var svgGlyph: MuiSVGGlyph? = null
/**************************************************************************
*
* Constructor
*
**************************************************************************/
constructor(): super() {
this.url.addListener { _, _, newValue -> run {
if(newValue != null) {
this.svgGlyph = MuiSVGGlyphLoader.loadMuiSVG(newValue)
this.addEventHandler(MouseEvent.MOUSE_ENTERED, { _ -> run {
if(this.svgGlyph != null && enterFill.isNotNull.get())
this.svgGlyph!!.setFill(enterFill.get())
}})
this.addEventHandler(MouseEvent.MOUSE_EXITED, { _ -> run {
if(this.svgGlyph != null)
this.svgGlyph!!.setFill(fill.get())
}})
if(this.svgGlyph != null)
this.svgGlyph!!.styleClass.add("mui-res-svg")
this.children.add(0, svgGlyph)
} else if(this.svgGlyph != null) {
this.children.remove(svgGlyph)
this.svgGlyph = null
}
}}
this.sizeRatio.addListener { _, _, newValue -> run {
if(this.svgGlyph != null)
this.svgGlyph!!.setSizeRatio(newValue.toDouble())
}}
this.fill.addListener { _, _, newValue -> run {
if(this.svgGlyph != null)
this.svgGlyph!!.setFill(newValue)
}}
this.padding = Insets(5.0)
}
/**************************************************************************
*
* Properties
*
**************************************************************************/
private var url: StringProperty = SimpleStringProperty()
fun urlProperty(): StringProperty
= url
fun getUrl(): String
= url.get()
fun setUrl(url: String)
= this.url.set(url)
private var sizeRatio: DoubleProperty = SimpleDoubleProperty()
fun sizeRatioProperty(): DoubleProperty
= sizeRatio
fun getSizeRatio(): Double
= sizeRatio.get()
fun setSizeRatio(sizeRatio: Double)
= this.sizeRatio.set(sizeRatio)
private var fill: ObjectProperty<Paint> = SimpleObjectProperty(Color.BLACK)
fun fillProperty(): ObjectProperty<Paint>
= fill
fun getFill(): Paint
= fill.get()
fun setFill(fill: Paint)
= this.fill.set(fill)
private var enterFill: ObjectProperty<Paint> = SimpleObjectProperty(null)
fun enterFillProperty(): ObjectProperty<Paint>
= enterFill
fun getEnterFill(): Paint
= enterFill.get()
fun setEnterFill(enterFill: Paint)
= this.enterFill.set(enterFill)
}
| gpl-3.0 | e82bebbce7065f0523c1c32213d7f4c0 | 31.780488 | 80 | 0.532986 | 4.905109 | false | false | false | false |
lgou2w/MoonLakeLauncher | src/main/kotlin/com/minecraft/moonlake/launcher/controller/MuiStageController.kt | 1 | 2735 | /*
* Copyright (C) 2017 The MoonLake 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.launcher.controller
import javafx.fxml.FXML
import javafx.scene.input.MouseButton
import javafx.scene.input.MouseEvent
import javafx.scene.layout.Pane
import javafx.stage.Stage
import java.net.URL
import java.util.*
abstract class MuiStageController<S: Stage, out T: Pane>: MuiController<T>() {
private var stage: S? = null
protected fun stage(): S
= stage!!
/**
* Set this controller stage instance
*/
internal fun setStage(stage: S) { this.stage = stage }
override fun initialize(location: URL?, resources: ResourceBundle?) {
super.initialize(location, resources)
}
/**************************************************************************
*
* Navbar Mouse Event Handler
*
**************************************************************************/
protected var navbarMouseX = .0
protected var navbarMouseY = .0
@FXML
open fun onNavbarPressed(event: MouseEvent) {
if(event.button == MouseButton.PRIMARY) {
navbarMouseX = event.x
navbarMouseY = event.y
event.consume()
}
}
@FXML
open fun onNavbarDragged(event: MouseEvent) {
if(event.button == MouseButton.PRIMARY) {
stage().x = event.screenX - navbarMouseX
stage().y = event.screenY - navbarMouseY
event.consume()
}
}
/**************************************************************************
*
* Window Control Button Event Handler
*
**************************************************************************/
@FXML
open fun onMinimizeClicked(event: MouseEvent) {
stage().isIconified = true
event.consume()
}
@FXML
open fun onMaximizeClicked(event: MouseEvent) {
stage().isMaximized = !stage().isMaximized
event.consume()
}
@FXML
open fun onCloseClicked(event: MouseEvent) {
stage().close()
event.consume()
}
}
| gpl-3.0 | 790dbbab12bccb1ab6f2b528c2e0f416 | 28.095745 | 80 | 0.5766 | 4.773124 | false | false | false | false |
JoosungPark/Leaning-Kotlin-Android | app/src/main/java/ma/sdop/weatherapp/data/database/Tables.kt | 1 | 454 | package ma.sdop.weatherapp.data.database
/**
* Created by parkjoosung on 2017. 4. 20..
*/
object CityForecastTable {
val NAME = "CityForecast"
val ID = "_id"
val CITY = "city"
val COUNTRY = "country"
}
object DayForecastTable {
val NAME = "DayForecast"
val ID = "_id"
val DATE = "date"
val DESCRIPTION = "description"
val HIGH = "high"
val LOW = "low"
val ICON_URL = "iconUrl"
val CITY_ID = "cityId"
} | apache-2.0 | db65304cf4008091aa4049cde3db0a63 | 18.782609 | 42 | 0.60793 | 3.413534 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/repositories/RegionsRepositoryImpl.kt | 1 | 2328 | package com.garpr.android.repositories
import com.garpr.android.data.exceptions.FailedToFetchRegionsException
import com.garpr.android.data.models.AbsRegion
import com.garpr.android.data.models.Endpoint
import com.garpr.android.data.models.Optional
import com.garpr.android.data.models.Region
import com.garpr.android.data.models.RegionsBundle
import com.garpr.android.misc.Timber
import com.garpr.android.networking.ServerApi
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import java.util.Collections
class RegionsRepositoryImpl(
private val serverApi: ServerApi,
private val timber: Timber
) : RegionsRepository {
override fun getRegions(): Single<RegionsBundle> {
return Single.zip(
getRegions(Endpoint.GAR_PR),
getRegions(Endpoint.NOT_GAR_PR),
BiFunction<Optional<RegionsBundle>, Optional<RegionsBundle>, RegionsBundle> { garPr, notGarPr ->
mergeResponses(garPr.orNull(), notGarPr.orNull())
})
}
private fun getRegions(endpoint: Endpoint): Single<Optional<RegionsBundle>> {
return serverApi.getRegions(endpoint)
.map { bundle ->
Optional.of(bundle)
}
.onErrorReturn { throwable ->
timber.e(TAG, "Error fetching \"$endpoint\" regions", throwable)
Optional.empty()
}
}
@Throws(FailedToFetchRegionsException::class)
private fun mergeResponses(garPr: RegionsBundle?, notGarPr: RegionsBundle?): RegionsBundle {
val regionsSet = mutableSetOf<Region>()
garPr?.regions?.mapTo(regionsSet) { region ->
Region(region = region, endpoint = Endpoint.GAR_PR)
}
notGarPr?.regions?.mapTo(regionsSet) { region ->
Region(region = region, endpoint = Endpoint.NOT_GAR_PR)
}
val regionsList = regionsSet.toList()
Collections.sort(regionsList, AbsRegion.ENDPOINT_ORDER)
if (regionsList.isEmpty()) {
timber.e(TAG, "Failed to fetch any regions")
throw FailedToFetchRegionsException()
}
return RegionsBundle(regions = regionsList)
}
companion object {
private const val TAG = "RegionsRepositoryImpl"
}
}
| unlicense | 97db681a88b15fa99046a96541fbc1fe | 33.746269 | 112 | 0.65378 | 4.392453 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/model/entities/Lesson.kt | 1 | 1365 | package net.tlalka.fiszki.model.entities
import com.j256.ormlite.field.DataType
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import net.tlalka.fiszki.model.dao.LessonDao
import net.tlalka.fiszki.model.types.LanguageType
import net.tlalka.fiszki.model.types.LevelType
import net.tlalka.fiszki.model.types.OwnerType
@DatabaseTable(tableName = "lessons", daoClass = LessonDao::class)
class Lesson {
@DatabaseField(generatedId = true)
var id: Long = 0
@DatabaseField(canBeNull = false)
var name: String = ""
@DatabaseField(canBeNull = false, dataType = DataType.ENUM_INTEGER)
var levelType: LevelType = LevelType.BEGINNER
@DatabaseField(canBeNull = false, index = true)
var languageType: LanguageType = LanguageType.PL
@DatabaseField(canBeNull = false, dataType = DataType.ENUM_INTEGER)
var ownerType: OwnerType = OwnerType.SYSTEM
@DatabaseField
var progress: Int = 0
@DatabaseField
var score: Int = 0
constructor() {
// Constructor required for ORMLite library.
}
constructor(name: String, levelType: LevelType, languageType: LanguageType) {
this.name = name
this.levelType = levelType
this.languageType = languageType
this.ownerType = OwnerType.SYSTEM
}
}
| mit | d634a838337efad906312dc5b77d7044 | 28.333333 | 81 | 0.701099 | 3.956522 | false | false | false | false |
Fitbit/MvRx | mvrx-mocking/src/main/kotlin/com/airbnb/mvrx/mocking/ViewMocker.kt | 1 | 8799 | package com.airbnb.mvrx.mocking
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import androidx.fragment.app.Fragment
import com.airbnb.mvrx.Mavericks
import com.airbnb.mvrx.MavericksView
import kotlin.system.measureTimeMillis
/**
* See [getMockVariants]
*
* Provides mocks for the view specified by the fully qualified name of its class.
*
* @param viewClassName The fully qualified name of the view's class.
* @param viewProvider Creates an instance of the view from the view class. The view should be created
* with the given arguments bundle if it exists. The bundle contains parcelable arguments under the
* [Mavericks.KEY_ARG] key.
*/
fun <V : MockableMavericksView> getMockVariants(
viewClassName: String,
viewProvider: (viewClass: Class<V>, argumentsBundle: Bundle?) -> V = { viewClass, argumentsBundle ->
@Suppress("UNCHECKED_CAST")
val view = viewClass.newInstance()
if (view is Fragment) view.arguments = argumentsBundle
view
},
emptyMockPlaceholder: EmptyMavericksViewMocks = EmptyMocks,
mockGroupIndex: Int? = null
): List<MockedViewProvider<V>>? {
@Suppress("UNCHECKED_CAST")
return getMockVariants(
viewClass = Class.forName(viewClassName) as Class<V>,
viewProvider = viewProvider,
emptyMockPlaceholder = emptyMockPlaceholder,
mockGroupIndex = mockGroupIndex
)
}
/**
* Helper for getting all mock variants off of a Fragment.
* It is an error to call this if the Fragment does not define any mocks.
*/
inline fun <reified T> mockVariants(): List<MockedViewProvider<T>> where T : Fragment, T : MockableMavericksView {
@Suppress("UNCHECKED_CAST")
val mocks: List<MockedViewProvider<MockableMavericksView>>? = getMockVariants(
viewClass = T::class.java as Class<MockableMavericksView>
)
@Suppress("UNCHECKED_CAST")
return checkNotNull(mocks) {
"${T::class.java.simpleName} does not have mocks defined for it"
} as List<MockedViewProvider<T>>
}
/**
* Helper for pulling the default state mock out of a list of mocks.
*/
fun <T : MockableMavericksView> List<MockedViewProvider<T>>.forDefaultState(): MockedViewProvider<T> {
return firstOrNull { it.mock.type == MavericksMock.Type.DefaultState }
?: error("No default state mock found")
}
/**
* Helper for pulling the default initialization mock out of a list of mocks.
*/
fun <T : MockableMavericksView> List<MockedViewProvider<T>>.forDefaultInitialization(): MockedViewProvider<T> {
return firstOrNull { it.mock.type == MavericksMock.Type.DefaultInitialization }
?: error("No default initialization mock found")
}
/**
* See [getMockVariants]
*
* Provides mocks for the view specified by the given class.
*
* @param viewClass The Java class representing the [MavericksView]
* @param viewProvider Creates an instance of the view from the view class. The view should be created
* with the given arguments bundle if it exists. The bundle contains parcelable arguments under the
* [Mavericks.KEY_ARG] key.
*/
fun <V : MockableMavericksView> getMockVariants(
viewClass: Class<V>,
viewProvider: (viewClass: Class<V>, argumentsBundle: Bundle?) -> V = { viewClassFromProvider, argumentsBundle ->
@Suppress("UNCHECKED_CAST")
val view = viewClassFromProvider.newInstance()
if (view is Fragment) view.arguments = argumentsBundle
view
},
emptyMockPlaceholder: EmptyMavericksViewMocks = EmptyMocks,
mockGroupIndex: Int? = null
): List<MockedViewProvider<V>>? {
return getMockVariants<V, Parcelable>(
viewProvider = { _, argumentsBundle ->
viewProvider(viewClass, argumentsBundle)
},
emptyMockPlaceholder = emptyMockPlaceholder,
mockGroupIndex = mockGroupIndex
)
}
/**
* Get all of the mocks declared for a [MavericksView]. The returned list of [MockedViewProvider]
* has one entry representing each mock in the view, which can be used to create a view mocked
* with that state and arguments.
*
* @param viewProvider Return an instance of the [MavericksView] that is being mocked. It should be
* created with the provided arguments if they exist. Both the arguments and argumentsBundle
* parameters in the lambda represent the same arguments, they are just provided in multiple
* forms so you can use the most convenient. The Bundle just contains the Parcelable arguments
* under the [Mavericks.KEY_ARG] key.
*
* @param emptyMockPlaceholder If you use a custom object to represent that a [MavericksView] legitimately
* has no mocks then specify it here. Otherwise any view with empty mocks will throw an error.
*
* @param mockGroupIndex If the mocks are declared with [combineMocks] then if an index is passed
* only the mocks in that group index will be returned. Will throw an error if this is not a valid
* group index for this view's mocks.
*/
fun <V : MockableMavericksView, A : Parcelable> getMockVariants(
viewProvider: (arguments: A?, argumentsBundle: Bundle?) -> V,
emptyMockPlaceholder: EmptyMavericksViewMocks = EmptyMocks,
mockGroupIndex: Int? = null
): List<MockedViewProvider<V>>? {
val view = viewProvider(null, null)
// This needs to be the FQN to completely define the view and make it creatable from reflection
val viewName = view.javaClass.canonicalName ?: error("Null canonical name for $view")
lateinit var mocks: List<MavericksMock<out MockableMavericksView, out Parcelable>>
val elapsedMs: Long = measureTimeMillis {
val mockData = MavericksViewMocks.getFrom(view).takeIf { it !== emptyMockPlaceholder } ?: return null
mocks = if (mockGroupIndex != null) {
mockData.mockGroups.getOrNull(mockGroupIndex) ?: error("Could not get mock group at index $mockGroupIndex for $viewName")
} else {
mockData.mocks
}
}
println("Created mocks for $viewName in $elapsedMs ms")
require(mocks.isNotEmpty()) {
"No mocks provided for $viewName. Use the placeholder '${emptyMockPlaceholder::class.simpleName}' to skip adding mocks"
}
return mocks.map { mvRxFragmentMock ->
@Suppress("UNCHECKED_CAST")
val mockInfo = mvRxFragmentMock as MavericksMock<V, A>
MockedViewProvider(
viewName = viewName,
createView = { mockBehavior ->
val configProvider = MockableMavericks.mockConfigFactory
// Test argument serialization/deserialization
val arguments = mockInfo.args
val bundle = if (arguments != null) argumentsBundle(arguments, viewName) else null
configProvider.withMockBehavior(mockBehavior) {
viewProvider(arguments, bundle)
}.let { view ->
// Set the view to be initialized with the mocked state when its viewmodels are created
MockableMavericks.mockStateHolder.setMock(view, mockInfo)
MockedView(
viewInstance = view,
viewName = viewName,
mockData = mockInfo,
cleanupMockState = { MockableMavericks.mockStateHolder.clearMock(view) }
)
}
},
mock = mockInfo
)
}
}
private fun argumentsBundle(arguments: Parcelable, viewName: String): Bundle {
@Suppress("Detekt.TooGenericExceptionCaught")
return try {
if (arguments is Bundle) {
arguments
} else {
Bundle().apply {
putParcelable(Mavericks.KEY_ARG, arguments)
}
}.makeClone()
} catch (e: Throwable) {
throw AssertionError(
"The arguments class ${arguments::class.simpleName} for view " +
"$viewName failed to be parceled. Make sure it is a valid Parcelable " +
"and all properties on it are valid Parcelables or Serializables.",
e
)
}
}
private fun <T : Parcelable> T.makeClone(): T {
val p = Parcel.obtain()
p.writeValue(this)
p.setDataPosition(0)
@Suppress("UNCHECKED_CAST")
val clone = p.readValue(MockedView::class.java.classLoader) as T
p.recycle()
return clone
}
data class MockedViewProvider<V : MavericksView>(
val viewName: String,
val createView: (MockBehavior) -> MockedView<V>,
val mock: MavericksMock<V, *>
)
/**
* @property cleanupMockState Call this when the view is done initializing its viewmodels, so that the global mock state can be cleared.
*/
class MockedView<V : MavericksView>(
val viewInstance: V,
val viewName: String,
val mockData: MavericksMock<V, *>,
val cleanupMockState: () -> Unit
)
| apache-2.0 | f0615bb27d1a0f9e6ad2cd8639997f8f | 38.635135 | 136 | 0.681896 | 4.563797 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/summit_register/AddSummitRegister.kt | 1 | 3089 | package de.westnordost.streetcomplete.quests.summit_register
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.quest.NoCountriesExcept
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.OUTDOORS
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.RARE
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
import de.westnordost.streetcomplete.util.distanceToArcs
class AddSummitRegister : OsmElementQuestType<Boolean> {
private val filter by lazy { """
nodes with
natural = peak and name and
(!summit:register or summit:register older today -4 years)
""".toElementFilterExpression() }
override val commitMessage = "Add whether summit register is present"
override val wikiLink = "Key:summit:register"
override val icon = R.drawable.ic_quest_peak
/*
override val enabledInCountries = NoCountriesExcept(
// regions gathered in
// https://github.com/streetcomplete/StreetComplete/issues/561#issuecomment-325623974
// Europe
"AT", "DE", "CZ", "ES", "IT", "FR", "GR", "SI", "CH", "RO", "SK",
//Americas
"US", "AR", "PE"
)
*/
override val questTypeAchievements = listOf(RARE, OUTDOORS)
override fun getTitle(tags: Map<String, String>) = R.string.quest_summit_register_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val peaks = mapData.nodes.filter { filter.matches(it) }
if (peaks.isEmpty()) return emptyList()
val hikingRoutes = mapData.relations
.filter { it.tags["route"] == "hiking" }
.mapNotNull { mapData.getRelationGeometry(it.id) as? ElementPolylinesGeometry }
if (hikingRoutes.isEmpty()) return emptyList()
// yes, this is very inefficient, however, peaks are very rare
return peaks.filter { peak ->
hikingRoutes.any { hikingRoute ->
hikingRoute.polylines.any { ways ->
peak.position.distanceToArcs(ways) <= 10
}
}
}
}
override fun isApplicableTo(element: Element): Boolean? =
if (!filter.matches(element)) false else null
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("summit:register", answer.toYesNo())
}
}
| gpl-3.0 | e1c8ba6b699eae424f59ccc175c75a77 | 40.743243 | 93 | 0.721269 | 4.556047 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/PersonActivity.kt | 1 | 5784 | package com.boardgamegeek.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.viewModels
import com.boardgamegeek.R
import com.boardgamegeek.entities.Status
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.adapter.PersonPagerAdapter
import com.boardgamegeek.ui.viewmodel.PersonViewModel
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
import java.util.*
class PersonActivity : HeroTabActivity() {
enum class PersonType {
ARTIST,
DESIGNER,
PUBLISHER
}
private var id = BggContract.INVALID_ID
private var name = ""
private var personType = PersonType.DESIGNER
private var emptyMessageDescription = ""
private val viewModel by viewModels<PersonViewModel>()
private val adapter: PersonPagerAdapter by lazy {
PersonPagerAdapter(this, id, name, personType)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
id = intent.getIntExtra(KEY_PERSON_ID, BggContract.INVALID_ID)
name = intent.getStringExtra(KEY_PERSON_NAME).orEmpty()
personType = (intent.getSerializableExtra(KEY_PERSON_TYPE) as PersonType?) ?: PersonType.DESIGNER
emptyMessageDescription = getString(R.string.title_person).lowercase(Locale.getDefault())
initializeViewPager()
safelySetTitle(name)
emptyMessageDescription = when (personType) {
PersonType.ARTIST -> {
viewModel.setArtistId(id)
getString(R.string.title_artist).lowercase(Locale.getDefault())
}
PersonType.DESIGNER -> {
viewModel.setDesignerId(id)
getString(R.string.title_designer).lowercase(Locale.getDefault())
}
PersonType.PUBLISHER -> {
viewModel.setPublisherId(id)
getString(R.string.title_publisher).lowercase(Locale.getDefault())
}
}
viewModel.details.observe(this) {
if (it?.status == Status.ERROR) {
toast(it.message.ifBlank { getString(R.string.empty_person, emptyMessageDescription) })
}
it?.data?.let { person ->
safelySetTitle(person.name)
if (person.heroImageUrl.isNotBlank()) {
loadToolbarImage(person.heroImageUrl)
} else if (person.thumbnailUrl.isNotBlank()) {
loadToolbarImage(person.thumbnailUrl)
}
}
}
if (savedInstanceState == null) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "Person")
param(FirebaseAnalytics.Param.ITEM_ID, id.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, name)
}
}
}
override val optionsMenuId = R.menu.person
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_view -> {
val path = when (personType) {
PersonType.DESIGNER -> "boardgamedesigner"
PersonType.ARTIST -> "boardgameartist"
PersonType.PUBLISHER -> "boardgamepublisher"
}
linkToBgg(path, id)
}
android.R.id.home -> {
when (personType) {
PersonType.DESIGNER -> startActivity(intentFor<DesignersActivity>().clearTop())
PersonType.ARTIST -> startActivity(intentFor<ArtistsActivity>().clearTop())
PersonType.PUBLISHER -> startActivity(intentFor<PublishersActivity>().clearTop())
}
finish()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun createAdapter() = adapter
override fun getPageTitle(position: Int) = adapter.getPageTitle(position)
companion object {
private const val KEY_PERSON_TYPE = "PERSON_TYPE"
private const val KEY_PERSON_ID = "PERSON_ID"
private const val KEY_PERSON_NAME = "PERSON_NAME"
fun startForArtist(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.ARTIST))
}
fun startForDesigner(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.DESIGNER))
}
fun startForPublisher(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.PUBLISHER))
}
fun startUpForArtist(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.ARTIST).clearTask().clearTop())
}
fun startUpForDesigner(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.DESIGNER).clearTask().clearTop())
}
fun startUpForPublisher(context: Context, id: Int, name: String) {
context.startActivity(createIntent(context, id, name, PersonType.PUBLISHER).clearTask().clearTop())
}
private fun createIntent(context: Context, id: Int, name: String, personType: PersonType): Intent {
return context.intentFor<PersonActivity>(
KEY_PERSON_ID to id,
KEY_PERSON_NAME to name,
KEY_PERSON_TYPE to personType,
)
}
}
}
| gpl-3.0 | f8360a96c23be747437f81def4b3ba25 | 37.304636 | 111 | 0.625864 | 4.82402 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/palette/Palette.kt | 1 | 2170 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.util.palette
/**
* Represents a palette.
*/
interface Palette<T : Any> {
/**
* Gets or assigns the id for the given [T].
*
* @param obj The type
* @return The id
*/
fun getIdOrAssign(obj: T): Int
/**
* Gets the id for the given [T].
*
* @param obj The object
* @return The id, or null if not found
*/
fun getNullableId(obj: T): Int? {
val id = getId(obj)
return if (id == INVALID_ID) null else id
}
/**
* Gets the id for the given [T].
*
* @param obj The obj
* @return The id, or [INVALID_ID] if not found
*/
fun getId(obj: T): Int
/**
* Requires the id that is assigned to the given object.
*
* @param obj The object
* @return The id
*/
fun requireId(obj: T): Int {
val id = getId(obj)
check(id != INVALID_ID) { "The given object $obj doesn't exist." }
return id
}
/**
* Gets the object that is assigned to the given id.
*
* @param id The id
* @return The object, or null if not found
*/
operator fun get(id: Int): T?
/**
* Requires the object that is assigned to the given id.
*
* @param id The id
* @return The object
*/
fun require(id: Int): T = get(id) ?: error("The given id $id doesn't exist.")
/**
* Gets all the objects that are assigned.
*
* @return The assigned objects
*/
val entries: Collection<T>
/**
* The size of the palette. (the amount of objects that are assigned.)
*/
val size: Int
/**
* Creates a copy of this palette.
*/
fun copy(): Palette<T>
companion object {
/**
* Represents a invalid id.
*/
const val INVALID_ID = -1
}
}
| mit | 22a785ce40d3842c7bb9ea697dafd903 | 21.371134 | 81 | 0.553456 | 3.767361 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/eventdataprovider/privacybudgetmanagement/PrivacyBudgetManager.kt | 1 | 3648 | /**
* Copyright 2022 The Cross-Media Measurement 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.wfanet.measurement.eventdataprovider.privacybudgetmanagement
/**
* This is the default value for the total amount that can be charged to a single privacy bucket.
*/
private const val MAXIMUM_PRIVACY_USAGE_PER_BUCKET = 1.0f
private const val MAXIMUM_DELTA_PER_BUCKET = 1.0e-9f
/**
* Instantiates a privacy budget manager.
*
* @param filter: An object that maps [PrivacyBucketGroup]s to Event messages.
* @param backingStore: An object that provides persistent storage of privacy budget data in a
* consistent and atomic manner.
* @param maximumPrivacyBudget: The maximum privacy budget that can be used in any privacy bucket.
* @param maximumTotalDelta: Maximum total value of the delta parameter that can be used in any
* privacy bucket.
*/
class PrivacyBudgetManager(
val filter: PrivacyBucketFilter,
val backingStore: PrivacyBudgetLedgerBackingStore,
val maximumPrivacyBudget: Float = MAXIMUM_PRIVACY_USAGE_PER_BUCKET,
val maximumTotalDelta: Float = MAXIMUM_DELTA_PER_BUCKET,
) {
val ledger = PrivacyBudgetLedger(backingStore, maximumPrivacyBudget, maximumTotalDelta)
/** Checks if calling charge with this [reference] will result in an update in the ledger. */
suspend fun referenceWillBeProcessed(reference: Reference) = !ledger.hasLedgerEntry(reference)
/**
* Checks if charging all of the privacy buckets identified by the given measurementSpec and
* requisitionSpec would not exceed privacy budget.
*
* @param query represents the [Query] that specifies charges and buckets to be charged.
* @throws PrivacyBudgetManagerException if an error occurs in handling this request. Possible
* exceptions could include running out of privacy budget or a failure to commit the transaction
* to the database.
*/
suspend fun chargingWillExceedPrivacyBudget(query: Query) =
ledger.chargingWillExceedPrivacyBudget(
filter.getPrivacyBucketGroups(query.reference.measurementConsumerId, query.landscapeMask),
setOf(query.charge)
)
/**
* Checks if charging all of the privacy buckets identified by the given measurementSpec and
* requisitionSpec would not exceed privacy budget.
*
* @param Reference representing the reference key and if the charge is a refund.
* @param measurementConsumerId that the charges are for.
* @param requisitionSpec The requisitionSpec protobuf that is associated with the query. The date
* range and demo groups are obtained from this.
* @param measurementSpec The measurementSpec protobuf that is associated with the query. The VID
* sampling interval is obtained from from this.
* @throws PrivacyBudgetManagerException if an error occurs in handling this request. Possible
* exceptions could include a failure to commit the transaction to the database.
*/
suspend fun chargePrivacyBudget(query: Query) =
ledger.charge(
query.reference,
filter.getPrivacyBucketGroups(query.reference.measurementConsumerId, query.landscapeMask),
setOf(query.charge)
)
}
| apache-2.0 | be1d55806898d28ce6ce78c08118bcb8 | 47.64 | 100 | 0.765899 | 4.635324 | false | false | false | false |
ageery/kwicket | kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/KWebMarkupContainer.kt | 1 | 4146 | package org.kwicket.wicket.core.markup.html
import org.apache.wicket.MarkupContainer
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.component.q
fun MarkupContainer.webMarkupContainer(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(
KWebMarkupContainer(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behavior = behavior
)
)
@Deprecated(message = "Use the one in the queued package", replaceWith = ReplaceWith("org.kwicket.wicket.core.queued.webMarkupContainer"))
fun MarkupContainer.webMarkupContainer(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KWebMarkupContainer(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
)
/**
* [WebMarkupContainer] component with named and default constructor arguments.
*
* @param id id of the [Component]
* @param model optional [IModel] of the [Component]
* @param outputMarkupId optional flag indicating whether an id attribute will be created on the HTML element
* @param outputMarkupPlaceholderTag optional flag indicating whether an id attribtue will be created on the HTML
* element, creating a placeholder id if the component is initially not visible
* @param visible optional flag indicating whether the [Component] is visible
* @param enabled optional flag indicating whether the [Component] is enabled
* @param renderBodyOnly optional flag indicating whether only the [Component]'s HTML will be rendered or whether the
* tag the [Component] is attached to will also be rendered
* @param behaviors [List] of [Behavior]s to add to the [Component]
*/
open class KWebMarkupContainer(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) : WebMarkupContainer(id, model) {
constructor(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) : this(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behaviors = listOf(behavior)
)
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
}
} | apache-2.0 | d15f674cbf25696908d5f3cfdad1ed6a | 33.848739 | 138 | 0.679932 | 5.043796 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terrarum/virtualcomputer/terranvmadapter/TextOnly.kt | 1 | 5813 | package net.torvald.terrarum.virtualcomputer.terranvmadapter
import com.badlogic.gdx.Game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputProcessor
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.torvald.terranvm.assets.BiosSetup
import net.torvald.terranvm.assets.Loader
import net.torvald.terranvm.runtime.Assembler
import net.torvald.terranvm.runtime.GdxPeripheralWrapper
import net.torvald.terranvm.runtime.TerranVM
import net.torvald.terranvm.runtime.compiler.cflat.Cflat
import net.torvald.terranvm.runtime.toUint
import net.torvald.terranvm.toReadableBin
import net.torvald.terranvm.toReadableOpcode
/**
* Created by minjaesong on 2017-11-17.
*/
class TextOnly : Game() {
private val ipsCounter = """
.code;
loadwordilo r1, 42;
loadbyte r2, r1, r0;
storebyte r1, r2, r0;
jmp 19h;
""".trimIndent()
lateinit var background: Texture
lateinit var execLed: Texture
lateinit var waitLed: Texture
lateinit var batch: SpriteBatch
lateinit var vm: TerranVM
lateinit var sevensegFont: BitmapFont
lateinit var peripheral: PeriMDA
lateinit var vmThread: Thread
lateinit var memvwr: Memvwr
override fun create() {
val vmDelay = 1
background = Texture(Gdx.files.internal("assets/8025_textonly.png"))
execLed = Texture(Gdx.files.internal("assets/led_green.tga"))
waitLed = Texture(Gdx.files.internal("assets/led_orange.tga"))
batch = SpriteBatch()
sevensegFont = SevensegFont()
peripheral = PeriMDA(vmExecDelay = vmDelay)
vm = TerranVM(8192, stdout = peripheral.printStream)
vm.peripherals[TerranVM.IRQ_KEYBOARD] = KeyboardAbstraction(vm)
vm.peripherals[3] = peripheral
val assembler = Assembler(vm)
//val programImage = assembler(Loader())
val programImage = assembler(ipsCounter)
val code = programImage.bytes
println("ASM size: ${code.size} (word-aligned: ${if (code.size % 4 == 0) "yes" else "HELL NAW!"})")
code.printASM()
vm.loadProgram(programImage)
vm.delayInMills = vmDelay
memvwr = Memvwr(vm)
Gdx.input.inputProcessor = TVMInputProcessor(vm)
vmThread = Thread(vm)
vmThread.start()
}
private val height: Int; get() = Gdx.graphics.height
private val lcdOffX = 74f
private val lcdOffY = 56f
override fun render() {
Gdx.graphics.setTitle("TerranVM Debugging Console - Text Only Mode — F: ${Gdx.graphics.framesPerSecond}")
//vm.pauseExec()
memvwr.update()
batch.inUse {
batch.color = Color.WHITE
batch.draw(background, 0f, 0f)
// exec lamp
if (vm.isRunning && !vm.isPaused) {
batch.draw(execLed, 51f, 39f)
}
// wait lamp
if (vm.isPaused) {
batch.draw(waitLed, 51f, 19f)
}
// draw whatever on the peripheral's memory
peripheral.render(batch, Gdx.graphics.rawDeltaTime, lcdOffX, lcdOffY)
// seven seg displays
// -> memsize
batch.color = Color(0x25e000ff)
sevensegFont.draw(batch, vm.memory.size.toString().padStart(8, ' '), 307f, height - 18 - 500f)
// -> program counter
batch.color = Color(0xff5a66ff.toInt())
sevensegFont.draw(batch, vm.pc.toString(16).padStart(6, ' '), 451f, height - 18 - 500f)
// -> link register
sevensegFont.draw(batch, vm.lr.toString(16).padStart(6, ' '), 585f, height - 18 - 500f)
// -> stack pointer
sevensegFont.draw(batch, vm.sp.toString(16).padStart(4, ' '), 719f, height - 18 - 500f)
}
//vm.resumeExec()
}
override fun dispose() {
background.dispose()
execLed.dispose()
waitLed.dispose()
}
private inline fun SpriteBatch.inUse(action: () -> Unit) {
this.begin()
action.invoke()
this.end()
}
class TVMInputProcessor(val vm: TerranVM) : InputProcessor {
override fun touchUp(p0: Int, p1: Int, p2: Int, p3: Int): Boolean {
return false
}
override fun mouseMoved(p0: Int, p1: Int): Boolean {
return false
}
override fun keyTyped(p0: Char): Boolean {
(vm.peripherals[TerranVM.IRQ_KEYBOARD] as GdxPeripheralWrapper).keyTyped(p0)
return true
}
override fun scrolled(p0: Int): Boolean {
return false
}
override fun keyUp(p0: Int): Boolean {
return false
}
override fun touchDragged(p0: Int, p1: Int, p2: Int): Boolean {
return false
}
override fun keyDown(p0: Int): Boolean {
return false
}
override fun touchDown(p0: Int, p1: Int, p2: Int, p3: Int): Boolean {
return false
}
}
}
fun ByteArray.printASM() {
for (i in 0 until this.size step 4) {
val b = this[i].toUint() or this[i + 1].toUint().shl(8) or this[i + 2].toUint().shl(16) or this[i + 3].toUint().shl(24)
print("${b.toReadableBin()}; ")
print("${b.toReadableOpcode()}\n")
}
}
fun main(args: Array<String>) {
val config = LwjglApplicationConfiguration()
config.width = 1106
config.height = 556
config.foregroundFPS = 0
config.resizable = false
LwjglApplication(TextOnly(), config)
} | mit | 8b259901998fe903d1f127c86968d5b3 | 26.158879 | 129 | 0.615213 | 3.810492 | false | false | false | false |
PaulWoitaschek/Voice | common/src/main/kotlin/voice/common/pref/PrefKeys.kt | 1 | 629 | package voice.common.pref
import javax.inject.Qualifier
object PrefKeys {
const val RESUME_ON_REPLUG = "RESUME_ON_REPLUG"
const val AUTO_REWIND_AMOUNT = "AUTO_REWIND"
const val SEEK_TIME = "SEEK_TIME"
const val SLEEP_TIME = "SLEEP_TIME"
const val SINGLE_BOOK_FOLDERS = "singleBookFolders"
const val COLLECTION_BOOK_FOLDERS = "folders"
const val DARK_THEME = "darkTheme"
const val GRID_MODE = "gridView"
}
@Qualifier
annotation class RootAudiobookFolders
@Qualifier
annotation class SingleFolderAudiobookFolders
@Qualifier
annotation class SingleFileAudiobookFolders
@Qualifier
annotation class CurrentBook
| gpl-3.0 | 3a122228708ed9d2466d4a7f687b5a9b | 22.296296 | 53 | 0.780604 | 3.721893 | false | false | false | false |
FHannes/intellij-community | platform/script-debugger/backend/src/org/jetbrains/debugger/Scope.kt | 31 | 1397 | /*
* 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.debugger
import org.jetbrains.debugger.values.ObjectValue
enum class ScopeType {
GLOBAL,
LOCAL,
WITH,
CLOSURE,
CATCH,
LIBRARY,
CLASS,
INSTANCE,
BLOCK,
SCRIPT,
UNKNOWN
}
interface Scope {
val type: ScopeType
/**
* Class or function or file name
*/
val description: String?
val variablesHost: VariablesHost<*>
val isGlobal: Boolean
}
abstract class ScopeBase(override val type: ScopeType, override val description: String?) : Scope {
override val isGlobal: Boolean
get() = type === ScopeType.GLOBAL || type === ScopeType.LIBRARY
}
class ObjectScope(type: ScopeType, private val value: ObjectValue) : ScopeBase(type, value.valueString), Scope {
override val variablesHost: VariablesHost<*>
get() = value.variablesHost
} | apache-2.0 | 8eecd340fab950aa597efdc677b1040b | 24.418182 | 112 | 0.725841 | 4.120944 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/settings/EditClientSettingsActivity.kt | 2 | 9668 | package com.lasthopesoftware.bluewater.client.settings
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.about.AboutTitleBuilder
import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRemoval
import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.BrowserLibrarySelection
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library.SyncedFileLocation
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.views.RemoveLibraryConfirmationDialogBuilder
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettingsLookup
import com.lasthopesoftware.bluewater.client.connection.settings.changes.ObservableConnectionSettingsLibraryStorage
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemAccess
import com.lasthopesoftware.bluewater.permissions.read.ApplicationReadPermissionsRequirementsProvider
import com.lasthopesoftware.bluewater.permissions.write.ApplicationWritePermissionsRequirementsProvider
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import java.util.*
class EditClientSettingsActivity : AppCompatActivity() {
private val saveButton = LazyViewFinder<Button>(this, R.id.btnConnect)
private val txtAccessCode = LazyViewFinder<EditText>(this, R.id.txtAccessCode)
private val txtUserName = LazyViewFinder<EditText>(this, R.id.txtUserName)
private val txtPassword = LazyViewFinder<EditText>(this, R.id.txtPassword)
private val txtSyncPath = LazyViewFinder<TextView>(this, R.id.txtSyncPath)
private val chkLocalOnly = LazyViewFinder<CheckBox>(this, R.id.chkLocalOnly)
private val rgSyncFileOptions = LazyViewFinder<RadioGroup>(this, R.id.rgSyncFileOptions)
private val chkIsUsingExistingFiles = LazyViewFinder<CheckBox>(this, R.id.chkIsUsingExistingFiles)
private val chkIsUsingLocalConnectionForSync = LazyViewFinder<CheckBox>(this, R.id.chkIsUsingLocalConnectionForSync)
private val chkIsWakeOnLanEnabled = LazyViewFinder<CheckBox>(this, R.id.isWakeOnLan)
private val applicationWritePermissionsRequirementsProviderLazy by lazy { ApplicationWritePermissionsRequirementsProvider(this) }
private val applicationReadPermissionsRequirementsProviderLazy by lazy { ApplicationReadPermissionsRequirementsProvider(this) }
private val libraryProvider by lazy { LibraryRepository(this) }
private val libraryStorage by lazy {
ObservableConnectionSettingsLibraryStorage(
LibraryRepository(this),
ConnectionSettingsLookup(libraryProvider),
MessageBus(LocalBroadcastManager.getInstance(this))
)
}
private val applicationSettingsRepository by lazy { getApplicationSettingsRepository() }
private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) }
private val settingsMenu = lazy {
EditClientSettingsMenu(
this,
AboutTitleBuilder(this),
RemoveLibraryConfirmationDialogBuilder(
this,
LibraryRemoval(
StoredItemAccess(this),
libraryStorage,
SelectedBrowserLibraryIdentifierProvider(getApplicationSettingsRepository()),
libraryProvider,
BrowserLibrarySelection(applicationSettingsRepository, messageBus, libraryProvider))))
}
private var library: Library? = null
private val connectionButtonListener = View.OnClickListener {
saveButton.findView().isEnabled = false
val localLibrary = library ?: Library(_nowPlayingId = -1)
library = localLibrary
.setAccessCode(txtAccessCode.findView().text.toString())
.setUserName(txtUserName.findView().text.toString())
.setPassword(txtPassword.findView().text.toString())
.setLocalOnly(chkLocalOnly.findView().isChecked)
.setCustomSyncedFilesPath(txtSyncPath.findView().text.toString())
.setSyncedFileLocation(when (rgSyncFileOptions.findView().checkedRadioButtonId) {
R.id.rbPublicLocation -> SyncedFileLocation.EXTERNAL
R.id.rbPrivateToApp -> SyncedFileLocation.INTERNAL
R.id.rbCustomLocation -> SyncedFileLocation.CUSTOM
else -> null
})
.setIsUsingExistingFiles(chkIsUsingExistingFiles.findView().isChecked)
.setIsSyncLocalConnectionsOnly(chkIsUsingLocalConnectionForSync.findView().isChecked)
.setIsWakeOnLanEnabled(chkIsWakeOnLanEnabled.findView().isChecked)
val permissionsToRequest = ArrayList<String>(2)
if (applicationReadPermissionsRequirementsProviderLazy.isReadPermissionsRequiredForLibrary(localLibrary))
permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
if (applicationWritePermissionsRequirementsProviderLazy.isWritePermissionsRequiredForLibrary(localLibrary))
permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permissionsToRequest.size > 0) {
val permissionsToRequestArray = permissionsToRequest.toTypedArray()
ActivityCompat.requestPermissions(this@EditClientSettingsActivity, permissionsToRequestArray, permissionsRequestInteger)
} else {
saveLibraryAndFinish()
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_server_settings)
setSupportActionBar(findViewById(R.id.serverSettingsToolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
saveButton.findView().setOnClickListener(connectionButtonListener)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean = settingsMenu.value.buildSettingsMenu(menu)
override fun onStart() {
super.onStart()
initializeLibrary(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
initializeLibrary(intent)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode != selectDirectoryResultId) {
super.onActivityResult(requestCode, resultCode, data)
return
}
val uri = data?.dataString
if (uri != null) txtSyncPath.findView().text = uri
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
settingsMenu.value.handleSettingsMenuClicks(item, library)
private fun initializeLibrary(intent: Intent) {
val externalFilesDir = Environment.getExternalStorageDirectory()
val syncPathTextView = txtSyncPath.findView()
if (externalFilesDir != null) syncPathTextView.text = externalFilesDir.path
val syncFilesRadioGroup = rgSyncFileOptions.findView()
syncFilesRadioGroup.check(R.id.rbPrivateToApp)
syncFilesRadioGroup.setOnCheckedChangeListener { _, checkedId -> syncPathTextView.isEnabled = checkedId == R.id.rbCustomLocation }
val libraryId = intent.getIntExtra(serverIdExtra, -1)
if (libraryId < 0) return
libraryProvider
.getLibrary(LibraryId(libraryId))
.eventually(LoopedInPromise.response({ result ->
library = result ?: return@response
chkLocalOnly.findView().isChecked = result.isLocalOnly
chkIsUsingExistingFiles.findView().isChecked = result.isUsingExistingFiles
chkIsUsingLocalConnectionForSync.findView().isChecked = result.isSyncLocalConnectionsOnly
chkIsWakeOnLanEnabled.findView().isChecked = result.isWakeOnLanEnabled
val customSyncPath = result.customSyncedFilesPath
if (customSyncPath != null && customSyncPath.isNotEmpty()) syncPathTextView.text = customSyncPath
syncFilesRadioGroup.check(when (result.syncedFileLocation) {
SyncedFileLocation.EXTERNAL -> R.id.rbPublicLocation
SyncedFileLocation.INTERNAL -> R.id.rbPrivateToApp
SyncedFileLocation.CUSTOM -> R.id.rbCustomLocation
else -> -1
})
txtAccessCode.findView().setText(result.accessCode)
txtUserName.findView().setText(result.userName)
txtPassword.findView().setText(result.password)
}, this))
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode != permissionsRequestInteger) return
for (grantResult in grantResults) {
if (grantResult == PackageManager.PERMISSION_GRANTED) continue
Toast.makeText(this, R.string.permissions_must_be_granted_for_settings, Toast.LENGTH_LONG).show()
saveButton.findView().isEnabled = true
return
}
saveLibraryAndFinish()
}
private fun saveLibraryAndFinish() {
val library = library ?: return
libraryStorage.saveLibrary(library).eventually(LoopedInPromise.response({
saveButton.findView().text = getText(R.string.btn_saved)
finish()
}, this))
}
companion object {
@JvmField
val serverIdExtra = MagicPropertyBuilder.buildMagicPropertyName(EditClientSettingsActivity::class.java, "serverIdExtra")
private const val selectDirectoryResultId = 93
private const val permissionsRequestInteger = 1
}
}
| lgpl-3.0 | 3e6901e863eda536a26b764d3e01ea2e | 45.705314 | 144 | 0.820439 | 4.398544 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/dokit/DemoKit.kt | 1 | 953 | package com.didichuxing.doraemondemo.dokit
import android.app.Activity
import android.content.Context
import com.didichuxing.doraemondemo.R
import com.didichuxing.doraemonkit.DoKit
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.didichuxing.doraemonkit.kit.Category
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-09-24-15:48
* 描 述:kit demo
* 修订历史:
* ================================================
*/
class DemoKit : AbstractKit() {
override val category: Int
get() = Category.BIZ
override val name: Int
get() = R.string.dk_kit_demo
override val icon: Int
get() = R.mipmap.dk_sys_info
override fun onClickWithReturn(activity: Activity): Boolean {
DoKit.launchFloating(DemoDoKitView::class.java)
return true
}
override fun onAppInit(context: Context?) {
}
}
| apache-2.0 | acaa7b49547c0888ca45cc84e1ea79e9 | 24.914286 | 65 | 0.611907 | 3.960699 | false | false | false | false |
soniccat/android-taskmanager | authorization/src/main/java/com/example/alexeyglushkov/authorization/AuthActivityProxy.kt | 1 | 1792 | package com.example.alexeyglushkov.authorization
import android.app.Activity
import android.content.Intent
import com.example.alexeyglushkov.authorization.OAuth.OAuthWebClient
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import java.lang.Exception
import java.lang.ref.WeakReference
/**
* Created by alexeyglushkov on 25.11.15.
*/
class AuthActivityProxy : OAuthWebClient {
override suspend fun loadUrl(url: String, callback: String): String {
Assert.assertNotNull(currentActivity)
val intent = Intent(getCurrentActivity(), AuthorizationActivity::class.java)
intent.putExtra(AuthorizationActivity.LOAD_URL, url)
intent.putExtra(AuthorizationActivity.CALLBACK_URL, callback)
authResult = Channel()
getCurrentActivity()?.startActivity(intent)
return authResult.receive()
}
companion object {
private var currentActivity: WeakReference<Activity>? = null
var authResult = Channel<String>()
//private static Callback currentCallback;
fun getCurrentActivity(): Activity? {
return if (currentActivity != null) currentActivity?.get() else null
}
fun setCurrentActivity(currentActivity: Activity?) {
Companion.currentActivity = if (currentActivity != null) WeakReference(currentActivity) else null
}
fun finish(url: String?, error: Exception?) = runBlocking {
if (error != null || url == null) {
val resultError = if (error != null) error else IllegalArgumentException(url)
authResult.close(resultError)
} else {
authResult.send(url)
authResult.close(null)
}
}
}
} | mit | ab8ca0205040ffe2a2c9fb25ebcaac67 | 34.86 | 109 | 0.679129 | 5.033708 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/OptionsRunner.kt | 1 | 6676 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.options
import javafx.collections.ObservableList
import javafx.event.ActionEvent
import javafx.scene.control.*
import javafx.scene.layout.BorderPane
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.Task
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.paratask.util.process.Exec
import uk.co.nickthecoder.paratask.util.process.OSCommand
open class OptionsRunner(val tool: Tool) {
protected var refresher: Refresher = Refresher()
fun createNonRowOptionsMenu(contextMenu: ContextMenu) {
contextMenu.items.clear()
val optionsName = tool.optionsName
val topLevelOptions = OptionsManager.getTopLevelOptions(optionsName)
var addedSubMenus = false
var count = 0
for (fileOptions in topLevelOptions.listFileOptions()) {
val items: ObservableList<MenuItem>
val optionsList = fileOptions.listOptions().filter { !it.isRow }.sorted()
if (optionsList.isNotEmpty()) {
if (count > 0 && count + optionsList.size > 15) {
val subMenu = Menu(fileOptions.name)
items = subMenu.items
if (!addedSubMenus) {
contextMenu.items.add(SeparatorMenuItem())
}
contextMenu.items.add(subMenu)
addedSubMenus = true
} else {
items = contextMenu.items
if (items.isNotEmpty()) {
items.add(SeparatorMenuItem())
}
}
for (option in optionsList) {
val menuItem = createMenuItem(option)
menuItem.addEventHandler(ActionEvent.ACTION) { runNonRow(option) }
items.add(menuItem)
count++
}
}
}
}
protected fun createMenuItem(option: Option): MenuItem {
val box = BorderPane()
val label = Label(option.label)
if (option.code == ".") {
label.styleClass.add("default")
}
label.minWidth = 250.0
box.center = label
box.right = Label(" " + option.code)
val item = CustomMenuItem(box, true)
return item
}
fun runNonRow(option: Option, prompt: Boolean = false, newTab: Boolean = false) {
refresher = Refresher()
doNonRow(option, prompt = prompt, newTab = newTab)
}
fun runNonRow(code: String, prompt: Boolean = false, newTab: Boolean = false): Boolean {
refresher = Refresher()
val option = OptionsManager.findNonRowOption(code, tool.optionsName)
if (option == null || option.isRow) {
return false
}
doNonRow(option, prompt = prompt, newTab = newTab)
return true
}
protected fun doNonRow(option: Option, prompt: Boolean = false, newTab: Boolean = false) {
try {
val result = option.runNonRow(tool)
process(result,
newTab = newTab || option.newTab,
prompt = prompt || option.prompt,
refresh = option.refresh)
} catch(e: Exception) {
handleException(e)
}
}
protected fun handleException(e: Exception) {
tool.toolPane?.halfTab?.projectTab?.projectTabs?.projectWindow?.handleException(e)
}
protected fun process(
result: Any?,
newTab: Boolean,
prompt: Boolean,
refresh: Boolean) {
when (result) {
is Exec -> {
processExec(result, refresh)
}
is OSCommand -> {
processExec(Exec(result), refresh)
}
is Tool -> {
processTool(result, newTab, prompt)
}
is Task -> {
processTask(result, prompt, refresh)
}
else -> {
if (refresh) {
refresher.add()
refresher.onFinished()
}
}
}
}
protected fun processTool(returnedTool: Tool, newTab: Boolean, prompt: Boolean) {
val halfTab = tool.toolPane?.halfTab
val projectTabs = halfTab?.projectTab?.projectTabs
// Reuse the current tool where possible, otherwise copy the tool
val newTool = if (returnedTool !== tool || newTab) returnedTool.copy() else tool
newTool.resolveParameters(tool.resolver)
if (newTab) {
val tab = projectTabs?.addAfter(tool.toolPane!!.halfTab.projectTab, newTool, run = !prompt)
tab?.isSelected
} else {
halfTab?.changeTool(newTool, prompt)
}
}
protected fun processTask(task: Task, prompt: Boolean, refresh: Boolean) {
task.resolveParameters(tool.resolver)
if (refresh) {
refresher.add()
task.taskRunner.listen {
refresher.onFinished()
}
}
var checked: Boolean
try {
task.check()
checked = true
} catch (e: Exception) {
checked = false
}
// Either prompt the Task, or run it straight away
if (prompt || !checked) {
TaskPrompter(task).placeOnStage(Stage())
} else {
task.taskRunner.run()
}
}
protected fun processExec(exec: Exec, refresh: Boolean) {
if (refresh) {
refresher.add()
exec.listen { refresher.onFinished() }
}
exec.start()
}
/**
* This is the "simple" version, but RowOptionsRunner has a more complex version, which handles
* batches.
*/
open inner class Refresher {
open fun add() {}
open fun onFinished() {
tool.toolPane?.parametersPane?.run()
}
}
}
| gpl-3.0 | 1d8c34e960bf27a6ec8f7e1029d5b1cc | 29.345455 | 103 | 0.572349 | 4.748222 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/Signature.kt | 1 | 1708 | package net.nemerosa.ontrack.model.structure
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.common.truncate
import java.time.LocalDateTime
/**
* Association of a [User] and a timestamp.
*/
data class Signature(
val time: LocalDateTime,
val user: User
) {
fun withTime(dateTime: LocalDateTime?): Signature = Signature(dateTime ?: Time.now(), user)
/**
* Keeps at most 4 first digits for the nano seconds.
*
* @see [Time.forStorage]
* @see [Time.fromStorage]
*/
fun truncate() = Signature(
time.truncate(),
user
)
/**
* Equality is based on the first 4 digits of the nano seconds
*/
override fun equals(other: Any?): Boolean = if (other is Signature) {
this.user == other.user && this.time.truncate() == other.time.truncate()
} else {
false
}
override fun hashCode(): Int {
var result = time.truncate().hashCode()
result = 31 * result + user.hashCode()
return result
}
companion object {
/**
* Builder from a user name, for current time
*/
@JvmStatic
fun of(name: String): Signature = of(Time.now(), name)
/**
* Builder from a user name and a given time
*/
@JvmStatic
fun of(dateTime: LocalDateTime, name: String) = Signature(
dateTime,
User.of(name)
)
/**
* Anonymous signature
*/
@JvmStatic
fun anonymous(): Signature {
return Signature(
Time.now(),
User.anonymous()
)
}
}
} | mit | 6a00a6c572f14644b7b613146b1ccb66 | 23.070423 | 95 | 0.54274 | 4.542553 | false | false | false | false |
RedstonerServer/Parcels | src/main/kotlin/io/dico/parcels2/blockvisitor/Schematic.kt | 1 | 4074 | package io.dico.parcels2.blockvisitor
import io.dico.parcels2.JobFunction
import io.dico.parcels2.JobScope
import io.dico.parcels2.util.math.Region
import io.dico.parcels2.util.math.Vec3i
import io.dico.parcels2.util.math.get
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.World
import org.bukkit.block.Sign
import org.bukkit.block.data.BlockData
private val air = Bukkit.createBlockData(Material.AIR)
class Schematic {
val size: Vec3i get() = _size!!
private var _size: Vec3i? = null
set(value) {
field?.let { throw IllegalStateException() }
field = value
}
private var blockDatas: Array<BlockData?>? = null
private val extra = mutableListOf<Pair<Vec3i, ExtraBlockChange>>()
private var isLoaded = false; private set
private val traverser: RegionTraverser = RegionTraverser.upward
suspend fun JobScope.load(world: World, region: Region) {
_size = region.size
val data = arrayOfNulls<BlockData>(region.blockCount).also { blockDatas = it }
val blocks = traverser.traverseRegion(region)
val total = region.blockCount.toDouble()
loop@ for ((index, vec) in blocks.withIndex()) {
markSuspensionPoint()
setProgress(index / total)
val block = world[vec]
if (block.y > 255) continue
val blockData = block.blockData
data[index] = blockData
val extraChange = when (blockData.material) {
Material.SIGN,
Material.WALL_SIGN -> SignStateChange(block.state as Sign)
else -> continue@loop
}
extra += (vec - region.origin) to extraChange
}
isLoaded = true
}
suspend fun JobScope.paste(world: World, position: Vec3i) {
if (!isLoaded) throw IllegalStateException()
val region = Region(position, _size!!)
val blocks = traverser.traverseRegion(region, worldHeight = world.maxHeight)
val blockDatas = blockDatas!!
var postponed = hashMapOf<Vec3i, BlockData>()
val total = region.blockCount.toDouble()
var processed = 0
for ((index, vec) in blocks.withIndex()) {
markSuspensionPoint()
setProgress(index / total)
val block = world[vec]
val type = blockDatas[index] ?: air
if (type !== air && isAttachable(type.material)) {
val supportingBlock = vec + getSupportingBlock(type)
if (!postponed.containsKey(supportingBlock) && traverser.comesFirst(vec, supportingBlock)) {
block.blockData = type
setProgress(++processed / total)
} else {
postponed[vec] = type
}
} else {
block.blockData = type
setProgress(++processed / total)
}
}
while (!postponed.isEmpty()) {
markSuspensionPoint()
val newMap = hashMapOf<Vec3i, BlockData>()
for ((vec, type) in postponed) {
val supportingBlock = vec + getSupportingBlock(type)
if (supportingBlock in postponed && supportingBlock != vec) {
newMap[vec] = type
} else {
world[vec].blockData = type
setProgress(++processed / total)
}
}
postponed = newMap
}
// Should be negligible so we don't track progress
for ((vec, extraChange) in extra) {
markSuspensionPoint()
val block = world[position + vec]
extraChange.update(block)
}
}
fun getLoadTask(world: World, region: Region): JobFunction = {
load(world, region)
}
fun getPasteTask(world: World, position: Vec3i): JobFunction = {
paste(world, position)
}
}
| gpl-2.0 | d7e7d0679e8e88ba0dab2b89e984f810 | 31.669421 | 108 | 0.564065 | 4.624291 | false | false | false | false |
goodwinnk/intellij-community | platform/credential-store/src/PasswordSafeConfigurable.kt | 1 | 9770 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.passwordSafe.impl.PasswordSafeImpl
import com.intellij.ide.passwordSafe.impl.createPersistentCredentialStore
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableBase
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.components.RadioButton
import com.intellij.ui.components.chars
import com.intellij.ui.layout.*
import com.intellij.util.text.nullize
import gnu.trove.THashMap
import java.awt.Component
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import javax.swing.JPanel
import kotlin.properties.Delegates.notNull
internal class PasswordSafeConfigurable(private val settings: PasswordSafeSettings) : ConfigurableBase<PasswordSafeConfigurableUi, PasswordSafeSettings>("application.passwordSafe", "Passwords", "reference.ide.settings.password.safe") {
override fun getSettings() = settings
override fun createUi() = PasswordSafeConfigurableUi()
}
internal fun getDefaultKeePassDbFilePath() = "${PathManager.getConfigPath()}${File.separatorChar}${DB_FILE_NAME}"
internal class PasswordSafeConfigurableUi : ConfigurableUi<PasswordSafeSettings> {
private val inKeychain = RadioButton("In native Keychain")
private val inKeePass = RadioButton("In KeePass")
private val keePassMasterPassword = JBPasswordField()
private var keePassDbFile: TextFieldWithHistoryWithBrowseButton by notNull()
private val rememberPasswordsUntilClosing = RadioButton("Do not save, forget passwords after restart")
private val modeToRow = THashMap<ProviderType, Row>()
override fun reset(settings: PasswordSafeSettings) {
when (settings.providerType) {
ProviderType.MEMORY_ONLY -> rememberPasswordsUntilClosing.isSelected = true
ProviderType.KEYCHAIN -> inKeychain.isSelected = true
ProviderType.KEEPASS -> inKeePass.isSelected = true
else -> throw IllegalStateException("Unknown provider type: ${settings.providerType}")
}
val currentProvider = (PasswordSafe.instance as PasswordSafeImpl).currentProvider
@Suppress("IfThenToElvis")
keePassDbFile.text = settings.state.keepassDb ?: if (currentProvider is KeePassCredentialStore) currentProvider.dbFile.toString() else getDefaultKeePassDbFilePath()
updateEnabledState()
}
override fun isModified(settings: PasswordSafeSettings): Boolean {
if (getProviderType() != settings.providerType) {
return true
}
if (getProviderType() == ProviderType.KEEPASS) {
if (!keePassMasterPassword.chars.isNullOrBlank()) {
return true
}
getCurrentDbFile()?.let {
val passwordSafe = PasswordSafe.instance as PasswordSafeImpl
if ((passwordSafe.currentProvider as KeePassCredentialStore).dbFile != it) {
return true
}
}
}
return false
}
override fun apply(settings: PasswordSafeSettings) {
val providerType = getProviderType()
val passwordSafe = PasswordSafe.instance as PasswordSafeImpl
var provider = passwordSafe.currentProvider
val masterPassword = keePassMasterPassword.chars.toString().nullize(true)?.toByteArray()
if (settings.providerType != providerType) {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (providerType) {
ProviderType.MEMORY_ONLY -> {
if (provider is KeePassCredentialStore) {
provider.memoryOnly = true
provider.deleteFileStorage()
}
else {
provider = KeePassCredentialStore(memoryOnly = true)
}
}
ProviderType.KEYCHAIN -> {
provider = createPersistentCredentialStore(provider as? KeePassCredentialStore)
}
ProviderType.KEEPASS -> {
provider = KeePassCredentialStore(existingMasterPassword = masterPassword, dbFile = getCurrentDbFile())
}
}
}
val newProvider = provider
if (newProvider === passwordSafe.currentProvider && newProvider is KeePassCredentialStore) {
if (masterPassword != null) {
// so, provider is the same and we must change master password for existing database file
newProvider.setMasterPassword(masterPassword)
}
getCurrentDbFile()?.let {
newProvider.dbFile = it
}
}
settings.providerType = providerType
if (newProvider is KeePassCredentialStore) {
settings.state.keepassDb = newProvider.dbFile.toString()
}
else {
settings.state.keepassDb = null
}
passwordSafe.currentProvider = newProvider
}
fun getCurrentDbFile() = keePassDbFile.text.trim().nullize()?.let { Paths.get(it) }
private fun updateEnabledState() {
modeToRow[ProviderType.KEEPASS]?.subRowsEnabled = getProviderType() == ProviderType.KEEPASS
}
override fun getComponent(): JPanel {
val passwordSafe = PasswordSafe.instance as PasswordSafeImpl
keePassMasterPassword.setPasswordIsStored(true)
return panel {
row { label("Save passwords:") }
buttonGroup({ updateEnabledState() }) {
if (SystemInfo.isLinux || isMacOsCredentialStoreSupported) {
row {
inKeychain()
}
}
modeToRow[ProviderType.KEEPASS] = row {
inKeePass()
row("Database:") {
val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor().withFileFilter {
it.name.endsWith(".kdbx")
}
keePassDbFile = textFieldWithBrowseButton("KeePass Database File",
fileChooserDescriptor = fileChooserDescriptor,
fileChosen = ::normalizeSelectedFile)
gearButton(
object : AnAction("Clear") {
override fun actionPerformed(event: AnActionEvent) {
if (MessageDialogBuilder.yesNo("Clear Passwords", "Are you sure want to remove all passwords?").yesText("Remove Passwords").isYes) {
passwordSafe.clearPasswords()
}
}
},
object : AnAction("Import") {
override fun actionPerformed(event: AnActionEvent) {
chooseFile(fileChooserDescriptor, event) {
val wantedDbFile = Paths.get(normalizeSelectedFile(it))
val dbFile = getCurrentDbFile()
if (dbFile != wantedDbFile) {
val contextComponent = event.getData(PlatformDataKeys.CONTEXT_COMPONENT) as Component
Messages.showInputDialog(
contextComponent, "Master Password:", "Specify Master Password", null)?.trim().nullize()?.let { masterPassword ->
try {
Files.copy(wantedDbFile, dbFile, StandardCopyOption.REPLACE_EXISTING)
passwordSafe.currentProvider = KeePassCredentialStore(existingMasterPassword = masterPassword.toByteArray(),
dbFile = getCurrentDbFile())
}
catch (e: Exception) {
LOG.error(e)
if (e.message == "Inconsistent stream bytes") {
Messages.showMessageDialog(contextComponent, if (e.message == "Inconsistent stream bytes") "Password is not correct" else "Internal error", "Cannot Import", Messages.getErrorIcon())
}
}
keePassMasterPassword.text = ""
}
}
}
}
}
)
}
row("Master Password:") {
keePassMasterPassword(comment = if (SystemInfo.isWindows) null else "Stored using weak encryption. It is recommended to store on encrypted volume for additional security.")
}
}
row {
var comment: String? = null
val currentProvider = passwordSafe.currentProvider
if (currentProvider is KeePassCredentialStore && !currentProvider.memoryOnly) {
comment = "Existing KeePass file will be removed."
}
rememberPasswordsUntilClosing(comment = comment)
}
}
}
}
private fun getProviderType(): ProviderType {
return when {
rememberPasswordsUntilClosing.isSelected -> ProviderType.MEMORY_ONLY
inKeePass.isSelected -> ProviderType.KEEPASS
else -> ProviderType.KEYCHAIN
}
}
}
private fun normalizeSelectedFile(file: VirtualFile): String {
if (file.isDirectory) {
return file.path + File.separator + DB_FILE_NAME
}
else {
return file.path
}
}
enum class ProviderType {
MEMORY_ONLY, KEYCHAIN, KEEPASS,
// unused, but we cannot remove it because enum value maybe stored in the config and we must correctly deserialize it
@Deprecated("")
DO_NOT_STORE
} | apache-2.0 | 7bb26f8e2fcc557f166e885142b0cbf6 | 38.881633 | 235 | 0.666735 | 5.232994 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/ext/gitlfs/storage/BasicAuthHttpLfsStorage.kt | 1 | 1850 | /*
* 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.ext.gitlfs.storage
import org.apache.http.impl.client.CloseableHttpClient
import org.eclipse.jgit.lib.Constants
import ru.bozaro.gitlfs.client.Client
import ru.bozaro.gitlfs.client.auth.AuthProvider
import ru.bozaro.gitlfs.client.auth.BasicAuthProvider
import svnserver.auth.User
import svnserver.ext.gitlfs.server.LfsServer
import svnserver.ext.gitlfs.storage.network.LfsHttpStorage
import java.net.URI
/**
* HTTP remote storage for LFS files.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
open class BasicAuthHttpLfsStorage(baseUrl: String, repositoryName: String, username: String, password: String) : LfsHttpStorage() {
private val httpClient: CloseableHttpClient = createHttpClient()
private val baseURI: URI = buildAuthURI(baseUrl, repositoryName)
private val fallbackAuthProvider: BasicAuthProvider = BasicAuthProvider(baseURI, username, password)
override fun lfsClient(user: User): Client {
return Client(authProvider(user, baseURI), httpClient)
}
protected open fun authProvider(user: User, baseURI: URI): AuthProvider {
return fallbackAuthProvider
}
companion object {
protected fun buildAuthURI(_baseUrl: String, repositoryName: String): URI {
var baseUrl = _baseUrl
if (!baseUrl.endsWith("/")) baseUrl += "/"
return URI.create(baseUrl + repositoryName + Constants.DOT_GIT_EXT + "/" + LfsServer.SERVLET_BASE)
}
}
}
| gpl-2.0 | 05cca6fbce6f90729232bd97eaebcb8e | 41.045455 | 132 | 0.739459 | 4.147982 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/ds/ImageCache.kt | 1 | 730 | package org.pixelndice.table.pixelclient.ds
import javafx.scene.image.Image
import org.apache.logging.log4j.LogManager
private val logger = LogManager.getLogger(ImageCache::class.java)
object ImageCache{
val hashMap = hashMapOf<String, Image>()
fun getImage(path: String): Image {
val ret = hashMap[path]
if( ret != null )
return ret
val img = Image(path)
hashMap[path] = img
return img
}
fun getImage(path: java.nio.file.Path): Image {
val str = path.toUri().toURL().toString()
val ret = hashMap[str]
if( ret != null )
return ret
val img = Image(str)
hashMap[str] = img
return img
}
} | bsd-2-clause | 98a9510b36e044f5eb4ac65bc0134cfd | 18.756757 | 65 | 0.594521 | 4.033149 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/sync/FileBasedPreferencesValuesSyncAction.kt | 1 | 2407 | /*
* 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.util.sync
import android.content.Context
import android.content.SharedPreferences
import java.io.Closeable
import java.util.*
abstract class FileBasedPreferencesValuesSyncAction<DownloadSession : Closeable, UploadSession : Closeable>(
context: Context,
var preferences: SharedPreferences,
val processor: Processor
) : FileBasedKeyValueSyncAction<DownloadSession, UploadSession>(context) {
override final val snapshotFileName: String = processor.snapshotFileName
override final val whatData: String = processor.whatData
override fun addToLocal(data: MutableMap<String, String>) {
val editor = preferences.edit()
for ((k, v) in data) {
processor.saveValue(editor, k, v)
}
editor.apply()
}
override fun removeFromLocal(data: MutableMap<String, String>) {
val editor = preferences.edit()
for (k in data.keys) {
editor.remove(k)
}
editor.apply()
}
override final fun loadFromLocal(): MutableMap<String, String> {
val result = HashMap<String, String>()
for ((k, v) in preferences.all) {
processor.loadValue(result, k, v)
}
return result
}
interface Processor {
val snapshotFileName: String
val whatData: String
fun saveValue(editor: SharedPreferences.Editor, key: String, value: String)
fun loadValue(map: MutableMap<String, String>, key: String, value: Any?)
}
} | gpl-3.0 | 11799049a2bab6800903c12ca81b342d | 33.4 | 108 | 0.691732 | 4.336937 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/view/CardNumberEditText.kt | 1 | 12760 | package com.stripe.android.view
import android.content.Context
import android.os.Build
import android.text.Editable
import android.text.InputFilter
import android.util.AttributeSet
import android.view.View
import androidx.annotation.VisibleForTesting
import com.stripe.android.PaymentConfiguration
import com.stripe.android.R
import com.stripe.android.cards.CardAccountRangeRepository
import com.stripe.android.cards.CardAccountRangeService
import com.stripe.android.cards.CardNumber
import com.stripe.android.cards.DefaultCardAccountRangeRepositoryFactory
import com.stripe.android.cards.DefaultStaticCardAccountRanges
import com.stripe.android.cards.StaticCardAccountRanges
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor
import com.stripe.android.model.AccountRange
import com.stripe.android.model.CardBrand
import com.stripe.android.networking.PaymentAnalyticsEvent
import com.stripe.android.networking.PaymentAnalyticsRequestFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
/**
* A [StripeEditText] that handles spacing out the digits of a credit card.
*/
@SuppressWarnings("LongParameterList")
class CardNumberEditText internal constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = androidx.appcompat.R.attr.editTextStyle,
// TODO(mshafrir-stripe): make immutable after `CardWidgetViewModel` is integrated in `CardWidget` subclasses
@get:VisibleForTesting
var workContext: CoroutineContext,
private val cardAccountRangeRepository: CardAccountRangeRepository,
private val staticCardAccountRanges: StaticCardAccountRanges = DefaultStaticCardAccountRanges(),
private val analyticsRequestExecutor: AnalyticsRequestExecutor,
private val paymentAnalyticsRequestFactory: PaymentAnalyticsRequestFactory
) : StripeEditText(context, attrs, defStyleAttr) {
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = androidx.appcompat.R.attr.editTextStyle
) : this(
context,
attrs,
defStyleAttr,
Dispatchers.IO,
{ PaymentConfiguration.getInstance(context).publishableKey }
)
private constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
workContext: CoroutineContext,
publishableKeySupplier: () -> String
) : this(
context,
attrs,
defStyleAttr,
workContext,
DefaultCardAccountRangeRepositoryFactory(context).create(),
DefaultStaticCardAccountRanges(),
DefaultAnalyticsRequestExecutor(),
PaymentAnalyticsRequestFactory(
context,
publishableKeyProvider = publishableKeySupplier
)
)
@VisibleForTesting
var cardBrand: CardBrand = CardBrand.Unknown
internal set(value) {
val prevBrand = field
field = value
if (value != prevBrand) {
brandChangeCallback(cardBrand)
updateLengthFilter()
}
}
@JvmSynthetic
internal var brandChangeCallback: (CardBrand) -> Unit = {}
set(callback) {
field = callback
// Immediately display the brand if known, in case this method is invoked when
// partial data already exists.
callback(cardBrand)
}
// invoked when a valid card has been entered
@JvmSynthetic
internal var completionCallback: () -> Unit = {}
internal val panLength: Int
get() = accountRangeService.accountRange?.panLength
?: accountRangeService.staticCardAccountRanges.first(unvalidatedCardNumber)?.panLength
?: CardNumber.DEFAULT_PAN_LENGTH
private val formattedPanLength: Int
get() = panLength + CardNumber.getSpacePositions(panLength).size
/**
* Check whether or not the card number is valid
*/
var isCardNumberValid: Boolean = false
private set
internal val validatedCardNumber: CardNumber.Validated?
get() = unvalidatedCardNumber.validate(panLength)
private val unvalidatedCardNumber: CardNumber.Unvalidated
get() = CardNumber.Unvalidated(fieldText)
private val isValid: Boolean
get() = validatedCardNumber != null
@VisibleForTesting
val accountRangeService = CardAccountRangeService(
cardAccountRangeRepository,
workContext,
staticCardAccountRanges,
object : CardAccountRangeService.AccountRangeResultListener {
override fun onAccountRangeResult(newAccountRange: AccountRange?) {
updateLengthFilter()
cardBrand = newAccountRange?.brand ?: CardBrand.Unknown
}
}
)
@JvmSynthetic
internal var isLoadingCallback: (Boolean) -> Unit = {}
private var loadingJob: Job? = null
init {
setNumberOnlyInputType()
setErrorMessage(resources.getString(R.string.invalid_card_number))
addTextChangedListener(CardNumberTextWatcher())
internalFocusChangeListeners.add { _, hasFocus ->
if (!hasFocus && unvalidatedCardNumber.isPartialEntry(panLength)) {
shouldShowError = true
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setAutofillHints(View.AUTOFILL_HINT_CREDIT_CARD_NUMBER)
}
updateLengthFilter()
this.layoutDirection = LAYOUT_DIRECTION_LTR
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
loadingJob = CoroutineScope(workContext).launch {
cardAccountRangeRepository.loading.collect {
withContext(Dispatchers.Main) {
isLoadingCallback(it)
}
}
}
}
override val accessibilityText: String
get() {
return resources.getString(R.string.acc_label_card_number_node, text)
}
override fun onDetachedFromWindow() {
loadingJob?.cancel()
loadingJob = null
accountRangeService.cancelAccountRangeRepositoryJob()
super.onDetachedFromWindow()
}
@JvmSynthetic
internal fun updateLengthFilter(maxLength: Int = formattedPanLength) {
filters = arrayOf<InputFilter>(InputFilter.LengthFilter(maxLength))
}
/**
* Updates the selection index based on the current (pre-edit) index, and
* the size change of the number being input.
*
* @param newFormattedLength the post-edit length of the string
* @param start the position in the string at which the edit action starts
* @param addedDigits the number of new characters going into the string (zero for
* delete)
* @param panLength the maximum normalized length of the PAN
* @return an index within the string at which to put the cursor
*/
@JvmSynthetic
internal fun calculateCursorPosition(
newFormattedLength: Int,
start: Int,
addedDigits: Int,
panLength: Int = this.panLength
): Int {
val gapSet = CardNumber.getSpacePositions(panLength)
val gapsJumped = gapSet.count { gap ->
start <= gap && start + addedDigits >= gap
}
val skipBack = gapSet.any { gap ->
// addedDigits can only be 0 if we are deleting,
// so we need to check whether or not to skip backwards one space
addedDigits == 0 && start == gap + 1
}
var newPosition = start + addedDigits + gapsJumped
if (skipBack && newPosition > 0) {
newPosition--
}
return if (newPosition <= newFormattedLength) {
newPosition
} else {
newFormattedLength
}
}
@JvmSynthetic
internal fun onCardMetadataLoadedTooSlow() {
analyticsRequestExecutor.executeAsync(
paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.CardMetadataLoadedTooSlow)
)
}
private inner class CardNumberTextWatcher : StripeTextWatcher() {
private var latestChangeStart: Int = 0
private var latestInsertionSize: Int = 0
private var newCursorPosition: Int? = null
private var formattedNumber: String? = null
private var beforeCardNumber = unvalidatedCardNumber
private var isPastedPan = false
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
isPastedPan = false
beforeCardNumber = unvalidatedCardNumber
latestChangeStart = start
latestInsertionSize = after
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val cardNumber = CardNumber.Unvalidated(s?.toString().orEmpty())
accountRangeService.onCardNumberChanged(cardNumber)
isPastedPan = isPastedPan(start, before, count, cardNumber)
if (isPastedPan) {
updateLengthFilter(cardNumber.getFormatted(cardNumber.length).length)
}
if (isPastedPan) {
cardNumber.length
} else {
panLength
}.let { maxPanLength ->
val formattedNumber = cardNumber.getFormatted(maxPanLength)
newCursorPosition = calculateCursorPosition(
formattedNumber.length,
latestChangeStart,
latestInsertionSize,
maxPanLength
)
this.formattedNumber = formattedNumber
}
}
override fun afterTextChanged(s: Editable?) {
if (shouldUpdateAfterChange) {
setTextSilent(formattedNumber)
newCursorPosition?.let {
setSelection(it.coerceIn(0, fieldText.length))
}
}
formattedNumber = null
newCursorPosition = null
if (unvalidatedCardNumber.length == panLength) {
val wasCardNumberValid = isCardNumberValid
isCardNumberValid = isValid
shouldShowError = !isValid
if (accountRangeService.accountRange == null && unvalidatedCardNumber.isValidLuhn) {
// a complete PAN was inputted before the card service returned results
onCardMetadataLoadedTooSlow()
}
if (isComplete(wasCardNumberValid)) {
completionCallback()
}
} else if (unvalidatedCardNumber.isPartialEntry(panLength) &&
!unvalidatedCardNumber.isPossibleCardBrand()
) {
// Partial card number entered and brand is not yet determine, but possible.
isCardNumberValid = isValid
shouldShowError = true
} else {
isCardNumberValid = isValid
// Don't show errors if we aren't full-length and the brand is known.
// TODO (michelleb-stripe) Should set error message to incomplete, then in focus change if it isn't complete it will update it.
shouldShowError = false
}
}
private val shouldUpdateAfterChange: Boolean
get() = (digitsAdded || !isLastKeyDelete) && formattedNumber != null
/**
* Have digits been added in this text change.
*/
private val digitsAdded: Boolean
get() = unvalidatedCardNumber.length > beforeCardNumber.length
/**
* If `true`, [completionCallback] will be invoked.
*/
private fun isComplete(
wasCardNumberValid: Boolean
) = !wasCardNumberValid && (
unvalidatedCardNumber.isMaxLength ||
(isValid && accountRangeService.accountRange != null)
)
/**
* The [currentCount] characters beginning at [startPosition] have just replaced old text
* that had length [previousCount]. If [currentCount] < [previousCount], digits were
* deleted.
*/
private fun isPastedPan(
startPosition: Int,
previousCount: Int,
currentCount: Int,
cardNumber: CardNumber.Unvalidated
): Boolean {
return currentCount > previousCount && startPosition == 0 &&
cardNumber.normalized.length >= CardNumber.MIN_PAN_LENGTH
}
}
}
| mit | a735e136049f9a4f414bef9df000678c | 33.863388 | 143 | 0.643887 | 5.356843 | false | false | false | false |
AndroidX/androidx | work/work-runtime/src/main/java/androidx/work/impl/model/WorkTypeConverters.kt | 3 | 9679 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.impl.model
import android.net.Uri
import android.os.Build
import androidx.room.TypeConverter
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.Constraints.ContentUriTrigger
import androidx.work.NetworkType
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkInfo
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.lang.IllegalArgumentException
/**
* TypeConverters for WorkManager enums and classes.
*/
object WorkTypeConverters {
/**
* Integer identifiers that map to [WorkInfo.State].
*/
object StateIds {
const val ENQUEUED = 0
const val RUNNING = 1
const val SUCCEEDED = 2
const val FAILED = 3
const val BLOCKED = 4
const val CANCELLED = 5
const val COMPLETED_STATES = "($SUCCEEDED, $FAILED, $CANCELLED)"
}
/**
* Integer identifiers that map to [BackoffPolicy].
*/
private object BackoffPolicyIds {
const val EXPONENTIAL = 0
const val LINEAR = 1
}
/**
* Integer identifiers that map to [NetworkType].
*/
private object NetworkTypeIds {
const val NOT_REQUIRED = 0
const val CONNECTED = 1
const val UNMETERED = 2
const val NOT_ROAMING = 3
const val METERED = 4
const val TEMPORARILY_UNMETERED = 5
}
/**
* Integer identifiers that map to [OutOfQuotaPolicy].
*/
private object OutOfPolicyIds {
const val RUN_AS_NON_EXPEDITED_WORK_REQUEST = 0
const val DROP_WORK_REQUEST = 1
}
/**
* TypeConverter for a State to an int.
*
* @param state The input State
* @return The associated int constant
*/
@JvmStatic
@TypeConverter
fun stateToInt(state: WorkInfo.State): Int {
return when (state) {
WorkInfo.State.ENQUEUED -> StateIds.ENQUEUED
WorkInfo.State.RUNNING -> StateIds.RUNNING
WorkInfo.State.SUCCEEDED -> StateIds.SUCCEEDED
WorkInfo.State.FAILED -> StateIds.FAILED
WorkInfo.State.BLOCKED -> StateIds.BLOCKED
WorkInfo.State.CANCELLED -> StateIds.CANCELLED
}
}
/**
* TypeConverter for an int to a State.
*
* @param value The input integer
* @return The associated State enum value
*/
@JvmStatic
@TypeConverter
fun intToState(value: Int): WorkInfo.State {
return when (value) {
StateIds.ENQUEUED -> WorkInfo.State.ENQUEUED
StateIds.RUNNING -> WorkInfo.State.RUNNING
StateIds.SUCCEEDED -> WorkInfo.State.SUCCEEDED
StateIds.FAILED -> WorkInfo.State.FAILED
StateIds.BLOCKED -> WorkInfo.State.BLOCKED
StateIds.CANCELLED -> WorkInfo.State.CANCELLED
else -> throw IllegalArgumentException("Could not convert $value to State")
}
}
/**
* TypeConverter for a BackoffPolicy to an int.
*
* @param backoffPolicy The input BackoffPolicy
* @return The associated int constant
*/
@JvmStatic
@TypeConverter
fun backoffPolicyToInt(backoffPolicy: BackoffPolicy): Int {
return when (backoffPolicy) {
BackoffPolicy.EXPONENTIAL -> BackoffPolicyIds.EXPONENTIAL
BackoffPolicy.LINEAR -> BackoffPolicyIds.LINEAR
}
}
/**
* TypeConverter for an int to a BackoffPolicy.
*
* @param value The input integer
* @return The associated BackoffPolicy enum value
*/
@JvmStatic
@TypeConverter
fun intToBackoffPolicy(value: Int): BackoffPolicy {
return when (value) {
BackoffPolicyIds.EXPONENTIAL -> BackoffPolicy.EXPONENTIAL
BackoffPolicyIds.LINEAR -> BackoffPolicy.LINEAR
else -> throw IllegalArgumentException("Could not convert $value to BackoffPolicy")
}
}
/**
* TypeConverter for a NetworkType to an int.
*
* @param networkType The input NetworkType
* @return The associated int constant
*/
@JvmStatic
@TypeConverter
fun networkTypeToInt(networkType: NetworkType): Int {
return when (networkType) {
NetworkType.NOT_REQUIRED -> NetworkTypeIds.NOT_REQUIRED
NetworkType.CONNECTED -> NetworkTypeIds.CONNECTED
NetworkType.UNMETERED -> NetworkTypeIds.UNMETERED
NetworkType.NOT_ROAMING -> NetworkTypeIds.NOT_ROAMING
NetworkType.METERED -> NetworkTypeIds.METERED
else -> {
if (Build.VERSION.SDK_INT >= 30 && networkType == NetworkType.TEMPORARILY_UNMETERED)
NetworkTypeIds.TEMPORARILY_UNMETERED
else
throw IllegalArgumentException("Could not convert $networkType to int")
}
}
}
/**
* TypeConverter for an int to a NetworkType.
*
* @param value The input integer
* @return The associated NetworkType enum value
*/
@JvmStatic
@TypeConverter
fun intToNetworkType(value: Int): NetworkType {
return when (value) {
NetworkTypeIds.NOT_REQUIRED -> NetworkType.NOT_REQUIRED
NetworkTypeIds.CONNECTED -> NetworkType.CONNECTED
NetworkTypeIds.UNMETERED -> NetworkType.UNMETERED
NetworkTypeIds.NOT_ROAMING -> NetworkType.NOT_ROAMING
NetworkTypeIds.METERED -> NetworkType.METERED
else -> {
if (Build.VERSION.SDK_INT >= 30 && value == NetworkTypeIds.TEMPORARILY_UNMETERED) {
return NetworkType.TEMPORARILY_UNMETERED
} else throw IllegalArgumentException("Could not convert $value to NetworkType")
}
}
}
/**
* Converts a [OutOfQuotaPolicy] to an int.
*
* @param policy The [OutOfQuotaPolicy] policy being used
* @return the corresponding int representation.
*/
@JvmStatic
@TypeConverter
fun outOfQuotaPolicyToInt(policy: OutOfQuotaPolicy): Int {
return when (policy) {
OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST ->
OutOfPolicyIds.RUN_AS_NON_EXPEDITED_WORK_REQUEST
OutOfQuotaPolicy.DROP_WORK_REQUEST -> OutOfPolicyIds.DROP_WORK_REQUEST
}
}
/**
* Converter from an int to a [OutOfQuotaPolicy].
*
* @param value The input integer
* @return An [OutOfQuotaPolicy]
*/
@JvmStatic
@TypeConverter
fun intToOutOfQuotaPolicy(value: Int): OutOfQuotaPolicy {
return when (value) {
OutOfPolicyIds.RUN_AS_NON_EXPEDITED_WORK_REQUEST ->
OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST
OutOfPolicyIds.DROP_WORK_REQUEST -> OutOfQuotaPolicy.DROP_WORK_REQUEST
else -> throw IllegalArgumentException("Could not convert $value to OutOfQuotaPolicy")
}
}
/**
* Converts a set of [Constraints.ContentUriTrigger]s to byte array representation
* @param triggers the list of [Constraints.ContentUriTrigger]s to convert
* @return corresponding byte array representation
*/
@JvmStatic
@TypeConverter
fun setOfTriggersToByteArray(triggers: Set<ContentUriTrigger>): ByteArray {
if (triggers.isEmpty()) {
return ByteArray(0)
}
val outputStream = ByteArrayOutputStream()
outputStream.use {
ObjectOutputStream(outputStream).use { objectOutputStream ->
objectOutputStream.writeInt(triggers.size)
for (trigger in triggers) {
objectOutputStream.writeUTF(trigger.uri.toString())
objectOutputStream.writeBoolean(trigger.isTriggeredForDescendants)
}
}
}
return outputStream.toByteArray()
}
/**
* Converts a byte array to set of [ContentUriTrigger]s
* @param bytes byte array representation to convert
* @return set of [ContentUriTrigger]
*/
@JvmStatic
@TypeConverter
fun byteArrayToSetOfTriggers(bytes: ByteArray): Set<ContentUriTrigger> {
val triggers = mutableSetOf<ContentUriTrigger>()
if (bytes.isEmpty()) {
// bytes will be null if there are no Content Uri Triggers
return triggers
}
val inputStream = ByteArrayInputStream(bytes)
inputStream.use {
try {
ObjectInputStream(inputStream).use { objectInputStream ->
repeat(objectInputStream.readInt()) {
val uri = Uri.parse(objectInputStream.readUTF())
val triggersForDescendants = objectInputStream.readBoolean()
triggers.add(ContentUriTrigger(uri, triggersForDescendants))
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
return triggers
}
} | apache-2.0 | b8e5dbaf2ab03fbaef2abaa4294d6fd1 | 33.326241 | 100 | 0.63519 | 4.895802 | false | false | false | false |
AndroidX/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentTestUtil.kt | 3 | 7086 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.RequiresApi
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.runOnUiThreadRethrow
import androidx.testutils.withActivity
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.lang.ref.WeakReference
fun FragmentTransaction.setReorderingAllowed(
reorderingAllowed: ReorderingAllowed
) = setReorderingAllowed(reorderingAllowed is Reordered)
sealed class ReorderingAllowed {
override fun toString(): String = this.javaClass.simpleName
}
object Reordered : ReorderingAllowed()
object Ordered : ReorderingAllowed()
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.executePendingTransactions(
fm: FragmentManager = activity.supportFragmentManager
): Boolean {
var ret = false
runOnUiThreadRethrow { ret = fm.executePendingTransactions() }
return ret
}
inline fun <reified A : FragmentActivity> ActivityScenario<A>.executePendingTransactions(
fm: FragmentManager = withActivity { supportFragmentManager }
) {
onActivity { fm.executePendingTransactions() }
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.popBackStackImmediate(): Boolean {
val instrumentation = InstrumentationRegistry.getInstrumentation()
var ret = false
instrumentation.runOnMainSync {
ret = activity.supportFragmentManager.popBackStackImmediate()
}
return ret
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.popBackStackImmediate(
id: Int,
flags: Int = 0
): Boolean {
val instrumentation = InstrumentationRegistry.getInstrumentation()
var ret = false
instrumentation.runOnMainSync {
ret = activity.supportFragmentManager.popBackStackImmediate(id, flags)
}
return ret
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.popBackStackImmediate(
name: String,
flags: Int = 0
): Boolean {
val instrumentation = InstrumentationRegistry.getInstrumentation()
var ret = false
instrumentation.runOnMainSync {
ret = activity.supportFragmentManager.popBackStackImmediate(name, flags)
}
return ret
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.setContentView(
@LayoutRes layoutId: Int
) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
instrumentation.runOnMainSync { activity.setContentView(layoutId) }
}
fun assertChildren(container: ViewGroup, vararg fragments: Fragment) {
val numFragments = fragments.size
assertWithMessage("There aren't the correct number of fragment Views in its container")
.that(container.childCount)
.isEqualTo(numFragments)
fragments.forEachIndexed { index, fragment ->
assertWithMessage("Wrong Fragment View order for [$index]")
.that(fragment.requireView())
.isSameInstanceAs(container.getChildAt(index))
}
}
@Suppress("DEPRECATION")
// Transition test methods start
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.findGreen(): View {
return activity.findViewById(R.id.greenSquare)
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.findBlue(): View {
return activity.findViewById(R.id.blueSquare)
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.findRed(): View? {
return activity.findViewById(R.id.redSquare)
}
val View.boundsOnScreen: Rect
get() {
val loc = IntArray(2)
getLocationOnScreen(loc)
return Rect(loc[0], loc[1], loc[0] + width, loc[1] + height)
}
data class TransitionVerificationInfo(
var epicenter: Rect? = null,
val exitingViews: MutableList<View> = mutableListOf(),
val enteringViews: MutableList<View> = mutableListOf()
)
fun TargetTracking.verifyAndClearTransition(block: TransitionVerificationInfo.() -> Unit) {
val (epicenter, exitingViews, enteringViews) = TransitionVerificationInfo().apply { block() }
assertThat(exitingTargets).containsExactlyElementsIn(exitingViews)
assertThat(enteringTargets).containsExactlyElementsIn(enteringViews)
if (epicenter == null) {
assertThat(capturedEpicenter).isNull()
} else {
assertThat(capturedEpicenter).isEqualTo(epicenter)
}
clearTargets()
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun verifyNoOtherTransitions(fragment: TransitionFragment) {
assertThat(fragment.enterTransition.enteringTargets).isEmpty()
assertThat(fragment.enterTransition.exitingTargets).isEmpty()
assertThat(fragment.exitTransition.enteringTargets).isEmpty()
assertThat(fragment.exitTransition.exitingTargets).isEmpty()
assertThat(fragment.reenterTransition.enteringTargets).isEmpty()
assertThat(fragment.reenterTransition.exitingTargets).isEmpty()
assertThat(fragment.returnTransition.enteringTargets).isEmpty()
assertThat(fragment.returnTransition.exitingTargets).isEmpty()
assertThat(fragment.sharedElementEnter.enteringTargets).isEmpty()
assertThat(fragment.sharedElementEnter.exitingTargets).isEmpty()
assertThat(fragment.sharedElementReturn.enteringTargets).isEmpty()
assertThat(fragment.sharedElementReturn.exitingTargets).isEmpty()
}
// Transition test methods end
/**
* Allocates until a garbage collection occurs.
*/
fun forceGC() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
// The following works on O+
Runtime.getRuntime().gc()
Runtime.getRuntime().gc()
Runtime.getRuntime().runFinalization()
} else {
// The following works on older versions
for (i in 0..1) {
// Use a random index in the list to detect the garbage collection each time because
// .get() may accidentally trigger a strong reference during collection.
val leak = ArrayList<WeakReference<ByteArray>>()
do {
val arr = WeakReference(ByteArray(100))
leak.add(arr)
} while (leak[(Math.random() * leak.size).toInt()].get() != null)
}
}
}
| apache-2.0 | 58c3a96aa63e5dd17d033c1dd9fd4fa9 | 35.153061 | 97 | 0.746966 | 4.677228 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/notifications/service/delegates/ExpoPresentationDelegate.kt | 2 | 9255 | package abi43_0_0.expo.modules.notifications.service.delegates
import android.app.NotificationManager
import android.content.Context
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcel
import android.provider.Settings
import android.service.notification.StatusBarNotification
import android.util.Log
import android.util.Pair
import androidx.core.app.NotificationManagerCompat
import expo.modules.notifications.notifications.enums.NotificationPriority
import expo.modules.notifications.notifications.model.Notification
import expo.modules.notifications.notifications.model.NotificationBehavior
import expo.modules.notifications.notifications.model.NotificationContent
import expo.modules.notifications.notifications.model.NotificationRequest
import abi43_0_0.expo.modules.notifications.notifications.presentation.builders.CategoryAwareNotificationBuilder
import abi43_0_0.expo.modules.notifications.notifications.presentation.builders.ExpoNotificationBuilder
import abi43_0_0.expo.modules.notifications.service.interfaces.PresentationDelegate
import org.json.JSONException
import org.json.JSONObject
import java.util.*
open class ExpoPresentationDelegate(
protected val context: Context
) : PresentationDelegate {
companion object {
protected const val ANDROID_NOTIFICATION_ID = 0
protected const val INTERNAL_IDENTIFIER_SCHEME = "expo-notifications"
protected const val INTERNAL_IDENTIFIER_AUTHORITY = "foreign_notifications"
protected const val INTERNAL_IDENTIFIER_TAG_KEY = "tag"
protected const val INTERNAL_IDENTIFIER_ID_KEY = "id"
/**
* Tries to parse given identifier as an internal foreign notification identifier
* created by us in [getInternalIdentifierKey].
*
* @param identifier String identifier of the notification
* @return Pair of (notification tag, notification id), if the identifier could be parsed. null otherwise.
*/
fun parseNotificationIdentifier(identifier: String): Pair<String?, Int>? {
try {
val parsedIdentifier = Uri.parse(identifier)
if (INTERNAL_IDENTIFIER_SCHEME == parsedIdentifier.scheme && INTERNAL_IDENTIFIER_AUTHORITY == parsedIdentifier.authority) {
val tag = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY)
val id = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_ID_KEY)!!.toInt()
return Pair(tag, id)
}
} catch (e: NullPointerException) {
Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e)
} catch (e: NumberFormatException) {
Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e)
} catch (e: UnsupportedOperationException) {
Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e)
}
return null
}
/**
* Creates an identifier for given [StatusBarNotification]. It's supposed to be parsable
* by [parseNotificationIdentifier].
*
* @param notification Notification to be identified
* @return String identifier
*/
protected fun getInternalIdentifierKey(notification: StatusBarNotification): String {
return with(Uri.parse("$INTERNAL_IDENTIFIER_SCHEME://$INTERNAL_IDENTIFIER_AUTHORITY").buildUpon()) {
notification.tag?.let {
this.appendQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY, it)
}
this.appendQueryParameter(INTERNAL_IDENTIFIER_ID_KEY, notification.id.toString())
this.toString()
}
}
}
/**
* Callback called to present the system UI for a notification.
*
* If the notification behavior is set to not show any alert,
* we (may) play a sound, but then bail out early. You cannot
* set badge count without showing a notification.
*/
override fun presentNotification(notification: Notification, behavior: NotificationBehavior?) {
if (behavior != null && !behavior.shouldShowAlert()) {
if (behavior.shouldPlaySound()) {
RingtoneManager.getRingtone(
context,
notification.notificationRequest.content.sound ?: Settings.System.DEFAULT_NOTIFICATION_URI
).play()
}
return
}
NotificationManagerCompat.from(context).notify(
notification.notificationRequest.identifier,
getNotifyId(notification.notificationRequest),
createNotification(notification, behavior)
)
}
protected open fun getNotifyId(request: NotificationRequest?): Int {
return ANDROID_NOTIFICATION_ID
}
/**
* Callback called to fetch a collection of currently displayed notifications.
*
* **Note:** This feature is only supported on Android 23+.
*
* @return A collection of currently displayed notifications.
*/
override fun getAllPresentedNotifications(): Collection<Notification> {
// getActiveNotifications() is not supported on platforms below Android 23
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return emptyList()
}
val notificationManager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
return notificationManager.activeNotifications.mapNotNull { getNotification(it) }
}
override fun dismissNotifications(identifiers: Collection<String>) {
identifiers.forEach { identifier ->
val foreignNotification = parseNotificationIdentifier(identifier)
if (foreignNotification != null) {
// Foreign notification identified by us
NotificationManagerCompat.from(context).cancel(foreignNotification.first, foreignNotification.second)
} else {
// If the notification exists, let's assume it's ours, we have no reason to believe otherwise
val existingNotification = this.getAllPresentedNotifications().find { it.notificationRequest.identifier == identifier }
NotificationManagerCompat.from(context).cancel(identifier, getNotifyId(existingNotification?.notificationRequest))
}
}
}
override fun dismissAllNotifications() = NotificationManagerCompat.from(context).cancelAll()
protected open fun createNotification(notification: Notification, notificationBehavior: NotificationBehavior?): android.app.Notification =
CategoryAwareNotificationBuilder(context, SharedPreferencesNotificationCategoriesStore(context)).also {
it.setNotification(notification)
it.setAllowedBehavior(notificationBehavior)
}.build()
protected open fun getNotification(statusBarNotification: StatusBarNotification): Notification? {
val notification = statusBarNotification.notification
notification.extras.getByteArray(ExpoNotificationBuilder.EXTRAS_MARSHALLED_NOTIFICATION_REQUEST_KEY)?.let {
try {
with(Parcel.obtain()) {
this.unmarshall(it, 0, it.size)
this.setDataPosition(0)
val request: NotificationRequest = NotificationRequest.CREATOR.createFromParcel(this)
this.recycle()
val notificationDate = Date(statusBarNotification.postTime)
return Notification(request, notificationDate)
}
} catch (e: Exception) {
// Let's catch all the exceptions -- there's nothing we can do here
// and we'd rather return an array with a single, naively reconstructed notification
// than throw an exception and return none.
val message = "Could not have unmarshalled NotificationRequest from (${statusBarNotification.tag}, ${statusBarNotification.id})."
Log.e("expo-notifications", message)
}
}
// We weren't able to reconstruct the notification from our data, which means
// it's either not our notification or we couldn't have unmarshaled it from
// the byte array. Let's do what we can.
val content = NotificationContent.Builder()
.setTitle(notification.extras.getString(android.app.Notification.EXTRA_TITLE))
.setText(notification.extras.getString(android.app.Notification.EXTRA_TEXT))
.setSubtitle(notification.extras.getString(android.app.Notification.EXTRA_SUB_TEXT)) // using deprecated field
.setPriority(NotificationPriority.fromNativeValue(notification.priority)) // using deprecated field
.setVibrationPattern(notification.vibrate) // using deprecated field
.setSound(notification.sound)
.setAutoDismiss(notification.flags and android.app.Notification.FLAG_AUTO_CANCEL != 0)
.setSticky(notification.flags and android.app.Notification.FLAG_ONGOING_EVENT != 0)
.setBody(fromBundle(notification.extras))
.build()
val request = NotificationRequest(getInternalIdentifierKey(statusBarNotification), content, null)
return Notification(request, Date(statusBarNotification.postTime))
}
protected open fun fromBundle(bundle: Bundle): JSONObject {
return JSONObject().also { json ->
for (key in bundle.keySet()) {
try {
json.put(key, JSONObject.wrap(bundle[key]))
} catch (e: JSONException) {
// can't do anything about it apart from logging it
Log.d("expo-notifications", "Error encountered while serializing Android notification extras: " + key + " -> " + bundle[key], e)
}
}
}
}
}
| bsd-3-clause | b44c500f0b7ba85edd206071f8699a0d | 45.507538 | 140 | 0.736899 | 4.9973 | false | false | false | false |
yechaoa/YUtils | yutilskt/src/main/java/com/yechaoa/yutilskt/SpUtil.kt | 1 | 2067 | package com.yechaoa.yutilskt
import android.content.Context
import android.content.SharedPreferences
/**
* Created by yechao on 2020/1/7.
* Describe : SpUtilKt
*
* GitHub : https://github.com/yechaoa
* CSDN : http://blog.csdn.net/yechaoa
*/
object SpUtil {
private const val FILE_NAME = "config"
private val sp: SharedPreferences = YUtils.getApp().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
/**
* String
*/
fun setString(key: String, value: String) {
sp.edit().putString(key, value).apply()
}
fun getString(key: String, defValue: String = ""): String {
return sp.getString(key, defValue)!!
}
/**
* StringSet
*/
fun setStringSet(key: String, value: Set<String>?) {
sp.edit().putStringSet(key, value).apply()
}
fun getStringSet(key: String): Set<String> {
return HashSet<String>(sp.getStringSet(key, HashSet<String>()))
}
/**
* Int
*/
fun setInt(key: String, value: Int) {
sp.edit().putInt(key, value).apply()
}
fun getInt(key: String, defValue: Int = 0): Int {
return sp.getInt(key, defValue)
}
/**
* Boolean
*/
fun setBoolean(key: String, value: Boolean) {
sp.edit().putBoolean(key, value).apply()
}
fun getBoolean(key: String, defValue: Boolean = false): Boolean {
return sp.getBoolean(key, defValue)
}
/**
* Float
*/
fun setFloat(key: String, value: Float) {
sp.edit().putFloat(key, value).apply()
}
fun getFloat(key: String, defValue: Float = 0f): Float {
return sp.getFloat(key, defValue)
}
/**
* Long
*/
fun setLong(key: String, value: Long) {
sp.edit().putLong(key, value).apply()
}
fun getLong(key: String, defValue: Long = 0): Long {
return sp.getLong(key, defValue)
}
/**
* Remove
*/
fun removeByKey(key: String) {
sp.edit().remove(key).apply()
}
fun removeAll() {
sp.edit().clear().apply()
}
} | apache-2.0 | eb83f12d86e54d3e91ce844a9d456ba9 | 21 | 109 | 0.575714 | 3.710952 | false | false | false | false |
TeamWizardry/LibrarianLib | testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/content/TestItem.kt | 1 | 6904 | package com.teamwizardry.librarianlib.testcore.content
import com.teamwizardry.librarianlib.core.util.append
import com.teamwizardry.librarianlib.testcore.TestModContentManager
import com.teamwizardry.librarianlib.testcore.TestModResourceManager
import com.teamwizardry.librarianlib.testcore.util.PlayerTestContext
import com.teamwizardry.librarianlib.testcore.content.impl.TestItemImpl
import com.teamwizardry.librarianlib.testcore.content.impl.TestItemModel
import com.teamwizardry.librarianlib.testcore.objects.TestObjectDslMarker
import com.teamwizardry.librarianlib.testcore.util.SidedAction
import net.devtech.arrp.json.models.JModel
import net.fabricmc.fabric.api.client.rendering.v1.ColorProviderRegistry
import net.minecraft.client.color.item.ItemColorProvider
import net.minecraft.entity.Entity
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.*
import net.minecraft.util.Hand
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.util.math.Vec3d
import net.minecraft.util.registry.Registry
import net.minecraft.world.World
/**
* The DSL for configuring an item
*/
@TestObjectDslMarker
public class TestItem(manager: TestModContentManager, id: Identifier): TestConfig(manager, id) {
/**
* The maximum stack size. Defaults to 1
*/
public var maxCount: Int = 1
set(value) {
field = value
properties.maxCount(value)
}
/**
* How long the right click and hold action should last in ticks. Setting this to a non-negative value will cause
* override the default behavior of returning one hour when either the [rightClickHold] or [rightClickRelease]
* actions are enabled
*/
public var rightClickHoldDuration: Int = -1
get() {
if (field < 0) {
if (rightClickHold.exists || rightClickRelease.exists)
return 3600 * 20
}
return field
}
/**
* The properties of the test item. Do not mutate this after this configuration has been passed to the [TestItemImpl]
* constructor.
*/
public val properties: Item.Settings = Item.Settings()
.group(manager.itemGroup)
.maxCount(maxCount)
/**
* Called when this item is right clicked.
*
* @see Item.onItemRightClick
* @see Item.onItemUse
* @see Item.itemInteractionForEntity
*/
public var rightClick: SidedAction<RightClickContext> = SidedAction()
/**
* Called when the item is right clicked in the air (i.e. not on a block or entity).
* @see Item.onItemRightClick
*/
public var rightClickAir: SidedAction<RightClickContext> = SidedAction()
/**
* Called when the item is right clicked on a block.
*
* @see Item.onItemUse
*/
public var rightClickBlock: SidedAction<RightClickBlockContext> = SidedAction()
/**
* Called each tick while the player is holding down the right mouse button.
*
* @see Item.onUsingTick
*/
public var rightClickHold: SidedAction<RightClickHoldContext> = SidedAction()
/**
* Called when the player releases the right mouse button.
*
* @see Item.onPlayerStoppedUsing
*/
public var rightClickRelease: SidedAction<RightClickReleaseContext> = SidedAction()
/**
* Called when this item is left-clicked on a block. If this callback exists the block will not be broken.
* @see Item.onBlockStartBreak
* @see BlockEvent.BreakEvent
*/
public var leftClickBlock: SidedAction<LeftClickBlockContext> = SidedAction()
/**
* Called when this item is left-clicked on an entity. If this callback exists the entity will not take damage.
* @see Item.onLeftClickEntity
*/
public var leftClickEntity: SidedAction<LeftClickEntityContext> = SidedAction()
/**
* Called when this item is right-clicked on an entity. If this callback exists the entity will not receive a
* click event.
*
* @see Item.itemInteractionForEntity
*/
public var rightClickEntity: SidedAction<RightClickEntityContext> = SidedAction()
/**
* Called each tick when the item is in the player's inventory.
*
* @see Item.inventoryTick
*/
public var inventoryTick: SidedAction<InventoryTickContext> = SidedAction()
/**
* Called each tick when the item is in the player's hand.
*
* @see Item.inventoryTick
*/
public var tickInHand: SidedAction<InventoryTickContext> = SidedAction()
public val instance: Item by lazy {
TestItemImpl(this)
}
public data class RightClickContext(val world: World, val player: PlayerEntity, val hand: Hand): PlayerTestContext(player) {
val stack: ItemStack = player.getStackInHand(hand)
}
public data class RightClickBlockContext(private val context: ItemUsageContext): PlayerTestContext(context.player!!) {
val stack: ItemStack = context.stack
val world: World = context.world
val player: PlayerEntity = context.player!!
val hand: Hand = context.hand
val side: Direction = context.side
val block: BlockPos = context.blockPos
val hitVec: Vec3d = context.hitPos
}
public data class RightClickHoldContext(val stack: ItemStack, val player: PlayerEntity, val timeLeft: Int): PlayerTestContext(player)
public data class RightClickReleaseContext(val stack: ItemStack, val world: World, val player: PlayerEntity, val timeLeft: Int): PlayerTestContext(player)
public data class LeftClickBlockContext(val stack: ItemStack, val pos: BlockPos, val player: PlayerEntity): PlayerTestContext(player)
public data class LeftClickEntityContext(val stack: ItemStack, val player: PlayerEntity, val entity: Entity): PlayerTestContext(player)
public data class RightClickEntityContext(val stack: ItemStack, val player: PlayerEntity, val target: LivingEntity, val hand: Hand): PlayerTestContext(player)
public data class InventoryTickContext(val stack: ItemStack, val world: World, val player: PlayerEntity, val itemSlot: Int, val isSelected: Boolean): PlayerTestContext(player)
override fun registerCommon(resources: TestModResourceManager) {
Registry.register(Registry.ITEM, id, instance)
resources.lang.item(id, name)
description?.lines()?.forEachIndexed { i, line ->
resources.lang.item(id.append(".tooltip.$i"), line)
}
}
override fun registerClient(resources: TestModResourceManager) {
val testModel = TestItemModel(id)
resources.arrp.addModel(
testModel.model,
Identifier(id.namespace, "item/${id.path}")
)
ColorProviderRegistry.ITEM.register(testModel.colorProvider, instance)
}
}
| lgpl-3.0 | a4b56accb39670828e14e87c4844bee4 | 38.00565 | 179 | 0.710747 | 4.439871 | false | true | false | false |
sebasjm/deepdiff | src/main/kotlin/diff/equality/strategies/LCSCollectionEqualityStrategy.kt | 1 | 2263 | package diff.equality.strategies
import diff.equality.EqualityStrategy
import diff.equality.LCSMatrix
import diff.equality.LongestCommonSubsequence
import diff.patch.Coordinate
import diff.patch.coords.ListCoordinates
import diff.patch.coords.RangeListCoordinates
import diff.patch.coords.RelativeCoordinates
/**
* Created by sebasjm on 09/03/18.
*/
class LCSCollectionEqualityStrategy : EqualityStrategy<List<Any>> {
val delegate = OrderedCollectionEqualityStrategy()
override fun compare(before: List<Any>, after: List<Any>): EqualityStrategy.CompareResult {
if (before.isEmpty() && after.isEmpty()) return EqualityStrategy.CompareResult.EQUALS
val result : MutableList<(parent: Coordinate<List<Any>, Any>) -> RelativeCoordinates<Any, List<Any>>> = ArrayList()
var atLeastOneIsDifferent = false
LongestCommonSubsequence<Any>()
.reduceAndSolve(before, after, object : LCSMatrix.Listener {
var bix = before.size
var aix = after.size
var bsz = 0
var asz = 0
fun reset(x: Int, y: Int) { bix = x; aix = y; bsz = 0; asz = 0 }
fun function(a:Int,b:Int,c:Int,d:Int) =
{ parent: Coordinate<List<Any>, Any> -> RangeListCoordinates(a,b,c,d, parent) as RelativeCoordinates<Any, List<Any>> }
override fun same(x: Int, y: Int) {
if (bsz > 0 || asz > 0) {
result.add(function(x+1,y+1,bsz,asz))
}
reset(x,y)
}
override fun add(x: Int) {
asz++
atLeastOneIsDifferent = true
}
override fun del(y: Int) {
bsz++
atLeastOneIsDifferent = true
}
})
return if (result.isEmpty()) {
if (atLeastOneIsDifferent) delegate.compare(before, after) else EqualityStrategy.CompareResult.EQUALS
} else {
EqualityStrategy.UndecidibleMoreToCompare(result)
}
}
override fun shouldUseThisStrategy(cls: Class<List<Any>>): Boolean {
return List::class.java.isAssignableFrom(cls)
}
}
| apache-2.0 | 385b105d5eac8318f3eb86e2203bbb22 | 35.5 | 138 | 0.586832 | 4.445972 | false | false | false | false |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/extensions/PreferenceExtensions.kt | 1 | 4022 | /*
* Copyright (c) 2018 52inc.
*
* 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.ftinc.kit.extensions
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
interface Preferences {
val sharedPreferences: SharedPreferences
abstract class Preference<T : Any?>(val key: String) : ReadWriteProperty<Preferences, T>
class StringPreference(key: String, private val default: String? = null) : Preference<String?>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): String? {
return thisRef.sharedPreferences.getString(key, default)
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: String?) {
thisRef.sharedPreferences.edit().putString(key, value).apply()
}
}
class IntPreference(key: String, private val default: Int = 0) : Preference<Int>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): Int {
return thisRef.sharedPreferences.getInt(key, default)
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: Int) {
thisRef.sharedPreferences.edit().putInt(key, value).apply()
}
}
class LongPreference(key: String, private val default: Long = 0) : Preference<Long>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): Long {
return thisRef.sharedPreferences.getLong(key, default)
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: Long) {
thisRef.sharedPreferences.edit().putLong(key, value).apply()
}
}
class BooleanPreference(key: String, private val default: Boolean = false) : Preference<Boolean>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): Boolean {
return thisRef.sharedPreferences.getBoolean(key, default)
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: Boolean) {
thisRef.sharedPreferences.edit().putBoolean(key, value).apply()
}
}
class StringSetPreference(key: String, private val default: Set<String> = HashSet()) : Preference<Set<String>>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): Set<String> {
return thisRef.sharedPreferences.getStringSet(key, default)
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: Set<String>) {
thisRef.sharedPreferences.edit().putStringSet(key, value).apply()
}
}
class CustomPreference<T>(
key: String,
private val getter: (String?) -> T?,
private val setter: (T?) -> String?
) : Preference<T?>(key) {
override fun getValue(thisRef: Preferences, property: KProperty<*>): T? {
return getter(thisRef.sharedPreferences.getString(key, null))
}
override fun setValue(thisRef: Preferences, property: KProperty<*>, value: T?) {
val item = setter(value)
if (item != null) {
thisRef.sharedPreferences.edit()
.putString(key, item)
.apply()
} else {
thisRef.sharedPreferences.edit()
.remove(key)
.apply()
}
}
}
}
| apache-2.0 | 05912b83a91c4392c9a112e693abc583 | 31.967213 | 121 | 0.637494 | 4.816766 | false | false | false | false |
wada811/RxViewModel | sample/src/main/kotlin/com/wada811/sample/viewmodel/MainViewModel.kt | 1 | 1155 | package com.wada811.sample.viewmodel
import android.util.Log
import com.wada811.rxviewmodel.RxViewModel
import com.wada811.rxviewmodel.commands.toRxCommand
import com.wada811.rxviewmodel.messages.RxMessenger
import com.wada811.rxviewmodel.properties.RxProperty
import com.wada811.rxviewmodel.properties.toReadOnlyRxProperty
import com.wada811.sample.view.activity.MainActivity
import io.reactivex.subjects.BehaviorSubject
class MainViewModel : RxViewModel() {
val observable: BehaviorSubject<String> = BehaviorSubject.createDefault("world")
val name = RxProperty<String>(observable, observable.value).asManaged()
val helloCommand = name.toObservable().map { it != "" }.toRxCommand<Unit>().asManaged()
val helloName = name.toObservable().map { "Hello, $it!" }.toReadOnlyRxProperty("Hello, ${name.value}!").asManaged()
init {
helloCommand.toObservable()
.subscribe({
RxMessenger.send(MainActivity.ToastAction(helloName.value))
}, {
Log.e("RxViewModel", "onError")
}, {
Log.i("RxViewModel", "onComplete")
}).asManaged()
}
} | apache-2.0 | 1038239c259f67802bfab1a1f2c76d5f | 40.285714 | 119 | 0.702165 | 4.02439 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/kotlin/builder/tasks/jvm/JdepsParser.kt | 1 | 3844 | /*
* Copyright 2018 The Bazel Authors. 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 io.bazel.kotlin.builder.tasks.jvm
import com.google.devtools.build.lib.view.proto.Deps
import java.nio.file.Path
import java.nio.file.Paths
import java.util.HashMap
import java.util.function.Predicate
internal class JdepsParser private constructor(
private val isImplicit: Predicate<String>,
) {
private val depMap = HashMap<String, Deps.Dependency.Builder>()
private val moduleDeps = HashMap<String, MutableList<String>>()
private val arrowRegex = " -> ".toRegex()
private fun consumeJarLine(classJarPath: String, kind: Deps.Dependency.Kind) {
// ignore absolute files, -- jdk jar paths etc.
// only process jar files
if (classJarPath.endsWith(".jar")) {
val entry = depMap.computeIfAbsent(classJarPath) {
val depBuilder = Deps.Dependency.newBuilder()
depBuilder.path = classJarPath
depBuilder.kind = kind
if (isImplicit.test(classJarPath)) {
depBuilder.kind = Deps.Dependency.Kind.IMPLICIT
}
depBuilder
}
// don't flip an implicit dep.
if (entry.kind != Deps.Dependency.Kind.IMPLICIT) {
entry.kind = kind
}
}
}
private fun addModuleDependency(module: String, jarFile: String) {
val entry = moduleDeps.computeIfAbsent(module) {
mutableListOf<String>()
}
entry.add(jarFile)
}
private fun processLine(line: String) {
val parts = line.split(arrowRegex).dropLastWhile { it.isEmpty() }.toTypedArray()
if (parts.size == 2 && parts[1].endsWith(".jar")) {
addModuleDependency(parts[0], parts[1])
}
}
private fun markFromEntry(entry: String, kind: Deps.Dependency.Kind) {
moduleDeps[entry]?.forEach { jarPath ->
val dependency = depMap[jarPath]
if (dependency != null) {
if (dependency.kind == Deps.Dependency.Kind.UNUSED) {
dependency.kind = kind
val jarFile = Paths.get(jarPath).getFileName().toString()
markFromEntry(jarFile, Deps.Dependency.Kind.IMPLICIT)
}
}
}
}
companion object {
fun pathSuffixMatchingPredicate(directory: Path, vararg jars: String): Predicate<String> {
val suffixes = jars.map { directory.resolve(it).toString() }
return Predicate { jar ->
for (implicitJarsEnding in suffixes) {
if (jar.endsWith(implicitJarsEnding)) {
return@Predicate true
}
}
false
}
}
fun parse(
label: String,
jarFile: String,
classPath: MutableList<String>,
lines: List<String>,
isImplicit: Predicate<String>,
): Deps.Dependencies {
val filename = Paths.get(jarFile).fileName.toString()
val jdepsParser = JdepsParser(isImplicit)
classPath.forEach { x -> jdepsParser.consumeJarLine(x, Deps.Dependency.Kind.UNUSED) }
lines.forEach { jdepsParser.processLine(it) }
jdepsParser.markFromEntry(filename, Deps.Dependency.Kind.EXPLICIT)
val rootBuilder = Deps.Dependencies.newBuilder()
rootBuilder.success = false
rootBuilder.ruleLabel = label
jdepsParser.depMap.values.forEach { b -> rootBuilder.addDependency(b.build()) }
rootBuilder.success = true
return rootBuilder.build()
}
}
}
| apache-2.0 | b3c75816e1bd85bc707c5d8ca07b3bd3 | 32.426087 | 94 | 0.672997 | 4.151188 | false | false | false | false |
ironjan/MensaUPB | app/src/main/java/de/ironjan/mensaupb/app_info/AboutFragment.kt | 1 | 2399 | package de.ironjan.mensaupb.app_info
import android.support.v4.app.Fragment
import android.support.v4.text.HtmlCompat
import android.support.v4.text.HtmlCompat.FROM_HTML_MODE_COMPACT
import android.support.v7.app.AppCompatActivity
import android.text.method.LinkMovementMethod
import android.widget.TextView
import de.ironjan.mensaupb.BuildConfig
import de.ironjan.mensaupb.R
import org.androidannotations.annotations.AfterViews
import org.androidannotations.annotations.EFragment
import org.androidannotations.annotations.ViewById
import org.slf4j.LoggerFactory
/**
* Fragment with some information about the app.
*/
@EFragment(R.layout.fragment_about)
open class AboutFragment : Fragment() {
private val LOGGER = LoggerFactory.getLogger(javaClass.simpleName)
@ViewById(R.id.txtDependencies)
internal lateinit var mTxtDependencies: TextView
@ViewById(R.id.txtAbout)
internal lateinit var mTxtAbout: TextView
@ViewById(R.id.txtDependencyNames)
internal lateinit var mTxtDependencyNames: TextView
@ViewById(R.id.textSource)
internal lateinit var mTextSourceLink: TextView
@AfterViews
internal fun linkify() {
val nonNullActivity = activity ?: return
val movementMethod = LinkMovementMethod.getInstance()
mTxtAbout.text = HtmlCompat.fromHtml(nonNullActivity.getString(R.string.aboutText), FROM_HTML_MODE_COMPACT)
mTxtDependencyNames.text = HtmlCompat.fromHtml(nonNullActivity.getString(R.string.dependencyNames), FROM_HTML_MODE_COMPACT)
mTxtDependencies.text = HtmlCompat.fromHtml(nonNullActivity.getString(R.string.dependencies), FROM_HTML_MODE_COMPACT)
mTextSourceLink.text = HtmlCompat.fromHtml(nonNullActivity.getString(R.string.source), FROM_HTML_MODE_COMPACT)
mTxtAbout.movementMethod = movementMethod
mTxtDependencyNames.movementMethod = movementMethod
mTxtDependencies.movementMethod = movementMethod
mTextSourceLink.movementMethod = movementMethod
if (BuildConfig.DEBUG) LOGGER.debug("linkify() done")
}
@AfterViews
internal fun bindVersion() {
val activity = activity as AppCompatActivity? ?: return
val actionBar = activity.supportActionBar ?: return
val app_name = resources.getString(R.string.app_name)
val title = app_name + " " + BuildConfig.VERSION_NAME
actionBar.title = title
}
}
| apache-2.0 | 358584b5ee7d7518a5376a952ab59ee3 | 37.079365 | 131 | 0.762401 | 4.283929 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/model/entity/anilist/user/UserStatistics.kt | 1 | 2284 | /*
* Copyright (C) 2019 AniTrend
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.mxt.anitrend.model.entity.anilist.user
import com.mxt.anitrend.model.entity.anilist.user.statistics.*
/** [UserStatistics](https://anilist.github.io/ApiV2-GraphQL-Docs/UserStatistics.doc.html)
*
* @param chaptersRead TBA
* @param count TBA
* @param countries TBA
* @param episodesWatched TBA
* @param formats TBA
* @param genres TBA
* @param lengths TBA
* @param meanScore TBA
* @param minutesWatched TBA
* @param releaseYears TBA
* @param scores TBA
* @param staff TBA
* @param standardDeviation TBA
* @param startYears TBA
* @param statuses TBA
* @param studios TBA
* @param tags TBA
* @param voiceActors TBA
* @param volumesRead TBA
*/
data class UserStatistics(
val chaptersRead: Int = 0,
val count: Int = 0,
val countries: List<UserCountryStatistic>?,
val episodesWatched: Int = 0,
val formats: List<UserFormatStatistic>?,
val genres: List<UserGenreStatistic>?,
val lengths: List<UserLengthStatistic>?,
val meanScore: Float = 0f,
val minutesWatched: Int = 0,
val releaseYears: List<UserReleaseYearStatistic>?,
val scores: List<UserScoreStatistic>?,
val staff: List<UserStaffStatistic>?,
val standardDeviation: Float = 0f,
val startYears: List<UserStartYearStatistic>?,
val statuses: List<UserStatusStatistic>?,
val studios: List<UserStudioStatistic>?,
val tags: List<UserTagStatistic>?,
val voiceActors: List<UserVoiceActorStatistic>?,
val volumesRead: Int = 0
) | lgpl-3.0 | b5a81cb4d57bdab23d725ec4a990f7ac | 34.703125 | 90 | 0.689142 | 3.931153 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/card/Card.kt | 1 | 4760 | package de.tum.`in`.tumcampusapp.component.ui.overview.card
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.Editor
import android.preference.PreferenceManager
import androidx.recyclerview.widget.DiffUtil
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.navigation.NavDestination
import de.tum.`in`.tumcampusapp.utils.Const.CARD_POSITION_PREFERENCE_SUFFIX
import de.tum.`in`.tumcampusapp.utils.Const.DISCARD_SETTINGS_START
import de.tum.`in`.tumcampusapp.utils.Utils
/**
* Base class for all cards
* @param cardType Individual integer for each card type
* @param context Android Context
* @param settingsPrefix Preference key prefix used for all preferences belonging to that card
*/
abstract class Card(
val cardType: Int,
protected var context: Context,
val settingsPrefix: String = ""
) : Comparable<Card> {
// Settings for showing this card on start page or as notification
private var showStart = Utils.getSettingBool(context, settingsPrefix + "_start", true)
open fun getId(): Int {
return 0
}
/**
* Tells the list adapter and indirectly the SwipeDismissList if the item is dismissible.
* E.g.: The restore card is not dismissible.
*/
open val isDismissible: Boolean
get() = true
/**
* The options menu that should be inflated when the user presses the options icon in a card.
*/
open val optionsMenuResId: Int
get() = R.menu.card_popup_menu_no_settings
open var position: Int
get() =
Utils.getSettingInt(context, "${this.javaClass.simpleName}$CARD_POSITION_PREFERENCE_SUFFIX", -1)
set(position) =
Utils.setSetting(context, "${this.javaClass.simpleName}$CARD_POSITION_PREFERENCE_SUFFIX", position)
/**
* Returns the [NavDestination] when the card is clicked, or null if nothing should happen
*/
open fun getNavigationDestination(): NavDestination? {
return null
}
/**
* Updates the Cards content.
* Override this method, if the card contains any dynamic content, that is not already in its XML
*
* @param viewHolder The Card specific view holder
*/
open fun updateViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
context = viewHolder.itemView.context
}
/**
* Should be called after the user has dismissed the card
*/
fun discard() {
val prefs = context.getSharedPreferences(DISCARD_SETTINGS_START, 0)
val editor = prefs.edit()
discard(editor)
editor.apply()
}
/**
* Returns the Card if it should be displayed in the overview screen or null otherwise.
*
* @return The Card to be displayed or null
*/
open fun getIfShowOnStart(): Card? {
if (showStart) {
val prefs = context.getSharedPreferences(DISCARD_SETTINGS_START, 0)
if (shouldShow(prefs)) {
return this
}
}
return null
}
/**
* Determines if the card should be shown. Decision is based on the given SharedPreferences.
* This method should be overridden in most cases.
*
* @return returns true if the card should be shown
*/
protected open fun shouldShow(prefs: SharedPreferences): Boolean {
return true
}
/**
* Sets preferences so that this card does not show up again until
* reactivated manually by the user
*/
open fun hideAlways() {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val e = prefs.edit()
e.putBoolean(settingsPrefix + "_start", false)
e.putBoolean(settingsPrefix + "_phone", false)
e.apply()
}
override fun compareTo(other: Card): Int {
return Integer.compare(position, other.position)
}
/**
* Save information about the dismissed card/notification to decide later if the cardView should be shown again
*
* @param editor Editor to be used for saving values
*/
protected abstract fun discard(editor: Editor)
class DiffCallback(
private val oldList: List<Card>,
private val newList: List<Card>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldList[oldItemPosition].cardType == newList[newItemPosition].cardType
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldList[oldItemPosition] == newList[newItemPosition]
}
}
| gpl-3.0 | c7af01e1ab53415919f767b45c3a8cc3 | 32.521127 | 115 | 0.671639 | 4.741036 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/log/MarkLogicErrorLogLine.kt | 1 | 4267 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.log
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType
import uk.co.reecedunn.intellij.plugin.processor.log.LogFileContentType
import uk.co.reecedunn.intellij.plugin.processor.log.LogLine
abstract class MarkLogicErrorLogLine(
val date: String,
val time: String,
override val logLevel: String,
val appServer: String?,
val continuation: Boolean
) : LogLine {
val contentType: ConsoleViewContentType
get() = when (logLevel) {
"Finest" -> LogFileContentType.FINEST
"Finer" -> LogFileContentType.FINER
"Fine" -> LogFileContentType.FINE
"Debug" -> LogFileContentType.DEBUG
"Config" -> LogFileContentType.CONFIG
"Info" -> LogFileContentType.INFO
"Notice" -> LogFileContentType.NOTICE
"Warning" -> LogFileContentType.WARNING
"Error" -> LogFileContentType.ERROR
"Critical" -> LogFileContentType.CRITICAL
"Alert" -> LogFileContentType.ALERT
"Emergency" -> LogFileContentType.EMERGENCY
else -> ConsoleViewContentType.NORMAL_OUTPUT
}
override fun print(consoleView: ConsoleView) {
consoleView.print("$date $time ", LogFileContentType.DATE_TIME)
val separator = if (continuation) '+' else ' '
when (appServer) {
null -> consoleView.print("$logLevel:$separator$message", contentType)
else -> consoleView.print("$logLevel:$separator$appServer: $message", contentType)
}
}
companion object {
@Suppress("RegExpAnonymousGroup", "RegExpRepeatedSpace")
private val LOG_LINE_RE = """^
([0-9\\-]+) # 1: Date
\s #
([0-9:.]+) # 2: Time
\s #
([A-Za-z]+): # 3: Log Level
(\s([a-zA-Z0-9\-_]+):)? # 5: application server name
([\s+]) # 6: MarkLogic 9.0 continuation
(.*) # 7: Message
${'$'}""".toRegex(RegexOption.COMMENTS)
@Suppress("RegExpRepeatedSpace")
private val EXCEPTION_LOCATION_RE = """^
in\s #
([^ ,]+) # 1: Exception Path
,\sat\s #
([0-9]+) # 2: Line
: #
([0-9]+) # 3: Column
(\s\[([0-9.\-ml]+)])? # 5: XQuery Version
${'$'}""".toRegex(RegexOption.COMMENTS)
fun parse(line: String): Any {
val groups = LOG_LINE_RE.find(line)?.groupValues ?: return line
return when (val exception = EXCEPTION_LOCATION_RE.find(groups[7])?.groupValues) {
null -> MarkLogicErrorLogMessage(
groups[1],
groups[2],
groups[3],
groups[5].takeIf { it.isNotEmpty() },
groups[6] == "+",
groups[7]
)
else -> MarkLogicErrorLogExceptionLocation(
groups[1],
groups[2],
groups[3],
groups[5].takeIf { it.isNotEmpty() },
groups[6] == "+",
exception[1],
exception[2].toInt(),
exception[3].toInt(),
exception[5].takeIf { it.isNotEmpty() }
)
}
}
}
}
| apache-2.0 | 3786eb278c3135d9493c1a77c7b3c4b9 | 38.878505 | 94 | 0.52285 | 4.673604 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/androidTest/java/com/habitrpg/android/habitica/ui/fragments/PartyDetailFragmentTest.kt | 1 | 2515 | package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.FragmentPartyDetailBinding
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.fragments.social.party.PartyDetailFragment
import com.habitrpg.android.habitica.ui.viewmodels.PartyViewModel
import io.github.kakaocup.kakao.common.views.KView
import io.github.kakaocup.kakao.image.KImageView
import io.github.kakaocup.kakao.screen.Screen
import io.github.kakaocup.kakao.text.KButton
import io.github.kakaocup.kakao.text.KTextView
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.reactivex.rxjava3.core.Flowable
import org.junit.Test
import org.junit.runner.RunWith
class PartyDetailScreen : Screen<PartyDetailScreen>() {
val titleView = KTextView { withId(R.id.title_view) }
val newQuestButton = KButton { withId(R.id.new_quest_button) }
val questDetailButton = KButton { withId(R.id.quest_detail_button) }
val questImageWrtapper = KImageView { withId(R.id.quest_image_view) }
val questProgressView = KView { withId(R.id.quest_progress_view) }
}
@LargeTest
@RunWith(AndroidJUnit4::class)
class PartyDetailFragmentTest : FragmentTestCase<PartyDetailFragment, FragmentPartyDetailBinding, PartyDetailScreen>() {
private lateinit var viewModel: PartyViewModel
override val screen = PartyDetailScreen()
override fun makeFragment() {
val group = Group()
group.name = "Group Name"
every { socialRepository.getGroup(any()) } returns Flowable.just(group)
viewModel = PartyViewModel(false)
viewModel.socialRepository = socialRepository
viewModel.userRepository = userRepository
viewModel.userViewModel = userViewModel
viewModel.notificationsManager = mockk(relaxed = true)
fragment = spyk()
fragment.shouldInitializeComponent = false
fragment.viewModel = viewModel
}
override fun launchFragment(args: Bundle?) {
scenario = launchFragmentInContainer(args, R.style.MainAppTheme) {
return@launchFragmentInContainer fragment
}
}
@Test
fun displaysParty() {
viewModel.setGroupID("")
screen {
titleView.hasText("Group Name")
}
}
}
| gpl-3.0 | 151bcf697687ccafb253f9b3c4eb1d32 | 37.692308 | 120 | 0.753479 | 4.313894 | false | true | false | false |
hitoshura25/Media-Player-Omega-Android | search_presentation/src/main/java/com/vmenon/mpo/search/presentation/adapter/ShowSearchResultsAdapter.kt | 1 | 2153 | package com.vmenon.mpo.search.presentation.adapter
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.vmenon.mpo.search.presentation.databinding.ShowResultBinding
import com.vmenon.mpo.search.domain.ShowSearchResultModel
class ShowSearchResultsAdapter :
RecyclerView.Adapter<ShowSearchResultsAdapter.ViewHolder>() {
private var listener: ShowSelectedListener? = null
private val shows = ArrayList<ShowSearchResultModel>()
interface ShowSelectedListener {
fun onShowSelected(show: ShowSearchResultModel)
}
class ViewHolder(binding: ShowResultBinding) : RecyclerView.ViewHolder(binding.root) {
val nameText: TextView = binding.showName
val imageView: ImageView = binding.showImage
}
fun setListener(listener: ShowSelectedListener) {
this.listener = listener
}
fun update(searchResults: List<ShowSearchResultModel>, diffResult: DiffUtil.DiffResult) {
this.shows.clear()
this.shows.addAll(searchResults)
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ShowResultBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val show = shows[position]
holder.nameText.text = show.name
Glide.with(holder.itemView.context)
.load(show.artworkUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.centerCrop()
.into(holder.imageView)
holder.itemView.setOnClickListener {
listener?.onShowSelected(shows[position])
}
}
override fun getItemCount(): Int {
return shows.size
}
}
| apache-2.0 | 164cd281d7855ffcb7770a0e5d1f0fd7 | 31.134328 | 93 | 0.714817 | 4.949425 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/MissingChapters.kt | 1 | 2596 | package eu.kanade.tachiyomi.ui.reader.viewer
import eu.kanade.domain.chapter.model.Chapter
import eu.kanade.tachiyomi.data.database.models.toDomainChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import kotlin.math.floor
private val pattern = Regex("""\d+""")
fun hasMissingChapters(higherReaderChapter: ReaderChapter?, lowerReaderChapter: ReaderChapter?): Boolean {
if (higherReaderChapter == null || lowerReaderChapter == null) return false
return hasMissingChapters(higherReaderChapter.chapter.toDomainChapter(), lowerReaderChapter.chapter.toDomainChapter())
}
fun hasMissingChapters(higherChapter: Chapter?, lowerChapter: Chapter?): Boolean {
if (higherChapter == null || lowerChapter == null) return false
// Check if name contains a number that is potential chapter number
if (!pattern.containsMatchIn(higherChapter.name) || !pattern.containsMatchIn(lowerChapter.name)) return false
// Check if potential chapter number was recognized as chapter number
if (!higherChapter.isRecognizedNumber || !lowerChapter.isRecognizedNumber) return false
return hasMissingChapters(higherChapter.chapterNumber, lowerChapter.chapterNumber)
}
fun hasMissingChapters(higherChapterNumber: Float, lowerChapterNumber: Float): Boolean {
if (higherChapterNumber < 0f || lowerChapterNumber < 0f) return false
return calculateChapterDifference(higherChapterNumber, lowerChapterNumber) > 0f
}
fun calculateChapterDifference(higherReaderChapter: ReaderChapter?, lowerReaderChapter: ReaderChapter?): Float {
if (higherReaderChapter == null || lowerReaderChapter == null) return 0f
return calculateChapterDifference(higherReaderChapter.chapter.toDomainChapter(), lowerReaderChapter.chapter.toDomainChapter())
}
fun calculateChapterDifference(higherChapter: Chapter?, lowerChapter: Chapter?): Float {
if (higherChapter == null || lowerChapter == null) return 0f
// Check if name contains a number that is potential chapter number
if (!pattern.containsMatchIn(higherChapter.name) || !pattern.containsMatchIn(lowerChapter.name)) return 0f
// Check if potential chapter number was recognized as chapter number
if (!higherChapter.isRecognizedNumber || !lowerChapter.isRecognizedNumber) return 0f
return calculateChapterDifference(higherChapter.chapterNumber, lowerChapter.chapterNumber)
}
fun calculateChapterDifference(higherChapterNumber: Float, lowerChapterNumber: Float): Float {
if (higherChapterNumber < 0f || lowerChapterNumber < 0f) return 0f
return floor(higherChapterNumber) - floor(lowerChapterNumber) - 1f
}
| apache-2.0 | 150cfcc62e6f60046ca2635e378b4235 | 55.434783 | 130 | 0.794684 | 4.538462 | false | false | false | false |
pambrose/prometheus-proxy | src/main/kotlin/io/prometheus/proxy/ChunkedContext.kt | 1 | 2107 | /*
* Copyright © 2020 Paul Ambrose ([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.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.proxy
import io.prometheus.common.ScrapeResults
import io.prometheus.grpc.ChunkedScrapeResponse
import java.io.ByteArrayOutputStream
import java.util.zip.CRC32
internal class ChunkedContext(response: ChunkedScrapeResponse) {
private val checksum = CRC32()
private val baos = ByteArrayOutputStream()
var totalChunkCount = 0
private set
var totalByteCount = 0
private set
val scrapeResults =
response.header.run {
ScrapeResults(
validResponse = headerValidResponse,
scrapeId = headerScrapeId,
agentId = headerAgentId,
statusCode = headerStatusCode,
zipped = true,
failureReason = headerFailureReason,
url = headerUrl,
contentType = headerContentType
)
}
fun applyChunk(data: ByteArray, chunkByteCount: Int, chunkCount: Int, chunkChecksum: Long) {
totalChunkCount++
totalByteCount += chunkByteCount
checksum.update(data, 0, data.size)
baos.write(data, 0, chunkByteCount)
check(totalChunkCount == chunkCount)
check(checksum.value == chunkChecksum)
}
fun applySummary(summaryChunkCount: Int, summaryByteCount: Int, summaryChecksum: Long) {
check(totalChunkCount == summaryChunkCount)
check(totalByteCount == summaryByteCount)
check(checksum.value == summaryChecksum)
baos.flush()
scrapeResults.contentAsZipped = baos.toByteArray()
}
} | apache-2.0 | e9124e44dccd381b6ada5caacc7e7bca | 30.447761 | 94 | 0.72887 | 4.509636 | false | false | false | false |
santoslucas/guarda-filme-android | app/src/test/java/com/guardafilme/ui/welcome/WelcomePresenterTest.kt | 1 | 2920 | package com.guardafilme.ui.welcome
import com.guardafilme.data.UserRepository
import com.guardafilme.model.WatchedMovie
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.Assert.assertThat
import org.mockito.*
import org.hamcrest.core.IsEqual.equalTo
import org.mockito.Mockito.*
/**
* Created by lucassantos on 03/11/17.
*/
class WelcomePresenterTest {
lateinit var showWatchedMoviesArgumentCaptor: ArgumentCaptor<List<WatchedMovie>>
@Mock
lateinit var userRepository: UserRepository
@Mock
lateinit var welcomeView: WelcomeContract.View
lateinit var welcomePresenter: WelcomePresenter
private fun <T> anyObject(): T {
return Mockito.any<T>()
}
lateinit var watchedMovies: List<WatchedMovie>
inline fun <reified T : Any> argumentCaptor() = ArgumentCaptor.forClass(T::class.java)
@Before
fun setupWelcomePresenter() {
MockitoAnnotations.initMocks(this)
showWatchedMoviesArgumentCaptor = argumentCaptor<List<WatchedMovie>>()
watchedMovies = mutableListOf(
WatchedMovie("1", 1, "Teste 1", "Teste 1", 12345),
WatchedMovie("2", 2, "Teste 2", "Teste 2", 12345),
WatchedMovie("3", 3, "Teste 3", "Teste 3", 12345)
)
Mockito.`when`(userRepository.getWatchedMovies(anyObject())).thenAnswer { invocation ->
val listener: (List<WatchedMovie>) -> Unit = invocation.arguments[0] as (List<WatchedMovie>) -> Unit
listener.invoke(watchedMovies)
}
welcomePresenter = WelcomePresenter(userRepository)
welcomePresenter.attach(welcomeView)
}
@Test
fun loadMovies_shouldWorkCorrectly() {
welcomePresenter.load()
// verifica se coloca o loadingView
verify(welcomeView).showLoading()
// verifica se a view recebe a quantidade certa de filmes
verify(welcomeView).addWatchedMovies(showWatchedMoviesArgumentCaptor.capture())
assertThat(showWatchedMoviesArgumentCaptor.value.size, equalTo(3))
// verifica se scrolla para o início da lista
verify(welcomeView).scrollToTop()
// verifica se o loading foi tirado
verify(welcomeView).hideLoading()
verify(welcomeView).hideTooltip()
verify(welcomeView).showMoviesList()
}
@Test
fun loadMoviesWhenEmptyList_shouldShowTooltip() {
watchedMovies = emptyList()
welcomePresenter.load()
// verifica se coloca o loadingView
verify(welcomeView).showLoading()
// verifica se o loading foi tirado e tooltip exibido
verify(welcomeView).hideLoading()
verify(welcomeView).hideMoviesList()
verify(welcomeView).showTooltip()
}
@Test
fun clickOnAddMovie_shouldShowSearchMovieUi() {
welcomePresenter.addMovie()
verify(welcomeView).showAddMovie()
}
} | gpl-3.0 | 1710636da139fc41172e2cf21ebe80e6 | 28.494949 | 112 | 0.682425 | 4.409366 | false | true | false | false |
Tandrial/Advent_of_Code | src/aoc2017/kot/Day25.kt | 1 | 1476 | package aoc2017.kot
import getNumbers
import getWords
import java.io.File
object Day25 {
data class Rule(val write: Int, val move: Int, val nextState: String)
fun solve(input: List<String>): Int {
val rules = mutableMapOf<Pair<String, Int>, Rule>()
val rulesText = input.drop(3)
for ((idx, line) in rulesText.withIndex()) {
if (line.contains("In state ")) {
val words = line.dropLast(1).split(" ")
val state = words.last()
for (value in 0..1) {
val values = generateSequence(idx + 2 + value * 4) { it + 1 }.take(3).map { rulesText[it].dropLast(1).split(" ").last() }.toList()
val write = values[0].toInt()
val move = if (values[1] == "right") 1 else -1
val nextState = values[2]
rules[Pair(state, value)] = Rule(write, move, nextState)
}
}
}
val checkAfter = input[1].getNumbers().first()
var currState = input[0].getWords().last()
val tape = mutableListOf(0)
var pos = 0
repeat(checkAfter) {
val rule = rules[Pair(currState, tape[pos])]!!
tape[pos] = rule.write
pos += rule.move
if (pos < 0) {
tape.add(0, 0)
pos = 0
} else if (pos >= tape.size) {
tape.add(0)
}
currState = rule.nextState
}
return tape.sum()
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day25_input.txt").readLines()
println("Part One = ${Day25.solve(input)}")
}
| mit | 951ed4c37a32f5d0a2c7ae00bb4757e8 | 26.333333 | 140 | 0.572493 | 3.385321 | false | false | false | false |
Hexworks/zircon | zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DBorderTransformer.kt | 1 | 3740 | package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.Border
import org.hexworks.zircon.api.modifier.BorderPosition.*
import org.hexworks.zircon.api.modifier.BorderType
import org.hexworks.zircon.api.modifier.BorderType.*
import org.hexworks.zircon.api.modifier.TextureTransformModifier
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.transformer.Java2DTextureTransformer
import java.awt.BasicStroke
import java.awt.Graphics2D
import java.awt.image.BufferedImage
class Java2DBorderTransformer : Java2DTextureTransformer() {
override fun transform(texture: TileTexture<BufferedImage>, tile: Tile): TileTexture<BufferedImage> {
return texture.also {
val txt = it.texture
txt.graphics.apply {
if (tile.hasBorder) {
tile.fetchBorderData().forEach { border ->
color = border.borderColor.toAWTColor()
border.borderPositions.forEach { pos ->
txt.width
FILLER_LOOKUP[pos]?.invoke(txt, this as Graphics2D, border.borderType, border.borderWidth)
}
}
}
dispose()
}
}
}
companion object {
private val BORDER_TYPE_LOOKUP = mapOf(
Pair(SOLID, this::drawSolidLine),
Pair(DOTTED, this::drawDottedLine),
Pair(DASHED, this::drawDashedLine)
).toMap()
private val FILLER_LOOKUP = mapOf(
Pair(TOP, { region: BufferedImage, graphics: Graphics2D, type: BorderType, width: Int ->
BORDER_TYPE_LOOKUP[type]?.invoke(graphics, width, 0, 0, region.width, 0)
}),
Pair(BOTTOM, { region: BufferedImage, graphics: Graphics2D, type: BorderType, width: Int ->
BORDER_TYPE_LOOKUP[type]?.invoke(graphics, width, 0, region.height, region.width, region.height)
}),
Pair(LEFT, { region: BufferedImage, graphics: Graphics2D, type: BorderType, width: Int ->
BORDER_TYPE_LOOKUP[type]?.invoke(graphics, width, 0, 0, 0, region.height)
}),
Pair(RIGHT, { region: BufferedImage, graphics: Graphics2D, type: BorderType, width: Int ->
BORDER_TYPE_LOOKUP[type]?.invoke(graphics, width, region.width, 0, region.width, region.height)
})
)
.toMap()
private fun drawDottedLine(
graphics: Graphics2D,
width: Int,
x1: Int,
y1: Int,
x2: Int,
y2: Int
) {
val dotted =
BasicStroke(width.toFloat(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, floatArrayOf(2f), 0f)
graphics.stroke = dotted
graphics.drawLine(x1, y1, x2, y2)
}
private fun drawSolidLine(
graphics: Graphics2D,
width: Int,
x1: Int,
y1: Int,
x2: Int,
y2: Int
) {
val solid = BasicStroke(width.toFloat())
graphics.stroke = solid
graphics.drawLine(x1, y1, x2, y2)
}
private fun drawDashedLine(
graphics: Graphics2D,
width: Int,
x1: Int,
y1: Int,
x2: Int,
y2: Int
) {
val dashed =
BasicStroke(width.toFloat(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, floatArrayOf(9f), 0f)
graphics.stroke = dashed
graphics.drawLine(x1, y1, x2, y2)
}
}
}
| apache-2.0 | d0bf0272208f99bffaf1858bb0aceb6c | 36.029703 | 118 | 0.568717 | 4.274286 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/delete/DeleteVisualLinesEndAction.kt | 1 | 2511 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.change.delete
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import java.util.*
/**
* @author vlan
*/
class DeleteVisualLinesEndAction : VisualOperatorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.DELETE
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_MOT_LINEWISE, CommandFlags.FLAG_EXIT_VISUAL)
override fun executeAction(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
range: VimSelection,
operatorArguments: OperatorArguments,
): Boolean {
val vimTextRange = range.toVimTextRange(true)
return if (range.type == SelectionType.BLOCK_WISE) {
val starts = vimTextRange.startOffsets
val ends = vimTextRange.endOffsets
for (i in starts.indices) {
if (ends[i] > starts[i]) {
ends[i] = editor.getLineEndForOffset(starts[i])
}
}
val blockRange = TextRange(starts, ends)
injector.changeGroup.deleteRange(
editor,
editor.primaryCaret(),
blockRange,
SelectionType.BLOCK_WISE,
false,
operatorArguments
)
} else {
val lineEndForOffset = editor.getLineEndForOffset(vimTextRange.endOffset)
val endsWithNewLine = if (lineEndForOffset.toLong() == editor.fileSize()) 0 else 1
val lineRange = TextRange(
editor.getLineStartForOffset(vimTextRange.startOffset),
lineEndForOffset + endsWithNewLine
)
injector.changeGroup.deleteRange(editor, caret, lineRange, SelectionType.LINE_WISE, false, operatorArguments)
}
}
}
| mit | e8533259f8d1be345202616f4de402a8 | 34.871429 | 118 | 0.739546 | 4.270408 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/DisplayUtilsWrapper.kt | 1 | 966 | package org.wordpress.android.util
import dagger.Reusable
import org.wordpress.android.viewmodel.ContextProvider
import javax.inject.Inject
@Reusable
class DisplayUtilsWrapper @Inject constructor(private val contextProvider: ContextProvider) {
private val windowWidth get() = DisplayUtils.getWindowPixelWidth(contextProvider.getContext())
private val windowHeight get() = DisplayUtils.getWindowPixelHeight(contextProvider.getContext())
fun getDisplayPixelWidth() = DisplayUtils.getDisplayPixelWidth()
fun isLandscapeBySize() = windowWidth > windowHeight
fun isLandscape() = DisplayUtils.isLandscape(contextProvider.getContext())
fun isTablet() = DisplayUtils.isTablet(contextProvider.getContext()) ||
DisplayUtils.isXLargeTablet(contextProvider.getContext())
fun getWindowPixelHeight() = DisplayUtils.getWindowPixelHeight(contextProvider.getContext())
fun isPhoneLandscape() = isLandscapeBySize() && !isTablet()
}
| gpl-2.0 | 8599bc6283494e4fa8dafe773f4eec86 | 39.25 | 100 | 0.79089 | 5.25 | false | false | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/components/terrain/TerrainComponentWidget.kt | 1 | 2585 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.inspector.components.terrain
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.tabbedpane.Tab
import com.kotcrab.vis.ui.widget.tabbedpane.TabbedPane
import com.kotcrab.vis.ui.widget.tabbedpane.TabbedPaneListener
import com.mbrlabs.mundus.commons.scene3d.GameObject
import com.mbrlabs.mundus.commons.scene3d.components.Component
import com.mbrlabs.mundus.commons.scene3d.components.TerrainComponent
import com.mbrlabs.mundus.editor.ui.modules.inspector.components.ComponentWidget
/**
* @author Marcus Brummer
* @version 29-01-2016
*/
class TerrainComponentWidget(terrainComponent: TerrainComponent) :
ComponentWidget<TerrainComponent>("Terrain Component", terrainComponent), TabbedPaneListener {
private val tabbedPane = TabbedPane()
private val tabContainer = VisTable()
private val raiseLowerTab = TerrainUpDownTab(this)
private val flattenTab = TerrainFlattenTab(this)
private val paintTab = TerrainPaintTab(this)
private val genTab = TerrainGenTab(this)
private val settingsTab = TerrainSettingsTab()
init {
tabbedPane.addListener(this)
tabbedPane.add(raiseLowerTab)
tabbedPane.add(flattenTab)
tabbedPane.add(paintTab)
tabbedPane.add(genTab)
tabbedPane.add(settingsTab)
collapsibleContent.add(tabbedPane.table).growX().row()
collapsibleContent.add(tabContainer).expand().fill().row()
tabbedPane.switchTab(0)
}
override fun setValues(go: GameObject) {
val c = go.findComponentByType(Component.Type.TERRAIN)
if (c != null) {
this.component = c as TerrainComponent
}
}
override fun switchedTab(tab: Tab) {
tabContainer.clearChildren()
tabContainer.add(tab.contentTable).expand().fill()
}
override fun removedTab(tab: Tab) {
// no
}
override fun removedAllTabs() {
// nope
}
}
| apache-2.0 | db7b5715faff7d28fb3c14c78c96111a | 32.141026 | 102 | 0.72147 | 4.020218 | false | false | false | false |
ingokegel/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/CodeFenceLanguageListCompletionProvider.kt | 7 | 3434 | // 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.intellij.plugins.markdown.editor
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.lang.Language
import com.intellij.lang.LanguageUtil
import com.intellij.psi.PsiElement
import com.intellij.ui.DeferredIconImpl
import com.intellij.util.ProcessingContext
import org.intellij.plugins.markdown.injection.aliases.CodeFenceLanguageAliases.findMainAlias
import org.intellij.plugins.markdown.injection.aliases.CodeFenceLanguageGuesser
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.util.hasType
import javax.swing.Icon
class CodeFenceLanguageListCompletionProvider: CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
for (provider in CodeFenceLanguageGuesser.customProviders) {
val lookups = provider.getCompletionVariantsForInfoString(parameters)
for (lookupElement in lookups) {
val element = LookupElementDecorator.withInsertHandler(lookupElement) { context: InsertionContext, item: LookupElementDecorator<LookupElement> ->
MyInsertHandler(parameters).handleInsert(context, item)
lookupElement.handleInsert(context)
}
result.addElement(element)
}
}
for (language in LanguageUtil.getInjectableLanguages()) {
val alias = findMainAlias(language.id)
val lookupElement = LookupElementBuilder.create(alias)
.withIcon(createLanguageIcon(language))
.withTypeText(language.displayName, true)
.withInsertHandler(MyInsertHandler(parameters))
result.addElement(lookupElement)
}
}
private class MyInsertHandler(private val parameters: CompletionParameters): InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
if (isInMiddleOfUnCollapsedFence(parameters.originalPosition, context.startOffset)) {
context.document.insertString(context.tailOffset, "\n\n")
context.editor.caretModel.moveCaretRelatively(1, 0, false, false, false)
}
}
}
companion object {
@JvmStatic
fun createLanguageIcon(language: Language): Icon {
return DeferredIconImpl(null, language, true) { curLanguage: Language -> curLanguage.associatedFileType?.icon }
}
@JvmStatic
fun isInMiddleOfUnCollapsedFence(element: PsiElement?, offset: Int): Boolean {
return when {
element == null -> false
element.hasType(MarkdownTokenTypes.CODE_FENCE_START) -> {
val range = element.textRange
range.startOffset + range.endOffset == offset * 2
}
element.hasType(MarkdownTokenTypes.TEXT) && element.parent.hasType(MarkdownElementTypes.CODE_SPAN) -> {
val range = element.textRange
val parentRange = element.parent.textRange
range.startOffset - parentRange.startOffset == parentRange.endOffset - range.endOffset
}
else -> false
}
}
}
}
| apache-2.0 | bafe2868f0df988254bf4121875ad3f2 | 45.405405 | 158 | 0.756261 | 4.905714 | false | false | false | false |
alexander-schmidt/ihh | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/comparator/ChangeProcessor.kt | 1 | 2116 | package com.asurasdevelopment.ihh.server.comparator
import org.javers.core.diff.changetype.NewObject
import org.javers.core.diff.changetype.ObjectRemoved
import org.javers.core.diff.changetype.ReferenceChange
import org.javers.core.diff.changetype.ValueChange
import org.javers.core.diff.changetype.container.ContainerChange
class ChangeProcessor {
companion object {
fun List<ValueChange>.byProperty() : Map<String, List<ValueChange>> {
val res = mutableMapOf<String, List<ValueChange>>()
this.forEach { res.put(it.propertyName, res.getOrDefault(it.propertyName, listOf()).plus(it)) }
return res
}
const val MATCH_RESULT = "result"
const val MATCH_REMARKS = "remarks"
const val MATCH_VENUE = "venue"
const val MATCH_DATE = "date"
const val MATCH_TIME = "time"
fun processChanges(leagueChanges: LeagueChanges) {
processMatchChanges(leagueChanges)
}
fun processMatchChanges(leagueChanges: LeagueChanges) {
val matchChanges = leagueChanges.getMatchChanges()
val valueChanges = leagueChanges.getMatchChanges(ValueChange::class.java).byProperty()
val newObjects = leagueChanges.getMatchChanges(NewObject::class.java)
val objectsRemoved = leagueChanges.getMatchChanges(ObjectRemoved::class.java)
val referenceChanges = leagueChanges.getMatchChanges(ReferenceChange::class.java)
val containerChanges = leagueChanges.getMatchChanges(ContainerChange::class.java)
}
}
}
/*
League
name
region
S->Groups
name
mode
tableMode
S->Teams
name
nameShort
type
rank
->Club
postCode
location
name
mail
homepage
shortName
region
S->Venues
S->Matches
venue #####
date #####
result #####
remarks #####??
->Team1
->Team2
->Referee1
->Referee2
->Observer
remarks #####?
S->Rows #####
matchCount
difference
points
position
->Team
S->MatchDays #####??
date
name
remarks
byPropertyName
-> venue (Match)
-> date (Match)
-> result (Match)
-> remarks (Match)
-> remarks (TeamGroup)
-> rows (List<Row>)
-> Teams (TeamGroup)*/ | apache-2.0 | 6ffd9e95ac9cc33c4cb55af653ca1316 | 22.786517 | 107 | 0.69707 | 3.785331 | false | false | false | false |
micolous/metrodroid | src/iOSMain/kotlin/au/id/micolous/metrodroid/card/felica/FelicaCardReaderIOS.kt | 1 | 2421 | /*
* FelicaCardReaderIOS.kt
*
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.card.felica
import au.id.micolous.metrodroid.card.Card
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.NativeThrows
import au.id.micolous.metrodroid.multi.logAndSwiftWrap
import kotlinx.coroutines.runBlocking
import platform.Foundation.*
object FelicaCardReaderIOS {
@NativeThrows
fun dump(wrapper: FelicaTransceiverIOS.SwiftWrapper,
defaultSysCode: NSData,
feedback: TagReaderFeedbackInterface): Card = logAndSwiftWrap (TAG, "Failed to dump"){
val xfer = FelicaTransceiverIOS(wrapper, defaultSysCode)
Log.d(TAG, "Start dump ${xfer.uid}")
runBlocking {
Log.d(TAG, "Start async")
/*
* onlyFirst = true is an iOS-specific hack to work around
* https://github.com/metrodroid/metrodroid/issues/613
*
* _NFReaderSession._validateFelicaCommand asserts that you're talking to the exact
* IDm that the system discovered -- including the upper 4 bits (which indicate the
* system number).
*
* Tell FelicaReader to only dump the first service.
*
* Once iOS fixes this, do an iOS version check instead.
*/
val df = FelicaReader.dumpTag(xfer, feedback, onlyFirst = true)
Card(tagId = xfer.uid?.let { if (it.size == 10) it.sliceOffLen(0, 7) else it }!!,
scannedAt = TimestampFull.now(), felica = df)
}
}
private const val TAG = "FelicaCardReaderIOS"
}
| gpl-3.0 | c44af971f0330107c41dc8d97f9de5af | 38.688525 | 99 | 0.679471 | 4.096447 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/players/PlayerListViewModel.kt | 3 | 1533 | package dev.mfazio.abl.players
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.PagingData
import androidx.paging.cachedIn
import dev.mfazio.abl.data.BaseballDatabase
import dev.mfazio.abl.data.BaseballRepository
import kotlinx.coroutines.flow.Flow
@ExperimentalPagingApi
class PlayerListViewModel(application: Application) :
AndroidViewModel(application) {
private val repo: BaseballRepository
private var currentTeamId: String? = null
private var currentNameQuery: String? = null
private var currentPlayerListItems: Flow<PagingData<PlayerListItem>>? = null
init {
repo = BaseballDatabase
.getDatabase(application, viewModelScope)
.let { db ->
BaseballRepository.getInstance(db)
}
}
fun getPlayerListItems(
teamId: String? = null,
nameQuery: String? = null
): Flow<PagingData<PlayerListItem>> {
val lastResult = currentPlayerListItems
return if (teamId == currentTeamId && nameQuery == currentNameQuery && lastResult != null) {
lastResult
} else {
currentNameQuery = nameQuery
currentTeamId = teamId
val newResult = repo
.getPlayerListItems(teamId, nameQuery)
.cachedIn(viewModelScope)
currentPlayerListItems = newResult
newResult
}
}
} | apache-2.0 | ffe30a2e337e9a4a435df6bcf9f643a4 | 28.5 | 100 | 0.682322 | 5.25 | false | false | false | false |
caarmen/FRCAndroidWidget | app/src/main/kotlin/ca/rmen/android/frccommon/FRCAboutActivity.kt | 1 | 2235 | /*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2011 - 2017 Carmen Alvarez
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package ca.rmen.android.frccommon
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import ca.rmen.android.frccommon.compat.Api11Helper
import ca.rmen.android.frccommon.compat.ApiHelper
import ca.rmen.android.frcwidget.render.Font
import ca.rmen.android.frenchcalendar.R
class FRCAboutActivity : Activity() {
companion object {
private val TAG = Constants.TAG + FRCAboutActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.about)
if (ApiHelper.apiLevel >= Build.VERSION_CODES.HONEYCOMB) {
Api11Helper.setDisplayHomeAsUpEnabled(this)
}
val view = findViewById<View>(R.id.aboutview)
Font.applyFont(this, view)
val tvAppVersion = view.findViewById<TextView>(R.id.tv_app_version)
try {
val pInfo = packageManager.getPackageInfo(packageName, 0)
tvAppVersion.text = pInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, e.message, e)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
}
| gpl-3.0 | e46e4ce500c762f5f33958fbcd7d717b | 35.048387 | 81 | 0.714989 | 4.193246 | false | false | false | false |
anitaa1990/DeviceInfo-Sample | deviceinfo/src/main/java/com/an/deviceinfo/device/DeviceInfo.kt | 1 | 24109 | package com.an.deviceinfo.device
import android.Manifest
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Activity
import android.app.ActivityManager
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Point
import android.media.AudioManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.nfc.NfcAdapter
import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.Settings
import android.support.annotation.RequiresApi
import android.telephony.TelephonyManager
import android.util.DisplayMetrics
import android.util.Patterns
import android.view.Display
import android.view.WindowManager
import android.webkit.WebSettings
import android.webkit.WebView
import com.an.deviceinfo.permission.PermissionUtils
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.util.ArrayList
import java.util.HashSet
import java.util.LinkedHashSet
import java.util.Locale
import java.util.regex.Pattern
class DeviceInfo(private val context: Context) {
private val BATTERY_HEALTH_COLD = "cold"
private val BATTERY_HEALTH_DEAD = "dead"
private val BATTERY_HEALTH_GOOD = "good"
private val BATTERY_HEALTH_OVERHEAT = "Over Heat"
private val BATTERY_HEALTH_OVER_VOLTAGE = "Over Voltage"
private val BATTERY_HEALTH_UNKNOWN = "Unknown"
private val BATTERY_HEALTH_UNSPECIFIED_FAILURE = "Unspecified failure"
private val BATTERY_PLUGGED_AC = "Charging via AC"
private val BATTERY_PLUGGED_USB = "Charging via USB"
private val BATTERY_PLUGGED_WIRELESS = "Wireless"
private val BATTERY_PLUGGED_UNKNOWN = "Unknown Source"
private val RINGER_MODE_NORMAL = "Normal"
private val RINGER_MODE_SILENT = "Silent"
private val RINGER_MODE_VIBRATE = "Vibrate"
private val PHONE_TYPE_GSM = "GSM"
private val PHONE_TYPE_CDMA = "CDMA"
private val PHONE_TYPE_NONE = "Unknown"
private val NETWORK_TYPE_2G = "2G"
private val NETWORK_TYPE_3G = "3G"
private val NETWORK_TYPE_4G = "4G"
private val NETWORK_TYPE_WIFI_WIFIMAX = "WiFi"
private val NOT_FOUND_VAL = "unknown"
private val permissionUtils: PermissionUtils
/* Device Info: */
val deviceName: String
get() {
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
return if (model.startsWith(manufacturer)) {
model
} else {
manufacturer + " " + model
}
}
val deviceLocale: String?
get() {
var locale: String? = null
val current = context.resources.configuration.locale
if (current != null) {
locale = current.toString()
}
return locale
}
val releaseBuildVersion: String
get() = Build.VERSION.RELEASE
val buildVersionCodeName: String
get() = Build.VERSION.CODENAME
val manufacturer: String
get() = Build.MANUFACTURER
val model: String
get() = Build.MODEL
val product: String
get() = Build.PRODUCT
val fingerprint: String
get() = Build.FINGERPRINT
val hardware: String
get() = Build.HARDWARE
val radioVer: String
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
get() = Build.getRadioVersion()
val device: String
get() = Build.DEVICE
val board: String
get() = Build.BOARD
val displayVersion: String
get() = Build.DISPLAY
val buildBrand: String
get() = Build.BRAND
val buildHost: String
get() = Build.HOST
val buildTime: Long
get() = Build.TIME
val buildUser: String
get() = Build.USER
val serial: String
get() = Build.SERIAL
val osVersion: String
get() = Build.VERSION.RELEASE
val language: String
get() = Locale.getDefault().language
val sdkVersion: Int
get() = Build.VERSION.SDK_INT
val screenDensity: String
get() {
val density = context.resources.displayMetrics.densityDpi
var scrType = ""
when (density) {
DisplayMetrics.DENSITY_LOW -> scrType = "ldpi"
DisplayMetrics.DENSITY_MEDIUM -> scrType = "mdpi"
DisplayMetrics.DENSITY_HIGH -> scrType = "hdpi"
DisplayMetrics.DENSITY_XHIGH -> scrType = "xhdpi"
else -> scrType = "other"
}
return scrType
}
// deprecated
val screenHeight: Int
get() {
var height = 0
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
if (Build.VERSION.SDK_INT > 12) {
val size = Point()
display.getSize(size)
height = size.y
} else {
height = display.height
}
return height
}
// deprecated
val screenWidth: Int
get() {
var width = 0
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
if (Build.VERSION.SDK_INT > 12) {
val size = Point()
display.getSize(size)
width = size.x
} else {
width = display.width
}
return width
}
/* App Info: */
val versionName: String?
get() {
val pInfo: PackageInfo
try {
pInfo = context.packageManager.getPackageInfo(
context.packageName, 0)
return pInfo.versionName
} catch (e1: Exception) {
return null
}
}
val versionCode: Int?
get() {
val pInfo: PackageInfo
try {
pInfo = context.packageManager.getPackageInfo(
context.packageName, 0)
return pInfo.versionCode
} catch (e1: Exception) {
return null
}
}
val packageName: String
get() = context.packageName
val activityName: String
get() = context.javaClass.simpleName
val appName: String
get() {
val packageManager = context.packageManager
var applicationInfo: ApplicationInfo? = null
try {
applicationInfo = packageManager.getApplicationInfo(context.applicationInfo.packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
}
return (if (applicationInfo != null) packageManager.getApplicationLabel(applicationInfo) else NOT_FOUND_VAL) as String
}
/* Battery Info:
* battery percentage
* is phone charging at the moment
* Battery Health
* Battery Technology
* Battery Temperature
* Battery Voltage
* Charging Source
* Check if battery is present */
private val batteryStatusIntent: Intent?
get() {
val batFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
return context.registerReceiver(null, batFilter)
}
val batteryPercent: Int
get() {
val intent = batteryStatusIntent
val rawlevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
var level = -1
if (rawlevel >= 0 && scale > 0) {
level = rawlevel * 100 / scale
}
return level
}
val isPhoneCharging: Boolean
get() {
val intent = batteryStatusIntent
val plugged = intent!!.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)
return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB
}
val batteryHealth: String
get() {
var health = BATTERY_HEALTH_UNKNOWN
val intent = batteryStatusIntent
val status = intent!!.getIntExtra(BatteryManager.EXTRA_HEALTH, 0)
when (status) {
BatteryManager.BATTERY_HEALTH_COLD -> health = BATTERY_HEALTH_COLD
BatteryManager.BATTERY_HEALTH_DEAD -> health = BATTERY_HEALTH_DEAD
BatteryManager.BATTERY_HEALTH_GOOD -> health = BATTERY_HEALTH_GOOD
BatteryManager.BATTERY_HEALTH_OVERHEAT -> health = BATTERY_HEALTH_OVERHEAT
BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> health = BATTERY_HEALTH_OVER_VOLTAGE
BatteryManager.BATTERY_HEALTH_UNKNOWN -> health = BATTERY_HEALTH_UNKNOWN
BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE -> health = BATTERY_HEALTH_UNSPECIFIED_FAILURE
}
return health
}
val batteryTechnology: String
get() {
val intent = batteryStatusIntent
return intent!!.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)
}
val batteryTemperature: Float
get() {
val intent = batteryStatusIntent
val temperature = intent!!.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
return (temperature / 10.0).toFloat()
}
val batteryVoltage: Int
get() {
val intent = batteryStatusIntent
return intent!!.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)
}
val chargingSource: String
get() {
val intent = batteryStatusIntent
val plugged = intent!!.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)
when (plugged) {
BatteryManager.BATTERY_PLUGGED_AC -> return BATTERY_PLUGGED_AC
BatteryManager.BATTERY_PLUGGED_USB -> return BATTERY_PLUGGED_USB
BatteryManager.BATTERY_PLUGGED_WIRELESS -> return BATTERY_PLUGGED_WIRELESS
else -> return BATTERY_PLUGGED_UNKNOWN
}
}
val isBatteryPresent: Boolean
get() {
val intent = batteryStatusIntent
return intent!!.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false)
}
/* Id Info: */
val bluetoothMAC: String
get() {
if (!permissionUtils.isPermissionGranted(Manifest.permission.BLUETOOTH))
throw RuntimeException("Access Bluetooth permission not granted!")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Settings.Secure.getString(context.contentResolver,
"bluetooth_address")
} else {
val bta = BluetoothAdapter.getDefaultAdapter()
return if (bta != null) bta.address else "00"
}
}
val isRunningOnEmulator: Boolean
get() = (Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
|| "google_sdk" == Build.PRODUCT
|| Build.PRODUCT.contains("vbox86p")
|| Build.DEVICE.contains("vbox86p")
|| Build.HARDWARE.contains("vbox86"))
val deviceRingerMode: String
get() {
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
when (audioManager.ringerMode) {
AudioManager.RINGER_MODE_SILENT -> return RINGER_MODE_SILENT
AudioManager.RINGER_MODE_VIBRATE -> return RINGER_MODE_VIBRATE
else -> return RINGER_MODE_NORMAL
}
}
val isDeviceRooted: Boolean
get() {
val paths = arrayOf("/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su")
for (path in paths) {
if (File(path).exists()) return true
}
return false
}
// API level 8+
val emailAccounts: List<String>
get() {
if (!permissionUtils.isPermissionGranted(Manifest.permission.GET_ACCOUNTS))
throw RuntimeException("Get Accounts permission not granted!")
val emails = HashSet<String>()
val emailPattern = Patterns.EMAIL_ADDRESS
val accounts = AccountManager.get(context).accounts
for (account in accounts) {
if (emailPattern.matcher(account.name).matches()) {
emails.add(account.name)
}
}
return ArrayList(LinkedHashSet(emails))
}
val androidId: String
get() = Settings.Secure.getString(context.contentResolver,
Settings.Secure.ANDROID_ID)
val installSource: String
get() {
val pm = context.packageManager
return pm.getInstallerPackageName(context.packageName)
}
val userAgent: String
get() {
val systemUa = System.getProperty("http.agent")
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
WebSettings.getDefaultUserAgent(context) + "__" + systemUa
} else WebView(context).settings.userAgentString + "__" + systemUa
}
val gsfId: String
get() {
val URI = Uri.parse("content://com.google.android.gsf.gservices")
val ID_KEY = "android_id"
val params = arrayOf(ID_KEY)
val c = context.contentResolver.query(URI, null, null, params, null)
if (!c!!.moveToFirst() || c.columnCount < 2) {
c.close()
return NOT_FOUND_VAL
}
try {
val gsfId = java.lang.Long.toHexString(java.lang.Long.parseLong(c.getString(1)))
c.close()
return gsfId
} catch (e: NumberFormatException) {
c.close()
return NOT_FOUND_VAL
}
}
val totalRAM: Long
get() {
var totalMemory: Long = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
val mi = ActivityManager.MemoryInfo()
val activityManager = context.getSystemService(Activity.ACTIVITY_SERVICE) as ActivityManager
activityManager.getMemoryInfo(mi)
return mi.totalMem
}
try {
val reader = RandomAccessFile("/proc/meminfo", "r")
val load = reader.readLine().replace("\\D+".toRegex(), "")
totalMemory = Integer.parseInt(load).toLong()
reader.close()
return totalMemory
} catch (e: IOException) {
e.printStackTrace()
return 0L
}
}
val availableInternalMemorySize: Long
get() {
val path = Environment.getDataDirectory()
val stat = StatFs(path.path)
val blockSize: Long
val availableBlocks: Long
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.blockSizeLong
availableBlocks = stat.availableBlocksLong
} else {
blockSize = stat.blockSize.toLong()
availableBlocks = stat.availableBlocks.toLong()
}
return availableBlocks * blockSize
}
val totalInternalMemorySize: Long
get() {
val path = Environment.getDataDirectory()
val stat = StatFs(path.path)
val blockSize: Long
val totalBlocks: Long
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.blockSizeLong
totalBlocks = stat.blockCountLong
} else {
blockSize = stat.blockSize.toLong()
totalBlocks = stat.blockCount.toLong()
}
return totalBlocks * blockSize
}
val availableExternalMemorySize: Long
get() {
if (hasExternalSDCard()) {
val path = Environment.getExternalStorageDirectory()
val stat = StatFs(path.path)
val blockSize: Long
val availableBlocks: Long
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.blockSizeLong
availableBlocks = stat.availableBlocksLong
} else {
blockSize = stat.blockSize.toLong()
availableBlocks = stat.availableBlocks.toLong()
}
return availableBlocks * blockSize
}
return 0
}
val totalExternalMemorySize: Long
get() {
if (hasExternalSDCard()) {
val path = Environment.getExternalStorageDirectory()
val stat = StatFs(path.path)
val blockSize: Long
val totalBlocks: Long
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.blockSizeLong
totalBlocks = stat.blockCountLong
} else {
blockSize = stat.blockSize.toLong()
totalBlocks = stat.blockCount.toLong()
}
return totalBlocks * blockSize
}
return 0
}
val imei: String
get() {
if (!permissionUtils.isPermissionGranted(Manifest.permission.READ_PHONE_STATE))
throw RuntimeException("Read Phone State permission not granted!")
val telephonyMgr = context.getSystemService(Activity.TELEPHONY_SERVICE) as TelephonyManager
return telephonyMgr.deviceId
}
val imsi: String
get() {
val telephonyMgr = context.getSystemService(Activity.TELEPHONY_SERVICE) as TelephonyManager
return telephonyMgr.subscriberId
}
val phoneType: String
get() {
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
when (tm.phoneType) {
TelephonyManager.PHONE_TYPE_GSM -> return PHONE_TYPE_GSM
TelephonyManager.PHONE_TYPE_CDMA -> return PHONE_TYPE_CDMA
TelephonyManager.PHONE_TYPE_NONE -> return PHONE_TYPE_NONE
else -> return PHONE_TYPE_NONE
}
}
val phoneNumber: String
get() {
if (!permissionUtils.isPermissionGranted(Manifest.permission.READ_PHONE_STATE))
throw RuntimeException("Read Phone State permission not granted!")
val serviceName = Context.TELEPHONY_SERVICE
val m_telephonyManager = context.getSystemService(serviceName) as TelephonyManager
return m_telephonyManager.line1Number
}
val operator: String
get() {
var operatorName: String?
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
operatorName = telephonyManager.networkOperatorName
if (operatorName == null)
operatorName = telephonyManager.simOperatorName
return operatorName
}
val simSerial: String
get() {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return telephonyManager.simSerialNumber
}
val isSimNetworkLocked: Boolean
get() {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return telephonyManager.simState == TelephonyManager.SIM_STATE_NETWORK_LOCKED
}
val isNfcPresent: Boolean
get() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
val nfcAdapter = NfcAdapter.getDefaultAdapter(context)
return nfcAdapter != null
}
return false
}
val isNfcEnabled: Boolean
get() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
val nfcAdapter = NfcAdapter.getDefaultAdapter(context)
return nfcAdapter != null && nfcAdapter.isEnabled
}
return false
}
val isWifiEnabled: Boolean
get() {
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
return wifiManager.isWifiEnabled
}
val isNetworkAvailable: Boolean
get() {
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnected
}
val networkClass: String
get() {
val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val networkType = mTelephonyManager.networkType
when (networkType) {
TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> return NETWORK_TYPE_2G
TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> return NETWORK_TYPE_3G
TelephonyManager.NETWORK_TYPE_LTE -> return NETWORK_TYPE_4G
else -> return NOT_FOUND_VAL
}
}
val networkType: String
get() {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork == null)
return NOT_FOUND_VAL
else if (activeNetwork.type == ConnectivityManager.TYPE_WIFI || activeNetwork.type == ConnectivityManager.TYPE_WIMAX) {
return NETWORK_TYPE_WIFI_WIFIMAX
} else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) {
return networkClass
}
return NOT_FOUND_VAL
}
init {
this.permissionUtils = PermissionUtils(context)
}
fun isAppInstalled(packageName: String): Boolean {
return context.packageManager.getLaunchIntentForPackage(packageName) != null
}
fun getWifiMacAddress(context: Context): String {
if (!permissionUtils.isPermissionGranted(Manifest.permission.ACCESS_WIFI_STATE))
throw RuntimeException("Access Wifi state permission not granted!")
val manager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
val info = manager.connectionInfo
return info.macAddress
}
fun hasExternalSDCard(): Boolean {
return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
}
}
| apache-2.0 | 7c415e67cca9b35211ff2f27bb7c13e8 | 33.639368 | 374 | 0.599237 | 4.998756 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinMultilineStringEnterHandler.kt | 1 | 16688 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.editor
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.injected.editor.EditorWindow
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.refactoring.hostEditor
import org.jetbrains.kotlin.idea.refactoring.project
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.psi.psiUtil.isSingleQuoted
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class KotlinMultilineStringEnterHandler : EnterHandlerDelegateAdapter() {
private var wasInMultilineString: Boolean = false
private var whiteSpaceAfterCaret: String = ""
private var isInBrace = false
override fun preprocessEnter(
file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>, dataContext: DataContext,
originalHandler: EditorActionHandler?
): Result {
val offset = caretOffset.get().toInt()
if (editor !is EditorWindow) {
return preprocessEnter(file, editor, offset, originalHandler, dataContext)
}
val hostPosition = getHostPosition(dataContext) ?: return Result.Continue
return preprocessEnter(hostPosition, originalHandler, dataContext)
}
private fun preprocessEnter(hostPosition: HostPosition, originalHandler: EditorActionHandler?, dataContext: DataContext): Result {
val (file, editor, offset) = hostPosition
return preprocessEnter(file, editor, offset, originalHandler, dataContext)
}
private fun preprocessEnter(
file: PsiFile,
editor: Editor,
offset: Int,
originalHandler: EditorActionHandler?,
dataContext: DataContext
): Result {
if (file !is KtFile) return Result.Continue
val document = editor.document
val text = document.text
if (offset == 0 || offset >= text.length) return Result.Continue
val element = file.findElementAt(offset)
if (!inMultilineString(element, offset)) {
return Result.Continue
} else {
wasInMultilineString = true
}
whiteSpaceAfterCaret = text.substring(offset).takeWhile { ch -> ch == ' ' || ch == '\t' }
document.deleteString(offset, offset + whiteSpaceAfterCaret.length)
val ch1 = text[offset - 1]
val ch2 = text[offset]
isInBrace = (ch1 == '(' && ch2 == ')') || (ch1 == '{' && ch2 == '}'|| (ch1 == '>' && ch2 == '<'))
if (!isInBrace || !CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
return Result.Continue
}
originalHandler?.execute(editor, editor.caretModel.currentCaret, dataContext)
return Result.DefaultForceIndent
}
override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): Result {
if (editor !is EditorWindow) {
return postProcessEnter(file, editor)
}
val hostPosition = getHostPosition(dataContext) ?: return Result.Continue
return postProcessEnter(hostPosition.file, hostPosition.editor)
}
private fun postProcessEnter(file: PsiFile, editor: Editor): Result {
if (file !is KtFile) return Result.Continue
if (!wasInMultilineString) return Result.Continue
wasInMultilineString = false
val project = file.project
val document = editor.document
PsiDocumentManager.getInstance(project).commitDocument(document)
val caretModel = editor.caretModel
val offset = caretModel.offset
val element = file.findElementAt(offset) ?: return Result.Continue
val literal = findString(element, offset) ?: return Result.Continue
val hasTrimIndentCallInChain = hasTrimIndentCallInChain(literal)
val marginChar = if (hasTrimIndentCallInChain)
null
else
getMarginCharFromTrimMarginCallsInChain(literal) ?: getMarginCharFromLiteral(literal)
runWriteAction {
val settings = MultilineSettings(file)
val caretMarker = document.createRangeMarker(offset, offset)
caretMarker.isGreedyToRight = true
fun caretOffset(): Int = caretMarker.endOffset
val prevLineNumber = document.getLineNumber(offset) - 1
assert(prevLineNumber >= 0)
val prevLine = getLineByNumber(prevLineNumber, document)
val currentLine = getLineByNumber(prevLineNumber + 1, document)
val nextLine = if (document.lineCount > prevLineNumber + 2) getLineByNumber(prevLineNumber + 2, document) else ""
val wasSingleLine = literal.text.indexOf("\n") == literal.text.lastIndexOf("\n") // Only one '\n' in the string after insertion
val lines = literal.text.split("\n")
val literalOffset = literal.textRange.startOffset
if (wasSingleLine || (lines.size == 3 && isInBrace)) {
val shouldUseTrimIndent = hasTrimIndentCallInChain || (marginChar == null && lines.first().trim() == MULTILINE_QUOTE)
val newMarginChar: Char? = if (shouldUseTrimIndent) null else (marginChar ?: DEFAULT_TRIM_MARGIN_CHAR)
insertTrimCall(document, literal, if (shouldUseTrimIndent) null else newMarginChar)
val prevIndent = settings.indentLength(prevLine)
val indentSize = prevIndent + settings.marginIndent
forceIndent(caretOffset(), indentSize, newMarginChar, document, settings)
val isInLineEnd = literal.text.substring(offset - literalOffset) == MULTILINE_QUOTE
if (isInLineEnd) {
// Move close quote to next line
caretMarker.isGreedyToRight = false
insertNewLine(caretOffset(), prevIndent, document, settings)
caretMarker.isGreedyToRight = true
}
if (isInBrace) {
// Move closing bracket under same indent
forceIndent(caretOffset() + 1, indentSize, newMarginChar, document, settings)
}
} else {
val isPrevLineFirst = document.getLineNumber(literalOffset) == prevLineNumber
val indentInPreviousLine = when {
isPrevLineFirst -> lines.first().substring(MULTILINE_QUOTE.length)
else -> prevLine
}.prefixLength { it == ' ' || it == '\t' }
val prefixStripped = when {
isPrevLineFirst -> lines.first().substring(indentInPreviousLine + MULTILINE_QUOTE.length)
else -> prevLine.substring(indentInPreviousLine)
}
val nonBlankNotFirstLines = lines.subList(1, lines.size).filterNot { it.isBlank() || it.trimStart() == MULTILINE_QUOTE }
val marginCharToInsert = if (marginChar != null &&
!prefixStripped.startsWith(marginChar) &&
nonBlankNotFirstLines.isNotEmpty() &&
nonBlankNotFirstLines.none { it.trimStart().startsWith(marginChar) }
) {
// We have margin char but decide not to insert it
null
} else {
marginChar
}
if (marginCharToInsert == null || !currentLine.trimStart().startsWith(marginCharToInsert)) {
val indentLength = when {
isInBrace -> settings.indentLength(nextLine)
!isPrevLineFirst -> settings.indentLength(prevLine)
else -> settings.indentLength(prevLine) + settings.marginIndent
}
forceIndent(caretOffset(), indentLength, marginCharToInsert, document, settings)
val wsAfterMargin = when {
marginCharToInsert != null && prefixStripped.startsWith(marginCharToInsert) -> {
prefixStripped.substring(1).takeWhile { it == ' ' || it == '\t' }
}
else -> ""
}
// Insert same indent after margin char that previous line has
document.insertString(caretOffset(), wsAfterMargin)
if (isInBrace) {
val nextLineOffset = document.getLineStartOffset(prevLineNumber + 2)
forceIndent(nextLineOffset, 0, null, document, settings)
document.insertString(nextLineOffset, (marginCharToInsert?.toString() ?: "") + wsAfterMargin)
forceIndent(nextLineOffset, indentLength, null, document, settings)
}
}
}
document.insertString(caretOffset(), whiteSpaceAfterCaret)
caretModel.moveToOffset(caretOffset())
caretMarker.dispose()
}
return Result.Stop
}
companion object {
private const val DEFAULT_TRIM_MARGIN_CHAR = '|'
private const val TRIM_INDENT_CALL = "trimIndent"
private const val TRIM_MARGIN_CALL = "trimMargin"
private const val MULTILINE_QUOTE = "\"\"\""
class MultilineSettings(file: PsiFile) {
private val kotlinIndentOptions = CodeStyle.getIndentOptions(file)
private val useTabs = kotlinIndentOptions.USE_TAB_CHARACTER
private val tabSize = kotlinIndentOptions.TAB_SIZE
private val regularIndent = kotlinIndentOptions.INDENT_SIZE
val marginIndent = regularIndent
fun getSmartSpaces(count: Int): String = when {
useTabs -> StringUtil.repeat("\t", count / tabSize) + StringUtil.repeat(" ", count % tabSize)
else -> StringUtil.repeat(" ", count)
}
fun indentLength(line: String): Int = when {
useTabs -> {
val tabsCount = line.prefixLength { it == '\t' }
tabsCount * tabSize + line.substring(tabsCount).prefixLength { it == ' ' }
}
else -> line.prefixLength { it == ' ' }
}
}
fun findString(element: PsiElement?, offset: Int): KtStringTemplateExpression? {
if (element !is LeafPsiElement) return null
when (element.elementType) {
KtTokens.REGULAR_STRING_PART -> {
// Ok
}
KtTokens.CLOSING_QUOTE, KtTokens.SHORT_TEMPLATE_ENTRY_START, KtTokens.LONG_TEMPLATE_ENTRY_START -> {
if (element.startOffset != offset) {
return null
}
}
else -> return null
}
return element.parents.firstIsInstanceOrNull()
}
fun inMultilineString(element: PsiElement?, offset: Int) =
!(findString(element, offset)?.isSingleQuoted() ?: true)
fun getMarginCharFromLiteral(str: KtStringTemplateExpression, marginChar: Char = DEFAULT_TRIM_MARGIN_CHAR): Char? {
val lines = str.text.lines()
if (lines.size <= 2) return null
val middleNonBlank = lines.subList(1, lines.size - 1).filter { !it.isBlank() }
if (middleNonBlank.isNotEmpty() && middleNonBlank.all { it.trimStart().startsWith(marginChar) }) {
return marginChar
}
return null
}
private fun getLiteralCalls(str: KtStringTemplateExpression): Sequence<KtCallExpression> {
var previous: PsiElement = str
return str.parents
.takeWhile { parent ->
if (parent is KtQualifiedExpression && parent.receiverExpression == previous) {
previous = parent
true
} else {
false
}
}
.mapNotNull { qualified ->
(qualified as KtQualifiedExpression).selectorExpression as? KtCallExpression
}
}
fun getMarginCharFromTrimMarginCallsInChain(str: KtStringTemplateExpression): Char? {
val literalCall = getLiteralCalls(str).firstOrNull { call ->
call.getCallNameExpression()?.text == TRIM_MARGIN_CALL
} ?: return null
val firstArgument = literalCall.valueArguments.getOrNull(0) ?: return DEFAULT_TRIM_MARGIN_CHAR
val argumentExpression = firstArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return DEFAULT_TRIM_MARGIN_CHAR
val entry = argumentExpression.entries.singleOrNull() as? KtLiteralStringTemplateEntry ?: return DEFAULT_TRIM_MARGIN_CHAR
return entry.text?.singleOrNull() ?: DEFAULT_TRIM_MARGIN_CHAR
}
fun hasTrimIndentCallInChain(str: KtStringTemplateExpression): Boolean {
return getLiteralCalls(str).any { call -> call.getCallNameExpression()?.text == TRIM_INDENT_CALL }
}
fun getLineByNumber(number: Int, document: Document): String =
document.getText(TextRange(document.getLineStartOffset(number), document.getLineEndOffset(number)))
fun insertNewLine(nlOffset: Int, indent: Int, document: Document, settings: MultilineSettings) {
document.insertString(nlOffset, "\n")
forceIndent(nlOffset + 1, indent, null, document, settings)
}
fun forceIndent(offset: Int, indent: Int, marginChar: Char?, document: Document, settings: MultilineSettings) {
val lineNumber = document.getLineNumber(offset)
val lineStart = document.getLineStartOffset(lineNumber)
val line = getLineByNumber(lineNumber, document)
val wsPrefix = line.takeWhile { c -> c == ' ' || c == '\t' }
document.replaceString(
lineStart,
lineStart + wsPrefix.length,
settings.getSmartSpaces(indent) + (marginChar?.toString() ?: "")
)
}
fun String.prefixLength(f: (Char) -> Boolean) = takeWhile(f).count()
fun insertTrimCall(document: Document, literal: KtStringTemplateExpression, marginChar: Char?) {
if (hasTrimIndentCallInChain(literal) || getMarginCharFromTrimMarginCallsInChain(literal) != null) return
if (literal.parents.any { it is KtAnnotationEntry || (it as? KtProperty)?.hasModifier(KtTokens.CONST_KEYWORD) == true }) return
if (marginChar == null) {
document.insertString(literal.textRange.endOffset, ".$TRIM_INDENT_CALL()")
} else {
document.insertString(
literal.textRange.endOffset,
if (marginChar == DEFAULT_TRIM_MARGIN_CHAR) {
".$TRIM_MARGIN_CALL()"
} else {
".$TRIM_MARGIN_CALL(\"$marginChar\")"
}
)
}
}
private data class HostPosition(val file: PsiFile, val editor: Editor, val offset: Int)
private fun getHostPosition(dataContext: DataContext): HostPosition? {
val editor = dataContext.hostEditor as? EditorEx ?: return null
val project = dataContext.project
val virtualFile = editor.virtualFile ?: return null
val psiFile = virtualFile.toPsiFile(project) ?: return null
return HostPosition(psiFile, editor, editor.caretModel.offset)
}
}
} | apache-2.0 | 6f3a28a7052b65deb0b7904216da68fe | 43.504 | 158 | 0.618528 | 5.155391 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/common/ReadmeBuilder.kt | 1 | 920 | package org.roylance.yaclib.core.services.common
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
class ReadmeBuilder(mainDependency: YaclibModel.Dependency) : IBuilder<YaclibModel.File> {
private val InitialTemplate = """${mainDependency.group}.${mainDependency.name}
================
This library and readme was auto-generated and auto-published by [Yaclib](https://github.com/roylanceMichael/yaclib). This TypeScript library contains the interfaces and implementations to communicate with the corresponding rest server in Java. More documentation to come...
"""
override fun build(): YaclibModel.File {
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(InitialTemplate.trim())
.setFileExtension(YaclibModel.FileExtension.MD_EXT)
.setFileName("README")
.setFullDirectoryLocation("")
.build()
return returnFile
}
} | mit | 851b5f53b7606d1522f747b75c146da5 | 40.863636 | 274 | 0.747826 | 4.842105 | false | false | false | false |
skyem123/StringMatcher1 | src/main/kotlin/uk/co/skyem/random/stringMatcher1/Matches.kt | 1 | 2111 | package uk.co.skyem.random.stringMatcher1
// TODO: Be as lazy as possible.
internal class Matches(matches: Array<Match>) : List<Match> {
constructor(matches: Collection<Match>) : this(matches.toTypedArray())
constructor() : this(arrayOf())
override val size = matches.size
companion object Matches {
fun arrayEqual(a: Array<Match>, b: Array<Match>): Boolean {
if (a.size != b.size) return false
a.forEach {
val thing = it
// If an element in a has been found in b...
var oneFound = false
b.forEach {
oneFound = oneFound || thing == it
}
// if one is not found, return false
if (!oneFound) return false
}
return true
}
}
private val matches = matches
fun matchFound(): Boolean {
return matches.isNotEmpty()
}
fun first(): Match {
return matches.first()
}
fun last(): Match {
return matches.last()
}
override fun isEmpty(): Boolean {
return matches.isEmpty()
}
override fun iterator(): Iterator<Match> {
return matches.iterator()
}
override fun get(index: Int): Match {
return matches.get(index)
}
override fun contains(element: Match): Boolean {
return matches.contains(element)
}
override fun listIterator(): ListIterator<Match> {
return matches.toList().listIterator()
}
override fun listIterator(index: Int): ListIterator<Match> {
return matches.toList().listIterator(index)
}
override fun subList(fromIndex: Int, toIndex: Int): List<Match> {
return matches.toList().subList(fromIndex, toIndex)
}
override fun equals(other: Any?): Boolean {
if (other != null && other is uk.co.skyem.random.stringMatcher1.Matches && Matches.arrayEqual(this.matches, other.matches))
return true
else
return false
}
override fun indexOf(element: Match): Int {
return matches.indexOf(element)
}
override fun containsAll(elements: Collection<Match>): Boolean {
return arrayEqual(elements.toTypedArray(), matches)
}
override fun lastIndexOf(element: Match): Int {
return matches.lastIndexOf(element)
}
// TODO: Store matcher object, so matches can be inverted?
}
| bsd-2-clause | cee4b765935652649b282d19c286b39e | 22.719101 | 125 | 0.686405 | 3.547899 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/internal/api/basicHelpersForWidgetCode.kt | 1 | 17130 | package imgui.internal.api
import gli_.hasnt
import glm_.f
import glm_.func.common.max
import glm_.func.common.min
import glm_.glm
import glm_.i
import glm_.vec2.Vec2
import glm_.wo
import imgui.*
import imgui.ImGui.clearActiveID
import imgui.ImGui.currentWindow
import imgui.ImGui.foregroundDrawList
import imgui.ImGui.hoveredId
import imgui.ImGui.io
import imgui.ImGui.isActiveIdUsingKey
import imgui.ImGui.isMouseHoveringRect
import imgui.ImGui.sameLine
import imgui.ImGui.style
import imgui.api.g
import imgui.internal.api.internal.Companion.shrinkWidthItemComparer
import imgui.internal.classes.Rect
import imgui.internal.classes.ShrinkWidthItem
import imgui.internal.classes.Window
import imgui.internal.floor
import imgui.internal.sections.*
import imgui.static.navProcessItem
import java.util.*
//-----------------------------------------------------------------------------
// [SECTION] LAYOUT
//-----------------------------------------------------------------------------
// - ItemSize()
// - ItemAdd()
// - SameLine()
// - Indent()
// - Unindent()
// - BeginGroup()
// - EndGroup()
// Also see in imgui_widgets: tab bars, columns.
//-----------------------------------------------------------------------------
/** Basic Helpers for widget code */
internal interface basicHelpersForWidgetCode {
/** Advance cursor given item size for layout.
* Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
* See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. */
fun itemSize(size: Vec2, textBaselineY: Float = -1f) {
val window = currentWindow
if (window.skipItems) return
// We increase the height in this function to accommodate for baseline offset.
// In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
// but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
val offsetToMatchBaselineY = if (textBaselineY >= 0f) 0f max (window.dc.currLineTextBaseOffset - textBaselineY) else 0f
val lineHeight = window.dc.currLineSize.y max (size.y + offsetToMatchBaselineY)
// Always align ourselves on pixel boundaries
window.dc.apply {
//if (io.keyAlt) window.drawList.addRect(window.dc.cursorPos, window.dc.cursorPos + Vec2(size.x, lineHeight), COL32(255,0,0,200)); // [DEBUG]
cursorPosPrevLine.put(cursorPos.x + size.x, cursorPos.y)
cursorPos.x = floor(window.pos.x + indent + columnsOffset) // Next line
cursorPos.y = floor(cursorPos.y + lineHeight + style.itemSpacing.y) // Next line
cursorMaxPos.x = cursorMaxPos.x max cursorPosPrevLine.x
cursorMaxPos.y = cursorMaxPos.y max (cursorPos.y - style.itemSpacing.y)
//if (io.keyAlt) window.drawList.addCircle(window.dc.cursorMaxPos, 3f, COL32(255,0,0,255), 4); // [DEBUG]
prevLineSize.y = lineHeight
currLineSize.y = 0f
prevLineTextBaseOffset = currLineTextBaseOffset max textBaselineY
currLineTextBaseOffset = 0f
// Horizontal layout mode
if (layoutType == LayoutType.Horizontal) sameLine()
}
}
fun itemSize(bb: Rect, textBaselineY: Float = -1f) = itemSize(bb.size, textBaselineY)
/** Declare item bounding box for clipping and interaction.
* Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
* declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. */
fun itemAdd(bb: Rect, id: ID, navBbArg: Rect? = null): Boolean {
val window = g.currentWindow!!
if (id != 0) {
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
// unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
// thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
// to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window.dc.navLayerActiveMaskNext = window.dc.navLayerActiveMaskNext or (1 shl window.dc.navLayerCurrent)
if (g.navId == id || g.navAnyRequest)
if (g.navWindow!!.rootWindowForNav === window.rootWindowForNav)
if (window == g.navWindow || (window.flags or g.navWindow!!.flags) has WindowFlag._NavFlattened)
navProcessItem(window, navBbArg ?: bb, id)
}
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
if (IMGUI_DEBUG_TOOL_ITEM_PICKER_EX && id == g.debugItemPickerBreakId) {
IM_DEBUG_BREAK()
g.debugItemPickerBreakId = 0
}
// Equivalent to calling SetLastItemData()
val dc = g.currentWindow!!.dc.apply {
lastItemId = id
lastItemRect = bb
lastItemStatusFlags = ItemStatusFlag.None.i
}
g.nextItemData.flags = NextItemDataFlag.None.i
if (IMGUI_ENABLE_TEST_ENGINE && id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(navBbArg ?: bb, id)
// Clipping test
if (isClippedEx(bb, id, false)) return false
//if (g.io.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (isMouseHoveringRect(bb))
dc.lastItemStatusFlags = dc.lastItemStatusFlags or ItemStatusFlag.HoveredRect
return true
}
/** Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). */
fun itemHoverable(bb: Rect, id: ID): Boolean {
val window = g.currentWindow!!
return when {
g.hoveredId != 0 && g.hoveredId != id && !g.hoveredIdAllowOverlap -> false
g.hoveredWindow !== window -> false
g.activeId != 0 && g.activeId != id && !g.activeIdAllowOverlap -> false
!isMouseHoveringRect(bb) -> false
g.navDisableMouseHover -> false
!window.isContentHoverable(HoveredFlag.None) || window.dc.itemFlags has ItemFlag.Disabled -> {
g.hoveredIdDisabled = true
false
}
else -> {
// We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
// hover test in widgets code. We could also decide to split this function is two.
if (id != 0) {
hoveredId = id
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.debugItemPickerActive && g.hoveredIdPreviousFrame == id)
foregroundDrawList.addRect(bb.min, bb.max, COL32(255, 255, 0, 255))
if (g.debugItemPickerBreakId == id)
IM_DEBUG_BREAK()
}
true
}
}
}
fun isClippedEx(bb: Rect, id: ID, clipEvenWhenLogged: Boolean): Boolean {
val window = g.currentWindow!!
if (!(bb overlaps window.clipRect))
if (id == 0 || (id != g.activeId && id != g.navId))
if (clipEvenWhenLogged || !g.logEnabled)
return true
return false
}
/** This is also inlined in ItemAdd()
* Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect! */
fun setLastItemData(window: Window, itemId: ID, itemFlags: ItemStatusFlags, itemRect: Rect) {
window.dc.lastItemId = itemId
window.dc.lastItemStatusFlags = itemFlags
window.dc.lastItemRect put itemRect
}
/** Return true if focus is requested
* Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. */
// TODO move both methods into Window class?
fun focusableItemRegister(window: Window, id: ID): Boolean {
// Increment counters
val isTabStop = window.dc.itemFlags hasnt (ItemFlag.NoTabStop or ItemFlag.Disabled)
window.dc.focusCounterRegular++
if (isTabStop)
window.dc.focusCounterTabStop++
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.activeId == id && g.focusTabPressed && !isActiveIdUsingKey(Key.Tab) && g.focusRequestNextWindow == null) {
g.focusRequestNextWindow = window
g.focusRequestNextCounterTabStop = window.dc.focusCounterTabStop + when {
// Modulo on index will be applied at the end of frame once we've got the total counter of items.
io.keyShift -> if (isTabStop) -1 else 0
else -> +1
}
}
// Handle focus requests
if (g.focusRequestCurrWindow === window) {
if (window.dc.focusCounterRegular == g.focusRequestCurrCounterRegular)
return true
if (isTabStop && window.dc.focusCounterTabStop == g.focusRequestCurrCounterTabStop) {
g.navJustTabbedId = id
return true
}
// If another item is about to be focused, we clear our own active id
if (g.activeId == id)
clearActiveID()
}
return false
}
fun focusableItemUnregister(window: Window) {
window.dc.focusCounterRegular--
window.dc.focusCounterTabStop--
}
/** [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
* Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
* Note that only CalcItemWidth() is publicly exposed.
* The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) */
fun calcItemSize(size_: Vec2, defaultW: Float, defaultH: Float): Vec2 {
val window = g.currentWindow!!
val regionMax = if (size_ anyLessThan 0f) contentRegionMaxAbs else Vec2()
val size = Vec2(size_)
if (size.x == 0f)
size.x = defaultW
else if (size.x < 0f)
size.x = 4f max (regionMax.x - window.dc.cursorPos.x + size.x)
if (size.y == 0f)
size.y = defaultH
else if (size.y < 0f)
size.y = 4f max (regionMax.y - window.dc.cursorPos.y + size.y)
return size
}
fun calcWrapWidthForPos(pos: Vec2, wrapPosX_: Float): Float {
if (wrapPosX_ < 0f) return 0f
var wrapPosX = wrapPosX_
val window = g.currentWindow!!
if (wrapPosX == 0f) {
// We could decide to setup a default wrapping max point for auto-resizing windows,
// or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
//if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
// wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
//else
wrapPosX = window.workRect.max.x
} else if (wrapPosX > 0f)
wrapPosX += window.pos.x - window.scroll.x // wrap_pos_x is provided is window local space
return glm.max(wrapPosX - pos.x, 1f)
}
fun pushMultiItemsWidths(components: Int, wFull: Float) {
val window = currentWindow
val wItemOne = 1f max floor((wFull - (style.itemInnerSpacing.x) * (components - 1)) / components.f)
val wItemLast = 1f max floor(wFull - (wItemOne + style.itemInnerSpacing.x) * (components - 1))
window.dc.itemWidthStack.push(wItemLast)
for (i in 0 until components - 1)
window.dc.itemWidthStack.push(wItemOne)
window.dc.itemWidth = window.dc.itemWidthStack.last()
g.nextItemData.flags = g.nextItemData.flags wo NextItemDataFlag.HasWidth
}
/** allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
* @param option = ItemFlag */
fun pushItemFlag(option: ItemFlags, enabled: Boolean) {
val window = g.currentWindow!!
var itemFlags = window.dc.itemFlags
assert(itemFlags == g.itemFlagsStack.last())
itemFlags = when {
enabled -> itemFlags or option
else -> itemFlags wo option
}
window.dc.itemFlags = itemFlags
g.itemFlagsStack += itemFlags
}
fun popItemFlag() {
val window = g.currentWindow!!
assert(g.itemFlagsStack.size > 1) { "Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack." }
g.itemFlagsStack.pop()
window.dc.itemFlags = g.itemFlagsStack.last()
}
/** Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) */
val isItemToggledSelection: Boolean
get() = g.currentWindow!!.dc.lastItemStatusFlags has ItemStatusFlag.ToggledSelection
/** [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
* ~GetContentRegionMaxAbs */
val contentRegionMaxAbs: Vec2
get() {
val window = g.currentWindow!!
val mx = window.contentRegionRect.max
if (window.dc.currentColumns != null || g.currentTable != null)
mx.x = window.workRect.max.x
return mx
}
/** Shrink excess width from a set of item, by removing width from the larger items first.
* Set items Width to -1.0f to disable shrinking this item. */
fun shrinkWidths(items: ArrayList<ShrinkWidthItem>, ptr: Int, count: Int, widthExcess_: Float) {
var widthExcess = widthExcess_
if (count == 1) {
if (items[ptr].width >= 0f)
items[ptr].width = (items[ptr].width - widthExcess) max 1f
return
}
items.subList(ptr, ptr + count).sortWith(shrinkWidthItemComparer)
var countSameWidth = 1
while (widthExcess > 0f && countSameWidth < count) {
while (countSameWidth < count && items[ptr].width <= items[countSameWidth].width)
countSameWidth++
val maxWidthToRemovePerItem = when {
countSameWidth < count && items[ptr + countSameWidth].width >= 0f -> items[ptr].width - items[ptr + countSameWidth].width
else -> items[ptr].width - 1f
}
if (maxWidthToRemovePerItem <= 0f)
break
val widthToRemovePerItem = (widthExcess / countSameWidth) min maxWidthToRemovePerItem
for (itemN in 0 until countSameWidth)
items[ptr + itemN].width -= widthToRemovePerItem
widthExcess -= widthToRemovePerItem * countSameWidth
}
// Round width and redistribute remainder left-to-right (could make it an option of the function?)
// Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator.
widthExcess = 0f
repeat(count) {
val widthRounded = floor(items[it].width)
widthExcess += items[it].width - widthRounded
items[it].width = widthRounded
}
if (widthExcess > 0f)
for (n in 0 until count)
if (items[n].index < (widthExcess + 0.01f).i)
items[n].width += 1f
}
} | mit | c40a7c657a3a7a15080669b9ce0b8f5c | 47.256338 | 161 | 0.624577 | 4.221291 | false | false | false | false |
P1xelfehler/BatteryWarner | app/src/main/java/com/laudien/p1xelfehler/batterywarner/HistoryActivity.kt | 1 | 14639 | package com.laudien.p1xelfehler.batterywarner
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.app.Dialog
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast.LENGTH_SHORT
import com.laudien.p1xelfehler.batterywarner.database.DatabaseModel
import com.laudien.p1xelfehler.batterywarner.database.DatabaseUtils
import com.laudien.p1xelfehler.batterywarner.fragments.HistoryPageFragment
import com.laudien.p1xelfehler.batterywarner.fragments.HistoryPageFragmentDataSource
import com.laudien.p1xelfehler.batterywarner.helper.KeyboardHelper
import com.laudien.p1xelfehler.batterywarner.helper.ToastHelper
import kotlinx.android.synthetic.main.activity_history.*
import java.io.File
import java.util.*
/**
* Activity that shows all the charging curves that were saved.
*/
class HistoryActivity : BaseActivity(), ViewPager.OnPageChangeListener {
private val PERMISSION_REQUEST_CODE = 60
private val adapter = HistoryPagerAdapter(supportFragmentManager)
private val handleButtonsHandler = Handler()
private val handleButtonsRunnable = Runnable {
val pos = viewPager.currentItem
if (adapter.count - 1 <= pos) {
slideOut(btn_next)
} else {
slideIn(btn_next)
}
if (pos <= 0) {
slideOut(btn_prev)
} else {
slideIn(btn_prev)
}
}
private var lastPage = 0
companion object {
val DATABASE_HISTORY_PATH = "${Environment.getExternalStorageDirectory()}/BatteryWarner"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
setToolbarTitle(getString(R.string.title_history))
btn_next.setOnClickListener {
viewPager.setCurrentItem(viewPager.currentItem + 1, true)
}
btn_prev.setOnClickListener {
viewPager.setCurrentItem(viewPager.currentItem - 1, true)
}
viewPager.offscreenPageLimit = 2
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(this)
if (savedInstanceState == null) {
lastPage = -1
}
// check for permission
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE
)
return
}
// permissions are granted at this point
loadGraphs()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.history_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_rename -> showRenameDialog()
R.id.menu_delete -> showDeleteDialog()
R.id.menu_delete_all -> showDeleteAllDialog()
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun onDestroy() {
super.onDestroy()
DatabaseModel.getInstance(this).closeAllExternalFiles()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_REQUEST_CODE) {
for (result in grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
finish()
return
}
}
loadGraphs()
}
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
val file = adapter.getFile(position)
textView_fileName.text = file?.name
if (adapter.count == 0) {
slideOut(btn_next)
slideOut(btn_prev)
return
}
handleButtonsHandler.removeCallbacks(handleButtonsRunnable)
if (position != lastPage) {
lastPage = position
handleButtonsRunnable.run()
} else {
handleButtonsHandler.postDelayed(handleButtonsRunnable, 1000)
}
}
override fun onPageScrollStateChanged(state: Int) {
}
private fun loadGraphs() {
val fileList = DatabaseUtils.getBatteryFiles()
adapter.loadFiles(fileList)
if (fileList.isEmpty()) {
textView_nothingSaved.visibility = VISIBLE
textView_fileName.visibility = INVISIBLE
}
}
private fun showDeleteDialog() {
if (adapter.count != 0) {
AlertDialog.Builder(this).setCancelable(true)
.setTitle(R.string.dialog_title_are_you_sure)
.setMessage(R.string.dialog_message_delete_graph)
.setIcon(R.drawable.ic_battery_status_full_green_48dp)
.setPositiveButton(getString(R.string.dialog_button_yes)) { _, _ ->
val currentPosition = viewPager.currentItem
if (adapter.deleteFile(currentPosition)) {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_success_delete_graph, LENGTH_SHORT)
if (adapter.count == 0) {
textView_nothingSaved.visibility = VISIBLE
}
} else {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_error_deleting, LENGTH_SHORT)
}
}.setNegativeButton(getString(R.string.dialog_button_cancel), null)
.create().show()
} else {
ToastHelper.sendToast(this, R.string.toast_no_graphs_saved, LENGTH_SHORT)
}
}
private fun showDeleteAllDialog() {
if (adapter.count != 0) {
AlertDialog.Builder(this).setCancelable(true)
.setTitle(R.string.dialog_title_are_you_sure)
.setMessage(R.string.dialog_message_delete_all_graphs)
.setIcon(R.drawable.ic_battery_status_full_green_48dp)
.setPositiveButton(getString(R.string.dialog_button_yes)) { _, _ ->
if (adapter.deleteAllFiles()) {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_success_delete_all_graphs, LENGTH_SHORT)
textView_nothingSaved.visibility = VISIBLE
} else {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_error_deleting, LENGTH_SHORT)
}
}.setNegativeButton(getString(R.string.dialog_button_cancel), null)
.create().show()
} else {
ToastHelper.sendToast(this, R.string.toast_no_graphs_saved, LENGTH_SHORT)
}
}
private fun showRenameDialog() {
if (adapter.count > 0) {
val oldName = adapter.getFile(viewPager.currentItem)?.name
val dialog = Dialog(this)
dialog.setContentView(R.layout.dialog_rename)
val editText = dialog.findViewById<EditText>(R.id.editText)
editText.setText(oldName)
dialog.findViewById<Button>(R.id.btn_ok).setOnClickListener {
val newName = editText.text.toString()
if (newName != oldName) {
if (newName.contains("/")) {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_error_renaming_wrong_characters, LENGTH_SHORT)
} else {
val newFile = File(DATABASE_HISTORY_PATH + "/" + newName)
if (newFile.exists()) {
ToastHelper.sendToast(this@HistoryActivity, String.format(Locale.getDefault(), "%s '%s'!",
getString(R.string.toast_graph_name_already_exists), newName))
} else if (adapter.renameFile(viewPager.currentItem, newFile)) {
textView_fileName.text = newName
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_success_renaming, LENGTH_SHORT)
} else {
ToastHelper.sendToast(this@HistoryActivity, R.string.toast_error_renaming, LENGTH_SHORT)
}
}
}
dialog.dismiss()
}
dialog.findViewById<Button>(R.id.btn_cancel).setOnClickListener { dialog.dismiss() }
dialog.show()
// show keyboard
KeyboardHelper.showKeyboard(dialog.window)
} else { // no graphs saved
ToastHelper.sendToast(this, R.string.toast_no_graphs_saved, LENGTH_SHORT)
}
}
private fun slideIn(view: View) {
if (view.visibility != VISIBLE) {
val animation = AnimationUtils.loadAnimation(this, R.anim.slide_in_bottom)
animation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
view.visibility = VISIBLE
}
override fun onAnimationEnd(animation: Animation) {
}
override fun onAnimationRepeat(animation: Animation) {
}
})
view.startAnimation(animation)
}
}
private fun slideOut(view: View) {
if (view.visibility == VISIBLE) {
val animation = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom)
animation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
view.visibility = INVISIBLE
}
override fun onAnimationRepeat(animation: Animation) {
}
})
view.startAnimation(animation)
}
}
/**
* A FragmentStatePagerAdapter that loads HistoryPageFragments into the ViewPager.
*/
private inner class HistoryPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm), HistoryPageFragmentDataSource {
private var files: ArrayList<File>? = null
override fun getItem(position: Int): Fragment {
val fragment = HistoryPageFragment()
fragment.dataSource = this
fragment.index = position
return fragment
}
override fun getCount(): Int {
return files?.size ?: 0
}
override fun getItemPosition(`object`: Any): Int {
return PagerAdapter.POSITION_NONE
}
override fun notifyDataSetChanged() {
super.notifyDataSetChanged()
onPageSelected(viewPager.currentItem)
}
override fun isCurrentItem(index: Int): Boolean {
return index == viewPager.currentItem
}
/**
* Removes the database file of the fragment at the given position.
*
* @param position The position of the fragment in the ViewPager.
* @return Returns true, if the file was successfully removed, false if not.
*/
internal fun deleteFile(position: Int): Boolean {
if (position <= count) {
val file = files?.get(position)
if (file?.delete() == true) {
files?.removeAt(position)
notifyDataSetChanged()
return true
}
}
return false
}
internal fun deleteAllFiles(): Boolean {
if (count > 0) {
for (f in files!!) {
if (!f.delete()) {
loadGraphs()
return false
}
}
files?.clear()
notifyDataSetChanged()
return true
} else {
return false
}
}
/**
* Get the database file of the fragment at the given position.
*
* @param position The position of the fragment in the ViewPager.
* @return Returns the database file of the fragment at the given position.
*/
override fun getFile(position: Int): File? {
if (count <= position) {
return null
}
return files?.get(position)
}
/**
* Rename the history file of a given position.
*
* @param position The position of the fragment in the ViewPager.
* @param newFile The new file with the new name to which the file should be renamed.
* @return Returns true, if the renaming was successful, false if not.
*/
internal fun renameFile(position: Int, newFile: File): Boolean {
if (position <= count) {
val oldFile = files!![position]
if (oldFile.renameTo(newFile)) {
textView_fileName.text = newFile.name
files!![position] = newFile
return true
}
}
return false
}
internal fun loadFiles(files: ArrayList<File>?) {
this.files = files
notifyDataSetChanged()
}
}
}
| gpl-3.0 | 3a1dffa31a9700df1e3f5bb778504c58 | 37.422572 | 129 | 0.589111 | 5.040978 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/AnalyticsOrganisationUnitHelper.kt | 1 | 5447 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStore
import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope
import org.hisp.dhis.android.core.common.RelativeOrganisationUnit
import org.hisp.dhis.android.core.organisationunit.*
import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore
internal class AnalyticsOrganisationUnitHelper @Inject constructor(
private val userOrganisationUnitStore: UserOrganisationUnitLinkStore,
private val organisationUnitStore: IdentifiableObjectStore<OrganisationUnit>,
private val organisationUnitLevelStore: IdentifiableObjectStore<OrganisationUnitLevel>,
private val organisationUnitOrganisationUnitGroupLinkStore: LinkStore<OrganisationUnitOrganisationUnitGroupLink>
) {
fun getRelativeOrganisationUnitUids(relative: RelativeOrganisationUnit): List<String> {
val userOrganisationUnits = userOrganisationUnitStore
.queryAssignedOrganisationUnitUidsByScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
val relativeOrganisationUnitsUids = when (relative) {
RelativeOrganisationUnit.USER_ORGUNIT ->
userOrganisationUnits
RelativeOrganisationUnit.USER_ORGUNIT_CHILDREN ->
queryChildrenOrganisationUnitUids(userOrganisationUnits)
RelativeOrganisationUnit.USER_ORGUNIT_GRANDCHILDREN ->
queryGrandChildrenOrganisationUnitUids(userOrganisationUnits)
}
val whereClause = WhereClauseBuilder()
.appendInKeyStringValues(
OrganisationUnitTableInfo.Columns.UID,
relativeOrganisationUnitsUids
).build()
return organisationUnitStore.selectUidsWhere(
whereClause,
"${OrganisationUnitTableInfo.Columns.NAME} ${RepositoryScope.OrderByDirection.ASC}"
)
}
fun getOrganisationUnitUidsByLevel(level: Int): List<String> {
val whereClause = WhereClauseBuilder()
.appendKeyNumberValue(OrganisationUnitTableInfo.Columns.LEVEL, level)
.build()
return organisationUnitStore.selectUidsWhere(whereClause)
}
fun getOrganisationUnitUidsByLevelUid(levelUid: String): List<String> {
val level = organisationUnitLevelStore.selectByUid(levelUid)
return getOrganisationUnitUidsByLevel(level?.level()!!)
}
fun getOrganisationUnitUidsByGroup(groupUid: String): List<String> {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(
OrganisationUnitOrganisationUnitGroupLinkTableInfo.Columns.ORGANISATION_UNIT_GROUP,
groupUid
).build()
return organisationUnitOrganisationUnitGroupLinkStore.selectStringColumnsWhereClause(
OrganisationUnitOrganisationUnitGroupLinkTableInfo.Columns.ORGANISATION_UNIT,
whereClause
).distinct()
}
private fun queryChildrenOrganisationUnitUids(parentUids: List<String>): List<String> {
return getChildrenOrganisationUnitUids(parentUids)
}
private fun queryGrandChildrenOrganisationUnitUids(parentUids: List<String>): List<String> {
return getChildrenOrganisationUnitUids(queryChildrenOrganisationUnitUids(parentUids))
}
private fun getChildrenOrganisationUnitUids(parentUids: List<String>): List<String> {
val childrenClause = WhereClauseBuilder()
.appendInKeyStringValues(OrganisationUnitTableInfo.Columns.PARENT, parentUids)
.build()
return organisationUnitStore.selectUidsWhere(childrenClause)
}
}
| bsd-3-clause | 1ae0011a9bfe6785c18c945a7011975b | 46.780702 | 116 | 0.755278 | 5.192564 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/show/ShowHabitView.kt | 1 | 2496 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.activities.habits.show
import android.content.Context
import android.view.LayoutInflater
import android.widget.FrameLayout
import org.isoron.uhabits.core.ui.screens.habits.show.ShowHabitPresenter
import org.isoron.uhabits.core.ui.screens.habits.show.ShowHabitState
import org.isoron.uhabits.databinding.ShowHabitBinding
import org.isoron.uhabits.utils.setupToolbar
class ShowHabitView(context: Context) : FrameLayout(context) {
private val binding = ShowHabitBinding.inflate(LayoutInflater.from(context))
init {
addView(binding.root)
}
fun setState(data: ShowHabitState) {
setupToolbar(
binding.toolbar,
title = data.title,
color = data.color,
theme = data.theme,
)
binding.subtitleCard.setState(data.subtitle)
binding.overviewCard.setState(data.overview)
binding.notesCard.setState(data.notes)
binding.targetCard.setState(data.target)
binding.streakCard.setState(data.streaks)
binding.scoreCard.setState(data.scores)
binding.frequencyCard.setState(data.frequency)
binding.historyCard.setState(data.history)
binding.barCard.setState(data.bar)
if (data.isNumerical) {
binding.overviewCard.visibility = GONE
binding.streakCard.visibility = GONE
} else {
binding.targetCard.visibility = GONE
}
}
fun setListener(presenter: ShowHabitPresenter) {
binding.scoreCard.setListener(presenter.scoreCardPresenter)
binding.historyCard.setListener(presenter.historyCardPresenter)
binding.barCard.setListener(presenter.barCardPresenter)
}
}
| gpl-3.0 | c86cb6633178b8662c5da5c856e71aeb | 36.80303 | 80 | 0.719439 | 4.264957 | false | false | false | false |
toonine/BalaFM | app/src/main/java/com/nice/balafm/util/CountDownTimerUtils.kt | 1 | 1895 | package com.nice.balafm.util
import android.graphics.Color
import android.os.CountDownTimer
import android.widget.Button
//获取验证码工具类
internal class CountDownTimerUtils(private val mButton: Button, millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
mButton.isClickable = false //设置不可点击
mButton.text = (millisUntilFinished / 1000).toString() + "s后重发" //设置倒计时时间
mButton.setBackgroundColor(Color.parseColor("#b8b8b8")) //设置按钮为灰色,这时是不能点击的
/**
* 超链接 URLSpan
* 文字背景颜色 BackgroundColorSpan
* 文字颜色 ForegroundColorSpan
* 字体大小 AbsoluteSizeSpan
* 粗体、斜体 StyleSpan
* 删除线 StrikethroughSpan
* 下划线 UnderlineSpan
* 图片 ImageSpan
* http://blog.csdn.net/ah200614435/article/details/7914459
*/
// val spannableString = SpannableString(mButton.text.toString()) //获取按钮上的文字
// val span = ForegroundColorSpan(Color.RED)
/**
* public void setSpan(Object what, int start, int end, int flags) {
* 主要是start跟end,start是起始位置,无论中英文,都算一个。
* 从0开始计算起。end是结束位置,所以处理的文字,包含开始位置,但不包含结束位置。
*/
// spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)//将倒计时的时间设置为红色
// mButton.text = spannableString
}
override fun onFinish() {
mButton.text = "获取验证码"
mButton.isClickable = true//重新获得点击
mButton.setBackgroundColor(Color.parseColor("#ff8922")) //还原背景色
}
} | apache-2.0 | 9d7be993d2f4962c2e99339eac0c8cbb | 35.465116 | 164 | 0.663689 | 3.71327 | false | false | false | false |
dahlstrom-g/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/data/RWActiveProcesses.kt | 8 | 1728 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.runToolbar.data
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.runToolbar.RunToolbarProcess
import com.intellij.execution.runToolbar.SlotDate
import com.intellij.execution.runToolbar.getRunToolbarProcess
import com.intellij.execution.runners.ExecutionEnvironment
class RWActiveProcesses {
internal var activeSlots = mutableListOf<SlotDate>()
val processes = mutableMapOf<RunToolbarProcess, MutableList<ExecutionEnvironment>>()
private var activeCount = 0
fun getActiveCount(): Int = activeCount
fun getText(): String? {
return when {
activeCount == 1 -> {
processes.entries.firstOrNull()?.let { entry ->
entry.value.firstOrNull()?.contentToReuse?.let {
ExecutionBundle.message("run.toolbar.started", entry.key.name, it.displayName)
}
}
}
activeCount > 1 -> {
processes.map { ExecutionBundle.message("run.toolbar.started", it.key.name, it.value.size) }.joinToString(" ")
}
else -> null
}
}
internal fun updateActiveProcesses(slotsData: MutableMap<String, SlotDate>) {
processes.clear()
val list = slotsData.values.filter { it.environment != null }.toMutableList()
activeSlots = list
list.mapNotNull { it.environment }.forEach { environment ->
environment.getRunToolbarProcess()?.let {
processes.computeIfAbsent(it) { mutableListOf() }.add(environment)
}
}
activeCount = processes.values.map { it.size }.sum()
}
internal fun clear() {
activeCount = 0
processes.clear()
}
}
| apache-2.0 | 12c925674ed6b4308c3e755654b608cc | 32.230769 | 120 | 0.701968 | 4.535433 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityParentListImpl.kt | 2 | 9022 | 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.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.referrersy
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityParentListImpl: MainEntityParentList, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(MainEntityParentList::class.java, AttachedEntityParentList::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField var _x: String? = null
override val x: String
get() = _x!!
override val children: List<AttachedEntityParentList>
get() = snapshot.extractOneToManyChildren<AttachedEntityParentList>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityParentListData?): ModifiableWorkspaceEntityBase<MainEntityParentList>(), MainEntityParentList.Builder {
constructor(): this(MainEntityParentListData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityParentList 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().isXInitialized()) {
error("Field MainEntityParentList#x should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field MainEntityParentList#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field MainEntityParentList#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field MainEntityParentList#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
// List of non-abstract referenced types
var _children: List<AttachedEntityParentList>? = emptyList()
override var children: List<AttachedEntityParentList>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<AttachedEntityParentList>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<AttachedEntityParentList> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<AttachedEntityParentList> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): MainEntityParentListData = result ?: super.getEntityData() as MainEntityParentListData
override fun getEntityClass(): Class<MainEntityParentList> = MainEntityParentList::class.java
}
}
class MainEntityParentListData : WorkspaceEntityData<MainEntityParentList>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityParentList> {
val modifiable = MainEntityParentListImpl.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): MainEntityParentList {
val entity = MainEntityParentListImpl()
entity._x = x
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityParentList::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityParentListData
if (this.x != other.x) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityParentListData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
} | apache-2.0 | 3d24991a8aaae105472269af45b26116 | 40.013636 | 230 | 0.626247 | 5.908317 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/LineCommentingSuggester.kt | 6 | 4522 | package training.featuresSuggester.suggesters
import com.google.common.collect.EvictingQueue
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import training.featuresSuggester.FeatureSuggesterBundle
import training.featuresSuggester.NoSuggestion
import training.featuresSuggester.Suggestion
import training.featuresSuggester.actions.Action
import training.featuresSuggester.actions.EditorTextInsertedAction
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.abs
class LineCommentingSuggester : AbstractFeatureSuggester() {
override val id: String = "Comment with line comment"
override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("line.commenting.name")
override val message = FeatureSuggesterBundle.message("line.commenting.message")
override val suggestingActionId = "CommentByLineComment"
override val suggestingTipFileName = "CommentCode.html"
override val minSuggestingIntervalDays = 14
private data class DocumentLine(val startOffset: Int, val endOffset: Int, val text: String)
private data class CommentData(val lineNumber: Int, val documentRef: WeakReference<Document>, val timeMillis: Long)
private data class CommentSymbolPlace(val offset: Int, val filePath: String)
override val languages = listOf("JAVA", "kotlin", "Python", "ECMAScript 6")
private val maxTimeMillisBetweenComments = 5000L
private val numberOfCommentsToGetSuggestion = 3
@Suppress("UnstableApiUsage")
private val commentsHistory: Queue<CommentData> = EvictingQueue.create(numberOfCommentsToGetSuggestion)
private var prevCommentSymbolPlace: CommentSymbolPlace? = null
override fun getSuggestion(action: Action): Suggestion {
if (action is EditorTextInsertedAction) {
if (isCommentSymbolAdded(action, '/')) {
val fileName = action.psiFile?.virtualFile?.path ?: return NoSuggestion
prevCommentSymbolPlace = CommentSymbolPlace(action.caretOffset, fileName)
}
else if (prevCommentSymbolPlace?.let { isSecondSlashAdded(action, it) } == true || isCommentSymbolAdded(action, '#')) {
val document = action.document
val commentData = CommentData(
lineNumber = document.getLineNumber(action.caretOffset),
documentRef = WeakReference(document),
timeMillis = action.timeMillis
)
commentsHistory.add(commentData)
prevCommentSymbolPlace = null
if (commentsHistory.size == numberOfCommentsToGetSuggestion &&
commentsHistory.isLinesCommentedInARow()
) {
commentsHistory.clear()
return createSuggestion()
}
}
}
return NoSuggestion
}
private fun isCommentSymbolAdded(action: EditorTextInsertedAction, symbol: Char): Boolean {
with(action) {
val psiFile = this.psiFile ?: return false
if (text != symbol.toString()) return false
val psiElement = psiFile.findElementAt(caretOffset) ?: return false
if (psiElement is PsiComment || psiElement.nextSibling is PsiComment) return false
val line = document.getLineByOffset(caretOffset)
val lineBeforeSlash = line.text.substring(0, caretOffset - line.startOffset)
return lineBeforeSlash.isBlank() && line.text.trim() != symbol.toString()
}
}
private fun isSecondSlashAdded(curAction: EditorTextInsertedAction, prevSymbol: CommentSymbolPlace): Boolean {
return curAction.text == "/"
&& abs(curAction.caretOffset - prevSymbol.offset) == 1
&& curAction.psiFile?.virtualFile?.path == prevSymbol.filePath
}
private fun Queue<CommentData>.isLinesCommentedInARow(): Boolean {
return !(
map(CommentData::lineNumber)
.sorted()
.zipWithNext { first, second -> second - first }
.any { it != 1 } ||
map { it.documentRef.get() }
.zipWithNext { first, second -> first != null && first === second }
.any { !it } ||
map(CommentData::timeMillis)
.zipWithNext { first, second -> second - first }
.any { it > maxTimeMillisBetweenComments }
)
}
private fun Document.getLineByOffset(offset: Int): DocumentLine {
val lineNumber = getLineNumber(offset)
val startOffset = getLineStartOffset(lineNumber)
val endOffset = getLineEndOffset(lineNumber)
return DocumentLine(
startOffset = startOffset,
endOffset = endOffset,
text = getText(TextRange(startOffset, endOffset))
)
}
}
| apache-2.0 | a585760277e01a26a94d3e6e3efcbb4d | 40.87037 | 125 | 0.725122 | 4.715328 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/interop/EthJStubGenerator.kt | 1 | 7200 | package me.serce.solidity.ide.interop
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import me.serce.solidity.ide.settings.SoliditySettings
import org.web3j.protocol.core.methods.response.AbiDefinition
import java.io.ByteArrayOutputStream
import java.lang.reflect.Modifier
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.zip.GZIPOutputStream
object EthJStubGenerator : Sol2JavaGenerator {
override fun generate(project: Project, dir: VirtualFile, contracts: List<CompiledContractDefinition>) {
val output = WriteCommandAction.runWriteCommandAction(project, Computable {
VfsUtil.createDirectoryIfMissing(dir, SoliditySettings.instance.basePackage.replace(".", "/"))
}).path
runReadAction {
val repo = EthJStubGenerator.generateRepo(contracts)
writeClass(output, repoClassName, repo)
contracts.forEach {
writeClass(output, it.contract.name!!, convert(it))
}
}
}
private const val repoClassName = "ContractsRepository"
private const val autoGenComment = "// This is a generated file. Not intended for manual editing."
private fun getPackageName(): String = SoliditySettings.instance.basePackage
private val objNames = Any::class.java.declaredMethods.asSequence()
.filter { !Modifier.isPrivate(it.modifiers) }
.map { it.name }
.toSet()
private fun contractStubTemplate(className: String, functions: List<AbiDefinition>): String =
"""$autoGenComment
package ${getPackageName()};
import org.ethereum.util.blockchain.SolidityContract;
public class $className {
private final SolidityContract contract;
$className(SolidityContract contract) {
this.contract = contract;
}
${functions.filter { it.name != null }.joinToString("\n") { funcStubTemplate(it) }}
}"""
private fun funcStubTemplate(function: AbiDefinition): String {
val params = stringifyParams(function)
val paramRefs = paramRefs(function)
val methodName = function.name
val firstOutput = function.outputs.firstOrNull()
val hasReturn = firstOutput != null
var returnType = if (hasReturn) EthJTypeConverter.convert(firstOutput!!.type, lax = true) else "void"
if (returnType.contains("BigInteger[]")) {
// EthJ always returns an object array if an int array defined for output. Bug?
returnType = returnType.replaceBefore("[", "Object")
}
return """
public $returnType ${methodName(methodName)}($params) {
${if (hasReturn) "return ($returnType) " else ""}contract.callFunction("$methodName"$paramRefs)${if (hasReturn) ".getReturnValue()" else ""};
}
"""
}
private fun methodName(name: String?) =
if (objNames.contains(name)) "_$name" else name
private fun paramRefs(function: AbiDefinition?): String {
val parameters = function?.inputs ?: return ""
return if (parameters.isNotEmpty()) {
", " + parameters.joinToString(", ") { "(Object)${it.name}" }
} else ""
}
private fun contractRepoTemplate(contracts: List<CompiledContractDefinition>): String =
"""$autoGenComment
package ${getPackageName()};
import org.ethereum.config.SystemProperties;
import org.ethereum.config.blockchain.FrontierConfig;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.util.blockchain.EasyBlockchain;
import org.ethereum.util.blockchain.StandaloneBlockchain;
import java.math.BigInteger;
public class $repoClassName {
private EasyBlockchain blockchain;
private $repoClassName(EasyBlockchain blockchain) {
this.blockchain = blockchain;
}
private static StandaloneBlockchain defaultBlockchain;
public static $repoClassName getInstance(EasyBlockchain blockchain) {
return new $repoClassName(blockchain);
}
public static synchronized $repoClassName getInstance() {
if (defaultBlockchain == null) {
defaultBlockchain = initDefaultBlockchain();
}
return new $repoClassName(defaultBlockchain);
}
private static StandaloneBlockchain initDefaultBlockchain() {
SystemProperties.getDefault().setBlockchainConfig(new FrontierConfig(new FrontierConfig.FrontierConstants() {
@Override
public BigInteger getMINIMUM_DIFFICULTY() {
return BigInteger.ONE;
}
}));
StandaloneBlockchain blockchain = new StandaloneBlockchain().withAutoblock(true);
System.out.println("Creating first empty block (need some time to generate DAG)...");
blockchain.createBlock();
System.out.println("Done.");
return blockchain;
}
public EasyBlockchain getBlockchain() {
return blockchain;
}
private static String unzip(String data) throws java.io.IOException {
byte[] bytes = java.util.Base64.getDecoder().decode(data);
try (java.util.zip.GZIPInputStream inputStream = new java.util.zip.GZIPInputStream(new java.io.ByteArrayInputStream(bytes));
java.io.ByteArrayOutputStream result = new java.io.ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString("UTF-8");
}
}
${contracts.joinToString("\n") { submitContractTemplate(it) }}
}"""
private fun submitContractTemplate(contract: CompiledContractDefinition): String {
val name = contract.contract.name
val constructor = contract.abis.find { it.isConstructor() }
val params = stringifyParams(constructor)
val paramRefs = paramRefs(constructor)
return """
public $name submit$name($params) {
CompilationResult.ContractMetadata metadata = new CompilationResult.ContractMetadata();
try {
metadata.abi = unzip("${zip(contract.metadata.abi)}");
metadata.bin = unzip("${zip(contract.metadata.bin)}");
} catch (Exception e) {
throw new RuntimeException(e);
}
return new $name(blockchain.submitNewContract(metadata$paramRefs));
}
"""
}
private fun zip(content: String): String {
val baos = ByteArrayOutputStream()
GZIPOutputStream(baos).bufferedWriter().use { it.write(content) }
return Base64.getEncoder().encodeToString(baos.toByteArray())
}
private fun stringifyParams(function: AbiDefinition?): String {
var paramCounter = 0
return function?.inputs?.joinToString(", ") {
"${EthJTypeConverter.convert(it.type)} ${it.name ?: "param${paramCounter++}"}"
} ?: ""
}
private fun convert(contract: CompiledContractDefinition): String {
return contractStubTemplate(contract.contract.name!!, contract.abis.filter { !it.isConstructor() })
}
private fun generateRepo(contracts: List<CompiledContractDefinition>): String {
return contractRepoTemplate(contracts)
}
private fun writeClass(stubsDir: String, className: String, content: String) {
Files.write(Paths.get(stubsDir, "$className.java"), content.toByteArray())
}
}
| mit | 0c8683a517fd32b316b99ace98ffd45c | 35.923077 | 143 | 0.71625 | 4.460967 | false | false | false | false |
android/location-samples | ActivityRecognition/app/src/main/java/com/google/android/gms/location/sample/activityrecognition/MainViewModel.kt | 1 | 4678 | /*
* Copyright 2022 Google, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.activityrecognition
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.location.sample.activityrecognition.PlayServicesAvailableState.Initializing
import com.google.android.gms.location.sample.activityrecognition.PlayServicesAvailableState.PlayServicesAvailable
import com.google.android.gms.location.sample.activityrecognition.PlayServicesAvailableState.PlayServicesUnavailable
import com.google.android.gms.location.sample.activityrecognition.data.ActivityTransitionManager
import com.google.android.gms.location.sample.activityrecognition.data.AppPreferences
import com.google.android.gms.location.sample.activityrecognition.data.PlayServicesAvailabilityChecker
import com.google.android.gms.location.sample.activityrecognition.data.db.ActivityTransitionDao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.time.Instant
import javax.inject.Inject
/**
* View model for the main screen of the app (which also happens to be the only screen). This stores
* state relevant to the UI so that state is properly maintained across configuration changes.
*/
@HiltViewModel
class MainViewModel @Inject constructor(
playServicesAvailabilityChecker: PlayServicesAvailabilityChecker,
private val appPreferences: AppPreferences,
private val activityTransitionManager: ActivityTransitionManager,
private val activityTransitionDao: ActivityTransitionDao
) : ViewModel() {
/**
* Whether Google Play Services are available. Using [stateIn] converts this to a hot flow,
* meaning it can be active even when there are no consumers. It will be started immediately
* with an initial value of [Initializing], then updated once we've checked for Play Services.
*/
val playServicesAvailableState = flow {
emit(
if (playServicesAvailabilityChecker.isGooglePlayServicesAvailable()) {
PlayServicesAvailable
} else {
PlayServicesUnavailable
}
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, Initializing)
val isActivityTransitionUpdatesTurnedOn = appPreferences.isActivityTransitionUpdatesTurnedOn
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
val transitionEvents = activityTransitionDao.getMostRecent()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
var errorMessages by mutableStateOf(emptyList<ErrorMessage>())
private set
fun toggleActivityTransitionUpdates() {
if (isActivityTransitionUpdatesTurnedOn.value) {
stopActivityTransitionUpdates()
} else {
startActivityTransitionUpdates()
}
}
private fun startActivityTransitionUpdates() {
viewModelScope.launch {
if (activityTransitionManager.requestActivityTransitionUpdates()) {
appPreferences.setActivityTransitionUpdatesTurnedOn(true)
} else {
errorMessages = errorMessages + ErrorMessage(R.string.error_requesting_updates)
}
}
}
private fun stopActivityTransitionUpdates() {
viewModelScope.launch {
activityTransitionManager.removeActivityTransitionUpdates()
appPreferences.setActivityTransitionUpdatesTurnedOn(false)
activityTransitionDao.deleteAll()
}
}
fun removeMessage(errorMessage: ErrorMessage) {
errorMessages = errorMessages.filterNot { it == errorMessage }
}
}
enum class PlayServicesAvailableState {
Initializing, PlayServicesUnavailable, PlayServicesAvailable
}
data class ErrorMessage(@StringRes val resId: Int, val time: Instant = Instant.now())
| apache-2.0 | 1dcae2010e367c7c1fe1619e9c8790fd | 41.144144 | 116 | 0.762719 | 5.197778 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Modules.kt | 1 | 44461 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
enum class Module(
val key: String,
val packageName: String,
packageInfo: String,
internal val callingConvention: CallingConvention = CallingConvention.DEFAULT,
internal val library: JNILibrary? = null,
internal val arrayOverloads: Boolean = true
) {
CORE("core", "org.lwjgl.system", ""),
CORE_JNI(
"core.jni",
"org.lwjgl.system.jni",
"Contains bindings to the Java Native Interface (JNI)."
),
CORE_LIBC(
"core.libc",
"org.lwjgl.system.libc",
"Contains bindings to standard C library APIs."
),
CORE_LIBFFI(
"core.libffi",
"org.lwjgl.system.libffi",
"""
Contains bindings to the ${url("https://sourceware.org/libffi/", "libffi")}, a portable, high level programming interface to various calling
conventions. This allows a programmer to call any function specified by a call interface description at run-time.
"""
),
CORE_LINUX(
"core.linux",
"org.lwjgl.system.linux",
"Contains bindings to native APIs specific to the Linux operating system."
),
CORE_LINUX_LIBURING(
"core.linux.liburing",
"org.lwjgl.system.linux.liburing",
"Contains bindings to liburing." // TODO:
),
CORE_MACOS(
"core.macos",
"org.lwjgl.system.macosx",
"Contains bindings to native APIs specific to the macOS operating system."
),
CORE_WINDOWS(
"core.windows",
"org.lwjgl.system.windows",
"Contains bindings to native APIs specific to the Windows operating system.",
CallingConvention.STDCALL
),
ASSIMP(
"assimp",
"org.lwjgl.assimp",
"""
Contains bindings to the ${url("http://www.assimp.org/", "Assimp")} library, a library to import and export various 3d-model-formats including
scene-post-processing to generate missing render data.
Assimp aims to provide a full asset conversion pipeline for use in game engines / realtime rendering systems of any kind, but it is not limited to this
purpose. In the past, it has been used in a wide range of applications.
Written in C++, it is available under a liberal BSD license. Assimp loads all input model formats into one straightforward data structure for further
processing. This feature set is augmented by various post processing tools, including frequently-needed operations such as computing normal and tangent
vectors.
"""
),
BGFX(
"bgfx",
"org.lwjgl.bgfx",
"""
Contains bindings to the ${url("https://github.com/bkaradzic/bgfx", "bgfx")} library.
The bgfx documentation can be found online ${url("https://bkaradzic.github.io/bgfx/", "here")}. The API reference is available
${url("https://bkaradzic.github.io/bgfx/bgfx.html", "here")}.
Starting with LWJGL 3.2.1, builds of the bgfx tools are available for download via the LWJGL site's <a href="https://www.lwjgl.org/browse">file
browser</a>. These tools are:
${ul(
"Geometry Compiler (geometryc)",
"Shader Compiler (shaderc)",
"Texture Compiler (texturec)",
"Texture Viewer (texturev)"
)}
The binaries are built from source, at the corresponding commit that was used to build the bgfx library. For example, the latest Windows x64 version of
shaderc can be found under {@code nightly/windows/x64/bgfx-tools/}.
"""
),
CUDA(
"cuda",
"org.lwjgl.cuda",
"""
Contains bindings to <a href="https://developer.nvidia.com/cuda-zone">CUDA</a>.
<h3>UNSTABLE API</h3>
Until these bindings are sufficiently tested, this API should be considered unstable. Also, bindings to more (and eventually, all) CUDA Toolkit
libraries will be added in the near future.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
EGL(
"egl",
"org.lwjgl.egl",
"""
Contains bindings to the ${url("https://www.khronos.org/egl", "EGL")} API, an interface between Khronos rendering APIs such as OpenGL ES or OpenVG and
the underlying native platform window system. It handles graphics context management, surface/buffer binding and rendering synchronization and enables
high-performance, accelerated, mixed-mode 2D and 3D rendering using other Khronos APIs.
The ${url("https://www.khronos.org/registry/EGL/", "Khronos EGL registry")} is a useful online resource that contains the EGL specification, as well
as specifications of EGL extensions.
""",
CallingConvention.STDCALL
),
GLFW(
"glfw",
"org.lwjgl.glfw",
"""
Contains bindings to the ${url("http://www.glfw.org/", "GLFW")} library.
GLFW comes with extensive documentation, which you can read online ${url("http://www.glfw.org/docs/latest/", "here")}. The
${url("http://www.glfw.org/faq.html", "Frequently Asked Questions")} are also useful.
<h3>Using GLFW on macOS</h3>
On macOS the JVM must be started with the {@code -XstartOnFirstThread} argument for GLFW to work. This is necessary because most GLFW functions must be
called on the main thread and the Cocoa API requires that thread to be the first thread in the process. GLFW windows and the GLFW event loop are
incompatible with other window toolkits (such as AWT/Swing or JavaFX).
Applications that cannot function with the above limitation may set {@link org.lwjgl.system.Configuration\#GLFW_LIBRARY_NAME GLFW_LIBRARY_NAME} to the
value {@code "glfw_async"}. This will instruct LWJGL to load an alternative GLFW build that dispatches Cocoa calls to the main thread in blocking mode.
The other window toolkit must be initialized (e.g. with AWT's {@code Toolkit.getDefaultToolkit()}) before #Init() is called.
"""
),
JAWT(
"jawt",
"org.lwjgl.system.jawt",
"Contains bindings to the AWT native interface (jawt.h).",
CallingConvention.STDCALL
),
JEMALLOC(
"jemalloc",
"org.lwjgl.system.jemalloc",
"""
Contains bindings to the ${url("http://jemalloc.net/", "jemalloc")} library. jemalloc is a general purpose malloc implementation that emphasizes
fragmentation avoidance and scalable concurrency support.
The jemalloc documentation can be found ${url("http://jemalloc.net/jemalloc.3.html", "here")}. The jemalloc
${url("https://github.com/jemalloc/jemalloc/wiki", "wiki")} also contains useful information.
The jemalloc shared library that comes with LWJGL is configured with:
${ul(
"--with-jemalloc-prefix=je_",
"--enable-lazy-lock (Linux)",
"--disable-stats",
"--disable-fill",
"--disable-cxx",
"--disable-initial-exec-tls (Linux & macOS)",
"--disable-zone-allocator (macOS)"
)}
The shared library may be replaced with a custom build that has more features enabled.
Dynamic configuration (for enabled features) is also possible, using either the {@code MALLOC_CONF} environment variable or the
${url("http://jemalloc.net/jemalloc.3.html\\#mallctl_namespace", "MALLCTL NAMESPACE")} and the {@code mallctl*} functions.
"""
),
LIBDIVIDE(
"libdivide",
"org.lwjgl.util.libdivide",
"Contains bindings to ${url("https://libdivide.com/", "libdivide")}.",
library = JNILibrary.simple(),
arrayOverloads = false
),
LLVM(
"llvm",
"org.lwjgl.llvm",
"""
Contains bindings to <a href="https://llvm.org/">LLVM</a>, a collection of modular and reusable compiler and toolchain technologies.
<h3>UNSTABLE API</h3>
Until these bindings are sufficiently tested, this API should be considered unstable.
<h3>BINDINGS ONLY</h3>
LWJGL does not currently include pre-built LLVM/Clang binaries. The user must download or build LLVM separately and use
{@link org.lwjgl.system.Configuration Configuration} to point LWJGL to the appropriate binaries.
""",
library = JNILibrary.create("LibLLVM"),
arrayOverloads = false
),
LMDB(
"lmdb",
"org.lwjgl.util.lmdb",
"""
Bindings to ${url("https://symas.com/lmdb/", "LMDB")}, the Symas Lightning Memory-Mapped Database.
LMDB is a Btree-based database management library modeled loosely on the BerkeleyDB API, but much simplified. The entire database is exposed in a
memory map, and all data fetches return data directly from the mapped memory, so no malloc's or memcpy's occur during data fetches. As such, the
library is extremely simple because it requires no page caching layer of its own, and it is extremely high performance and memory-efficient. It is also
fully transactional with full ACID semantics, and when the memory map is read-only, the database integrity cannot be corrupted by stray pointer writes
from application code.
The library is fully thread-aware and supports concurrent read/write access from multiple processes and threads. Data pages use a copy-on-write
strategy so no active data pages are ever overwritten, which also provides resistance to corruption and eliminates the need of any special recovery
procedures after a system crash. Writes are fully serialized; only one write transaction may be active at a time, which guarantees that writers can
never deadlock. The database structure is multi-versioned so readers run with no locks; writers cannot block readers, and readers don't block writers.
Unlike other well-known database mechanisms which use either write-ahead transaction logs or append-only data writes, LMDB requires no maintenance
during operation. Both write-ahead loggers and append-only databases require periodic checkpointing and/or compaction of their log or database files
otherwise they grow without bound. LMDB tracks free pages within the database and re-uses them for new write operations, so the database size does not
grow without bound in normal use.
The memory map can be used as a read-only or read-write map. It is read-only by default as this provides total immunity to corruption. Using read-write
mode offers much higher write performance, but adds the possibility for stray application writes thru pointers to silently corrupt the database. Of
course if your application code is known to be bug-free (...) then this is not an issue.
<h3>Restrictions/caveats (in addition to those listed for some functions)</h3>
${ul(
"""
Only the database owner should normally use the database on BSD systems or when otherwise configured with {@code MDB_USE_POSIX_SEM}. Multiple users
can cause startup to fail later, as noted above.
""",
"""
There is normally no pure read-only mode, since readers need write access to locks and lock file. Exceptions: On read-only filesystems or with the
#NOLOCK flag described under #env_open().
""",
"""
An LMDB configuration will often reserve considerable unused memory address space and maybe file size for future growth. This does not use actual
memory or disk space, but users may need to understand the difference so they won't be scared off.
""",
"""
By default, in versions before 0.9.10, unused portions of the data file might receive garbage data from memory freed by other code. (This does not
happen when using the #WRITEMAP flag.) As of 0.9.10 the default behavior is to initialize such memory before writing to the data file. Since there
may be a slight performance cost due to this initialization, applications may disable it using the #NOMEMINIT flag. Applications handling sensitive
data which must not be written should not use this flag. This flag is irrelevant when using #WRITEMAP.
""",
"""
A thread can only use one transaction at a time, plus any child transactions. Each transaction belongs to one thread. The #NOTLS flag changes this
for read-only transactions.
""",
"Use an {@code MDB_env*} in the process which opened it, without {@code fork()}ing.",
"""
Do not have open an LMDB database twice in the same process at the same time. Not even from a plain {@code open()} call - {@code close()}ing it
breaks {@code flock()} advisory locking.
""",
"""
Avoid long-lived transactions. Read transactions prevent reuse of pages freed by newer write transactions, thus the database can grow quickly.
Write transactions prevent other write transactions, since writes are serialized.
""",
"""
Avoid suspending a process with active transactions. These would then be "long-lived" as above. Also read transactions suspended when writers
commit could sometimes see wrong data.
"""
)}
...when several processes can use a database concurrently:
${ul(
"""
Avoid aborting a process with an active transaction. The transaction becomes "long-lived" as above until a check for stale readers is performed or
the lockfile is reset, since the process may not remove it from the lockfile.
This does not apply to write transactions if the system clears stale writers, see above.
""",
"If you do that anyway, do a periodic check for stale readers. Or close the environment once in a while, so the lockfile can get reset.",
"""
Do not use LMDB databases on remote filesystems, even between processes on the same host. This breaks {@code flock()} on some OSes, possibly memory
map sync, and certainly sync between programs on different hosts.
""",
"Opening a database can fail if another process is opening or closing it at exactly the same time."
)}
<h3>Reader Lock Table</h3>
Readers don't acquire any locks for their data access. Instead, they simply record their transaction ID in the reader table. The reader mutex is needed
just to find an empty slot in the reader table. The slot's address is saved in thread-specific data so that subsequent read transactions started by the
same thread need no further locking to proceed.
If #NOTLS is set, the slot address is not saved in thread-specific data.
No reader table is used if the database is on a read-only filesystem, or if #NOLOCK is set.
Since the database uses multi-version concurrency control, readers don't actually need any locking. This table is used to keep track of which readers
are using data from which old transactions, so that we'll know when a particular old transaction is no longer in use. Old transactions that have
discarded any data pages can then have those pages reclaimed for use by a later write transaction.
The lock table is constructed such that reader slots are aligned with the processor's cache line size. Any slot is only ever used by one thread. This
alignment guarantees that there will be no contention or cache thrashing as threads update their own slot info, and also eliminates any need for
locking when accessing a slot.
A writer thread will scan every slot in the table to determine the oldest outstanding reader transaction. Any freed pages older than this will be
reclaimed by the writer. The writer doesn't use any locks when scanning this table. This means that there's no guarantee that the writer will see the
most up-to-date reader info, but that's not required for correct operation - all we need is to know the upper bound on the oldest reader, we don't care
at all about the newest reader. So the only consequence of reading stale information here is that old pages might hang around a while longer before
being reclaimed. That's actually good anyway, because the longer we delay reclaiming old pages, the more likely it is that a string of contiguous pages
can be found after coalescing old pages from many old transactions together.
""",
library = JNILibrary.create("LibLMDB", setupAllocator = true)
),
LZ4(
"lz4",
"org.lwjgl.util.lz4",
"""
Contains bindings to ${url("http://lz4.github.io/lz4/", "LZ4")}, a lossless compression algorithm, providing compression speed > 500 MB/s per core,
scalable with multi-cores CPU. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limits on
multi-core systems.
""",
library = JNILibrary.create("LibLZ4", setupAllocator = true),
arrayOverloads = false
),
MEOW(
"meow",
"org.lwjgl.util.meow",
"Contains bindings to ${url("https://github.com/cmuratori/meow_hash", "Meow hash")}, an extremely fast non-cryptographic hash.",
library = JNILibrary.create("LibMeow"),
arrayOverloads = false
),
MESHOPTIMIZER(
"meshoptimizer",
"org.lwjgl.util.meshoptimizer",
"Contains bindings to ${url("https://github.com/zeux/meshoptimizer", "meshoptimizer")}, a library that provides algorithms to help optimize meshes.",
library = JNILibrary.create("LibMeshOptimizer"),
arrayOverloads = false
),
NANOVG(
"nanovg",
"org.lwjgl.nanovg",
"""
Contains bindings to ${url("https://github.com/memononen/nanovg", "NanoVG")}, a small antialiased vector graphics rendering library for OpenGL. It has
lean API modeled after HTML5 canvas API. It is aimed to be a practical and fun toolset for building scalable user interfaces and visualizations.
""",
library = JNILibrary.create("LibNanoVG", setupAllocator = true)
),
NFD(
"nfd",
"org.lwjgl.util.nfd",
"""
Contains bindings to ${url("https://github.com/mlabbe/nativefiledialog", "Native File Dialog")}, a tiny, neat C library that portably invokes native
file open and save dialogs. Write dialog code once and have it popup native dialogs on all supported platforms.
""",
library = JNILibrary.create("LibNFD", setupAllocator = true)
),
NUKLEAR(
"nuklear",
"org.lwjgl.nuklear",
"""
Bindings to the ${url("https://github.com/vurtun/nuklear", "Nuklear")} library.
A minimal state immediate mode graphical user interface single header toolkit written in ANSI C and licensed under public domain. It was designed as a
simple embeddable user interface for application and does not have any dependencies, a default renderbackend or OS window and input handling but
instead provides a very modular library approach by using simple input state for input and draw commands describing primitive shapes as output. So
instead of providing a layered library that tries to abstract over a number of platform and render backends it only focuses on the actual UI.
Developed by Micha Mettke.
""",
library = JNILibrary.simple()
),
ODBC(
"odbc",
"org.lwjgl.odbc",
"""
Contains bindings to ${url("https://docs.microsoft.com/en-us/sql/odbc/microsoft-open-database-connectivity-odbc", "ODBC")}.
The Microsoft Open Database Connectivity (ODBC) interface is a C programming language interface that makes it possible for applications to access data
from a variety of database management systems (DBMSs). ODBC is a low-level, high-performance interface that is designed specifically for relational
data stores.
The ODBC interface allows maximum interoperability — an application can access data in diverse DBMSs through a single interface. Moreover, that
application will be independent of any DBMS from which it accesses data. Users of the application can add software components called drivers, which
interface between an application and a specific DBMS.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
OPENAL(
"openal",
"org.lwjgl.openal",
"""
Contains bindings to the ${url("http://www.openal.org/", "OpenAL")} cross-platform 3D audio API.
LWJGL comes with a software OpenAL implementation, ${url("http://www.openal-soft.org/", "OpenAL Soft")}.
OpenAL Soft can be dynamically configured with ${url("https://github.com/kcat/openal-soft/blob/master/docs/env-vars.txt", "environment variables")}. A
very useful option for debugging is {@code ALSOFT_LOGLEVEL}; it can be set to values 0 through 4, with higher values producing more information.
In addition to standard OpenAL features, OpenAL Soft supports ${url("https://en.wikipedia.org/wiki/Head-related_transfer_function", "HRTF")},
${url("https://en.wikipedia.org/wiki/Ambisonics", "Ambisonics")} and ${url("http://www.codemasters.com/research/3D_sound_for_3D_games.pdf", "3D7.1")}.
Documentation for these features is available in the OpenAL Soft ${url("https://github.com/kcat/openal-soft/tree/master/docs", "repository")}.
"""
),
OPENCL(
"opencl",
"org.lwjgl.opencl",
"""
Contains bindings to the ${url("https://www.khronos.org/opencl/", "OpenCL")} cross-platform parallel programming API.
The ${url("https://www.khronos.org/registry/OpenCL/", "Khronos OpenCL registry")} is a useful online resource that contains the OpenCL specification, as
well as the specifications of OpenCL extensions.
""",
CallingConvention.STDCALL
),
OPENGL(
"opengl",
"org.lwjgl.opengl",
"""
Contains bindings to the ${url("https://www.opengl.org/", "OpenGL")} cross-platform 2D and 3D rendering API.
The ${url("https://www.khronos.org/registry/OpenGL/index_gl.php", "OpenGL registry")} is a useful online resource that contains the OpenGL and OpenGL
Shading Language specifications, as well as specifications of OpenGL extensions.
The ${url("https://www.khronos.org/registry/OpenGL-Refpages/", "OpenGL Reference Pages")} is another convenient source of documentation.
The bindings of the core OpenGL functionality are contained in two distinct class hierarchies:
${ul(
"{@code GL11..GL46}: all symbols of the Compatibility Profile are included",
"{@code GL11C..GL46C}: only symbols of the Core Profile are included"
)}
Each of the above classes extends the class of the previous OpenGL version in the corresponding hierarchy.
The recommended way to write OpenGL applications with LWJGL is to statically import the class that corresponds to the minimum required OpenGL version.
This will expose all symbols up to that version. Additional functionality (later core versions or extensions) should be guarded with appropriate checks
using the {@link org.lwjgl.opengl.GLCapabilities GLCapabilities} instance of the OpenGL context.
The Compatibility Profile and Core Profile class hierarchies should not be mixed with static imports, as that would result in compilation ambiguities
when resolving the symbols. Note that the Compatibility Profile hierarchy can be used with a Core Profile context (as long as no deprecated symbol is
used) and the Core Profile hierarchy can be used with a Compatibility Profile context. The recommendation is to use the Compatibility Profile hierarchy
only when deprecated functionality is required. In any other case, the Core Profile hierarchy should be preferred.
For example, an OpenGL application that requires OpenGL 3.3, must use modern OpenGL features only and needs the best possible performance:
${ul(
"Should create a 3.3 Compatibility Profile context. A Core Profile context would have extra validation overhead.",
"Should use the Core Profile hierarchy to avoid deprecated symbols. Auto-complete lists in an IDE will also be cleaner."
)}
""",
CallingConvention.STDCALL,
library = JNILibrary.create("GL", custom = true)
),
OPENGLES(
"opengles",
"org.lwjgl.opengles",
"""
Contains bindings to the ${url("https://www.khronos.org/opengles/", "OpenGL ES")}, a royalty-free, cross-platform API for full-function 2D and 3D
graphics on embedded systems - including consoles, phones, appliances and vehicles. It consists of well-defined subsets of desktop OpenGL, creating a
flexible and powerful low-level interface between software and graphics acceleration.
The ${url(
"https://www.khronos.org/registry/OpenGL/index_es.php",
"Khronos OpenGL ES registry"
)} is a useful online resource that contains the OpenGL ES and OpenGL
ES Shading Language specifications, as well as specifications of OpenGL ES extensions. The ${url(
"https://www.khronos.org/registry/OpenGL-Refpages/",
"OpenGL ES Reference Pages"
)} is another convenient source of documentation.
""",
CallingConvention.STDCALL,
library = JNILibrary.create("GLES", custom = true)
),
OPENVR(
"openvr",
"org.lwjgl.openvr",
"""
Contains bindings to ${url("https://github.com/ValveSoftware/openvr", "OpenVR")}.
OpenVR is an API and runtime that allows access to VR hardware from multiple vendors without requiring that applications have specific knowledge of the
hardware they are targeting.
""",
CallingConvention.STDCALL,
library = JNILibrary.create("OpenVR", custom = true),
arrayOverloads = false
),
OPENXR(
"openxr",
"org.lwjgl.openxr",
"""
Contains bindings to ${url("https://www.khronos.org/openxr/", "OpenXR")}.
OpenXR is a royalty-free, open standard that provides high-performance access to Augmented Reality (AR) and Virtual Reality (VR)—collectively known as
XR—platforms and devices.
""",
CallingConvention.STDCALL,
arrayOverloads = false
),
OPUS(
"opus",
"org.lwjgl.util.opus",
"Contains bindings to the <a href=\"https://opus-codec.org\">opus-codec</a> library.",
arrayOverloads = false
),
OVR(
"ovr",
"org.lwjgl.ovr",
"""
Contains bindings to LibOVR, the ${url("https://developer.oculus.com/", "Oculus SDK")} library.
Documentation on how to get started with the Oculus SDK can be found ${url("https://developer.oculus.com/documentation/", "here")}.
""",
library = JNILibrary.create("LibOVR")
),
PAR(
"par",
"org.lwjgl.util.par",
"Contains bindings to the ${url("https://github.com/prideout/par", "par")} library.",
library = JNILibrary.create("LibPar", setupAllocator = true)
),
REMOTERY(
"remotery",
"org.lwjgl.util.remotery",
"""
Contains bindings to ${url("https://github.com/Celtoys/Remotery", "Remotery")}, a realtime CPU/GPU profiler hosted in a single C file with a viewer
that runs in a web browser.
""",
library = JNILibrary.create("LibRemotery"),
arrayOverloads = false
),
RPMALLOC(
"rpmalloc",
"org.lwjgl.system.rpmalloc",
"""
Contains bindings to the ${url("https://github.com/mjansson/rpmalloc", "rpmalloc")} library. rpmalloc is a public domain cross platform lock free
thread caching 16-byte aligned memory allocator implemented in C.
""",
library = JNILibrary.create("LibRPmalloc"),
arrayOverloads = false
),
SHADERC(
"shaderc",
"org.lwjgl.util.shaderc",
"""
Contains bindings to ${url("https://github.com/google/shaderc", "Shaderc")}, a collection of libraries for shader compilation.
Shaderc wraps around core functionality in ${url("https://github.com/KhronosGroup/glslang", "glslang")} and ${url(
"https://github.com/KhronosGroup/SPIRV-Tools",
"SPIRV-Tools"
)}. Shaderc aims to to provide:
${ul(
"a command line compiler with GCC- and Clang-like usage, for better integration with build systems",
"an API where functionality can be added without breaking existing clients",
"an API supporting standard concurrency patterns across multiple operating systems",
"increased functionality such as file \\#include support"
)}
""",
arrayOverloads = false
),
SPVC(
"spvc",
"org.lwjgl.util.spvc",
"""
Contains bindings to ${url("https://github.com/KhronosGroup/SPIRV-Cross", "SPIRV-Cross")}, a library for performing reflection on SPIR-V and
disassembling SPIR-V back to high level languages.
""",
arrayOverloads = false
),
SSE(
"sse",
"org.lwjgl.util.simd",
"Contains bindings to SSE macros.",
library = JNILibrary.create("LibSSE")
),
STB(
"stb",
"org.lwjgl.stb",
"""
Contains bindings to ${url("https://github.com/nothings/stb", "stb")}, a set of single-file public domain libraries.
The functionality provided by stb includes:
${ul(
"Parsing TrueType files, extract glyph metrics and rendering packed font textures.",
"Easy rendering of bitmap fonts.",
"Reading/writing image files and resizing images (e.g. for gamma-correct MIP map creation).",
"Decoding Ogg Vorbis audio files.",
"Compressing DXT textures at runtime.",
"Packing rectangular textures into texture atlases.",
"Computing Perlin noise."
)}
""",
library = JNILibrary.create("LibSTB", setupAllocator = true)
),
TINYEXR(
"tinyexr",
"org.lwjgl.util.tinyexr",
"""
Contains bindings to the ${url("https://github.com/syoyo/tinyexr", "Tiny OpenEXR")} image library.
tinyexr is a small, single header-only library to load and save OpenEXR(.exr) images.
""",
library = JNILibrary.simple(),
arrayOverloads = false
),
TINYFD(
"tinyfd",
"org.lwjgl.util.tinyfd",
"Contains bindings to ${url("https://sourceforge.net/projects/tinyfiledialogs/", "tiny file dialogs")}.",
library = JNILibrary.simple(
"""Library.loadSystem(System::load, System::loadLibrary, TinyFileDialogs.class, "org.lwjgl.tinyfd", Platform.mapLibraryNameBundled("lwjgl_tinyfd"));
if (Platform.get() == Platform.WINDOWS) {
tinyfd_setGlobalInt("tinyfd_winUtf8", 1);
}"""
)
),
TOOTLE(
"tootle",
"org.lwjgl.util.tootle",
"""
Contains bindings to ${url("https://github.com/GPUOpen-Tools/amd-tootle", "AMD Tootle")}.
AMD Tootle (Triangle Order Optimization Tool) is a 3D triangle mesh optimization library that improves on existing mesh preprocessing techniques. By
using AMD Tootle, developers can optimize their models for pixel overdraw as well as vertex cache performance. This can provide significant performance
improvements in pixel limited situations, with no penalty in vertex-limited scenarios, and no runtime cost.
""",
library = JNILibrary.simple(),
arrayOverloads = false
),
VMA(
"vma",
"org.lwjgl.util.vma",
"""
Contains bindings to ${url("https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator", "Vulkan")}, an easy to integrate Vulkan memory
allocation library.
<h4>Problem</h4>
Memory allocation and resource (buffer and image) creation in Vulkan is difficult (comparing to older graphics API-s, like D3D11 or OpenGL) for several
reasons:
${ul(
"It requires a lot of boilerplate code, just like everything else in Vulkan, because it is a low-level and high-performance API.",
"""
There is additional level of indirection: {@code VkDeviceMemory} is allocated separately from creating {@code VkBuffer/VkImage} and they must be
bound together. The binding cannot be changed later - resource must be recreated.
""",
"Driver must be queried for supported memory heaps and memory types. Different IHVs provide different types of it.",
"It is recommended practice to allocate bigger chunks of memory and assign parts of them to particular resources."
)}
<h4>Features</h4>
This library can help game developers to manage memory allocations and resource creation by offering some higher-level functions. Features of the
library are divided into several layers, low level to high level:
${ol(
"""
Functions that help to choose correct and optimal memory type based on intended usage of the memory.
- Required or preferred traits of the memory are expressed using higher-level description comparing to Vulkan flags.
""",
"""
Functions that allocate memory blocks, reserve and return parts of them (`VkDeviceMemory` + offset + size) to the user.
- Library keeps track of allocated memory blocks, used and unused ranges inside them, finds best matching unused ranges for new allocations, takes
all the rules of alignment and buffer/image granularity into consideration.
""",
"Functions that can create an image/buffer, allocate memory for it and bind them together - all in one call."
)}
Additional features:
${ul(
"Thread-safety: Library is designed to be used by multithreaded code.",
"Configuration: Fill optional members of CreateInfo structure to provide custom CPU memory allocator and other parameters.",
"""
Customization: Predefine appropriate macros to provide your own implementation of all external facilities used by the library, from assert, mutex,
and atomic, to vector and linked list.
""",
"""
Support memory mapping, reference-counted internally. Support for persistently mapped memory: Just allocate with appropriate flag and you get
access to mapped pointer.
""",
"Custom memory pools: Create a pool with desired parameters (e.g. fixed or limited maximum size) and allocate memory out of it.",
"Support for VK_KHR_dedicated_allocation extension: Enable it and it will be used automatically by the library.",
"Defragmentation: Call one function and let the library move data around to free some memory blocks and make your allocations better compacted.",
"""
Lost allocations: Allocate memory with appropriate flags and let the library remove allocations that are not used for many frames to make room for
new ones.
""",
"""
Statistics: Obtain detailed statistics about the amount of memory used, unused, number of allocated blocks, number of allocations etc. - globally,
per memory heap, and per memory type.
""",
"Debug annotations: Associate string with name or opaque pointer to your own data with every allocation.",
"JSON dump: Obtain a string in JSON format with detailed map of internal state, including list of allocations and gaps between them."
)}
""",
library = JNILibrary.create("LibVma", setupAllocator = true, cpp = true),
arrayOverloads = false
),
VULKAN(
"vulkan",
"org.lwjgl.vulkan",
"""
Contains bindings to ${url("https://www.khronos.org/vulkan/", "Vulkan")}, a new generation graphics and compute API that provides high-efficiency,
cross-platform access to modern GPUs used in a wide variety of devices from PCs and consoles to mobile phones and embedded platforms.
Experimental extensions (KHX, NVX, etc) is not supported API. When such an extension is promoted to stable, the corresponding experimental bindings
will be removed.
<b>macOS</b>: LWJGL bundles ${url("https://moltengl.com/moltenvk/", "MoltenVK")}, which emulates Vulkan over Metal.
""",
CallingConvention.STDCALL
),
XXHASH(
"xxhash",
"org.lwjgl.util.xxhash",
"""
Contains bindings to ${url("https://github.com/Cyan4973/xxHash", "xxHash")}, an extremely fast non-cryptographic hash algorithm.
xxHash successfully completes the ${url("https://github.com/aappleby/smhasher", "SMHasher")} test suite which evaluates collision, dispersion and
randomness qualities of hash functions.
""",
library = JNILibrary.create("LibXXHash", setupAllocator = true)
),
YOGA(
"yoga",
"org.lwjgl.util.yoga",
"""
Contains bindings to ${url("https://facebook.github.io/yoga/", "Yoga")}.
Yoga is a cross-platform layout engine enabling maximum collaboration within your team by implementing an API familiar to many designers and opening it
up to developers across different platforms.
${ul(
"Do you already know Flexbox? Then you already know Yoga.",
"Write code in a language familiar to you - Java, C#, Objective-C, C.",
"C under the hood so your code moves fast.",
"Battle tested in popular frameworks like React Native."
)}
<h3>LWJGL implementation</h3>
Unlike the official Yoga Java bindings, the LWJGL bindings directly expose the native C API. {@code YGNodeRef} handles do not need to be wrapped in Java
instances, so there is no memory overhead. The internal Yoga structs are also exposed, which makes it very efficient to read the current tree layout
after a call to #NodeCalculateLayout():
${codeBlock("""
// Public API, 4x JNI call overhead
float l = YGNodeLayoutGetLeft(node);
float t = YGNodeLayoutGetTop(node);
float w = YGNodeLayoutGetWidth(node);
float h = YGNodeLayoutGetHeight(node);
// Internal API without overhead (plain memory accesses, assuming allocations are eliminated via EA)
YGLayout layout = YGNode.create(node).layout();
float l = layout.positions(YGEdgeLeft);
float t = layout.positions(YGEdgeTop);
float w = layout.dimensions(YGDimensionWidth);
float h = layout.dimensions(YGDimensionHeight);""")}
""",
library = JNILibrary.create("LibYoga"),
arrayOverloads = false
),
ZSTD(
"zstd",
"org.lwjgl.util.zstd",
"""
Contains bindings to ${url("http://facebook.github.io/zstd/", "Zstandard")} (zstd), a fast lossless compression algorithm, targeting real-time
compression scenarios at zlib-level and better compression ratios.
Zstandard is a real-time compression algorithm, providing high compression ratios. It offers a very wide range of compression / speed trade-off, while
being backed by a very fast decoder. It also offers a special mode for small data, called dictionary compression, and can create dictionaries from any
sample set.
""",
library = JNILibrary.create("LibZstd", setupAllocator = true),
arrayOverloads = false
);
companion object {
internal val CHECKS = !System.getProperty("binding.DISABLE_CHECKS", "false")!!.toBoolean()
}
init {
if (packageInfo.isNotEmpty()) {
packageInfo(this, packageInfo)
}
if (library != null && enabled) {
library.configure(this)
}
}
val enabled
get() = key.startsWith("core") || System.getProperty("binding.$key", "false")!!.toBoolean()
val path = if (name.startsWith("CORE_")) "core" else name.lowercase()
val java = if (name.startsWith("CORE_")) "org.lwjgl" else "org.lwjgl.${name.lowercase()}"
internal val packageKotlin
get() = name.let {
if (it.startsWith("CORE_")) {
this.key
} else {
it.lowercase()
}
}
@Suppress("LeakingThis")
private val CALLBACK_RECEIVER = ANONYMOUS.nativeClass(this)
fun callback(init: NativeClass.() -> FunctionType) = CALLBACK_RECEIVER.init()
}
internal interface JNILibrary {
companion object {
fun simple(expression: String? = null): JNILibrary = JNILibrarySimple(expression)
fun create(className: String, custom: Boolean = false, setupAllocator: Boolean = false, cpp: Boolean = false): JNILibrary =
JNILibraryWithInit(className, custom, setupAllocator, cpp)
}
fun expression(module: Module): String
fun configure(module: Module)
}
private class JNILibrarySimple(private val expression: String?) : JNILibrary {
override fun expression(module: Module) = if (expression != null)
expression
else
"lwjgl_${module.key}"
override fun configure(module: Module) = Unit
}
private class JNILibraryWithInit constructor(
private val className: String,
private val custom: Boolean = false,
private val setupAllocator: Boolean = false,
private val cpp: Boolean = false
) : JNILibrary {
override fun expression(module: Module) = "$className.initialize();"
override fun configure(module: Module) {
if (custom) {
return
}
Generator.register(object : GeneratorTargetNative(module, className) {
init {
this.access = Access.INTERNAL
this.cpp = [email protected]
this.documentation = "Initializes the ${module.key} shared library."
javaImport("org.lwjgl.system.*")
if (setupAllocator)
javaImport("static org.lwjgl.system.MemoryUtil.*")
nativeDirective(
"""#define LWJGL_MALLOC_LIB $nativeFileNameJNI
#include "lwjgl_malloc.h""""
)
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println(
"""${access.modifier}final class $className {
static {
String libName = Platform.mapLibraryNameBundled("lwjgl_${module.key}");
Library.loadSystem(System::load, System::loadLibrary, $className.class, "${module.java}", libName);${if (setupAllocator) """
MemoryAllocator allocator = getAllocator(Configuration.DEBUG_MEMORY_ALLOCATOR_INTERNAL.get(true));
setupMalloc(
allocator.getMalloc(),
allocator.getCalloc(),
allocator.getRealloc(),
allocator.getFree(),
allocator.getAlignedAlloc(),
allocator.getAlignedFree()
);""" else ""}
}
private $className() {
}
static void initialize() {
// intentionally empty to trigger static initializer
}${if (setupAllocator) """
private static native void setupMalloc(
long malloc,
long calloc,
long realloc,
long free,
long aligned_alloc,
long aligned_free
);""" else ""}
}"""
)
}
override val skipNative
get() = !setupAllocator
override fun PrintWriter.generateNative() {
generateNativePreamble()
}
})
}
}
fun String.dependsOn(vararg modules: Module): String? = if (modules.any { it.enabled }) this else null | bsd-3-clause | f0fe4e961e32d52efbc5c4bc05fcc17c | 48.286031 | 160 | 0.656642 | 4.654974 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.