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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AndroidX/androidx | fragment/fragment-testing/src/androidTest/java/androidx/fragment/app/testing/FragmentScenarioDialogFragmentTest.kt | 3 | 9850 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app.testing
import androidx.lifecycle.Lifecycle.State
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.hamcrest.CoreMatchers.not
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests for FragmentScenario's implementation against DialogFragment.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class FragmentScenarioDialogFragmentTest {
@Ignore // b/259726188
@Test
fun launchFragment() {
with(launchFragment<SimpleDialogFragment>()) {
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
onView(withText("my button")).inRoot(isDialog()).check(matches(isDisplayed()))
}
}
@Ignore // b/259727355
@Test
fun launchFragmentInContainer() {
with(launchFragmentInContainer<SimpleDialogFragment>()) {
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
// We show SimpleDialogFragment in container so dialog is not created.
assertThat(fragment.dialog).isNull()
}
onView(withText("my button")).inRoot(not(isDialog())).check(matches(isDisplayed()))
}
}
@Test
fun fromResumedToCreated() {
with(launchFragment<SimpleDialogFragment>()) {
moveToState(State.CREATED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.CREATED)
assertWithMessage("The dialog should not exist when the Fragment is only CREATED")
.that(fragment.dialog)
.isNull()
}
}
}
@Test
fun fromResumedToStarted() {
with(launchFragment<SimpleDialogFragment>()) {
moveToState(State.STARTED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.STARTED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromResumedToResumed() {
with(launchFragment<SimpleDialogFragment>()) {
moveToState(State.RESUMED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromResumedToDestroyed() {
with(launchFragment<SimpleDialogFragment>()) {
moveToState(State.DESTROYED)
}
}
@Test
fun fromCreatedToCreated() {
with(launchFragment<SimpleDialogFragment>(initialState = State.CREATED)) {
moveToState(State.CREATED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.CREATED)
assertWithMessage("The dialog should not exist when the Fragment is only CREATED")
.that(fragment.dialog)
.isNull()
}
}
}
@Test
fun fromCreatedToStarted() {
with(launchFragment<SimpleDialogFragment>(initialState = State.CREATED)) {
moveToState(State.STARTED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.STARTED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromCreatedToResumed() {
with(launchFragment<SimpleDialogFragment>(initialState = State.CREATED)) {
moveToState(State.RESUMED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromCreatedToDestroyed() {
with(launchFragment<SimpleDialogFragment>(initialState = State.CREATED)) {
moveToState(State.DESTROYED)
}
}
@Test
fun fromStartedToCreated() {
with(launchFragment<SimpleDialogFragment>(initialState = State.STARTED)) {
moveToState(State.CREATED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.CREATED)
assertWithMessage("The dialog should not exist when the Fragment is only CREATED")
.that(fragment.dialog)
.isNull()
}
}
}
@Test
fun fromStartedToStarted() {
with(launchFragment<SimpleDialogFragment>(initialState = State.STARTED)) {
moveToState(State.STARTED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.STARTED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromStartedToResumed() {
with(launchFragment<SimpleDialogFragment>(initialState = State.STARTED)) {
moveToState(State.RESUMED)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun fromStartedToDestroyed() {
with(launchFragment<SimpleDialogFragment>(initialState = State.STARTED)) {
moveToState(State.DESTROYED)
}
}
@Test
fun fromDestroyedToDestroyed() {
with(launchFragment<SimpleDialogFragment>()) {
moveToState(State.DESTROYED)
moveToState(State.DESTROYED)
}
}
@Test
fun recreateCreatedFragment() {
var numOfInstantiation = 0
with(
launchFragment(initialState = State.CREATED) {
++numOfInstantiation
SimpleDialogFragment()
}
) {
assertThat(numOfInstantiation).isEqualTo(1)
recreate()
assertThat(numOfInstantiation).isEqualTo(2)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.CREATED)
assertWithMessage("The dialog should not exist when the Fragment is only CREATED")
.that(fragment.dialog)
.isNull()
}
}
}
@Test
fun recreateStartedFragment() {
var numOfInstantiation = 0
with(
launchFragment(initialState = State.STARTED) {
++numOfInstantiation
SimpleDialogFragment()
}
) {
assertThat(numOfInstantiation).isEqualTo(1)
recreate()
assertThat(numOfInstantiation).isEqualTo(2)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.STARTED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun recreateResumedFragment() {
var numOfInstantiation = 0
with(
launchFragment {
++numOfInstantiation
SimpleDialogFragment()
}
) {
assertThat(numOfInstantiation).isEqualTo(1)
recreate()
assertThat(numOfInstantiation).isEqualTo(2)
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
}
}
}
@Test
fun dismissDialog() {
with(launchFragment<SimpleDialogFragment>()) {
onFragment { fragment ->
assertThat(fragment.lifecycle.currentState).isEqualTo(State.RESUMED)
assertThat(fragment.dialog).isNotNull()
assertThat(fragment.requireDialog().isShowing).isTrue()
fragment.dismiss()
fragment.parentFragmentManager.executePendingTransactions()
assertThat(fragment.dialog).isNull()
}
}
}
} | apache-2.0 | c7ce17ae96b8759cec2ecbc56051c078 | 34.05694 | 98 | 0.614518 | 5.379574 | false | true | false | false |
MeilCli/Twitter4HK | test/src/main/java/com/twitter/meil_mitu/twitter4hktest/StreamActivity.kt | 1 | 5624 | package com.twitter.meil_mitu.twitter4hktest
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import com.twitter.meil_mitu.twitter4hk.data.DirectMessage
import com.twitter.meil_mitu.twitter4hk.data.Status
import com.twitter.meil_mitu.twitter4hk.data.User
import com.twitter.meil_mitu.twitter4hk.data.UserList
import com.twitter.meil_mitu.twitter4hk.streaming.IStreamListener
import com.twitter.meil_mitu.twitter4hk.streaming.Stream
import com.twitter.meil_mitu.twitter4hk.streaming.user.IUserStreamListener
import com.twitter.meil_mitu.twitter4hk.streaming.user.UserStream
class StreamActivity : Activity(), IUserStreamListener<DirectMessage, Status, User, UserList>, IStreamListener {
var stream : Stream? = null
var textView : TextView?=null
var handler : Handler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handler= Handler()
val scrollView = ScrollView(this)
setContentView(scrollView)
val linearLayout = LinearLayout(this).apply {
orientation= LinearLayout.VERTICAL
}
scrollView.addView(linearLayout)
linearLayout.addView(
Button(this).apply {
text="startStream"
setOnClickListener {
val userStream= twitter.stream.user()
userStream.streamListener= this@StreamActivity
userStream.userStreamListener=this@StreamActivity
userStream.replies= UserStream.RepliesAll
userStream.with= UserStream.WithFollowings
stream=userStream.call()
}
}
,0)
linearLayout.addView(
Button(this).apply {
text="closeStream"
setOnClickListener{
stream?.close()
stream=null
}
}
,1)
textView= TextView(this)
linearLayout.addView(textView,2)
}
fun show(text:String){
handler?.post {
textView?.text= "${textView?.text ?:""} $text \n"
}
}
override fun onException(e: Exception) {
show("exception: ${e.toString()}")
}
override fun onConnect() {
show("connect: ")
}
override fun onDisConnect() {
show("disconnect: ")
}
override fun onClose() {
show("close: ")
}
override fun onStatus(status: Status) {
show("status: ${status.id}")
}
override fun onDeleteStatus(userId: Long, id: Long) {
show("delete_status: $id")
}
override fun onFriends(friends: LongArray) {
show("friends: ${friends.size}")
}
override fun onDirectMessage(directMessage: DirectMessage) {
show("directmessage: ${directMessage.id}")
}
override fun onBlock(user: User, blockedUser: User) {
show("block: ${user.screenName}")
}
override fun onUnBlock(user: User, unblockedUser: User) {
show("unblock: ${user.screenName}")
}
override fun onFavorite(user: User, favoritedUser: User, status: Status) {
show("favorite: ${user.screenName}")
}
override fun onUnFavorite(user: User, unfavoritedUser: User, status: Status) {
show("unfavorite: ${user.screenName}")
}
override fun onFollow(user: User, followedUser: User) {
show("follow: ${user.screenName}")
}
override fun onUnFollow(user: User, unfollowedUser: User) {
show("unfollow: ${user.screenName}")
}
override fun onListCreated(user: User, userList: UserList) {
show("list_created: ${user.screenName}")
}
override fun onListDestroyed(user: User, userList: UserList) {
show("list_destroyed: ${user.screenName}")
}
override fun onListUpdated(user: User, userList: UserList) {
show("list_updated: ${user.screenName}")
}
override fun onListMemberAdded(user: User, addedUser: User, userList: UserList) {
show("list_member_added: ${user.screenName}")
}
override fun onListMemberRemoved(user: User, removedUser: User, userList: UserList) {
show("list_member_removed: ${user.screenName}")
}
override fun onListUserSubscribed(user: User, ownerUser: User, userList: UserList) {
show("list_user_subscribed: ${user.screenName}")
}
override fun onListUserUnSubscribed(user: User, ownerUser: User, userList: UserList) {
show("list_user_unsubscribed: ${user.screenName}")
}
override fun onUserUpdate(user: User) {
show("user_update: ${user.screenName}")
}
override fun onMute(user: User, mutedUser: User) {
show("mute: ${user.screenName}")
}
override fun onUnMute(user: User, unmutedUser: User) {
show("unmute: ${user.screenName}")
}
override fun onFavoritedRetweet(user: User, favoritedRetweetingUser: User, status: Status) {
show("favorited_retweet: ${user.screenName}")
}
override fun onRetweetedRetweet(user: User, retweetedRetweetingUser: User, status: Status) {
show("retweeted_retweet: ${user.screenName}")
}
override fun onQuotedTweet(user: User, quotedUser: User, status: Status) {
show("quotedtweet: ${user.screenName}")
}
override fun onUnknown(line: String) {
show("unknown: $line")
}
} | mit | 267d34ef7b2c515863afcfcacaa6cd48 | 30.601124 | 112 | 0.627489 | 4.356313 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/extraxtExpressionUtils.kt | 3 | 2833 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import org.rust.ide.utils.findExpressionAtCaret
import org.rust.ide.utils.findExpressionInRange
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsItemElement
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.ancestors
import java.util.*
fun findCandidateExpressionsToExtract(editor: Editor, file: RsFile): List<RsExpr> {
val selection = editor.selectionModel
return if (selection.hasSelection()) {
// If there's an explicit selection, suggest only one expression
listOfNotNull(findExpressionInRange(file, selection.selectionStart, selection.selectionEnd))
} else {
val expr = findExpressionAtCaret(file, editor.caretModel.offset)
?: return emptyList()
// Finds possible expressions that might want to be bound to a local variable.
// We don't go further than the current block scope,
// further more path expressions don't make sense to bind to a local variable so we exclude them.
expr.ancestors
.takeWhile { it !is RsBlock }
.filterIsInstance<RsExpr>()
.filter { it !is RsPathExpr }
.toList()
}
}
/**
* Finds occurrences in the sub scope of expr, so that all will be replaced if replace all is selected.
*/
fun findOccurrences(expr: RsExpr): List<RsExpr> {
val parent = expr.ancestorOrSelf<RsBlock>()
?: expr.ancestorOrSelf<RsItemElement>() // outside a function, try to find a parent
?: return emptyList()
return findOccurrences(parent, expr)
}
fun findOccurrences(parent: RsElement, expr: RsExpr): List<RsExpr> {
val visitor = object : PsiRecursiveElementVisitor() {
val foundOccurrences = ArrayList<RsExpr>()
override fun visitElement(element: PsiElement) {
if (element is RsExpr && PsiEquivalenceUtil.areElementsEquivalent(expr, element)) {
foundOccurrences.add(element)
} else {
super.visitElement(element)
}
}
}
parent.acceptChildren(visitor)
return visitor.foundOccurrences
}
fun moveEditorToNameElement(editor: Editor, element: PsiElement?): RsPatBinding? {
val newName = element?.findBinding()
editor.caretModel.moveToOffset(newName?.identifier?.textRange?.startOffset ?: 0)
return newName
}
fun PsiElement.findBinding() = PsiTreeUtil.findChildOfType(this, RsPatBinding::class.java)
| mit | 16fbc4bba8152e285b287ed7b8afd4a4 | 38.901408 | 105 | 0.712672 | 4.482595 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/rest/pagination-keyset-gui-v2/src/main/kotlin/org/tsdes/advanced/rest/guiv2/BookRest.kt | 1 | 4693 | package org.tsdes.advanced.rest.guiv2
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.tsdes.advanced.rest.guiv2.dto.BookDto
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.tsdes.advanced.rest.dto.PageDto
import org.tsdes.advanced.rest.dto.RestResponseFactory
import org.tsdes.advanced.rest.dto.WrappedResponse
import org.tsdes.advanced.rest.guiv2.db.Book
import org.tsdes.advanced.rest.guiv2.db.BookRepository
import java.net.URI
@Api(value = "/api/books", description = "Handling of creating and retrieving book entries")
@RequestMapping(path = ["/api/books"], produces = [MediaType.APPLICATION_JSON_UTF8_VALUE])
@RestController
class BookRest(
val repository: BookRepository
) {
@ApiOperation("Get all the books")
@GetMapping
fun getAll(
@RequestParam("keysetId", required = false)
keysetId: Long?,
@RequestParam("keysetYear", required = false)
keysetYear: Int?
): ResponseEntity<WrappedResponse<PageDto<BookDto>>> {
val page = PageDto<BookDto>()
val n = 5
val books = DtoConverter.transform(repository.getNextPage(n, keysetId, keysetYear))
page.list = books
if(books.size == n){
val last = books.last()
page.next = "/api/books?keysetId=${last.id}&keysetYear=${last.year}"
}
return RestResponseFactory.payload(200, page)
}
@ApiOperation("Create a new book")
@PostMapping(consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE])
fun create(
@ApiParam("Data for new book")
@RequestBody
dto: BookDto
): ResponseEntity<WrappedResponse<Void>> {
if (dto.id != null) {
return RestResponseFactory.userFailure("Cannot specify an id when creating a new book")
}
val entity = Book(dto.title!!, dto.author!!, dto.year!!)
repository.save(entity)
return RestResponseFactory.created(URI.create("/api/books/" + entity.id))
}
@ApiOperation("Get a specific book, by id")
@GetMapping(path = ["/{id}"])
fun getById(
@ApiParam("The id of the book")
@PathVariable("id")
pathId: String
): ResponseEntity<WrappedResponse<BookDto>> {
val id: Long
try {
id = pathId.toLong()
} catch (e: Exception) {
return RestResponseFactory.userFailure("Invalid id")
}
val book = repository.findById(id).orElse(null)
?: return RestResponseFactory.notFound("Book with id $id does not exist")
return RestResponseFactory.payload(200, DtoConverter.transform(book))
}
@ApiOperation("Delete a specific book, by id")
@DeleteMapping(path = ["/{id}"])
fun deleteById(
@ApiParam("The id of the book")
@PathVariable("id")
pathId: String
): ResponseEntity<WrappedResponse<Void>> {
val id: Long
try {
id = pathId.toLong()
} catch (e: Exception) {
return RestResponseFactory.userFailure("Invalid id")
}
if (!repository.existsById(id)) {
return RestResponseFactory.notFound("Book with id $id does not exist")
}
repository.deleteById(id)
return RestResponseFactory.noPayload(204)
}
@ApiOperation("Update a specific book")
@PutMapping(path = ["/{id}"], consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE])
fun updateById(
@ApiParam("The id of the book")
@PathVariable("id")
pathId: String,
//
@ApiParam("New data for updating the book")
@RequestBody
dto: BookDto
): ResponseEntity<WrappedResponse<Void>> {
val id: Long
try {
id = pathId.toLong()
} catch (e: Exception) {
return RestResponseFactory.userFailure("Invalid id")
}
if(dto.id == null){
return RestResponseFactory.userFailure("Missing id")
}
if(dto.id != pathId){
return RestResponseFactory.userFailure("Inconsistency between id ${dto.id} and $pathId", 409)
}
val entity = repository.findById(id).orElse(null)
?: return return RestResponseFactory.notFound("Book with id $id does not exist")
entity.author = dto.author!!
entity.title = dto.title!!
entity.year = dto.year!!
repository.save(entity)
return RestResponseFactory.noPayload(204)
}
} | lgpl-3.0 | 4fdccc9900413a748f2e1ab08d18a917 | 29.480519 | 105 | 0.621138 | 4.305505 | false | false | false | false |
androidx/androidx | wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/SliderDemo.kt | 3 | 8723 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.demos
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.AutoCenteringParams
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.InlineSlider
import androidx.wear.compose.material.InlineSliderColors
import androidx.wear.compose.material.InlineSliderDefaults
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
@Composable
fun InlineSliderDemo() {
var valueWithoutSegments by remember { mutableStateOf(5f) }
var valueWithSegments by remember { mutableStateOf(2f) }
var enabled by remember { mutableStateOf(true) }
ScalingLazyColumnWithRSB(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(
space = 4.dp,
alignment = Alignment.CenterVertically
),
modifier = Modifier.fillMaxSize(),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
item { Text("No segments, value = $valueWithoutSegments") }
item {
DefaultInlineSlider(
value = valueWithoutSegments,
enabled = enabled,
valueRange = 1f..100f,
steps = 98,
onValueChange = { valueWithoutSegments = it })
}
item { Text("With segments, value = $valueWithSegments") }
item {
DefaultInlineSlider(
value = valueWithSegments,
enabled = enabled,
onValueChange = { valueWithSegments = it },
valueRange = 1f..10f,
steps = 8,
segmented = true
)
}
item {
ToggleChip(
checked = enabled,
onCheckedChange = { enabled = it },
label = { Text("Sliders enabled") },
// For Switch toggle controls the Wear Material UX guidance is to set the
// unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
// rather than the default.
colors = ToggleChipDefaults.toggleChipColors(
uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked = enabled),
contentDescription = if (enabled) "On" else "Off"
)
}
)
}
}
}
@Composable
fun InlineSliderWithIntegersDemo() {
var valueWithoutSegments by remember { mutableStateOf(5) }
var valueWithSegments by remember { mutableStateOf(2) }
ScalingLazyColumnWithRSB(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(
space = 4.dp,
alignment = Alignment.CenterVertically
),
modifier = Modifier.fillMaxSize(),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
item { Text("No segments, value = $valueWithoutSegments") }
item {
DefaultInlineSlider(
value = valueWithoutSegments,
valueProgression = IntProgression.fromClosedRange(0, 15, 3),
segmented = false,
onValueChange = { valueWithoutSegments = it })
}
item { Text("With segments, value = $valueWithSegments") }
item {
DefaultInlineSlider(
value = valueWithSegments,
onValueChange = { valueWithSegments = it },
valueProgression = IntProgression.fromClosedRange(110, 220, 5),
segmented = true
)
}
}
}
@Composable
fun InlineSliderRTLDemo() {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
InlineSliderDemo()
}
}
@Composable
fun InlineSliderCustomColorsDemo() {
var value by remember { mutableStateOf(4.5f) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
DefaultInlineSlider(
value = value,
onValueChange = { value = it },
valueRange = 3f..6f,
steps = 5,
segmented = false,
colors = InlineSliderDefaults.colors(
selectedBarColor = AlternatePrimaryColor1,
),
modifier = Modifier.padding(horizontal = 10.dp)
)
}
}
@Composable
fun InlineSliderSegmented() {
var numberOfSegments by remember { mutableStateOf(5f) }
var progress by remember { mutableStateOf(10f) }
ScalingLazyColumnWithRSB(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(
space = 4.dp,
alignment = Alignment.CenterVertically
),
modifier = Modifier.fillMaxSize(),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
item { Text("Num of segments ${numberOfSegments.toInt()}") }
item {
DefaultInlineSlider(
value = numberOfSegments,
valueRange = 0f..30f,
onValueChange = { numberOfSegments = it },
steps = 29
)
}
item { Text("Progress: $progress/20") }
item {
DefaultInlineSlider(
value = progress,
onValueChange = { progress = it },
valueRange = 1f..20f,
segmented = numberOfSegments <= 8,
steps = numberOfSegments.toInt()
)
}
}
}
@Composable
fun DefaultInlineSlider(
value: Float,
onValueChange: (Float) -> Unit,
steps: Int,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueRange: ClosedFloatingPointRange<Float> = 0f..(steps + 1).toFloat(),
segmented: Boolean = steps <= 8,
decreaseIcon: @Composable () -> Unit = { Icon(InlineSliderDefaults.Decrease, "Decrease") },
increaseIcon: @Composable () -> Unit = { Icon(InlineSliderDefaults.Increase, "Increase") },
colors: InlineSliderColors = InlineSliderDefaults.colors(),
) {
InlineSlider(
value = value,
onValueChange = onValueChange,
increaseIcon = increaseIcon,
decreaseIcon = decreaseIcon,
valueRange = valueRange,
segmented = segmented,
modifier = modifier,
enabled = enabled,
colors = colors,
steps = steps
)
}
@Composable
fun DefaultInlineSlider(
value: Int,
onValueChange: (Int) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueProgression: IntProgression,
segmented: Boolean,
decreaseIcon: @Composable () -> Unit = { Icon(InlineSliderDefaults.Decrease, "Decrease") },
increaseIcon: @Composable () -> Unit = { Icon(InlineSliderDefaults.Increase, "Increase") },
colors: InlineSliderColors = InlineSliderDefaults.colors(),
) {
InlineSlider(
value = value,
onValueChange = onValueChange,
increaseIcon = increaseIcon,
decreaseIcon = decreaseIcon,
valueProgression = valueProgression,
segmented = segmented,
modifier = modifier,
enabled = enabled,
colors = colors,
)
} | apache-2.0 | 25f192caf5750a33750fe7c01dc5039c | 33.756972 | 99 | 0.630173 | 4.998854 | false | false | false | false |
stoyicker/dinger | app/src/main/kotlin/app/settings/SettingsActivity.kt | 1 | 1977 | package app.settings
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.startIntent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.include_toolbar.toolbar
import org.stoyicker.dinger.R
internal class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
setupToolbar()
setupFragment(savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu) = super.onCreateOptionsMenu(menu).also {
menuInflater.inflate(R.menu.activity_settings, menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_linkedin -> true.also {
startIntent(Intent(
Intent.ACTION_VIEW, Uri.parse(getString(R.string.linkedin_profile_url))))
}
else -> super.onOptionsItemSelected(item)
}
private fun setupToolbar() {
toolbar.setTitle(R.string.label_settings)
setSupportActionBar(toolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_arrow_left)
}
}
@SuppressLint("CommitTransaction")
private fun setupFragment(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
val fragment = supportFragmentManager
.findFragmentByTag(SettingsPreferenceFragmentCompat.FRAGMENT_TAG)
?: SettingsPreferenceFragmentCompat()
supportFragmentManager.beginTransaction().apply {
replace(R.id.fragment_container,
fragment, SettingsPreferenceFragmentCompat.FRAGMENT_TAG)
commitNowAllowingStateLoss()
}
}
}
companion object {
fun getCallingIntent(context: Context) = Intent(context, SettingsActivity::class.java)
}
}
| mit | 604ae950acf535a49a119e6b14c43a45 | 30.887097 | 90 | 0.749115 | 4.707143 | false | false | false | false |
androidx/androidx | compose/material/material/samples/src/main/java/androidx/compose/material/samples/NavigationRailSample.kt | 3 | 3923 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Spacer
import androidx.compose.material.Icon
import androidx.compose.material.NavigationRail
import androidx.compose.material.NavigationRailItem
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
@Sampled
@Composable
fun NavigationRailSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Home", "Search", "Settings")
val icons = listOf(Icons.Filled.Home, Icons.Filled.Search, Icons.Filled.Settings)
NavigationRail {
items.forEachIndexed { index, item ->
NavigationRailItem(
icon = { Icon(icons[index], contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}
}
@Composable
fun NavigationRailWithOnlySelectedLabelsSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Home", "Search", "Settings")
val icons = listOf(Icons.Filled.Home, Icons.Filled.Search, Icons.Filled.Settings)
NavigationRail {
items.forEachIndexed { index, item ->
NavigationRailItem(
icon = { Icon(icons[index], contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index },
alwaysShowLabel = false
)
}
}
}
@Composable
fun CompactNavigationRailSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Home", "Search", "Settings")
val icons = listOf(Icons.Filled.Home, Icons.Filled.Search, Icons.Filled.Settings)
NavigationRail {
items.forEachIndexed { index, item ->
NavigationRailItem(
icon = { Icon(icons[index], contentDescription = item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}
}
@Composable
fun NavigationRailBottomAlignSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Home", "Search", "Settings")
val icons = listOf(Icons.Filled.Home, Icons.Filled.Search, Icons.Filled.Settings)
NavigationRail {
// A Spacer that pushes the NavigationRail items to the bottom of the NavigationRail.
Spacer(Modifier.weight(1f))
items.forEachIndexed { index, item ->
NavigationRailItem(
icon = { Icon(icons[index], contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index },
alwaysShowLabel = false
)
}
}
}
| apache-2.0 | d9b4649c71372af48b5efb4c82f8d226 | 35.663551 | 93 | 0.665817 | 4.593677 | false | false | false | false |
androidx/androidx | compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/Animatable.kt | 3 | 21260 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.animation.core.AnimationEndReason.BoundReached
import androidx.compose.animation.core.AnimationEndReason.Finished
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.CancellationException
/**
* [Animatable] is a value holder that automatically animates its value when the value is
* changed via [animateTo]. If [animateTo] is invoked during an ongoing value change animation,
* a new animation will transition [Animatable] from its current value (i.e. value at the point of
* interruption) to the new [targetValue]. This ensures that the value change is __always__
* continuous using [animateTo]. If a [spring] animation (e.g. default animation) is used with
* [animateTo], the velocity change will guarantee to be continuous as well.
*
* Unlike [AnimationState], [Animatable] ensures *mutual exclusiveness* on its animations. To
* achieve this, when a new animation is started via [animateTo] (or [animateDecay]), any ongoing
* animation will be canceled via a [CancellationException].
*
* @sample androidx.compose.animation.core.samples.AnimatableAnimateToGenericsType
*
* @param initialValue initial value of the animatable value holder
* @param typeConverter A two-way converter that converts the given type [T] from and to
* [AnimationVector]
* @param visibilityThreshold Threshold at which the animation may round off to its target value.
*
* @see animateTo
* @see animateDecay
*/
@Suppress("NotCloseable")
class Animatable<T, V : AnimationVector>(
initialValue: T,
val typeConverter: TwoWayConverter<T, V>,
private val visibilityThreshold: T? = null,
val label: String = "Animatable"
) {
@Deprecated(
"Maintained for binary compatibility",
replaceWith = ReplaceWith(
"Animatable(initialValue, typeConverter, visibilityThreshold, \"Animatable\")"
),
DeprecationLevel.HIDDEN
)
constructor(
initialValue: T,
typeConverter: TwoWayConverter<T, V>,
visibilityThreshold: T? = null
) : this(initialValue, typeConverter, visibilityThreshold, "Animatable")
internal val internalState = AnimationState(
typeConverter = typeConverter,
initialValue = initialValue
)
/**
* Current value of the animation.
*/
val value: T
get() = internalState.value
/**
* Velocity vector of the animation (in the form of [AnimationVector].
*/
val velocityVector: V
get() = internalState.velocityVector
/**
* Returns the velocity, converted from [velocityVector].
*/
val velocity: T
get() = typeConverter.convertFromVector(velocityVector)
/**
* Indicates whether the animation is running.
*/
var isRunning: Boolean by mutableStateOf(false)
private set
/**
* The target of the current animation. If the animation finishes un-interrupted, it will
* reach this target value.
*/
var targetValue: T by mutableStateOf(initialValue)
private set
/**
* Lower bound of the animation, null by default (meaning no lower bound). Bounds can be
* changed using [updateBounds].
*
* Animation will stop as soon as *any* dimension specified in [lowerBound] is reached. For
* example: For an Animatable<Offset> with an [lowerBound] set to Offset(100f, 200f), when
* the [value].x drops below 100f *or* [value].y drops below 200f, the animation will stop.
*/
var lowerBound: T? = null
private set
/**
* Upper bound of the animation, null by default (meaning no upper bound). Bounds can be
* changed using [updateBounds].
*
* Animation will stop as soon as *any* dimension specified in [upperBound] is reached. For
* example: For an Animatable<Offset> with an [upperBound] set to Offset(100f, 200f), when
* the [value].x exceeds 100f *or* [value].y exceeds 200f, the animation will stop.
*/
var upperBound: T? = null
private set
private val mutatorMutex = MutatorMutex()
internal val defaultSpringSpec: SpringSpec<T> =
SpringSpec(visibilityThreshold = visibilityThreshold)
private val negativeInfinityBounds = initialValue.createVector(Float.NEGATIVE_INFINITY)
private val positiveInfinityBounds = initialValue.createVector(Float.POSITIVE_INFINITY)
private var lowerBoundVector: V = negativeInfinityBounds
private var upperBoundVector: V = positiveInfinityBounds
private fun T.createVector(value: Float): V {
val newVector = [email protected](this)
for (i in 0 until newVector.size) {
newVector[i] = value
}
return newVector
}
/**
* Updates either [lowerBound] or [upperBound], or both. This will update
* [Animatable.lowerBound] and/or [Animatable.upperBound] accordingly after a check to ensure
* the provided [lowerBound] is no greater than [upperBound] in any dimension.
*
* Setting the bounds will immediate clamp the [value], only if the animation isn't running.
* For the on-going animation, the value at the next frame update will be checked against the
* bounds. If the value reaches the bound, then the animation will end with [BoundReached]
* end reason.
*
* @param lowerBound lower bound of the animation. Defaults to the [Animatable.lowerBound]
* that is currently set.
* @param upperBound upper bound of the animation. Defaults to the [Animatable.upperBound]
* that is currently set.
* @throws [IllegalStateException] if the [lowerBound] is greater than [upperBound] in any
* dimension.
*/
fun updateBounds(lowerBound: T? = this.lowerBound, upperBound: T? = this.upperBound) {
val lowerBoundVector = lowerBound?.run { typeConverter.convertToVector(this) }
?: negativeInfinityBounds
val upperBoundVector = upperBound?.run { typeConverter.convertToVector(this) }
?: positiveInfinityBounds
for (i in 0 until lowerBoundVector.size) {
// TODO: is this check too aggressive?
check(lowerBoundVector[i] <= upperBoundVector[i]) {
"Lower bound must be no greater than upper bound on *all* dimensions. The " +
"provided lower bound: $lowerBoundVector is greater than upper bound " +
"$upperBoundVector on index $i"
}
}
// After the correctness check:
this.lowerBoundVector = lowerBoundVector
this.upperBoundVector = upperBoundVector
this.upperBound = upperBound
this.lowerBound = lowerBound
if (!isRunning) {
val clampedValue = clampToBounds(value)
if (clampedValue != value) {
this.internalState.value = clampedValue
}
}
}
/**
* Starts an animation to animate from [value] to the provided [targetValue]. If there is
* already an animation in-flight, this method will cancel the ongoing animation before
* starting a new animation continuing the current [value] and [velocity]. It's recommended to
* set the optional [initialVelocity] only when [animateTo] is used immediately after a fling.
* In most of the other cases, altering velocity would result in visual discontinuity.
*
* The animation will use the provided [animationSpec] to animate the value towards the
* [targetValue]. When no [animationSpec] is specified, a [spring] will be used. [block] will
* be invoked on each animation frame.
*
* Returns an [AnimationResult] object. It contains: 1) the reason for ending the animation,
* and 2) an end state of the animation. The reason for ending the animation can be either of
* the following two:
* - [Finished], when the animation finishes successfully without any interruption,
* - [BoundReached] If the animation reaches the either [lowerBound] or [upperBound] in any
* dimension, the animation will end with [BoundReached] being the end reason.
*
* If the animation gets interrupted by 1) another call to start an animation
* (i.e. [animateTo]/[animateDecay]), 2) [Animatable.stop], or 3)[Animatable.snapTo], the
* canceled animation will throw a [CancellationException] as the job gets canceled. As a
* result, all the subsequent work in the caller's coroutine will be canceled. This is often
* the desired behavior. If there's any cleanup that needs to be done when an animation gets
* canceled, consider starting the animation in a `try-catch` block.
*
* __Note__: once the animation ends, its velocity will be reset to 0. The animation state at
* the point of interruption/reaching bound is captured in the returned [AnimationResult].
* If there's a need to continue the momentum that the animation had before it was interrupted
* or reached the bound, it's recommended to use the velocity in the returned
* [AnimationResult.endState] to start another animation.
*
* @sample androidx.compose.animation.core.samples.AnimatableFadeIn
*/
suspend fun animateTo(
targetValue: T,
animationSpec: AnimationSpec<T> = defaultSpringSpec,
initialVelocity: T = velocity,
block: (Animatable<T, V>.() -> Unit)? = null
): AnimationResult<T, V> {
val anim = TargetBasedAnimation(
animationSpec = animationSpec,
initialValue = value,
targetValue = targetValue,
typeConverter = typeConverter,
initialVelocity = initialVelocity
)
return runAnimation(anim, initialVelocity, block)
}
/**
* Start a decay animation (i.e. an animation that *slows down* from the given
* [initialVelocity] starting at current [Animatable.value] until the velocity reaches 0.
* If there's already an ongoing animation, the animation in-flight will be immediately
* cancelled. Decay animation is often used after a fling gesture.
*
* [animationSpec] defines the decay animation that will be used for this animation. Some
* options for this [animationSpec] include: [splineBasedDecay][androidx.compose
* .animation.splineBasedDecay] and [exponentialDecay]. [block] will be
* invoked on each animation frame.
*
* Returns an [AnimationResult] object, that contains the [reason][AnimationEndReason] for
* ending the animation, and an end state of the animation. The reason for ending the animation
* will be [Finished] if the animation finishes successfully without any interruption.
* If the animation reaches the either [lowerBound] or [upperBound] in any dimension, the
* animation will end with [BoundReached] being the end reason.
*
* If the animation gets interrupted by 1) another call to start an animation
* (i.e. [animateTo]/[animateDecay]), 2) [Animatable.stop], or 3)[Animatable.snapTo], the
* canceled animation will throw a [CancellationException] as the job gets canceled. As a
* result, all the subsequent work in the caller's coroutine will be canceled. This is often
* the desired behavior. If there's any cleanup that needs to be done when an animation gets
* canceled, consider starting the animation in a `try-catch` block.
*
* __Note__, once the animation ends, its velocity will be reset to 0. If there's a need to
* continue the momentum before the animation gets interrupted or reaches the bound, it's
* recommended to use the velocity in the returned [AnimationResult.endState] to start
* another animation.
*
* @sample androidx.compose.animation.core.samples.AnimatableDecayAndAnimateToSample
*/
suspend fun animateDecay(
initialVelocity: T,
animationSpec: DecayAnimationSpec<T>,
block: (Animatable<T, V>.() -> Unit)? = null
): AnimationResult<T, V> {
val anim = DecayAnimation(
animationSpec = animationSpec,
initialValue = value,
initialVelocityVector = typeConverter.convertToVector(initialVelocity),
typeConverter = typeConverter
)
return runAnimation(anim, initialVelocity, block)
}
// All the different types of animation code paths eventually converge to this method.
private suspend fun runAnimation(
animation: Animation<T, V>,
initialVelocity: T,
block: (Animatable<T, V>.() -> Unit)?
): AnimationResult<T, V> {
// Store the start time before it's reset during job cancellation.
val startTime = internalState.lastFrameTimeNanos
return mutatorMutex.mutate {
try {
internalState.velocityVector = typeConverter.convertToVector(initialVelocity)
targetValue = animation.targetValue
isRunning = true
val endState = internalState.copy(
finishedTimeNanos = AnimationConstants.UnspecifiedTime
)
var clampingNeeded = false
endState.animate(
animation,
startTime
) {
updateState(internalState)
val clamped = clampToBounds(value)
if (clamped != value) {
internalState.value = clamped
endState.value = clamped
block?.invoke(this@Animatable)
cancelAnimation()
clampingNeeded = true
} else {
block?.invoke(this@Animatable)
}
}
val endReason = if (clampingNeeded) BoundReached else Finished
endAnimation()
AnimationResult(endState, endReason)
} catch (e: CancellationException) {
// Clean up internal states first, then throw.
endAnimation()
throw e
}
}
}
private fun clampToBounds(value: T): T {
if (
lowerBoundVector == negativeInfinityBounds &&
upperBoundVector == positiveInfinityBounds
) {
// Expect this to be the most common use case
return value
}
val valueVector = typeConverter.convertToVector(value)
var clamped = false
for (i in 0 until valueVector.size) {
if (valueVector[i] < lowerBoundVector[i] || valueVector[i] > upperBoundVector[i]) {
clamped = true
valueVector[i] =
valueVector[i].coerceIn(lowerBoundVector[i], upperBoundVector[i])
}
}
if (clamped) {
return typeConverter.convertFromVector(valueVector)
} else {
return value
}
}
private fun endAnimation() {
// Reset velocity
internalState.apply {
velocityVector.reset()
lastFrameTimeNanos = AnimationConstants.UnspecifiedTime
}
isRunning = false
}
/**
* Sets the current value to the target value, without any animation. This will also cancel any
* on-going animation with a [CancellationException]. This function will return *after*
* canceling any on-going animation and updating the [Animatable.value] and
* [Animatable.targetValue] to the provided [targetValue].
*
* __Note__: If the [lowerBound] or [upperBound] is specified, the provided [targetValue]
* will be clamped to the bounds to ensure [Animatable.value] is always within bounds.
*
* See [animateTo] and [animateDecay] for more details about animation being canceled.
*
* @param targetValue The new target value to set [value] to.
*
* @see animateTo
* @see animateDecay
* @see stop
*/
suspend fun snapTo(targetValue: T) {
mutatorMutex.mutate {
endAnimation()
val clampedValue = clampToBounds(targetValue)
internalState.value = clampedValue
this.targetValue = clampedValue
}
}
/**
* Stops any on-going animation with a [CancellationException].
*
* This function will not return until the ongoing animation has been canceled (if any).
* Note, [stop] function does **not** skip the animation value to its target value. Rather the
* animation will be stopped in its track. Consider [snapTo] if it's desired to not only stop
* the animation but also snap the [value] to a given value.
*
* See [animateTo] and [animateDecay] for more details about animation being canceled.
*
* @see animateTo
* @see animateDecay
* @see snapTo
*/
suspend fun stop() {
mutatorMutex.mutate {
endAnimation()
}
}
/**
* Returns a [State] representing the current [value] of this animation. This allows
* hoisting the animation's current value without causing unnecessary recompositions
* when the value changes.
*/
fun asState(): State<T> = internalState
}
/**
* This [Animatable] function creates a float value holder that automatically
* animates its value when the value is changed via [animateTo]. [Animatable] supports value
* change during an ongoing value change animation. When that happens, a new animation will
* transition [Animatable] from its current value (i.e. value at the point of interruption) to the
* new target. This ensures that the value change is *always* continuous using [animateTo]. If
* [spring] animation (i.e. default animation) is used with [animateTo], the velocity change will
* be guaranteed to be continuous as well.
*
* Unlike [AnimationState], [Animatable] ensures mutual exclusiveness on its animation. To
* do so, when a new animation is started via [animateTo] (or [animateDecay]), any ongoing
* animation job will be cancelled.
*
* @sample androidx.compose.animation.core.samples.AnimatableFadeIn
*
* @param initialValue initial value of the animatable value holder
* @param visibilityThreshold Threshold at which the animation may round off to its target value.
* [Spring.DefaultDisplacementThreshold] by default.
*/
fun Animatable(
initialValue: Float,
visibilityThreshold: Float = Spring.DefaultDisplacementThreshold
) = Animatable(
initialValue,
Float.VectorConverter,
visibilityThreshold
)
// TODO: Consider some version of @Composable fun<T, V: AnimationVector> Animatable<T, V>.animateTo
/**
* AnimationResult contains information about an animation at the end of the animation. [endState]
* captures the value/velocity/frame time, etc of the animation at its last frame. It can be
* useful for starting another animation to continue the velocity from the previously interrupted
* animation. [endReason] describes why the animation ended, it could be either of the following:
* - [Finished], when the animation finishes successfully without any interruption
* - [BoundReached] If the animation reaches the either [lowerBound][Animatable.lowerBound] or
* [upperBound][Animatable.upperBound] in any dimension, the animation will end with
* [BoundReached] being the end reason.
*
* @sample androidx.compose.animation.core.samples.AnimatableAnimationResultSample
*/
class AnimationResult<T, V : AnimationVector>(
/**
* The state of the animation in its last frame before it's canceled or reset. This captures
* the animation value/velocity/frame time, etc at the point of interruption, or before the
* velocity is reset when the animation finishes successfully.
*/
val endState: AnimationState<T, V>,
/**
* The reason why the animation has ended. Could be either of the following:
* - [Finished], when the animation finishes successfully without any interruption
* - [BoundReached] If the animation reaches the either [lowerBound][Animatable.lowerBound] or
* [upperBound][Animatable.upperBound] in any dimension, the animation will end with
* [BoundReached] being the end reason.
*/
val endReason: AnimationEndReason
) {
override fun toString(): String = "AnimationResult(endReason=$endReason, endState=$endState)"
} | apache-2.0 | adfe22dac28cfc658373bd64a91c8358 | 43.572327 | 99 | 0.670085 | 4.823049 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/amd_bus_addressable_memory.kt | 1 | 6208 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
val amd_bus_addressable_memory = "AMDBusAddressableMemory".nativeClassCL("amd_bus_addressable_memory", AMD) {
documentation =
"""
Native bindings to the $extensionLink extension.
This extension defines an API that allows improved control of the physical memory used by the graphics device.
It allows to share a memory allocated by the Graphics driver to be used by other device on the bus by exposing a write-only bus address. One example of
application would be a video capture device which would DMA into the GPU memory.
It also offers the reverse operation of specifying a buffer allocated on another device to be used for write access by the GPU.
"""
IntConstant(
"""
Accepted by the {@code flags} parameter of CL10#CreateBuffer().
This flag specifies that the application wants the OpenCL implementation to create a buffer that can be accessed by remote device DMA.
#MEM_BUS_ADDRESSABLE_AMD, CL10#MEM_ALLOC_HOST_PTR and CL10#MEM_USE_HOST_PTR are mutually exclusive.
""",
"MEM_BUS_ADDRESSABLE_AMD".."1<<30"
)
IntConstant(
"""
Accepted by the {@code flags} parameter of CL10#CreateBuffer().
This flag specifies that the application wants the OpenCL implementation to create a buffer from an already allocated memory on remote device.
#MEM_EXTERNAL_PHYSICAL_AMD, CL10#MEM_ALLOC_HOST_PTR, CL10#MEM_COPY_HOST_PTR and CL10#MEM_USE_HOST_PTR are mutually exclusive.
#MEM_EXTERNAL_PHYSICAL_AMD, CL10#MEM_READ_WRITE and CL10#MEM_READ_ONLY are mutually exclusive.
""",
"MEM_EXTERNAL_PHYSICAL_AMD".."1<<31"
)
IntConstant(
"New command types for the events returned by the $extensionName functions.",
"COMMAND_WAIT_SIGNAL_AMD"..0x4080,
"COMMAND_WRITE_SIGNAL_AMD"..0x4081,
"COMMAND_MAKE_BUFFERS_RESIDENT_AMD"..0x4082
)
cl_int(
"EnqueueWaitSignalAMD",
"Instructs the OpenCL to wait until {@code value} is written to {@code buffer} before issuing the next command.",
cl_command_queue.IN("command_queue", "a command-queue"),
cl_mem.IN("mem_object", "a memory object"),
cl_uint.IN("value", "the signal value"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_MEM_OBJECT is generated if the {@code buffer} parameter of clEnqueueWaitSignalAMD is not a valid buffer.",
"$INVALID_COMMAND_QUEUE is generated if the {@code command_queue} parameter of clEnqueueWaitSignalAMD is not a valid command queue.",
"""
$INVALID_MEM_OBJECT is generated if the {@code buffer} parameter of clEnqueueWaitSignalAMD does not represent a buffer allocated with
#MEM_BUS_ADDRESSABLE_AMD.
""",
"$INVALID_VALUE is generated if the signal address used by clEnqueueWaitSignalAMD of {@code bufffer} is invalid (for example 0)."
)}
"""
)
cl_int(
"EnqueueWriteSignalAMD",
"""
This command instructs the OpenCL to write {@code value} to the signal address + {@code offset} of {@code buffer} (which must be a buffer created with
#MEM_EXTERNAL_PHYSICAL_AMD). This should be done after a write operation by the device into that buffer is complete. Consecutive marker values must
keep increasing.
""",
cl_command_queue.IN("command_queue", "a command-queue"),
cl_mem.IN("mem_object", "a memory object"),
cl_uint.IN("value", "the signal value"),
cl_ulong.IN("offset", "the write offset"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_MEM_OBJECT is generated if the {@code buffer} parameter of clEnqueueWriteSignalAMD is not a valid buffer.",
"$INVALID_COMMAND_QUEUE is generated if the {@code command_queue} parameter of clEnqueueWriteSignalAMD is not a valid command queue.",
"""
$INVALID_MEM_OBJECT is generated if the {@code buffer} parameter of clEnqueueWriteSignalAMD does not represent a buffer defined as
#MEM_EXTERNAL_PHYSICAL_AMD.
""",
"""
$INVALID_BUFFER_SIZE is generated if the {@code offset} parameter of clEnqueueWriteSignalAMD would lead to a write beyond the size of
{@code buffer}.
""",
"$INVALID_VALUE is generated if the signal address used by clEnqueueWriteSignalAMD of {@code bufffer} is invalid (for example 0)."
)}
"""
)
cl_int(
"EnqueueMakeBuffersResidentAMD",
"""
The application requires the bus address in order to access the buffers from a remote device. As the OS may rearrange buffers to make space for other
memory allocation, we must make the buffers resident before trying to access them on remote device.
This function is used to make buffers resident.
""",
cl_command_queue.IN("command_queue", "a command-queue"),
AutoSize("mem_objects", "bus_addresses")..cl_uint.IN("num_mem_objs", "the number of memory objects in {@code mem_objects}"),
const..cl_mem_p.IN("mem_objects", "a pointer to a list of memory objects created with #MEM_BUS_ADDRESSABLE_AMD flag"),
cl_bool.IN("blocking_make_resident", "indicates if read operation is <em>blocking</em> or <em>non-blocking</em>"),
cl_bus_address_amd_p.OUT("bus_addresses", "a pointer to a list of ##CLBusAddressAMD structures"),
NEWL,
EWL,
EVENT,
returnDoc =
"""
$SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:
${ul(
"$INVALID_OPERATION is generated if any of the pointer parameters of clEnqueueMakeBuffersResidentAMD are $NULL (and count is > 0).",
"""
$INVALID_OPERATION is generated if any of the mem_objects passed to clEnqueueMakeBuffersResidentAMD was not a valid cl_mem object created with
#MEM_BUS_ADDRESSABLE_AMD flag.
""",
"""
CL10#OUT_OF_HOST_MEMORY is generated if any of the mem_objects passed to clEnqueueMakeBuffersResidentAMD could not be made resident so that the buffer
or signal bus addresses will be returned as 0.
"""
)}
"""
)
} | bsd-3-clause | 0acf3adc2ba0dd848adc6a71f452c1b9 | 39.848684 | 159 | 0.717461 | 3.739759 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCItemsDropped.kt | 1 | 1981 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QItemDrops
import com.demonwav.statcraft.querydsl.QPlayers
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCItemsDropped(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("itemsdropped", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.itemsdropped")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Items Dropped" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val i = QItemDrops.itemDrops
val result = query.from(i).where(i.id.eq(id)).uniqueResult(i.amount.sum()) ?: 0
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Items Dropped" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val i = QItemDrops.itemDrops
val p = QPlayers.players
val list = query
.from(i)
.innerJoin(p)
.on(i.id.eq(p.id))
.groupBy(p.name)
.orderBy(i.amount.sum().desc())
.limit(num)
.list(p.name, i.amount.sum())
return topListResponse("Items Dropped", list)
}
}
| mit | a35cd4a3f01df2bd3ba778f89a2dbc6f | 30.444444 | 133 | 0.647653 | 4.161765 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/codeInsight/intention/ComputeConstantValueIntention.kt | 2 | 2468 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.codeInsight.intention
import com.intellij.codeInsight.intention.impl.BaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.tang.intellij.lua.psi.*
class ComputeConstantValueIntention : BaseIntentionAction() {
override fun getFamilyName() = "Compute constant value"
override fun isAvailable(project: Project, editor: Editor, psiFile: PsiFile): Boolean {
val expr = LuaPsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.caretModel.offset, LuaExpr::class.java, false)
if (expr is LuaBinaryExpr) {
val result = ExpressionUtil.compute(expr)
text = "Compute constant value of ${expr.text}"
return result != null
}
return false
}
override fun invoke(project: Project, editor: Editor, psiFile: PsiFile) {
val expr = LuaPsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.caretModel.offset, LuaExpr::class.java, false)
if (expr is LuaBinaryExpr) {
val result = ExpressionUtil.compute(expr)
if (result != null) {
when (result.kind) {
ComputeKind.Number,
ComputeKind.Bool,
ComputeKind.Nil -> {
val new = LuaElementFactory.createLiteral(project, result.string)
expr.replace(new)
}
ComputeKind.String -> {
val new = LuaElementFactory.createLiteral(project, "[[${result.string}]]")
expr.replace(new)
}
ComputeKind.Other -> {
result.expr?.let { expr.replace(it) }
}
}
}
}
}
} | apache-2.0 | ba48c3cf42adb570bba2bb35ccc81038 | 39.47541 | 123 | 0.624392 | 4.692015 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-compose/src/main/kotlin/org/ccci/gto/android/common/androidx/compose/ui/text/AnnotatedString+Linkify.kt | 1 | 2176 | package org.ccci.gto.android.common.androidx.compose.ui.text
import android.text.SpannableString
import android.text.style.URLSpan
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.core.text.util.LinkifyCompat
import androidx.core.text.util.LinkifyCompat.LinkifyMask
private const val TAG_URI = "uri"
fun String.addUriAnnotations(@LinkifyMask mask: Int, linkStyle: SpanStyle?) = AnnotatedString.Builder(this).apply {
val (spannable, spans) = getUrlSpans(this@addUriAnnotations, mask)
addUrlSpans(spannable, spans, linkStyle)
}.toAnnotatedString()
fun AnnotatedString.addUriAnnotations(
@LinkifyMask mask: Int,
linkStyle: SpanStyle?
): AnnotatedString {
val (spannable, spans) = getUrlSpans(this, mask)
return when {
spans.isEmpty() -> this
else -> buildAnnotatedString {
append(this@addUriAnnotations)
addUrlSpans(spannable, spans, linkStyle)
}
}
}
fun AnnotatedString.Builder.addUriAnnotations(@LinkifyMask mask: Int, linkStyle: SpanStyle?) {
val (spannable, spans) = getUrlSpans(toAnnotatedString().text, mask)
addUrlSpans(spannable, spans, linkStyle)
}
private fun getUrlSpans(string: CharSequence, @LinkifyMask mask: Int): Pair<SpannableString, Array<URLSpan>> {
val spannable = SpannableString(string).apply { LinkifyCompat.addLinks(this, mask) }
return spannable to spannable.getSpans(0, spannable.length, URLSpan::class.java)
}
private fun AnnotatedString.Builder.addUrlSpans(
spannable: SpannableString,
spans: Array<URLSpan>,
linkStyle: SpanStyle?
) {
spans.forEach {
val spanStart = spannable.getSpanStart(it)
val spanEnd = spannable.getSpanEnd(it)
addUriAnnotation(it.url, spanStart, spanEnd)
if (linkStyle != null) addStyle(linkStyle, spanStart, spanEnd)
}
}
private fun AnnotatedString.Builder.addUriAnnotation(uri: String, start: Int, end: Int) =
addStringAnnotation(TAG_URI, uri, start, end)
fun AnnotatedString.getUriAnnotations(start: Int, end: Int) = getStringAnnotations(TAG_URI, start, end)
| mit | 155663b894611d9253e1acc34860e09b | 37.175439 | 115 | 0.744945 | 4.052142 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/view/ContentDetailFragment.kt | 1 | 2001 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.Repository
import net.mm2d.dmsexplorer.databinding.ContentDetailFragmentBinding
import net.mm2d.dmsexplorer.viewmodel.ContentDetailFragmentModel
/**
* CDSアイテムの詳細情報を表示するFragment。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ContentDetailFragment : Fragment() {
private var model: ContentDetailFragmentModel? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = DataBindingUtil.inflate<ContentDetailFragmentBinding>(
inflater,
R.layout.content_detail_fragment,
container,
false
)
val activity = requireActivity()
try {
model = ContentDetailFragmentModel(activity, Repository.get())
binding.model = model
} catch (ignored: IllegalStateException) {
activity.finish()
return binding.root
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
model?.terminate()
}
override fun onResume() {
super.onResume()
model?.onResume()
}
companion object {
/**
* インスタンスを作成する。
*
* Bundleの設定と読み出しをこのクラス内で完結させる。
*
* @return インスタンス。
*/
fun newInstance(): ContentDetailFragment = ContentDetailFragment()
}
}
| mit | 25a6e12b2ea67be302968c5d170762e9 | 25.013889 | 76 | 0.653497 | 4.448931 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/psi/Path.kt | 1 | 4611 | package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileSystem
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.cabal.CabalFile
import org.jetbrains.cabal.psi.Checkable
import org.jetbrains.cabal.psi.PropertyValue
import org.jetbrains.cabal.psi.PathsField
import org.jetbrains.cabal.highlight.ErrorMessage
import org.jetbrains.cabal.references.FilePsiReference
import java.io.File
import java.io.FilenameFilter
import java.util.ArrayList
import com.intellij.psi.PsiReference
public open class Path(node: ASTNode) : ASTWrapperPsiElement(node), PropertyValue, Checkable {
public override fun getReference(): PsiReference? {
val originalRootDir = getCabalRootFile()
if (originalRootDir == null) return null
val refFile: VirtualFile? = getVirtualFile(originalRootDir)
if ((refFile == null) || (refFile.isDirectory())) return null
val resolveTo = getManager()?.findFile(refFile)
if (resolveTo == null) return null
return FilePsiReference(this, resolveTo)
}
public fun getParentField(): PathsField = getParent() as PathsField
public fun getDefaultTextRange(): TextRange = TextRange(0, getText().length())
public fun getFile(): File = File(getText())
public fun getFilename(): String = getFile().getName()
public fun getCabalFile(): CabalFile = (getContainingFile() as CabalFile)
public fun isAbsolute(): Boolean = getFile().isAbsolute()
public fun isWildcard(): Boolean {
val parentField = getParentField()
if (parentField.hasName("extra-source-files") || parentField.hasName("data-files")) {
return getFilename().matches("^\\*\\.(.+)$".toRegex())
}
return false
}
public override fun check(): List<ErrorMessage> {
val originalRootFile = getCabalRootFile()!!
if (isWildcard()) {
val parentDir = getVirtualParentDir(originalRootFile)
if (parentDir == null) return listOf(ErrorMessage(this, "invalid path", "warning"))
if (filterByWildcard(parentDir).size() == 0) return listOf(ErrorMessage(this, "invalid wildcard", "warning"))
return listOf()
}
else {
if (getVirtualFile(originalRootFile) == null) return listOf(ErrorMessage(this, "invalid path", "warning"))
}
return listOf()
}
public fun getFileWithParent(parent: VirtualFile): VirtualFile? {
if (isAbsolute()) return findFileByPath(parent.getFileSystem(), getText())
return findFileByRelativePath(parent, getText())
}
public fun getPathWithParent(parent: VirtualFile): String = if (isAbsolute()) getText() else File(parent.getPath(), getText()).getPath()
public fun getVirtualFile(originalRootDir: VirtualFile): VirtualFile? {
val parentField = getParentField()
if (!parentField.validRelativity(getFile())) return null
for (sourceDir in parentField.getSourceDirs(originalRootDir)) {
val file = getFileWithParent(sourceDir)
if ((file != null) && parentField.validVirtualFile(file)) return file
}
return null
}
public fun getVirtualParentDir(originalRootDir: VirtualFile): VirtualFile? {
val parentField = getParentField()
if (!parentField.validRelativity(getFile())) return null
for (sourceDir in parentField.getSourceDirs(originalRootDir)) {
val filePath = getPathWithParent(sourceDir)
val dirPath = File(filePath).getParent()
val dir = if (dirPath == null) null else findFileByPath(originalRootDir.getFileSystem(), dirPath)
if ((dir != null) && dir.isDirectory()) return dir
}
return null
}
private fun findFileByRelativePath(parentDir: VirtualFile, path: String)
= parentDir.findFileByRelativePath(path.replace(File.separatorChar, '/'))
private fun findFileByPath(virtualSystem: VirtualFileSystem, path: String)
= virtualSystem.findFileByPath(path.replace(File.separatorChar, '/'))
private fun filterByWildcard(parentDir: VirtualFile): List<VirtualFile> {
val ext = getFile().getName().replace("^\\*(\\..+)$".toRegex(), "$1")
return parentDir.getChildren()?.filter { it.getName().matches("^[^.]*\\Q${ext}\\E$".toRegex()) } ?: listOf()
}
private fun getCabalRootFile(): VirtualFile? = getCabalFile().getVirtualFile()?.getParent()
} | apache-2.0 | 2b01bc67d17f5fd092d6bff42a448f83 | 42.102804 | 140 | 0.68727 | 4.748713 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/TaskRepository.kt | 1 | 3167 | package com.habitrpg.android.habitica.data
import com.habitrpg.android.habitica.models.BaseMainObject
import com.habitrpg.android.habitica.models.responses.BulkTaskScoringData
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskList
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.shared.habitica.models.responses.TaskScoringResult
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.habitrpg.shared.habitica.models.tasks.TasksOrder
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
import kotlinx.coroutines.flow.Flow
import java.util.Date
interface TaskRepository : BaseRepository {
fun getTasks(taskType: TaskType, userID: String? = null, includedGroupIDs: Array<String>): Flow<List<Task>>
fun getTasksFlowable(taskType: TaskType, userID: String? = null, includedGroupIDs: Array<String>): Flowable<out List<Task>>
fun saveTasks(userId: String, order: TasksOrder, tasks: TaskList)
suspend fun retrieveTasks(userId: String, tasksOrder: TasksOrder): TaskList?
fun retrieveTasks(userId: String, tasksOrder: TasksOrder, dueDate: Date): Flowable<TaskList>
fun taskChecked(
user: User?,
task: Task,
up: Boolean,
force: Boolean,
notifyFunc: ((TaskScoringResult) -> Unit)?
): Flowable<TaskScoringResult>
fun taskChecked(
user: User?,
taskId: String,
up: Boolean,
force: Boolean,
notifyFunc: ((TaskScoringResult) -> Unit)?
): Maybe<TaskScoringResult>
fun scoreChecklistItem(taskId: String, itemId: String): Flowable<Task>
fun getTask(taskId: String): Flowable<Task>
fun getTaskCopy(taskId: String): Flowable<Task>
fun createTask(task: Task, force: Boolean = false): Flowable<Task>
fun updateTask(task: Task, force: Boolean = false): Maybe<Task>?
fun deleteTask(taskId: String): Flowable<Void>
fun saveTask(task: Task)
fun createTasks(newTasks: List<Task>): Flowable<List<Task>>
fun markTaskCompleted(taskId: String, isCompleted: Boolean)
fun <T : BaseMainObject> modify(obj: T, transaction: (T) -> Unit)
fun swapTaskPosition(firstPosition: Int, secondPosition: Int)
fun updateTaskPosition(taskType: TaskType, taskID: String, newPosition: Int): Maybe<List<String>>
fun getUnmanagedTask(taskid: String): Flowable<Task>
fun updateTaskInBackground(task: Task)
fun createTaskInBackground(task: Task)
fun getTaskCopies(userId: String): Flow<List<Task>>
fun getTaskCopies(tasks: List<Task>): List<Task>
fun retrieveDailiesFromDate(date: Date): Flowable<TaskList>
fun retrieveCompletedTodos(userId: String? = null): Flowable<TaskList>
fun syncErroredTasks(): Single<List<Task>>
fun unlinkAllTasks(challengeID: String?, keepOption: String): Flowable<Void>
fun getTasksForChallenge(challengeID: String?): Flowable<out List<Task>>
fun bulkScoreTasks(data: List<Map<String, String>>): Flowable<BulkTaskScoringData>
}
| gpl-3.0 | 2bd2e710dbd1a3978e8dceb6c634cef4 | 40.797297 | 127 | 0.727187 | 4.145288 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt | 3 | 7081 | package info.nightscout.androidaps.plugins.source
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.dialogs.CareDialog
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.T
import org.json.JSONObject
import org.slf4j.LoggerFactory
object SourceDexcomPlugin : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginName(R.string.dexcom_app_patched)
.shortName(R.string.dexcom_short)
.preferencesId(R.xml.pref_bgsource)
.description(R.string.description_source_dexcom)), BgSourceInterface {
private val log = LoggerFactory.getLogger(L.BGSOURCE)
private val PACKAGE_NAMES = arrayOf("com.dexcom.cgm.region1.mgdl", "com.dexcom.cgm.region1.mmol",
"com.dexcom.cgm.region2.mgdl", "com.dexcom.cgm.region2.mmol",
"com.dexcom.g6.region1.mmol", "com.dexcom.g6.region2.mgdl",
"com.dexcom.g6.region3.mgdl", "com.dexcom.g6.region3.mmol")
const val PERMISSION = "com.dexcom.cgm.EXTERNAL_PERMISSION"
override fun advancedFilteringSupported(): Boolean {
return true
}
override fun onStart() {
super.onStart()
if (ContextCompat.checkSelfPermission(MainApp.instance(), PERMISSION) != PackageManager.PERMISSION_GRANTED) {
val intent = Intent(MainApp.instance(), RequestDexcomPermissionActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
MainApp.instance().startActivity(intent)
}
}
fun findDexcomPackageName(): String? {
val packageManager = MainApp.instance().packageManager
for (packageInfo in packageManager.getInstalledPackages(0)) {
if (PACKAGE_NAMES.contains(packageInfo.packageName)) return packageInfo.packageName
}
return null
}
override fun handleNewData(intent: Intent) {
if (!isEnabled(PluginType.BGSOURCE)) return
try {
val sensorType = intent.getStringExtra("sensorType") ?: ""
val glucoseValues = intent.getBundleExtra("glucoseValues")
for (i in 0 until glucoseValues.size()) {
glucoseValues.getBundle(i.toString())?.let { glucoseValue ->
val bgReading = BgReading()
bgReading.value = glucoseValue.getInt("glucoseValue").toDouble()
bgReading.direction = glucoseValue.getString("trendArrow")
bgReading.date = glucoseValue.getLong("timestamp") * 1000
bgReading.raw = 0.0
if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) {
if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType")
}
if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading)
}
}
}
}
val meters = intent.getBundleExtra("meters")
for (i in 0 until meters.size()) {
val meter = meters.getBundle(i.toString())
meter?.let {
val timestamp = it.getLong("timestamp") * 1000
val now = DateUtil.now()
if (timestamp > now - T.months(1).msecs() && timestamp < now)
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp) == null) {
val jsonObject = JSONObject()
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("created_at", DateUtil.toISOString(timestamp))
jsonObject.put("eventType", CareportalEvent.BGCHECK)
jsonObject.put("glucoseType", "Finger")
jsonObject.put("glucose", meter.getInt("meterValue"))
jsonObject.put("units", Constants.MGDL)
val careportalEvent = CareportalEvent()
careportalEvent.date = timestamp
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.BGCHECK
careportalEvent.json = jsonObject.toString()
MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadCareportalEntryToNS(jsonObject)
}
}
}
if (SP.getBoolean(R.string.key_dexcom_lognssensorchange, false) && intent.hasExtra("sensorInsertionTime")) {
intent.extras?.let {
val sensorInsertionTime = it.getLong("sensorInsertionTime") * 1000
val now = DateUtil.now()
if (sensorInsertionTime > now - T.months(1).msecs() && sensorInsertionTime < now)
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(sensorInsertionTime) == null) {
val jsonObject = JSONObject()
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
val careportalEvent = CareportalEvent()
careportalEvent.date = sensorInsertionTime
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.SENSORCHANGE
careportalEvent.json = jsonObject.toString()
MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadCareportalEntryToNS(jsonObject)
}
}
}
} catch (e: Exception) {
log.error("Error while processing intent from Dexcom App", e)
}
}
}
| agpl-3.0 | 2a4972266d8d69851ba84611a1a40376 | 51.066176 | 120 | 0.611778 | 4.876722 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/objects/useAnonymousObjectAsIterator.kt | 5 | 369 | // KT-5869
operator fun <T> Iterator<T>.iterator(): Iterator<T> = this
fun box(): String {
val iterator = object : Iterator<Int> {
var i = 0
override fun next() = i++
override fun hasNext() = i < 5
}
var result = ""
for (i in iterator) {
result += i
}
return if (result == "01234") "OK" else "Fail $result"
}
| apache-2.0 | 6db982b9926ea74c1ce407649e5b5d17 | 19.5 | 59 | 0.525745 | 3.448598 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectRetrofit/app/src/main/java/me/liuqingwen/android/projectretrofit/dummy/DummyContent.kt | 1 | 1559 | package me.liuqingwen.android.projectretrofit.dummy
import java.util.ArrayList
import java.util.HashMap
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
*
*
* TODO: Replace all uses of this class before publishing your app.
*/
object DummyContent
{
/**
* An array of sample (dummy) items.
*/
val ITEMS: MutableList<DummyItem> = ArrayList()
/**
* A map of sample (dummy) items, by ID.
*/
val ITEM_MAP: MutableMap<String, DummyItem> = HashMap()
private val COUNT = 25
init
{
// Add some sample items.
for (i in 1..COUNT)
{
addItem(createDummyItem(i))
}
}
private fun addItem(item: DummyItem)
{
ITEMS.add(item)
ITEM_MAP[item.id] = item
}
private fun createDummyItem(position: Int): DummyItem
{
return DummyItem(position.toString(), "Item " + position, makeDetails(position))
}
private fun makeDetails(position: Int): String
{
val builder = StringBuilder()
builder.append("Details about Item: ").append(position)
for (i in 0 until position)
{
builder.append("\nMore details information here.")
}
return builder.toString()
}
/**
* A dummy item representing a piece of content.
*/
class DummyItem(val id: String, val content: String, val details: String)
{
override fun toString(): String
{
return content
}
}
}
| mit | d310fe3246e243565efa20c9bcecc2ec | 21.271429 | 88 | 0.597178 | 4.330556 | false | false | false | false |
GlenKPeterson/TestUtils | src/main/java/org/organicdesign/testUtils/string/DiffResult.kt | 1 | 734 | package org.organicdesign.testUtils.string
import org.organicdesign.indented.IndentedStringable
import org.organicdesign.indented.StringUtils.fieldsOnOneLineK
data class DiffResult(
val first: String,
val second: String
) : IndentedStringable {
override fun indentedStr(indent: Int, singleLine: Boolean): String =
if ( first == "" &&
second == "" ) {
"IDENTICAL"
} else {
fieldsOnOneLineK(indent, "DiffResult",
listOf("" to first,
"" to second))
}
override fun toString(): String = indentedStr(0)
companion object {
@JvmField
val IDENTICAL = DiffResult("", "")
}
} | apache-2.0 | dde10c1a563bd292d2cf015ba1d52dba | 26.222222 | 72 | 0.577657 | 4.797386 | false | false | false | false |
cyclestreets/android | libraries/cyclestreets-view/src/main/java/net/cyclestreets/liveride/AudioFocuser.kt | 1 | 2566 | package net.cyclestreets.liveride
import android.content.Context
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import android.media.AudioAttributes.CONTENT_TYPE_SPEECH
import android.media.AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE
import android.media.AudioManager.*
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import net.cyclestreets.util.Logging
import kotlin.collections.HashMap
private val TAG = Logging.getTag(AudioFocuser::class.java)
class AudioFocuser(context: Context) : UtteranceProgressListener(), AudioManager.OnAudioFocusChangeListener {
private val audioAttributes = android.media.AudioAttributes.Builder()
.setUsage(USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
.setContentType(CONTENT_TYPE_SPEECH)
.build()
private val am: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private val audioFocusRequests: MutableMap<String, AudioFocusRequest> = HashMap()
@Suppress("deprecation")
override fun onStart(utteranceId: String) {
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val afr = AudioFocusRequest.Builder(AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK).setAudioAttributes(audioAttributes).build()
audioFocusRequests[utteranceId] = afr
am.requestAudioFocus(afr)
} else {
am.requestAudioFocus(this, CONTENT_TYPE_SPEECH, AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
}
Log.d(TAG, "Audio focus request for utterance $utteranceId: result $result ($AUDIOFOCUS_REQUEST_GRANTED=granted, $AUDIOFOCUS_REQUEST_FAILED=failed)")
}
@Suppress("deprecation")
override fun onDone(utteranceId: String) {
val result: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioFocusRequests.remove(utteranceId)?.let {
am.abandonAudioFocusRequest(it)
} ?: -1
} else {
am.abandonAudioFocus(this)
}
Log.d(TAG, "Audio focus release for utterance $utteranceId: result $result ($AUDIOFOCUS_REQUEST_GRANTED=granted, $AUDIOFOCUS_REQUEST_FAILED=failed, -1=utterance unknown)")
}
@Deprecated("")
override fun onError(utteranceId: String) {
Log.d(TAG, "TTS error occurred processing utterance $utteranceId")
audioFocusRequests.remove(utteranceId)
}
override fun onAudioFocusChange(focusChange: Int) {
// Nothing to do - it's not the end of the world if we can't get audio focus
}
}
| gpl-3.0 | 0306b37f15784007c933ea867df00106 | 41.766667 | 179 | 0.721356 | 4.298157 | false | false | false | false |
sirixdb/sirix | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/Auth.kt | 1 | 2579 | package org.sirix.rest
import io.netty.handler.codec.http.HttpResponseStatus
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.auth.User
import io.vertx.ext.auth.authorization.AuthorizationProvider
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization
import io.vertx.ext.auth.authorization.RoleBasedAuthorization
import io.vertx.ext.auth.oauth2.OAuth2Auth
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.core.json.json
import io.vertx.kotlin.core.json.obj
import io.vertx.kotlin.coroutines.await
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
/**
* Authentication.
*/
class Auth(private val keycloak: OAuth2Auth, private val authz: AuthorizationProvider, private val role: AuthRole) {
suspend fun handle(ctx: RoutingContext): Route {
ctx.request().pause()
val token = ctx.request().getHeader(HttpHeaders.AUTHORIZATION.toString())
val tokenToAuthenticate = json {
obj(
"access_token" to token.substring(7),
"token_type" to "Bearer"
)
}
val user = keycloak.authenticate(tokenToAuthenticate).await()
val database = ctx.pathParam("database")
authz.getAuthorizations(user).await()
val isAuthorized =
if (database == null) {
false
} else {
RoleBasedAuthorization.create(role.databaseRole(database)).match(user)
}
if (!isAuthorized && !RoleBasedAuthorization.create(role.keycloakRole()).match(user)) {
ctx.fail(HttpResponseStatus.UNAUTHORIZED.code())
ctx.response().end()
}
ctx.put("user", user)
ctx.request().resume()
return ctx.currentRoute()
}
companion object {
@OptIn(DelicateCoroutinesApi::class)
fun checkIfAuthorized(user: User, dispatcher: CoroutineDispatcher, name: String, role: AuthRole, authz: AuthorizationProvider) {
GlobalScope.launch(dispatcher) {
authz.getAuthorizations(user).await()
val isAuthorized = PermissionBasedAuthorization.create(role.databaseRole(name)).match(user)
require(isAuthorized || RoleBasedAuthorization.create(role.keycloakRole()).match(user)) {
"${HttpResponseStatus.UNAUTHORIZED.code()}: User is not allowed to $role the database $name"
}
}
}
}
}
| bsd-3-clause | ff0f34ae287b430e4b89c0ee098b08c9 | 35.323944 | 136 | 0.674292 | 4.438898 | false | false | false | false |
zachdeibert/operation-manipulation | operation-missing-android/app/src/main/java/com/zachdeibert/operationmissing/ui/menu/BackgroundSprite.kt | 1 | 2873 | package com.zachdeibert.operationmissing.ui.menu
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import com.zachdeibert.operationmissing.math.BezierCurve
import com.zachdeibert.operationmissing.math.Vector
import com.zachdeibert.operationmissing.ui.Color
import com.zachdeibert.operationmissing.ui.Component
import com.zachdeibert.operationmissing.ui.Renderer
import kotlin.random.Random
const val MILLIS_PER_CONTROL_UNIT: Long = 10000
val random = Random(System.currentTimeMillis())
class BackgroundSprite(text: String, colorId: Int, alpha: Float) : Component {
private val text: String = text
private val colorId: Int = colorId
private var start: BezierCurve
private var end: BezierCurve
private var startTime: Long = 0
private var endTime: Long = 0
private val alpha = alpha
private lateinit var color: Color
private fun random(): Float = random.nextFloat() * 2f - 1f
private fun resetTimer() {
startTime = System.currentTimeMillis()
val dist = (start.controlDistance() + end.controlDistance()) / 2f
endTime = startTime + (MILLIS_PER_CONTROL_UNIT * dist).toLong()
}
private fun projectNewPath(path: BezierCurve): BezierCurve {
val cur = Vector(path.points[2])
val control = Vector(path.points[1])
val next = Vector(floatArrayOf(random(), random()))
val dir = cur - control
val short = next - cur
val newControl = short.projectOnto(dir) + cur
return BezierCurve(arrayOf(cur.data, newControl.data, next.data))
}
override fun onResize(renderer: Renderer, width: Int, height: Int) {
}
override fun onTouchEvent(event: MotionEvent) {
}
override fun init(context: Context) {
color = Color(context, colorId)
color.A = alpha
}
override fun render(renderer: Renderer, mvp: FloatArray) {
var t: Float = (System.currentTimeMillis() - startTime).toFloat() / (endTime - startTime).toFloat()
if (t > 1) {
t = 1f
}
val startP = start.evaluate(t)
val endP = end.evaluate(t)
renderer.text.default.drawString(text, 0, text.length - 1, startP[0], startP[1] - 0.5f, endP[0], endP[1] - 0.5f, mvp, color)
if (t >= 1f) {
start = projectNewPath(start)
end = projectNewPath(end)
resetTimer()
}
}
init {
start = BezierCurve(arrayOf(floatArrayOf(random(), random()),
floatArrayOf(random(), random()),
floatArrayOf(random(), random())))
end = BezierCurve(arrayOf(floatArrayOf(random(), random()),
floatArrayOf(random(), random()),
floatArrayOf(random(), random())))
resetTimer()
}
}
| mit | 154cc09c0996eb7bf39ed1e570e1d7ce | 34.9125 | 132 | 0.630352 | 4.121951 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community | app/src/main/java/pl/orbitemobile/wspolnoty/activities/article/ArticleView.kt | 1 | 2420 | /*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.activities.article
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.squareup.picasso.Picasso
import pl.orbitemobile.mvp.bind
import pl.orbitemobile.wspolnoty.R
import pl.orbitemobile.wspolnoty.activities.mvp.DownloadViewUtil
import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO
import pl.orbitemobile.wspolnoty.data.remote.parser.Parser
class ArticleView : ArticleContract.View(R.layout.article_view) {
override var viewContent: View? = null
override var progressBar: View? = null
override var errorLayout: LinearLayout? = null
override var errorButton: TextView? = null
private lateinit var articleTitle: TextView
private lateinit var articleDescription: TextView
lateinit var appbarCollapsingImage: ImageView
private lateinit var showArticleButton: TextView
private val parser = Parser.instance
override fun View.bindViews(): View {
articleTitle = bind(R.id.article_title)
articleDescription = bind(R.id.article_description)
progressBar = bind(R.id.progress_bar)
errorLayout = bind(R.id.error_layout)
errorButton = bind(R.id.error_button)
viewContent = bind(R.id.article_layout)
showArticleButton = bind(R.id.show_article_button)
appbarCollapsingImage = activity.bind(R.id.appbar_collapsing_image)
return this
}
override fun showErrorMessage() = DownloadViewUtil.showErrorMessage(this) { presenter!!.onRetryClick() }
override fun showLoadingScreen() = DownloadViewUtil.showLoadingScreen(this)
override fun showArticleDetails(article: ArticleDTO) {
displayArticle(article)
DownloadViewUtil.showViewContent(this)
showArticleButton.setOnClickListener { presenter!!.onShowWebsiteClick() }
}
private fun displayArticle(article: ArticleDTO) {
articleTitle.text = article.title
articleDescription.movementMethod = LinkMovementMethod.getInstance()
articleDescription.text = parser.fromHtml(article.description)
Picasso.with(context)
.load(article.imgUrl)
.into(appbarCollapsingImage)
}
override fun getIntent() = activity.intent
}
| agpl-3.0 | 5decbf8bcb9f83bbf22c6d7b35fe6100 | 35.119403 | 108 | 0.742975 | 4.523364 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/compiler-plugins/noarg/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/noarg/gradleJava/NoArgGradleProjectImportHandler.kt | 3 | 2011 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.noarg.gradleJava
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler
import org.jetbrains.kotlin.idea.gradleTooling.model.noarg.NoArgModel
import org.jetbrains.kotlin.noarg.NoArgPluginNames.ANNOTATION_OPTION_NAME
import org.jetbrains.kotlin.noarg.NoArgPluginNames.INVOKE_INITIALIZERS_OPTION_NAME
import org.jetbrains.kotlin.noarg.NoArgPluginNames.PLUGIN_ID
import org.jetbrains.kotlin.noarg.NoArgPluginNames.SUPPORTED_PRESETS
class NoArgGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<NoArgModel>() {
override val compilerPluginId = PLUGIN_ID
override val pluginName = "noarg"
override val annotationOptionName = ANNOTATION_OPTION_NAME
override val pluginJarFileFromIdea = KotlinArtifacts.noargCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override val modelKey = NoArgProjectResolverExtension.KEY
override fun getOptions(model: NoArgModel): List<PluginOption> {
val additionalOptions = listOf(
PluginOption(
INVOKE_INITIALIZERS_OPTION_NAME,
model.invokeInitializers.toString()
)
)
return super.getOptions(model) + additionalOptions
}
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
| apache-2.0 | 73d9fb968a7707b74747b9138ecb4e13 | 46.880952 | 158 | 0.773744 | 5.143223 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/change/FilterMotionAction.kt | 1 | 1808 | /*
* 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.change
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.DuplicableOperatorAction
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.endOffsetInclusive
class FilterMotionAction : VimActionHandler.SingleExecution(), DuplicableOperatorAction {
override val type: Command.Type = Command.Type.CHANGE
override val argumentType: Argument.Type = Argument.Type.MOTION
override val duplicateWith: Char = '!'
override fun execute(editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments): Boolean {
val argument = cmd.argument ?: return false
val range = injector.motion.getMotionRange(editor, editor.primaryCaret(), context, argument, operatorArguments)
?: return false
val current = editor.currentCaret().getBufferPosition()
val start = editor.offsetToBufferPosition(range.startOffset)
val end = editor.offsetToBufferPosition(range.endOffsetInclusive)
if (current.line != start.line) {
editor.primaryCaret().moveToOffset(range.startOffset)
}
val count = if (start.line < end.line) end.line - start.line + 1 else 1
injector.processGroup.startFilterCommand(editor, context, Argument.EMPTY_COMMAND.copy(rawCount = count))
return true
}
}
| mit | a74b769bb297e28586dfdd0f496daace | 37.468085 | 131 | 0.775996 | 4.234192 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/extension/VimExtensionFacade.kt | 1 | 6925 | /*
* 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.extension
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.change.Extension
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.CommandAlias
import com.maddyhome.idea.vim.common.CommandAliasHandler
import com.maddyhome.idea.vim.helper.CommandLineHelper
import com.maddyhome.idea.vim.helper.EditorDataContext
import com.maddyhome.idea.vim.helper.TestInputModel
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.key.MappingOwner
import com.maddyhome.idea.vim.key.OperatorFunction
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.ui.ModalEntry
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
/**
* Vim API facade that defines functions similar to the built-in functions and statements of the original Vim.
*
* See :help eval.
*
* @author vlan
*/
object VimExtensionFacade {
/** The 'map' command for mapping keys to handlers defined in extensions. */
@JvmStatic
fun putExtensionHandlerMapping(
modes: Set<MappingMode>,
fromKeys: List<KeyStroke>,
pluginOwner: MappingOwner,
extensionHandler: ExtensionHandler,
recursive: Boolean,
) {
VimPlugin.getKey().putKeyMapping(modes, fromKeys, pluginOwner, extensionHandler, recursive)
}
/**
* COMPATIBILITY-LAYER: Additional method
* Please see: https://jb.gg/zo8n0r
*/
/** The 'map' command for mapping keys to handlers defined in extensions. */
@JvmStatic
fun putExtensionHandlerMapping(
modes: Set<MappingMode>,
fromKeys: List<KeyStroke>,
pluginOwner: MappingOwner,
extensionHandler: VimExtensionHandler,
recursive: Boolean,
) {
VimPlugin.getKey().putKeyMapping(modes, fromKeys, pluginOwner, extensionHandler, recursive)
}
/** The 'map' command for mapping keys to other keys. */
@JvmStatic
fun putKeyMapping(
modes: Set<MappingMode>,
fromKeys: List<KeyStroke>,
pluginOwner: MappingOwner,
toKeys: List<KeyStroke>,
recursive: Boolean,
) {
VimPlugin.getKey().putKeyMapping(modes, fromKeys, pluginOwner, toKeys, recursive)
}
/** The 'map' command for mapping keys to other keys if there is no other mapping to these keys */
@JvmStatic
fun putKeyMappingIfMissing(
modes: Set<MappingMode>,
fromKeys: List<KeyStroke>,
pluginOwner: MappingOwner,
toKeys: List<KeyStroke>,
recursive: Boolean,
) {
val filteredModes = modes.filterNotTo(HashSet()) { VimPlugin.getKey().hasmapto(it, toKeys) }
VimPlugin.getKey().putKeyMapping(filteredModes, fromKeys, pluginOwner, toKeys, recursive)
}
/**
* Equivalent to calling 'command' to set up a user-defined command or alias
*/
fun addCommand(
name: String,
handler: CommandAliasHandler,
) {
addCommand(name, 0, 0, handler)
}
/**
* Equivalent to calling 'command' to set up a user-defined command or alias
*/
@JvmStatic
fun addCommand(
name: String,
minimumNumberOfArguments: Int,
maximumNumberOfArguments: Int,
handler: CommandAliasHandler,
) {
VimPlugin.getCommand()
.setAlias(name, CommandAlias.Call(minimumNumberOfArguments, maximumNumberOfArguments, name, handler))
}
/** Sets the value of 'operatorfunc' to be used as the operator function in 'g@'. */
@JvmStatic
fun setOperatorFunction(function: OperatorFunction) {
VimPlugin.getKey().operatorFunction = function
}
/**
* Runs normal mode commands similar to ':normal! {commands}'.
* Mappings doesn't work with this function
*
* XXX: Currently it doesn't make the editor enter the normal mode, it doesn't recover from incomplete commands, it
* leaves the editor in the insert mode if it's been activated.
*/
@JvmStatic
fun executeNormalWithoutMapping(keys: List<KeyStroke>, editor: Editor) {
val context = EditorDataContext.init(editor)
keys.forEach { KeyHandler.getInstance().handleKey(editor.vim, it, context.vim, false, false) }
}
/** Returns a single key stroke from the user input similar to 'getchar()'. */
@JvmStatic
fun inputKeyStroke(editor: Editor): KeyStroke {
if (editor.vim.vimStateMachine.isDotRepeatInProgress) {
val input = Extension.consumeKeystroke()
return input ?: error("Not enough keystrokes saved: ${Extension.lastExtensionHandler}")
}
val key: KeyStroke? = if (ApplicationManager.getApplication().isUnitTestMode) {
val mappingStack = KeyHandler.getInstance().keyStack
mappingStack.feedSomeStroke() ?: TestInputModel.getInstance(editor).nextKeyStroke()?.also {
if (editor.vim.vimStateMachine.isRecording) {
KeyHandler.getInstance().modalEntryKeys += it
}
}
} else {
var ref: KeyStroke? = null
ModalEntry.activate(editor.vim) { stroke: KeyStroke? ->
ref = stroke
false
}
ref
}
val result = key ?: KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE.toChar())
Extension.addKeystroke(result)
return result
}
/** Returns a string typed in the input box similar to 'input()'. */
@JvmStatic
fun inputString(editor: Editor, prompt: String, finishOn: Char?): String {
return service<CommandLineHelper>().inputString(editor.vim, prompt, finishOn) ?: ""
}
/** Get the current contents of the given register similar to 'getreg()'. */
@JvmStatic
fun getRegister(register: Char): List<KeyStroke>? {
val reg = VimPlugin.getRegister().getRegister(register) ?: return null
return reg.keys
}
@JvmStatic
fun getRegisterForCaret(register: Char, caret: VimCaret): List<KeyStroke>? {
val reg = caret.registerStorage.getRegister(caret, register) ?: return null
return reg.keys
}
/** Set the current contents of the given register */
@JvmStatic
fun setRegister(register: Char, keys: List<KeyStroke?>?) {
VimPlugin.getRegister().setKeys(register, keys?.filterNotNull() ?: emptyList())
}
/** Set the current contents of the given register */
@JvmStatic
fun setRegisterForCaret(register: Char, caret: VimCaret, keys: List<KeyStroke?>?) {
caret.registerStorage.setKeys(caret, register, keys?.filterNotNull() ?: emptyList())
}
/** Set the current contents of the given register */
@JvmStatic
fun setRegister(register: Char, keys: List<KeyStroke?>?, type: SelectionType) {
VimPlugin.getRegister().setKeys(register, keys?.filterNotNull() ?: emptyList(), type)
}
}
| mit | d8bc2a2c15f4748191680e617476ac05 | 33.625 | 117 | 0.722022 | 4.19697 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/functionalities/activations/ELUSpec.kt | 1 | 1760 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.functionalities.activations
import com.kotlinnlp.simplednn.core.functionalities.activations.ELU
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class ELUSpec : Spek({
describe("an ELU activation function") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.1, 0.01, -0.1, -0.01, 1.0, 10.0, -1.0, -10.0))
context("alpha = 1.0") {
val activationFunction = ELU(alpha = 1.0)
val activatedArray = activationFunction.f(array)
context("f") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(
0.0, 0.1, 0.01, -0.095162582, -0.009950166, 1.0, 10.0, -0.632120559, -0.9999546
))
it("should return the expected values") {
assertTrue { expectedArray.equals(activatedArray, tolerance = 1.0e-08) }
}
}
context("dfOptimized") {
val dfArray = activationFunction.dfOptimized(activatedArray)
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(
1.0, 1.0, 1.0, 0.904837418, 0.990049834, 1.0, 1.0, 0.367879441, 0.0000454
))
it("should return the expected values") {
assertTrue { expectedArray.equals(dfArray, tolerance = 1.0e-08) }
}
}
}
}
})
| mpl-2.0 | d0808b35cc8ba7cab914dd10e5bb56d3 | 31 | 111 | 0.644318 | 3.659044 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/generate/KotlinUastCodeGenerationPlugin.kt | 3 | 23107 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.kotlin.generate
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.references.fe10.KtFe10SimpleNameReference
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.kotlin.*
import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement
class KotlinUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override val language: Language
get() = KotlinLanguage.INSTANCE
override fun getElementFactory(project: Project): UastElementFactory =
KotlinUastElementFactory(project)
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.toSourcePsiFakeAware().singleOrNull() ?: return null
val newPsi = newElement.sourcePsi?.let {
when {
it is KtCallExpression && it.parent is KtQualifiedExpression -> it.parent
else -> it
}
} ?: return null
val psiFactory = KtPsiFactory(oldPsi.project)
val oldParentPsi = oldPsi.parent
val (updOldPsi, updNewPsi) = when {
oldParentPsi is KtStringTemplateExpression && oldParentPsi.entries.size == 1 ->
oldParentPsi to newPsi
oldPsi is KtStringTemplateEntry && newPsi !is KtStringTemplateEntry && newPsi is KtExpression ->
oldPsi to psiFactory.createBlockStringTemplateEntry(newPsi)
oldPsi is KtBlockExpression && newPsi is KtBlockExpression -> {
if (!hasBraces(oldPsi) && hasBraces(newPsi)) {
oldPsi to psiFactory.createLambdaExpression("none", newPsi.statements.joinToString("\n") { "println()" }).bodyExpression!!.also {
it.statements.zip(newPsi.statements).forEach { it.first.replace(it.second) }
}
} else
oldPsi to newPsi
}
else ->
oldPsi to newPsi
}
val replaced = updOldPsi.replace(updNewPsi)?.safeAs<KtElement>()?.let { ShortenReferences.DEFAULT.process(it) }
return when {
newElement.sourcePsi is KtCallExpression && replaced is KtQualifiedExpression -> replaced.selectorExpression
else -> replaced
}?.toUElementOfExpectedTypes(elementType)
}
override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? {
val sourcePsi = reference.sourcePsi ?: return null
if (sourcePsi !is KtSimpleNameExpression) return null
return KtFe10SimpleNameReference(sourcePsi)
.bindToElement(element, KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING)
}
override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? {
val sourcePsi = reference.sourcePsi ?: return null
if (sourcePsi !is KtElement) return null
return ShortenReferences.DEFAULT.process(sourcePsi).toUElementOfType()
}
override fun importMemberOnDemand(reference: UQualifiedReferenceExpression): UExpression? {
val ktQualifiedExpression = reference.sourcePsi?.castSafelyTo<KtDotQualifiedExpression>() ?: return null
val selector = ktQualifiedExpression.selectorExpression ?: return null
val ptr = SmartPointerManager.createPointer(selector)
ImportAllMembersIntention().applyTo(ktQualifiedExpression, null)
return ptr.element?.toUElementOfType()
}
}
private fun hasBraces(oldPsi: KtBlockExpression): Boolean = oldPsi.lBrace != null && oldPsi.rBrace != null
class KotlinUastElementFactory(project: Project) : UastElementFactory {
private val psiFactory = KtPsiFactory(project)
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory.createExpression(qualifiedName).let {
when (it) {
is KtDotQualifiedExpression -> KotlinUQualifiedReferenceExpression(it, null)
is KtSafeQualifiedExpression -> KotlinUSafeQualifiedExpression(it, null)
else -> null
}
}
}
override fun createCallExpression(
receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?
): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val name = methodName.quoteIfNeeded()
val methodCall = psiFactory.createExpression(
buildString {
if (receiver != null) {
append("a")
receiver.sourcePsi?.nextSibling.safeAs<PsiWhiteSpace>()?.let { whitespaces ->
append(whitespaces.text)
}
append(".")
}
append(name)
append("()")
}
).getPossiblyQualifiedCallExpression() ?: return null
if (receiver != null) {
methodCall.parent.safeAs<KtDotQualifiedExpression>()?.receiverExpression?.replace(wrapULiteral(receiver).sourcePsi!!)
}
val valueArgumentList = methodCall.valueArgumentList
for (parameter in parameters) {
valueArgumentList?.addArgument(psiFactory.createArgument(wrapULiteral(parameter).sourcePsi as KtExpression))
}
if (context !is KtElement) return KotlinUFunctionCallExpression(methodCall, null)
val analyzableMethodCall = psiFactory.getAnalyzableMethodCall(methodCall, context)
if (analyzableMethodCall.canMoveLambdaOutsideParentheses()) {
analyzableMethodCall.moveFunctionLiteralOutsideParentheses()
}
if (expectedReturnType == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null)
val methodCallPsiType = KotlinUFunctionCallExpression(analyzableMethodCall, null).getExpressionType()
if (methodCallPsiType == null || !expectedReturnType.isAssignableFrom(GenericsUtil.eliminateWildcards(methodCallPsiType))) {
val typeParams = (context as? KtElement)?.let { kontext ->
val resolutionFacade = kontext.getResolutionFacade()
(expectedReturnType as? PsiClassType)?.parameters?.map { it.resolveToKotlinType(resolutionFacade) }
}
if (typeParams == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null)
for (typeParam in typeParams) {
val typeParameter = psiFactory.createTypeArgument(typeParam.fqName?.asString().orEmpty())
analyzableMethodCall.addTypeArgument(typeParameter)
}
return KotlinUFunctionCallExpression(analyzableMethodCall, null)
}
return KotlinUFunctionCallExpression(analyzableMethodCall, null)
}
private fun KtPsiFactory.getAnalyzableMethodCall(methodCall: KtCallExpression, context: KtElement): KtCallExpression {
val analyzableElement = ((createExpressionCodeFragment("(null)", context).copy() as KtExpressionCodeFragment)
.getContentElement()!! as KtParenthesizedExpression).expression!!
val isQualified = methodCall.parent is KtQualifiedExpression
return if (isQualified) {
(analyzableElement.replaced(methodCall.parent) as KtQualifiedExpression).lastChild as KtCallExpression
} else {
analyzableElement.replaced(methodCall)
}
}
override fun createCallableReferenceExpression(
receiver: UExpression?,
methodName: String,
context: PsiElement?
): UCallableReferenceExpression? {
val text = receiver?.sourcePsi?.text ?: ""
val callableExpression = psiFactory.createCallableReferenceExpression("$text::$methodName") ?: return null
return KotlinUCallableReferenceExpression(callableExpression, null)
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression {
return KotlinStringULiteralExpression(psiFactory.createExpression(StringUtil.wrapWithDoubleQuote(text)), null)
}
override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? {
return when (val literalExpr = psiFactory.createExpression(long.toString() + "L")) {
is KtConstantExpression -> KotlinULiteralExpression(literalExpr, null)
is KtPrefixExpression -> KotlinUPrefixExpression(literalExpr, null)
else -> null
}
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression {
return psiFactory.createExpression("null").toUElementOfType()!!
}
@Suppress("UNUSED_PARAMETER")
/*override*/ fun createIntLiteral(value: Int, context: PsiElement?): ULiteralExpression {
return psiFactory.createExpression(value.toString()).toUElementOfType()!!
}
private fun KtExpression.ensureBlockExpressionBraces(): KtExpression {
if (this !is KtBlockExpression || hasBraces(this)) return this
val blockExpression = psiFactory.createBlock(this.statements.joinToString("\n") { "println()" })
for ((placeholder, statement) in blockExpression.statements.zip(this.statements)) {
placeholder.replace(statement)
}
return blockExpression
}
@Deprecated("use version with context parameter")
fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?): UIfExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createIfExpression(condition, thenBranch, elseBranch, null)
}
override fun createIfExpression(
condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?
): UIfExpression? {
val conditionPsi = condition.sourcePsi as? KtExpression ?: return null
val thenBranchPsi = thenBranch.sourcePsi as? KtExpression ?: return null
val elseBranchPsi = elseBranch?.sourcePsi as? KtExpression
return KotlinUIfExpression(
psiFactory.createIf(conditionPsi, thenBranchPsi.ensureBlockExpressionBraces(), elseBranchPsi?.ensureBlockExpressionBraces()),
givenParent = null
)
}
@Deprecated("use version with context parameter")
fun createParenthesizedExpression(expression: UExpression): UParenthesizedExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createParenthesizedExpression(expression, null)
}
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val source = expression.sourcePsi ?: return null
val parenthesized = psiFactory.createExpression("(${source.text})") as? KtParenthesizedExpression ?: return null
return KotlinUParenthesizedExpression(parenthesized, null)
}
@Deprecated("use version with context parameter")
fun createSimpleReference(name: String): USimpleNameReferenceExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createSimpleReference(name, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression {
return KotlinUSimpleReferenceExpression(psiFactory.createSimpleName(name), null)
}
@Deprecated("use version with context parameter")
fun createSimpleReference(variable: UVariable): USimpleNameReferenceExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createSimpleReference(variable, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
@Deprecated("use version with context parameter")
fun createReturnExpresion(expression: UExpression?, inLambda: Boolean): UReturnExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createReturnExpresion(expression, inLambda, null)
}
override fun createReturnExpresion(expression: UExpression?, inLambda: Boolean, context: PsiElement?): UReturnExpression {
val label = if (inLambda && context != null) getParentLambdaLabelName(context)?.let { "@$it" } ?: "" else ""
val returnExpression = psiFactory.createExpression("return$label 1") as KtReturnExpression
val sourcePsi = expression?.sourcePsi
if (sourcePsi != null) {
returnExpression.returnedExpression!!.replace(sourcePsi)
} else {
returnExpression.returnedExpression?.delete()
}
return KotlinUReturnExpression(returnExpression, null)
}
private fun getParentLambdaLabelName(context: PsiElement): String? {
val lambdaExpression = context.getParentOfType<KtLambdaExpression>(false) ?: return null
lambdaExpression.parent.safeAs<KtLabeledExpression>()?.let { return it.getLabelName() }
val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null
callExpression.valueArguments.find {
it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression
} ?: return null
return callExpression.getCallNameExpression()?.text
}
@Deprecated("use version with context parameter")
fun createBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator
): UBinaryExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createBinaryExpression(leftOperand, rightOperand, operator, null)
}
override fun createBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?
): UBinaryExpression? {
val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null
return KotlinUBinaryExpression(binaryExpression, null)
}
private fun joinBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator
): KtBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val binaryExpression = psiFactory.createExpression("a ${operator.text} b") as? KtBinaryExpression ?: return null
binaryExpression.left?.replace(leftPsi)
binaryExpression.right?.replace(rightPsi)
return binaryExpression
}
@Deprecated("use version with context parameter")
fun createFlatBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator
): UPolyadicExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createFlatBinaryExpression(leftOperand, rightOperand, operator, null)
}
override fun createFlatBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?
): UPolyadicExpression? {
fun unwrapParentheses(exp: KtExpression?) {
if (exp !is KtParenthesizedExpression) return
if (!KtPsiUtil.areParenthesesUseless(exp)) return
exp.expression?.let { exp.replace(it) }
}
val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null
unwrapParentheses(binaryExpression.left)
unwrapParentheses(binaryExpression.right)
return psiFactory.createExpression(binaryExpression.text).toUElementOfType()!!
}
@Deprecated("use version with context parameter")
fun createBlockExpression(expressions: List<UExpression>): UBlockExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createBlockExpression(expressions, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression {
val sourceExpressions = expressions.flatMap { it.toSourcePsiFakeAware() }
val block = psiFactory.createBlock(
sourceExpressions.joinToString(separator = "\n") { "println()" }
)
for ((placeholder, psiElement) in block.statements.zip(sourceExpressions)) {
placeholder.replace(psiElement)
}
return KotlinUBlockExpression(block, null)
}
@Deprecated("use version with context parameter")
fun createDeclarationExpression(declarations: List<UDeclaration>): UDeclarationsExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createDeclarationExpression(declarations, null)
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression {
return object : KotlinUDeclarationsExpression(null), KotlinFakeUElement {
override var declarations: List<UDeclaration> = declarations
override fun unwrapToSourcePsi(): List<PsiElement> = declarations.flatMap { it.toSourcePsiFakeAware() }
}
}
override fun createLambdaExpression(
parameters: List<UParameterInfo>,
body: UExpression,
context: PsiElement?
): ULambdaExpression? {
val resolutionFacade = (context as? KtElement)?.getResolutionFacade()
val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true }
val newLambdaStatements = if (body is UBlockExpression) {
body.expressions.flatMap { member ->
when {
member is UReturnExpression -> member.returnExpression?.toSourcePsiFakeAware().orEmpty()
else -> member.toSourcePsiFakeAware()
}
}
} else
listOf(body.sourcePsi!!)
val ktLambdaExpression = psiFactory.createLambdaExpression(
parameters.joinToString(", ") { p ->
val ktype = resolutionFacade?.let { p.type?.resolveToKotlinType(it) }
StringBuilder().apply {
append(p.suggestedName ?: ktype?.let { Fe10KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() })
?: Fe10KotlinNameSuggester.suggestNameByName("v", validator)
ktype?.fqName?.toString()?.let { append(": ").append(it) }
}
},
newLambdaStatements.joinToString("\n") { "placeholder" }
)
for ((old, new) in ktLambdaExpression.bodyExpression!!.statements.zip(newLambdaStatements)) {
old.replace(new)
}
return ktLambdaExpression.toUElementOfType()!!
}
@Deprecated("use version with context parameter")
fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression): ULambdaExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createLambdaExpression(parameters, body, null)
}
override fun createLocalVariable(
suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?
): ULocalVariable {
val resolutionFacade = (context as? KtElement)?.getResolutionFacade()
val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true }
val ktype = resolutionFacade?.let { type?.resolveToKotlinType(it) }
val function = psiFactory.createFunction(
buildString {
append("fun foo() { ")
append(if (immutable) "val" else "var")
append(" ")
append(suggestedName ?: ktype?.let { Fe10KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() })
?: Fe10KotlinNameSuggester.suggestNameByName("v", validator)
ktype?.fqName?.toString()?.let { append(": ").append(it) }
append(" = null")
append("}")
}
)
val ktVariable = PsiTreeUtil.findChildOfType(function, KtVariableDeclaration::class.java)!!
val newVariable = ktVariable.initializer!!.replace(initializer.sourcePsi!!).parent
return newVariable.toUElementOfType<UVariable>() as ULocalVariable
}
@Deprecated("use version with context parameter")
fun createLocalVariable(
suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean
): ULocalVariable {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createLocalVariable(suggestedName, type, initializer, immutable, null)
}
}
private fun usedNamesFilter(context: KtElement): (String) -> Boolean {
val scope = context.getResolutionScope()
return { name: String -> scope.findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) == null }
}
| apache-2.0 | f73022ebbb817685bf2cc58e8415311e | 45.870183 | 149 | 0.696283 | 5.827743 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/keyboard/KeyboardPagerFragment.kt | 2 | 3827 |
package org.thoughtcrime.securesms.keyboard
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.MediaKeyboard
import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardPageFragment
import org.thoughtcrime.securesms.keyboard.gif.GifKeyboardPageFragment
import org.thoughtcrime.securesms.keyboard.sticker.StickerKeyboardPageFragment
import org.thoughtcrime.securesms.util.visible
import kotlin.reflect.KClass
class KeyboardPagerFragment : Fragment(R.layout.keyboard_pager_fragment) {
private lateinit var emojiButton: View
private lateinit var stickerButton: View
private lateinit var gifButton: View
private lateinit var viewModel: KeyboardPagerViewModel
private val fragments: MutableMap<KClass<*>, Fragment> = mutableMapOf()
private var currentFragment: Fragment? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
emojiButton = view.findViewById(R.id.keyboard_pager_fragment_emoji)
stickerButton = view.findViewById(R.id.keyboard_pager_fragment_sticker)
gifButton = view.findViewById(R.id.keyboard_pager_fragment_gif)
viewModel = ViewModelProviders.of(requireActivity())[KeyboardPagerViewModel::class.java]
viewModel.page().observe(viewLifecycleOwner, this::onPageSelected)
viewModel.pages().observe(viewLifecycleOwner) { pages ->
emojiButton.visible = pages.contains(KeyboardPage.EMOJI) && pages.size > 1
stickerButton.visible = pages.contains(KeyboardPage.STICKER) && pages.size > 1
gifButton.visible = pages.contains(KeyboardPage.GIF) && pages.size > 1
}
emojiButton.setOnClickListener { viewModel.switchToPage(KeyboardPage.EMOJI) }
stickerButton.setOnClickListener { viewModel.switchToPage(KeyboardPage.STICKER) }
gifButton.setOnClickListener { viewModel.switchToPage(KeyboardPage.GIF) }
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.page().value?.let(this::onPageSelected)
}
private fun onPageSelected(page: KeyboardPage) {
emojiButton.isSelected = page == KeyboardPage.EMOJI
stickerButton.isSelected = page == KeyboardPage.STICKER
gifButton.isSelected = page == KeyboardPage.GIF
when (page) {
KeyboardPage.EMOJI -> displayEmojiPage()
KeyboardPage.GIF -> displayGifPage()
KeyboardPage.STICKER -> displayStickerPage()
}
findListener<MediaKeyboard.MediaKeyboardListener>()?.onKeyboardChanged(page)
}
private fun displayEmojiPage() = displayPage(::EmojiKeyboardPageFragment)
private fun displayGifPage() = displayPage(::GifKeyboardPageFragment)
private fun displayStickerPage() = displayPage(::StickerKeyboardPageFragment)
private inline fun <reified F : Fragment> displayPage(fragmentFactory: () -> F) {
if (currentFragment is F) {
return
}
val transaction = childFragmentManager.beginTransaction()
currentFragment?.let { transaction.hide(it) }
var fragment = fragments[F::class]
if (fragment == null) {
fragment = fragmentFactory()
transaction.add(R.id.fragment_container, fragment)
fragments[F::class] = fragment
} else {
transaction.show(fragment)
}
currentFragment = fragment
transaction.commitAllowingStateLoss()
}
fun show() {
if (isAdded && view != null) {
viewModel.page().value?.let(this::onPageSelected)
}
}
fun hide() {
if (isAdded && view != null) {
val transaction = childFragmentManager.beginTransaction()
fragments.values.forEach { transaction.remove(it) }
transaction.commitAllowingStateLoss()
currentFragment = null
fragments.clear()
}
}
}
| gpl-3.0 | 6f55212bcdac4f60c91284a996318c3a | 34.766355 | 92 | 0.75098 | 4.678484 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/helpers/OrchidGroovydocInvokerImpl.kt | 1 | 1568 | package com.eden.orchid.groovydoc.helpers
import com.caseyjbrooks.clog.Clog
import com.copperleaf.groovydoc.json.GroovydocInvoker
import com.copperleaf.groovydoc.json.GroovydocInvokerImpl
import com.copperleaf.groovydoc.json.models.GroovydocRootdoc
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.utilities.InputStreamIgnorer
import com.eden.orchid.utilities.OrchidUtils
import java.io.File
import java.nio.file.Path
import javax.inject.Inject
import javax.inject.Named
class OrchidGroovydocInvokerImpl
@Inject
constructor(
val context: OrchidContext
) : OrchidGroovydocInvoker {
var hasRunGroovydoc = false
val cacheDir: Path by lazy { OrchidUtils.getCacheDir("groovydoc") }
val outputDir: Path by lazy { OrchidUtils.getTempDir("groovydoc", true) }
val groovydocRunner: GroovydocInvoker by lazy {
GroovydocInvokerImpl(cacheDir)
}
override fun getRootDoc(
sourceDirs: List<String>,
extraArgs: List<String>
): GroovydocRootdoc? {
if(hasRunGroovydoc) {
val cachedRootDoc = groovydocRunner.loadCachedRootDoc(outputDir)
if (cachedRootDoc != null) {
Clog.i("returning cached groovydoc")
return cachedRootDoc
}
}
val sources = sourceDirs.map { File(context.sourceDir).toPath().resolve(it) }
val rootDoc = groovydocRunner.getRootDoc(sources, outputDir, extraArgs) { inputStream ->
InputStreamIgnorer(inputStream)
}
hasRunGroovydoc = true
return rootDoc
}
}
| mit | f7a3deb2492889783020a9ee7fa58374 | 31.666667 | 96 | 0.714286 | 4.367688 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/habit/edit/EditHabitViewState.kt | 1 | 14507 | package io.ipoli.android.habit.edit
import io.ipoli.android.Constants
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.Validator
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.habit.edit.EditHabitViewState.StateType.*
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Icon
import io.ipoli.android.tag.Tag
import org.threeten.bp.DayOfWeek
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 6/16/18.
*/
sealed class EditHabitAction : Action {
object Save : EditHabitAction()
object MakeBad : EditHabitAction()
object MakeGood : EditHabitAction()
data class Load(
val habitId: String,
val params: EditHabitViewController.Params?
) : EditHabitAction() {
override fun toMap() = mapOf(
"mode" to if (params != null) "addPreset" else if (habitId.isBlank()) "add" else "edit",
"habitId" to habitId,
"name" to params?.name,
"color" to params?.color?.name,
"icon" to params?.icon?.name,
"isGood" to params?.isGood,
"timesADay" to params?.timesADay,
"days" to params?.days?.joinToString(",") { it.name }
)
}
data class DeselectDay(val weekDay: DayOfWeek) : EditHabitAction() {
override fun toMap() = mapOf("weekDay" to weekDay.name)
}
data class SelectDay(val weekDay: DayOfWeek) : EditHabitAction() {
override fun toMap() = mapOf("weekDay" to weekDay.name)
}
data class AddTag(val tagName: String) : EditHabitAction() {
override fun toMap() = mapOf("tagName" to tagName)
}
data class RemoveTag(val tag: Tag) : EditHabitAction() {
override fun toMap() = mapOf("tag" to tag)
}
data class ChangeColor(val color: Color) : EditHabitAction() {
override fun toMap() = mapOf("color" to color.name)
}
data class ChangeIcon(val icon: Icon) : EditHabitAction() {
override fun toMap() = mapOf("icon" to icon.name)
}
data class ChangeChallenge(val challenge: Challenge?) : EditHabitAction() {
override fun toMap() = mapOf("challenge" to challenge)
}
data class ChangeNote(val note: String) : EditHabitAction() {
override fun toMap() = mapOf("note" to note)
}
data class Validate(
val name: String
) : EditHabitAction() {
override fun toMap() = mapOf(
"name" to name
)
}
data class Remove(val habitId: String) : EditHabitAction() {
override fun toMap() = mapOf("habitId" to habitId)
}
data class AddReminder(val reminder: Habit.Reminder) : EditHabitAction()
data class ChangeReminder(val index: Int, val reminder: Habit.Reminder) : EditHabitAction()
data class RemoveReminder(val index: Int) : EditHabitAction()
data class ChangeTimesADay(val index: Int) : EditHabitAction()
}
object EditHabitReducer : BaseViewStateReducer<EditHabitViewState>() {
override val stateKey = key<EditHabitViewState>()
override fun reduce(
state: AppState,
subState: EditHabitViewState,
action: Action
) =
when (action) {
is EditHabitAction.Load -> {
val s = if (action.habitId.isBlank()) {
subState.copy(
type = EditHabitViewState.StateType.HABIT_DATA_CHANGED,
tags = state.dataState.tags,
isEditing = false,
hasChangedColor = false,
hasChangedIcon = false
)
} else {
createFromHabits(state.dataState.habits!!, action.habitId, subState, state)
}
val params = action.params
if (params != null) {
s.copy(
name = params.name,
color = params.color,
icon = params.icon,
timesADay = params.timesADay,
isGood = params.isGood,
days = params.days,
hasChangedColor = true,
hasChangedIcon = true
)
} else s
}
is DataLoadedAction.TagsChanged ->
subState.copy(
type = TAGS_CHANGED,
tags = action.tags - subState.habitTags
)
is DataLoadedAction.ChallengesChanged ->
if (subState.isEditing && subState.challenge != null)
subState.copy(
type = CHALLENGE_CHANGED,
challenge = action.challenges.firstOrNull { it.id == subState.challenge.id }
)
else
subState
is EditHabitAction.SelectDay ->
subState.copy(
type = EditHabitViewState.StateType.DAYS_CHANGED,
days = subState.days + action.weekDay
)
is EditHabitAction.DeselectDay ->
subState.copy(
type = EditHabitViewState.StateType.DAYS_CHANGED,
days = subState.days - action.weekDay
)
is EditHabitAction.RemoveTag -> {
val habitTags = subState.habitTags - action.tag
subState.copy(
type = TAGS_CHANGED,
habitTags = habitTags,
tags = subState.tags + action.tag,
maxTagsReached = habitTags.size >= Constants.MAX_TAGS_PER_ITEM
)
}
is EditHabitAction.AddTag -> {
val tag = subState.tags.first { it.name == action.tagName }
val color = if (!subState.hasChangedColor && subState.habitTags.isEmpty())
tag.color
else subState.color
val icon =
if (!subState.hasChangedIcon && subState.habitTags.isEmpty() && tag.icon != null)
tag.icon
else subState.icon
val habitTags = subState.habitTags + tag
subState.copy(
type = TAGS_CHANGED,
habitTags = habitTags,
tags = subState.tags - tag,
maxTagsReached = habitTags.size >= Constants.MAX_TAGS_PER_ITEM,
icon = icon,
color = color
)
}
is EditHabitAction.ChangeColor ->
subState.copy(
type = COLOR_CHANGED,
color = action.color,
hasChangedColor = true
)
is EditHabitAction.ChangeIcon ->
subState.copy(
type = ICON_CHANGED,
icon = action.icon,
hasChangedIcon = true
)
is EditHabitAction.ChangeChallenge ->
subState.copy(
type = CHALLENGE_CHANGED,
challenge = action.challenge
)
is EditHabitAction.ChangeNote ->
subState.copy(
type = NOTE_CHANGED,
note = action.note
)
is EditHabitAction.MakeGood ->
subState.copy(
type = HABIT_TYPE_CHANGED,
isGood = true
)
is EditHabitAction.MakeBad ->
subState.copy(
type = HABIT_TYPE_CHANGED,
isGood = false
)
is EditHabitAction.ChangeTimesADay -> {
val newTimesADay = subState.timesADayValues[action.index]
subState.copy(
type = TIMES_A_DAY_CHANGED,
timesADay = newTimesADay,
maxRemindersReached = if(newTimesADay == Habit.UNLIMITED_TIMES_A_DAY) false else newTimesADay <= subState.reminders.size,
reminders = when {
newTimesADay == Habit.UNLIMITED_TIMES_A_DAY -> subState.reminders
subState.reminders.size > newTimesADay -> subState.reminders.subList(
0,
newTimesADay
)
else -> subState.reminders
}
)
}
is EditHabitAction.AddReminder -> {
val newReminders = (subState.reminders + action.reminder)
.distinctBy { it.time }
.sortedBy { it.time }
subState.copy(
type = REMINDERS_CHANGED,
reminders = newReminders,
maxRemindersReached = if(subState.timesADay == Habit.UNLIMITED_TIMES_A_DAY) false else newReminders.size == subState.timesADay
)
}
is EditHabitAction.ChangeReminder ->
subState.copy(
type = REMINDERS_CHANGED,
reminders = subState.reminders
.mapIndexed { i, r ->
if (i == action.index) action.reminder else r
}
.distinctBy { it.time }
.sortedBy { it.time }
)
is EditHabitAction.RemoveReminder ->
subState.copy(
type = REMINDERS_CHANGED,
reminders = subState.reminders
.mapIndexedNotNull { i, r ->
if (i == action.index) null else r
}
.sortedBy { it.time },
maxRemindersReached = false
)
is EditHabitAction.Validate -> {
val name = action.name
val errors = Validator.validate(action).check<ValidationError> {
"name" {
given { name.isBlank() } addError ValidationError.EMPTY_NAME
}
"days" {
given { subState.days.isEmpty() } addError ValidationError.EMPTY_DAYS
}
}
when {
errors.isEmpty() ->
subState.copy(
type = VALID_NAME,
name = name
)
errors.contains(ValidationError.EMPTY_NAME) -> subState.copy(
type = VALIDATION_ERROR_EMPTY_NAME
)
else -> subState.copy(
type = VALIDATION_ERROR_EMPTY_DAYS
)
}
}
else -> subState
}
private fun createFromHabits(
habits: List<Habit>,
habitId: String,
subState: EditHabitViewState,
state: AppState
): EditHabitViewState {
val habit = habits.firstOrNull { it.id == habitId }
return if (habit == null) {
subState.copy(
type = REMOVED
)
} else {
val challenge = if (habit.challengeId != null) {
state.dataState.challenges?.first { it.id == habit.challengeId }
} else null
subState.copy(
type = HABIT_DATA_CHANGED,
habit = habit,
id = habit.id,
name = habit.name,
color = habit.color,
icon = habit.icon,
habitTags = habit.tags,
tags = state.dataState.tags - habit.tags,
challenge = challenge,
note = habit.note,
maxTagsReached = habit.tags.size >= Constants.MAX_TAGS_PER_ITEM,
isGood = habit.isGood,
timesADay = habit.timesADay,
days = habit.days.toSet(),
reminders = habit.reminders,
maxRemindersReached = if(habit.isUnlimited) false else habit.reminders.size == habit.timesADay,
isEditing = true,
hasChangedColor = true,
hasChangedIcon = true
)
}
}
override fun defaultState() = EditHabitViewState(
type = LOADING,
habit = null,
id = "",
name = "",
habitTags = emptyList(),
tags = emptyList(),
days = DayOfWeek.values().toSet(),
isGood = true,
timesADay = Habit.UNLIMITED_TIMES_A_DAY,
color = Color.GREEN,
icon = Icon.FLOWER,
challenge = null,
note = "",
maxTagsReached = false,
timesADayValues = listOf(Habit.UNLIMITED_TIMES_A_DAY) + (1..Constants.MAX_HABIT_TIMES_A_DAY).toList(),
reminders = emptyList(),
maxRemindersReached = false,
isEditing = false,
hasChangedColor = false,
hasChangedIcon = false
)
enum class ValidationError {
EMPTY_NAME, EMPTY_DAYS
}
}
data class EditHabitViewState(
val type: StateType,
val habit: Habit?,
val id: String,
val name: String,
val habitTags: List<Tag>,
val tags: List<Tag>,
val days: Set<DayOfWeek>,
val isGood: Boolean,
val timesADay: Int,
val color: Color,
val icon: Icon,
val challenge: Challenge?,
val note: String,
val maxTagsReached: Boolean,
val timesADayValues: List<Int>,
val reminders: List<Habit.Reminder>,
val maxRemindersReached: Boolean,
val isEditing: Boolean,
val hasChangedColor: Boolean,
val hasChangedIcon: Boolean
) : BaseViewState() {
enum class StateType {
LOADING,
HABIT_DATA_CHANGED,
TAGS_CHANGED,
DAYS_CHANGED,
COLOR_CHANGED,
ICON_CHANGED,
CHALLENGE_CHANGED,
NOTE_CHANGED,
REMINDERS_CHANGED,
TIMES_A_DAY_CHANGED,
VALID_NAME,
HABIT_TYPE_CHANGED,
VALIDATION_ERROR_EMPTY_NAME,
VALIDATION_ERROR_EMPTY_DAYS,
REMOVED
}
} | gpl-3.0 | 4d36089e9953a731908451be88c12c03 | 33.460808 | 146 | 0.51003 | 5.059993 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifySuperTypeFix.kt | 3 | 5708 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class SpecifySuperTypeFix(
superExpression: KtSuperExpression,
private val superTypes: List<String>
) : KotlinQuickFixAction<KtSuperExpression>(superExpression) {
override fun getText() = KotlinBundle.message("intention.name.specify.supertype")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val superExpression = element ?: return
CommandProcessor.getInstance().runUndoTransparentAction {
if (superTypes.size == 1) {
superExpression.specifySuperType(superTypes.first())
} else {
JBPopupFactory
.getInstance()
.createListPopup(createListPopupStep(superExpression, superTypes))
.showInBestPositionFor(editor)
}
}
}
private fun KtSuperExpression.specifySuperType(superType: String) {
project.executeWriteCommand(KotlinBundle.message("intention.name.specify.supertype")) {
val label = this.labelQualifier?.text ?: ""
replace(KtPsiFactory(this).createExpression("super<$superType>$label"))
}
}
private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<String>): ListPopupStep<*> {
return object : BaseListPopupStep<String>(KotlinBundle.message("popup.title.choose.supertype"), superTypes) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
superExpression.specifySuperType(selectedValue)
}
return PopupStep.FINAL_CHOICE
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtSuperExpression>? {
val superExpression = diagnostic.psiElement as? KtSuperExpression ?: return null
val qualifiedExpression = superExpression.getQualifiedExpressionForReceiver() ?: return null
val selectorExpression = qualifiedExpression.selectorExpression ?: return null
val containingClassOrObject = superExpression.getStrictParentOfType<KtClassOrObject>() ?: return null
val superTypeListEntries = containingClassOrObject.superTypeListEntries
if (superTypeListEntries.isEmpty()) return null
val context = superExpression.analyze(BodyResolveMode.PARTIAL)
val superTypes = superTypeListEntries.mapNotNull {
val typeReference = it.typeReference ?: return@mapNotNull null
val typeElement = it.typeReference?.typeElement ?: return@mapNotNull null
val kotlinType = context[BindingContext.TYPE, typeReference] ?: return@mapNotNull null
typeElement to kotlinType
}
if (superTypes.size != superTypeListEntries.size) return null
val psiFactory = KtPsiFactory(superExpression)
val superTypesForSuperExpression = superTypes.mapNotNull { (typeElement, kotlinType) ->
if (superTypes.any { it.second != kotlinType && it.second.isSubtypeOf(kotlinType) }) return@mapNotNull null
val fqName = kotlinType.fqName ?: return@mapNotNull null
val fqNameAsString = fqName.asString()
val name = if (typeElement.text.startsWith(fqNameAsString)) fqNameAsString else fqName.shortName().asString()
val newQualifiedExpression = psiFactory.createExpressionByPattern("super<$name>.$0", selectorExpression, reformat = false)
val newContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context)
if (newQualifiedExpression.getResolvedCall(newContext)?.resultingDescriptor == null) return@mapNotNull null
if (newContext.diagnostics.noSuppression().forElement(newQualifiedExpression).isNotEmpty()) return@mapNotNull null
name
}
if (superTypesForSuperExpression.isEmpty()) return null
return SpecifySuperTypeFix(superExpression, superTypesForSuperExpression)
}
}
}
| apache-2.0 | f54847fad6d2c51b83bad7e81a2ab9e6 | 52.345794 | 158 | 0.71794 | 5.685259 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/RemoveExplicitTypeIntention.kt | 1 | 8025 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.analysis.api.components.DefaultTypeClassIds
import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.ExplicitApiMode
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.*
import org.jetbrains.kotlin.idea.codeinsight.utils.getClassId
import org.jetbrains.kotlin.idea.codeinsight.utils.isAnnotatedDeep
import org.jetbrains.kotlin.idea.codeinsight.utils.isSetterParameter
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class RemoveExplicitTypeIntention : AbstractKotlinApplicatorBasedIntention<KtDeclaration, KotlinApplicatorInput.Empty>(
KtDeclaration::class
) {
override fun getApplicator(): KotlinApplicator<KtDeclaration, KotlinApplicatorInput.Empty> = applicator {
familyAndActionName(KotlinBundle.lazyMessage("remove.explicit.type.specification"))
isApplicableByPsi { declaration ->
when {
declaration.typeReference == null || declaration.typeReference?.isAnnotatedDeep() == true -> false
declaration is KtParameter -> declaration.isLoopParameter || declaration.isSetterParameter
declaration is KtNamedFunction -> true
declaration is KtProperty || declaration is KtPropertyAccessor -> declaration.getInitializerOrGetterInitializer() != null
else -> false
}
}
applyTo { declaration, _ -> declaration.removeTypeReference() }
}
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtDeclaration> =
applicabilityRanges ranges@{ declaration ->
val typeReference = declaration.typeReference ?: return@ranges emptyList()
if (declaration is KtParameter && declaration.isSetterParameter) {
return@ranges listOf(typeReference.textRangeIn(declaration))
}
val typeReferenceRelativeEndOffset = typeReference.endOffset - declaration.startOffset
listOf(TextRange(0, typeReferenceRelativeEndOffset))
}
override fun getInputProvider(): KotlinApplicatorInputProvider<KtDeclaration, KotlinApplicatorInput.Empty> =
inputProvider { declaration ->
when {
declaration is KtParameter -> KotlinApplicatorInput.Empty
declaration is KtNamedFunction && declaration.hasBlockBody() ->
if (declaration.getReturnKtType().isUnit) KotlinApplicatorInput.Empty else null
declaration is KtCallableDeclaration && publicReturnTypeShouldBePresentInApiMode(declaration) -> null
explicitTypeMightBeNeededForCorrectTypeInference(declaration) -> null
else -> KotlinApplicatorInput.Empty
}
}
private val KtDeclaration.typeReference: KtTypeReference?
get() = when (this) {
is KtCallableDeclaration -> typeReference
is KtPropertyAccessor -> returnTypeReference
else -> null
}
private fun KtDeclaration.removeTypeReference() {
if (this is KtCallableDeclaration) {
typeReference = null
} else if (this is KtPropertyAccessor) {
val first = rightParenthesis?.nextSibling ?: return
val last = returnTypeReference ?: return
deleteChildRange(first, last)
}
}
private fun KtDeclaration.getInitializerOrGetterInitializer(): KtExpression? {
if (this is KtDeclarationWithInitializer && initializer != null) return initializer
return (this as? KtProperty)?.getter?.initializer
}
private val KtDeclaration.isVar: Boolean
get() {
val property = (this as? KtProperty) ?: (this as? KtPropertyAccessor)?.property
return property?.isVar == true
}
private fun KtAnalysisSession.publicReturnTypeShouldBePresentInApiMode(declaration: KtCallableDeclaration): Boolean {
if (declaration.languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode) == ExplicitApiMode.DISABLED) return false
if (declaration.containingClassOrObject?.isLocal == true) return false
if (declaration is KtFunction && declaration.isLocal) return false
if (declaration is KtProperty && declaration.isLocal) return false
val symbolWithVisibility = declaration.getSymbol() as? KtSymbolWithVisibility ?: return false
return isPublicApi(symbolWithVisibility)
}
private fun KtAnalysisSession.explicitTypeMightBeNeededForCorrectTypeInference(declaration: KtDeclaration): Boolean {
val initializer = declaration.getInitializerOrGetterInitializer() ?: return true
val initializerType = getInitializerTypeIfContextIndependent(initializer) ?: return true
val explicitType = declaration.getReturnKtType()
val typeCanBeRemoved = if (declaration.isVar) {
initializerType.isEqualTo(explicitType)
} else {
initializerType.isSubTypeOf(explicitType)
}
return !typeCanBeRemoved
}
private fun KtAnalysisSession.getInitializerTypeIfContextIndependent(initializer: KtExpression): KtType? {
return when (initializer) {
is KtStringTemplateExpression -> buildClassType(DefaultTypeClassIds.STRING)
is KtConstantExpression -> initializer.getClassId()?.let { buildClassType(it) }
is KtCallExpression -> {
val isNotContextFree = initializer.typeArgumentList == null && returnTypeOfCallDependsOnTypeParameters(initializer)
if (isNotContextFree) null else initializer.getKtType()
}
else -> {
// get type for expressions that a compiler views as constants, e.g. `1 + 2`
val evaluatedConstant = initializer.evaluate(KtConstantEvaluationMode.CONSTANT_EXPRESSION_EVALUATION)
if (evaluatedConstant != null) initializer.getKtType() else null
}
}
}
private fun KtAnalysisSession.returnTypeOfCallDependsOnTypeParameters(callExpression: KtCallExpression): Boolean {
val call = callExpression.resolveCall().singleFunctionCallOrNull() ?: return true
val callSymbol = call.partiallyAppliedSymbol.symbol
val typeParameters = callSymbol.typeParameters
val returnType = callSymbol.returnType
return typeParameters.any { typeReferencesTypeParameter(it, returnType) }
}
private fun KtAnalysisSession.typeReferencesTypeParameter(typeParameter: KtTypeParameterSymbol, type: KtType): Boolean {
return when (type) {
is KtTypeParameterType -> type.symbol == typeParameter
is KtNonErrorClassType -> type.typeArguments.mapNotNull { it.type }.any { typeReferencesTypeParameter(typeParameter, it) }
else -> false
}
}
} | apache-2.0 | feee74ab8312d94b51b275540191cd86 | 50.121019 | 137 | 0.726854 | 5.62763 | false | false | false | false |
MiJack/ImageDrive | app/src/main/java/cn/mijack/imagedrive/adapter/ImageAdapter.kt | 1 | 5419 | package cn.mijack.imagedrive.adapter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.util.Pair
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import cn.mijack.imagedrive.R
import cn.mijack.imagedrive.entity.Folder
import cn.mijack.imagedrive.entity.Image
import cn.mijack.imagedrive.entity.Media
import cn.mijack.imagedrive.ui.ImageDisplayActivity
import cn.mijack.imagedrive.ui.ImageFolderActivity
import cn.mijack.imagedrive.util.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import java.io.File
/**
* @author Mr.Yuan
* *
* @date 2017/4/17
*/
class ImageAdapter(context: Context, private var bigSpanCount: Int) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), View.OnClickListener {
private val glide: Glide = Glide.get(context)
private val requestManager: RequestManager = Glide.with(context)
private var data: List<Media>? = null
private var images: List<Image>? = null
var showType: Int = 0
set(showType) {
field = showType
this.notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
if (this.showType == SHOW_IMAGE_ONLY) {
return ITEM_IMAGE
}
val media = data!![position]
if (media is Folder) {
return ITEM_FOLDER
} else if (media is Image) {
return ITEM_IMAGE
}
throw IllegalArgumentException()
}
fun getSpanSize(position: Int): Int {
if (this.showType == SHOW_FOLDER) {
val media = data!![position]
return if (media is Folder) bigSpanCount else 1
}
return 2
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
var view: View? = null
val context = parent.context
val inflater = LayoutInflater.from(context)
when (viewType) {
ITEM_FOLDER -> view = inflater.inflate(R.layout.item_folder, parent, false)
ITEM_IMAGE -> view = inflater.inflate(R.layout.item_image, parent, false)
}
view!!.setOnClickListener(this)
return object : RecyclerView.ViewHolder(view!!) {
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val itemViewType = getItemViewType(position)
val root = holder.itemView
root.setTag(R.id.layout_position, position)
when (itemViewType) {
ITEM_FOLDER -> {
val folder = data!![position] as Folder
val folderName = root.findViewById<View>(R.id.folderName) as TextView
// TextView folderDesc = (TextView) root.findViewById(R.id.folderDesc);
folderName.text = File(folder.path).name
}
ITEM_IMAGE -> {
val image = (if (this.showType == SHOW_FOLDER) data else images)!![position] as Image
val imageView = root.findViewById<View>(R.id.imageView) as ImageView
requestManager.load(File(image.path)).placeholder(R.drawable.ic_empty_picture)
.into(imageView)
}
}// folderDesc.setText((folder.getCount() > 0 ? String.format("%d张图片", folder.getCount()) : ""));
}
override fun getItemCount(): Int {
return if (this.showType == SHOW_FOLDER) Utils.size(data) else Utils.size(images)
}
fun getBigSpanCount(): Int {
return bigSpanCount
}
fun setBigSpanCount(bigSpanCount: Int) {
this.bigSpanCount = bigSpanCount
this.notifyDataSetChanged()
}
fun setData(data: List<Media>?, images: List<Image>?) {
assert(data != null)
assert(images != null)
this.data = data
this.images = images
this.notifyDataSetChanged()
}
override fun onClick(v: View) {
val position = v.getTag(R.id.layout_position) as Int
val itemViewType = getItemViewType(position)
val data = if (this.showType == SHOW_FOLDER) this.data else this.images
Log.d(TAG, "itemViewType:" + if (itemViewType == ITEM_FOLDER) "ITEM_FOLDER" else "ITEM_IMAGE")
if (itemViewType == ITEM_FOLDER) {
val folder = data!![position] as Folder
val intent = Intent(v.context, ImageFolderActivity::class.java)
intent.putExtra(ImageFolderActivity.FOLDER_PATH, folder.path)
v.context.startActivity(intent)
} else if (itemViewType == ITEM_IMAGE) {
val image = data!![position] as Image
val context = v.context
val activityOptions = ActivityOptionsCompat
.makeSceneTransitionAnimation(context as Activity,
Pair(v.findViewById<View>(R.id.imageView), "image")
)
ImageDisplayActivity.showLocalImage(v.context, image, activityOptions.toBundle())
}
}
companion object {
val ITEM_FOLDER = 0
val ITEM_IMAGE = 1
val SHOW_FOLDER = 3
val SHOW_IMAGE_ONLY = 4
private val TAG = "ImageAdapter"
}
}
| apache-2.0 | 7316447a9feea161d0fc0bac73d994ab | 36.075342 | 141 | 0.633844 | 4.418776 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsConstant.kt | 1 | 2194 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.DEFAULT
import org.rust.lang.core.stubs.RsConstantStub
enum class RsConstantKind {
STATIC,
MUT_STATIC,
CONST
}
val RsConstant.kind: RsConstantKind get() = when {
mut != null -> RsConstantKind.MUT_STATIC
const != null -> RsConstantKind.CONST
else -> RsConstantKind.STATIC
}
sealed class RsConstantOwner {
object Free : RsConstantOwner()
object Foreign : RsConstantOwner()
class Trait(val trait: RsTraitItem) : RsConstantOwner()
class Impl(val impl: RsImplItem) : RsConstantOwner()
}
val RsConstant.owner: RsConstantOwner get() {
return when (parent) {
is RsItemsOwner -> RsConstantOwner.Free
is RsForeignModItem -> RsConstantOwner.Foreign
is RsMembers -> {
val grandDad = parent.parent
when (grandDad) {
is RsTraitItem -> RsConstantOwner.Trait(grandDad)
is RsImplItem -> RsConstantOwner.Impl(grandDad)
else -> error("unreachable")
}
}
else -> error("Unexpected constant parent: $parent")
}
}
val RsConstant.default: PsiElement?
get() = node.findChildByType(DEFAULT)?.psi
val RsConstant.isMut: Boolean
get() = mut != null
abstract class RsConstantImplMixin : RsStubbedNamedElementImpl<RsConstantStub>, RsConstant {
constructor(node: ASTNode) : super(node)
constructor(stub: RsConstantStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int) = iconWithVisibility(flags, when (kind) {
RsConstantKind.CONST -> RsIcons.CONSTANT
RsConstantKind.MUT_STATIC -> RsIcons.MUT_STATIC
RsConstantKind.STATIC -> RsIcons.STATIC
})
override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub)
override val isAbstract: Boolean get() = expr == null
}
| mit | b5a0b7ea55bd057dea8f0130c5232900 | 29.901408 | 95 | 0.690975 | 4.235521 | false | false | false | false |
ruinkami/KotlinDemo | app/src/main/java/app/ruinkami/kotlindemo/kotlin/KInfoActivity.kt | 1 | 757 | package app.ruinkami.kotlindemo.kotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import org.jetbrains.anko.setContentView
class KInfoActivity : AppCompatActivity() {
var stuName: String = ""
var stuAge: Int = 0
var stuHobby: String = ""
var stuUniversity: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initData()
InfoUI().setContentView(this@KInfoActivity)
}
private fun initData() {
stuName = intent.getStringExtra("stu_name")
stuAge = intent.getIntExtra("stu_age", 20)
stuHobby = intent.getStringExtra("stu_hobby")
stuUniversity = intent.getStringExtra("stu_university")
}
}
| apache-2.0 | 02708e6a3ed0bfe4d060e98ee0468548 | 26.035714 | 63 | 0.686922 | 3.963351 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/recent/history/HistoryController.kt | 1 | 8365 | package eu.kanade.tachiyomi.ui.recent.history
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dev.chrisbanes.insetter.applyInsetter
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.backup.BackupRestoreService
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.History
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.databinding.HistoryControllerBinding
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.RootController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.browse.source.browse.ProgressItem
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.util.view.onAnimationsFinished
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import logcat.LogPriority
import reactivecircus.flowbinding.appcompat.queryTextChanges
import uy.kohesive.injekt.injectLazy
/**
* Fragment that shows recently read manga.
*/
class HistoryController :
NucleusController<HistoryControllerBinding, HistoryPresenter>(),
RootController,
FlexibleAdapter.OnUpdateListener,
FlexibleAdapter.EndlessScrollListener,
HistoryAdapter.OnRemoveClickListener,
HistoryAdapter.OnResumeClickListener,
HistoryAdapter.OnItemClickListener,
RemoveHistoryDialog.Listener {
private val db: DatabaseHelper by injectLazy()
/**
* Adapter containing the recent manga.
*/
var adapter: HistoryAdapter? = null
private set
/**
* Endless loading item.
*/
private var progressItem: ProgressItem? = null
/**
* Search query.
*/
private var query = ""
override fun getTitle(): String? {
return resources?.getString(R.string.label_recent_manga)
}
override fun createPresenter(): HistoryPresenter {
return HistoryPresenter()
}
override fun createBinding(inflater: LayoutInflater) = HistoryControllerBinding.inflate(inflater)
override fun onViewCreated(view: View) {
super.onViewCreated(view)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
// Initialize adapter
binding.recycler.layoutManager = LinearLayoutManager(view.context)
adapter = HistoryAdapter(this@HistoryController)
binding.recycler.setHasFixedSize(true)
binding.recycler.adapter = adapter
adapter?.fastScroller = binding.fastScroller
}
override fun onDestroyView(view: View) {
adapter = null
super.onDestroyView(view)
}
/**
* Populate adapter with chapters
*
* @param mangaHistory list of manga history
*/
fun onNextManga(mangaHistory: List<HistoryItem>, cleanBatch: Boolean = false) {
if (adapter?.itemCount ?: 0 == 0) {
resetProgressItem()
}
if (cleanBatch) {
adapter?.updateDataSet(mangaHistory)
} else {
adapter?.onLoadMoreComplete(mangaHistory)
}
binding.recycler.onAnimationsFinished {
(activity as? MainActivity)?.ready = true
}
}
/**
* Safely error if next page load fails
*/
fun onAddPageError(error: Throwable) {
adapter?.onLoadMoreComplete(null)
adapter?.endlessTargetCount = 1
logcat(LogPriority.ERROR, error)
}
override fun onUpdateEmptyView(size: Int) {
if (size > 0) {
binding.emptyView.hide()
} else {
binding.emptyView.show(R.string.information_no_recent_manga)
}
}
/**
* Sets a new progress item and reenables the scroll listener.
*/
private fun resetProgressItem() {
progressItem = ProgressItem()
adapter?.endlessTargetCount = 0
adapter?.setEndlessScrollListener(this, progressItem!!)
}
override fun onLoadMore(lastPosition: Int, currentPage: Int) {
val view = view ?: return
if (BackupRestoreService.isRunning(view.context.applicationContext)) {
onAddPageError(Throwable())
return
}
val adapter = adapter ?: return
presenter.requestNext(adapter.itemCount, query)
}
override fun noMoreLoad(newItemsSize: Int) {}
override fun onResumeClick(position: Int) {
val activity = activity ?: return
val (manga, chapter, _) = (adapter?.getItem(position) as? HistoryItem)?.mch ?: return
val nextChapter = presenter.getNextChapter(chapter, manga)
if (nextChapter != null) {
val intent = ReaderActivity.newIntent(activity, manga, nextChapter)
startActivity(intent)
} else {
activity.toast(R.string.no_next_chapter)
}
}
override fun onRemoveClick(position: Int) {
val (manga, _, history) = (adapter?.getItem(position) as? HistoryItem)?.mch ?: return
RemoveHistoryDialog(this, manga, history).showDialog(router)
}
override fun onItemClick(position: Int) {
val manga = (adapter?.getItem(position) as? HistoryItem)?.mch?.manga ?: return
router.pushController(MangaController(manga).withFadeTransaction())
}
override fun removeHistory(manga: Manga, history: History, all: Boolean) {
if (all) {
// Reset last read of chapter to 0L
presenter.removeAllFromHistory(manga.id!!)
} else {
// Remove all chapters belonging to manga from library
presenter.removeFromHistory(history)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.history, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
searchView.maxWidth = Int.MAX_VALUE
if (query.isNotEmpty()) {
searchItem.expandActionView()
searchView.setQuery(query, true)
searchView.clearFocus()
}
searchView.queryTextChanges()
.drop(1) // Drop first event after subscribed
.filter { router.backstack.lastOrNull()?.controller == this }
.onEach {
query = it.toString()
presenter.updateList(query)
}
.launchIn(viewScope)
// Fixes problem with the overflow icon showing up in lieu of search
searchItem.fixExpand(
onExpand = { invalidateMenuOnExpand() }
)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_clear_history -> {
val ctrl = ClearHistoryDialogController()
ctrl.targetController = this@HistoryController
ctrl.showDialog(router)
}
}
return super.onOptionsItemSelected(item)
}
class ClearHistoryDialogController : DialogController() {
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(activity!!)
.setMessage(R.string.clear_history_confirmation)
.setPositiveButton(android.R.string.ok) { _, _ ->
(targetController as? HistoryController)?.clearHistory()
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
}
private fun clearHistory() {
db.deleteHistory().executeAsBlocking()
activity?.toast(R.string.clear_history_completed)
}
}
| apache-2.0 | ac78fd940ccef04c08c02720c01a8e93 | 33.004065 | 101 | 0.67113 | 4.82689 | false | false | false | false |
airbnb/lottie-android | sample-compose/src/main/java/com/airbnb/lottie/sample/compose/lottiefiles/LottieFilesSearchPage.kt | 1 | 7290 | package com.airbnb.lottie.sample.compose.lottiefiles
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Repeat
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.airbnb.lottie.sample.compose.R
import com.airbnb.lottie.sample.compose.Route
import com.airbnb.lottie.sample.compose.api.AnimationDataV2
import com.airbnb.lottie.sample.compose.api.LottieFilesApi
import com.airbnb.lottie.sample.compose.composables.AnimationRow
import com.airbnb.lottie.sample.compose.dagger.AssistedViewModelFactory
import com.airbnb.lottie.sample.compose.dagger.daggerMavericksViewModelFactory
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.MavericksViewModel
import com.airbnb.mvrx.MavericksViewModelFactory
import com.airbnb.mvrx.compose.collectAsState
import com.airbnb.mvrx.compose.mavericksViewModel
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
data class LottieFilesSearchState(
val query: String = "",
val results: List<AnimationDataV2> = emptyList(),
val currentPage: Int = 1,
val lastPage: Int = 0,
val fetchException: Boolean = false,
) : MavericksState
class LottieFilesSearchViewModel @AssistedInject constructor(
@Assisted initialState: LottieFilesSearchState,
private val api: LottieFilesApi,
) : MavericksViewModel<LottieFilesSearchState>(initialState) {
private var fetchJob: Job? = null
init {
onEach(LottieFilesSearchState::query) { query ->
fetchJob?.cancel()
if (query.isBlank()) {
setState { copy(results = emptyList(), currentPage = 1, lastPage = 1, fetchException = false) }
} else {
fetchJob = viewModelScope.launch {
val results = try {
api.search(query, 1)
} catch (e: Exception) {
setState { copy(fetchException = true) }
return@launch
}
setState {
copy(
results = results.data.map(::AnimationDataV2),
currentPage = results.current_page,
lastPage = results.last_page,
fetchException = false
)
}
}
}
}
}
fun fetchNextPage() = withState { state ->
fetchJob?.cancel()
if (state.currentPage >= state.lastPage) return@withState
fetchJob = viewModelScope.launch {
val response = try {
api.search(state.query, state.currentPage + 1)
} catch (e: Exception) {
setState { copy(fetchException = true) }
return@launch
}
setState {
copy(
results = results + response.data.map(::AnimationDataV2),
currentPage = response.current_page,
fetchException = false
)
}
}
}
fun setQuery(query: String) = setState { copy(query = query, currentPage = 1, results = emptyList()) }
@AssistedFactory
interface Factory : AssistedViewModelFactory<LottieFilesSearchViewModel, LottieFilesSearchState> {
override fun create(initialState: LottieFilesSearchState): LottieFilesSearchViewModel
}
companion object : MavericksViewModelFactory<LottieFilesSearchViewModel, LottieFilesSearchState> by daggerMavericksViewModelFactory()
}
@Composable
fun LottieFilesSearchPage(navController: NavController) {
val viewModel: LottieFilesSearchViewModel = mavericksViewModel()
val state by viewModel.collectAsState()
LottieFilesSearchPage(
state,
viewModel::setQuery,
viewModel::fetchNextPage,
onAnimationClicked = { data ->
navController.navigate(Route.Player.forUrl(data.file, backgroundColor = data.bg_color))
}
)
}
@Composable
fun LottieFilesSearchPage(
state: LottieFilesSearchState,
onQueryChanged: (String) -> Unit,
fetchNextPage: () -> Unit,
onAnimationClicked: (AnimationDataV2) -> Unit,
modifier: Modifier = Modifier,
) {
Box {
Column(
modifier = Modifier.then(modifier)
) {
OutlinedTextField(
value = state.query,
onValueChange = onQueryChanged,
label = { Text(stringResource(R.string.query)) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
singleLine = true
)
LazyColumn(
modifier = Modifier.weight(1f)
) {
itemsIndexed(state.results) { index, result ->
if (index == state.results.size - 1) {
SideEffect(fetchNextPage)
}
AnimationRow(
title = result.title,
previewUrl = result.preview_url ?: "",
previewBackgroundColor = result.bgColor,
onClick = { onAnimationClicked(result) }
)
}
}
}
if (state.fetchException) {
FloatingActionButton(
onClick = fetchNextPage,
content = {
Icon(
imageVector = Icons.Filled.Repeat,
tint = Color.White,
contentDescription = null
)
},
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 24.dp)
)
}
}
}
@Preview
@Composable
fun PreviewSearchPage() {
val data = AnimationDataV2(0, null, "https://assets9.lottiefiles.com/render/k1821vf5.png", "Loading", "")
val state = LottieFilesSearchState(
results = listOf(data, data, data),
fetchException = true
)
Surface(color = Color.White) {
LottieFilesSearchPage(
state = state,
onQueryChanged = {},
fetchNextPage = {},
onAnimationClicked = {}
)
}
} | apache-2.0 | 5e31441a0cab32f0ea6b667c48b0aa96 | 35.638191 | 137 | 0.616598 | 5.03801 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/controls/ScreenConfig.kt | 2 | 5748 | package graphics.scenery.controls
import org.joml.Matrix4f
import org.joml.Vector3f
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.KotlinModule
import graphics.scenery.utils.JsonDeserialisers
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.extensions.minus
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
/**
* Screen config class, for configuration and use of projection screen geometry and transformations.
*
* @author Ulrik Günther <[email protected]>
*/
class ScreenConfig {
/**
* Represents a screen configuration, potentially with multiple [screens] with a
* shared size of [screenWidth] x [screenHeight]. A [name] and [description] can be given.
*/
data class Config(
var name: String,
var description: String?,
var screenWidth: Int = 1920,
var screenHeight: Int = 1200,
var screens: Map<String, SingleScreenConfig>
)
/** Represents a single screen in the configuration */
class SingleScreenConfig(
/** How to match this screen (e.g. by host or IP) */
var match: ScreenMatcher,
/** Lower left screen corner, in meters */
@JsonDeserialize(using = JsonDeserialisers.VectorDeserializer::class)
var lowerLeft: Vector3f = Vector3f(0.0f, 0.0f, 0.0f),
/** Lower right screen corner, in meters */
@JsonDeserialize(using = JsonDeserialisers.VectorDeserializer::class)
var lowerRight: Vector3f = Vector3f(0.0f, 0.0f, 0.0f),
/** Upper left screen corner, in meters */
@JsonDeserialize(using = JsonDeserialisers.VectorDeserializer::class)
var upperLeft: Vector3f = Vector3f(0.0f, 0.0f, 0.0f)
) {
private var screenTransform: Matrix4f
/** Calculated width of the screen, in meters */
var width = 0.0f
private set
/** Calculated height of the screen, in meters */
var height = 0.0f
private set
init {
var vr = lowerRight - lowerLeft
val vu = upperLeft - lowerLeft
val vn = Vector3f(vr).cross(vu)
width = vr.length()
height = vu.length()
vu.normalize()
vn.normalize()
vr = Vector3f(vu).cross(vn).normalize()
screenTransform = Matrix4f(
vr.x(), vr.y(), vr.z(), 0.0f,
vu.x(), vu.y(), vu.z(), 0.0f,
vn.x(), vn.y(), vn.z(), 0.0f,
lowerLeft.x(), lowerLeft.y(), lowerLeft.z(), 1.0f)
logger.debug("Screen {}: {} {} {} {}x{}", match, lowerLeft, lowerRight, upperLeft, width, height)
screenTransform.invert()
}
/** Returns the frustum transform for this screen */
fun getTransform(): Matrix4f = screenTransform
}
/**
* Screen matcher class with [type] and [value].
*/
data class ScreenMatcher(
var type: ScreenMatcherType,
var value: String
)
/** A screen matcher can be based on a system property or a hostname currently. */
enum class ScreenMatcherType { Property, Hostname }
/**
* ScreenConfig companion class for static functions
*/
companion object {
private val logger by LazyLogger()
/**
* Matches a single screen to the [config] given.
*
* Returns a [SingleScreenConfig] if the screen could be matched, and null otherwise.
*/
@JvmStatic fun getScreen(config: Config): SingleScreenConfig? {
for ((_, screen) in config.screens) {
if (screen.match.type == ScreenMatcherType.Hostname) {
if (getHostname().lowercase() == screen.match.value) {
return screen
}
}
if (screen.match.type == ScreenMatcherType.Property) {
if (System.getProperty("scenery.ScreenName") == screen.match.value) {
return screen
}
}
}
logger.warn("No matching screen found.")
return null
}
private fun getHostname(): String {
val proc = Runtime.getRuntime().exec("hostname")
proc.inputStream.use { stream -> Scanner(stream).useDelimiter("\\A").use { s -> return if (s.hasNext()) s.next() else "" } }
}
/**
* Loads a [ScreenConfig.Config] from a [path] and returns it.
*
* If [path] cannot be found, a default configuration included with scenery will be loaded.
*/
@JvmStatic fun loadFromFile(path: String): ScreenConfig.Config {
val mapper = ObjectMapper(YAMLFactory())
mapper.registerModule(KotlinModule())
var stream = ScreenConfig::class.java.getResourceAsStream(path)
if (stream == null) {
val p = Paths.get(path)
return if (!Files.exists(p)) {
stream = ScreenConfig::class.java.getResourceAsStream("CAVEExample.yml")
logger.warn("Screen configuration not found at $path, returning default configuration.")
mapper.readValue(stream, ScreenConfig.Config::class.java)
} else {
Files.newBufferedReader(p).use {
mapper.readValue(it, ScreenConfig.Config::class.java)
}
}
}
return mapper.readValue(stream, ScreenConfig.Config::class.java)
}
}
}
| lgpl-3.0 | 7f15ebd8a63cd1d195cb388f72bb35ee | 33.620482 | 136 | 0.586045 | 4.475857 | false | true | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsCardsFragment.kt | 1 | 20561 | package org.wikipedia.suggestededits
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.drawable.Animatable
import android.os.Bundle
import android.view.*
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants.*
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.SuggestedEditsFeedFunnel
import org.wikipedia.analytics.SuggestedEditsFunnel
import org.wikipedia.databinding.FragmentSuggestedEditsCardsBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.dataclient.mwapi.SiteMatrix
import org.wikipedia.descriptions.DescriptionEditActivity
import org.wikipedia.descriptions.DescriptionEditActivity.Action.*
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.suggestededits.SuggestionsActivity.Companion.EXTRA_SOURCE_ADDED_CONTRIBUTION
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.PositionAwareFragmentStateAdapter
class SuggestedEditsCardsFragment : Fragment(), SuggestedEditsItemFragment.Callback {
private var _binding: FragmentSuggestedEditsCardsBinding? = null
private val binding get() = _binding!!
private val viewPagerListener = ViewPagerListener()
private val disposables = CompositeDisposable()
private val app = WikipediaApp.getInstance()
private var siteMatrix: SiteMatrix? = null
private var languageList: MutableList<String> = mutableListOf()
private var swappingLanguageSpinners: Boolean = false
private var resettingViewPager: Boolean = false
private var funnel: SuggestedEditsFeedFunnel? = null
var langFromCode: String = app.language().appLanguageCode
var langToCode: String = if (app.language().appLanguageCodes.size == 1) "" else app.language().appLanguageCodes[1]
var action: DescriptionEditActivity.Action = ADD_DESCRIPTION
private val topTitle: PageTitle?
get() {
val f = topChild()
return if (action == ADD_DESCRIPTION || action == ADD_CAPTION) {
f?.sourceSummaryForEdit?.pageTitle?.description = f?.addedContribution
f?.sourceSummaryForEdit?.pageTitle
} else {
f?.targetSummaryForEdit?.pageTitle?.description = f?.addedContribution
f?.targetSummaryForEdit?.pageTitle
}
}
private fun topBaseChild(): SuggestedEditsItemFragment? {
return (binding.cardsViewPager.adapter as ViewPagerAdapter?)?.getFragmentAt(binding.cardsViewPager.currentItem) as SuggestedEditsItemFragment?
}
private fun topChild(): SuggestedEditsCardsItemFragment? {
return (binding.cardsViewPager.adapter as ViewPagerAdapter?)?.getFragmentAt(binding.cardsViewPager.currentItem) as SuggestedEditsCardsItemFragment?
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
action = arguments?.getSerializable(INTENT_EXTRA_ACTION) as DescriptionEditActivity.Action
funnel = SuggestedEditsFeedFunnel(action, requireArguments().getSerializable(INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource)
// Reset image recommendations sequence to the last successful one
Prefs.setImageRecsItemSequence(Prefs.getImageRecsItemSequenceSuccess())
// Record the first impression, since the ViewPager doesn't send an event for the first topmost item.
SuggestedEditsFunnel.get()!!.impression(action)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentSuggestedEditsCardsBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setInitialUiState()
binding.cardsViewPager.offscreenPageLimit = 2
binding.cardsViewPager.registerOnPageChangeCallback(viewPagerListener) // addOnPageChangeListener(viewPagerListener)
resetViewPagerItemAdapter()
funnel?.start()
if (action == IMAGE_RECOMMENDATION) {
binding.cardsViewPager.isUserInputEnabled = false
}
if (binding.wikiLanguageDropdownContainer.visibility == VISIBLE) {
if (languageList.isEmpty()) {
// Fragment is created for the first time.
requestLanguagesAndBuildSpinner()
} else {
// Fragment already exists, so just update the UI.
initLanguageSpinners()
}
binding.wikiFromLanguageSpinner.onItemSelectedListener = OnFromSpinnerItemSelectedListener()
binding.wikiToLanguageSpinner.onItemSelectedListener = OnToSpinnerItemSelectedListener()
binding.arrow.setOnClickListener { binding.wikiFromLanguageSpinner.setSelection(binding.wikiToLanguageSpinner.selectedItemPosition) }
}
binding.backButton.setOnClickListener { previousPage() }
binding.nextButton.setOnClickListener {
if (binding.nextButton.drawable is Animatable) {
(binding.nextButton.drawable as Animatable).start()
}
nextPage(null)
}
updateBackButton(0)
binding.addContributionButton.setOnClickListener { onSelectPage() }
updateActionButton()
maybeShowOnboarding()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(action == ADD_IMAGE_TAGS || action == IMAGE_RECOMMENDATION)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
if (action == ADD_IMAGE_TAGS || action == IMAGE_RECOMMENDATION) {
inflater.inflate(R.menu.menu_suggested_edits, menu)
ResourceUtil.setMenuItemTint(requireContext(), menu.findItem(R.id.menu_help), R.attr.colorAccent)
if (action == IMAGE_RECOMMENDATION) {
requireView().post {
if (isAdded) {
requireActivity().window.decorView.findViewById<TextView>(R.id.menu_help).let {
TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(it, 0, 0, R.drawable.ic_open_in_new_black_24px, 0)
TextViewCompat.setCompoundDrawableTintList(it, ColorStateList.valueOf(ResourceUtil.getThemedColor(requireContext(), R.attr.secondary_text_color)))
it.letterSpacing = binding.addContributionButton.letterSpacing
it.compoundDrawablePadding = DimenUtil.roundedDpToPx(4f)
it.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.secondary_text_color))
it.text = getString(R.string.image_recommendations_faq)
}
}
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_help -> {
if (action == ADD_IMAGE_TAGS) {
FeedbackUtil.showAndroidAppEditingFAQ(requireContext(), R.string.suggested_edits_image_tags_help_url)
} else if (action == IMAGE_RECOMMENDATION) {
FeedbackUtil.showAndroidAppEditingFAQ(requireContext(), R.string.suggested_edits_image_recs_help_url)
} else {
FeedbackUtil.showAndroidAppEditingFAQ(requireContext())
}
val child = topBaseChild()
if (child != null && child is ImageRecsFragment) {
child.onInfoClicked()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun maybeShowOnboarding() {
if (action == ADD_IMAGE_TAGS && Prefs.shouldShowImageTagsOnboarding()) {
Prefs.setShowImageTagsOnboarding(false)
startActivity(SuggestedEditsImageTagsOnboardingActivity.newIntent(requireContext()))
}
}
private fun updateBackButton(pagerPosition: Int) {
binding.backButton.isClickable = pagerPosition != 0
binding.backButton.alpha = if (pagerPosition == 0) 0.31f else 1f
}
override fun getLangCode(): String {
return langFromCode
}
override fun getSinglePage(): MwQueryPage? {
return null
}
override fun updateActionButton() {
val child = topBaseChild()
var isAddedContributionEmpty = true
if (child != null) {
if (child is SuggestedEditsCardsItemFragment) {
isAddedContributionEmpty = child.addedContribution.isEmpty()
if (!isAddedContributionEmpty) child.showAddedContributionView(child.addedContribution)
}
binding.addContributionButton.setIconResource((if (isAddedContributionEmpty) R.drawable.ic_add_gray_white_24dp else R.drawable.ic_mode_edit_white_24dp))
binding.addContributionButton.isEnabled = child.publishEnabled()
binding.addContributionButton.alpha = if (child.publishEnabled()) 1f else 0.5f
}
if (action == IMAGE_RECOMMENDATION) {
binding.bottomButtonContainer.visibility = GONE
} else {
binding.bottomButtonContainer.visibility = VISIBLE
}
if (action == ADD_IMAGE_TAGS) {
if (binding.addContributionButton.tag == "landscape") {
// implying landscape mode, where addContributionText doesn't exist.
binding.addContributionButton.text = null
binding.addContributionButton.setIconResource(R.drawable.ic_check_black_24dp)
} else {
binding.addContributionButton.text = getString(R.string.description_edit_save)
binding.addContributionButton.icon = null
}
} else if (action == TRANSLATE_DESCRIPTION || action == TRANSLATE_CAPTION) {
binding.addContributionButton.text = getString(if (isAddedContributionEmpty) R.string.suggested_edits_add_translation_button else R.string.suggested_edits_edit_translation_button)
} else if (binding.addContributionButton.tag == "portrait") {
if (action == ADD_CAPTION) {
binding.addContributionButton.text = getString(if (isAddedContributionEmpty) R.string.suggested_edits_add_caption_button else R.string.suggested_edits_edit_caption_button)
} else {
binding.addContributionButton.text = getString(if (isAddedContributionEmpty) R.string.suggested_edits_add_description_button else R.string.suggested_edits_edit_description_button)
}
}
}
override fun onDestroyView() {
funnel?.stop()
disposables.clear()
binding.cardsViewPager.unregisterOnPageChangeCallback(viewPagerListener)
binding.cardsViewPager.adapter = null
_binding = null
super.onDestroyView()
}
override fun onPause() {
super.onPause()
SuggestedEditsFunnel.get()!!.pause()
}
override fun onResume() {
super.onResume()
SuggestedEditsFunnel.get()!!.resume()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ACTIVITY_REQUEST_DESCRIPTION_EDIT && resultCode == RESULT_OK) {
logSuccess()
topChild()?.showAddedContributionView(data?.getStringExtra(EXTRA_SOURCE_ADDED_CONTRIBUTION))
FeedbackUtil.showMessage(this,
when (action) {
ADD_CAPTION -> getString(R.string.description_edit_success_saved_image_caption_snackbar)
TRANSLATE_CAPTION -> getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(topChild()!!.targetSummaryForEdit!!.lang))
TRANSLATE_DESCRIPTION -> getString(R.string.description_edit_success_saved_in_lang_snackbar, app.language().getAppLanguageLocalizedName(topChild()!!.targetSummaryForEdit!!.lang))
else -> getString(R.string.description_edit_success_saved_snackbar)
}
)
nextPage(null)
}
}
private fun previousPage() {
viewPagerListener.setNextPageSelectedAutomatic()
if (binding.cardsViewPager.currentItem > 0) {
binding.cardsViewPager.setCurrentItem(binding.cardsViewPager.currentItem - 1, true)
}
updateActionButton()
}
override fun nextPage(sourceFragment: Fragment?) {
if (sourceFragment == topBaseChild() || sourceFragment == null) {
viewPagerListener.setNextPageSelectedAutomatic()
binding.cardsViewPager.setCurrentItem(binding.cardsViewPager.currentItem + 1, true)
updateActionButton()
}
}
override fun logSuccess() {
funnel?.editSuccess()
}
fun onSelectPage() {
if (action == ADD_IMAGE_TAGS && topBaseChild() != null) {
topBaseChild()!!.publish()
} else if (action == IMAGE_RECOMMENDATION && topBaseChild() != null) {
topBaseChild()!!.publish()
} else if (topTitle != null) {
startActivityForResult(DescriptionEditActivity.newIntent(requireContext(), topTitle!!, null, topChild()!!.sourceSummaryForEdit, topChild()!!.targetSummaryForEdit,
action, InvokeSource.SUGGESTED_EDITS), ACTIVITY_REQUEST_DESCRIPTION_EDIT)
}
}
private fun requestLanguagesAndBuildSpinner() {
disposables.add(ServiceFactory.get(app.wikiSite).siteMatrix
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { siteMatrix = it; }
.doAfterTerminate { initLanguageSpinners() }
.subscribe({
app.language().appLanguageCodes.forEach {
languageList.add(getLanguageLocalName(it))
}
}, { L.e(it) }))
}
private fun getLanguageLocalName(code: String): String {
if (siteMatrix == null) {
return app.language().getAppLanguageLocalizedName(code)!!
}
var name: String? = null
SiteMatrix.getSites(siteMatrix!!).forEach {
if (code == it.code()) {
name = it.name()
return@forEach
}
}
if (name.isNullOrEmpty()) {
name = app.language().getAppLanguageLocalizedName(code)
}
return name ?: code
}
private fun resetViewPagerItemAdapter() {
if (!resettingViewPager) {
resettingViewPager = true
val postDelay: Long = 250
binding.cardsViewPager.postDelayed({
if (isAdded) {
binding.cardsViewPager.adapter = ViewPagerAdapter(this)
resettingViewPager = false
}
}, postDelay)
}
}
private fun setInitialUiState() {
binding.wikiLanguageDropdownContainer.visibility = if (app.language().appLanguageCodes.size > 1 &&
(action == TRANSLATE_DESCRIPTION || action == TRANSLATE_CAPTION)) VISIBLE else GONE
}
private fun swapLanguageSpinnerSelection(isFromLang: Boolean) {
if (!swappingLanguageSpinners) {
swappingLanguageSpinners = true
val preLangPosition = app.language().appLanguageCodes.indexOf(if (isFromLang) langFromCode else langToCode)
if (isFromLang) {
binding.wikiToLanguageSpinner.setSelection(preLangPosition)
} else {
binding.wikiFromLanguageSpinner.setSelection(preLangPosition)
}
swappingLanguageSpinners = false
}
}
private fun initLanguageSpinners() {
binding.wikiFromLanguageSpinner.adapter = ArrayAdapter(requireContext(), R.layout.item_language_spinner, languageList)
binding.wikiToLanguageSpinner.adapter = ArrayAdapter(requireContext(), R.layout.item_language_spinner, languageList)
binding.wikiToLanguageSpinner.setSelection(app.language().appLanguageCodes.indexOf(langToCode))
}
private inner class OnFromSpinnerItemSelectedListener : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (langToCode == app.language().appLanguageCodes[position]) {
swapLanguageSpinnerSelection(true)
}
if (!swappingLanguageSpinners && langFromCode != app.language().appLanguageCodes[position]) {
langFromCode = app.language().appLanguageCodes[position]
resetViewPagerItemAdapter()
updateBackButton(0)
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
private inner class OnToSpinnerItemSelectedListener : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (langFromCode == app.language().appLanguageCodes[position]) {
swapLanguageSpinnerSelection(false)
}
if (!swappingLanguageSpinners && langToCode != app.language().appLanguageCodes[position]) {
langToCode = app.language().appLanguageCodes[position]
resetViewPagerItemAdapter()
updateBackButton(0)
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
private inner class ViewPagerAdapter constructor(fragment: Fragment) : PositionAwareFragmentStateAdapter(fragment) {
override fun getItemCount(): Int {
return Integer.MAX_VALUE
}
override fun createFragment(position: Int): Fragment {
return when (action) {
ADD_IMAGE_TAGS -> {
SuggestedEditsImageTagsFragment.newInstance()
}
IMAGE_RECOMMENDATION -> {
ImageRecsFragment.newInstance()
}
else -> {
SuggestedEditsCardsItemFragment.newInstance()
}
}
}
}
private inner class ViewPagerListener : ViewPager2.OnPageChangeCallback() {
private var prevPosition: Int = 0
private var nextPageSelectedAutomatic: Boolean = false
fun setNextPageSelectedAutomatic() {
nextPageSelectedAutomatic = true
}
override fun onPageSelected(position: Int) {
updateBackButton(position)
updateActionButton()
SuggestedEditsFunnel.get()!!.impression(action)
nextPageSelectedAutomatic = false
prevPosition = position
val storedOffScreenPagesCount = binding.cardsViewPager.offscreenPageLimit * 2 + 1
if (position >= storedOffScreenPagesCount) {
(binding.cardsViewPager.adapter as ViewPagerAdapter).removeFragmentAt(position - storedOffScreenPagesCount)
}
}
}
companion object {
fun newInstance(action: DescriptionEditActivity.Action, invokeSource: InvokeSource): SuggestedEditsCardsFragment {
val addTitleDescriptionsFragment = SuggestedEditsCardsFragment()
addTitleDescriptionsFragment.arguments = bundleOf(INTENT_EXTRA_ACTION to action,
INTENT_EXTRA_INVOKE_SOURCE to invokeSource)
return addTitleDescriptionsFragment
}
}
}
| apache-2.0 | cac3ea8e09ec7c5c5702863ecec124a1 | 43.504329 | 212 | 0.659501 | 5.27611 | false | false | false | false |
BenjaminEarley/GithubApiDemo | app/src/main/java/com/benjaminearley/githubapi/functional/algebraicDataTypes/DisjunctUnions.kt | 1 | 2985 | package com.benjaminearley.githubapi.functional.algebraicDataTypes
sealed class Sum3<out A : Any, out B : Any, out C : Any> {
abstract fun <D> with(a: (A) -> D, b: (B) -> D, c: (C) -> D): D
}
class Sum3A<out A : Any, out B : Any, out C : Any>(val value: A) : Sum3<A, B, C>() {
override fun <D> with(a: (A) -> D, b: (B) -> D, c: (C) -> D): D = a(value)
}
class Sum3B<out A : Any, out B : Any, out C : Any>(val value: B) : Sum3<A, B, C>() {
override fun <D> with(a: (A) -> D, b: (B) -> D, c: (C) -> D): D = b(value)
}
class Sum3C<out A : Any, out B : Any, out C : Any>(val value: C) : Sum3<A, B, C>() {
override fun <D> with(a: (A) -> D, b: (B) -> D, c: (C) -> D): D = c(value)
}
sealed class Sum4<out A : Any, out B : Any, out C : Any, out D : Any> {
abstract fun <E> with(a: (A) -> E, b: (B) -> E, c: (C) -> E, d: (D) -> E): E
}
class Sum4A<out A : Any, out B : Any, out C : Any, out D : Any>(val value: A) : Sum4<A, B, C, D>() {
override fun <E> with(a: (A) -> E, b: (B) -> E, c: (C) -> E, d: (D) -> E): E = a(value)
}
class Sum4B<out A : Any, out B : Any, out C : Any, out D : Any>(val value: B) : Sum4<A, B, C, D>() {
override fun <E> with(a: (A) -> E, b: (B) -> E, c: (C) -> E, d: (D) -> E): E = b(value)
}
class Sum4C<out A : Any, out B : Any, out C : Any, out D : Any>(val value: C) : Sum4<A, B, C, D>() {
override fun <E> with(a: (A) -> E, b: (B) -> E, c: (C) -> E, d: (D) -> E): E = c(value)
}
class Sum4D<out A : Any, out B : Any, out C : Any, out D : Any>(val value: D) : Sum4<A, B, C, D>() {
override fun <E> with(a: (A) -> E, b: (B) -> E, c: (C) -> E, d: (D) -> E): E = d(value)
}
sealed class Sum5<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any> {
abstract fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F
}
class Sum5A<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any>(private val value: A) : Sum5<A, B, C, D, E>() {
override fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F = a(value)
}
class Sum5B<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any>(private val value: B) : Sum5<A, B, C, D, E>() {
override fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F = b(value)
}
class Sum5C<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any>(private val value: C) : Sum5<A, B, C, D, E>() {
override fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F = c(value)
}
class Sum5D<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any>(private val value: D) : Sum5<A, B, C, D, E>() {
override fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F = d(value)
}
class Sum5E<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any>(private val value: E) : Sum5<A, B, C, D, E>() {
override fun <F> with(a: (A) -> F, b: (B) -> F, c: (C) -> F, d: (D) -> F, e: (E) -> F): F = e(value)
}
| mit | f64a8c34e1d32aac921e7e2c0de83390 | 47.934426 | 124 | 0.473702 | 2.158351 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt | 2 | 3975 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.refactoring.addTypeArgumentsIfNeeded
import org.jetbrains.kotlin.idea.refactoring.getQualifiedTypeArgumentList
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.isExplicitTypeReferenceNeededForTypeInference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker
import org.jetbrains.kotlin.types.typeUtil.isUnit
class RemoveExplicitTypeIntention : SelfTargetingRangeIntention<KtCallableDeclaration>(
KtCallableDeclaration::class.java,
KotlinBundle.lazyMessage("remove.explicit.type.specification")
), HighPriorityAction {
override fun applicabilityRange(element: KtCallableDeclaration): TextRange? = getRange(element)
override fun applyTo(element: KtCallableDeclaration, editor: Editor?) = removeExplicitType(element)
companion object {
fun removeExplicitType(element: KtCallableDeclaration) {
val initializer = (element as? KtProperty)?.initializer
val typeArgumentList = initializer?.let { getQualifiedTypeArgumentList(it) }
element.typeReference = null
if (typeArgumentList != null) addTypeArgumentsIfNeeded(initializer, typeArgumentList)
}
fun isApplicableTo(element: KtCallableDeclaration): Boolean {
return getRange(element) != null
}
fun getRange(element: KtCallableDeclaration): TextRange? {
if (element.containingFile is KtCodeFragment) return null
val typeReference = element.typeReference ?: return null
if (typeReference.isAnnotatedDeep()) return null
if (element is KtParameter) {
if (element.isLoopParameter) return element.textRange
if (element.isSetterParameter) return typeReference.textRange
}
if (element !is KtProperty && element !is KtNamedFunction) return null
if (element is KtNamedFunction
&& element.hasBlockBody()
&& (element.descriptor as? FunctionDescriptor)?.returnType?.isUnit()?.not() != false
) return null
val initializer = (element as? KtDeclarationWithInitializer)?.initializer
if (element is KtProperty && element.isVar && initializer?.node?.elementType == KtNodeTypes.NULL) return null
if (ExplicitApiDeclarationChecker.publicReturnTypeShouldBePresentInApiMode(
element,
element.languageVersionSettings,
element.resolveToDescriptorIfAny()
)
) return null
if (element.isExplicitTypeReferenceNeededForTypeInference()) return null
return when {
initializer != null -> TextRange(element.startOffset, initializer.startOffset - 1)
element is KtProperty && element.getter != null -> TextRange(element.startOffset, typeReference.endOffset)
element is KtNamedFunction -> TextRange(element.startOffset, typeReference.endOffset)
else -> null
}
}
}
}
internal val KtParameter.isSetterParameter: Boolean get() = (parent.parent as? KtPropertyAccessor)?.isSetter ?: false
| apache-2.0 | d2d2efeb18055adeda5a4f66f16dc07a | 47.47561 | 122 | 0.723019 | 5.670471 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineAnonymousFunctionHandler.kt | 5 | 1442 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.inline
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.isAnonymousFunction
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtFunctionLiteral
class KotlinInlineAnonymousFunctionHandler : AbstractKotlinInlineFunctionHandler<KtFunction>() {
override fun canInlineKotlinFunction(function: KtFunction): Boolean = function.isAnonymousFunction || function is KtFunctionLiteral
override fun inlineKotlinFunction(project: Project, editor: Editor?, function: KtFunction) {
val call = KotlinInlineAnonymousFunctionProcessor.findCallExpression(function)
if (call == null) {
val message = if (function is KtFunctionLiteral)
KotlinBundle.message("refactoring.cannot.be.applied.to.lambda.expression.without.invocation", refactoringName)
else
KotlinBundle.message("refactoring.cannot.be.applied.to.anonymous.function.without.invocation", refactoringName)
return showErrorHint(project, editor, message)
}
KotlinInlineAnonymousFunctionProcessor(function, call, editor, project).run()
}
}
| apache-2.0 | 03fdc67bfea1cc742b9801cf459361b3 | 50.5 | 158 | 0.769071 | 4.904762 | false | false | false | false |
ediTLJ/novelty | app/src/main/java/ro/edi/novelty/data/remote/AtomLink.kt | 1 | 1205 | /*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.data.remote
import org.simpleframework.xml.Attribute
import org.simpleframework.xml.Root
import org.simpleframework.xml.Text
import java.io.Serializable
@Root(name = "link", strict = false)
data class AtomLink(
@param:Attribute(name = "href", required = false)
@field:Attribute(name = "href", required = false)
val href: String? = null,
@param:Attribute(name = "rel", required = false)
@field:Attribute(name = "rel", required = false)
val rel: String? = null,
@param:Text(required = false)
@field:Text(required = false)
val value: String? = null
) : Serializable | apache-2.0 | d84e0340bb9c0ef4f946a90b49424aaa | 32.5 | 74 | 0.728631 | 3.789308 | false | false | false | false |
airbnb/epoxy | epoxy-processor/src/main/java/com/airbnb/epoxy/processor/DataBindingModuleLookup.kt | 1 | 4122 | package com.airbnb.epoxy.processor
import androidx.room.compiler.processing.XProcessingEnv
import androidx.room.compiler.processing.XTypeElement
import com.airbnb.epoxy.processor.resourcescanning.ResourceScanner
import com.squareup.javapoet.ClassName
import kotlin.math.min
class DataBindingModuleLookup(
private val environment: XProcessingEnv,
private val logger: Logger,
private val resourceProcessor: ResourceScanner
) {
fun getModuleName(element: XTypeElement): String {
val packageName = element.packageName
// First we try to get the module name by looking at what R classes were found when processing
// layout annotations. This may find nothing if no layouts were given as annotation params
var moduleName: String? = getModuleNameViaResources(packageName)
if (moduleName == null) {
// If the first approach fails, we try to guess at the R class for the module and look up
// the class to see if it exists. This can fail if this model's package name does not
// include the module name as a prefix (convention makes this unlikely.)
moduleName = getModuleNameViaGuessing(packageName)
}
if (moduleName == null) {
logger.logError("Could not find module name for DataBinding BR class.")
// Fallback to using the package name so we can at least try to generate and compile something
moduleName = packageName
}
return moduleName
}
/**
* Attempts to get the module name of the given package. We can do this because the package name
* of an R class is the module. Generally only one R class is used and we can just use that module
* name, but it is possible to have multiple R classes. In that case we compare the package names
* to find what is the most similar.
*
*
* We need to get the module name to know the path of the BR class for data binding.
*/
private fun getModuleNameViaResources(packageName: String): String {
val rClasses = resourceProcessor.rClassNames
if (rClasses.isEmpty()) {
return packageName
}
if (rClasses.size == 1) {
// Common case
return rClasses[0].packageName()
}
// Generally the only R class used should be the app's. It is possible to use other R classes
// though, like Android's. In that case we figure out the most likely match by comparing the
// package name.
// For example we might have "com.airbnb.epoxy.R" and "android.R"
val packageNames = packageName.split("\\.").toTypedArray()
var bestMatch: ClassName? = null
val bestNumMatches = -1
for (rClass in rClasses) {
val rModuleNames = rClass.packageName().split("\\.").toTypedArray()
var numNameMatches = 0
for (i in 0 until min(packageNames.size, rModuleNames.size)) {
if (packageNames[i] == rModuleNames[i]) {
numNameMatches++
} else {
break
}
}
if (numNameMatches > bestNumMatches) {
bestMatch = rClass
}
}
return bestMatch!!.packageName()
}
/**
* Attempts to get the android module that is currently being processed.. We can do this because
* the package name of an R class is the module name. So, we take any element in the module,
*
*
* We need to get the module name to know the path of the BR class for data binding.
*/
private fun getModuleNameViaGuessing(packageName: String): String? {
val packageNameParts = packageName.split("\\.").toTypedArray()
var moduleName = ""
for (i in packageNameParts.indices) {
moduleName += packageNameParts[i]
val rClass = environment.findType("$moduleName.R")
moduleName += if (rClass != null) {
return moduleName
} else {
"."
}
}
return null
}
}
| apache-2.0 | 15bba672ff71b34b62d9ecfbca501f0a | 40.22 | 106 | 0.626638 | 4.924731 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/model/Receipt.kt | 2 | 8826 | package co.smartreceipts.android.model
import android.os.Parcelable
import co.smartreceipts.android.date.DisplayableDate
import co.smartreceipts.android.search.Searchable
import co.smartreceipts.core.sync.model.SyncState
import co.smartreceipts.core.sync.model.Syncable
import co.smartreceipts.android.utils.StrictModeConfiguration
import kotlinx.android.parcel.Parcelize
import java.io.File
import java.sql.Date
import java.util.*
/**
* A mostly immutable implementation of the [Receipt] interface that
* serves as the default implementation.
*/
@Parcelize
class Receipt constructor(
override val id: Int,
override val uuid: UUID,
/**
* The "index" of this receipt relative to others. If this was the second earliest receipt, it would appear
* as a receipt of index 2.
*/
val index: Int,
/**
* The parent trip for this receipt. This can only be null if it's detached from a [Trip]
* (e.g. if it's a converted distance).
*/
val trip: Trip,
/**
* The file attached to this receipt or `null` if none is presentFirstTimeInformation
*/
val file: File?,
/**
* The payment method associated with this receipt item.
*/
val paymentMethod: PaymentMethod,
/**
* The name of this receipt. This should never be `null`.
*/
val name: String,
/**
* The [Category] to which this receipt is attached
*/
val category: Category,
/**
* The user defined comment for this receipt
*/
val comment: String,
override val price: Price,
/**
* The [Price] tax associated with this receipt
*/
val tax: Price,
/**
* The [Price] second (optional) tax associated with this receipt
*/
val tax2: Price,
/**
* The [DisplayableDate] during which this receipt occurred
*/
val displayableDate: DisplayableDate,
/**
* Checks if the receipt was marked as Reimbursable (i.e. counting towards the total) or not
*/
val isReimbursable: Boolean,
/**
* Checks if this receipt should be printed as a full page in the PDF report
*/
val isFullPage: Boolean,
/**
* Checks if this receipt is currently selected or not
*/
val isSelected: Boolean,
/**
* An extra [String], which certain white-label builds might have
*/
val extraEditText1: String?,
/**
* An extra [String], which certain white-label builds might have
*/
val extraEditText2: String?,
/**
* An extra [String], which certain white-label builds might have
*/
val extraEditText3: String?,
override val syncState: SyncState,
override val customOrderId: Long,
val autoCompleteMetadata: AutoCompleteMetadata
) : Keyed, Parcelable, Priceable, Draggable<Receipt>, Syncable, Searchable {
/**
* The [Date] in which the [displayableDate] was set
*/
val date: Date get() = displayableDate.date
/**
* The [TimeZone] in which the [displayableDate] was set
*/
val timeZone: TimeZone get() = displayableDate.timeZone
/**
* The name of this Receipt's file from [.getFile].
*/
val fileName: String
get() = file?.name ?: ""
/**
* The last updated time or `-1` if we don't have a file
*
* Java uses immutable [File], so when we rename our files as part of a receipt update, we might rename it
* to the same file name as the old receipt. By tracking the last update time as well, we can determine if this file
* was updated between two "like" receipts
*/
val fileLastModifiedTime: Long
get() = StrictModeConfiguration.permitDiskReads { file?.lastModified() } ?: -1
/**
* The absolute path of this Receipt's file from [.getFile].
*/
val filePath: String
get() = file?.absolutePath ?: ""
/**
* Checks if this receipt is connected to an image file
*/
fun hasImage(): Boolean {
return file?.name?.run {
endsWith(".jpg", ignoreCase = true) || endsWith(".jpeg", ignoreCase = true) || endsWith(".png", ignoreCase = true)
} ?: false
}
/**
* Checks if this receipt is connected to an PDF file
*/
fun hasPDF(): Boolean {
return file?.name?.endsWith(".pdf", ignoreCase = true) ?: false
}
fun hasExtraEditText1(): Boolean = extraEditText1 != null
fun hasExtraEditText2(): Boolean = extraEditText2 != null
fun hasExtraEditText3(): Boolean = extraEditText3 != null
override fun toString(): String {
return "DefaultReceiptImpl{" +
"id=" + id +
", uuid='" + uuid.toString() +
", name='" + name + '\''.toString() +
", trip=" + trip.name +
", paymentMethod=" + paymentMethod +
", index=" + index +
", comment='" + comment + '\''.toString() +
", category=" + category +
", price=" + price.currencyFormattedPrice +
", displayableDate=" + displayableDate +
", timeZone=" + timeZone.id +
", isReimbursable=" + isReimbursable +
", isFullPage=" + isFullPage +
", autoCompleteMetadata=" + autoCompleteMetadata +
", extraEditText1='" + extraEditText1 + '\''.toString() +
", extraEditText2='" + extraEditText2 + '\''.toString() +
", extraEditText3='" + extraEditText3 + '\''.toString() +
", isSelected=" + isSelected +
", file=" + file +
", customOrderId=" + customOrderId +
'}'.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Receipt) return false
val that = other as Receipt?
if (id != that!!.id) return false
if (uuid != that.uuid) return false
if (isReimbursable != that.isReimbursable) return false
if (isFullPage != that.isFullPage) return false
if (trip != that.trip) return false
if (paymentMethod != that.paymentMethod) return false
if (index != that.index) return false
if (name != that.name) return false
if (comment != that.comment) return false
if (category != that.category) return false
if (price != that.price) return false
if (tax != that.tax) return false
if (tax2 != that.tax2) return false
if (displayableDate != that.displayableDate) return false
if (autoCompleteMetadata != that.autoCompleteMetadata) return false
if (if (extraEditText1 != null) extraEditText1 != that.extraEditText1 else that.extraEditText1 != null)
return false
if (if (extraEditText2 != null) extraEditText2 != that.extraEditText2 else that.extraEditText2 != null)
return false
if (if (extraEditText3 != null) extraEditText3 != that.extraEditText3 else that.extraEditText3 != null)
return false
if (fileLastModifiedTime != that.fileLastModifiedTime) return false
if (customOrderId != that.customOrderId) return false
return if (file != null) file == that.file else that.file == null
}
override fun hashCode(): Int {
var result = id
result = 31 * result + uuid.hashCode()
result = 31 * result + trip.hashCode()
result = 31 * result + paymentMethod.hashCode()
result = 31 * result + index
result = 31 * result + name.hashCode()
result = 31 * result + comment.hashCode()
result = 31 * result + category.hashCode()
result = 31 * result + price.hashCode()
result = 31 * result + tax.hashCode()
result = 31 * result + tax2.hashCode()
result = 31 * result + displayableDate.hashCode()
result = 31 * result + if (isReimbursable) 1 else 0
result = 31 * result + if (isFullPage) 1 else 0
result = 31 * result + autoCompleteMetadata.hashCode()
result = 31 * result + (extraEditText1?.hashCode() ?: 0)
result = 31 * result + (extraEditText2?.hashCode() ?: 0)
result = 31 * result + (extraEditText3?.hashCode() ?: 0)
result = 31 * result + if (file != null) file.hashCode() else 0
result = 31 * result + fileLastModifiedTime.toInt()
result = 31 * result + (customOrderId xor customOrderId.ushr(32)).toInt()
return result
}
override fun compareTo(other: Receipt): Int {
return if (customOrderId == other.customOrderId) {
other.date.compareTo(date)
} else {
-java.lang.Long.compare(customOrderId, other.customOrderId)
}
}
companion object {
@JvmField
val PARCEL_KEY: String = Receipt::class.java.name
}
} | agpl-3.0 | b03ee7a95ea7df53cf03878a11ef97dd | 35.17623 | 126 | 0.604917 | 4.473391 | false | false | false | false |
flesire/ontrack | ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/resources/ValidationStampFilterResourceDecorator.kt | 2 | 2835 | package net.nemerosa.ontrack.boot.resources
import net.nemerosa.ontrack.boot.ui.ValidationStampFilterController
import net.nemerosa.ontrack.model.security.*
import net.nemerosa.ontrack.model.structure.ValidationStampFilter
import net.nemerosa.ontrack.model.structure.ValidationStampFilterScope
import net.nemerosa.ontrack.ui.resource.AbstractResourceDecorator
import net.nemerosa.ontrack.ui.resource.Link
import net.nemerosa.ontrack.ui.resource.ResourceContext
import org.springframework.stereotype.Component
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on
@Component
class ValidationStampFilterResourceDecorator : AbstractResourceDecorator<ValidationStampFilter>(ValidationStampFilter::class.java) {
override fun links(resource: ValidationStampFilter, resourceContext: ResourceContext): List<Link> {
// Scope of the validation stamp filter
val canUpdate: Boolean = when {
resource.project != null -> resourceContext.isProjectFunctionGranted(resource.project, ValidationStampFilterMgt::class.java)
resource.branch != null -> resourceContext.isProjectFunctionGranted(resource.branch, ValidationStampFilterCreate::class.java)
else -> resourceContext.isGlobalFunctionGranted(GlobalSettings::class.java)
}
// Links
return resourceContext.links()
// Update if authorized
.link(
Link.UPDATE,
on(ValidationStampFilterController::class.java).getValidationStampFilterUpdateForm(resource.id),
canUpdate
)
// Delete if authorized
.link(
Link.DELETE,
on(ValidationStampFilterController::class.java).deleteValidationStampFilter(resource.id),
canUpdate
)
// Share at project level
.link(
"_shareAtProject",
on(ValidationStampFilterController::class.java).shareValidationStampFilterAtProject(resource.id),
resource.scope == ValidationStampFilterScope.BRANCH && resourceContext.isProjectFunctionGranted(resource.branch, ValidationStampFilterShare::class.java)
)
// Share at global level
.link(
"_shareAtGlobal",
on(ValidationStampFilterController::class.java).shareValidationStampFilterAtGlobal(resource.id),
(resource.scope == ValidationStampFilterScope.PROJECT || resource.scope == ValidationStampFilterScope.BRANCH) && resourceContext.isGlobalFunctionGranted(GlobalSettings::class.java)
)
// OK
.build()
}
}
| mit | 4405ccb5830f0ced4d9bc3bddc5c1cf0 | 52.490566 | 204 | 0.66455 | 5.845361 | false | false | false | false |
seratch/jslack | slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/OverflowMenuElementBuilder.kt | 1 | 2436 | package com.slack.api.model.kotlin_extension.block.element
import com.slack.api.model.block.composition.ConfirmationDialogObject
import com.slack.api.model.block.composition.OptionObject
import com.slack.api.model.block.element.OverflowMenuElement
import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder
import com.slack.api.model.kotlin_extension.block.Builder
import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder
import com.slack.api.model.kotlin_extension.block.composition.container.MultiOptionContainer
import com.slack.api.model.kotlin_extension.block.composition.dsl.OptionObjectDsl
@BlockLayoutBuilder
class OverflowMenuElementBuilder : Builder<OverflowMenuElement> {
private var actionId: String? = null
private var options: List<OptionObject>? = null
private var confirm: ConfirmationDialogObject? = null
/**
* An identifier for the action triggered when a menu option is selected. You can use this when you receive an
* interaction payload to identify the source of the action. Should be unique among all other action_ids used
* elsewhere by your app. Maximum length for this field is 255 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#overflow">Overflow menu element documentation</a>
*/
fun actionId(id: String) {
actionId = id
}
/**
* An array of option objects to display in the menu. Maximum number of options is 5, minimum is 2.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#overflow">Overflow menu element documentation</a>
*/
fun options(builder: OptionObjectDsl.() -> Unit) {
options = MultiOptionContainer().apply(builder).underlying
}
/**
* A confirm object that defines an optional confirmation dialog that appears after a menu item is selected.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#overflow">Overflow menu element documentation</a>
*/
fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) {
confirm = ConfirmationDialogObjectBuilder().apply(builder).build()
}
override fun build(): OverflowMenuElement {
return OverflowMenuElement.builder()
.actionId(actionId)
.options(options)
.confirm(confirm)
.build()
}
} | mit | e3b1b09f1604b0bd268617d969413ee6 | 44.12963 | 127 | 0.724138 | 4.326821 | false | false | false | false |
bmwcarit/joynr | tools/generator/joynr-generator-gradle-plugin/src/main/kotlin/io/joynr/tools/generator/gradle/JoynrGeneratorPluginExtension.kt | 1 | 2166 | /*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.tools.generator.gradle
import org.gradle.api.Project
/**
* All variables defined in this class can be configured
* in the gradle build script using this plugin.
*/
open class JoynrGeneratorPluginExtension(project: Project) {
/**
* Path to model file or directory containing multiple modelPath files.
* This is a required parameter.
*/
val modelPath = project.objects.property(String::class.java)!!
/**
* Path where the generated source code is to be placed.
* This is a required parameter.
*/
val outputPath = project.objects.property(String::class.java)!!
/**
* Sets the generation language. This is a required parameter.
*/
val generationLanguage = project.objects.property(String::class.java)!!
/**
* Sets the target (optional).
*/
val target = project.objects.property(String::class.java)!!
/**
* If set to true, execution of the joynr generator is skipped (optional).
*/
val skip = project.objects.property(java.lang.Boolean::class.java)!!
/**
* Specify how the major version shall affect the generated interface name and package.
*/
val addVersionTo = project.objects.property(String::class.java)!!
/**
* Sets extra parameters that may be required by custom generators (optional).
* In the gradle build file, this has to be set using a Map<String, String> structure.
*/
val extraParameters = project.objects.mapProperty(String::class.java, String::class.java)!!
}
| apache-2.0 | 1f94d8719551484e57a6b560cf3bced3 | 32.323077 | 95 | 0.687904 | 4.197674 | false | false | false | false |
neilellis/kontrol | mock/src/main/kotlin/MockMachineGroup.kt | 1 | 4174 | /*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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 kontrol.mock
import kontrol.api.MachineGroup
import kontrol.api.Machine
import kontrol.api.MachineState
import kontrol.common.DefaultStateMachineRules
import kontrol.api.MachineGroupState
import kontrol.common.DefaultStateMachine
import kontrol.api.Monitor
import kontrol.api.sensors.SensorArray
import kontrol.common.DefaultSensorArray
import java.util.ArrayList
import kontrol.api.MonitorRule
import kontrol.api.DownStreamKonfigurator
import kontrol.api.UpStreamKonfigurator
import java.util.SortedSet
import java.util.TreeSet
import kontrol.api.Postmortem
import kontrol.api.Controller
import kontrol.api.Monitorable
import kontrol.api.sensors.GroupSensorArray
import kontrol.common.DefaultGroupSensorArray
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
public class MockMachineGroup(val name: String, val machines: MutableList<MockMachine>, override val monitor: Monitor<MachineGroupState, MachineGroup>, override val upstreamGroups: MutableList<MachineGroup>, override val downStreamKonfigurator: DownStreamKonfigurator?, override val upStreamKonfigurator: UpStreamKonfigurator?, override val controller: Controller, override val groupSensors: GroupSensorArray = DefaultGroupSensorArray()) : MachineGroup{
override var disableAction: ((Monitorable<MachineGroupState>) -> Unit)? = null
override var enableAction: ((Monitorable<MachineGroupState>) -> Unit)? = null
override val hardMax: Int = 10000000
override fun costPerHourInDollars(): Double {
return 0.0;
}
override fun groupName(): String {
return name;
}
override val postmortems: List<Postmortem> = listOf()
override val downStreamGroups: MutableList<MachineGroup> = ArrayList()
override var enabled: Boolean = true
override val min: Int = 0
override val max: Int = 100000
var configureCalls: Int = 0
override val machineMonitorRules: SortedSet<MonitorRule<MachineState, Machine>> = TreeSet();
override val groupMonitorRules: SortedSet<MonitorRule<MachineGroupState, MachineGroup>> = TreeSet();
override val sensors: SensorArray = DefaultSensorArray(ArrayList())
override val stateMachine = DefaultStateMachine<MachineGroupState>(this);
override val defaultMachineRules = DefaultStateMachineRules<MachineState>();
{
machines.forEach { it.fsm.rules = defaultMachineRules }
stateMachine.rules = DefaultStateMachineRules<MachineGroupState>();
println("${name()} has upstream group ${upstreamGroups}")
upstreamGroups.forEach { (it as MockMachineGroup).downStreamGroups.add(this) }
}
override fun name(): String {
return name;
}
override fun machines(): List<Machine> {
return machines;
}
override fun expand(): Machine {
println("**** Expand $name");
val mockMachine = MockMachine("10.10.10." + (Math.random() * 256));
mockMachine.monitor = MockMachineMonitor();
mockMachine.fsm.rules = defaultMachineRules;
machines.add(mockMachine);
return mockMachine;
}
override fun contract(): MachineGroup {
println("**** Contract $name");
if (machines.size() > 0) {
machines.remove(machines[0]);
}
return this;
}
override fun destroy(machine: Machine): MachineGroup {
machines.remove(machine);
return this
}
override fun configure(): MachineGroup {
this.configureCalls++;
return super<MachineGroup>.configure()
}
} | apache-2.0 | 4f7fbb0b85307c056eb6ec19da3c49b2 | 35.622807 | 453 | 0.727839 | 4.389064 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | data/src/main/java/de/ph1b/audiobook/data/repo/BookRepository.kt | 1 | 4890 | package de.ph1b.audiobook.data.repo
import de.ph1b.audiobook.common.Optional
import de.ph1b.audiobook.common.toOptional
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.BookSettings
import de.ph1b.audiobook.data.Chapter
import de.ph1b.audiobook.data.repo.internals.BookStorage
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.util.ArrayList
import java.util.Collections
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BookRepository
@Inject constructor(private val storage: BookStorage) {
private val allBooks by lazy {
runBlocking { storage.books() }
}
private val active: MutableList<Book> by lazy {
val activeBooks = allBooks.filter { it.content.settings.active }
Collections.synchronizedList(activeBooks)
}
private val orphaned: MutableList<Book> by lazy {
val orphanedBooks = allBooks.filter { it.content.settings.active }
Collections.synchronizedList(orphanedBooks)
}
private val activeBooksSubject: BehaviorSubject<List<Book>> by lazy {
BehaviorSubject.createDefault<List<Book>>(active)
}
fun booksStream(): Observable<List<Book>> = activeBooksSubject
fun byId(id: UUID): Observable<Optional<Book>> {
return activeBooksSubject.map { books ->
books.find { it.id == id }.toOptional()
}
}
suspend fun addBook(book: Book) {
withContext(Dispatchers.IO) {
Timber.v("addBook=${book.name}")
storage.addOrUpdate(book)
active.add(book)
withContext(Dispatchers.Main) {
activeBooksSubject.onNext(active.toList())
}
}
}
/** All active books. */
val activeBooks: List<Book>
get() = synchronized(this) { ArrayList(active) }
fun bookById(id: UUID) = active.firstOrNull { it.id == id }
suspend fun updateBookSettings(settings: BookSettings) {
updateBookInMemory(settings.id) {
val currentFileInChapters = content.chapters.any { it.file == settings.currentFile }
if (currentFileInChapters) {
update(updateSettings = { settings })
} else {
this
}
}
storage.updateBookSettings(settings)
}
fun getOrphanedBooks(): List<Book> = ArrayList(orphaned)
suspend fun updateBook(book: Book) {
if (bookById(book.id) == book) {
return
}
withContext(Dispatchers.IO) {
val index = active.indexOfFirst { it.id == book.id }
if (index != -1) {
active[index] = book
storage.addOrUpdate(book)
withContext(Dispatchers.Main) {
activeBooksSubject.onNext(active.toList())
}
} else Timber.e("update failed as there was no book")
}
}
suspend fun updateBookName(id: UUID, name: String) {
withContext(Dispatchers.IO) {
storage.updateBookName(id, name)
updateBookInMemory(id) {
updateMetaData { copy(name = name) }
}
}
}
private suspend inline fun updateBookInMemory(id: UUID, update: Book.() -> Book) {
val index = active.indexOfFirst { it.id == id }
if (index != -1) {
active[index] = update(active[index])
withContext(Dispatchers.Main) {
activeBooksSubject.onNext(active.toList())
}
} else {
Timber.e("update failed as there was no book")
}
}
suspend fun markBookAsPlayedNow(id: UUID) {
withContext(Dispatchers.IO) {
val lastPlayedAt = System.currentTimeMillis()
storage.updateLastPlayedAt(id, lastPlayedAt)
updateBookInMemory(id) {
update(updateSettings = {
copy(lastPlayedAtMillis = lastPlayedAt)
})
}
}
}
suspend fun hideBook(toDelete: List<Book>) {
withContext(Dispatchers.IO) {
Timber.v("hideBooks=${toDelete.size}")
if (toDelete.isEmpty()) return@withContext
val idsToDelete = toDelete.map(Book::id)
active.removeAll { idsToDelete.contains(it.id) }
orphaned.addAll(toDelete)
toDelete.forEach { storage.hideBook(it.id) }
withContext(Dispatchers.Main) {
activeBooksSubject.onNext(active.toList())
}
}
}
suspend fun revealBook(book: Book) {
withContext(Dispatchers.IO) {
Timber.v("Called revealBook=$book")
orphaned.removeAll { it.id == book.id }
active.add(book)
storage.revealBook(book.id)
withContext(Dispatchers.Main) {
activeBooksSubject.onNext(active.toList())
}
}
}
fun chapterByFile(file: File) = chapterByFile(file, active) ?: chapterByFile(file, orphaned)
private fun chapterByFile(file: File, books: List<Book>): Chapter? {
books.forEach { book ->
book.content.chapters.forEach { chapter ->
if (chapter.file == file) return chapter
}
}
return null
}
}
| lgpl-3.0 | 344fb20f2270f8b87322ecc1d2a36972 | 27.934911 | 94 | 0.676074 | 3.946731 | false | false | false | false |
denzelby/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/youtube/service/SubscriptionUpdateScheduler.kt | 2 | 977 | package com.github.bumblebee.command.youtube.service
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.TimeUnit
@Component
class SubscriptionUpdateScheduler(private val service: YoutubeSubscriptionService) {
@Scheduled(fixedRate = delay)
fun checkOverdueSubscriptions() {
val date = Date()
service.getSubscriptions().forEach { subscription ->
val interval = date.time - subscription.updatedDate.time
if (interval > overdueInterval) {
subscription.updatedDate = date
if (service.subscribeChannel(subscription.channelId))
service.storeSubscription(subscription)
}
}
}
companion object {
private const val delay = (60 * 1000 * 60 * 4).toLong() //4 Hours in millis
private val overdueInterval = TimeUnit.DAYS.toMillis(4)
}
}
| mit | 5003725c9e24a4c7db2b0d8139fc1c1a | 33.892857 | 84 | 0.681679 | 4.959391 | false | false | false | false |
chetdeva/recyclerview-bindings | app/src/main/java/com/fueled/recyclerviewbindings/widget/decoration/SpaceItemDecoration.kt | 1 | 2829 | package com.fueled.recyclerviewbindings.core
/**
* Available `ItemDecoration` of `RecyclerView` doesn't allow option of show / hide
* top / bottom dividers. It also doesn't allow us to specify height / width of divider if it's not a drawable
* and just space.
*
*
* Created to have control over item decoration.
* Ability to show / not show divider on top bottom.
* Created by garima-fueled on 21/07/17.
*/
import android.content.Context
import android.graphics.Rect
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
class SpaceItemDecoration : RecyclerView.ItemDecoration {
private val space: Int
private var showFirstDivider = false
private var showLastDivider = false
internal var orientation = -1
constructor(spaceInPx: Int) {
space = spaceInPx
}
constructor(spaceInPx: Int, showFirstDivider: Boolean,
showLastDivider: Boolean) : this(spaceInPx) {
this.showFirstDivider = showFirstDivider
this.showLastDivider = showLastDivider
}
constructor(ctx: Context, resId: Int) {
space = ctx.resources.getDimensionPixelSize(resId)
}
constructor(ctx: Context, resId: Int, showFirstDivider: Boolean,
showLastDivider: Boolean) : this(ctx, resId) {
this.showFirstDivider = showFirstDivider
this.showLastDivider = showLastDivider
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State?) {
if (space == 0) {
return
}
if (orientation == -1) {
getOrientation(parent)
}
val position = parent.getChildAdapterPosition(view)
if (position == RecyclerView.NO_POSITION || position == 0 && !showFirstDivider) {
return
}
if (orientation == LinearLayoutManager.VERTICAL) {
outRect.top = space
if (showLastDivider && position == state!!.itemCount - 1) {
outRect.bottom = outRect.top
}
} else {
outRect.left = space
if (showLastDivider && position == state!!.itemCount - 1) {
outRect.right = outRect.left
}
}
}
private fun getOrientation(parent: RecyclerView): Int {
if (orientation == -1) {
if (parent.layoutManager is LinearLayoutManager) {
val layoutManager = parent.layoutManager as LinearLayoutManager
orientation = layoutManager.orientation
} else {
throw IllegalStateException(
"SpaceItemDecoration can only be used with a LinearLayoutManager.")
}
}
return orientation
}
}
| mit | 00b6a7f8aaaf3c9d74c632d9d49b4662 | 31.147727 | 110 | 0.624249 | 5.042781 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/util/ExportOptions.kt | 2 | 710 | package io.github.chrislo27.rhre3.util
data class ExportOptions(val bitrateKbps: Int, val sampleRate: Int, val madeWithComment: Boolean) {
companion object {
/**
* Standard output settings.
*/
val DEFAULT = ExportOptions(196, 44100, true)
/**
* A lower bitrate for quick uploads.
*/
val QUICKUPLOAD = ExportOptions(128, 44100, true)
/**
* Same as [DEFAULT] but with no comments.
*/
val BLEND = DEFAULT.copy(madeWithComment = false)
/**
* A lower-quality lower-filesize option for the Challenge Train.
*/
val CHALLENGE_TRAIN = ExportOptions(128, 44100, true)
}
}
| gpl-3.0 | 07f5eea7deddc0b8bbc6438fbd56a040 | 27.4 | 99 | 0.584507 | 4.382716 | false | false | false | false |
aporter/coursera-android | ExamplesKotlin/UITimePickerFragment/app/src/main/java/course/examples/ui/datepicker/TimePickerFragmentActivity.kt | 1 | 2957 | package course.examples.ui.datepicker
import android.app.Dialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v4.app.DialogFragment
import android.view.View
import android.widget.TextView
import android.widget.TimePicker
import java.util.*
class TimePickerFragmentActivity : FragmentActivity(), OnTimeSetListener {
companion object {
private const val KEY_CURRENT_TIME = "CURRENT_TIME_KEY"
@Suppress("unused")
private const val TAG = "TimePickerFragmentActivity"
// Prepends a "0" to 1-digit minute values
private fun pad(c: Int): String {
return if (c >= 10)
c.toString()
else
"0$c"
}
}
private lateinit var mTimeDisplay: TextView
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
// Capture UI element
mTimeDisplay = findViewById(R.id.timeDisplay)
setupUI(savedInstanceState)
}
private fun setupUI(savedInstanceState: Bundle?) {
if (null == savedInstanceState) {
mTimeDisplay.setText(R.string.no_time_selected_string)
} else {
mTimeDisplay.text = savedInstanceState.getCharSequence(KEY_CURRENT_TIME)
}
}
// OnClickListener for the "Change the Time" Button
fun buttonPressedCallback(view: View) {
// Create and display DatePickerFragment
TimePickerFragment().show(supportFragmentManager, "TimePicker")
}
// Callback called by TimePickerFragment when user sets the time
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
mTimeDisplay.text = StringBuilder().append(pad(hourOfDay)).append(":").append(pad(minute))
}
// Save instance state
public override fun onSaveInstanceState(bundle: Bundle) {
// TextView Time String
bundle.putCharSequence(KEY_CURRENT_TIME, mTimeDisplay.text)
// call superclass to save any view hierarchy
super.onSaveInstanceState(bundle)
}
// Time Picking Fragment
class TimePickerFragment : DialogFragment(), OnTimeSetListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val c = Calendar.getInstance()
val hourOfDay = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
return TimePickerDialog(activity, this, hourOfDay, minute,false)
}
// Callback called by TimePickerDialog when user sets the time
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
(activity as OnTimeSetListener).onTimeSet(view, hourOfDay, minute)
}
}
}
| mit | fab18c9dc670b3087e51041227776c88 | 30.795699 | 98 | 0.675008 | 4.887603 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/content/AudioStore.kt | 1 | 8797 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.content
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Parcelable
import android.provider.MediaStore
import android.provider.MediaStore.Audio.*
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import javax.inject.Inject
class AudioStore @Inject constructor(
@ApplicationContext private val context: Context,
) {
fun getAlbums(): List<Album> {
return try {
loadAlbums(
context.contentResolver.query(
Albums.EXTERNAL_CONTENT_URI,
arrayOf(
Albums._ID,
Albums.ARTIST,
Albums.LAST_YEAR,
Albums.ALBUM,
),
null,
null,
Albums.ALBUM
)
)
} catch (e: Throwable) {
e.printStackTrace()
emptyList()
}
}
fun getAlbums(artist: Artist): List<Album> {
return try {
loadAlbums(
context.contentResolver.query(
Artists.Albums.getContentUri(MediaStore.VOLUME_EXTERNAL, artist.id),
arrayOf(
Albums._ID,
Albums.ARTIST,
Albums.LAST_YEAR,
Albums.ALBUM,
),
null,
null,
Albums.ALBUM
)
)
} catch (e: Throwable) {
e.printStackTrace()
emptyList()
}
}
fun getArtists(): List<Artist> {
try {
context.contentResolver.query(
Artists.EXTERNAL_CONTENT_URI,
arrayOf(
Artists._ID,
Artists.ARTIST,
Artists.NUMBER_OF_ALBUMS,
),
null,
null,
Albums.ARTIST
)?.use {
if (it.moveToFirst()) {
val idIndex: Int = it.getColumnIndex(Artists._ID)
val artistIndex: Int = it.getColumnIndex(Artists.ARTIST)
val numberOfAlbumsIndex: Int = it.getColumnIndex(Artists.NUMBER_OF_ALBUMS)
val result = ArrayList<Artist>(it.count)
do {
try {
val id = it.getLong(idIndex)
result.add(
Artist(
id,
it.getString(artistIndex),
it.getInt(numberOfAlbumsIndex),
ContentUris.withAppendedId(Artists.EXTERNAL_CONTENT_URI, id),
)
)
} catch (e: Throwable) {
e.printStackTrace()
}
} while (it.moveToNext())
return result
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return emptyList()
}
fun getSongs(selection: String, selectionArgs: Array<String>): List<Song> {
try {
context.contentResolver.query(
Media.EXTERNAL_CONTENT_URI,
arrayOf(
Media._ID,
Media.ARTIST,
Media.ALBUM,
Media.ALBUM_ID,
Media.TITLE,
Media.DISPLAY_NAME,
Media.MIME_TYPE,
Media.SIZE,
Media.DATE_MODIFIED
),
selection,
selectionArgs,
Media.TITLE
)?.use {
if (it.moveToFirst()) {
val idIndex: Int = it.getColumnIndex(Media._ID)
val artistIndex: Int = it.getColumnIndex(Media.ARTIST)
val albumIndex: Int = it.getColumnIndex(Media.ALBUM)
val albumIdIndex = it.getColumnIndex(Media.ALBUM_ID)
val titleIndex: Int = it.getColumnIndex(Media.TITLE)
val displayNameIndex: Int = it.getColumnIndex(Media.DISPLAY_NAME)
val mimeTypeIndex: Int = it.getColumnIndex(Media.MIME_TYPE)
val sizeIndex: Int = it.getColumnIndex(Media.SIZE)
val dateModifiedIndex: Int = it.getColumnIndex(Media.DATE_MODIFIED)
val result = ArrayList<Song>(it.count)
do {
try {
val id = it.getLong(idIndex)
result.add(
Song(
id,
it.getString(artistIndex),
it.getString(albumIndex),
it.getString(titleIndex),
it.getString(displayNameIndex),
it.getString(mimeTypeIndex),
it.getLong(sizeIndex),
it.getLong(dateModifiedIndex),
ContentUris.withAppendedId(Media.EXTERNAL_CONTENT_URI, id),
ContentUris.withAppendedId(Albums.EXTERNAL_CONTENT_URI, it.getLong(albumIdIndex))
)
)
} catch (e: Throwable) {
e.printStackTrace()
}
} while (it.moveToNext())
return result
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return emptyList()
}
private fun loadAlbums(cursor: Cursor?): List<Album> {
if (cursor != null && cursor.moveToFirst()) {
val idIndex: Int = cursor.getColumnIndex(Albums._ID)
val artistIndex: Int = cursor.getColumnIndex(Albums.ARTIST)
val albumIndex: Int = cursor.getColumnIndex(Albums.ALBUM)
val lastYearIndex: Int = cursor.getColumnIndex(Albums.LAST_YEAR)
val result = ArrayList<Album>(cursor.count)
do {
try {
val id = cursor.getLong(idIndex)
result.add(
Album(
id,
cursor.getString(artistIndex),
cursor.getString(albumIndex),
cursor.getInt(lastYearIndex),
ContentUris.withAppendedId(Albums.EXTERNAL_CONTENT_URI, id),
)
)
} catch (e: Throwable) {
e.printStackTrace()
}
} while (cursor.moveToNext())
return result
}
return emptyList()
}
}
@Parcelize
data class Album(
val id: Long,
val artist: String,
val title: String,
val year: Int,
val uri: Uri,
) : Parcelable
@Parcelize
data class Artist(
val id: Long,
val name: String,
val numberOfAlbums: Int,
val uri: Uri,
) : Parcelable
@Parcelize
data class Song(
val id: Long,
val artist: String,
val album: String,
val title: String,
val displayName: String,
val mimeType: String,
val size: Long,
val dateModified: Long,
val uri: Uri,
val albumUri: Uri,
) : Parcelable {
@IgnoredOnParcel
var isSelected = false
override fun equals(other: Any?): Boolean {
return other is Song && uri == other.uri
}
}
| gpl-2.0 | 51794f0b9b735a39262881136c5b6b78 | 32.572519 | 117 | 0.476126 | 5.500938 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/flow/FlowFlattenMergeBenchmark.kt | 1 | 1886 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.flow
import benchmarks.common.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
/**
* Benchmark to measure performance of [kotlinx.coroutines.flow.FlowKt.flattenMerge].
* In addition to that, it can be considered as a macro benchmark for the [kotlinx.coroutines.sync.Semaphore]
*/
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(1)
open class FlowFlattenMergeBenchmark {
@Param
private var flowsNumberStrategy: FlowsNumberStrategy = FlowsNumberStrategy.`10xConcurrency flows`
@Param("1", "2", "4", "8")
private var concurrency: Int = 0
private lateinit var flow: Flow<Flow<Int>>
@Setup
fun setup() {
val n = flowsNumberStrategy.get(concurrency)
val flowElementsToProcess = ELEMENTS / n
flow = (1..n).asFlow().map {
flow {
repeat(flowElementsToProcess) {
doGeomDistrWork(WORK)
emit(it)
}
}
}
}
@Benchmark
fun flattenMerge() = runBlocking(Dispatchers.Default) {
flow.flattenMerge(concurrency = concurrency).collect()
}
}
enum class FlowsNumberStrategy(val get: (concurrency: Int) -> Int) {
`10xConcurrency flows`({ concurrency -> concurrency * 10 }),
`1xConcurrency flows`({ it }),
`100 flows`({ 100 }),
`500 flows`({ 500 })
}
// If you change this variable please be sure that you change variable elements in the generate_plots_flow_flatten_merge.py
// python script as well
private const val ELEMENTS = 100_000
private const val WORK = 100
| apache-2.0 | 2c3bf99bd1c599ad89ac5c0f5609cfdb | 28.936508 | 123 | 0.671792 | 3.978903 | false | false | false | false |
spring-projects/spring-framework | spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt | 1 | 7846 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.web.reactive.function.client
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kotlinx.coroutines.reactor.asFlux
import kotlinx.coroutines.reactor.mono
import org.reactivestreams.Publisher
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.ResponseEntity
import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
/**
* Extension for [WebClient.RequestBodySpec.body] providing a `body(Publisher<T>)` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any, S : Publisher<T>> RequestBodySpec.body(publisher: S): RequestHeadersSpec<*> =
body(publisher, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [WebClient.RequestBodySpec.body] providing a `body(Flow<T>)` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
* @param flow the [Flow] to write to the request
* @param T the type of the elements contained in the flow
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> RequestBodySpec.body(flow: Flow<T>): RequestHeadersSpec<*> =
body(flow, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [WebClient.RequestBodySpec.body] providing a `body<T>(Any)` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
* @param producer the producer to write to the request. This must be a
* [Publisher] or another producer adaptable to a
* [Publisher] via [org.springframework.core.ReactiveAdapterRegistry]
* @param T the type of the elements contained in the producer
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> RequestBodySpec.body(producer: Any): RequestHeadersSpec<*> =
body(producer, object : ParameterizedTypeReference<T>() {})
/**
* Coroutines variant of [WebClient.RequestHeadersSpec.exchange].
*
* @author Sebastien Deleuze
* @since 5.2
*/
@Suppress("DEPRECATION")
@Deprecated("Deprecated since 5.3 due to the possibility to leak memory and/or connections; please," +
"use awaitExchange { } or exchangeToFlow { } instead; consider also using retrieve()" +
"which provides access to the response status and headers via ResponseEntity along with error status handling.")
suspend fun RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchange(): ClientResponse =
exchange().awaitSingle()
/**
* Coroutines variant of [WebClient.RequestHeadersSpec.exchangeToMono].
*
* @author Sebastien Deleuze
* @since 5.3
*/
suspend fun <T: Any> RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchange(responseHandler: suspend (ClientResponse) -> T): T =
exchangeToMono { mono(Dispatchers.Unconfined) { responseHandler.invoke(it) } }.awaitSingle()
/**
* Variant of [WebClient.RequestHeadersSpec.awaitExchange] that allows a nullable return
*
* @since 5.3.8
*/
@Suppress("DEPRECATION")
suspend fun <T: Any> RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchangeOrNull(responseHandler: suspend (ClientResponse) -> T?): T? =
exchangeToMono { mono(Dispatchers.Unconfined) { responseHandler.invoke(it) } }.awaitSingleOrNull()
/**
* Coroutines variant of [WebClient.RequestHeadersSpec.exchangeToFlux].
*
* @author Sebastien Deleuze
* @since 5.3
*/
fun <T: Any> RequestHeadersSpec<out RequestHeadersSpec<*>>.exchangeToFlow(responseHandler: (ClientResponse) -> Flow<T>): Flow<T> =
exchangeToFlux { responseHandler.invoke(it).asFlux() }.asFlow()
/**
* Extension for [WebClient.ResponseSpec.bodyToMono] providing a `bodyToMono<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any> WebClient.ResponseSpec.bodyToMono(): Mono<T> =
bodyToMono(object : ParameterizedTypeReference<T>() {})
/**
* Extension for [WebClient.ResponseSpec.bodyToFlux] providing a `bodyToFlux<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any> WebClient.ResponseSpec.bodyToFlux(): Flux<T> =
bodyToFlux(object : ParameterizedTypeReference<T>() {})
/**
* Coroutines [kotlinx.coroutines.flow.Flow] based variant of [WebClient.ResponseSpec.bodyToFlux].
*
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> WebClient.ResponseSpec.bodyToFlow(): Flow<T> =
bodyToFlux<T>().asFlow()
/**
* Coroutines variant of [WebClient.ResponseSpec.bodyToMono].
*
* @author Sebastien Deleuze
* @since 5.2
*/
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBody() : T =
when (T::class) {
Unit::class -> awaitBodilessEntity().let { Unit as T }
else -> bodyToMono<T>().awaitSingle()
}
/**
* Coroutines variant of [WebClient.ResponseSpec.bodyToMono].
*
* @author Valentin Shakhov
* @since 5.3.6
*/
@Suppress("DEPRECATION")
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBodyOrNull() : T? =
when (T::class) {
Unit::class -> awaitBodilessEntity().let { Unit as T? }
else -> bodyToMono<T>().awaitSingleOrNull()
}
/**
* Coroutines variant of [WebClient.ResponseSpec.toBodilessEntity].
*/
suspend fun WebClient.ResponseSpec.awaitBodilessEntity() =
toBodilessEntity().awaitSingle()
/**
* Extension for [WebClient.ResponseSpec.toEntity] providing a `toEntity<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @since 5.3.2
*/
inline fun <reified T : Any> WebClient.ResponseSpec.toEntity(): Mono<ResponseEntity<T>> =
toEntity(object : ParameterizedTypeReference<T>() {})
/**
* Extension for [WebClient.ResponseSpec.toEntityList] providing a `toEntityList<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @since 5.3.2
*/
inline fun <reified T : Any> WebClient.ResponseSpec.toEntityList(): Mono<ResponseEntity<List<T>>> =
toEntityList(object : ParameterizedTypeReference<T>() {})
/**
* Extension for [WebClient.ResponseSpec.toEntityFlux] providing a `toEntityFlux<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @since 5.3.2
*/
inline fun <reified T : Any> WebClient.ResponseSpec.toEntityFlux(): Mono<ResponseEntity<Flux<T>>> =
toEntityFlux(object : ParameterizedTypeReference<T>() {})
| apache-2.0 | 5bd57e386a0628750f8583c95986c8db | 37.841584 | 141 | 0.752103 | 4.058976 | false | false | false | false |
zdary/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/VcsActionUsagesCollector.kt | 1 | 1537 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.Change
private const val VCS_GROUP = "vcs"
private const val REFRESH_ACTION_ID = "changes.view.refresh"
fun logRefreshActionPerformed(project: Project,
changesBefore: Collection<Change>,
changesAfter: Collection<Change>,
unversionedBefore: Collection<FilePath>,
unversionedAfter: Collection<FilePath>,
wasUpdatingBefore: Boolean) {
val changes: MutableSet<Change> = (changesBefore union changesAfter).toMutableSet()
changes.removeAll(changesBefore intersect changesAfter)
val unversioned: MutableSet<FilePath> = (unversionedBefore union unversionedAfter).toMutableSet()
unversioned.removeAll(unversionedBefore intersect unversionedAfter)
val data = FeatureUsageData()
.addData("wasUpdatingBefore", wasUpdatingBefore)
.addData("changesDelta", changes.size)
.addData("unversionedDelta", unversioned.size)
FUCounterUsageLogger.getInstance().logEvent(project, VCS_GROUP, REFRESH_ACTION_ID, data)
} | apache-2.0 | 5dffcf86f598e1b6ec26670a7f77ef91 | 47.0625 | 140 | 0.733897 | 4.879365 | false | false | false | false |
leafclick/intellij-community | platform/configuration-store-impl/src/DirectoryBasedStorage.kt | 1 | 9433 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.schemeManager.createDir
import com.intellij.configurationStore.schemeManager.getOrCreateChild
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.isEmpty
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Path
abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: com.intellij.openapi.components.StateSplitter,
protected val pathMacroSubstitutor: PathMacroSubstitutor? = null) : StateStorageBase<StateMap>() {
protected var componentName: String? = null
protected abstract val virtualFile: VirtualFile?
public override fun loadData(): StateMap = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor))
override fun createSaveSessionProducer(): SaveSessionProducer? = null
override fun analyzeExternalChangesAndUpdateIfNeeded(componentNames: MutableSet<in String>) {
// todo reload only changed file, compute diff
val newData = loadData()
storageDataRef.set(newData)
if (componentName != null) {
componentNames.add(componentName!!)
}
}
override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? {
this.componentName = componentName
if (storageData.isEmpty()) {
return null
}
// FileStorageCoreUtil on load check both component and name attributes (critical important for external store case, where we have only in-project artifacts, but not external)
val state = Element(FileStorageCoreUtil.COMPONENT).setAttribute(FileStorageCoreUtil.NAME, componentName)
if (splitter is StateSplitterEx) {
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
splitter.mergeStateInto(state, subState.clone())
}
}
else {
val subElements = SmartList<Element>()
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
subElements.add(subState.clone())
}
if (!subElements.isEmpty()) {
splitter.mergeStatesInto(state, subElements.toTypedArray())
}
}
return state
}
override fun hasState(storageData: StateMap, componentName: String): Boolean = storageData.hasStates()
}
@ApiStatus.Internal
interface DirectoryBasedSaveSessionProducer : SaveSessionProducer {
fun setFileState(fileName: String, componentName: String, element: Element?)
}
open class DirectoryBasedStorage(private val dir: Path,
@Suppress("DEPRECATION") splitter: com.intellij.openapi.components.StateSplitter,
pathMacroSubstitutor: PathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) {
override val isUseVfsForWrite: Boolean
get() = true
@Volatile
private var cachedVirtualFile: VirtualFile? = null
override val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath)
cachedVirtualFile = result
}
return result
}
internal fun setVirtualDir(dir: VirtualFile?) {
cachedVirtualFile = dir
}
override fun createSaveSessionProducer(): SaveSessionProducer? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData())
private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase(), SaveSession, DirectoryBasedSaveSessionProducer {
private var copiedStorageData: MutableMap<String, Any>? = null
private val dirtyFileNames = SmartHashSet<String>()
private var isSomeFileRemoved = false
override fun setSerializedState(componentName: String, element: Element?) {
storage.componentName = componentName
val stateAndFileNameList = if (element.isEmpty()) emptyList() else storage.splitter.splitState(element!!)
if (stateAndFileNameList.isEmpty()) {
if (copiedStorageData != null) {
copiedStorageData!!.clear()
}
else if (!originalStates.isEmpty()) {
copiedStorageData = THashMap()
}
return
}
val existingFiles = THashSet<String>(stateAndFileNameList.size)
for (pair in stateAndFileNameList) {
doSetState(pair.second, pair.first)
existingFiles.add(pair.second)
}
for (key in originalStates.keys()) {
if (existingFiles.contains(key)) {
continue
}
removeFileData(key)
}
}
override fun setFileState(fileName: String, componentName: String, element: Element?) {
storage.componentName = componentName
if (element != null) {
doSetState(fileName, element)
}
else {
removeFileData(fileName)
}
}
private fun removeFileData(fileName: String) {
if (copiedStorageData == null) {
copiedStorageData = originalStates.toMutableMap()
}
isSomeFileRemoved = true
copiedStorageData!!.remove(fileName)
}
private fun doSetState(fileName: String, subState: Element) {
if (copiedStorageData == null) {
copiedStorageData = setStateAndCloneIfNeeded(fileName, subState, originalStates)
if (copiedStorageData != null) {
dirtyFileNames.add(fileName)
}
}
else if (updateState(copiedStorageData!!, fileName, subState)) {
dirtyFileNames.add(fileName)
}
}
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this
override fun save() {
val stateMap = StateMap.fromMap(copiedStorageData!!)
if (copiedStorageData!!.isEmpty()) {
val dir = storage.virtualFile
if (dir != null && dir.exists()) {
dir.delete(this)
}
storage.setStorageData(stateMap)
return
}
if (!dirtyFileNames.isEmpty) {
saveStates(stateMap)
}
if (isSomeFileRemoved) {
val dir = storage.virtualFile
if (dir != null && dir.exists()) {
deleteFiles(dir)
}
}
storage.setStorageData(stateMap)
}
private fun saveStates(states: StateMap) {
var dir = storage.cachedVirtualFile
for (fileName in states.keys()) {
if (!dirtyFileNames.contains(fileName)) {
continue
}
val element = states.getElement(fileName) ?: continue
if (dir == null || !dir.exists()) {
dir = storage.virtualFile
if (dir == null || !dir.exists()) {
dir = createDir(storage.dir, this)
storage.cachedVirtualFile = dir
}
}
try {
val file = dir.getOrCreateChild(fileName, this)
// we don't write xml prolog due to historical reasons (and should not in any case)
val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager
val xmlDataWriter = XmlDataWriter(FileStorageCoreUtil.COMPONENT, listOf(element), mapOf(FileStorageCoreUtil.NAME to storage.componentName!!), macroManager, dir.path)
writeFile(null, this, file, xmlDataWriter, getOrDetectLineSeparator(file) ?: LineSeparator.getSystemLineSeparator(), false)
}
catch (e: IOException) {
LOG.error(e)
}
}
}
private fun deleteFiles(dir: VirtualFile) {
val copiedStorageData = copiedStorageData!!
for (file in dir.children) {
val fileName = file.name
if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData.containsKey(fileName)) {
if (file.isWritable) {
file.delete(this)
}
else {
throw ReadOnlyModificationException(file, null)
}
}
}
}
}
private fun setStorageData(newStates: StateMap) {
storageDataRef.set(newStates)
}
override fun toString() = "${javaClass.simpleName}(file=${virtualFile?.path}, componentName=$componentName)"
}
private fun getOrDetectLineSeparator(file: VirtualFile): LineSeparator? {
if (!file.exists()) {
return null
}
file.detectedLineSeparator?.let {
return LineSeparator.fromString(it)
}
val lineSeparator = detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(file.contentsToByteArray())))
file.detectedLineSeparator = lineSeparator.separatorString
return lineSeparator
} | apache-2.0 | 934300ccc00fa995d9537827331cdafd | 35.145594 | 181 | 0.692569 | 5.149017 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHAccountsPanel.kt | 1 | 16237 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.CollectionListModel
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN
import com.intellij.ui.SimpleTextAttributes.STYLE_UNDERLINE
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.JBList
import com.intellij.util.progress.ProgressVisibilityManager
import com.intellij.util.ui.*
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.CachingGithubUserAvatarLoader
import org.jetbrains.plugins.github.util.GithubImageResizer
import org.jetbrains.plugins.github.util.GithubUIUtil
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
private const val LINK_TAG = "EDIT_LINK"
internal class GHAccountsPanel(private val project: Project,
private val executorFactory: GithubApiRequestExecutor.Factory,
private val avatarLoader: CachingGithubUserAvatarLoader,
private val imageResizer: GithubImageResizer) : BorderLayoutPanel(), Disposable {
private val accountListModel = CollectionListModel<GithubAccountDecorator>().apply {
// disable link handler when there are no errors
addListDataListener(object : ListDataListener {
override fun contentsChanged(e: ListDataEvent?) = setLinkHandlerEnabled(items.any { it.errorText != null })
override fun intervalRemoved(e: ListDataEvent?) {}
override fun intervalAdded(e: ListDataEvent?) {}
})
}
private val accountList = JBList<GithubAccountDecorator>(accountListModel).apply {
val decoratorRenderer = GithubAccountDecoratorRenderer()
cellRenderer = decoratorRenderer
UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(decoratorRenderer))
selectionMode = ListSelectionModel.SINGLE_SELECTION
emptyText.apply {
appendText(IdeBundle.message("github.accounts.added"))
appendSecondaryText(IdeBundle.message("github.accounts.add"), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, { addAccount() })
appendSecondaryText(" (${KeymapUtil.getFirstKeyboardShortcutText(CommonShortcuts.getNew())})", StatusText.DEFAULT_ATTRIBUTES, null)
}
}
private val progressManager = createListProgressManager()
private val errorLinkHandler = createLinkActivationListener()
private var errorLinkHandlerInstalled = false
private var currentTokensMap = mapOf<GithubAccount, String?>()
private val newTokensMap = mutableMapOf<GithubAccount, String>()
init {
addToCenter(ToolbarDecorator.createDecorator(accountList)
.disableUpDownActions()
.setAddAction { addAccount() }
.addExtraAction(object : ToolbarDecorator.ElementActionButton("Set default",
AllIcons.Actions.Checked) {
override fun actionPerformed(e: AnActionEvent) {
if (accountList.selectedValue.projectDefault) return
for (accountData in accountListModel.items) {
if (accountData == accountList.selectedValue) {
accountData.projectDefault = true
accountListModel.contentsChanged(accountData)
}
else if (accountData.projectDefault) {
accountData.projectDefault = false
accountListModel.contentsChanged(accountData)
}
}
}
override fun updateButton(e: AnActionEvent) {
isEnabled = isEnabled && !accountList.selectedValue.projectDefault
}
})
.createPanel())
Disposer.register(this, progressManager)
}
private fun addAccount() {
val dialog = GithubLoginDialog(executorFactory, project, this, ::isAccountUnique)
if (dialog.showAndGet()) {
val githubAccount = GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer())
newTokensMap[githubAccount] = dialog.getToken()
val accountData = GithubAccountDecorator(githubAccount, false)
accountListModel.add(accountData)
loadAccountDetails(accountData)
}
}
private fun editAccount(decorator: GithubAccountDecorator) {
val dialog = GithubLoginDialog(executorFactory, project, this).apply {
withServer(decorator.account.server.toString(), false)
withCredentials(decorator.account.name)
}
if (dialog.showAndGet()) {
decorator.account.name = dialog.getLogin()
newTokensMap[decorator.account] = dialog.getToken()
loadAccountDetails(decorator)
}
}
private fun isAccountUnique(login: String, server: GithubServerPath) =
accountListModel.items.none { it.account.name == login && it.account.server == server }
/**
* Manages link hover and click for [GithubAccountDecoratorRenderer.loadingError]
* Sets the proper cursor and underlines the link on hover
*
* @see [GithubAccountDecorator.errorText]
* @see [GithubAccountDecorator.showReLoginLink]
* @see [GithubAccountDecorator.errorLinkPointedAt]
*/
private fun createLinkActivationListener() = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent) {
val decorator = findDecoratorWithLoginLinkAt(e.point)
if (decorator != null) {
UIUtil.setCursor(accountList, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
}
else {
UIUtil.setCursor(accountList, Cursor.getDefaultCursor())
}
var hasChanges = false
for (item in accountListModel.items) {
val isLinkPointedAt = item == decorator
hasChanges = hasChanges || isLinkPointedAt != item.errorLinkPointedAt
item.errorLinkPointedAt = isLinkPointedAt
}
if (hasChanges) accountListModel.allContentsChanged()
}
override fun mouseClicked(e: MouseEvent) {
findDecoratorWithLoginLinkAt(e.point)?.run(::editAccount)
}
/**
* Checks if mouse is pointed at decorator error link
*
* @return decorator with error link under mouse pointer or null
*/
private fun findDecoratorWithLoginLinkAt(point: Point): GithubAccountDecorator? {
val idx = accountList.locationToIndex(point)
if (idx < 0) return null
val cellBounds = accountList.getCellBounds(idx, idx)
if (!cellBounds.contains(point)) return null
val decorator = accountListModel.getElementAt(idx)
if (decorator?.errorText == null) return null
val rendererComponent = accountList.cellRenderer.getListCellRendererComponent(accountList, decorator, idx, true, true)
rendererComponent.setBounds(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height)
UIUtil.layoutRecursively(rendererComponent)
val rendererRelativeX = point.x - cellBounds.x
val rendererRelativeY = point.y - cellBounds.y
val childComponent = UIUtil.getDeepestComponentAt(rendererComponent, rendererRelativeX, rendererRelativeY)
if (childComponent !is SimpleColoredComponent) return null
val childRelativeX = rendererRelativeX - childComponent.parent.x - childComponent.x
return if (childComponent.getFragmentTagAt(childRelativeX) == LINK_TAG) decorator else null
}
}
private fun setLinkHandlerEnabled(enabled: Boolean) {
if (enabled) {
if (!errorLinkHandlerInstalled) {
accountList.addMouseListener(errorLinkHandler)
accountList.addMouseMotionListener(errorLinkHandler)
errorLinkHandlerInstalled = true
}
}
else if (errorLinkHandlerInstalled) {
accountList.removeMouseListener(errorLinkHandler)
accountList.removeMouseMotionListener(errorLinkHandler)
errorLinkHandlerInstalled = false
}
}
fun loadExistingAccountsDetails() {
for (accountData in accountListModel.items) {
loadAccountDetails(accountData)
}
}
private fun loadAccountDetails(accountData: GithubAccountDecorator) {
val account = accountData.account
val token = newTokensMap[account] ?: currentTokensMap[account]
if (token == null) {
accountListModel.contentsChanged(accountData.apply {
errorText = "Missing access token"
showReLoginLink = true
})
return
}
val executor = executorFactory.create(token)
progressManager.run(object : Task.Backgroundable(project, "Not Visible") {
lateinit var loadedDetails: GithubAuthenticatedUser
var correctScopes: Boolean = true
override fun run(indicator: ProgressIndicator) {
val (details, scopes) = GHSecurityUtil.loadCurrentUserWithScopes(executor, indicator, account.server)
loadedDetails = details
correctScopes = GHSecurityUtil.isEnoughScopes(scopes.orEmpty())
}
override fun onSuccess() {
accountListModel.contentsChanged(accountData.apply {
details = loadedDetails
iconProvider = CachingGithubAvatarIconsProvider(avatarLoader, imageResizer, executor, GithubUIUtil.avatarSize, accountList)
if (correctScopes) {
errorText = null
showReLoginLink = false
}
else {
errorText = "Insufficient security scopes"
showReLoginLink = true
}
})
}
override fun onThrowable(error: Throwable) {
accountListModel.contentsChanged(accountData.apply {
errorText = error.message.toString()
showReLoginLink = error is GithubAuthenticationException
})
}
})
}
private fun createListProgressManager() = object : ProgressVisibilityManager() {
override fun setProgressVisible(visible: Boolean) = accountList.setPaintBusy(visible)
override fun getModalityState() = ModalityState.any()
}
fun setAccounts(accounts: Map<GithubAccount, String?>, defaultAccount: GithubAccount?) {
accountListModel.removeAll()
accountListModel.addAll(0, accounts.keys.map { GithubAccountDecorator(it, it == defaultAccount) })
currentTokensMap = accounts
}
/**
* @return list of accounts and associated tokens if new token was created and selected default account
*/
fun getAccounts(): Pair<Map<GithubAccount, String?>, GithubAccount?> {
return accountListModel.items.associate { it.account to newTokensMap[it.account] } to
accountListModel.items.find { it.projectDefault }?.account
}
fun clearNewTokens() = newTokensMap.clear()
fun isModified(accounts: Set<GithubAccount>, defaultAccount: GithubAccount?): Boolean {
return accountListModel.items.find { it.projectDefault }?.account != defaultAccount ||
accountListModel.items.map { it.account }.toSet() != accounts ||
newTokensMap.isNotEmpty()
}
override fun dispose() {}
}
private class GithubAccountDecoratorRenderer : ListCellRenderer<GithubAccountDecorator>, JPanel() {
private val accountName = JLabel()
private val serverName = JLabel()
private val profilePicture = JLabel()
private val fullName = JLabel()
private val loadingError = SimpleColoredComponent()
/**
* UPDATE [createLinkActivationListener] IF YOU CHANGE LAYOUT
*/
init {
layout = FlowLayout(FlowLayout.LEFT, 0, 0)
border = JBUI.Borders.empty(5, 8)
val namesPanel = JPanel().apply {
layout = GridBagLayout()
border = JBUI.Borders.empty(0, 6, 4, 6)
val bag = GridBag()
.setDefaultInsets(JBUI.insetsRight(UIUtil.DEFAULT_HGAP))
.setDefaultAnchor(GridBagConstraints.WEST)
.setDefaultFill(GridBagConstraints.VERTICAL)
add(fullName, bag.nextLine().next())
add(accountName, bag.next())
add(loadingError, bag.next())
add(serverName, bag.nextLine().coverLine())
}
add(profilePicture)
add(namesPanel)
}
override fun getListCellRendererComponent(list: JList<out GithubAccountDecorator>,
value: GithubAccountDecorator,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
UIUtil.setBackgroundRecursively(this, ListUiUtil.WithTallRow.background(list, isSelected, list.hasFocus()))
val primaryTextColor = ListUiUtil.WithTallRow.foreground(isSelected, list.hasFocus())
val secondaryTextColor = ListUiUtil.WithTallRow.secondaryForeground(list, isSelected)
accountName.apply {
text = value.account.name
setBold(if (value.details?.name == null) value.projectDefault else false)
foreground = if (value.details?.name == null) primaryTextColor else secondaryTextColor
}
serverName.apply {
text = value.account.server.toString()
foreground = secondaryTextColor
}
profilePicture.apply {
icon = value.getIcon()
}
fullName.apply {
text = value.details?.name
setBold(value.projectDefault)
isVisible = value.details?.name != null
foreground = primaryTextColor
}
loadingError.apply {
clear()
value.errorText?.let {
append(it, SimpleTextAttributes.ERROR_ATTRIBUTES)
append(" ")
if (value.showReLoginLink) append("Re-Login",
if (value.errorLinkPointedAt)
SimpleTextAttributes(STYLE_UNDERLINE, JBUI.CurrentTheme.Link.linkColor())
else
SimpleTextAttributes(STYLE_PLAIN, JBUI.CurrentTheme.Link.linkColor()),
LINK_TAG)
}
}
return this
}
companion object {
private fun JLabel.setBold(isBold: Boolean) {
font = font.deriveFont(if (isBold) font.style or Font.BOLD else font.style and Font.BOLD.inv())
}
}
}
/**
* Account + auxillary info + info loading error
*/
private class GithubAccountDecorator(val account: GithubAccount, var projectDefault: Boolean) {
var details: GithubAuthenticatedUser? = null
var iconProvider: GHAvatarIconsProvider? = null
var errorText: String? = null
var showReLoginLink = false
var errorLinkPointedAt = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GithubAccountDecorator
if (account != other.account) return false
return true
}
override fun hashCode(): Int {
return account.hashCode()
}
fun getIcon(): Icon? {
val url = details?.avatarUrl
return iconProvider?.getIcon(url)
}
}
| apache-2.0 | e11e23fbcb315ddf4210dc1928eca973 | 38.992611 | 140 | 0.696865 | 5.388981 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/model/psi/impl/ranges.kt | 10 | 1929 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.psi.impl
import com.intellij.openapi.util.TextRange
import com.intellij.util.SmartList
import com.intellij.util.containers.minimalElements
import java.util.function.Function
/**
* @return collection of items with the same minimal range
* @throws RangeOverlapException if some range overlaps another range
*/
internal fun <X> chooseByRange(items: Collection<X>, offset: Int, itemRange: (X) -> TextRange): Collection<X> {
if (items.size < 2) {
return items
}
val toTheLeftOfOffset = SmartList<X>()
val containingOffset = SmartList<X>()
for (item in items) {
if (itemRange(item).endOffset == offset) {
toTheLeftOfOffset.add(item)
}
else {
containingOffset.add(item)
}
}
if (containingOffset.isNotEmpty()) {
return containingOffset.minimalElements(Comparator.comparing(Function(itemRange), RANGE_CONTAINS_COMPARATOR))
}
else {
return toTheLeftOfOffset.minimalElements(Comparator.comparing(Function(itemRange), RANGE_START_COMPARATOR_INVERTED))
}
}
private val RANGE_CONTAINS_COMPARATOR: Comparator<TextRange> = Comparator { range1: TextRange, range2: TextRange ->
val contains1 = range1.contains(range2)
val contains2 = range2.contains(range1)
when {
contains1 && contains2 -> 0
contains1 && !contains2 -> 1
!contains1 && contains2 -> -1
else -> throw RangeOverlapException(range1, range2)
}
}
private val RANGE_START_COMPARATOR_INVERTED: Comparator<TextRange> = Comparator { range1: TextRange, range2: TextRange ->
range2.startOffset - range1.startOffset // prefer range with greater start offset
}
internal class RangeOverlapException(
range1: TextRange,
range2: TextRange
) : IllegalArgumentException("Overlapping ranges: $range1 and $range2")
| apache-2.0 | 44ddbf648d31d7daeaef3bb08cd1ab67 | 34.722222 | 158 | 0.741317 | 3.904858 | false | false | false | false |
LouisCAD/Splitties | modules/preferences/src/darwinMain/kotlin/splitties/preferences/Changes.kt | 1 | 1845 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.preferences
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.conflate
import platform.Foundation.NSNotificationCenter
import platform.Foundation.NSOperationQueue
import platform.Foundation.NSUserDefaultsDidChangeNotification
import splitties.experimental.NonSymmetricalApi
import splitties.mainthread.isMainThread
@OptIn(ExperimentalCoroutinesApi::class)
internal actual fun PreferencesStorage.changesFlow(
key: String,
emitAfterRegister: Boolean
): Flow<Unit> = channelFlow {
if (this@changesFlow is NSUserDefaultsBackedPreferencesStorage) {
val defaultNotificationCenter = NSNotificationCenter.defaultCenter
val observer = defaultNotificationCenter.addObserverForName(
name = NSUserDefaultsDidChangeNotification,
`object` = userDefaults,
queue = if (isMainThread) NSOperationQueue.mainQueue else null
) {
trySend(Unit)
}
if (emitAfterRegister) trySend(Unit)
awaitClose {
defaultNotificationCenter.removeObserver(observer)
}
} else {
@OptIn(NonSymmetricalApi::class)
val listener = OnSharedPreferenceChangeListener { _, changedKey ->
if (key == changedKey) trySend(Unit)
}
@OptIn(NonSymmetricalApi::class)
registerOnSharedPreferenceChangeListener(listener)
if (emitAfterRegister) trySend(Unit)
awaitClose {
@OptIn(NonSymmetricalApi::class)
unregisterOnSharedPreferenceChangeListener(listener)
}
}
}.conflate()
| apache-2.0 | 995bae4741121cf97e7d74b08e22930b | 35.9 | 109 | 0.732791 | 5.040984 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHIOExecutorLoadingModel.kt | 10 | 2466 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.collaboration.async.CompletableFutureUtil
import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Disposer
import com.intellij.util.concurrency.annotations.RequiresEdt
import java.util.concurrent.CompletableFuture
class GHIOExecutorLoadingModel<T>(parentDisposable: Disposable)
: GHSimpleLoadingModel<T>(), Disposable {
private var currentProgressIndicator: ProgressIndicator? = null
init {
Disposer.register(parentDisposable, this)
}
@RequiresEdt
fun load(progressIndicator: ProgressIndicator, task: (ProgressIndicator) -> T): CompletableFuture<T> {
if (Disposer.isDisposed(this)) return CompletableFuture.failedFuture(ProcessCanceledException())
currentProgressIndicator?.cancel()
currentProgressIndicator = progressIndicator
error = null
loading = true
eventDispatcher.multicaster.onLoadingStarted()
return ProgressManager.getInstance()
.submitIOTask(progressIndicator, task)
.successOnEdt {
if (progressIndicator.isCanceled) return@successOnEdt it
result = it
resultAvailable = true
it
}.errorOnEdt {
if (progressIndicator.isCanceled || CompletableFutureUtil.isCancellation(it)) return@errorOnEdt
error = it
resultAvailable = false
}.completionOnEdt {
if (progressIndicator.isCanceled) return@completionOnEdt
loading = false
currentProgressIndicator = null
eventDispatcher.multicaster.onLoadingCompleted()
}
}
@RequiresEdt
fun reset() {
currentProgressIndicator?.cancel()
currentProgressIndicator = null
loading = false
result = null
resultAvailable = false
error = null
eventDispatcher.multicaster.onReset()
}
override fun dispose() {
reset()
}
} | apache-2.0 | 246dd0ed4d358d21f4f0a017307737aa | 34.753623 | 140 | 0.768856 | 5.224576 | false | false | false | false |
zielu/GitToolBox | src/test/kotlin/zielu/gittoolbox/branch/BranchSubscriberTest.kt | 1 | 2992 | package zielu.gittoolbox.branch
import com.intellij.vcs.log.Hash
import git4idea.GitLocalBranch
import git4idea.repo.GitRepository
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.junit5.MockKExtension
import io.mockk.verify
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import zielu.gittoolbox.cache.RepoInfo
import zielu.gittoolbox.cache.RepoStatus
import zielu.gittoolbox.cache.RepoStatusRemote
@ExtendWith(MockKExtension::class)
internal class BranchSubscriberTest {
@RelaxedMockK
private lateinit var facadeMock: BranchSubscriberFacade
private lateinit var subscriber: BranchSubscriber
@BeforeEach
fun beforeEach() {
subscriber = BranchSubscriber(facadeMock)
}
@Test
fun `should detect switching between branches`(
@MockK repositoryMock: GitRepository
) {
// given
val oldBranch = GitLocalBranch("old_branch")
val newBranch = GitLocalBranch("new_branch")
val oldRepoInfo = RepoInfo.create(
RepoStatus.create(oldBranch, null, RepoStatusRemote.empty()),
null,
listOf()
)
val newRepoInfo = RepoInfo.create(
RepoStatus.create(newBranch, null, RepoStatusRemote.empty()),
null,
listOf()
)
// when
subscriber.onRepoStateChanged(oldRepoInfo, newRepoInfo, repositoryMock)
// then
verify {
facadeMock.branchSwitch(oldBranch, newBranch, repositoryMock)
}
}
@Test
fun `should detect switching from detached to branch`(
@MockK repositoryMock: GitRepository,
@MockK oldHash: Hash
) {
// given
val newBranch = GitLocalBranch("new_branch")
every { oldHash.toShortString() } returns "old-hash"
val oldRepoInfo = RepoInfo.create(
RepoStatus.create(null, oldHash, RepoStatusRemote.empty()),
null,
listOf()
)
val newRepoInfo = RepoInfo.create(
RepoStatus.create(newBranch, null, RepoStatusRemote.empty()),
null,
listOf()
)
// when
subscriber.onRepoStateChanged(oldRepoInfo, newRepoInfo, repositoryMock)
// then
verify {
facadeMock.switchToBranchFromOther(newBranch, repositoryMock)
}
}
@Test
fun `should detect switching from branch to detached`(
@MockK repositoryMock: GitRepository,
@MockK newHash: Hash
) {
// given
val oldBranch = GitLocalBranch("old_branch")
val oldRepoInfo = RepoInfo.create(
RepoStatus.create(oldBranch, null, RepoStatusRemote.empty()),
null,
listOf()
)
every { newHash.toShortString() } returns "new-hash"
val newRepoInfo = RepoInfo.create(
RepoStatus.create(null, newHash, RepoStatusRemote.empty()),
null,
listOf()
)
// when
subscriber.onRepoStateChanged(oldRepoInfo, newRepoInfo, repositoryMock)
// then
verify {
facadeMock.switchFromBranchToOther(oldBranch, repositoryMock)
}
}
}
| apache-2.0 | f9e3c953a3af06122f5e29fa5facec93 | 24.793103 | 75 | 0.710227 | 4.132597 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.kt | 1 | 7232 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.WhatsNewAction
import com.intellij.ide.nls.NlsMessages
import com.intellij.ide.plugins.newui.PluginLogo
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.VerticalGaps
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.JBUI
import javax.swing.JComponent
import javax.swing.JEditorPane
private const val TOOLBOX_URL =
"https://www.jetbrains.com/toolbox-app/?utm_source=product&utm_medium=link&utm_campaign=toolbox_app_in_IDE_updatewindow&utm_content=we_recommend"
class UpdateSettingsConfigurable @JvmOverloads constructor (private val checkNowEnabled: Boolean = true) :
BoundConfigurable(IdeBundle.message("updates.settings.title"), "preferences.updates") {
private lateinit var myLink: JComponent
private lateinit var myLastCheckedLabel: JEditorPane
override fun createPanel(): DialogPanel {
val settings = UpdateSettings.getInstance()
val manager = ExternalUpdateManager.ACTUAL
val channelSelectionLockedMessage = UpdateStrategyCustomization.getInstance().getChannelSelectionLockedMessage()
val appInfo = ApplicationInfo.getInstance()
val channelModel = CollectionComboBoxModel(settings.activeChannels)
return panel {
row(IdeBundle.message("updates.settings.current.version") + ' ' + ApplicationNamesInfo.getInstance().fullProductName + ' ' + appInfo.fullVersion) {
comment(appInfo.build.asString() + ' ' + NlsMessages.formatDateLong(appInfo.buildDate.time))
}.bottomGap(BottomGap.SMALL)
row {
when {
manager != null -> {
comment(IdeBundle.message("updates.settings.external", manager.toolName))
}
channelSelectionLockedMessage != null -> {
checkBox(IdeBundle.message("updates.settings.checkbox"))
.bindSelected(settings.state::isCheckNeeded)
comment(channelSelectionLockedMessage)
}
else -> {
val checkBox = checkBox(IdeBundle.message("updates.settings.checkbox.for"))
.bindSelected(settings.state::isCheckNeeded)
.gap(RightGap.SMALL)
comboBox(channelModel)
.bindItem(getter = { settings.selectedActiveChannel },
setter = { settings.selectedChannelStatus = selectedChannel(it) })
.enabledIf(checkBox.selected)
}
}
}
row {
checkBox(IdeBundle.message("updates.plugins.settings.checkbox"))
.bindSelected(settings.state::isPluginsCheckNeeded)
}
row {
if (checkNowEnabled) {
button(IdeBundle.message("updates.settings.check.now.button")) {
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myLastCheckedLabel))
val settingsCopy = UpdateSettings()
settingsCopy.state.copyFrom(settings.state)
settingsCopy.state.isCheckNeeded = true
settingsCopy.state.isPluginsCheckNeeded = true
settingsCopy.selectedChannelStatus = selectedChannel(channelModel.selected)
UpdateChecker.updateAndShowResult(project, settingsCopy)
updateLastCheckedLabel(settings.lastTimeChecked)
}
}
myLastCheckedLabel = comment("").component
updateLastCheckedLabel(settings.lastTimeChecked)
}.topGap(TopGap.SMALL)
.bottomGap(BottomGap.SMALL)
if (WhatsNewAction.isAvailable()) {
row {
checkBox(IdeBundle.message("updates.settings.show.editor"))
.bindSelected(settings.state::isShowWhatsNewEditor)
}
}
if (settings.ignoredBuildNumbers.isNotEmpty()) {
row {
myLink = link(IdeBundle.message("updates.settings.ignored")) {
val text = settings.ignoredBuildNumbers.joinToString("\n")
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myLink))
val result = Messages.showMultilineInputDialog(project, null, IdeBundle.message("updates.settings.ignored.title"), text, null, null)
if (result != null) {
settings.ignoredBuildNumbers.clear()
settings.ignoredBuildNumbers.addAll(result.split('\n'))
}
}.component
}
}
if (!(manager == ExternalUpdateManager.TOOLBOX || Registry.`is`("ide.hide.toolbox.promo"))) {
group(indent = false) {
customizeSpacingConfiguration(SpacingConfiguration.EMPTY) {
row {
icon(PluginLogo.reloadIcon(AllIcons.Nodes.Toolbox, 40, 40, null))
.verticalAlign(VerticalAlign.TOP)
.customize(customGaps = Gaps(right = JBUI.scale(10)))
panel {
row {
text(IdeBundle.message("updates.settings.recommend.toolbox", TOOLBOX_URL, ExternalUpdateManager.TOOLBOX.toolName))
.bold()
}
row {
label(IdeBundle.message("updates.settings.recommend.toolbox.multiline.description"))
}.customize(customRowGaps = VerticalGaps(top = JBUI.scale(3)))
}
}.customize(customRowGaps = VerticalGaps(top = JBUI.scale(12)))
}
}
}
var wasEnabled = settings.isCheckNeeded || settings.isPluginsCheckNeeded
onApply {
val isEnabled = settings.isCheckNeeded || settings.isPluginsCheckNeeded
if (isEnabled != wasEnabled) {
if (isEnabled) {
UpdateCheckerService.getInstance().queueNextCheck()
}
else {
UpdateCheckerService.getInstance().cancelChecks()
}
wasEnabled = isEnabled
}
}
}
}
private fun selectedChannel(value: ChannelStatus?): ChannelStatus = value ?: ChannelStatus.RELEASE
private fun updateLastCheckedLabel(time: Long): Unit =
if (time > 0) {
myLastCheckedLabel.text = IdeBundle.message("updates.settings.last.check", DateFormatUtil.formatPrettyDateTime(time))
myLastCheckedLabel.toolTipText = DateFormatUtil.formatDate(time) + ' ' + DateFormatUtil.formatTimeWithSeconds(time)
}
else {
myLastCheckedLabel.text = IdeBundle.message("updates.settings.last.check", IdeBundle.message("updates.last.check.never"))
myLastCheckedLabel.toolTipText = null
}
}
| apache-2.0 | 84c422c14d3447b395493a2169127e3a | 42.830303 | 153 | 0.68667 | 4.837458 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/GameLift.kt | 1 | 1874 | package uy.kohesive.iac.model.aws.cloudformation.resources
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationType
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationTypes
import uy.kohesive.iac.model.aws.cloudformation.ResourceProperties
@CloudFormationTypes
object GameLift {
@CloudFormationType("AWS::GameLift::Alias")
data class Alias(
val Description: String? = null,
val Name: String,
val RoutingStrategy: Alias.RoutingStrategyProperty
) : ResourceProperties {
data class RoutingStrategyProperty(
val FleetId: String? = null,
val Message: String? = null,
val Type: String
)
}
@CloudFormationType("AWS::GameLift::Build")
data class Build(
val Name: String? = null,
val StorageLocation: Build.StorageLocationProperty? = null,
val Version: String? = null
) : ResourceProperties {
data class StorageLocationProperty(
val Bucket: String,
val Key: String,
val RoleArn: String
)
}
@CloudFormationType("AWS::GameLift::Fleet")
data class Fleet(
val BuildId: String,
val Description: String? = null,
val DesiredEC2Instances: String,
val EC2InboundPermissions: List<GameLift.Fleet.EC2InboundPermissionProperty>? = null,
val EC2InstanceType: String,
val LogPaths: List<String>? = null,
val MaxSize: String? = null,
val MinSize: String? = null,
val Name: String,
val ServerLaunchParameters: String? = null,
val ServerLaunchPath: String
) : ResourceProperties {
data class EC2InboundPermissionProperty(
val FromPort: String,
val IpRange: String,
val Protocol: String,
val ToPort: String
)
}
} | mit | 49d1c3a1ad1d323a8bb2a732096db7c9 | 27.846154 | 93 | 0.637673 | 4.581907 | false | false | false | false |
tensorflow/examples | lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/MainActivity.kt | 1 | 15753 | /* Copyright 2021 The TensorFlow 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 org.tensorflow.lite.examples.poseestimation
import android.Manifest
import android.app.AlertDialog
import android.app.Dialog
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Process
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.tensorflow.lite.examples.poseestimation.camera.CameraSource
import org.tensorflow.lite.examples.poseestimation.data.Device
import org.tensorflow.lite.examples.poseestimation.ml.*
class MainActivity : AppCompatActivity() {
companion object {
private const val FRAGMENT_DIALOG = "dialog"
}
/** A [SurfaceView] for camera preview. */
private lateinit var surfaceView: SurfaceView
/** Default pose estimation model is 1 (MoveNet Thunder)
* 0 == MoveNet Lightning model
* 1 == MoveNet Thunder model
* 2 == MoveNet MultiPose model
* 3 == PoseNet model
**/
private var modelPos = 1
/** Default device is CPU */
private var device = Device.CPU
private lateinit var tvScore: TextView
private lateinit var tvFPS: TextView
private lateinit var spnDevice: Spinner
private lateinit var spnModel: Spinner
private lateinit var spnTracker: Spinner
private lateinit var vTrackerOption: View
private lateinit var tvClassificationValue1: TextView
private lateinit var tvClassificationValue2: TextView
private lateinit var tvClassificationValue3: TextView
private lateinit var swClassification: SwitchCompat
private lateinit var vClassificationOption: View
private var cameraSource: CameraSource? = null
private var isClassifyPose = false
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
// Permission is granted. Continue the action or workflow in your
// app.
openCamera()
} else {
// Explain to the user that the feature is unavailable because the
// features requires a permission that the user has denied. At the
// same time, respect the user's decision. Don't link to system
// settings in an effort to convince the user to change their
// decision.
ErrorDialog.newInstance(getString(R.string.tfe_pe_request_permission))
.show(supportFragmentManager, FRAGMENT_DIALOG)
}
}
private var changeModelListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
// do nothing
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
changeModel(position)
}
}
private var changeDeviceListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
changeDevice(position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// do nothing
}
}
private var changeTrackerListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
changeTracker(position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// do nothing
}
}
private var setClassificationListener =
CompoundButton.OnCheckedChangeListener { _, isChecked ->
showClassificationResult(isChecked)
isClassifyPose = isChecked
isPoseClassifier()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// keep screen on while app is running
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
tvScore = findViewById(R.id.tvScore)
tvFPS = findViewById(R.id.tvFps)
spnModel = findViewById(R.id.spnModel)
spnDevice = findViewById(R.id.spnDevice)
spnTracker = findViewById(R.id.spnTracker)
vTrackerOption = findViewById(R.id.vTrackerOption)
surfaceView = findViewById(R.id.surfaceView)
tvClassificationValue1 = findViewById(R.id.tvClassificationValue1)
tvClassificationValue2 = findViewById(R.id.tvClassificationValue2)
tvClassificationValue3 = findViewById(R.id.tvClassificationValue3)
swClassification = findViewById(R.id.swPoseClassification)
vClassificationOption = findViewById(R.id.vClassificationOption)
initSpinner()
spnModel.setSelection(modelPos)
swClassification.setOnCheckedChangeListener(setClassificationListener)
if (!isCameraPermissionGranted()) {
requestPermission()
}
}
override fun onStart() {
super.onStart()
openCamera()
}
override fun onResume() {
cameraSource?.resume()
super.onResume()
}
override fun onPause() {
cameraSource?.close()
cameraSource = null
super.onPause()
}
// check if permission is granted or not.
private fun isCameraPermissionGranted(): Boolean {
return checkPermission(
Manifest.permission.CAMERA,
Process.myPid(),
Process.myUid()
) == PackageManager.PERMISSION_GRANTED
}
// open camera
private fun openCamera() {
if (isCameraPermissionGranted()) {
if (cameraSource == null) {
cameraSource =
CameraSource(surfaceView, object : CameraSource.CameraSourceListener {
override fun onFPSListener(fps: Int) {
tvFPS.text = getString(R.string.tfe_pe_tv_fps, fps)
}
override fun onDetectedInfo(
personScore: Float?,
poseLabels: List<Pair<String, Float>>?
) {
tvScore.text = getString(R.string.tfe_pe_tv_score, personScore ?: 0f)
poseLabels?.sortedByDescending { it.second }?.let {
tvClassificationValue1.text = getString(
R.string.tfe_pe_tv_classification_value,
convertPoseLabels(if (it.isNotEmpty()) it[0] else null)
)
tvClassificationValue2.text = getString(
R.string.tfe_pe_tv_classification_value,
convertPoseLabels(if (it.size >= 2) it[1] else null)
)
tvClassificationValue3.text = getString(
R.string.tfe_pe_tv_classification_value,
convertPoseLabels(if (it.size >= 3) it[2] else null)
)
}
}
}).apply {
prepareCamera()
}
isPoseClassifier()
lifecycleScope.launch(Dispatchers.Main) {
cameraSource?.initCamera()
}
}
createPoseEstimator()
}
}
private fun convertPoseLabels(pair: Pair<String, Float>?): String {
if (pair == null) return "empty"
return "${pair.first} (${String.format("%.2f", pair.second)})"
}
private fun isPoseClassifier() {
cameraSource?.setClassifier(if (isClassifyPose) PoseClassifier.create(this) else null)
}
// Initialize spinners to let user select model/accelerator/tracker.
private fun initSpinner() {
ArrayAdapter.createFromResource(
this,
R.array.tfe_pe_models_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spnModel.adapter = adapter
spnModel.onItemSelectedListener = changeModelListener
}
ArrayAdapter.createFromResource(
this,
R.array.tfe_pe_device_name, android.R.layout.simple_spinner_item
).also { adaper ->
adaper.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spnDevice.adapter = adaper
spnDevice.onItemSelectedListener = changeDeviceListener
}
ArrayAdapter.createFromResource(
this,
R.array.tfe_pe_tracker_array, android.R.layout.simple_spinner_item
).also { adaper ->
adaper.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spnTracker.adapter = adaper
spnTracker.onItemSelectedListener = changeTrackerListener
}
}
// Change model when app is running
private fun changeModel(position: Int) {
if (modelPos == position) return
modelPos = position
createPoseEstimator()
}
// Change device (accelerator) type when app is running
private fun changeDevice(position: Int) {
val targetDevice = when (position) {
0 -> Device.CPU
1 -> Device.GPU
else -> Device.NNAPI
}
if (device == targetDevice) return
device = targetDevice
createPoseEstimator()
}
// Change tracker for Movenet MultiPose model
private fun changeTracker(position: Int) {
cameraSource?.setTracker(
when (position) {
1 -> TrackerType.BOUNDING_BOX
2 -> TrackerType.KEYPOINTS
else -> TrackerType.OFF
}
)
}
private fun createPoseEstimator() {
// For MoveNet MultiPose, hide score and disable pose classifier as the model returns
// multiple Person instances.
val poseDetector = when (modelPos) {
0 -> {
// MoveNet Lightning (SinglePose)
showPoseClassifier(true)
showDetectionScore(true)
showTracker(false)
MoveNet.create(this, device, ModelType.Lightning)
}
1 -> {
// MoveNet Thunder (SinglePose)
showPoseClassifier(true)
showDetectionScore(true)
showTracker(false)
MoveNet.create(this, device, ModelType.Thunder)
}
2 -> {
// MoveNet (Lightning) MultiPose
showPoseClassifier(false)
showDetectionScore(false)
// Movenet MultiPose Dynamic does not support GPUDelegate
if (device == Device.GPU) {
showToast(getString(R.string.tfe_pe_gpu_error))
}
showTracker(true)
MoveNetMultiPose.create(
this,
device,
Type.Dynamic
)
}
3 -> {
// PoseNet (SinglePose)
showPoseClassifier(true)
showDetectionScore(true)
showTracker(false)
PoseNet.create(this, device)
}
else -> {
null
}
}
poseDetector?.let { detector ->
cameraSource?.setDetector(detector)
}
}
// Show/hide the pose classification option.
private fun showPoseClassifier(isVisible: Boolean) {
vClassificationOption.visibility = if (isVisible) View.VISIBLE else View.GONE
if (!isVisible) {
swClassification.isChecked = false
}
}
// Show/hide the detection score.
private fun showDetectionScore(isVisible: Boolean) {
tvScore.visibility = if (isVisible) View.VISIBLE else View.GONE
}
// Show/hide classification result.
private fun showClassificationResult(isVisible: Boolean) {
val visibility = if (isVisible) View.VISIBLE else View.GONE
tvClassificationValue1.visibility = visibility
tvClassificationValue2.visibility = visibility
tvClassificationValue3.visibility = visibility
}
// Show/hide the tracking options.
private fun showTracker(isVisible: Boolean) {
if (isVisible) {
// Show tracker options and enable Bounding Box tracker.
vTrackerOption.visibility = View.VISIBLE
spnTracker.setSelection(1)
} else {
// Set tracker type to off and hide tracker option.
vTrackerOption.visibility = View.GONE
spnTracker.setSelection(0)
}
}
private fun requestPermission() {
when (PackageManager.PERMISSION_GRANTED) {
ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) -> {
// You can use the API that requires the permission.
openCamera()
}
else -> {
// You can directly ask for the permission.
// The registered ActivityResultCallback gets the result of this request.
requestPermissionLauncher.launch(
Manifest.permission.CAMERA
)
}
}
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
/**
* Shows an error message dialog.
*/
class ErrorDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
AlertDialog.Builder(activity)
.setMessage(requireArguments().getString(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok) { _, _ ->
// do nothing
}
.create()
companion object {
@JvmStatic
private val ARG_MESSAGE = "message"
@JvmStatic
fun newInstance(message: String): ErrorDialog = ErrorDialog().apply {
arguments = Bundle().apply { putString(ARG_MESSAGE, message) }
}
}
}
}
| apache-2.0 | df4d15d36e48a46d367de8684b4cb434 | 35.634884 | 100 | 0.592966 | 5.228344 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/AddOnViewHolder.kt | 1 | 5240 | package com.kickstarter.ui.viewholders
import android.util.Pair
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.kickstarter.R
import com.kickstarter.databinding.ItemAddOnBinding
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.RewardViewUtils
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.setGone
import com.kickstarter.models.Reward
import com.kickstarter.ui.adapters.RewardItemsAdapter
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.viewmodels.AddOnViewHolderViewModel
import rx.android.schedulers.AndroidSchedulers
class AddOnViewHolder(private val binding: ItemAddOnBinding) : KSViewHolder(binding.root) {
private var viewModel = AddOnViewHolderViewModel.ViewModel(environment())
private val currencyConversionString = context().getString(R.string.About_reward_amount)
private val ksString = requireNotNull(environment().ksString())
init {
val rewardItemAdapter = setUpItemAdapter()
this.viewModel.outputs.conversionIsGone()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe(ViewUtils.setGone(binding.addOnConversionTextView))
this.viewModel.outputs.conversion()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
binding.addOnConversionTextView.text = this.ksString.format(
this.currencyConversionString,
"reward_amount", it
)
}
this.viewModel.outputs.descriptionForNoReward()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.addOnDescriptionTextView.setText(it) }
this.viewModel.outputs.titleForNoReward()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.titleContainer.addOnTitleNoSpannable.setText(it) }
this.viewModel.outputs.descriptionForReward()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.addOnDescriptionTextView.text = it }
this.viewModel.outputs.minimumAmountTitle()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.addOnMinimumTextView.text = it }
this.viewModel.outputs.rewardItems()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { rewardItemAdapter.rewardsItems(it) }
this.viewModel.outputs.rewardItemsAreGone()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe(ViewUtils.setGone(binding.addOnItemsContainer.addOnItemLayout))
this.viewModel.outputs.isAddonTitleGone()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { shouldHideAddonAmount ->
if (shouldHideAddonAmount) {
binding.titleContainer.addOnTitleTextView.visibility = View.GONE
binding.titleContainer.addOnTitleNoSpannable.visibility = View.VISIBLE
} else {
binding.titleContainer.addOnTitleNoSpannable.visibility = View.GONE
binding.titleContainer.addOnTitleTextView.visibility = View.VISIBLE
}
}
this.viewModel.outputs.titleForReward()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.titleContainer.addOnTitleNoSpannable.text = it }
this.viewModel.outputs.titleForAddOn()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.titleContainer.addOnTitleTextView.text = RewardViewUtils.styleTitleForAddOns(context(), it.first, it.second) }
this.viewModel.outputs.localPickUpIsGone()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.rewardItemLocalPickupContainer.localPickupGroup.setGone(it)
}
this.viewModel.outputs.localPickUpName()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.rewardItemLocalPickupContainer.localPickupLocation.text = it
}
}
override fun bindData(data: Any?) {
if (data is (Pair<*, *>)) {
if (data.second is Reward) {
bindReward(data as Pair<ProjectData, Reward>)
}
}
}
private fun bindReward(projectAndReward: Pair<ProjectData, Reward>) {
this.viewModel.inputs.configureWith(projectAndReward.first, projectAndReward.second)
}
private fun setUpItemAdapter(): RewardItemsAdapter {
val rewardItemAdapter = RewardItemsAdapter()
val itemRecyclerView = binding.addOnItemsContainer.addOnItemRecyclerView
itemRecyclerView.adapter = rewardItemAdapter
itemRecyclerView.layoutManager = LinearLayoutManager(context())
return rewardItemAdapter
}
}
| apache-2.0 | a0ef551747ba9534bc9f380fce0778e1 | 39.620155 | 143 | 0.666603 | 5.309017 | false | false | false | false |
JetBrains/xodus | entity-store/src/main/kotlin/jetbrains/exodus/entitystore/EntityIterableCacheStatistics.kt | 1 | 1709 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.entitystore
class EntityIterableCacheStatistics {
var totalJobsEnqueued = 0L
private set
var totalJobsNotQueued = 0L
private set
var totalJobsStarted = 0L
private set
var totalJobsInterrupted = 0L
private set
var totalJobsNotStarted = 0L
private set
var totalCountJobsEnqueued = 0L
private set
var totalHits = 0L
private set
var totalMisses = 0L
private set
var totalCountHits = 0L
private set
var totalCountMisses = 0L
private set
fun incTotalJobsEnqueued() = ++totalJobsEnqueued
fun incTotalJobsNonQueued() = ++totalJobsNotQueued
fun incTotalJobsStarted() = ++totalJobsStarted
fun incTotalJobsInterrupted() = ++totalJobsInterrupted
fun incTotalJobsNotStarted() = ++totalJobsNotStarted
fun incTotalCountJobsEnqueued() = ++totalCountJobsEnqueued
fun incTotalHits() = ++totalHits
fun incTotalMisses() = ++totalMisses
fun incTotalCountHits() = ++totalCountHits
fun incTotalCountMisses() = ++totalCountMisses
} | apache-2.0 | 8f7a635f22a4f8841d4058ddf4589347 | 27.5 | 75 | 0.707431 | 4.473822 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt | 1 | 9038 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pushDown
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.listeners.RefactoringEventData
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewBundle
import com.intellij.usageView.UsageViewDescriptor
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper
import org.jetbrains.kotlin.idea.refactoring.pullUp.*
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor
import org.jetbrains.kotlin.utils.keysToMap
class KotlinPushDownContext(
val sourceClass: KtClass,
val membersToMove: List<KotlinMemberInfo>
) {
val resolutionFacade = sourceClass.getResolutionFacade()
val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(listOf(sourceClass)).bindingContext
val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor
val memberDescriptors = membersToMove.map { it.member }.keysToMap {
when (it) {
is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)!!
else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]!!
}
}
}
class KotlinPushDownProcessor(
project: Project,
sourceClass: KtClass,
membersToMove: List<KotlinMemberInfo>
) : BaseRefactoringProcessor(project) {
private val context = KotlinPushDownContext(sourceClass, membersToMove)
inner class UsageViewDescriptorImpl : UsageViewDescriptor {
override fun getProcessedElementsHeader() = RefactoringBundle.message("push.down.members.elements.header")
override fun getElements() = arrayOf(context.sourceClass)
override fun getCodeReferencesText(usagesCount: Int, filesCount: Int) =
RefactoringBundle.message("classes.to.push.down.members.to", UsageViewBundle.getReferencesString(usagesCount, filesCount))
override fun getCommentReferencesText(usagesCount: Int, filesCount: Int) = null
}
class SubclassUsage(element: PsiElement) : UsageInfo(element)
override fun getCommandName() = PUSH_MEMBERS_DOWN
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>) = UsageViewDescriptorImpl()
override fun getBeforeData() = RefactoringEventData().apply {
addElement(context.sourceClass)
addElements(context.membersToMove.map { it.member }.toTypedArray())
}
override fun getAfterData(usages: Array<out UsageInfo>) = RefactoringEventData().apply {
addElements(usages.mapNotNull { it.element as? KtClassOrObject })
}
override fun findUsages(): Array<out UsageInfo> {
return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false).searchInheritors()
.mapNotNull { it.unwrapped }
.map(::SubclassUsage)
.toTypedArray()
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
val usages = refUsages.get() ?: UsageInfo.EMPTY_ARRAY
if (usages.isEmpty()) {
val message = KotlinBundle.message("text.0.have.no.inheritors.warning", context.sourceClassDescriptor.renderForConflicts())
val answer = Messages.showYesNoDialog(message.capitalize(), PUSH_MEMBERS_DOWN, Messages.getWarningIcon())
if (answer == Messages.NO) return false
}
val conflicts = myProject.runSynchronouslyWithProgress(RefactoringBundle.message("detecting.possible.conflicts"), true) {
runReadAction { analyzePushDownConflicts(context, usages) }
} ?: return false
return showConflicts(conflicts, usages)
}
private fun pushDownToClass(targetClass: KtClassOrObject) {
val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor
val substitutor = getTypeSubstitutor(context.sourceClassDescriptor.defaultType, targetClassDescriptor.defaultType)
?: TypeSubstitutor.EMPTY
members@ for (memberInfo in context.membersToMove) {
val member = memberInfo.member
val memberDescriptor = context.memberDescriptors[member] ?: continue
val movedMember = when (member) {
is KtProperty, is KtNamedFunction -> {
memberDescriptor as CallableMemberDescriptor
moveCallableMemberToClass(
member as KtCallableDeclaration,
memberDescriptor,
targetClass,
targetClassDescriptor,
substitutor,
memberInfo.isToAbstract
)
}
is KtClassOrObject, is KtPsiClassWrapper -> {
if (memberInfo.overrides != null) {
context.sourceClass.getSuperTypeEntryByDescriptor(
memberDescriptor as ClassDescriptor,
context.sourceClassContext
)?.let {
addSuperTypeEntry(it, targetClass, targetClassDescriptor, context.sourceClassContext, substitutor)
}
continue@members
} else {
addMemberToTarget(member, targetClass)
}
}
else -> continue@members
}
applyMarking(movedMember, substitutor, targetClassDescriptor)
}
}
private fun removeOriginalMembers() {
for (memberInfo in context.membersToMove) {
val member = memberInfo.member
val memberDescriptor = context.memberDescriptors[member] ?: continue
when (member) {
is KtProperty, is KtNamedFunction -> {
member as KtCallableDeclaration
memberDescriptor as CallableMemberDescriptor
if (memberDescriptor.modality != Modality.ABSTRACT && memberInfo.isToAbstract) {
if (member.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
member.addModifier(KtTokens.PROTECTED_KEYWORD)
}
makeAbstract(member, memberDescriptor, TypeSubstitutor.EMPTY, context.sourceClass)
member.typeReference?.addToShorteningWaitSet()
} else {
member.delete()
}
}
is KtClassOrObject, is KtPsiClassWrapper -> {
if (memberInfo.overrides != null) {
context.sourceClass.getSuperTypeEntryByDescriptor(
memberDescriptor as ClassDescriptor,
context.sourceClassContext
)?.let {
context.sourceClass.removeSuperTypeListEntry(it)
}
} else {
member.delete()
}
}
}
}
}
override fun performRefactoring(usages: Array<out UsageInfo>) {
val markedElements = ArrayList<KtElement>()
try {
context.membersToMove.forEach {
markedElements += markElements(it.member, context.sourceClassContext, context.sourceClassDescriptor, null)
}
usages.forEach { (it.element as? KtClassOrObject)?.let { pushDownToClass(it) } }
removeOriginalMembers()
} finally {
clearMarking(markedElements)
}
}
} | apache-2.0 | f449a2387dce414f96aa3c4e217f9304 | 44.422111 | 158 | 0.669175 | 5.731135 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsHandler.kt | 1 | 14373 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveHandlerDelegate
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesImpl
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesDialog
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinSelectNestedClassRefactoringDialog
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinNestedClassesDialog
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsDialog
import org.jetbrains.kotlin.idea.util.isEffectivelyActual
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.isTopLevelInFileOrScript
private val defaultHandlerActions = object : MoveKotlinDeclarationsHandlerActions {
override fun showErrorHint(
project: Project,
editor: Editor?,
@NlsContexts.DialogMessage message: String,
@NlsContexts.DialogTitle title: String,
helpId: String?
) {
CommonRefactoringUtil.showErrorHint(project, editor, message, title, helpId)
}
override fun invokeMoveKotlinNestedClassesRefactoring(
project: Project,
elementsToMove: List<KtClassOrObject>,
originalClass: KtClassOrObject,
targetClass: KtClassOrObject,
moveCallback: MoveCallback?
) = MoveKotlinNestedClassesDialog(project, elementsToMove, originalClass, targetClass, null, moveCallback).show()
override fun invokeMoveKotlinTopLevelDeclarationsRefactoring(
project: Project,
elementsToMove: Set<KtNamedDeclaration>,
targetPackageName: String,
targetDirectory: PsiDirectory?,
targetFile: KtFile?,
freezeTargets: Boolean,
moveToPackage: Boolean,
moveCallback: MoveCallback?
) = MoveKotlinTopLevelDeclarationsDialog(
project,
elementsToMove,
targetPackageName,
targetDirectory,
targetFile,
freezeTargets,
moveToPackage,
moveCallback
).show()
override fun invokeKotlinSelectNestedClassChooser(nestedClass: KtClassOrObject, targetContainer: PsiElement?) =
KotlinSelectNestedClassRefactoringDialog.chooseNestedClassRefactoring(nestedClass, targetContainer)
override fun invokeKotlinAwareMoveFilesOrDirectoriesRefactoring(
project: Project,
initialDirectory: PsiDirectory?,
elements: List<PsiFileSystemItem>,
moveCallback: MoveCallback?
) = KotlinAwareMoveFilesOrDirectoriesDialog(project, initialDirectory, elements, moveCallback).show()
}
class MoveKotlinDeclarationsHandler internal constructor(private val handlerActions: MoveKotlinDeclarationsHandlerActions) :
MoveHandlerDelegate() {
private var freezeTargets: Boolean = true
constructor() : this(defaultHandlerActions)
constructor(freezeTargets: Boolean) : this() {
this.freezeTargets = freezeTargets
}
private fun getUniqueContainer(elements: Array<out PsiElement>): PsiElement? {
val allTopLevel = elements.all { isTopLevelInFileOrScript(it) }
val getContainer: (PsiElement) -> PsiElement? =
{ e ->
if (allTopLevel) {
e.containingFile?.parent
} else {
when (e) {
is KtNamedDeclaration -> e.containingClassOrObject ?: e.parent
is KtFile -> e.parent
else -> null
}
}
}
return elements.mapNotNullTo(LinkedHashSet(), getContainer).singleOrNull()
}
private fun KtNamedDeclaration.canMove() = if (this is KtClassOrObject) !isLocal else isTopLevelInFileOrScript(this)
private fun doMoveWithCheck(
project: Project, elements: Array<out PsiElement>, targetContainer: PsiElement?, callback: MoveCallback?, editor: Editor?
): Boolean {
if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, elements.toList(), true)) return false
val container = getUniqueContainer(elements)
if (container == null) {
handlerActions.showErrorHint(
project,
editor,
KotlinBundle.message("text.all.declarations.must.belong.to.the.same.directory.or.class"),
MOVE_DECLARATIONS,
null
)
return false
}
val elementsToSearch = elements.flatMapTo(LinkedHashSet<KtNamedDeclaration>()) {
when (it) {
is KtNamedDeclaration -> listOf(it)
is KtFile -> it.declarations.filterIsInstance<KtNamedDeclaration>()
else -> emptyList()
}
}
// todo: allow moving companion object
if (elementsToSearch.any { it is KtObjectDeclaration && it.isCompanion() }) {
val message = RefactoringBundle.getCannotRefactorMessage(
KotlinBundle.message("text.move.declaration.no.support.for.companion.objects")
)
handlerActions.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null)
return true
}
if (elementsToSearch.any { !it.canMove() }) {
val message =
RefactoringBundle.getCannotRefactorMessage(KotlinBundle.message("text.move.declaration.supports.only.top.levels.and.nested.classes"))
handlerActions.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null)
return true
}
if (elementsToSearch.any { it is KtEnumEntry }) {
val message = RefactoringBundle.getCannotRefactorMessage(KotlinBundle.message("text.move.declaration.no.support.for.enums"))
handlerActions.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null)
return true
}
if (elements.all { it is KtFile }) {
val ktFileElements = elements.map { it as KtFile }
val initialTargetElement = when {
targetContainer is PsiPackage || targetContainer is PsiDirectory -> targetContainer
container is PsiPackage || container is PsiDirectory -> container
else -> null
}
val initialTargetDirectory = MoveFilesOrDirectoriesUtil.resolveToDirectory(project, initialTargetElement)
if (!ApplicationManager.getApplication().isUnitTestMode &&
elementsToSearch.any { it.isExpectDeclaration() || it.isEffectivelyActual() }
) {
val message =
RefactoringBundle.getCannotRefactorMessage(KotlinBundle.message("text.move.declaration.proceed.move.without.mpp.counterparts.text"))
val title =
RefactoringBundle.getCannotRefactorMessage(KotlinBundle.message("text.move.declaration.proceed.move.without.mpp.counterparts.title"))
val proceedWithIncompleteRefactoring = Messages.showYesNoDialog(project, message, title, Messages.getWarningIcon())
if (proceedWithIncompleteRefactoring != Messages.YES) return true
}
handlerActions.invokeKotlinAwareMoveFilesOrDirectoriesRefactoring(
project, initialTargetDirectory, ktFileElements, callback
)
return true
}
when (container) {
is PsiDirectory, is PsiPackage, is KtFile -> {
val targetPackageName = MoveClassesOrPackagesImpl.getInitialTargetPackageName(targetContainer, elements)
val targetDirectory = if (targetContainer != null) {
MoveClassesOrPackagesImpl.getInitialTargetDirectory(targetContainer, elements)
} else null
val targetFile = targetContainer as? KtFile
val moveToPackage = targetContainer !is KtFile
handlerActions.invokeMoveKotlinTopLevelDeclarationsRefactoring(
project,
elementsToSearch,
targetPackageName,
targetDirectory,
targetFile,
freezeTargets,
moveToPackage,
callback
)
}
is KtClassOrObject -> {
if (elementsToSearch.size > 1) {
// todo: allow moving multiple classes to upper level
if (targetContainer !is KtClassOrObject) {
val message =
RefactoringBundle.getCannotRefactorMessage(
KotlinBundle.message("text.moving.multiple.nested.classes.to.top.level.not.supported")
)
handlerActions.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null)
return true
}
@Suppress("UNCHECKED_CAST")
handlerActions.invokeMoveKotlinNestedClassesRefactoring(
project,
elementsToSearch.filterIsInstance<KtClassOrObject>(),
container,
targetContainer,
callback
)
return true
}
handlerActions.invokeKotlinSelectNestedClassChooser(
elementsToSearch.first() as KtClassOrObject,
targetContainer
)
}
else -> throw AssertionError("Unexpected container: ${container.getElementTextWithContext()}")
}
return true
}
private fun canMove(elements: Array<out PsiElement>, targetContainer: PsiElement?, editorMode: Boolean): Boolean {
if (targetContainer != null && !isValidTarget(targetContainer, elements)) return false
val container = getUniqueContainer(elements) ?: return false
if (container is KtClassOrObject && targetContainer != null && targetContainer !is KtClassOrObject && elements.size > 1) {
return false
}
return elements.all { e ->
when {
e is KtClass || e is KtObjectDeclaration && !e
.isObjectLiteral() || e is KtNamedFunction || e is KtProperty || e is KtTypeAlias ->
(editorMode || (e as KtNamedDeclaration).canMove()) && e.canRefactor()
e is KtFile ->
e.declarations.any { it is KtNamedDeclaration } && e.canRefactor()
else ->
false
}
}
}
private fun tryToMoveImpl(
element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor?
): Boolean {
val elementsToMove = element.unwrapped?.let { arrayOf(it) } ?: PsiElement.EMPTY_ARRAY
val targetContainer = dataContext?.let { context -> LangDataKeys.TARGET_PSI_ELEMENT.getData(context) }
return canMove(elementsToMove, targetContainer, true) && doMoveWithCheck(project, elementsToMove, targetContainer, null, editor)
}
private fun recursivelyTryToMove(
element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor?
): Boolean {
return tryToMoveImpl(element, project, dataContext, reference, editor)
|| element.parent?.let { recursivelyTryToMove(it, project, dataContext, reference, editor) } ?: false
}
override fun canMove(elements: Array<out PsiElement>, targetContainer: PsiElement?, reference: PsiReference?): Boolean {
return canMove(elements, targetContainer, false)
}
override fun isValidTarget(psiElement: PsiElement?, sources: Array<out PsiElement>): Boolean {
return psiElement is PsiPackage
|| (psiElement is PsiDirectory && psiElement.getPackage() != null)
|| psiElement is KtFile
|| (psiElement is KtClassOrObject
&& !(psiElement.hasModifier(KtTokens.ANNOTATION_KEYWORD))
&& !sources.any { it.parent is KtFile })
}
override fun doMove(project: Project, elements: Array<out PsiElement>, targetContainer: PsiElement?, callback: MoveCallback?) {
doMoveWithCheck(project, elements, targetContainer, callback, null)
}
override fun tryToMove(
element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor?
): Boolean {
if (element is PsiWhiteSpace && element.textOffset > 0) {
val prevElement = element.containingFile.findElementAt(element.textOffset - 1)
return prevElement != null
&& recursivelyTryToMove(prevElement, project, dataContext, reference, editor)
}
return tryToMoveImpl(element, project, dataContext, reference, editor)
}
}
private val MOVE_DECLARATIONS: String get() = KotlinBundle.message("text.move.declarations")
| apache-2.0 | 504436b890ab7d9824ea6e4f254a5d6c | 44.920128 | 158 | 0.659709 | 5.746901 | false | false | false | false |
siosio/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalSystemJdkComboBoxUtil.kt | 1 | 2839 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("ExternalSystemJdkComboBoxUtil")
@file:ApiStatus.Internal
package com.intellij.openapi.externalSystem.service.ui
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.*
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.roots.ui.configuration.SdkComboBox
import com.intellij.openapi.roots.ui.configuration.SdkListItem
import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider
import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider.SdkInfo
import org.jetbrains.annotations.ApiStatus
private val RESOLVING_JDK by lazy { ExternalSystemBundle.message("external.system.java.in.resolving") }
fun SdkComboBox.getSelectedJdkReference(sdkLookupProvider: SdkLookupProvider): String? {
return sdkLookupProvider.resolveJdkReference(selectedItem)
}
fun SdkComboBox.setSelectedJdkReference(sdkLookupProvider: SdkLookupProvider, jdkReference: String?) {
when (jdkReference) {
USE_PROJECT_JDK -> selectedItem = showProjectSdkItem()
USE_JAVA_HOME -> selectedItem = addJdkReferenceItem(JAVA_HOME, getJavaHome())
null -> when (val sdkInfo = sdkLookupProvider.getSdkInfo()) {
SdkInfo.Undefined -> selectedItem = showNoneSdkItem()
SdkInfo.Unresolved -> selectedItem = addJdkReferenceItem(RESOLVING_JDK, null, true)
is SdkInfo.Resolving -> selectedItem = addJdkReferenceItem(sdkInfo.name, sdkInfo.versionString, true)
is SdkInfo.Resolved -> setSelectedSdk(sdkInfo.name)
}
else -> return setSelectedSdk(jdkReference)
}
}
fun SdkComboBox.addJdkReferenceItem(name: String, homePath: String?): SdkListItem {
val type = getJavaSdkType()
val isValid = isValidJdk(homePath)
val versionString = if (isValid && homePath != null) type.getVersionString(homePath) else null
return addSdkReferenceItem(type, name, versionString, isValid)
}
fun SdkComboBox.addJdkReferenceItem(name: String, versionString: String?, isValid: Boolean): SdkListItem {
val type = getJavaSdkType()
return addSdkReferenceItem(type, name, versionString, isValid)
}
fun SdkLookupProvider.resolveJdkReference(item: SdkListItem?): String? {
return when (item) {
is SdkListItem.ProjectSdkItem -> USE_PROJECT_JDK
is SdkListItem.SdkItem -> item.sdk.name
is SdkListItem.InvalidSdkItem -> item.sdkName
is SdkListItem.SdkReferenceItem -> when (item.name) {
JAVA_HOME -> USE_JAVA_HOME
RESOLVING_JDK -> getSdk()?.name
else -> when (val sdkInfo = getSdkInfo()) {
SdkInfo.Undefined -> null
SdkInfo.Unresolved -> null
is SdkInfo.Resolving -> null
is SdkInfo.Resolved -> sdkInfo.name
}
}
else -> null
}
}
| apache-2.0 | b83925d147b5692d783ee689d7ffc964 | 43.359375 | 140 | 0.764001 | 4.394737 | false | true | false | false |
kivensolo/UiUsingListView | module-Home/src/main/java/com/zeke/home/api/AndroidDemoProvider.kt | 1 | 6608 | package com.zeke.home.api
import android.content.Context
import android.content.res.AssetManager
import android.os.AsyncTask
import android.util.JsonReader
import android.widget.Toast
import com.zeke.home.entity.DemoGroup
import com.zeke.home.entity.DemoSample
import com.zeke.kangaroo.utils.ZLog
import com.zeke.network.response.IRequestResponse
import org.jetbrains.annotations.NotNull
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
/**
* author:KingZ
* date:2020/2/15
* description:Demo样例数据的数据提供实现类,
* 负责Demo数据配置文件解析和数据返回
*/
class AndroidDemoProvider : DataApiService<MutableList<DemoGroup>> {
companion object {
private val TAG = AndroidDemoProvider::class.java.simpleName
private lateinit var mCallBack: IRequestResponse<MutableList<DemoGroup>>
}
/**
* 获取Demo展示数据信息
* @param context Context
* @param callback DataApiService.IDataResponse
*/
override fun requestData(context: Context,@NotNull callback: IRequestResponse<MutableList<DemoGroup>>) {
mCallBack = callback
val assetManager = context.assets
val uris: Array<String>
val uriList = ArrayList<String>()
checkMainList(assetManager, uriList, context)
// 显式指定数组的长度,数组元素全部被初始化为null。
// 相当于Java数组的动态初始化。
// uris = arrayOfNulls<String?>(uriList.size)
uris = uriList.toTypedArray()
// 同java Arrays.sort(uris);
uris.sort()
// AsyncTask 异步加载列表数据
SampleListLoader(context).execute(uris[0])
}
/**
* 检查首页数据列表
*/
private fun checkMainList(assetManager: AssetManager, uriList: ArrayList<String>, context: Context) {
try {
for (asset in assetManager.list("")) {
if (asset.endsWith(".mainlist.json")) {
//uriList.add("asset:///" + asset);
uriList.add(asset)
}
}
} catch (e: IOException) {
Toast.makeText(context,
"One or more lists failed to load !!!",
Toast.LENGTH_LONG)
.show()
}
}
class SampleListLoader(var ctx:Context)
: AsyncTask<String, Void, MutableList<DemoGroup>>() {
private var sawError: Boolean = false
override fun doInBackground(vararg parms: String?): MutableList<DemoGroup> {
val demoGroup = ArrayList<DemoGroup>()
for (uri in parms) {
try {
val inputStream = ctx.assets.open(uri)
readSampleGroups(JsonReader(InputStreamReader(inputStream,
"UTF-8")), demoGroup)
} catch (e: Exception) {
ZLog.e(TAG, "Error loading sample list: $uri", e)
sawError = true
}
}
return demoGroup
}
// 等同于Java的 throws IOException
@Throws(IOException::class)
private fun readSampleGroups(
reader: JsonReader,
groups: MutableList<DemoGroup>) {
reader.beginArray()
while (reader.hasNext()) {
readSampleGroup(reader, groups)
}
reader.endArray()
}
@Throws(IOException::class)
private fun readSampleGroup(
reader: JsonReader,
groups: MutableList<DemoGroup>) {
var groupName = ""
var groupDesc = ""
val samples = ArrayList<DemoSample>()
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
// switch-case
when (name) {
"name" -> groupName = reader.nextString()
"samples" -> {
reader.beginArray()
while (reader.hasNext()) {
samples.add(readEntry(reader))
}
reader.endArray()
}
"desc" -> groupDesc = reader.nextString()
else -> {
// throw ParserException("Unsupported attribute name: $name")
ZLog.e("Main-Demo","不支持的属性数据")
}
}
}
reader.endObject()
val group = getGroup(groupName,groupDesc, groups)
group.samples.addAll(samples)
}
@Throws(IOException::class)
private fun readEntry(reader: JsonReader): DemoSample {
var sampleName: String? = null
var clazzName: String? = null
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (name) {
"name" -> sampleName = reader.nextString()
"class" -> clazzName = reader.nextString()
else -> {
// throw ParserException("Unsupported attribute name: $name")
ZLog.e("Main-Demo","不支持的属性数据")
}
}
}
reader.endObject()
return DemoSample(sampleName, clazzName)
}
/**
* 根据分组名称获取到改组的Demo数据的分组数据
*/
private fun getGroup(groupName: String,
groupDesc: String,
groups: MutableList<DemoGroup>): DemoGroup {
for (i in groups.indices) {
if (groupName == groups[i].title) {
return groups[i]
}
}
val group = DemoGroup(groupName, groupDesc)
groups.add(group)
return group
}
override fun onPostExecute(result: MutableList<DemoGroup>) {
super.onPostExecute(result)
mCallBack.onSuccess(result)
}
}
// private fun onSampleGroups(ctx:Context,
// groups: List<SampleGroup>,
// sawError: Boolean) {
// if (sawError) {
// Toast.makeText(ctx, "One or more page lists failed to load.", Toast.LENGTH_LONG)
// .show()
// }
// // expandAdapter.setSampleGroups(groups)
// }
} | gpl-2.0 | 9e9a57163d4d1badc09006d1bfbb172f | 31.906736 | 108 | 0.522047 | 4.828897 | false | false | false | false |
rustamgaifullin/MP | app/src/test/kotlin/io/rg/mp/drive/BalanceServiceTest.kt | 1 | 1598 | package io.rg.mp.drive
import com.google.api.client.testing.http.MockLowLevelHttpResponse
import io.rg.mp.balance
import io.rg.mp.drive.data.Balance
import io.rg.mp.emptyBalance
import io.rg.mp.mockResponse
import io.rg.mp.mockSheetClient
import io.rg.mp.partialBalance
import org.junit.Test
import java.util.LinkedList
class BalanceServiceTest {
@Test
fun `should return balance response`() {
val responses = LinkedList<MockLowLevelHttpResponse>()
responses.add(mockResponse(balance()))
val sut = BalanceService(mockSheetClient(responses))
sut.retrieve("any").toFlowable().test()
.assertNoErrors()
.assertValue {
it == Balance("2000", "200", "1000")
}
}
@Test
fun `should return empty balance`() {
val responses = LinkedList<MockLowLevelHttpResponse>()
responses.add(mockResponse(emptyBalance()))
val sut = BalanceService(mockSheetClient(responses))
sut.retrieve("any").toFlowable().test()
.assertNoErrors()
.assertValue {
it == Balance()
}
}
@Test
fun `should return partial balance`() {
val responses = LinkedList<MockLowLevelHttpResponse>()
responses.add(mockResponse(partialBalance()))
val sut = BalanceService(mockSheetClient(responses))
sut.retrieve("any").toFlowable().test()
.assertNoErrors()
.assertValue {
it == Balance(actual = "200")
}
}
} | mit | 944ce973437fa7abf9c1319be03db787 | 28.072727 | 66 | 0.606383 | 4.686217 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/codeStyleUtils.kt | 6 | 1457 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.formatter
import com.intellij.application.options.CodeStyle
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
val CodeStyleSettings.kotlinCommonSettings: KotlinCommonCodeStyleSettings
get() = getCommonSettings(KotlinLanguage.INSTANCE) as KotlinCommonCodeStyleSettings
val CodeStyleSettings.kotlinCustomSettings: KotlinCodeStyleSettings
get() = getCustomSettings(KotlinCodeStyleSettings::class.java)
fun CodeStyleSettings.kotlinCodeStyleDefaults(): String? = kotlinCustomSettings.CODE_STYLE_DEFAULTS?.takeIf { customStyleId ->
customStyleId == kotlinCommonSettings.CODE_STYLE_DEFAULTS
}
fun CodeStyleSettings.supposedKotlinCodeStyleDefaults(): String? =
kotlinCustomSettings.CODE_STYLE_DEFAULTS ?: kotlinCommonSettings.CODE_STYLE_DEFAULTS
val PsiFile.kotlinCommonSettings: KotlinCommonCodeStyleSettings get() = CodeStyle.getSettings(this).kotlinCommonSettings
val PsiFile.kotlinCustomSettings: KotlinCodeStyleSettings get() = CodeStyle.getSettings(this).kotlinCustomSettings
val PsiFile.rightMarginOrDefault: Int get() = CodeStyle.getSettings(this).getRightMargin(KotlinLanguage.INSTANCE) | apache-2.0 | eeebafd149265f834b014319d42fc049 | 55.076923 | 158 | 0.843514 | 5.041522 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CurrentBranchComponent.kt | 5 | 4503 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangesUtil.getFilePath
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.ColorUtil
import com.intellij.ui.JBColor
import com.intellij.ui.JBColor.namedColor
import com.intellij.ui.components.JBLabel
import com.intellij.util.EventDispatcher
import com.intellij.util.ui.JBUI.emptySize
import com.intellij.vcs.branch.BranchData
import com.intellij.vcs.branch.BranchPresentation.getText
import com.intellij.vcs.branch.BranchPresentation.getTooltip
import com.intellij.vcs.branch.BranchStateProvider
import com.intellij.vcsUtil.VcsUtil.getFilePath
import java.awt.Color
import java.awt.Dimension
import java.beans.PropertyChangeListener
import javax.swing.JTree.TREE_MODEL_PROPERTY
import javax.swing.UIManager
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
import kotlin.properties.Delegates.observable
class CurrentBranchComponent(private val tree: ChangesTree,
private val pathsProvider: () -> Iterable<FilePath>) : JBLabel(), Disposable {
private val changeEventDispatcher = EventDispatcher.create(ChangeListener::class.java)
private var branches: Set<BranchData> by observable(setOf()) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
text = getText(newValue)
toolTipText = getTooltip(newValue)
isVisible = newValue.isNotEmpty()
changeEventDispatcher.multicaster.stateChanged(ChangeEvent(this))
}
private val isGroupedByRepository: Boolean
get() {
val groupingSupport = tree.groupingSupport
return groupingSupport.isAvailable(REPOSITORY_GROUPING) && groupingSupport[REPOSITORY_GROUPING]
}
val project: Project get() = tree.project
init {
isVisible = false
icon = AllIcons.Vcs.Branch
foreground = TEXT_COLOR
val treeChangeListener = PropertyChangeListener { e ->
if (e.propertyName == TREE_MODEL_PROPERTY) {
refresh()
}
}
tree.addPropertyChangeListener(treeChangeListener)
Disposer.register(this, Disposable { tree.removePropertyChangeListener(treeChangeListener) })
refresh()
}
fun addChangeListener(block: () -> Unit, parent: Disposable) =
changeEventDispatcher.addListener(ChangeListener { block() }, parent)
override fun getPreferredSize(): Dimension? = if (isVisible) super.getPreferredSize() else emptySize()
override fun dispose() = Unit
private fun refresh() {
val needShowBranch = !isGroupedByRepository
branches =
if (needShowBranch) pathsProvider().mapNotNull { getCurrentBranch(project, it) }.toSet()
else emptySet()
}
companion object {
private val BACKGROUND_BALANCE
get() = namedDouble("VersionControl.RefLabel.backgroundBrightness", 0.08)
private val BACKGROUND_BASE_COLOR = namedColor("VersionControl.RefLabel.backgroundBase", JBColor(Color.BLACK, Color.WHITE))
@JvmField
val TEXT_COLOR: JBColor = namedColor("VersionControl.RefLabel.foreground", JBColor(Color(0x7a7a7a), Color(0x909090)))
@Suppress("SameParameterValue")
private fun namedDouble(name: String, default: Double): Double {
return when (val value = UIManager.get(name)) {
is Double -> value
is Int -> value.toDouble()
is String -> value.toDoubleOrNull() ?: default
else -> default
}
}
fun getCurrentBranch(project: Project, change: Change) = getCurrentBranch(project, getFilePath(change))
fun getCurrentBranch(project: Project, file: VirtualFile) = getCurrentBranch(project, getFilePath(file))
fun getCurrentBranch(project: Project, path: FilePath) =
getProviders(project).asSequence().mapNotNull { it.getCurrentBranch(path) }.firstOrNull()
@JvmStatic
fun getBranchPresentationBackground(background: Color) = ColorUtil.mix(background, BACKGROUND_BASE_COLOR, BACKGROUND_BALANCE)
private fun getProviders(project: Project) = BranchStateProvider.EP_NAME.getExtensionList(project)
}
}
| apache-2.0 | b19c85c5ee921e19766814d9c954b3d6 | 37.487179 | 140 | 0.759716 | 4.51655 | false | false | false | false |
idea4bsd/idea4bsd | platform/platform-api/src/com/intellij/util/EncryptionSupport.kt | 17 | 2233 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util
import java.nio.ByteBuffer
import java.security.Key
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
// opposite to PropertiesEncryptionSupport, we store iv length, but not body length
open class EncryptionSupport(private val key: Key = SecretKeySpec(generateAesKey(), "AES")) {
open fun encrypt(data: ByteArray, size: Int = data.size) = encrypt(data, size, key)
open fun decrypt(data: ByteArray) = decrypt(data, key)
}
fun generateAesKey(): ByteArray {
// http://security.stackexchange.com/questions/14068/why-most-people-use-256-bit-encryption-instead-of-128-bit
val bytes = ByteArray(16)
SecureRandom().nextBytes(bytes)
return bytes
}
private fun encrypt(message: ByteArray, size: Int, key: Key): ByteArray {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val body = cipher.doFinal(message, 0, size)
val iv = cipher.iv
val byteBuffer = ByteBuffer.wrap(ByteArray(4 + iv.size + body.size))
byteBuffer.putInt(iv.size)
byteBuffer.put(iv)
byteBuffer.put(body)
return byteBuffer.array()
}
private fun decrypt(data: ByteArray, key: Key): ByteArray {
val byteBuffer = ByteBuffer.wrap(data)
@Suppress("UsePropertyAccessSyntax")
val ivLength = byteBuffer.getInt()
val ciph = Cipher.getInstance("AES/CBC/PKCS5Padding")
ciph.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(data, byteBuffer.position(), ivLength))
val dataOffset = byteBuffer.position() + ivLength
return ciph.doFinal(data, dataOffset, data.size - dataOffset)
} | apache-2.0 | bad3cb3f156d3177a26a349f5a345d08 | 36.233333 | 112 | 0.753695 | 3.85 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/EnumClassLowering.kt | 1 | 15646 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.ClassLoweringPass
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.lower.EnumWhenLowering
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlockBody
import org.jetbrains.kotlin.backend.common.runOnFilePostfix
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.DECLARATION_ORIGIN_ENUM
import org.jetbrains.kotlin.backend.konan.llvm.IntrinsicType
import org.jetbrains.kotlin.backend.konan.llvm.tryGetIntrinsicType
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrPropertyImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin.ARGUMENTS_REORDERING_FOR_CALL
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrPropertySymbolImpl
import org.jetbrains.kotlin.ir.types.classifierOrNull
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
private class EnumSyntheticFunctionsBuilder(val context: Context) {
fun buildValuesExpression(startOffset: Int, endOffset: Int,
enumClass: IrClass): IrExpression {
val loweredEnum = context.specialDeclarationsFactory.getLoweredEnum(enumClass)
return irCall(startOffset, endOffset, genericValuesSymbol.owner, listOf(enumClass.defaultType))
.apply {
putValueArgument(0, loweredEnum.getValuesField(startOffset, endOffset))
}
}
fun buildValueOfExpression(startOffset: Int, endOffset: Int,
enumClass: IrClass,
value: IrExpression): IrExpression {
val loweredEnum = context.specialDeclarationsFactory.getLoweredEnum(enumClass)
return irCall(startOffset, endOffset, genericValueOfSymbol.owner, listOf(enumClass.defaultType))
.apply {
putValueArgument(0, value)
putValueArgument(1, loweredEnum.getValuesField(startOffset, endOffset))
}
}
private val genericValueOfSymbol = context.ir.symbols.valueOfForEnum
private val genericValuesSymbol = context.ir.symbols.valuesForEnum
}
internal class EnumUsageLowering(val context: Context)
: IrElementTransformerVoid(), FileLoweringPass {
private val enumSyntheticFunctionsBuilder = EnumSyntheticFunctionsBuilder(context)
override fun lower(irFile: IrFile) {
visitFile(irFile)
}
override fun visitGetEnumValue(expression: IrGetEnumValue): IrExpression {
val entry = expression.symbol.owner
return loadEnumEntry(
expression.startOffset,
expression.endOffset,
entry.parentAsClass,
entry.name
)
}
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
val intrinsicType = tryGetIntrinsicType(expression)
if (intrinsicType != IntrinsicType.ENUM_VALUES && intrinsicType != IntrinsicType.ENUM_VALUE_OF)
return expression
val startOffset = expression.startOffset
val endOffset = expression.endOffset
val irClassSymbol = expression.getTypeArgument(0)!!.classifierOrNull as? IrClassSymbol
if (irClassSymbol == null || irClassSymbol == context.ir.symbols.enum) {
// Either a type parameter or a type parameter erased to 'Enum'.
return irCall(startOffset, endOffset, context.ir.symbols.throwIllegalStateException.owner, emptyList())
}
val irClass = irClassSymbol.owner
assert (irClass.kind == ClassKind.ENUM_CLASS)
return if (intrinsicType == IntrinsicType.ENUM_VALUES) {
enumSyntheticFunctionsBuilder.buildValuesExpression(startOffset, endOffset, irClass)
} else {
val value = expression.getValueArgument(0)!!
enumSyntheticFunctionsBuilder.buildValueOfExpression(startOffset, endOffset, irClass, value)
}
}
private fun loadEnumEntry(startOffset: Int, endOffset: Int, enumClass: IrClass, name: Name): IrExpression {
val loweredEnum = context.specialDeclarationsFactory.getLoweredEnum(enumClass)
val ordinal = loweredEnum.entriesMap.getValue(name)
return IrCallImpl.fromSymbolDescriptor(
startOffset, endOffset, enumClass.defaultType,
loweredEnum.itemGetterSymbol.owner.symbol,
typeArgumentsCount = 0,
loweredEnum.itemGetterSymbol.owner.valueParameters.size
).apply {
dispatchReceiver = IrCallImpl(startOffset, endOffset, loweredEnum.valuesGetter.returnType,
loweredEnum.valuesGetter.symbol, loweredEnum.valuesGetter.typeParameters.size,
loweredEnum.valuesGetter.valueParameters.size)
putValueArgument(0, IrConstImpl.int(startOffset, endOffset, context.irBuiltIns.intType, ordinal))
}
}
}
internal class EnumClassLowering(val context: Context) : FileLoweringPass {
fun run(irFile: IrFile) {
// EnumWhenLowering should be performed before EnumUsageLowering because
// the latter performs lowering of IrGetEnumValue
EnumWhenLowering(context).lower(irFile)
lower(irFile)
EnumUsageLowering(context).lower(irFile)
}
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitClass(declaration: IrClass): IrStatement {
declaration.transformChildrenVoid()
if (declaration.kind == ClassKind.ENUM_CLASS)
EnumClassTransformer(declaration).run()
return declaration
}
})
}
private inner class EnumClassTransformer(val irClass: IrClass) {
private val loweredEnum = context.specialDeclarationsFactory.getInternalLoweredEnum(irClass)
private val enumSyntheticFunctionsBuilder = EnumSyntheticFunctionsBuilder(context)
fun run() {
pullUpEnumEntriesClasses()
createImplObject()
}
private fun pullUpEnumEntriesClasses() {
irClass.declarations.transformFlat { declaration ->
if (declaration is IrEnumEntry) {
val correspondingClass = declaration.correspondingClass
declaration.correspondingClass = null
listOfNotNull(declaration, correspondingClass)
} else null
}
}
private fun createImplObject() {
val implObject = loweredEnum.implObject
val enumEntries = mutableListOf<IrEnumEntry>()
var i = 0
while (i < irClass.declarations.size) {
val declaration = irClass.declarations[i]
var delete = false
when (declaration) {
is IrEnumEntry -> {
enumEntries.add(declaration)
delete = true
}
is IrFunction -> {
val body = declaration.body
if (body is IrSyntheticBody) {
when (body.kind) {
IrSyntheticBodyKind.ENUM_VALUEOF ->
declaration.body = createSyntheticValueOfMethodBody(declaration)
IrSyntheticBodyKind.ENUM_VALUES ->
declaration.body = createSyntheticValuesMethodBody(declaration)
}
}
}
}
if (delete)
irClass.declarations.removeAt(i)
else
++i
}
implObject.declarations += createSyntheticValuesPropertyDeclaration(enumEntries)
irClass.declarations += implObject
}
private val createUninitializedInstance = context.ir.symbols.createUninitializedInstance.owner
private fun createSyntheticValuesPropertyDeclaration(enumEntries: List<IrEnumEntry>): IrProperty {
val startOffset = irClass.startOffset
val endOffset = irClass.endOffset
val implObject = loweredEnum.implObject
val constructor = implObject.constructors.single()
val irValuesInitializer = context.createArrayOfExpression(
startOffset, endOffset,
irClass.defaultType,
enumEntries
.sortedBy { it.name }
.map {
val initializer = it.initializerExpression?.expression
val entryConstructorCall = when {
initializer is IrConstructorCall -> initializer
initializer is IrBlock && initializer.origin == ARGUMENTS_REORDERING_FOR_CALL ->
initializer.statements.last() as IrConstructorCall
else -> error("Unexpected initializer: $initializer")
}
val entryClass = entryConstructorCall.symbol.owner.constructedClass
irCall(startOffset, endOffset,
createUninitializedInstance,
listOf(entryClass.defaultType)
)
}
)
val irField = loweredEnum.valuesField
context.createIrBuilder(constructor.symbol).run {
(constructor.body as IrBlockBody).statements +=
irSetField(irGet(implObject.thisReceiver!!), irField, irValuesInitializer)
}
val getter = loweredEnum.valuesGetter
context.createIrBuilder(getter.symbol).run {
getter.body = irBlockBody(irClass) { +irReturn(irGetField(irGetObject(implObject.symbol), irField)) }
}
createValuesPropertyInitializer(enumEntries)
return with(loweredEnum.valuesField.descriptor) {
IrPropertyImpl(
startOffset, endOffset, DECLARATION_ORIGIN_ENUM, IrPropertySymbolImpl(this),
name, visibility, modality, isVar, isConst, isLateInit, isDelegated, isExternal
).apply {
this.backingField = irField
this.getter = getter
this.parent = implObject
}
}
}
private val initInstanceSymbol = context.ir.symbols.initInstance
private val arrayGetSymbol = context.ir.symbols.array.functions.single { it.owner.name == Name.identifier("get") }
private val arrayType = context.ir.symbols.array.typeWith(irClass.defaultType)
private fun createValuesPropertyInitializer(enumEntries: List<IrEnumEntry>) {
val startOffset = irClass.startOffset
val endOffset = irClass.endOffset
fun IrBlockBuilder.initInstanceCall(instance: IrCall, constructor: IrConstructorCall): IrCall =
irCall(initInstanceSymbol).apply {
putValueArgument(0, instance)
putValueArgument(1, constructor)
}
val implObject = loweredEnum.implObject
val constructor = implObject.constructors.single()
val irBuilder = context.createIrBuilder(constructor.symbol, startOffset, endOffset)
val valuesInitializer = irBuilder.irBlock(startOffset, endOffset) {
val receiver = implObject.thisReceiver!!
val instances = irTemporary(irGetField(irGet(receiver), loweredEnum.valuesField))
val enumIndices = enumEntries.sortedBy { it.name }.withIndex().associate { it.value to it.index }
enumEntries.forEach {
val instance = irCall(arrayGetSymbol).apply {
dispatchReceiver = irGet(instances)
putValueArgument(0, irInt(enumIndices[it]!!))
}
val initializer = it.initializerExpression!!.expression
initializer.setDeclarationsParent(constructor)
when {
initializer is IrConstructorCall -> +initInstanceCall(instance, initializer)
initializer is IrBlock && initializer.origin == ARGUMENTS_REORDERING_FOR_CALL -> {
val statements = initializer.statements
val constructorCall = statements.last() as IrConstructorCall
statements[statements.lastIndex] = initInstanceCall(instance, constructorCall)
+initializer
}
else -> error("Unexpected initializer: $initializer")
}
}
+irCall([email protected], listOf(arrayType)).apply {
extensionReceiver = irGet(receiver)
}
}
(constructor.body as IrBlockBody).statements += valuesInitializer
}
private fun createSyntheticValuesMethodBody(declaration: IrFunction): IrBody {
val startOffset = irClass.startOffset
val endOffset = irClass.endOffset
val valuesExpression = enumSyntheticFunctionsBuilder.buildValuesExpression(startOffset, endOffset, irClass)
return IrBlockBodyImpl(startOffset, endOffset).apply {
statements += IrReturnImpl(
startOffset,
endOffset,
context.irBuiltIns.nothingType,
declaration.symbol,
valuesExpression
)
}
}
private fun createSyntheticValueOfMethodBody(declaration: IrFunction): IrBody {
val startOffset = irClass.startOffset
val endOffset = irClass.endOffset
val parameter = declaration.valueParameters[0]
val value = IrGetValueImpl(startOffset, endOffset, parameter.type, parameter.symbol)
val valueOfExpression = enumSyntheticFunctionsBuilder.buildValueOfExpression(startOffset, endOffset, irClass, value)
return IrBlockBodyImpl(startOffset, endOffset).apply {
statements += IrReturnImpl(
startOffset,
endOffset,
context.irBuiltIns.nothingType,
declaration.symbol,
valueOfExpression
)
}
}
}
}
| apache-2.0 | 6ec7523a2f88986cf7b295321fe2ef71 | 43.95977 | 128 | 0.617027 | 5.72694 | false | false | false | false |
GunoH/intellij-community | python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationLink.kt | 7 | 5752 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.documentation
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.PyTypeParser
import com.jetbrains.python.psi.types.TypeEvalContext
object PyDocumentationLink {
private const val LINK_TYPE_CLASS = "#class#"
private const val LINK_TYPE_PARAM = "#param#"
private const val LINK_TYPE_TYPENAME = "#typename#"
private const val LINK_TYPE_FUNC = "#func#"
private const val LINK_TYPE_MODULE = "#module#"
@JvmStatic
fun toContainingClass(content: String?): String {
return "<a href=\"${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_CLASS\">$content</a>"
}
@JvmStatic
fun toParameterPossibleClass(type: String, anchor: PsiElement, context: TypeEvalContext): String {
return when (PyTypeParser.getTypeByName(anchor, type, context)) {
is PyClassType -> "<a href=\"${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_PARAM\">$type</a>"
else -> type
}
}
@JvmStatic
fun toPossibleClass(type: String, anchor: PsiElement, context: TypeEvalContext): String = toPossibleClass(type, type, anchor, context)
@JvmStatic
fun toPossibleClass(content: String, qualifiedName: String, anchor: PsiElement, context: TypeEvalContext): String {
return when (PyTypeParser.getTypeByName(anchor, qualifiedName, context)) {
is PyClassType -> "<a href=\"${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_TYPENAME$qualifiedName\">$content</a>"
else -> content
}
}
@JvmStatic
fun toFunction(func: PyFunction): String = toFunction(func.qualifiedName ?: func.name.orEmpty(), func)
@JvmStatic
fun toFunction(content: String, func: PyFunction): String {
val qualifiedName = func.qualifiedName
return when {
qualifiedName != null -> "<a href=\"${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_FUNC$qualifiedName\">$content</a>"
else -> content
}
}
@JvmStatic
fun toModule(content: String, qualifiedName: String): String {
return "<a href=\"${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_MODULE$qualifiedName\">$content</a>"
}
@JvmStatic
fun elementForLink(link: String, element: PsiElement, context: TypeEvalContext): PsiElement? {
return when {
link == LINK_TYPE_CLASS -> containingClass(element)
link == LINK_TYPE_PARAM -> parameterPossibleClass(element, context)
link.startsWith(LINK_TYPE_TYPENAME) -> possibleClass(link.substring(LINK_TYPE_TYPENAME.length), element, context)
link.startsWith(LINK_TYPE_FUNC) -> possibleFunction(link.substring(LINK_TYPE_FUNC.length), element)
link.startsWith(LINK_TYPE_MODULE) -> possibleModule(link.substring(LINK_TYPE_MODULE.length), element)
else -> null
}
}
private fun possibleModule(qualifiedName: String, element: PsiElement): PyFile? {
val facade = PyPsiFacade.getInstance(element.project)
val qName = QualifiedName.fromDottedString(qualifiedName)
val resolveContext = facade.createResolveContextFromFoothold(element)
return facade.resolveQualifiedName(qName, resolveContext)
.filterIsInstance<PsiFileSystemItem>()
.map { PyUtil.turnDirIntoInit(it) }
.filterIsInstance<PyFile>()
.firstOrNull()
}
@JvmStatic
private fun possibleFunction(qualifiedName: String, element: PsiElement): PyFunction? {
// TODO a better, more general way to resolve qualified names of function
val facade = PyPsiFacade.getInstance(element.project)
val qName = QualifiedName.fromDottedString(qualifiedName)
val resolveContext = facade.createResolveContextFromFoothold(element).copyWithMembers()
val topLevel = facade.resolveQualifiedName(qName, resolveContext).filterIsInstance<PyFunction>().firstOrNull()
if (topLevel != null) {
return topLevel
}
return facade.resolveQualifiedName(qName.removeLastComponent(), resolveContext)
.asSequence()
.filterIsInstance<PyClass>()
.map { it.findMethodByName(qName.lastComponent, false, null) }
.firstOrNull()
}
@JvmStatic
private fun containingClass(element: PsiElement): PyClass? {
return when (element) {
is PyClass -> element
is PyFunction -> element.containingClass
else -> PsiTreeUtil.getParentOfType(element, PyClass::class.java)
}
}
@JvmStatic
private fun parameterPossibleClass(parameter: PsiElement, context: TypeEvalContext): PyClass? {
if (parameter is PyNamedParameter) {
val type = context.getType(parameter)
if (type is PyClassType) {
return type.pyClass
}
}
return null
}
@JvmStatic
private fun possibleClass(type: String, anchor: PsiElement, context: TypeEvalContext): PyClass? {
return when (val pyType = PyTypeParser.getTypeByName(anchor, type, context)) {
is PyClassType -> pyType.pyClass
else -> null
}
}
}
| apache-2.0 | ed524381d3ff69144ebe9de9bbac23f8 | 38.129252 | 139 | 0.731919 | 4.441699 | false | false | false | false |
GunoH/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/PluginDescriptorLoader.kt | 1 | 36855 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment")
@file:JvmName("PluginDescriptorLoader")
@file:Internal
package com.intellij.ide.plugins
import com.intellij.idea.AppMode
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.io.NioFiles
import com.intellij.util.PlatformUtils
import com.intellij.util.io.Decompressor
import com.intellij.util.io.URLUtil
import com.intellij.util.lang.UrlClassLoader
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import kotlinx.coroutines.*
import org.codehaus.stax2.XMLStreamReader2
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.ExecutionException
import java.util.zip.ZipFile
import javax.xml.stream.XMLStreamException
import kotlin.io.path.name
private val LOG: Logger
get() = PluginManagerCore.getLogger()
@TestOnly
fun loadDescriptor(file: Path, parentContext: DescriptorListLoadingContext): IdeaPluginDescriptorImpl? {
return loadDescriptorFromFileOrDir(file = file,
context = parentContext,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null)
}
internal fun loadForCoreEnv(pluginRoot: Path, fileName: String): IdeaPluginDescriptorImpl? {
val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER
val parentContext = DescriptorListLoadingContext()
if (Files.isDirectory(pluginRoot)) {
return loadDescriptorFromDir(file = pluginRoot,
descriptorRelativePath = "${PluginManagerCore.META_INF}$fileName",
pluginPath = null,
context = parentContext,
isBundled = true,
isEssential = true,
pathResolver = pathResolver,
useCoreClassLoader = false)
}
else {
return runBlocking {
loadDescriptorFromJar(file = pluginRoot,
fileName = fileName,
pathResolver = pathResolver,
parentContext = parentContext,
isBundled = true,
isEssential = true,
pluginPath = null,
useCoreClassLoader = false,
pool = null)
}
}
}
private fun loadDescriptorFromDir(file: Path,
descriptorRelativePath: String,
pluginPath: Path?,
context: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver): IdeaPluginDescriptorImpl? {
try {
val input = Files.readAllBytes(file.resolve(descriptorRelativePath))
val dataLoader = LocalFsDataLoader(file)
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(file)
return descriptor
}
catch (e: NoSuchFileException) {
return null
}
catch (e: Throwable) {
if (isEssential) {
throw e
}
LOG.warn("Cannot load ${file.resolve(descriptorRelativePath)}", e)
return null
}
}
private fun loadDescriptorFromJar(file: Path,
fileName: String,
pathResolver: PathResolver,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pluginPath: Path?,
pool: ZipFilePool?): IdeaPluginDescriptorImpl? {
var closeable: Closeable? = null
try {
val dataLoader = if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
JavaZipFileDataLoader(zipFile)
}
else {
ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
val raw = readModuleDescriptor(input = dataLoader.load("META-INF/$fileName") ?: return null,
readContext = parentContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = parentContext, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(descriptor.pluginPath)
return descriptor
}
catch (e: Throwable) {
if (isEssential) {
throw if (e is XMLStreamException) RuntimeException("Cannot read $file", e) else e
}
parentContext.reportCannotLoad(file, e)
}
finally {
closeable?.close()
}
return null
}
private class JavaZipFileDataLoader(private val file: ZipFile) : DataLoader {
override val pool: ZipFilePool?
get() = null
override fun load(path: String): InputStream? {
val entry = file.getEntry(if (path[0] == '/') path.substring(1) else path) ?: return null
return file.getInputStream(entry)
}
override fun toString() = file.toString()
}
@VisibleForTesting
fun loadDescriptorFromFileOrDir(
file: Path,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
isBundled: Boolean,
isEssential: Boolean,
isDirectory: Boolean,
useCoreClassLoader: Boolean,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
return when {
isDirectory -> {
loadFromPluginDir(
file = file,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
useCoreClassLoader = useCoreClassLoader,
pathResolver = pathResolver,
isUnitTestMode = isUnitTestMode,
pool = pool,
)
}
file.fileName.toString().endsWith(".jar", ignoreCase = true) -> {
loadDescriptorFromJar(file = file,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pathResolver,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = null,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
else -> null
}
}
// [META-INF] [classes] lib/*.jar
private fun loadFromPluginDir(
file: Path,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val pluginJarFiles = resolveArchives(file)
if (!pluginJarFiles.isNullOrEmpty()) {
putMoreLikelyPluginJarsFirst(file, pluginJarFiles)
val pluginPathResolver = PluginXmlPathResolver(pluginJarFiles)
for (jarFile in pluginJarFiles) {
loadDescriptorFromJar(file = jarFile,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pluginPathResolver,
parentContext = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = file,
useCoreClassLoader = useCoreClassLoader,
pool = pool)?.let {
it.jarFiles = pluginJarFiles
return it
}
}
}
// not found, ok, let's check classes (but only for unbundled plugins)
if (!isBundled || isUnitTestMode) {
val classesDir = file.resolve("classes")
sequenceOf(classesDir, file)
.firstNotNullOfOrNull {
loadDescriptorFromDir(
file = it,
descriptorRelativePath = PluginManagerCore.PLUGIN_XML_PATH,
pluginPath = file,
context = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
)
}?.let {
if (pluginJarFiles.isNullOrEmpty()) {
it.jarFiles = Collections.singletonList(classesDir)
}
else {
val classPath = ArrayList<Path>(pluginJarFiles.size + 1)
classPath.add(classesDir)
classPath.addAll(pluginJarFiles)
it.jarFiles = classPath
}
return it
}
}
return null
}
private fun resolveArchives(path: Path): MutableList<Path>? {
try {
return Files.newDirectoryStream(path.resolve("lib")).use { stream ->
stream.filterTo(ArrayList()) {
val childPath = it.toString()
childPath.endsWith(".jar", ignoreCase = true) || childPath.endsWith(".zip", ignoreCase = true)
}
}
}
catch (e: NoSuchFileException) {
return null
}
}
/*
* Sort the files heuristically to load the plugin jar containing plugin descriptors without extra ZipFile accesses.
* File name preference:
* a) last order for files with resources in name, like resources_en.jar
* b) last order for files that have `-digit` suffix is the name e.g., completion-ranking.jar is before `gson-2.8.0.jar` or `junit-m5.jar`
* c) jar with name close to plugin's directory name, e.g., kotlin-XXX.jar is before all-open-XXX.jar
* d) shorter name, e.g., android.jar is before android-base-common.jar
*/
private fun putMoreLikelyPluginJarsFirst(pluginDir: Path, filesInLibUnderPluginDir: MutableList<Path>) {
val pluginDirName = pluginDir.fileName.toString()
// don't use kotlin sortWith to avoid loading of CollectionsKt
Collections.sort(filesInLibUnderPluginDir, Comparator { o1: Path, o2: Path ->
val o2Name = o2.fileName.toString()
val o1Name = o1.fileName.toString()
val o2StartsWithResources = o2Name.startsWith("resources")
val o1StartsWithResources = o1Name.startsWith("resources")
if (o2StartsWithResources != o1StartsWithResources) {
return@Comparator if (o2StartsWithResources) -1 else 1
}
val o2IsVersioned = fileNameIsLikeVersionedLibraryName(o2Name)
val o1IsVersioned = fileNameIsLikeVersionedLibraryName(o1Name)
if (o2IsVersioned != o1IsVersioned) {
return@Comparator if (o2IsVersioned) -1 else 1
}
val o2StartsWithNeededName = o2Name.startsWith(pluginDirName, ignoreCase = true)
val o1StartsWithNeededName = o1Name.startsWith(pluginDirName, ignoreCase = true)
if (o2StartsWithNeededName != o1StartsWithNeededName) {
return@Comparator if (o2StartsWithNeededName) 1 else -1
}
val o2EndsWithIdea = o2Name.endsWith("-idea.jar")
val o1EndsWithIdea = o1Name.endsWith("-idea.jar")
if (o2EndsWithIdea != o1EndsWithIdea) {
return@Comparator if (o2EndsWithIdea) 1 else -1
}
o1Name.length - o2Name.length
})
}
private fun fileNameIsLikeVersionedLibraryName(name: String): Boolean {
val i = name.lastIndexOf('-')
if (i == -1) {
return false
}
if (i + 1 < name.length) {
val c = name[i + 1]
return Character.isDigit(c) || ((c == 'm' || c == 'M') && i + 2 < name.length && Character.isDigit(name[i + 2]))
}
return false
}
private fun CoroutineScope.loadDescriptorsFromProperty(context: DescriptorListLoadingContext,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val pathProperty = System.getProperty("plugin.path") ?: return emptyList()
// gradle-intellij-plugin heavily depends on this property in order to have core class loader plugins during tests
val useCoreClassLoaderForPluginsFromProperty = java.lang.Boolean.getBoolean("idea.use.core.classloader.for.plugin.path")
val t = StringTokenizer(pathProperty, File.pathSeparatorChar + ",")
val list = mutableListOf<Deferred<IdeaPluginDescriptorImpl?>>()
while (t.hasMoreTokens()) {
val file = Paths.get(t.nextToken())
list.add(async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = useCoreClassLoaderForPluginsFromProperty,
pool = pool,
)
})
}
return list
}
@Suppress("DeferredIsResult")
internal fun CoroutineScope.scheduleLoading(zipFilePoolDeferred: Deferred<ZipFilePool>?): Deferred<PluginSet> {
val resultDeferred = async(CoroutineName("plugin descriptor loading") + Dispatchers.Default) {
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
val result = DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
).use { context ->
context to loadDescriptors(
context = context,
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePoolDeferred = zipFilePoolDeferred,
)
}
result
}
val pluginSetDeferred = async(Dispatchers.Default) {
val pair = resultDeferred.await()
PluginManagerCore.initializeAndSetPlugins(pair.first, pair.second, PluginManagerCore::class.java.classLoader)
}
// logging is no not as a part of plugin set job for performance reasons
launch(Dispatchers.Default) {
val pair = resultDeferred.await()
logPlugins(plugins = pluginSetDeferred.await().allPlugins, context = pair.first, loadingResult = pair.second)
}
return pluginSetDeferred
}
private fun logPlugins(plugins: Collection<IdeaPluginDescriptorImpl>,
context: DescriptorListLoadingContext,
loadingResult: PluginLoadingResult) {
if (AppMode.isDisableNonBundledPlugins()) {
LOG.info("Running with disableThirdPartyPlugins argument, third-party plugins will be disabled")
}
val bundled = StringBuilder()
val disabled = StringBuilder()
val custom = StringBuilder()
val disabledPlugins = HashSet<PluginId>()
for (descriptor in plugins) {
var target: StringBuilder
val pluginId = descriptor.pluginId
target = if (!descriptor.isEnabled) {
if (!context.isPluginDisabled(pluginId)) {
// plugin will be logged as part of "Problems found loading plugins"
continue
}
disabledPlugins.add(pluginId)
disabled
}
else if (descriptor.isBundled || PluginManagerCore.SPECIAL_IDEA_PLUGIN_ID == pluginId) {
bundled
}
else {
custom
}
appendPlugin(descriptor, target)
}
for ((pluginId, descriptor) in loadingResult.getIncompleteIdMap()) {
// log only explicitly disabled plugins
if (context.isPluginDisabled(pluginId) && !disabledPlugins.contains(pluginId)) {
appendPlugin(descriptor, disabled)
}
}
val log = LOG
log.info("Loaded bundled plugins: $bundled")
if (custom.isNotEmpty()) {
log.info("Loaded custom plugins: $custom")
}
if (disabled.isNotEmpty()) {
log.info("Disabled plugins: $disabled")
}
}
private fun appendPlugin(descriptor: IdeaPluginDescriptor, target: StringBuilder) {
if (target.isNotEmpty()) {
target.append(", ")
}
target.append(descriptor.name)
val version = descriptor.version
if (version != null) {
target.append(" (").append(version).append(')')
}
}
// used and must be used only by Rider
@Suppress("unused")
@Internal
suspend fun getLoadedPluginsForRider(): List<IdeaPluginDescriptorImpl?> {
PluginManagerCore.getNullablePluginSet()?.enabledPlugins?.let {
return it
}
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
return DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
).use { context ->
val result = loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
PluginManagerCore.initializeAndSetPlugins(context, result, PluginManagerCore::class.java.classLoader).enabledPlugins
}
}
@Internal
@Deprecated("do not use")
fun loadDescriptorsForDeprecatedWizard(): PluginLoadingResult {
return runBlocking {
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
).use { context ->
loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
}
}
}
/**
* Think twice before use and get approve from core team.
*
* Returns enabled plugins only.
*/
@OptIn(ExperimentalCoroutinesApi::class)
@Internal
suspend fun loadDescriptors(
context: DescriptorListLoadingContext,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean,
zipFilePoolDeferred: Deferred<ZipFilePool>? = null,
): PluginLoadingResult {
val listDeferred: List<Deferred<IdeaPluginDescriptorImpl?>>
val extraListDeferred: List<Deferred<IdeaPluginDescriptorImpl?>>
coroutineScope {
val zipFilePool = if (context.transient) null else zipFilePoolDeferred?.await()
withContext(Dispatchers.IO) {
listDeferred = loadDescriptorsFromDirs(
context = context,
customPluginDir = Paths.get(PathManager.getPluginsPath()),
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePool = zipFilePool,
)
extraListDeferred = loadDescriptorsFromProperty(context, zipFilePool)
}
}
val buildNumber = context.productBuildNumber()
val loadingResult = PluginLoadingResult()
loadingResult.addAll(descriptors = listDeferred.map { it.getCompleted() }, overrideUseIfCompatible = false, productBuildNumber = buildNumber)
// plugins added via property shouldn't be overridden to avoid plugin root detection issues when running external plugin tests
loadingResult.addAll(descriptors = extraListDeferred.map { it.getCompleted() }, overrideUseIfCompatible = true, productBuildNumber = buildNumber)
if (isUnitTestMode && loadingResult.enabledPluginsById.size <= 1) {
// we're running in unit test mode, but the classpath doesn't contain any plugins; try to load bundled plugins anyway
loadingResult.addAll(
descriptors = coroutineScope {
loadDescriptorsFromDir(
dir = Paths.get(PathManager.getPreInstalledPluginsPath()),
context = context,
isBundled = true,
pool = if (context.transient) null else zipFilePoolDeferred?.await()
)
}.awaitAll(),
overrideUseIfCompatible = false,
productBuildNumber = buildNumber
)
}
return loadingResult
}
private fun CoroutineScope.loadDescriptorsFromDirs(
context: DescriptorListLoadingContext,
customPluginDir: Path,
bundledPluginDir: Path? = null,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean = PluginManagerCore.isRunningFromSources(),
zipFilePool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
val isInDevServerMode = AppMode.isDevServer()
val platformPrefixProperty = PlatformUtils.getPlatformPrefix()
val platformPrefix = if (platformPrefixProperty == PlatformUtils.QODANA_PREFIX) {
System.getProperty("idea.parent.prefix", PlatformUtils.IDEA_PREFIX)
}
else {
platformPrefixProperty
}
val root = loadCoreModules(context = context,
platformPrefix = platformPrefix,
isUnitTestMode = isUnitTestMode,
isInDevServerMode = isInDevServerMode,
isRunningFromSources = isRunningFromSources,
pool = zipFilePool)
val custom = loadDescriptorsFromDir(dir = customPluginDir, context = context, isBundled = false, pool = zipFilePool)
val effectiveBundledPluginDir = bundledPluginDir ?: if (isUnitTestMode) {
null
}
else if (isInDevServerMode) {
Paths.get(PathManager.getHomePath(), "out/dev-run", AppMode.getDevBuildRunDirName(platformPrefix), "plugins")
}
else {
Paths.get(PathManager.getPreInstalledPluginsPath())
}
val bundled = if (effectiveBundledPluginDir == null) {
emptyList()
}
else {
loadDescriptorsFromDir(dir = effectiveBundledPluginDir, context = context, isBundled = true, pool = zipFilePool)
}
return (root + custom + bundled)
}
private fun CoroutineScope.loadCoreModules(context: DescriptorListLoadingContext,
platformPrefix: String,
isUnitTestMode: Boolean,
isInDevServerMode: Boolean,
isRunningFromSources: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val classLoader = DescriptorListLoadingContext::class.java.classLoader
val pathResolver = ClassPathXmlPathResolver(classLoader = classLoader, isRunningFromSources = isRunningFromSources && !isInDevServerMode)
val useCoreClassLoader = pathResolver.isRunningFromSources ||
platformPrefix.startsWith("CodeServer") ||
java.lang.Boolean.getBoolean("idea.force.use.core.classloader")
// should be the only plugin in lib (only for Ultimate and WebStorm for now)
val rootModuleDescriptors = if ((platformPrefix == PlatformUtils.IDEA_PREFIX || platformPrefix == PlatformUtils.WEB_PREFIX) &&
(isInDevServerMode || (!isUnitTestMode && !isRunningFromSources))) {
Collections.singletonList(async {
loadCoreProductPlugin(getResourceReader(PluginManagerCore.PLUGIN_XML_PATH, classLoader)!!,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader)
})
}
else {
val fileName = "${platformPrefix}Plugin.xml"
var result = listOf(async {
getResourceReader("${PluginManagerCore.META_INF}$fileName", classLoader)?.let {
loadCoreProductPlugin(it, context, pathResolver, useCoreClassLoader)
}
})
val urlToFilename = collectPluginFilesInClassPath(classLoader)
if (!urlToFilename.isEmpty()) {
@Suppress("SuspiciousCollectionReassignment")
result += loadDescriptorsFromClassPath(urlToFilename = urlToFilename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
result
}
return rootModuleDescriptors
}
private fun getResourceReader(path: String, classLoader: ClassLoader): XMLStreamReader2? {
if (classLoader is UrlClassLoader) {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsBytes(path, false) ?: return null, path)
}
else {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsStream(path) ?: return null, path)
}
}
private fun loadCoreProductPlugin(reader: XMLStreamReader2,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean): IdeaPluginDescriptorImpl {
val dataLoader = object : DataLoader {
override val pool: ZipFilePool
get() = throw IllegalStateException("must be not called")
override val emptyDescriptorIfCannotResolve: Boolean
get() = true
override fun load(path: String) = throw IllegalStateException("must be not called")
override fun toString() = "product classpath"
}
val raw = readModuleDescriptor(reader,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null)
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = Paths.get(PathManager.getLibPath()),
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
return descriptor
}
private fun collectPluginFilesInClassPath(loader: ClassLoader): Map<URL, String> {
val urlToFilename = LinkedHashMap<URL, String>()
try {
val enumeration = loader.getResources(PluginManagerCore.PLUGIN_XML_PATH)
while (enumeration.hasMoreElements()) {
urlToFilename.put(enumeration.nextElement(), PluginManagerCore.PLUGIN_XML)
}
}
catch (e: IOException) {
LOG.warn(e)
}
return urlToFilename
}
@Throws(IOException::class)
fun loadDescriptorFromArtifact(file: Path, buildNumber: BuildNumber?): IdeaPluginDescriptorImpl? {
val context = DescriptorListLoadingContext(isMissingSubDescriptorIgnored = true,
productBuildNumber = { buildNumber ?: PluginManagerCore.getBuildNumber() },
transient = true)
val descriptor = runBlocking {
loadDescriptorFromFileOrDir(file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = false,
useCoreClassLoader = false,
pool = null)
}
if (descriptor != null || !file.toString().endsWith(".zip")) {
return descriptor
}
val outputDir = Files.createTempDirectory("plugin")!!
try {
Decompressor.Zip(file).withZipExtensionsIfUnix().extract(outputDir)
try {
//org.jetbrains.intellij.build.io.ZipArchiveOutputStream may add __index__ entry to the plugin zip, we need to ignore it here
val rootDir = NioFiles.list(outputDir).firstOrNull { it.name != "__index__" }
if (rootDir != null) {
return runBlocking {
loadDescriptorFromFileOrDir(file = rootDir,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = true,
useCoreClassLoader = false,
pool = null)
}
}
}
catch (ignore: NoSuchFileException) {
}
}
finally {
NioFiles.deleteRecursively(outputDir)
}
return null
}
fun loadDescriptor(
file: Path,
isBundled: Boolean,
pathResolver: PathResolver,
): IdeaPluginDescriptorImpl? {
DescriptorListLoadingContext().use { context ->
return runBlocking {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = pathResolver,
isBundled = isBundled,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null,
)
}
}
}
@Throws(ExecutionException::class, InterruptedException::class, IOException::class)
fun loadDescriptors(
customPluginDir: Path,
bundledPluginDir: Path?,
brokenPluginVersions: Map<PluginId, Set<String?>>?,
productBuildNumber: BuildNumber?,
): PluginLoadingResult {
return DescriptorListLoadingContext(
disabledPlugins = emptySet(),
brokenPluginVersions = brokenPluginVersions ?: PluginManagerCore.getBrokenPluginVersions(),
productBuildNumber = { productBuildNumber ?: PluginManagerCore.getBuildNumber() },
isMissingIncludeIgnored = true,
isMissingSubDescriptorIgnored = true,
).use { context ->
runBlocking {
val result = PluginLoadingResult()
val descriptors = loadDescriptorsFromDirs(
context = context,
customPluginDir = customPluginDir,
bundledPluginDir = bundledPluginDir,
zipFilePool = null,
).awaitAll()
result.addAll(
descriptors = descriptors,
overrideUseIfCompatible = false,
productBuildNumber = context.productBuildNumber(),
)
result
}
}
}
@TestOnly
fun testLoadDescriptorsFromClassPath(loader: ClassLoader): List<IdeaPluginDescriptor> {
val urlToFilename = collectPluginFilesInClassPath(loader)
val buildNumber = BuildNumber.fromString("2042.42")!!
val context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet(),
brokenPluginVersions = emptyMap(),
productBuildNumber = { buildNumber })
return runBlocking {
val result = PluginLoadingResult(checkModuleDependencies = false)
result.addAll(loadDescriptorsFromClassPath(
urlToFilename = urlToFilename,
context = context,
pathResolver = ClassPathXmlPathResolver(loader, isRunningFromSources = false),
useCoreClassLoader = true,
pool = if (context.transient) null else ZipFilePool.POOL,
).awaitAll(), overrideUseIfCompatible = false, productBuildNumber = buildNumber)
result.enabledPlugins
}
}
private fun CoroutineScope.loadDescriptorsFromDir(dir: Path,
context: DescriptorListLoadingContext,
isBundled: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
if (!Files.isDirectory(dir)) {
return emptyList()
}
return Files.newDirectoryStream(dir).use { dirStream ->
dirStream.map { file ->
async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = isBundled,
isDirectory = Files.isDirectory(file),
isEssential = false,
useCoreClassLoader = false,
pool = pool,
)
}
}
}
}
// urls here expected to be a file urls to plugin.xml
private fun CoroutineScope.loadDescriptorsFromClassPath(
urlToFilename: Map<URL, String>,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
return urlToFilename.map { (url, filename) ->
async {
loadDescriptorFromResource(resource = url,
filename = filename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
}
}
// filename - plugin.xml or ${platformPrefix}Plugin.xml
private fun loadDescriptorFromResource(
resource: URL,
filename: String,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val file = Paths.get(UrlClassLoader.urlToFilePath(resource.path))
var closeable: Closeable? = null
val dataLoader: DataLoader
val basePath: Path
try {
val input: InputStream
when {
URLUtil.FILE_PROTOCOL == resource.protocol -> {
basePath = file.parent.parent
dataLoader = LocalFsDataLoader(basePath)
input = Files.newInputStream(file)
}
URLUtil.JAR_PROTOCOL == resource.protocol -> {
// support for unpacked plugins in classpath, e.g. .../community/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar
basePath = file.parent?.takeIf { !it.endsWith("lib") }?.parent ?: file
if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
dataLoader = JavaZipFileDataLoader(zipFile)
}
else {
dataLoader = ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
input = dataLoader.load("META-INF/$filename") ?: return null
}
else -> return null
}
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
// it is very important to not set useCoreClassLoader = true blindly
// - product modules must uses own class loader if not running from sources
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = basePath,
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
// do not set jarFiles by intention - doesn't make sense
return descriptor
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.info("Cannot load $resource", e)
return null
}
finally {
closeable?.close()
}
} | apache-2.0 | 35dd8dbf911be8eb8e16833967b4c9a1 | 38.292111 | 147 | 0.635789 | 5.366972 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/EditBreakpointSuggester.kt | 2 | 2671 | package training.featuresSuggester.suggesters
import com.google.common.collect.EvictingQueue
import com.intellij.lang.Language
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.XSourcePosition.isOnTheSameLine
import training.featuresSuggester.FeatureSuggesterBundle
import training.featuresSuggester.NoSuggestion
import training.featuresSuggester.SuggestingUtils.findBreakpointOnPosition
import training.featuresSuggester.Suggestion
import training.featuresSuggester.TipSuggestion
import training.featuresSuggester.actions.Action
import training.featuresSuggester.actions.DebugSessionPausedAction
import training.util.WeakReferenceDelegator
import java.lang.ref.WeakReference
import java.util.*
class EditBreakpointSuggester : AbstractFeatureSuggester() {
override val id: String = "Edit breakpoint"
override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("edit.breakpoint.name")
override val message = FeatureSuggesterBundle.message("edit.breakpoint.message")
override val suggestingActionId = "com.intellij.xdebugger.impl.actions.EditBreakpointAction\$ContextAction"
override val suggestingTipId = "BreakpointSpeedmenu"
override val minSuggestingIntervalDays = 30
override val languages = listOf(Language.ANY.id)
private val numOfPausesToGetSuggestion = 8
@Suppress("UnstableApiUsage")
private val pausesOnBreakpointHistory: Queue<WeakReference<XSourcePosition>> =
EvictingQueue.create(numOfPausesToGetSuggestion)
private var previousSuggestionPosition: XSourcePosition? by WeakReferenceDelegator(null)
override fun getSuggestion(action: Action): Suggestion {
when (action) {
is DebugSessionPausedAction -> {
val breakpoint = findBreakpointOnPosition(action.project, action.position)
if (breakpoint != null && breakpoint.conditionExpression == null) {
pausesOnBreakpointHistory.add(WeakReference(action.position))
}
else {
pausesOnBreakpointHistory.clear()
}
if (pausesOnBreakpointHistory.isAllOnTheSameLine() &&
!isOnTheSameLine(pausesOnBreakpointHistory.lastOrNull()?.get(), previousSuggestionPosition)
) {
previousSuggestionPosition = pausesOnBreakpointHistory.lastOrNull()?.get()
pausesOnBreakpointHistory.clear()
return TipSuggestion(message, id, suggestingTipId)
}
}
}
return NoSuggestion
}
private fun Queue<WeakReference<XSourcePosition>>.isAllOnTheSameLine(): Boolean {
if (size < numOfPausesToGetSuggestion) return false
val lastPos = last().get()
return all { isOnTheSameLine(it.get(), lastPos) }
}
}
| apache-2.0 | 40e5ccde93ff59de50e6a25024aeea8e | 40.734375 | 109 | 0.782104 | 4.928044 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt | 2 | 3354 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.psi.KtObjectLiteralExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
class KotlinUObjectLiteralExpression(
override val sourcePsi: KtObjectLiteralExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UObjectLiteralExpression, UCallExpressionEx, DelegatedMultiResolve, KotlinUElementWithType {
override val declaration: UClass by lz {
sourcePsi.objectDeclaration.toLightClass()
?.let { getLanguagePlugin().convert<UClass>(it, this) }
?: KotlinInvalidUClass("<invalid object code>", sourcePsi, this)
}
override fun getExpressionType() = sourcePsi.objectDeclaration.toPsiType()
private val superClassConstructorCall by lz {
sourcePsi.objectDeclaration.superTypeListEntries.firstOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry
}
override val classReference: UReferenceExpression? by lz { superClassConstructorCall?.let { ObjectLiteralClassReference(it, this) } }
override val valueArgumentCount: Int
get() = superClassConstructorCall?.valueArguments?.size ?: 0
override val valueArguments by lz {
val psi = superClassConstructorCall ?: return@lz emptyList<UExpression>()
psi.valueArguments.map { KotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) }
}
override val typeArgumentCount: Int
get() = superClassConstructorCall?.typeArguments?.size ?: 0
override val typeArguments by lz {
val psi = superClassConstructorCall ?: return@lz emptyList<PsiType>()
psi.typeArguments.map { it.typeReference.toPsiType(this, boxed = true) }
}
override fun resolve() = superClassConstructorCall?.let { resolveToPsiMethod(it) }
override fun getArgumentForParameter(i: Int): UExpression? =
superClassConstructorCall?.let { it.getResolvedCall(it.analyze()) }?.let { getArgumentExpressionByIndex(i, it, this) }
private class ObjectLiteralClassReference(
override val sourcePsi: KtSuperTypeCallEntry,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), USimpleNameReferenceExpression {
override val javaPsi: PsiElement? get() = null
override val psi: KtSuperTypeCallEntry get() = sourcePsi
override fun resolve() = resolveToPsiMethod(sourcePsi)?.containingClass
override val uAnnotations: List<UAnnotation>
get() = emptyList()
override val resolvedName: String?
get() = identifier
override val identifier: String
get() = psi.name ?: referenceNameElement.sourcePsi?.text ?: "<error>"
override val referenceNameElement: UElement
get() = KotlinUIdentifier(psi.typeReference?.nameElement, this)
}
} | apache-2.0 | 31ab0823e1c677042cae34dfa2847b0f | 41.468354 | 158 | 0.742695 | 5.400966 | false | false | false | false |
smmribeiro/intellij-community | platform/script-debugger/debugger-ui/src/com/jetbrains/javascript/debugger/FileUrlMapper.kt | 12 | 1430 | package com.jetbrains.javascript.debugger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.util.Url
import org.jetbrains.debugger.sourcemap.SourceFileResolver
abstract class FileUrlMapper {
companion object {
@JvmField
val EP_NAME: ExtensionPointName<FileUrlMapper> = ExtensionPointName.create("com.jetbrains.fileUrlMapper")
}
open fun getUrls(file: VirtualFile, project: Project, currentAuthority: String?): List<Url> = emptyList()
/**
* Optional to implement, useful if default navigation position to source file is not equals to 0:0 (java file for example)
*/
open fun getNavigatable(url: Url, project: Project, requestor: Url?): Navigatable? = getFile(url, project, requestor)?.let { OpenFileDescriptor(project, it) }
abstract fun getFile(url: Url, project: Project, requestor: Url?): VirtualFile?
/**
* Optional to implement, sometimes you cannot build URL, but can match.
* Lifetime: resolve session lifetime. Could be called multiple times: n <= total sourcemap count
*/
open fun createSourceResolver(file: VirtualFile, project: Project): SourceFileResolver? = null
open fun getFileType(url: Url): FileType? = null
}
| apache-2.0 | df8ec15f30ce0f2fa2e05abdb6871777 | 41.058824 | 160 | 0.775524 | 4.454829 | false | false | false | false |
StuStirling/ribot-viewer | domain/src/main/java/com/stustirling/ribotviewer/domain/Resource.kt | 1 | 1073 | package com.stustirling.ribotviewer.domain
/**
* Created by Stu Stirling on 21/09/2017.
*/
//a generic class that describes a data with a status
class Resource<out T> private constructor(val status: Status, val data: T?, val message: String?) {
companion object {
fun <T> success(data: T): Resource<T> {
return Resource(Status.SUCCESS, data, null)
}
fun <T> error(data: T? = null, msg: String? = null): Resource<T> {
return Resource(Status.ERROR, data, msg)
}
fun <T> error(throwable: Throwable, msg: String? = null) : Resource<T> {
return Resource(Status.ERROR,null,msg).apply {
this.throwable = throwable
}
}
fun <T> loading(data: T? = null): Resource<T> {
return Resource(Status.LOADING, data, null)
}
}
var throwable: Throwable? = null
enum class Status {
SUCCESS,ERROR,LOADING
}
override fun toString(): String {
return "$status ${throwable?.localizedMessage}: $data "
}
}
| apache-2.0 | 31492f8660450d2db423a33c8f1827b9 | 26.512821 | 99 | 0.585275 | 3.95941 | false | false | false | false |
sky-map-team/stardroid | app/src/main/java/com/google/android/stardroid/layers/StarOfBethlehemLayer.kt | 1 | 4631 | // Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.layers
import android.content.res.Resources
import android.util.Log
import com.google.android.stardroid.R
import com.google.android.stardroid.base.TimeConstants
import com.google.android.stardroid.control.AstronomerModel
import com.google.android.stardroid.math.Vector3
import com.google.android.stardroid.renderer.RendererObjectManager.UpdateType
import com.google.android.stardroid.renderables.AbstractAstronomicalRenderable
import com.google.android.stardroid.renderables.AstronomicalRenderable
import com.google.android.stardroid.renderables.ImagePrimitive
import com.google.android.stardroid.renderables.Renderable
import com.google.android.stardroid.util.MiscUtil
import java.util.*
import kotlin.math.abs
/**
* A [Layer] specially for Christmas.
*
* @author John Taylor
*/
class StarOfBethlehemLayer(private val model: AstronomerModel, resources: Resources) :
AbstractRenderablesLayer(resources, true) {
override fun initializeAstroSources(sources: ArrayList<AstronomicalRenderable>) {
sources.add(StarOfBethlehemRenderable(model, resources))
}
override val layerDepthOrder = 40
// TODO(brent): Remove this.
override val preferenceId = "source_provider.0"
override val layerName = "Easter Egg"
override val layerNameId = R.string.show_stars_pref
private class StarOfBethlehemRenderable(private val model: AstronomerModel, resources: Resources) :
AbstractAstronomicalRenderable() {
override val images: MutableList<ImagePrimitive> = ArrayList()
private var lastUpdateTimeMs = 0L
private val coords = Vector3(1f, 0f, 0f)
private val theImage: ImagePrimitive =
ImagePrimitive(coords, resources, R.drawable.blank, UP, SCALE_FACTOR)
private fun updateStar() {
lastUpdateTimeMs = model.time.time
// We will only show the star if it's Christmas Eve.
val calendar = Calendar.getInstance()
calendar.timeInMillis = model.time.time
theImage.setUpVector(UP)
// TODO(johntaylor): consider varying the sizes by scaling factor as time progresses.
if (calendar[Calendar.MONTH] == Calendar.DECEMBER
&& calendar[Calendar.DAY_OF_MONTH] == 25
) {
Log.d(TAG, "Showing Easter Egg")
theImage.setImageId(R.drawable.star_of_b)
val zenith = model.zenith
val east = model.east
coords.assign(
(zenith.x + 2 * east.x) / 3,
(zenith.y + 2 * east.y) / 3,
(zenith.z + 2 * east.z) / 3
)
theImage.setUpVector(zenith)
} else {
theImage.setImageId(R.drawable.blank)
}
}
override fun initialize(): Renderable {
updateStar()
return this
}
override fun update(): EnumSet<UpdateType> {
val updateTypes = EnumSet.noneOf(UpdateType::class.java)
if (abs(model.time.time - lastUpdateTimeMs) > UPDATE_FREQ_MS) {
updateStar()
updateTypes.add(UpdateType.UpdateImages)
updateTypes.add(UpdateType.UpdatePositions)
}
return updateTypes
}
companion object {
private val UP = Vector3(0.0f, 1.0f, 0.0f)
private const val UPDATE_FREQ_MS = 1L * TimeConstants.MILLISECONDS_PER_MINUTE
private const val SCALE_FACTOR = 0.03f
}
init {
// star_off2 is a 1pxX1px image that should be invisible.
// We'd prefer not to show any image except on the Christmas dates, but there
// appears to be a bug in the renderer in that new images added later don't get
// picked up, even if we return UpdateType.Reset.
images.add(theImage)
}
}
companion object {
val TAG = MiscUtil.getTag(StarOfBethlehemLayer::class.java)
}
} | apache-2.0 | bb72fc0adceebbee5518f9e9c41b9806 | 39.278261 | 103 | 0.657957 | 4.198549 | false | false | false | false |
android/uamp | common/src/main/java/com/example/android/uamp/media/extensions/MediaMetadataCompatExt.kt | 2 | 11503 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.extensions
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.library.JsonSource
import com.google.android.exoplayer2.MediaMetadata
import com.google.android.exoplayer2.util.MimeTypes
/**
* Useful extensions for [MediaMetadataCompat].
*/
inline val MediaMetadataCompat.id: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)
inline val MediaMetadataCompat.title: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_TITLE)
inline val MediaMetadataCompat.artist: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ARTIST)
inline val MediaMetadataCompat.duration
get() = getLong(MediaMetadataCompat.METADATA_KEY_DURATION)
inline val MediaMetadataCompat.album: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ALBUM)
inline val MediaMetadataCompat.author: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_AUTHOR)
inline val MediaMetadataCompat.writer: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_WRITER)
inline val MediaMetadataCompat.composer: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_COMPOSER)
inline val MediaMetadataCompat.compilation: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_COMPILATION)
inline val MediaMetadataCompat.date: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DATE)
inline val MediaMetadataCompat.year: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_YEAR)
inline val MediaMetadataCompat.genre: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_GENRE)
inline val MediaMetadataCompat.trackNumber
get() = getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER)
inline val MediaMetadataCompat.trackCount
get() = getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)
inline val MediaMetadataCompat.discNumber
get() = getLong(MediaMetadataCompat.METADATA_KEY_DISC_NUMBER)
inline val MediaMetadataCompat.albumArtist: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST)
inline val MediaMetadataCompat.art: Bitmap
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_ART)
inline val MediaMetadataCompat.artUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_ART_URI).toUri()
inline val MediaMetadataCompat.albumArt: Bitmap?
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)
inline val MediaMetadataCompat.albumArtUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI).toUri()
inline val MediaMetadataCompat.userRating
get() = getLong(MediaMetadataCompat.METADATA_KEY_USER_RATING)
inline val MediaMetadataCompat.rating
get() = getLong(MediaMetadataCompat.METADATA_KEY_RATING)
inline val MediaMetadataCompat.displayTitle: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)
inline val MediaMetadataCompat.displaySubtitle: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE)
inline val MediaMetadataCompat.displayDescription: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION)
inline val MediaMetadataCompat.displayIcon: Bitmap
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)
inline val MediaMetadataCompat.displayIconUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI).toUri()
inline val MediaMetadataCompat.mediaUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI).toUri()
inline val MediaMetadataCompat.downloadStatus
get() = getLong(MediaMetadataCompat.METADATA_KEY_DOWNLOAD_STATUS)
/**
* Custom property for storing whether a [MediaMetadataCompat] item represents an
* item that is [MediaItem.FLAG_BROWSABLE] or [MediaItem.FLAG_PLAYABLE].
*/
inline val MediaMetadataCompat.flag
get() = this.getLong(METADATA_KEY_UAMP_FLAGS).toInt()
/**
* Useful extensions for [MediaMetadataCompat.Builder].
*/
// These do not have getters, so create a message for the error.
const val NO_GET = "Property does not have a 'get'"
inline var MediaMetadataCompat.Builder.id: String
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, value)
}
inline var MediaMetadataCompat.Builder.title: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_TITLE, value)
}
inline var MediaMetadataCompat.Builder.artist: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, value)
}
inline var MediaMetadataCompat.Builder.album: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, value)
}
inline var MediaMetadataCompat.Builder.duration: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, value)
}
inline var MediaMetadataCompat.Builder.genre: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_GENRE, value)
}
inline var MediaMetadataCompat.Builder.mediaUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, value)
}
inline var MediaMetadataCompat.Builder.albumArtUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, value)
}
inline var MediaMetadataCompat.Builder.albumArt: Bitmap?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, value)
}
inline var MediaMetadataCompat.Builder.trackNumber: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, value)
}
inline var MediaMetadataCompat.Builder.trackCount: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, value)
}
inline var MediaMetadataCompat.Builder.displayTitle: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, value)
}
inline var MediaMetadataCompat.Builder.displaySubtitle: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, value)
}
inline var MediaMetadataCompat.Builder.displayDescription: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, value)
}
inline var MediaMetadataCompat.Builder.displayIconUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, value)
}
inline var MediaMetadataCompat.Builder.downloadStatus: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_DOWNLOAD_STATUS, value)
}
/**
* Custom property for storing whether a [MediaMetadataCompat] item represents an
* item that is [MediaItem.FLAG_BROWSABLE] or [MediaItem.FLAG_PLAYABLE].
*/
inline var MediaMetadataCompat.Builder.flag: Int
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(METADATA_KEY_UAMP_FLAGS, value.toLong())
}
fun MediaMetadataCompat.toMediaItemMetadata(): com.google.android.exoplayer2.MediaMetadata {
return with(MediaMetadata.Builder()) {
setTitle(title)
setDisplayTitle(displayTitle)
setAlbumArtist(artist)
setAlbumTitle(album)
setComposer(composer)
setTrackNumber(trackNumber.toInt())
setTotalTrackCount(trackCount.toInt())
setDiscNumber(discNumber.toInt())
setWriter(writer)
setArtworkUri(albumArtUri)
val extras = Bundle()
getString(JsonSource.ORIGINAL_ARTWORK_URI_KEY)?.let {
// album art is a content:// URI. Keep the original for Cast.
extras.putString(
JsonSource.ORIGINAL_ARTWORK_URI_KEY,
getString(JsonSource.ORIGINAL_ARTWORK_URI_KEY)
)
}
extras.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration)
setExtras(extras)
}.build()
}
fun MediaMetadataCompat.toMediaItem(): com.google.android.exoplayer2.MediaItem {
return with(com.google.android.exoplayer2.MediaItem.Builder()) {
setMediaId(mediaUri.toString())
setUri(mediaUri)
setMimeType(MimeTypes.AUDIO_MPEG)
setMediaMetadata(toMediaItemMetadata())
}.build()
}
/**
* Custom property that holds whether an item is [MediaItem.FLAG_BROWSABLE] or
* [MediaItem.FLAG_PLAYABLE].
*/
const val METADATA_KEY_UAMP_FLAGS = "com.example.android.uamp.media.METADATA_KEY_UAMP_FLAGS"
| apache-2.0 | b4c0c3f82f416d957d3149460bdac0d1 | 38.12585 | 92 | 0.75502 | 4.530524 | false | false | false | false |
dscoppelletti/spaceship | lib/src/main/kotlin/it/scoppelletti/spaceship/lifecycle/AlertDialogModel.kt | 1 | 2547 | /*
* Copyright (C) 2019 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* 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("JoinDeclarationAndAssignment", "RedundantVisibilityModifier",
"RemoveRedundantQualifierName")
package it.scoppelletti.spaceship.lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import it.scoppelletti.spaceship.app.AlertDialogFragment
import it.scoppelletti.spaceship.app.AppExt
import it.scoppelletti.spaceship.i18n.I18NProvider
import it.scoppelletti.spaceship.i18n.MessageSpec
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* `ViewModel` of an [AlertDialogFragment] view.
*
* @since 1.0.0
*
* @property message Message.
*/
public class AlertDialogModel(
private val i18nProvider: I18NProvider,
private val handle: SavedStateHandle
): ViewModel() {
private val _message = MutableLiveData<String>()
public val message: LiveData<String> = _message
init {
_message.value = handle[AlertDialogModel.PROP_MSG]
}
/**
* Loads the message.
*
* @param messageSpec Message specification.
*/
public fun load(messageSpec: MessageSpec) = viewModelScope.launch {
val msg: String
msg = messageSpec.buildMessage(i18nProvider)
handle.set(AlertDialogModel.PROP_MSG, msg)
_message.value = msg
}
private companion object {
const val PROP_MSG = AppExt.PROP_MESSAGE
}
}
/**
* Implementation of `ViewModelProviderEx.Factory` interface for
* [AlertDialogModel] class.
*
* @since 1.0.0
*/
public class AlertDialogModelFactory @Inject constructor(
private val i18nProvider: I18NProvider
) : ViewModelProviderEx.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(handle: SavedStateHandle): T =
AlertDialogModel(i18nProvider, handle) as T
}
| apache-2.0 | b89252ca378dfc58c9e63510772f63bf | 28.275862 | 77 | 0.729878 | 4.237937 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/util/BasicAuthenticatorInterceptor.kt | 2 | 1985 | package chat.rocket.android.util
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.Credentials
import java.io.IOException
import chat.rocket.android.server.domain.model.BasicAuth
import chat.rocket.android.server.domain.GetBasicAuthInteractor
import chat.rocket.android.server.domain.SaveBasicAuthInteractor
import javax.inject.Inject
/**
* An OkHttp interceptor which adds Authorization header based on URI userInfo
* part. Can be applied as an
* [application interceptor][OkHttpClient.interceptors]
* or as a [ ][OkHttpClient.networkInterceptors].
*/
class BasicAuthenticatorInterceptor @Inject constructor (
private val getBasicAuthInteractor: GetBasicAuthInteractor,
private val saveBasicAuthInteractor: SaveBasicAuthInteractor
): Interceptor {
private val credentials = HashMap<String, String>()
init {
val basicAuths = getBasicAuthInteractor.getAll()
for (basicAuth in basicAuths){
credentials[basicAuth.host] = basicAuth.credentials
}
}
private fun saveCredentials(host: String, basicCredentials: String) {
saveBasicAuthInteractor.save(
BasicAuth(
host,
basicCredentials
)
)
credentials[host] = basicCredentials
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val url = request.url
val host = url.host
val username = url.username
if (!username.isNullOrEmpty()) {
saveCredentials(host, Credentials.basic(username, url.password))
request = request.newBuilder().url(
url.newBuilder().username("").password("").build()
).build()
}
credentials[host]?.let {
request = request.newBuilder().header("Authorization", it).build()
}
return chain.proceed(request)
}
}
| mit | a555d3f432f02a3976b35558636fdc29 | 30.507937 | 78 | 0.679597 | 4.87715 | false | false | false | false |
vjache/klips | src/main/java/org/klips/dsl/Guard.kt | 1 | 3670 | package org.klips.dsl
import org.klips.dsl.Facet.IntervalFacet
import org.klips.dsl.Guard.BinaryPredicate.Code.*
import org.klips.dsl.Guard.Junction.And
import org.klips.dsl.Guard.Junction.Or
import org.klips.engine.Binding
import org.klips.engine.Modification
sealed class Guard
{
abstract class Predicate : Guard()
class OnceBy(val group: String, vararg val facets: Facet<*>) : Guard() {
override fun eval(cache: MutableMap<Any, Any>, env: Modification<Binding>): Boolean {
val identity = Pair(group, env.inherit(facets.map{ env.arg[it] }))
if(cache[identity] != null)
return false
cache[identity] = identity
return true
}
}
class BinaryPredicate<T : Comparable<T>>(
val code: Code,
val left: Facet<T>,
val right: Facet<T>) : Predicate(){
override fun eval(cache:MutableMap<Any,Any>, env: Modification<Binding>) = when (code) {
Eq -> compare(env) == 0
Ne -> compare(env) != 0
Gt -> compare(env) > 0
Ge -> compare(env) >= 0
Le -> compare(env) <= 0
Lt -> compare(env) < 0
In -> {
if(right !is IntervalFacet<T>)
false
else {
val leftVal = env.arg.fetchValue2(left)
leftVal >= right.min && leftVal <= right.max
}
}
}
private fun compare(env: Modification<Binding>): Int {
fun asConst(arg:Facet<*>) : Facet.ConstFacet<*>{
return when (arg){
is Facet.ConstFacet -> arg
is Facet.FacetRef -> env.arg[arg] as Facet.ConstFacet<*>
else -> throw IllegalArgumentException("Expected const or ref: $arg")
}
}
return asConst(left).compareTo(asConst(right))
}
enum class Code { Eq, Ne, Gt, Lt, Ge, Le, In }
}
// class UnaryPredicate<T>(
// val code: Code,
// val arg: Facet<T>) : Predicate() {
// override fun eval(env: Binding) = when(code) {
// }
//
// enum class Code { Odd, Even }
// }
abstract class Operator : Guard()
enum class Junction { And, Or }
class BinaryJunction(
val code:Junction,
val left: Guard, val right: Guard) : Operator() {
override fun eval(cache:MutableMap<Any,Any>, env: Modification<Binding>) = when(code){
And -> left.eval(cache, env) && right.eval(cache, env)
Or -> left.eval(cache, env) || right.eval(cache, env)
}
}
class MultiJunction(val code:Junction, vararg args: Guard) : Operator()
{
override fun eval(cache:MutableMap<Any,Any>, env: Modification<Binding>) = when(code){
And -> juncts.all { it.eval(cache, env) }
Or -> juncts.any { it.eval(cache, env) }
}
val juncts = mutableListOf(*args)
}
class NotOperator(val arg: Guard) : Operator(){
override fun eval(cache:MutableMap<Any,Any>, env: Modification<Binding>) = !arg.eval(cache, env)
}
class LambdaGuard(private val lambda: (Modification<Binding>) -> Boolean) : Guard() {
override fun eval(cache:MutableMap<Any,Any>, env: Modification<Binding>) = lambda(env)
}
////////////////////////////////////
infix fun and(t: Guard) = BinaryJunction(And, this, t)
infix fun or (t: Guard) = BinaryJunction(Or, this, t)
fun not() = NotOperator(this)
abstract fun eval(cache:MutableMap<Any,Any>, env:Modification<Binding>) : Boolean
} | apache-2.0 | 6f1c7adb7419c06e6b198da5b2695977 | 32.372727 | 104 | 0.552044 | 3.971861 | false | false | false | false |
passsy/CompositeAndroid | generator/src/main/kotlin/parse/JavaFileParser.kt | 1 | 2687 | package parse
import java.io.File
fun parseJavaFile(file: File): AnalyzedJavaFile {
val source = file.readText()
val importMatches = "(?:import.*;)"
.toRegex(RegexOption.MULTILINE)
.findAll(source)
val builder = StringBuilder();
for (match in importMatches.iterator()) {
val groups = match.groups
if (groups.size > 0) {
builder.append(groups[0]?.value?.trim())
builder.append("\n")
}
}
val imports = builder.toString()
// findAll runs out of memory
val methodMatches = mutableListOf<MatchResult>()
var pos = 0
while (true) {
// for regex101 https://regex101.com/r/D7gTv3/2
// (?:\n*?((?:\h*?\/\*\*\h*[\w@]*\n*){1}(?:\h*\*.*\n*)*?(?:\h*\*\/){1})\n)*((?:^\h*\@.*\n)*?)?\h*((?:\w* )*)(.* )?([\w\.<>]*(?:\[\])?) (\w*)\(((?:\n*[^\)]*)*)\)([^\{]*)\{((?:.*\n)(?:\n*(?: .*\n))*)\ \}\n*
val methodsMatch = "(?:\n*?((?:\\h*?\\/\\*\\*\\h*[\\w@]*\n*){1}(?:\\h*\\*.*\n*)*?(?:\\h*\\*\\/){1})\n)*((?:^\\h*\\@.*\n)*?)?\\h*((?:\\w* )*)(.* )?([\\w\\.<>]*(?:\\[\\])?) (\\w*)\\(((?:\n*[^\\)]*)*)\\)([^\\{]*)\\{((?:.*\n)(?:\n*(?: .*\n))*)\\ \\}\n*"
.toRegex(RegexOption.MULTILINE)
.find(source, pos)
if (methodsMatch == null) {
break
}
methodMatches.add(methodsMatch)
pos = methodsMatch.range.last
}
val methods = mutableListOf<AnalyzedJavaMethod>()
for (match in methodMatches) {
val groups = match.groups
val javadoc = groups[1]?.value
val annotations = groups[2]?.value
val visibility = groups[3]?.value ?: ""
val genericTypeDefinition = groups[4]?.value ?: ""
val returnType = groups[5]?.value!!
val name = groups[6]?.value!!
val parameters = groups[7]?.value?.replace("\n", " ")?.replace(",\\h+".toRegex(), ", ")
val throws = groups[8]?.value?.replace("\n", " ")?.replace(",\\h+".toRegex(), ", ")?.trim()
val paramNames = mutableListOf<String>()
val paramType = mutableListOf<String>()
if (parameters != null) {
if (!parameters.trim().isEmpty()) {
parameters.split(',').forEach {
it.trim()
val split = it.split(' ')
paramNames.add(split.last())
paramType.add(split.elementAt(split.size - 2))
}
}
}
methods.add(AnalyzedJavaMethod(name, visibility, genericTypeDefinition, returnType,
javadoc, annotations, parameters, throws))
}
return AnalyzedJavaFile(imports, methods)
}
| apache-2.0 | fd5d08c8b1a82ae1f78891820d14bdc2 | 34.826667 | 267 | 0.47339 | 3.670765 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/stage/GameStage.kt | 1 | 4241 | /*
Tickle
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.tickle.stage
import uk.co.nickthecoder.tickle.Actor
import uk.co.nickthecoder.tickle.Game
import uk.co.nickthecoder.tickle.physics.TickleWorld
/**
* The standard implementation of [Stage].
*/
open class GameStage() : Stage {
protected val mutableViews = mutableListOf<StageView>()
override val views: List<StageView> = mutableViews
override var world: TickleWorld? = null
protected val mutableActors = mutableSetOf<Actor>()
override val actors: Set<Actor> = mutableActors
private var began = false
override fun begin() {
began = true
// Note. We create a new list (of Role), so that there is no concurrent modification exception if an actor is
// removed from the stage.
actors.map { it.role }.forEach { role ->
if (role?.actor?.stage != null) {
try {
role.begin()
} catch (e: Exception) {
Game.instance.errorHandler.roleError(role, e)
}
}
}
}
override fun activated() {
// Note. We create a new list (of Role), so that there is no concurrent modification exception if an actor is
// removed from the stage.
actors.map { it.role }.forEach { role ->
if (role?.actor?.stage != null) {
try {
role.activated()
} catch (e: Exception) {
Game.instance.errorHandler.roleError(role, e)
}
}
}
}
override fun end() {
// Note. We create a new list (of Role), so that there is no concurrent modification exception if an actor is
// removed from the stage.
actors.map { it.role }.forEach { role ->
if (role?.actor?.stage != null) {
try {
role.end()
} catch (e: Exception) {
Game.instance.errorHandler.roleError(role, e)
}
}
}
mutableActors.clear()
}
override fun tick() {
// Note. We create a new list (of Role), so that there is no concurrent modification exception if an actor is
// removed from the stage.
actors.map { it.role }.forEach { role ->
if (role?.actor?.stage != null) {
try {
role.tick()
} catch (e: Exception) {
Game.instance.errorHandler.roleError(role, e)
}
}
}
}
override fun add(actor: Actor) {
if (actor._stage != this) {
actor._stage?.remove(actor)
actor.costume.bodyDef?.let { bodyDef ->
world?.createBody(bodyDef, actor)
}
mutableActors.add(actor)
actor._stage = this
if (began) {
actor.role?.begin()
actor.role?.let { role ->
try {
role.activated()
} catch (e: Exception) {
Game.instance.errorHandler.roleError(role, e)
}
}
}
}
}
override fun remove(actor: Actor) {
if (actor._stage == this) {
actor.body?.let {
world?.destroyBody(it)
actor.body = null
}
mutableActors.remove(actor)
actor._stage = null
}
}
override fun addView(view: StageView) {
mutableViews.add(view)
}
}
| gpl-3.0 | 3308385ef0254707758048ff6792318a | 29.292857 | 117 | 0.54539 | 4.599783 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/FirebaseLoginActivity.kt | 1 | 7917 | package com.itachi1706.cheesecakeutilities
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.SignInButton
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.itachi1706.cheesecakeutilities.modules.vehicleMileageTracker.VehMileageFirebaseUtils
import com.itachi1706.helperlib.helpers.LogHelper
import com.itachi1706.helperlib.utils.NotifyUserUtil
import kotlinx.android.synthetic.main.activity_firebase_login.*
class FirebaseLoginActivity : BaseModuleActivity() {
companion object {
private const val TAG: String = "FirebaseLoginActivity"
private const val RC_SIGN_IN: Int = 9001
/**
* Intent to forward to after successful sign in
*/
const val CONTINUE_INTENT: String = "forwardTo"
/**
* Help message to replace the current activity's message
* Will be shown via Overflow > About from the activity
*/
const val HELP_EXTRA: String = "helpMessage"
}
private var message: String = "This is a place to manage Firebase Logins\n\nSome utilities make use of Firebase to persist your user data"
private lateinit var progress: ProgressBar
private val mAuth = FirebaseAuth.getInstance()
private lateinit var sp: SharedPreferences
private var showDebug: Boolean = false
private var continueIntent: Intent? = null
override val helpDescription: String
get() = message
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_firebase_login)
// Setup login form
progress = findViewById(R.id.sign_in_progress)
progress.isIndeterminate = true
progress.visibility = View.GONE
// Setup Google Signin
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build()
val mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
google_sign_in_button.setSize(SignInButton.SIZE_WIDE)
google_sign_in_button.setOnClickListener {
// Attempts to sign in with Google
LogHelper.d(TAG, "Signing in with Google")
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
sp = PreferenceManager.getDefaultSharedPreferences(this)
if (intent.hasExtra("logout") && intent.getBooleanExtra("logout", false)) signout(true)
if (intent.hasExtra(CONTINUE_INTENT)) continueIntent = intent.getParcelableExtra(CONTINUE_INTENT)
if (intent.hasExtra(HELP_EXTRA)) message = intent.getStringExtra(HELP_EXTRA)
val firebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
firebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
if (firebaseRemoteConfig.getBoolean("firebase_login_debug")) showDebug = true
showHideLogin(true)
sign_out.setOnClickListener { signout(false) }
test_account.setOnClickListener { mAuth.signInWithEmailAndPassword("[email protected]", "test123").addOnCompleteListener { task -> processSignIn("signInTestEmail", task) } }
}
private fun processSignIn(log: String, task: Task<AuthResult>) {
if (task.isSuccessful) {
// Sign in successful, update UI with the signed-in user's information
LogHelper.d(TAG, "$log:success")
val user = mAuth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user
LogHelper.w(TAG, "$log:failure", task.exception!!)
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show()
updateUI(null)
}
}
private fun signout(supress: Boolean) {
mAuth.signOut()
if (sp.contains(VehMileageFirebaseUtils.FB_UID)) sp.edit().remove(VehMileageFirebaseUtils.FB_UID).apply()
updateUI(null, supress)
}
private fun showHideLogin(show: Boolean) {
if (show) {
google_sign_in_button.visibility = View.VISIBLE
if (showDebug) test_account.visibility = View.VISIBLE
sign_in_as.visibility = View.GONE
sign_out.visibility = View.GONE
} else {
google_sign_in_button.visibility = View.GONE
test_account.visibility = View.GONE
sign_in_as.visibility = View.VISIBLE
sign_out.visibility = View.VISIBLE
}
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = mAuth.currentUser
updateUI(currentUser)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
LogHelper.i(TAG, "Sign in successful")
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
LogHelper.e(TAG, "Sign in failed")
updateUI(null)
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
LogHelper.d(TAG, "firebaseAuthWithGoogle:" + acct.id)
progress.visibility = View.VISIBLE
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
mAuth.signInWithCredential(credential).addOnCompleteListener(this) { task ->
processSignIn("signInWithGoogle", task)
progress.visibility = View.GONE
}
}
private fun updateUI(user: FirebaseUser?) {
updateUI(user, false)
}
private fun updateUI(user: FirebaseUser?, supress: Boolean) {
progress.visibility = View.GONE
if (user != null) { // There's a user
if (!supress) NotifyUserUtil.createShortToast(this, "Signed in!")
sp.edit().putString(VehMileageFirebaseUtils.FB_UID, user.uid).apply()
var login = user.displayName
if (login == null) login = user.email
sign_in_as.text = "Signed in as $login"
if (continueIntent != null) {
if (intent.hasExtra("globalcheck")) continueIntent!!.putExtra("globalcheck", intent.getBooleanExtra("globalcheck", false))
startActivity(continueIntent!!)
finish()
} else {
LogHelper.e(TAG, "No continue intent found. Exiting by default unless specified not to")
if (!intent.getBooleanExtra("persist", false)) finish()
showHideLogin(false)
}
} else {
if (!supress) NotifyUserUtil.createShortToast(this, "Currently Logged Out")
sp.edit().remove(VehMileageFirebaseUtils.FB_UID).apply()
sign_in_as.text = "Currently Logged Out"
showHideLogin(true)
}
}
}
| mit | 0751dd903ea7cfbb3f92a94a09ca5c71 | 40.450262 | 177 | 0.670582 | 4.594893 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/icon/ComboArrowIcon.kt | 1 | 1055 | package cn.yiiguxing.plugin.translate.ui.icon
import com.intellij.openapi.ui.GraphicsConfig
import com.intellij.util.ui.JBUI
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.Icon
/**
* ComboArrowIcon
*/
class ComboArrowIcon(var color: Color = Color.WHITE) : Icon {
private val shape: Shape
init {
val w = iconWidth.toDouble()
val h = iconHeight.toDouble()
shape = Path2D.Double().apply {
moveTo(0.0, 0.0)
lineTo(w, 0.0)
lineTo(w / 2.0, h)
closePath()
}
}
override fun getIconWidth(): Int = JBUI.scale(7)
override fun getIconHeight(): Int = JBUI.scale(5)
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
g as Graphics2D
val config = GraphicsConfig(g)
config.setupRoundedBorderAntialiasing()
with(g) {
translate(x, y)
color = [email protected]
g.fill(shape)
translate(-x, -y)
}
config.restore()
}
} | mit | ea94fb02eec15af2452204636325cfe7 | 21.956522 | 71 | 0.587678 | 3.663194 | false | true | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/util/ColorUtils.kt | 1 | 1589 | package com.itachi1706.cheesecakeutilities.util
import android.content.Context
import androidx.core.content.ContextCompat
import com.itachi1706.cheesecakeutilities.R
/**
* Created by Kenneth on 5/7/2018.
* for com.itachi1706.cheesecakeutilities.Util in CheesecakeUtilities
*/
class ColorUtils {
companion object {
fun getColorFromVariable(context: Context, color: Int): Int {
return when (color) {
RED -> ContextCompat.getColor(context, R.color.red)
ORANGE -> ContextCompat.getColor(context, R.color.orange)
YELLOW -> ContextCompat.getColor(context, R.color.yellow)
GREEN -> ContextCompat.getColor(context, R.color.green)
BLUE -> ContextCompat.getColor(context, R.color.blue)
INDIGO -> ContextCompat.getColor(context, R.color.indigo)
VIOLET -> ContextCompat.getColor(context, R.color.violet)
DARK_GREEN -> ContextCompat.getColor(context, R.color.dark_green)
DARK_YELLOW -> ContextCompat.getColor(context, R.color.dark_yellow)
LIGHT_BLUE -> ContextCompat.getColor(context, R.color.gpa_blue_light)
else -> ContextCompat.getColor(context, R.color.black)
}
}
const val RED = 0
const val ORANGE = 1
const val YELLOW = 2
const val GREEN = 3
const val BLUE = 4
const val INDIGO = 5
const val VIOLET = 6
const val DARK_GREEN = 7
const val DARK_YELLOW = 8
const val LIGHT_BLUE = 9
}
}
| mit | 5de910c11058e5c366262c5474080e4b | 35.953488 | 85 | 0.624292 | 4.37741 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/FrameLayout.kt | 1 | 1907 | package cn.yiiguxing.plugin.translate.ui
import com.intellij.util.ui.AbstractLayoutManager
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
/**
* FrameLayout
*/
class FrameLayout : AbstractLayoutManager() {
override fun preferredLayoutSize(parent: Container): Dimension = parent.getSize { preferredSize }
override fun minimumLayoutSize(parent: Container): Dimension = parent.getSize { minimumSize }
override fun maximumLayoutSize(parent: Container): Dimension = parent.getSize { maximumSize }
private inline fun Container.getSize(targetSize: Component.() -> Dimension): Dimension {
synchronized(treeLock) {
var w = 0
var h = 0
for (i in 0 until componentCount) {
getComponent(i)
.takeIf { it.isVisible }
?.targetSize()
?.let { (tw, th) ->
w = maxOf(tw, w)
h = maxOf(th, h)
}
}
return with(insets) {
Dimension(left + right + w, top + bottom + h)
}
}
}
override fun layoutContainer(parent: Container) = with(parent) {
synchronized(treeLock) {
val insets = insets
val pw = width - insets.left - insets.right
val ph = height - insets.top - insets.bottom
for (i in 0 until componentCount) {
getComponent(i)
.takeIf { it.isVisible }
?.apply {
val (w, h) = preferredSize
val x = alignmentX.let { it * (pw - w) }.toInt()
val y = alignmentY.let { it * (ph - h) }.toInt()
setBounds(x, y, w, h)
}
}
}
}
} | mit | 1004e49ad621902f506f4929a882ab67 | 33.690909 | 101 | 0.500787 | 5.005249 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-tip-calculator | app/src/main/java/com/example/tiptime/MainActivity.kt | 1 | 6545 | /*
* 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.tiptime
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Surface
import androidx.compose.material.Switch
import androidx.compose.material.SwitchDefaults
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.tiptime.ui.theme.TipTimeTheme
import java.text.NumberFormat
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TipTimeTheme {
Surface(modifier = Modifier.fillMaxSize()) {
TipTimeScreen()
}
}
}
}
}
@Composable
fun TipTimeScreen() {
var amountInput by remember { mutableStateOf("") }
var tipInput by remember { mutableStateOf("") }
var roundUp by remember { mutableStateOf(false) }
val amount = amountInput.toDoubleOrNull() ?: 0.0
val tipPercent = tipInput.toDoubleOrNull() ?: 0.0
val tip = calculateTip(amount, tipPercent, roundUp)
val focusManager = LocalFocusManager.current
Column(
modifier = Modifier.padding(32.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = stringResource(R.string.calculate_tip),
fontSize = 24.sp,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Spacer(Modifier.height(16.dp))
EditNumberField(
label = R.string.cost_of_service,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Down) }
),
value = amountInput,
onValueChanged = { amountInput = it }
)
EditNumberField(
label = R.string.how_was_the_service,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = { focusManager.clearFocus() }
),
value = tipInput,
onValueChanged = { tipInput = it }
)
RoundTheTipRow(roundUp = roundUp, onRoundUpChanged = { roundUp = it })
Spacer(Modifier.height(24.dp))
Text(
text = stringResource(R.string.tip_amount, tip),
modifier = Modifier.align(Alignment.CenterHorizontally),
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
@Composable
fun EditNumberField(
@StringRes label: Int,
keyboardOptions: KeyboardOptions,
keyboardActions: KeyboardActions,
value: String,
onValueChanged: (String) -> Unit,
modifier: Modifier = Modifier
) {
TextField(
value = value,
singleLine = true,
modifier = modifier.fillMaxWidth(),
onValueChange = onValueChanged,
label = { Text(stringResource(label)) },
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions
)
}
@Composable
fun RoundTheTipRow(
roundUp: Boolean,
onRoundUpChanged: (Boolean) -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = Modifier
.fillMaxWidth()
.size(48.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = stringResource(R.string.round_up_tip))
Switch(
modifier = modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.End),
checked = roundUp,
onCheckedChange = onRoundUpChanged,
colors = SwitchDefaults.colors(
uncheckedThumbColor = Color.DarkGray
)
)
}
}
/**
* Calculates the tip based on the user input and format the tip amount
* according to the local currency and display it onscreen.
* Example would be "$10.00".
*/
private fun calculateTip(amount: Double, tipPercent: Double = 15.0, roundUp: Boolean): String {
var tip = tipPercent / 100 * amount
if (roundUp)
tip = kotlin.math.ceil(tip)
return NumberFormat.getCurrencyInstance().format(tip)
}
@Preview
@Composable
fun TipTimeScreenPreview() {
TipTimeTheme {
TipTimeScreen()
}
}
| apache-2.0 | 5f5918c092586a13817441fef8ebe00e | 32.911917 | 95 | 0.68602 | 4.651741 | false | false | false | false |
Kotlin/anko | anko/library/generator/src/org/jetbrains/android/anko/generator/ServiceGenerator.kt | 2 | 2016 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.utils.packageName
import org.jetbrains.android.anko.utils.simpleName
import org.objectweb.asm.tree.FieldNode
class ServiceGenerator : Generator<ServiceElement> {
override fun generate(state: GenerationState): Iterable<ServiceElement> {
return state.classTree.findNode("android/content/Context")?.data?.fields
?.filter { it.name.endsWith("_SERVICE") }
?.mapNotNull { serviceField ->
state.availableClasses.find { classNode ->
classNode.packageName.startsWith("android")
&& classNode.simpleName == serviceField.toServiceClassName()
}
?.let { ServiceElement(it, serviceField.name) }
}
?.sortedBy { it.simpleName }
?: emptyList()
}
private fun FieldNode.toServiceClassName(): String {
var nextCapital = true
val builder = StringBuilder()
for (char in name.replace("_SERVICE", "_MANAGER").toCharArray()) when (char) {
'_' -> nextCapital = true
else -> builder.append(
if (nextCapital) {
nextCapital = false; char
} else Character.toLowerCase(char)
)
}
return builder.toString()
}
} | apache-2.0 | a872f41650743f3f0fdb56bd930ffea8 | 37.788462 | 92 | 0.620536 | 4.811456 | false | false | false | false |
joffrey-bion/hashcode-utils | src/main/kotlin/org/hildan/hashcode/utils/HCUtils.kt | 1 | 2897 | package org.hildan.hashcode.utils
import org.hildan.hashcode.utils.reader.HCReader
import org.hildan.hashcode.utils.reader.withHCReader
import org.hildan.hashcode.utils.runner.UncaughtExceptionsLogger
import org.hildan.hashcode.utils.runner.runInParallel
import org.hildan.hashcode.utils.writer.writeHCOutputFile
import java.nio.file.Path
import kotlin.io.path.*
/**
* Reads the input file at [inputFilePath] by calling [readAndSolve], and writes the returned lines to the file at
* [outputFilePath].
*
* @param inputFilePath the path to the input file
* @param outputFilePath the path to the output file (will be overwritten if it exists). By default, the output file
* is computed from the input filename using [computeHCOutputPath].
* @param readAndSolve a function that reads the problem, solves it, and returns the output lines to write
*/
inline fun solveHCProblemAndWriteFile(
inputFilePath: Path,
outputFilePath: Path = computeHCOutputPath(inputFilePath),
readAndSolve: HCReader.() -> Iterable<CharSequence>
) {
val outputLines = withHCReader(inputFilePath) { readAndSolve() }
writeHCOutputFile(outputFilePath, outputLines)
}
/**
* Computes the output file path based on the input file path. If there is a `.in` extension, it is changed to `.out`,
* otherwise `.out` is simply appended. If there is a parent folder called `inputs`, it is changed to `outputs`.
*/
fun computeHCOutputPath(inputPath: Path): Path {
val normalized = inputPath.normalize()
val parent: Path? = normalized.parent
val newFileName = normalized.fileName.toString().removeSuffix(".in") + ".out"
return when {
parent == null -> Path(newFileName)
parent.endsWith("inputs") -> parent.resolveSibling("outputs").resolve(newFileName)
else -> parent.resolve(newFileName)
}
}
/**
* Solves the problems defined by each of the given input files, each in its own coroutine.
*
* @param filenames the paths to the input files to read
* @param exceptionsLogger the way to log uncaught exceptions (defaults to standard error stream)
* @param remindExceptionsAtTheEnd whether to remind all exceptions that occurred during the runs when all coroutines
* are done (true by default to ease debugging when the output is too big)
* @param readAndSolve a function to read the input and solve the problem, returning the output lines to write
*/
suspend fun solveHCFilesInParallel(
vararg filenames: String,
exceptionsLogger: UncaughtExceptionsLogger = UncaughtExceptionsLogger.STDERR,
remindExceptionsAtTheEnd: Boolean = true,
readAndSolve: suspend HCReader.() -> Iterable<CharSequence>
) {
runInParallel(
*filenames,
exceptionsLogger = exceptionsLogger,
remindExceptionsAtTheEnd = remindExceptionsAtTheEnd
) {
solveHCProblemAndWriteFile(Path(it)) {
readAndSolve()
}
}
}
| mit | 843e6fa5a4af38cfc7158bafa764ad79 | 40.385714 | 118 | 0.743873 | 4.210756 | false | false | false | false |
eugeis/ee | ee-design/src/main/kotlin/ee/design/DesignUtils.kt | 1 | 17763 | package ee.design
import ee.common.ext.then
import ee.design.gen.go.toGoPropOptionalAfterBody
import ee.lang.*
import org.slf4j.LoggerFactory
private val log = LoggerFactory.getLogger("DesignUtils")
open class DesignDerivedKindNames : LangDerivedKindNames() {
val HttpGet = "Get"
val HttpPost = "Post"
val HttpPut = "Put"
val HttpDelete = "Delete"
}
object DesignDerivedKind : DesignDerivedKindNames()
open class DesignDerivedTypeNames {
val Aggregate = "Aggregate"
val AggregateCommands = "AggregateCommands"
val AggregateEvents = "AggregateEvents"
val AggregateEngine = "AggregateEngine"
val AggregateType = "AggregateType"
val Command = "Command"
val CommandHandler = "CommandHandler"
val Http = "Http"
val HttpRouter = "Router"
val Client = "Client"
val HttpClient = "Client"
val Cli = "Cli"
val QueryRepository = "QueryRepository"
val HttpQueryHandler = "HttpQueryHandler"
val HttpCommandHandler = "HttpCommandHandler"
val Event = "Event"
val EventHandler = "EventHandler"
val EsEngine = "EsEngine"
val Handler = "Handler"
val Handlers = "Handlers"
val Executor = "Executor"
val Executors = "Executors"
val Logic = "Logic"
val Projector = "Projector"
val Query = "Query"
val StateMachine = "State"
val StateMachineEvents = "StateEvents"
val StateMachineCommands = "StateCommands"
}
object DesignDerivedType : DesignDerivedTypeNames()
fun EntityI<*>.findBy(vararg params: AttributeI<*>) = findBy {
params(*params)
ret(this@findBy)
}
fun EntityI<*>.existBy(vararg params: AttributeI<*>) = existBy {
params(*params)
ret(n.Boolean)
}
fun EntityI<*>.countBy(vararg params: AttributeI<*>) = countBy {
params(*params)
ret(n.Int)
}
fun CompilationUnitI<*>.op(vararg params: AttributeI<*>, body: OperationI<*>.() -> Unit = {}) = op {
params(*params)
body()
}
fun EntityI<*>.command(vararg params: AttributeI<*>) = command { props(*params) }
fun EntityI<*>.createBy(vararg params: AttributeI<*>) = createBy { props(*params) }
fun EntityI<*>.updateBy(vararg params: AttributeI<*>) = updateBy { props(*params) }
fun EntityI<*>.deleteBy(vararg params: AttributeI<*>) = deleteBy { props(*params) }
fun EntityI<*>.composite(vararg commands: CommandI<*>) = composite { commands(*commands) }
fun EntityI<*>.event(vararg params: AttributeI<*>) = event { props(*params) }
fun EntityI<*>.created(vararg params: AttributeI<*>) = created { props(*params) }
fun EntityI<*>.updated(vararg params: AttributeI<*>) = updated { props(*params) }
fun EntityI<*>.deleted(vararg params: AttributeI<*>) = deleted { props(*params) }
//TODO provide customizable solution for event name derivation from command
val consonants = ".*[wrtzpsdfghklxcvbnm]".toRegex()
fun OperationI<*>.findParamKey() = params().find { it.isKey() }
fun OperationI<*>.findParamsNoKeys() = params().filter { !it.isKey() }
fun CompilationUnitI<*>.findPropKey() = props().find { it.isKey() }
fun CompilationUnitI<*>.findPropsNoKeys() = props().filter { !it.isKey() }
fun <T : OperationI<*>> List<T>.filterOpsWithKey(): List<T> =
filter { item -> item.params().find { it.isKey() } != null }
fun <T : OperationI<*>> List<T>.filterOpsWithoutKey(): List<T> =
filter { item -> item.params().find { it.isKey() } == null }
fun <T : CommandI<*>> List<T>.filterCommandsWithKey(): List<T> =
filter { item -> item.props().find { it.isKey() } != null }
fun <T : CommandI<*>> List<T>.filterCommandsWithoutKey(): List<T> =
filter { item -> item.props().find { it.isKey() } == null }
fun CommandI<*>.deriveEventName(): String {
var ret = name().capitalize()
ret = when {
ret.contains("Send") -> {
ret.replace("Send", "Sent")
}
name().contains("send") -> {
ret.replace("send", "sent")
}
name().endsWith("gin") -> {
ret.replace("gin", "gged")
}
name().endsWith("ay") -> {
ret.replace("ay", "aid")
}
else -> {
"$ret${consonants.matches(ret).then("e")}d"
}
}
return ret
}
fun CommandI<*>.deriveEvent(): EventI<*> {
val entity = findParentMust(EntityI::class.java)
val eventName = deriveEventName()
val eventProps = props().toTypedArray()
return when (val command = this) {
is CreateByI -> entity.created {
name(eventName)
//paramsNotDerived(*command.paramsNotDerived().map { p(it) }.toTypedArray())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
is UpdateByI -> entity.updated {
name(eventName)
//paramsNotDerived(*command.paramsNotDerived().map { p(it) }.toTypedArray())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
is DeleteByI -> entity.deleted {
name(eventName)
//paramsNotDerived(*command.paramsNotDerived().map { p(it) }.toTypedArray())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
is AddChildByI -> entity.childAdded {
name(eventName)
type(command.type())
child(command.child())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
is UpdateChildByI -> entity.childUpdated {
name(eventName)
type(command.type())
child(command.child())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
is RemoveChildByI -> entity.childRemoved {
name(eventName)
type(command.type())
child(command.child())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
else -> entity.event {
name(eventName)
//paramsNotDerived(*command.paramsNotDerived().map { p(it) }.toTypedArray())
props(*eventProps)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
}
fun EntityI<*>.hasNoQueries() = findBys().isEmpty() && countBys().isEmpty() && existBys().isEmpty()
fun EntityI<*>.hasNoEvents() = events().isEmpty() && created().isEmpty() && updated().isEmpty() && deleted().isEmpty()
fun EntityI<*>.hasNoCommands() =
commands().isEmpty() && createBys().isEmpty() && updateBys().isEmpty() && deleteBys().isEmpty()
fun StructureUnitI<*>.renameControllersAccordingParentType() {
findDownByType(ControllerI::class.java).forEach { item ->
item.extendAdapt {
val parent = findParent(CompilationUnitI::class.java)
if (parent != null) {
val parentPrefix = parent.name().capitalize()
if (!name().startsWith(parentPrefix)) {
name("$parentPrefix${name().capitalize()}")
}
}
}
}
}
fun StructureUnitI<*>.addQueriesForAggregates() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() && it.isDefaultQueries() }.extend {
val item = this
log.debug("Add isDefault queries to ${name()}")
findBy {
name("FindAll")
ret(n.List.GT(item))
}
findBy {
name("FindById")
params(propIdOrAdd())
ret(item)
}
countBy {
name("CountAll")
ret(n.Long)
}
countBy {
name("CountById")
params(propIdOrAdd())
ret(n.Long)
}
existBy {
name("ExistAll")
ret(n.Boolean)
}
existBy {
name("ExistById")
params(propIdOrAdd())
ret(n.Boolean)
}
}
}
fun StructureUnitI<*>.addDefaultReturnValuesForQueries() {
findDownByType(FindByI::class.java).filter { it.returns().isEmpty() }.extend {
if (isMultiResult()) {
ret(n.List.GT(findParentMust(TypeI::class.java)))
} else {
ret(findParentMust(TypeI::class.java))
}
}
findDownByType(CountByI::class.java).filter { it.returns().isEmpty() }.extend {
ret(n.Long)
}
findDownByType(ExistByI::class.java).filter { it.returns().isEmpty() }.extend {
ret(n.Boolean)
}
}
fun StructureUnitI<*>.addCommandsAndEventsForAggregates() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() }.extend {
if (isDefaultCommands()) {
commandCreate()
commandUpdate()
commandDelete()
propsCollectionValues().forEach {
it.commandAddToList()
it.commandUpdateToList()
it.commandRemoveToList()
//it.commandRemoveAll()
}
propsMapValues().forEach {
it.commandPutToMap()
it.commandUpdateToMap()
it.commandRemoveFromMap()
//it.commandRemoveAll()
}
}
if (isDefaultEvents()) {
findDownByType(CommandI::class.java).filter { it.event().isEMPTY() }.forEach {
it.event(it.deriveEvent())
}
}
}
}
fun AttributeI<*>.commandRemoveAll(): CommandI<*> = storage.getOrPut(this, "commandRemoveAll") {
commandAdd(type().generics().first().type())
}
fun AttributeI<*>.commandAddToList(): CommandI<*> = storage.getOrPut(this, "commandAddToList") {
commandAdd(type().generics().first().type())
}
fun AttributeI<*>.commandUpdateToList(): CommandI<*> = storage.getOrPut(this, "commandUpdateToList") {
commandUpdate(type().generics().first().type())
}
fun AttributeI<*>.commandRemoveToList(): CommandI<*> = storage.getOrPut(this, "commandRemoveToList") {
commandRemove(type().generics().first().type())
}
fun AttributeI<*>.commandPutToMap(): CommandI<*> = storage.getOrPut(this, "commandPutToMap") {
commandAdd(type().generics()[1].type())
}
fun AttributeI<*>.commandUpdateToMap(): CommandI<*> = storage.getOrPut(this, "commandUpdateToMap") {
commandUpdate(type().generics()[1].type())
}
fun AttributeI<*>.commandRemoveFromMap(): CommandI<*> = storage.getOrPut(this, "commandRemoveFromMap") {
commandRemove(type().generics()[1].type())
}
private fun AttributeI<*>.commandRemoveAll(type: TypeI<*>): AddChildByI<*> {
val attr = this
val entity = parent() as EntityI
return entity.addChildBy {
name("${attr.nameSingular()}RemoveAll")
type(type)
child(attr)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
private fun AttributeI<*>.commandAdd(type: TypeI<*>): AddChildByI<*> {
val attr = this
val entity = parent() as EntityI
val props = type.propsNoMeta().toTypedArray()
return entity.addChildBy {
name("${attr.nameSingular()}Add")
type(type)
child(attr)
props(*props)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
private fun AttributeI<*>.commandUpdate(type: TypeI<*>): UpdateChildByI<*> {
val attr = this
val entity = parent() as EntityI
val props = type.propsNoMeta().toTypedArray()
return entity.updateChildBy {
name("${attr.nameSingular()}Update")
type(type)
child(attr)
props(*props)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
private fun AttributeI<*>.commandRemove(type: TypeI<*>): RemoveChildByI<*> {
val attr = this
val entity = parent() as EntityI
return entity.removeChildBy {
name("${attr.nameSingular()}Remove")
type(type)
child(attr)
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
fun StructureUnitI<*>.addAggregateHandler() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() && it.handlers().isEmpty() }.extend {
handler {
name("Handler")
val initial = state { name("initial") }
}
}
}
fun StructureUnitI<*>.addIdPropToEntities() {
findDownByType(EntityI::class.java).filter { item -> !item.isVirtual() && item.propId() == null }
.forEach {
it.propIdOrAdd()
}
}
fun StructureUnitI<*>.addIdPropToCommands() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() }.forEach { entity ->
entity.findDownByType(CommandI::class.java).forEach { command ->
command.propIdOrAdd()
if (command is ChildCommandByI) {
val childPropId = command.type().propIdFullName()
if (childPropId != null) {
if (command.props().findLast { it.name() == childPropId.name() } == null) {
command.prop(childPropId)
}
}
}
}
}
}
fun StructureUnitI<*>.addIdPropToEvents() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() }.forEach { entity ->
entity.findDownByType(ChildEventI::class.java).forEach { event ->
val childPropId = event.type().propIdFullName()
if (childPropId != null) {
if (event.props().findLast { it.name() == childPropId.name() } == null) {
event.prop(childPropId)
}
}
}
}
}
fun StructureUnitI<*>.addIdPropToEntityValues() {
findDownByType(EntityI::class.java).filter { !it.isVirtual() }.forEach { entity ->
entity.propsCollectionValueTypes().filter { item -> item.propId() == null }
.forEach {
it.prop(entity.propIdOrAdd())
}
}
}
fun StructureUnitI<*>.markReplaceableConfigProps() {
findDownByType(ConfigI::class.java).forEach { item ->
item.props().forEach {
it.replaceable()
}
}
}
fun <T : StructureUnitI<*>> T.markTypesPropsReplaceable(): T {
findDownByType(TypeI::class.java).forEach { item ->
if (item !is EnumTypeI && item !is ControllerI) {
item.props().forEach { prop ->
if (prop.isReplaceable() == null) {
prop.replaceable()
}
}
}
}
return this
}
fun StructureUnitI<*>.setOptionalTagToEventsAndCommandsProps() {
val allProps = hashSetOf<AttributeI<*>>()
findDownByType(EventI::class.java).forEach {
allProps.addAll(it.props().filter { !it.isKey() })
}
findDownByType(CommandI::class.java).forEach {
allProps.addAll(it.props().filter { !it.isKey() })
}
allProps.forEach {
it.setOptionalTag()
}
}
fun AttributeI<*>.setOptionalTag(): AttributeI<*> {
macrosAfterBody(AttributeI<*>::toGoPropOptionalAfterBody.name)
return this
}
fun <T : CompilationUnitI<*>> T.propagateItemToSubtypes(item: CompilationUnitI<*>) {
superUnitFor().filter { superUnitChild ->
superUnitChild.items().filterIsInstance<CompilationUnitI<*>>().find {
(it.name() == item.name() || it.superUnit() == superUnitChild)
} == null
}.forEach { superUnitChild ->
val derivedItem = item.deriveSubType {
namespace(superUnitChild.namespace())
G { type(superUnitChild).name("T") }
}
superUnitChild.addItem(derivedItem)
superUnitChild.propagateItemToSubtypes(derivedItem)
}
}
const val PROP_DELETED_AT = "deletedAt"
fun EntityI<*>.addPropDeletedAt(): AttributeI<*> {
return prop {
key(true).type(n.Date).name(PROP_DELETED_AT)
}
}
fun EntityI<*>.propDeletedAt(): AttributeI<*> = storage.getOrPut(this, "propDeletedAt") {
initIfNotInitialized()
var ret = props().find { it.name() == PROP_DELETED_AT }
if (ret == null && superUnit() is EntityI<*>) {
ret = (superUnit() as EntityI<*>).propDeletedAt()
} else if (ret == null) {
log.debug("prop 'deleted' can't be found for '$this', build default one")
ret = addPropDeletedAt()
}
ret
}
fun TypeI<*>.propsNoMeta(): List<AttributeI<*>> = storage.getOrPut(this, "dataTypeProps") {
propsAll().filter { !it.isMeta() }.map { p(it) }
}
fun EntityI<*>.commandCreate(): CommandI<*> = storage.getOrPut(this, "commandCreate") {
createBy {
name("create")
props(*[email protected]().toTypedArray())
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
fun EntityI<*>.commandUpdate(): CommandI<*> = storage.getOrPut(this, "commandUpdate") {
updateBy {
name("update")
props(*[email protected]().toTypedArray())
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
fun EntityI<*>.commandDelete(): CommandI<*> = storage.getOrPut(this, "commandDelete") {
deleteBy {
name("delete")
constructorFull { derivedAsType(LangDerivedKind.MANUAL) }
}
}
fun StateI<*>.execute(command: CommandI<*>, value: ExecutorI<*>.() -> Unit = {}) = execute {
on(command)
value()
}
fun StateI<*>.handle(event: EventI<*>, value: HandlerI<*>.() -> Unit = {}) = handle {
on(event)
value()
}
fun eventOf(command: CommandI<*>): EventI<*> {
if (command.event().isEMPTY()) {
command.event(command.deriveEvent())
}
return command.event()
}
fun StateI<*>.executeAndProduce(command: CommandI<*>): ExecutorI<*> {
val ret = execute(command)
ret.produce(eventOf(command))
return ret
}
fun StateI<*>.executeAndProduceAndHandle(command: CommandI<*>): HandlerI<*> {
val ret = execute(command)
val event = eventOf(command)
ret.produce(event)
return handle(event)
}
fun EventI<*>.hasData(): Boolean = propsNoMetaNoValueNoId().isNotEmpty() | apache-2.0 | aaae28df8d9d3d50d9949b717a8c8472 | 31.181159 | 118 | 0.604065 | 4.020598 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.