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
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/electronico/comprobantes/factura/Factura.kt
1
1701
package com.quijotelui.electronico.comprobantes.factura import com.quijotelui.electronico.comprobantes.InformacionTributaria import comprobantes.InformacionAdicional import comprobantes.factura.Detalles import comprobantes.factura.InformacionFactura import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement import javax.xml.bind.annotation.XmlType @XmlRootElement @XmlType(propOrder = arrayOf("informacionTributaria", "informacionFactura", "detalles", "informacionAdicional")) class Factura { @XmlAttribute private var id : String? = null @XmlAttribute private var version : String? = null @XmlElement(name = "infoTributaria") private var informacionTributaria = InformacionTributaria() @XmlElement(name = "infoFactura") private var informacionFactura = InformacionFactura() @XmlElement private var detalles = Detalles() @XmlElement(name = "infoAdicional") private var informacionAdicional : InformacionAdicional? = null fun setId(id : String) { this.id = id } fun setVersion(version : String) { this.version = version } fun setInformacionTributaria(informacionTributaria : InformacionTributaria) { this.informacionTributaria = informacionTributaria } fun setInformacionFactura(informacionFactura : InformacionFactura) { this.informacionFactura = informacionFactura } fun setDetalles(detalles : Detalles) { this.detalles = detalles } fun setInformacionAdicional(informacionAdicional: InformacionAdicional) { this.informacionAdicional = informacionAdicional } }
gpl-3.0
a7e50145e553a4a3348d6c2d803329c9
28.344828
112
0.753674
4.647541
false
false
false
false
yzbzz/beautifullife
icore/src/main/java/com/ddu/icore/util/PopupUtils.kt
2
1236
package com.ddu.icore.util import android.app.Activity import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.view.Gravity import android.view.View import android.widget.LinearLayout import android.widget.PopupWindow import com.ddu.icore.R /** * Created by yzbzz on 16/4/18. */ object PopupUtils { fun showTopRightPopupWindow(activity: Activity, view: View, popupView: View) { val frame = Rect() activity.window.decorView.getWindowVisibleDisplayFrame(frame) val location = IntArray(2) view.getLocationOnScreen(location) val popupWindow = showPopupWindow(popupView) popupWindow.showAtLocation(view, Gravity.TOP or Gravity.RIGHT, 0, location[1] + frame.top - popupWindow.height) popupWindow.update() } fun showPopupWindow(popupView: View): PopupWindow { val popupWindow = PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) popupWindow.isFocusable = true popupWindow.isOutsideTouchable = true popupWindow.setBackgroundDrawable(BitmapDrawable()) popupWindow.animationStyle = R.style.MorePopupAnim return popupWindow } }
apache-2.0
46a9db7eac936b2df167db27999a2b84
29.9
128
0.737864
4.544118
false
false
false
false
mhsjlw/AndroidSnap
app/src/main/java/me/keegan/snap/MessageAdapter.kt
1
1820
package me.keegan.snap import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.parse.ParseObject class MessageAdapter(protected var mContext: Context, protected var mMessages: MutableList<ParseObject>) : ArrayAdapter<ParseObject>(mContext, R.layout.message_item, mMessages) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val holder: ViewHolder if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.message_item, null) holder = ViewHolder() holder.iconImageView = convertView!!.findViewById<View>(R.id.messageIcon) as ImageView holder.nameLabel = convertView.findViewById<View>(R.id.senderLabel) as TextView convertView.tag = holder } else { holder = convertView.tag as ViewHolder } val message = mMessages[position] if (message.getString(ParseConstants.KEY_FILE_TYPE) == ParseConstants.TYPE_IMAGE) { holder.iconImageView!!.setImageResource(R.drawable.ic_action_picture) } else { holder.iconImageView!!.setImageResource(R.drawable.ic_action_play_over_video) } holder.nameLabel!!.text = message.getString(ParseConstants.KEY_SENDER_NAME) return convertView } fun refill(messages: List<ParseObject>) { mMessages.clear() mMessages.addAll(messages) notifyDataSetChanged() } private class ViewHolder { internal var iconImageView: ImageView? = null internal var nameLabel: TextView? = null } }
mit
5b8bc06a543d14a26a81b119e624acb9
34.686275
178
0.692857
4.678663
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/relocation/BringIntoViewResponderTest.kt
3
23548
/* * 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.foundation.relocation import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.TestActivity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalFoundationApi::class, ExperimentalCoroutinesApi::class) @SmallTest @RunWith(AndroidJUnit4::class) class BringIntoViewResponderTest { @get:Rule val rule = createAndroidComposeRule<TestActivity>() private fun Float.toDp(): Dp = with(rule.density) { [email protected]() } @Test fun zeroSizedItem_zeroSizedParent_bringIntoView() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() var requestedRect: Rect? = null rule.setContent { Box( Modifier .fakeScrollable { requestedRect = it() } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect.Zero) } } @Test fun bringIntoView_rectInChild() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() var requestedRect: Rect? = null rule.setContent { Box( Modifier .fakeScrollable { requestedRect = it() } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView(Rect(1f, 2f, 3f, 4f)) } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect(1f, 2f, 3f, 4f)) } } @Test fun bringIntoView_childWithSize() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() var requestedRect: Rect? = null rule.setContent { Box(Modifier) { Box( Modifier .fakeScrollable { requestedRect = it() } .size(20f.toDp(), 10f.toDp()) .offset { IntOffset(40, 30) } .bringIntoViewRequester(bringIntoViewRequester) ) } } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect(40f, 30f, 60f, 40f)) } } @Test fun bringIntoView_childBiggerThanParent() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() var requestedRect: Rect? = null rule.setContent { Box( Modifier .size(1f.toDp()) .fakeScrollable { requestedRect = it() } .bringIntoViewRequester(bringIntoViewRequester) .size(20f.toDp(), 10f.toDp()) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect(0f, 0f, 20f, 10f)) } } @Test fun bringIntoView_propagatesToMultipleResponders() { // Arrange. var outerRequest: Rect? = null var innerRequest: Rect? = null val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable { outerRequest = it() } .offset(2f.toDp(), 1f.toDp()) .fakeScrollable { innerRequest = it() } .size(20f.toDp(), 10f.toDp()) .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(innerRequest).isEqualTo(Rect(0f, 0f, 20f, 10f)) assertThat(outerRequest).isEqualTo(Rect(2f, 1f, 22f, 11f)) } } @Test fun bringIntoView_onlyPropagatesUp() { // Arrange. var parentRequest: Rect? = null var childRequest: Rect? = null val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable { parentRequest = it() } .bringIntoViewRequester(bringIntoViewRequester) .fakeScrollable { childRequest = it() } ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(parentRequest).isEqualTo(Rect.Zero) assertThat(childRequest).isNull() } } @Test fun bringIntoView_propagatesUp_whenRectForParentReturnsInput() { // Arrange. var parentRequest: Rect? = null var childRequest: Rect? = null val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable { parentRequest = it() } .fakeScrollable { childRequest = it() } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(parentRequest).isEqualTo(Rect.Zero) assertThat(childRequest).isEqualTo(Rect.Zero) } } @Test fun bringIntoView_translatesByCalculateRectForParent() { // Arrange. var requestedRect: Rect? = null val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable { requestedRect = it() } .fakeScrollable(Offset(2f, 3f)) {} .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect(2f, 3f, 2f, 3f)) } } @Test fun bringIntoView_noops_whenNewRequestEqualToCurrent() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() val initialRequest = requests.single() assertThat(initialRequest.isActive).isTrue() requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) assertThat(requests.single()).isSameInstanceAs(initialRequest) assertThat(initialRequest.isActive).isTrue() } @Test fun bringIntoView_noops_whenNewRequestContainedInCurrent() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() val initialRequest = requests.single() assertThat(initialRequest.isActive).isTrue() requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(1f, 1f, 9f, 9f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) assertThat(requests.single()).isSameInstanceAs(initialRequest) assertThat(initialRequest.isActive).isTrue() } @Test fun bringIntoView_interruptsCurrentRequest_whenNewRequestOverlapsButNotContainedByCurrent() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() val initialRequest = requests.single() assertThat(initialRequest.isActive).isTrue() requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(5f, 5f, 15f, 15f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(2) val newRequest = requests.last() assertThat(newRequest).isNotSameInstanceAs(initialRequest) assertThat(newRequest.isActive).isTrue() } @Test fun bringIntoView_interruptsCurrentRequest_whenNewRequestOutsideCurrent() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() val initialRequest = requests.single() assertThat(initialRequest.isActive).isTrue() requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(15f, 15f, 20f, 20f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(2) val newRequest = requests.last() assertThat(newRequest).isNotSameInstanceAs(initialRequest) assertThat(newRequest.isActive).isTrue() } /** * When an ongoing request is interrupted, it shouldn't be cancelled: the implementor is * responsible for cancelling ongoing work. */ @Test fun bringIntoView_doesNotCancelOngoingRequest_whenInterrupted() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) // Act. requestScope.launch { // Send an interrupting request. bringIntoViewRequester.bringIntoView(rect = Rect(15f, 15f, 20f, 20f)) } requestScope.advanceUntilIdle() // Assert. assertThat(requests).hasSize(2) assertThat(requests.first().isActive).isTrue() } @Test fun bringIntoView_suspendsUntilPreviousRequestComplete_whenOverlapping() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) // Act. requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() // Assert. // Second request shouldn't have been dispatched yet. assertThat(requests).hasSize(1) } @Test fun bringIntoView_resumes_whenOverlappingPreviousRequestCancelled() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } val firstRequestJob = requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) // Act. firstRequestJob.cancel() requestScope.advanceUntilIdle() // Assert. assertThat(requests).hasSize(2) assertThat(requests.last().isActive).isTrue() } @Test fun bringIntoView_neverCallsQueuedResponders_whenInterrupted() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val requests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() var startedRequests = 0 rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { requests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } repeat(5) { requestScope.launch { startedRequests++ bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } } requestScope.advanceUntilIdle() assertThat(requests).hasSize(1) // Act. val lastJob = requestScope.launch { startedRequests++ bringIntoViewRequester.bringIntoView(rect = Rect(15f, 15f, 20f, 20f)) } // Cancelling the first request *without* a new request will cause the next request to // start – but in this case the next request should detect that it was also interrupted and // never even be dispatched. requests.first().cancel() requestScope.advanceUntilIdle() // Assert. assertThat(startedRequests).isEqualTo(6) assertThat(requests).hasSize(2) assertThat(requests.last().isActive).isTrue() assertThat(requests.last().context.job.isChildOf(lastJob)).isTrue() } @Test fun bringIntoView_childResponderNotCancelled_whenParentCancelled() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val childRequests = mutableListOf<CancellableContinuation<Unit>>() val parentRequests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { parentRequests += it } } .fakeScrollable { suspendCancellableCoroutine { childRequests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(childRequests).hasSize(1) assertThat(parentRequests).hasSize(1) // Act. parentRequests.single().cancel() // Assert. assertThat(childRequests.single().isActive).isTrue() } @Test fun bringIntoView_parentResponderNotCancelled_whenChildCancelled() { // Arrange. val bringIntoViewRequester = BringIntoViewRequester() val childRequests = mutableListOf<CancellableContinuation<Unit>>() val parentRequests = mutableListOf<CancellableContinuation<Unit>>() val requestScope = TestScope() rule.setContent { Box( Modifier .fakeScrollable { suspendCancellableCoroutine { parentRequests += it } } .fakeScrollable { suspendCancellableCoroutine { childRequests += it } } .bringIntoViewRequester(bringIntoViewRequester) ) } requestScope.launch { bringIntoViewRequester.bringIntoView(rect = Rect(0f, 0f, 10f, 10f)) } requestScope.advanceUntilIdle() assertThat(childRequests).hasSize(1) assertThat(parentRequests).hasSize(1) // Act. childRequests.single().cancel() // Assert. assertThat(parentRequests.single().isActive).isTrue() } @Test fun bringChildIntoView_isCalled_whenRectForParentDoesNotReturnInput() { // Arrange. var requestedRect: Rect? = null val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable(Offset.Zero) { requestedRect = it() } .bringIntoViewRequester(bringIntoViewRequester) ) } // Act. runBlocking { bringIntoViewRequester.bringIntoView() } // Assert. rule.runOnIdle { assertThat(requestedRect).isEqualTo(Rect.Zero) } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun bringChildIntoView_calledConcurrentlyOnAllResponders() { // Arrange. var childStarted = false var parentStarted = false var childFinished = false var parentFinished = false val bringIntoViewRequester = BringIntoViewRequester() rule.setContent { Box( Modifier .fakeScrollable { parentStarted = true try { awaitCancellation() } finally { parentFinished = true } } .fakeScrollable { childStarted = true try { awaitCancellation() } finally { childFinished = true } } .bringIntoViewRequester(bringIntoViewRequester) ) } val testScope = TestScope() val requestJob = testScope.launch { bringIntoViewRequester.bringIntoView() } rule.waitForIdle() assertThat(childStarted).isFalse() assertThat(parentStarted).isFalse() assertThat(childFinished).isFalse() assertThat(parentFinished).isFalse() // Act. testScope.advanceUntilIdle() // Assert. assertThat(childStarted).isTrue() assertThat(parentStarted).isTrue() assertThat(childFinished).isFalse() assertThat(parentFinished).isFalse() // Act. requestJob.cancel() testScope.advanceUntilIdle() // Assert. assertThat(childFinished).isTrue() assertThat(parentFinished).isTrue() } @Test fun isChildOf_returnsTrue_whenDirectChild() { val parent = Job() val child = Job(parent) assertThat(child.isChildOf(parent)).isTrue() } @Test fun isChildOf_returnsTrue_whenIndirectChild() { val root = Job() val parent = Job(root) val child = Job(parent) assertThat(child.isChildOf(root)).isTrue() } @Test fun isChildOf_returnsFalse_whenReceiverIsParent() { val parent = Job() val child = Job(parent) assertThat(parent.isChildOf(child)).isFalse() } @Test fun isChildOf_returnsFalse_whenUnrelated() { val job1 = Job() val job2 = Job() assertThat(job1.isChildOf(job2)).isFalse() } private fun Job.isChildOf(expectedParent: Job): Boolean = expectedParent.children.any { it === this || this.isChildOf(it) } }
apache-2.0
1c99a8ae6bcdaf4d47c1b4f087b27451
32.118143
99
0.585535
5.195499
false
true
false
false
yschimke/okhttp
okhttp/src/commonMain/kotlin/okhttp3/internal/-UtilCommon.kt
1
10253
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal import kotlin.jvm.JvmField import okhttp3.OkHttp import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString.Companion.decodeHex import okio.Closeable import okio.FileNotFoundException import okio.FileSystem import okio.IOException import okio.Options import okio.Path import okio.use // TODO: migrate callers to [Regex.matchAt] when that API is not experimental. internal fun Regex.matchAtPolyfill(input: CharSequence, index: Int): MatchResult? { val candidate = find(input, index) ?: return null if (candidate.range.first != index) return null // Didn't match where it should have. return candidate } @JvmField val EMPTY_BYTE_ARRAY: ByteArray = ByteArray(0) /** Byte order marks. */ internal val UNICODE_BOMS = Options.of( "efbbbf".decodeHex(), // UTF-8 "feff".decodeHex(), // UTF-16BE "fffe".decodeHex(), // UTF-16LE "0000ffff".decodeHex(), // UTF-32BE "ffff0000".decodeHex() // UTF-32LE ) /** * Returns an array containing only elements found in this array and also in [other]. The returned * elements are in the same order as in this. */ internal fun Array<String>.intersect( other: Array<String>, comparator: Comparator<in String> ): Array<String> { val result = mutableListOf<String>() for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { result.add(a) break } } } return result.toTypedArray() } /** * Returns true if there is an element in this array that is also in [other]. This method terminates * if any intersection is found. The sizes of both arguments are assumed to be so small, and the * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the * memory cost of hashing. */ internal fun Array<String>.hasIntersection( other: Array<String>?, comparator: Comparator<in String> ): Boolean { if (isEmpty() || other == null || other.isEmpty()) { return false } for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { return true } } } return false } internal fun Array<String>.indexOf(value: String, comparator: Comparator<String>): Int = indexOfFirst { comparator.compare(it, value) == 0 } @Suppress("UNCHECKED_CAST") internal fun Array<String>.concat(value: String): Array<String> { val result = copyOf(size + 1) result[result.lastIndex] = value return result as Array<String> } /** Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. */ internal fun String.indexOfFirstNonAsciiWhitespace( startIndex: Int = 0, endIndex: Int = length ): Int { for (i in startIndex until endIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i } } return endIndex } /** * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex]. */ internal fun String.indexOfLastNonAsciiWhitespace( startIndex: Int = 0, endIndex: Int = length ): Int { for (i in endIndex - 1 downTo startIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i + 1 } } return startIndex } /** Equivalent to `string.substring(startIndex, endIndex).trim()`. */ fun String.trimSubstring(startIndex: Int = 0, endIndex: Int = length): String { val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex) val end = indexOfLastNonAsciiWhitespace(start, endIndex) return substring(start, end) } /** * Returns the index of the first character in this string that contains a character in * [delimiters]. Returns endIndex if there is no such character. */ fun String.delimiterOffset( delimiters: String, startIndex: Int = 0, endIndex: Int = length ): Int { for (i in startIndex until endIndex) { if (this[i] in delimiters) return i } return endIndex } /** * Returns the index of the first character in this string that is [delimiter]. Returns [endIndex] * if there is no such character. */ fun String.delimiterOffset( delimiter: Char, startIndex: Int = 0, endIndex: Int = length ): Int { for (i in startIndex until endIndex) { if (this[i] == delimiter) return i } return endIndex } /** * Returns the index of the first character in this string that is either a control character (like * `\u0000` or `\n`) or a non-ASCII character. Returns -1 if this string has no such characters. */ internal fun String.indexOfControlOrNonAscii(): Int { for (i in 0 until length) { val c = this[i] if (c <= '\u001f' || c >= '\u007f') { return i } } return -1 } /** Returns true if we should void putting this this header in an exception or toString(). */ internal fun isSensitiveHeader(name: String): Boolean { return name.equals("Authorization", ignoreCase = true) || name.equals("Cookie", ignoreCase = true) || name.equals("Proxy-Authorization", ignoreCase = true) || name.equals("Set-Cookie", ignoreCase = true) } internal fun Char.parseHexDigit(): Int = when (this) { in '0'..'9' -> this - '0' in 'a'..'f' -> this - 'a' + 10 in 'A'..'F' -> this - 'A' + 10 else -> -1 } internal infix fun Byte.and(mask: Int): Int = toInt() and mask internal infix fun Short.and(mask: Int): Int = toInt() and mask internal infix fun Int.and(mask: Long): Long = toLong() and mask @Throws(IOException::class) internal fun BufferedSink.writeMedium(medium: Int) { writeByte(medium.ushr(16) and 0xff) writeByte(medium.ushr(8) and 0xff) writeByte(medium and 0xff) } @Throws(IOException::class) internal fun BufferedSource.readMedium(): Int { return (readByte() and 0xff shl 16 or (readByte() and 0xff shl 8) or (readByte() and 0xff)) } /** Run [block] until it either throws an [IOException] or completes. */ internal inline fun ignoreIoExceptions(block: () -> Unit) { try { block() } catch (_: IOException) { } } internal fun Buffer.skipAll(b: Byte): Int { var count = 0 while (!exhausted() && this[0] == b) { count++ readByte() } return count } /** * Returns the index of the next non-whitespace character in this. Result is undefined if input * contains newline characters. */ internal fun String.indexOfNonWhitespace(startIndex: Int = 0): Int { for (i in startIndex until length) { val c = this[i] if (c != ' ' && c != '\t') { return i } } return length } fun String.toLongOrDefault(defaultValue: Long): Long { return try { toLong() } catch (_: NumberFormatException) { defaultValue } } /** * Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too * large, or [defaultValue] if it cannot be parsed. */ internal fun String?.toNonNegativeInt(defaultValue: Int): Int { try { val value = this?.toLong() ?: return defaultValue return when { value > Int.MAX_VALUE -> Int.MAX_VALUE value < 0 -> 0 else -> value.toInt() } } catch (_: NumberFormatException) { return defaultValue } } /** Closes this, ignoring any checked exceptions. */ fun Closeable.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** * Returns true if file streams can be manipulated independently of their paths. This is typically * true for systems like Mac, Unix, and Linux that use inodes in their file system interface. It is * typically false on Windows. * * If this returns false we won't permit simultaneous reads and writes. When writes commit we need * to delete the previous snapshots, and that won't succeed if the file is open. (We do permit * multiple simultaneous reads.) * * @param file a file in the directory to check. This file shouldn't already exist! */ internal fun FileSystem.isCivilized(file: Path): Boolean { sink(file).use { try { delete(file) return true } catch (_: IOException) { } } delete(file) return false } /** Delete file we expect but don't require to exist. */ internal fun FileSystem.deleteIfExists(path: Path) { try { delete(path) } catch (fnfe: FileNotFoundException) { return } } /** Tolerant delete, try to clear as many files as possible even after a failure. */ internal fun FileSystem.deleteContents(directory: Path) { var exception: IOException? = null val files = try { list(directory) } catch (fnfe: FileNotFoundException) { return } for (file in files) { try { if (metadata(file).isDirectory) { deleteContents(file) } delete(file) } catch (ioe: IOException) { if (exception == null) { exception = ioe } } } if (exception != null) { throw exception } } internal fun <E> MutableList<E>.addIfAbsent(element: E) { if (!contains(element)) add(element) } internal fun Exception.withSuppressed(suppressed: List<Exception>): Throwable = apply { for (e in suppressed) addSuppressed(e) } internal inline fun <T> Iterable<T>.filterList(predicate: T.() -> Boolean): List<T> { var result: List<T> = emptyList() for (i in this) { if (predicate(i)) { if (result.isEmpty()) result = mutableListOf() (result as MutableList<T>).add(i) } } return result } internal const val userAgent: String = "okhttp/${OkHttp.VERSION}" internal fun <T> interleave(a: Iterable<T>, b: Iterable<T>): List<T> { val ia = a.iterator() val ib = b.iterator() return buildList { while (ia.hasNext() || ib.hasNext()) { if (ia.hasNext()) { add(ia.next()) } if (ib.hasNext()) { add(ib.next()) } } } }
apache-2.0
263c12e41e878e2a9e17cf356f3e105e
26.124339
100
0.667317
3.752928
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/models/SplashImage.kt
1
1588
package org.thoughtcrime.securesms.components.settings.models import android.view.View import android.widget.ImageView import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.PreferenceModel import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder /** * Renders a single image, horizontally centered. */ object SplashImage { fun register(mappingAdapter: MappingAdapter) { mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.splash_image)) } class Model(@DrawableRes val splashImageResId: Int, @ColorRes val splashImageTintResId: Int = -1) : PreferenceModel<Model>() { override fun areItemsTheSame(newItem: Model): Boolean { return newItem.splashImageResId == splashImageResId && newItem.splashImageTintResId == splashImageTintResId } } private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) { private val splashImageView: ImageView = itemView as ImageView override fun bind(model: Model) { splashImageView.setImageResource(model.splashImageResId) if (model.splashImageTintResId != -1) { splashImageView.setColorFilter(ContextCompat.getColor(context, model.splashImageTintResId)) } else { splashImageView.clearColorFilter() } } } }
gpl-3.0
9d1000f881c9bd0e569bf7b9dda648fb
35.930233
128
0.783375
4.616279
false
false
false
false
yuncheolkim/gitmt
src/main/kotlin/com/joyouskim/git/Receive.kt
1
4820
package com.joyouskim.git import com.joyouskim.http.* import com.joyouskim.log.COMMON import io.netty.handler.codec.http.HttpResponseStatus import io.vertx.core.http.HttpMethod import io.vertx.kotlin.lang.contentType import io.vertx.kotlin.lang.setStatus import org.eclipse.jgit.lib.PersonIdent import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.transport.* import org.eclipse.jgit.transport.resolver.ReceivePackFactory import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException import org.eclipse.jgit.util.HttpSupport import java.io.IOException import java.io.OutputStream /** * Created by jinyunzhe on 16/4/7. */ class DefaultReceivePackFy : ReceivePackFactory<HttpRequest>{ override fun create(req: HttpRequest?, db: Repository?): ReceivePack? { val user = "anonymous" return createFor(req,db,user) } private fun createFor(req: HttpRequest?, db: Repository?, user: String): ReceivePack? { val rp = ReceivePack(db) rp.refLogIdent = toPersonIdent(req, user) return rp } private fun toPersonIdent(req: HttpRequest?, user: String): PersonIdent? { return PersonIdent(user,"$user@${req?.getRemoteHost()}") } } class ReceiveAction : Action { override fun doAction(httpRequest: HttpRequest, httpResponse: HttpResponse) { if(httpRequest.method() != HttpMethod.POST){ return } if (RECEIVE_PACK_REQUEST_TYPE != httpRequest.getContentType()) { httpResponse.statusCode = HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code() return } val out = object : SmartOutputStream(httpRequest,httpResponse,false){ override fun flush() { doFlush() } } val rp: ReceivePack = httpRequest.attMap[ATTRIBUTE_HANDLER] as ReceivePack try{ rp.isBiDirectionalPipe = false httpResponse.contentType(RECEIVE_PACK_RESULT_TYPE) rp.receive(getInputStream(httpRequest),out, null ) out.close() }catch(e: ServiceMayNotContinueException){ if (e.isOutput) { httpRequest.consumeBody() }else if (!httpResponse.ended()) { sendError(httpRequest,httpResponse,HttpResponseStatus.FORBIDDEN.code(),e.message) } COMMON.error("",e) return; }catch(e: UploadPackInternalServerErrorException){ httpRequest.consumeBody() COMMON.error("",e) }catch(e:Throwable){ if (!httpResponse.ended()) { sendError(httpRequest,httpResponse,HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),e.message) } COMMON.error("",e) return } } override fun init() { } class Factory(val receivePackFactory: ReceivePackFactory<HttpRequest>) : Filter { override fun init() { } override fun doFilter(httpRequest: HttpRequest, httpResponse: HttpResponse, filterChain: FilterChain) { try { var up = receivePackFactory.create(httpRequest, getRepository(httpRequest)) httpRequest.attMap.put(ATTRIBUTE_HANDLER, up) filterChain.doFilterChain(httpRequest, httpResponse) } catch(e: ServiceNotAuthorizedException) { httpResponse.setStatus(HttpResponseStatus.UNAUTHORIZED.code(), e.message.toString()) COMMON.error("",e) return } catch(e: ServiceNotEnabledException) { sendError(httpRequest, httpResponse, HttpResponseStatus.FORBIDDEN.code(), e.message) COMMON.error("",e) return }finally{ httpRequest.attMap.remove(ATTRIBUTE_HANDLER) } } } class Info(val receivePackFactory: ReceivePackFactory<HttpRequest>, override val filters:Array<Filter>):SmartServiceInfoRefs(RECEIVE_PACK,filters){ override fun init() { } override fun advertise(httpRequest: HttpRequest, pck: RefAdvertiser.PacketLineOutRefAdvertiser) { val up:ReceivePack = httpRequest.attMap[ATTRIBUTE_HANDLER] as ReceivePack try{ up.sendAdvertisedRefs(pck) }catch(e:Exception){ COMMON.error("",e) }finally{ up.revWalk.close() } } override fun begin(httpRequest: HttpRequest, db: Repository) { val up = receivePackFactory.create(httpRequest,db) InternalHttpServerGlue.setPeerUserAgent(up,httpRequest.getHeader(HttpSupport.HDR_USER_AGENT)) httpRequest.attMap.put(ATTRIBUTE_HANDLER,up) } } }
mit
6e253da8306f5762b6143465015b6386
33.184397
151
0.638589
4.573055
false
false
false
false
MarcelBlanck/AoC2016
src/main/kotlin/day2/BathroomKeypadSolver.kt
1
4669
/* * MIT License * * Copyright (c) 2017 Marcel Blanck * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package day2 class BathroomKeypadSolver { fun findNineKeypadCombination(instructions: List<String>) : List<Int> = findKeypadCombination(5, emptyList(), instructions, NineKeypadStepper()) fun findThirteenKeypadCombination(instructions: List<String>) : List<Int> = findKeypadCombination(5, emptyList(), instructions, ThirteenKeypadStepper()) private tailrec fun findKeypadCombination(currentKey: Int, knownKeycode: List<Int>, instructions: List<String>, keypadStepper: KeypadStepper) : List<Int> = if (instructions.isEmpty()) { knownKeycode } else { val nextKey = followInstruction(currentKey, instructions.first(), keypadStepper) findKeypadCombination( nextKey, knownKeycode.plus(nextKey), instructions.takeLast(instructions.count() - 1), keypadStepper) } private tailrec fun followInstruction(currentKey: Int, instruction: String, keypadStepper: KeypadStepper) : Int = if (instruction.isEmpty()) { currentKey } else { val nextKey = keypadStepper.step(currentKey, instruction.first()) followInstruction(nextKey, instruction.takeLast(instruction.length - 1), keypadStepper) } } internal interface KeypadStepper { fun step(currentKey: Int, instruction: Char): Int } internal class NineKeypadStepper : KeypadStepper { override fun step(currentKey: Int, instructionStep: Char) : Int = when (instructionStep) { 'R' -> when (currentKey) { 3, 6, 9 -> currentKey else -> currentKey + 1 } 'L' -> when (currentKey) { 1, 4, 7 -> currentKey else -> currentKey - 1 } 'D' -> when (currentKey) { 7, 8, 9 -> currentKey else -> currentKey + 3 } 'U' -> when (currentKey) { 1, 2, 3 -> currentKey else -> currentKey - 3 } else -> throw IllegalArgumentException("Illegal instruction step found $instructionStep") } } internal class ThirteenKeypadStepper : KeypadStepper { override fun step(currentKey: Int, instructionStep: Char) : Int = when (instructionStep) { 'R' -> when (currentKey) { 0x1, 0x4, 0x9, 0xC, 0xD -> currentKey else -> currentKey + 1 } 'L' -> when (currentKey) { 0x1, 0x2, 0x5, 0xA, 0xD -> currentKey else -> currentKey - 1 } 'D' -> when (currentKey) { 0x5, 0xA, 0xD, 0xC, 0x9 -> currentKey 0x1, 0xB -> currentKey + 2 else -> currentKey + 4 } 'U' -> when (currentKey) { 0x1, 0x2, 0x4, 0x5, 0x9 -> currentKey 0x3, 0xD -> currentKey - 2 else -> currentKey - 4 } else -> throw IllegalArgumentException("Illegal instruction step found $instructionStep") } }
mit
1a2ac745c293cabbaf41926c7d204163
40.6875
105
0.556222
4.935518
false
false
false
false
inorichi/tachiyomi-extensions
src/en/mangamiso/src/eu/kanade/tachiyomi/extension/en/mangamiso/MangaMiso.kt
1
15253
package eu.kanade.tachiyomi.extension.en.mangamiso import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.jsonObject import okhttp3.HttpUrl import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.injectLazy import java.lang.Exception import java.text.SimpleDateFormat import java.util.Locale @Nsfw class MangaMiso : HttpSource() { companion object { const val MANGA_PER_PAGE = 50 val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US) const val PREFIX_ID_SEARCH = "id:" } override val name = "MangaMiso" override val baseUrl = "https://mangamiso.net" override val lang = "en" override val supportsLatest = true override val client = network.cloudflareClient private val json: Json by injectLazy() override fun popularMangaRequest(page: Int): Request { val url = getBaseURLBuilder() .addPathSegment("mangas-get") .addPathSegment("get-new-mangas") .addQueryParameter("perPage", MANGA_PER_PAGE.toString()) .addQueryParameter("page", page.toString()) .toString() return GET(url, headers) } override fun popularMangaParse(response: Response): MangasPage { val mangaList = json.decodeFromString<MisoNewMangaPage>(response.body!!.string()) val page = response.request.url.queryParameter("page")!!.toInt() val totalViewedManga = page * MANGA_PER_PAGE return MangasPage(mangaList.newManga.map(::toSManga), mangaList.total > totalViewedManga) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val builder = getBaseURLBuilder() .addQueryParameter("perPage", MANGA_PER_PAGE.toString()) .addQueryParameter("page", page.toString()) return when { query.startsWith(PREFIX_ID_SEARCH) -> { val id = query.removePrefix(PREFIX_ID_SEARCH) val url = "$baseUrl/mangas/$id" return GET(url, headers) } query.isNotBlank() -> throw UnsupportedOperationException("Text search currently not supported") else -> { val url = builder.addPathSegment("genres") var tagCount = 0 filters.forEach { filter -> when (filter) { is MangaStatusFilter -> { val statusSlug = filter.toUriPart() url.addQueryParameter("status", statusSlug) } is UriPartFilter -> { if (filter.toUriPart() != "") { val genreSlug = filter.toUriPart() url.addPathSegment(genreSlug) tagCount++ if (tagCount > 1) { throw UnsupportedOperationException("Too many categories selected") } } } else -> {} } } // If no filters selected, default to "all" if (tagCount == 0) { url.addPathSegment("all") } GET(url.toString(), headers) } } } override fun searchMangaParse(response: Response): MangasPage { // This search was for a specific manga id return if (response.request.url.pathSegments[0] == "mangas") { val manga = mangaDetailsParse(response) MangasPage(listOf(manga), false) } else { val mangaList = json.decodeFromString<MisoBrowseManga>(response.body!!.string()) val page = response.request.url.queryParameter("page")!!.toInt() val totalViewedManga = page * MANGA_PER_PAGE MangasPage(mangaList.foundList.map(::toSManga), mangaList.total > totalViewedManga) } } override fun latestUpdatesRequest(page: Int): Request { val url = getBaseURLBuilder() .addPathSegment("mangas-get") .addPathSegment("get-latestUpdate-mangas") .addQueryParameter("perPage", MANGA_PER_PAGE.toString()) .addQueryParameter("page", page.toString()) return GET(url.toString(), headers) } override fun latestUpdatesParse(response: Response): MangasPage { val mangaList = json.decodeFromString<MisoLatestUpdatesPage>(response.body!!.string()) val page = response.request.url.queryParameter("page")!!.toInt() val totalViewedManga = page * MANGA_PER_PAGE return MangasPage(mangaList.newManga.map(::toSManga), mangaList.total > totalViewedManga) } // Since mangaDetailsRequest is what drives the webview, // we are using this solely to provide that URL override fun mangaDetailsRequest(manga: SManga): Request { return GET(manga.url, headers) } // This is what actually gets the manga details override fun fetchMangaDetails(manga: SManga): Observable<SManga> { val jsonURL = manga.url.replace("/manga/", "/mangas/") return client.newCall( GET(jsonURL, headers) ).asObservableSuccess() .map { response -> mangaDetailsParse(response) } } override fun mangaDetailsParse(response: Response): SManga { val mangaRoot = json.parseToJsonElement(response.body!!.string()) val mangaObj = mangaRoot.jsonObject["manga"]!! return toSManga(json.decodeFromJsonElement(mangaObj)) } private fun cleanDescription(mangaDesc: String): String { // Get description up to the closing tag (</p>) var description = mangaDesc.substringBefore("</p>") // Convert any breaks <br> to newlines description = description.replace("<br>", "\n") // Replace any other tags with nothing description = description.replace("<.*?>".toRegex(), "") return description } private fun mapStatus(status: String) = when (status) { "ongoing", "hiatus" -> SManga.ONGOING "completed", "cancelled" -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListRequest(manga: SManga): Request { val url = "${manga.url.replace("/manga/", "/mangas/")}/get-manga-chapters-12345?page=1&perPage=9999&sort=-1" return GET(url, headers) } override fun chapterListParse(response: Response): List<SChapter> { val chapterRoot = json.parseToJsonElement(response.body!!.string()) val chapterBase = chapterRoot.jsonObject["chapters"]!! val chapterList = json.decodeFromJsonElement<MisoChapterList>(chapterBase) val path = response.request.url.pathSegments[1] // this is the pathName of the manga return chapterList.chapters.map { toSChapter(it, "$baseUrl/manga/$path") } } override fun pageListRequest(chapter: SChapter): Request { return GET(chapter.url.replace("/manga/", "/mangas/"), headers) } override fun pageListParse(response: Response): List<Page> { val chapterRoot = json.parseToJsonElement(response.body!!.string()) val chapterBase = chapterRoot.jsonObject["chapter"]!! val pageList = json.decodeFromJsonElement<MisoPageList>(chapterBase) return pageList.pages.mapIndexed { index, misoPage -> val imgURL = "$baseUrl${misoPage.path}" Page( index, imgURL, imgURL ) } } override fun imageUrlParse(response: Response) = throw UnsupportedOperationException("Not used.") //region Filter Classes private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } private class MangaStatusFilter : UriPartFilter( "Manga Status", arrayOf( Pair("All", "all"), Pair("Ongoing", "ongoing"), Pair("Completed", "completed"), Pair("Cancelled", "cancelled"), Pair("On Hiatus", "hiatus") ) ) private class DemographicFilter : UriPartFilter( "Demographic", arrayOf( Pair("<Select>", ""), Pair("Shounen", "shounen"), Pair("Shoujo", "shoujo"), Pair("Seinen", "seinen"), Pair("Josei", "josei") ) ) private class GenreFilter : UriPartFilter( "Genre", arrayOf( Pair("<Select>", ""), Pair("Action", "action"), Pair("Adventure", "adventure"), Pair("Comedy", "comedy"), Pair("Crime", "crime"), Pair("Drama", "drama"), Pair("Fantasy", "fantasy"), Pair("Historical", "historical"), Pair("Horror", "horror"), Pair("Isekai", "isekai"), Pair("Magical Girls", "magical_girls"), Pair("Mature", "mature"), Pair("Mecha", "mecha"), Pair("Medical", "medical"), Pair("Mystery", "mystery"), Pair("Philosopical", "philosopical"), Pair("Psychological", "psychological"), Pair("Romance", "romance"), Pair("Sci-fi", "sci-fi"), Pair("Shoujo Ai", "shoujo_ai"), Pair("Shounen Ai", "shounen_ai"), Pair("Slice of Life", "slice_of_life"), Pair("Sports", "sports"), Pair("Superhero", "superhero"), Pair("Thriller", "thriller"), Pair("Tragedy", "tragedy"), Pair("Wuxia", "wuxia"), Pair("Yaoi", "yaoi"), Pair("Yuri", "yuri") ) ) private class ThemeFilter : UriPartFilter( "Themes", arrayOf( Pair("<Select>", ""), Pair("Aliens", "aliens"), Pair("Animals", "animals"), Pair("Cooking", "cooking"), Pair("Crossdressing", "crossdressing"), Pair("Delinquents", "delinquents"), Pair("Demons", "demons"), Pair("Games", "games"), Pair("Gender bender", "gender_bender"), Pair("Ghosts", "ghosts"), Pair("Gyaru", "gyaru"), Pair("Harem", "harem"), Pair("Mafia", "mafia"), Pair("Magic", "magic"), Pair("Martial Arts", "martial_arts"), Pair("Military", "military"), Pair("Monster Girls", "monster_girls"), Pair("Monsters", "monsters"), Pair("Music", "music"), Pair("Ninja", "ninja"), Pair("Office", "office"), Pair("Police", "police"), Pair("Post Apocalyptic", "post_apocalyptic"), Pair("Reincarnation", "reincarnation"), Pair("Reverse Harem", "reverse_harem"), Pair("Samurai", "samurai"), Pair("School Life", "school_life"), Pair("Supernatural", "supernatural"), Pair("Super Power", "super_power"), Pair("Survival", "survival"), Pair("Time Travel", "time_travel"), Pair("Vampires", "vampires"), Pair("Video Games", "video_games"), Pair("Villainess", "villainess"), Pair("Virtual Reality", "virtual_reality"), Pair("Zombies", "zombies") ) ) private class ContentTypeFilter : UriPartFilter( "Content Type", arrayOf( Pair("<Select>", ""), Pair("4-Koma", "4-Koma"), Pair("Anthology", "anthology"), Pair("Doujinshi", "doujinshi"), Pair("Fan Colored", "fan-colored"), Pair("Full Colored", "full-colored"), Pair("Long Strip", "long_strip"), Pair("Manhwa", "manhwa"), Pair("Officially Colored", "officially-colored"), Pair("One Shot", "one_shot"), Pair("Partly-Colored", "partly-colored"), Pair("Web Comic", "web_comic"), ) ) private class ContentWarningFilter : UriPartFilter( "Content Warning", arrayOf( Pair("<Select>", ""), Pair("Adult", "adult"), Pair("Ecchi", "ecchi"), Pair("Gore", "gore"), Pair("Sexual Violence", "sexual_violence"), Pair("Smut", "smut") ) ) private class GloryFilter : UriPartFilter( "Glory", arrayOf( Pair("<Select>", ""), Pair("Adaptation", "adaptation"), Pair("Adapted to Anime", "adapted_to_anime"), Pair("Award Winning", "award_winning") ) ) //endregion override fun getFilterList(): FilterList { return FilterList( MangaStatusFilter(), Filter.Header("Max 1 selection from any of the below categories"), DemographicFilter(), GenreFilter(), ThemeFilter(), ContentTypeFilter(), ContentWarningFilter(), GloryFilter() ) } private fun getBaseURLBuilder(): HttpUrl.Builder { return HttpUrl.Builder() .scheme("https") .host("mangamiso.net") } private fun toSManga(manga: MisoManga): SManga { return SManga.create().apply { title = manga.title author = manga.author.joinToString(",", transform = ::humanizeID) artist = manga.artist.joinToString(",", transform = ::humanizeID) thumbnail_url = "$baseUrl${manga.coverImage}" url = "$baseUrl/manga/${manga.pathName}" genre = manga.tags.joinToString(", ") { humanizeID(it) } description = cleanDescription(manga.description) status = mapStatus(manga.status) } } private fun toSChapter(chapter: MisoChapter, mangaURL: String): SChapter { return SChapter.create().apply { name = chapter.title date_upload = try { DATE_FORMAT.parse(chapter.createdAt)!!.time } catch (e: Exception) { System.currentTimeMillis() } url = "$mangaURL/${chapter.pathName}" chapter_number = chapter.chapterNum } } // Convert the id of authors / artists / tags to a better form. (Eg. school_life -> School Life) private fun humanizeID(text: String) = text.split("_").joinToString(" ") { it.capitalize(Locale.US) } }
apache-2.0
2e7548b3135ad6ff0390225f862bc2e7
35.577938
129
0.570183
4.657405
false
false
false
false
bastman/kotlin-spring-jpa-examples
src/main/kotlin/com/example/demo/api/common/validation/annotations/NotBlankOrNull.kt
1
1685
package com.example.demo.api.common.validation.annotations import org.hibernate.validator.constraints.CompositionType.OR import org.hibernate.validator.constraints.ConstraintComposition import javax.validation.Constraint import javax.validation.Payload import javax.validation.constraints.Null import kotlin.reflect.KClass import org.hibernate.validator.constraints.NotBlank as HibernateNotBlank @ConstraintComposition(OR) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FIELD, AnnotationTarget.ANNOTATION_CLASS) @Retention(AnnotationRetention.RUNTIME) @Constraint(validatedBy = arrayOf()) @MustBeDocumented @Null @NotBlankComposition annotation class NotBlankOrNull( // see: https://github.com/lukaszguz/optional-field-validation/blob/master/src/main/java/pl/guz/domain/validation/OptionalSpecialField.java val message: String = "{}", val groups: Array<KClass<*>> = arrayOf(), val payload: Array<KClass<out Payload>> = arrayOf() ) @ConstraintComposition @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FIELD, AnnotationTarget.ANNOTATION_CLASS) @Retention(AnnotationRetention.RUNTIME) @Constraint(validatedBy = arrayOf()) @MustBeDocumented @HibernateNotBlank annotation class NotBlankComposition( // see: // see: https://github.com/lukaszguz/optional-field-validation/blob/master/src/main/java/pl/guz/domain/validation/OptionalSpecialField.java val message: String = "{}", val groups: Array<KClass<*>> = arrayOf(), val payload: Array<KClass<out Payload>> = arrayOf() )
mit
e7e860ad116daa6dd0ddba2628fad8ad
40.097561
161
0.791691
4.365285
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/news/NewsFragment.kt
1
4571
package de.tum.`in`.tumcampusapp.component.ui.news import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl.USE_CACHE import de.tum.`in`.tumcampusapp.component.other.generic.adapter.EqualSpacingItemDecoration import de.tum.`in`.tumcampusapp.component.other.generic.fragment.FragmentForDownloadingExternal import de.tum.`in`.tumcampusapp.di.injector import de.tum.`in`.tumcampusapp.service.DownloadWorker import de.tum.`in`.tumcampusapp.utils.NetUtils import de.tum.`in`.tumcampusapp.utils.Utils import kotlinx.android.synthetic.main.fragment_news.newsRecyclerView import java.lang.Math.round import javax.inject.Inject class NewsFragment : FragmentForDownloadingExternal( R.layout.fragment_news, R.string.news ) { @Inject lateinit var newsController: NewsController @Inject lateinit var newsDownloadAction: DownloadWorker.Action override val method: DownloadWorker.Action? get() = newsDownloadAction private var firstVisibleItemPosition: Int? = null override fun onAttach(context: Context) { super.onAttach(context) injector.newsComponent().inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initRecyclerView() requestDownload(USE_CACHE) } private fun initRecyclerView() { val spacing = round(resources.getDimension(R.dimen.material_card_view_padding)) newsRecyclerView.addItemDecoration(EqualSpacingItemDecoration(spacing)) } override fun onStart() { super.onStart() // Gets all news from database val news = newsController.getAllFromDb(requireContext()) if (news.isEmpty()) { if (NetUtils.isConnected(requireContext())) { showErrorLayout() } else { showNoInternetLayout() } return } val adapter = NewsAdapter(requireContext(), news) newsRecyclerView.adapter = adapter // Restore previous state (including selected item index and scroll position) val firstVisiblePosition = firstVisibleItemPosition ?: newsController.todayIndex newsRecyclerView.scrollToPosition(firstVisiblePosition) showLoadingEnded() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater?.inflate(R.menu.menu_activity_news, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item?.itemId) { R.id.action_disable_sources -> { showNewsSourcesDialog() true } else -> super.onOptionsItemSelected(item) } } private fun showNewsSourcesDialog() { // Populate the settings dialog from the NewsController sources val newsSources = newsController.newsSources val items = newsSources.map { it.title }.toTypedArray() val checked = newsSources.map { Utils.getSettingBool(requireContext(), "news_source_${it.id}", true) }.toTypedArray().toBooleanArray() AlertDialog.Builder(requireContext()) .setMultiChoiceItems(items, checked, this::onNewsSourceToggled) .create() .apply { window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) } .show() } private fun onNewsSourceToggled(dialog: DialogInterface, index: Int, isChecked: Boolean) { val newsSources = newsController.newsSources if (index < newsSources.size) { val key = "news_source_" + newsSources[index].id Utils.setSetting(requireContext(), key, isChecked) val layoutManager = newsRecyclerView.layoutManager as LinearLayoutManager firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() requestDownload(USE_CACHE) } } companion object { fun newInstance() = NewsFragment() } }
gpl-3.0
a6a326cec93a894ad406f7e013f66079
33.11194
95
0.689565
5.006572
false
false
false
false
kryptnostic/rhizome
src/main/kotlin/com/openlattice/hazelcast/serializers/StreamSerializers.kt
1
7449
package com.openlattice.hazelcast.serializers import com.google.common.collect.Maps import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import java.util.* class StreamSerializers { companion object { @JvmStatic fun <T> serializeSet(out: ObjectDataOutput, elements: Set<T>, serializeFunc: (T) -> Unit ) { out.writeInt(elements.size) for (elem in elements) { serializeFunc(elem) } } @JvmStatic fun <T> deserializeSet(`in`: ObjectDataInput, set: MutableSet<T> = mutableSetOf(), deserializeFunc: () -> T ): MutableSet<T> { val size = `in`.readInt() repeat(size) { set.add(deserializeFunc()) } return set } @JvmStatic fun serializeIntList(out: ObjectDataOutput, `object`: Collection<Int> ) { out.writeIntArray(`object`.toIntArray()) } @JvmStatic fun deserializeIntList(`in`: ObjectDataInput, collection: MutableCollection<Int> = mutableListOf() ): MutableCollection<Int> { val data = `in`.readIntArray()!! for (i in data) { collection.add(i) } return collection } @JvmStatic fun serializeUUIDUUIDMap( out: ObjectDataOutput, map: Map<UUID, UUID> ) { val keysMost = LongArray( map.size ) val keysLeast = LongArray( map.size ) val valsMost = LongArray( map.size ) val valsLeast = LongArray( map.size ) for ( ( i, entry ) in map.entries.withIndex() ) { keysMost[ i ] = entry.key.mostSignificantBits keysLeast[ i ] = entry.key.leastSignificantBits valsMost[ i ] = entry.value.mostSignificantBits valsLeast[ i ] = entry.value.leastSignificantBits } out.writeLongArray( keysMost ) // keys most significant bits out.writeLongArray( keysLeast ) // keys least significant bits out.writeLongArray( valsMost ) // vals most significant bits out.writeLongArray( valsLeast ) // vals least significant bits } @JvmStatic fun deserializeUUIDUUIDMap( `in`: ObjectDataInput, map: MutableMap<UUID, UUID> = Maps.newLinkedHashMap() ): Map<UUID, UUID> { val keysMost = `in`.readLongArray()!! val keysLeast = `in`.readLongArray()!! val valsMost = `in`.readLongArray()!! val valsLeast = `in`.readLongArray()!! for ( i in keysMost.indices){ map[ UUID( keysMost[ i ], keysLeast[ i ])] = UUID( valsMost[ i ], valsLeast[ i ]) } return map } @JvmStatic fun serializeStringStringMap(out: ObjectDataOutput, map: Map<String, String> ) { val pairs = arrayOfNulls<String>(map.size * 2) for ( ( i, entry ) in map.entries.withIndex() ) { pairs[ i ] = entry.key pairs[ i + map.size ] = entry.value } out.writeInt( map.size ) out.writeUTFArray( pairs ) } @JvmStatic fun deserializeStringStringMap( `in`: ObjectDataInput): Map<String, String> { val size = `in`.readInt() val map = Maps.newLinkedHashMapWithExpectedSize<String, String>( size ) val pairs = `in`.readStringArray()!! for (index in 0 until size) { map.put( pairs[index], pairs[index + size] ) } return map } @JvmStatic fun <K, V> serializeMap(out: ObjectDataOutput, `object`: Map<K, V>, keyWritingFun: (K) -> Unit, valWritingFun: (V) -> Unit ) { out.writeInt(`object`.size) for ( entry in `object`.entries ) { keyWritingFun(entry.key) valWritingFun(entry.value) } } @JvmStatic fun <K, V> deserializeMap( `in`: ObjectDataInput, keyMappingFun: (ObjectDataInput) -> K, valMappingFun: (ObjectDataInput) -> V ): Map<K, V> { val size = `in`.readInt() val map = mutableMapOf<K, V>() repeat(size) { val key = keyMappingFun(`in`) val value = valMappingFun(`in`) map[key] = value } return map } @JvmStatic fun <K, K2, V> serializeMapMap( out: ObjectDataOutput, `object`: Map<K, Map<K2, V>>, keyWritingFun: (K) -> Unit, subKeyWritingFun: (K2) -> Unit, valWritingFun: (V) -> Unit ) { out.writeInt(`object`.size) for ( entry in `object`.entries ) { keyWritingFun(entry.key) out.writeInt(entry.value.size) for ( subEntry in entry.value ) { subKeyWritingFun(subEntry.key) valWritingFun(subEntry.value) } } } @JvmStatic fun <K, K2, V> deserializeMapMap(`in`: ObjectDataInput, map: MutableMap<K, MutableMap<K2, V>> = mutableMapOf(), keyMappingFun: (ObjectDataInput) -> K, subKeyMappingFun: (ObjectDataInput) -> K2, valMappingFun: (ObjectDataInput) -> V ): MutableMap<K, MutableMap<K2, V>> { val size = `in`.readInt() repeat(size) { val k1 = keyMappingFun(`in`) val innerSize = `in`.readInt() val innerMap = mutableMapOf<K2, V>() repeat(innerSize) { val subKey = subKeyMappingFun(`in`) val value = valMappingFun(`in`) innerMap[subKey] = value } map[k1] = innerMap } return map } @JvmStatic inline fun <T> serializeMaybeValue(out: ObjectDataOutput, value: T?, write: (ObjectDataOutput) -> Unit ) { if ( value == null ){ out.writeBoolean( false ) return } out.writeBoolean( true ) write( out ) } @JvmStatic inline fun <T> deserializeMaybeValue(`in`: ObjectDataInput, read: (ObjectDataInput) -> T ): T? { val maybePresent = `in`.readBoolean() if ( !maybePresent ){ return null } return read( `in` ) } @JvmStatic inline fun <T> serializeOptionalValue(out: ObjectDataOutput, value: Optional<T>, write: (ObjectDataOutput) -> Unit ) { if ( !value.isPresent ){ out.writeBoolean( false ) return } out.writeBoolean( true ) write( out ) } @JvmStatic inline fun <T> deserializeOptional(`in`: ObjectDataInput, read: (ObjectDataInput) -> T ): Optional<T> { val maybePresent = `in`.readBoolean() if ( !maybePresent ){ return Optional.empty() } return Optional.of( read( `in` ) ) } } }
apache-2.0
dd9679cdbb3244fe78bfb5863f2776ff
35.514706
149
0.503692
4.708597
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/storage/dao/BlockDaoImpl.kt
2
4152
package org.stepic.droid.storage.dao import android.content.ContentValues import android.database.Cursor import com.google.gson.Gson import com.google.gson.JsonArray import org.stepic.droid.model.BlockPersistentWrapper import org.stepic.droid.storage.operations.DatabaseOperations import org.stepik.android.cache.block.structure.DbStructureBlock import org.stepik.android.cache.video.dao.VideoDao import org.stepik.android.model.Block import org.stepik.android.model.Video import org.stepik.android.model.code.CodeOptions import javax.inject.Inject class BlockDaoImpl @Inject constructor( databaseOperations: DatabaseOperations, private val gson: Gson, private val videoDao: VideoDao ) : DaoBase<BlockPersistentWrapper>(databaseOperations) { public override fun parsePersistentObject(cursor: Cursor): BlockPersistentWrapper { val indexName = cursor.getColumnIndex(DbStructureBlock.Column.NAME) val indexText = cursor.getColumnIndex(DbStructureBlock.Column.TEXT) val indexStep = cursor.getColumnIndex(DbStructureBlock.Column.STEP_ID) //now get video related info: val indexExternalVideoThumbnail = cursor.getColumnIndex(DbStructureBlock.Column.EXTERNAL_THUMBNAIL) val indexExternalVideoId = cursor.getColumnIndex(DbStructureBlock.Column.EXTERNAL_VIDEO_ID) val indexExternalVideoDuration = cursor.getColumnIndex(DbStructureBlock.Column.EXTERNAL_VIDEO_DURATION) val externalThumbnail = cursor.getString(indexExternalVideoThumbnail) val externalVideoId = cursor.getLong(indexExternalVideoId) val externalVideoDuration = cursor.getLong(indexExternalVideoDuration) var video: Video? = null if (externalThumbnail != null && externalVideoId > 0) { video = Video(externalVideoId, externalThumbnail, duration = externalVideoDuration) } val codeOptionsIndex = cursor.getColumnIndex(DbStructureBlock.Column.CODE_OPTIONS) val storedCodeOptionJson = cursor.getString(codeOptionsIndex) var codeOptions: CodeOptions? = null if (storedCodeOptionJson != null) { codeOptions = gson.fromJson(storedCodeOptionJson, CodeOptions::class.java) } val block = Block( name = cursor.getString(indexName), text = cursor.getString(indexText), video = video, options = codeOptions, subtitleFiles = JsonArray() ) return BlockPersistentWrapper(block, stepId = cursor.getLong(indexStep)) } public override fun getContentValues(blockWrapper: BlockPersistentWrapper): ContentValues { val values = ContentValues() values.put(DbStructureBlock.Column.STEP_ID, blockWrapper.stepId) values.put(DbStructureBlock.Column.NAME, blockWrapper.block.name) values.put(DbStructureBlock.Column.TEXT, blockWrapper.block.text) val externalVideo = blockWrapper.block.video if (externalVideo != null) { values.put(DbStructureBlock.Column.EXTERNAL_VIDEO_DURATION, externalVideo.duration) values.put(DbStructureBlock.Column.EXTERNAL_THUMBNAIL, externalVideo.thumbnail) values.put(DbStructureBlock.Column.EXTERNAL_VIDEO_ID, externalVideo.id) } blockWrapper.block.options?.let { val jsonString = gson.toJson(it, CodeOptions::class.java) values.put(DbStructureBlock.Column.CODE_OPTIONS, jsonString) } return values } public override fun getDbName() = DbStructureBlock.TABLE_NAME public override fun getDefaultPrimaryColumn() = DbStructureBlock.Column.STEP_ID public override fun getDefaultPrimaryValue(persistentObject: BlockPersistentWrapper) = persistentObject.stepId.toString() override fun populateNestedObjects(persistentObject: BlockPersistentWrapper): BlockPersistentWrapper = persistentObject.apply { block.video = videoDao.get(block.video?.id ?: -1) } override fun storeNestedObjects(persistentObject: BlockPersistentWrapper) { persistentObject.block.video?.let(videoDao::replace) } }
apache-2.0
df4fb9af98bb9c77f4cbfac8d4876698
41.804124
125
0.732659
4.707483
false
false
false
false
funkyg/funkytunes
app/src/main/kotlin/com/github/funkyg/funkytunes/Model.kt
1
1280
package com.github.funkyg.funkytunes import android.view.View data class Album(val title: String, val artist: String, val year: Int?, val image: Image) { fun getQuery(): String { // Exclude additions like "(Original Motion Picture Soundtrack)" or "(Deluxe Edition)" from // the query. val name = title.split('(', '[', limit = 2)[0] val yearFormat = year?.toString() ?: "" return "$artist $name $yearFormat" } } data class Song(var name: String, var artist: String?, val image: Image, var duration: Int?, val indexInTorrent: Int, var isPlaying: Boolean = false, var isQueued: Boolean = false, var progress: Int = 0) { var isPaused: Boolean = false val songPausedVisible: Int get() = if (isPlaying && !isQueued && isPaused) View.VISIBLE else View.GONE val songPlayingVisible: Int get() = if (isPlaying && !isQueued && !isPaused) View.VISIBLE else View.GONE val songProgressVisible: Int get() = if (isQueued && !isPlaying && progress > 0) View.VISIBLE else View.GONE val songLoadingVisible: Int get() = if (isQueued && !isPlaying && progress <= 0) View.VISIBLE else View.GONE val stringProgress: String get() = progress.toString() } data class Image(val url: String)
gpl-3.0
57caffbf003dd09e29926d25cf65863c
43.137931
205
0.65625
3.92638
false
false
false
false
hitoshura25/Media-Player-Omega-Android
downloads_presentation/src/main/java/com/vmenon/mpo/downloads/presentation/adapter/DownloadsAdapter.kt
1
2026
package com.vmenon.mpo.downloads.presentation.adapter import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.vmenon.mpo.downloads.presentation.databinding.DownloadBinding import com.vmenon.mpo.downloads.domain.QueuedDownloadModel import kotlin.math.roundToLong class DownloadsAdapter(private val downloads: List<QueuedDownloadModel>) : RecyclerView.Adapter<DownloadsAdapter.ViewHolder>() { class ViewHolder(binding: DownloadBinding) : RecyclerView.ViewHolder(binding.root) { val nameText: TextView = binding.episodeName val progressText: TextView = binding.progress val imageView: ImageView = binding.showImage var download: QueuedDownloadModel? = null } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: DownloadBinding = DownloadBinding.inflate( LayoutInflater.from(parent.context), parent, false ) val vh = ViewHolder(binding) binding.root.setOnClickListener { } return vh } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val download = downloads[position] holder.download = download holder.nameText.text = download.download.name var progress: Double = if (download.total == 0) 0.0 else download.progress * 1.0 / download.total progress *= 100.0 holder.progressText.text = "${progress.roundToLong()}%" Glide.with(holder.itemView.context) .load(download.download.imageUrl) .transition(DrawableTransitionOptions.withCrossFade()) .centerCrop() .into(holder.imageView) } override fun getItemCount(): Int { return downloads.size } }
apache-2.0
3f60b5998766d506f118412607ef1385
32.766667
88
0.702369
4.905569
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/Round.kt
1
884
package info.nightscout.androidaps.utils import android.os.Bundle import java.math.BigDecimal import java.security.InvalidParameterException import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToLong /** * Created by mike on 20.06.2016. */ object Round { fun roundTo(x: Double, step: Double): Double { if (x.isNaN()) throw InvalidParameterException("Parameter is NaN") return if (x == 0.0) 0.0 else BigDecimal.valueOf((x / step).roundToLong()).multiply(BigDecimal.valueOf(step)).toDouble() } fun floorTo(x: Double, step: Double): Double = if (x != 0.0) floor(x / step) * step else 0.0 fun ceilTo(x: Double, step: Double): Double = if (x != 0.0) ceil(x / step) * step else 0.0 fun isSame(d1: Double, d2: Double): Boolean = abs(d1 - d2) <= 0.000001 }
agpl-3.0
6d1fa1b4d8b55794d484d0d65ca6dca2
26.65625
103
0.652715
3.521912
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/TemporaryBasalStorage.kt
1
2326
package info.nightscout.androidaps.plugins.pump.common.bolusInfo import info.nightscout.androidaps.annotations.OpenForTesting import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.T import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.math.abs @OpenForTesting @Singleton class TemporaryBasalStorage @Inject constructor( val aapsLogger: AAPSLogger ) { val store = ArrayList<PumpSync.PumpState.TemporaryBasal>() @Synchronized fun add(temporaryBasal: PumpSync.PumpState.TemporaryBasal) { aapsLogger.debug("Stored temporary basal info: $temporaryBasal") store.add(temporaryBasal) } @Synchronized fun findTemporaryBasal(time: Long, rate: Double): PumpSync.PumpState.TemporaryBasal? { // Look for info with temporary basal for (i in store.indices) { val d = store[i] //aapsLogger.debug(LTag.PUMP, "Existing temporary basal info: " + store[i]) if (time > d.timestamp - T.mins(1).msecs() && time < d.timestamp + T.mins(1).msecs() && abs(store[i].rate - rate) < 0.01) { aapsLogger.debug(LTag.PUMP, "Using & removing temporary basal info: ${store[i]}") store.removeAt(i) return d } } // If not found use time only for (i in store.indices) { val d = store[i] if (time > d.timestamp - T.mins(1).msecs() && time < d.timestamp + T.mins(1).msecs() && rate <= store[i].rate + 0.01) { aapsLogger.debug(LTag.PUMP, "Using TIME-ONLY & removing temporary basal info: ${store[i]}") store.removeAt(i) return d } } // If not found, use last record if amount is the same if (store.size > 0) { val d = store[store.size - 1] if (abs(d.rate - rate) < 0.01) { aapsLogger.debug(LTag.PUMP, "Using LAST & removing temporary basal info: $d") store.removeAt(store.size - 1) return d } } //Not found //aapsLogger.debug(LTag.PUMP, "Temporary basal info not found") return null } }
agpl-3.0
6dc79ca5ee67ea74b51186acfc65a23e
37.147541
135
0.615219
4.153571
false
false
false
false
searene/OneLetterOnePage
src/main/kotlin/com/searene/domain/CharacterContainer.kt
1
588
package com.searene.domain import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement @XmlRootElement(name = "characters") class CharacterContainer( paperSize: PaperSize, characters: List<Character> ) { constructor(): this(PaperSize(), listOf()) var paperSize: PaperSize = paperSize @XmlElement(name = "paperSize") set var characters: List<Character> = characters @XmlElement(name = "character") set override fun toString(): String { return "CharacterContainer(characters=$characters)" } }
apache-2.0
5ab1bcd3ae0bbad67b1109d7ca231a02
25.727273
59
0.70068
4.355556
false
false
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/ModifyCategoryDialogFragment.kt
1
3891
package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.TextView.OnEditorActionListener import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.databinding.DialogModifycategoryBinding import com.rolandvitezhu.todocloud.helper.setSoftInputMode import com.rolandvitezhu.todocloud.ui.activity.main.fragment.MainListFragment import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.CategoriesViewModel import kotlinx.android.synthetic.main.dialog_modifycategory.* import kotlinx.android.synthetic.main.dialog_modifycategory.view.* class ModifyCategoryDialogFragment : AppCompatDialogFragment() { private val categoriesViewModel by lazy { ViewModelProvider(requireActivity()).get(CategoriesViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dialogModifycategoryBinding: DialogModifycategoryBinding = DialogModifycategoryBinding.inflate(inflater, container, false) val view: View = dialogModifycategoryBinding.root dialogModifycategoryBinding.modifyCategoryDialogFragment = this dialogModifycategoryBinding.categoriesViewModel = categoriesViewModel dialogModifycategoryBinding.executePendingBindings() requireDialog().setTitle(R.string.modifycategory_title) setSoftInputMode() applyTextChangedEvents(view) applyEditorEvents(view) return view } private fun applyTextChangedEvents(view: View) { view.textinputedittext_modifycategory_title.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { validateTitle() } }) } private fun applyEditorEvents(view: View) { view.textinputedittext_modifycategory_title.setOnEditorActionListener( OnEditorActionListener { v, actionId, event -> val pressDone = actionId == EditorInfo.IME_ACTION_DONE var pressEnter = false if (event != null) { val keyCode = event.keyCode pressEnter = keyCode == KeyEvent.KEYCODE_ENTER } if (pressEnter || pressDone) { view.button_modifycategory_ok.performClick() return@OnEditorActionListener true } false }) } private fun validateTitle(): Boolean { return if (categoriesViewModel.category.title.isBlank()) { this.textinputlayout_modifycategory_title!!.error = getString(R.string.all_entertitle) false } else { this.textinputlayout_modifycategory_title!!.isErrorEnabled = false true } } fun onButtonOkClick(view: View) { if (validateTitle()) { categoriesViewModel.onModifyCategory() (targetFragment as MainListFragment?)?.finishActionMode() dismiss() } } fun onButtonCancelClick(view: View) { dismiss() } }
mit
ab9b439f80a34bc04e82aaa83dfd81d9
36.786408
98
0.699563
5.020645
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt
2
7029
// 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.intentions import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.unifier.toRange import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.* import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens 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 class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention<KtObjectLiteralExpression>( KtObjectLiteralExpression::class.java, KotlinBundle.lazyMessage("convert.object.literal.to.class") ) { override fun applicabilityRange(element: KtObjectLiteralExpression) = element.objectDeclaration.getObjectKeyword()?.textRange override fun startInWriteAction() = false private fun doApply(editor: Editor, element: KtObjectLiteralExpression, targetParent: KtElement) { val project = element.project val scope = element.getResolutionScope() val validator: (String) -> Boolean = { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val classNames = element.objectDeclaration.superTypeListEntries .mapNotNull { it.typeReference?.typeElement?.let { Fe10KotlinNameSuggester.suggestTypeAliasNameByPsi(it, validator) } } .takeIf { it.isNotEmpty() } ?: listOf(Fe10KotlinNameSuggester.suggestNameByName("O", validator)) val className = classNames.first() val psiFactory = KtPsiFactory(element) val targetSibling = element.parentsWithSelf.first { it.parent == targetParent } val objectDeclaration = element.objectDeclaration val containingClass = element.containingClass() val hasMemberReference = containingClass?.body?.allChildren?.any { (it is KtProperty || it is KtNamedFunction) && ReferencesSearch.search(it, element.useScope).findFirst() != null } ?: false val newClass = psiFactory.createClass("class $className") objectDeclaration.getSuperTypeList()?.let { newClass.add(psiFactory.createColon()) newClass.add(it) } objectDeclaration.body?.let { newClass.add(it) } ExtractionEngine( object : ExtractionEngineHelper(text) { override fun configureAndRun( project: Project, editor: Editor, descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, onFinish: (ExtractionResult) -> Unit ) { project.executeWriteCommand(text) { val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = listOf(className)) doRefactor( ExtractionGeneratorConfiguration(descriptor, ExtractionGeneratorOptions.DEFAULT), onFinish ) } } } ).run(editor, ExtractionData(element.containingKtFile, element.toRange(), targetSibling)) { extractionResult -> val functionDeclaration = extractionResult.declaration as KtFunction if (functionDeclaration.valueParameters.isNotEmpty()) { val valKeyword = psiFactory.createValKeyword() newClass.createPrimaryConstructorParameterListIfAbsent() .replaced(functionDeclaration.valueParameterList!!) .parameters .forEach { it.addAfter(valKeyword, null) it.addModifier(KtTokens.PRIVATE_KEYWORD) } } val introducedClass = functionDeclaration.replaced(newClass).apply { if (hasMemberReference && containingClass == (parent.parent as? KtClass)) addModifier(KtTokens.INNER_KEYWORD) primaryConstructor?.reformatted() }.let { CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(it) } ?: return@run val file = introducedClass.containingFile val template = TemplateBuilderImpl(file).let { builder -> builder.replaceElement(introducedClass.nameIdentifier!!, NEW_CLASS_NAME, ChooseStringExpression(classNames), true) for (psiReference in ReferencesSearch.search(introducedClass, LocalSearchScope(file), false)) { builder.replaceElement(psiReference.element, USAGE_VARIABLE_NAME, NEW_CLASS_NAME, false) } builder.buildInlineTemplate() } editor.caretModel.moveToOffset(file.startOffset) TemplateManager.getInstance(project).startTemplate(editor, template) } } override fun applyTo(element: KtObjectLiteralExpression, editor: Editor?) { if (editor == null) return val containers = element.getExtractionContainers(strict = true, includeAll = true) if (isUnitTestMode()) { val targetComment = element.containingKtFile.findDescendantOfType<PsiComment>()?.takeIf { it.text == "// TARGET_BLOCK:" } val target = containers.firstOrNull { it == targetComment?.parent } ?: containers.last() return doApply(editor, element, target) } chooseContainerElementIfNecessary( containers, editor, if (containers.first() is KtFile) KotlinBundle.message("select.target.file") else KotlinBundle.message("select.target.code.block.file"), true ) { doApply(editor, element, it) } } } private const val NEW_CLASS_NAME = "NEW_CLASS_NAME" private const val USAGE_VARIABLE_NAME = "OTHER_VAR"
apache-2.0
c72515e9992898af027e5676ee50a6ec
45.549669
158
0.681605
5.419429
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/merge/cosinesimilarity/CosineLayerStructureSpec.kt
1
1820
/* 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 contexte at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.merge.cosinesimilarity 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 CosineLayerStructureSpec: Spek({ describe("a CosineLayer") { context("forward") { val layer = CosineLayerUtils.buildLayer() layer.forward() it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.085901)), tolerance = 1.0e-05) } } } context("backward") { val layer = CosineLayerUtils.buildLayer() layer.forward() layer.outputArray.assignErrors(CosineLayerUtils.getOutputErrors()) layer.backward(propagateToInput = true) it("should match the expected errors of the inputArray1") { assertTrue { layer.inputArrays[0].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.20470, -0.16376, 0.29455, -0.31159)), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray2") { assertTrue { layer.inputArrays[1].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.31900, -0.34126, 0.25436, 0.22256)), tolerance = 1.0e-05) } } } } })
mpl-2.0
4c8b2503c06f97ee3ceb005857a897fa
28.354839
95
0.629121
4.222738
false
false
false
false
felipefpx/utility-util-android-extensions
fresco-exts/src/main/kotlin/com/felipeporge/utility/fresco/FrescoExt.kt
1
5780
@file:JvmName("FrescoUtils") package com.felipeporge.utility.fresco import android.net.Uri import android.support.graphics.drawable.VectorDrawableCompat import android.support.v4.content.ContextCompat import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.drawee.drawable.ScalingUtils import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder import com.facebook.drawee.generic.RoundingParams import com.facebook.drawee.view.SimpleDraweeView /** * Loads an image from url. * @param imgUrl Image url. * @param defaultImgResId Default image resource id. * @param isRound Is image round? * @param backgroundColorId Background color resource id. * @param scaleType Scale type. */ fun SimpleDraweeView.loadImgUrl(imgUrl: String?, defaultImgResId: Int, isRound: Boolean = false, backgroundColorId: Int = android.R.color.white, scaleType: ScalingUtils.ScaleType = ScalingUtils.ScaleType.CENTER_CROP) { hierarchy = GenericDraweeHierarchyBuilder(context.resources) .setPlaceholderImage(defaultImgResId) .setPlaceholderImageScaleType(scaleType) .setFailureImage(defaultImgResId) .setFailureImageScaleType(scaleType) .setRoundingParams(RoundingParams().apply { roundAsCircle = isRound roundingMethod = RoundingParams.RoundingMethod.BITMAP_ONLY }) .setBackground(ContextCompat.getDrawable(context, backgroundColorId)) .build() // Load image url. controller = Fresco.newDraweeControllerBuilder().apply{ callerContext = context oldController = controller imgUrl?.let { setUri(Uri.parse(it)) } }.build() } /** * Changes Simple Drawee View Rounding params. * @param imgResId Image resource id. * @param isRound Is image round? * @param backgroundColorId Background color resource id. * @param scaleType Scale type. */ fun SimpleDraweeView.loadDrawable(imgResId: Int, isRound: Boolean = false, backgroundColorId: Int = android.R.color.white, scaleType: ScalingUtils.ScaleType = ScalingUtils.ScaleType.CENTER_CROP) { hierarchy = GenericDraweeHierarchyBuilder(context.resources) .setPlaceholderImage(imgResId) .setPlaceholderImageScaleType(scaleType) .setRoundingParams(RoundingParams().apply { roundAsCircle = isRound roundingMethod = RoundingParams.RoundingMethod.BITMAP_ONLY }) .setBackground(ContextCompat.getDrawable(context, backgroundColorId)) .build() // Reset controller to avoid old images. controller = Fresco.newDraweeControllerBuilder().apply{ callerContext = context oldController = controller }.build() } /** * Loads an image from url. * @param imgUrl Image url. * @param defaultImgResId Default image resource id. * @param isRound Is image round? * @param backgroundColorId Background color resource id. * @param scaleType Scale type. */ fun SimpleDraweeView.loadImgUrlOrVector(imgUrl: String?, defaultImgResId: Int, isRound: Boolean = false, backgroundColorId: Int = android.R.color.white, scaleType: ScalingUtils.ScaleType = ScalingUtils.ScaleType.CENTER_CROP) { val drawable = VectorDrawableCompat.create(resources, defaultImgResId, context.theme) hierarchy = GenericDraweeHierarchyBuilder(context.resources) .setPlaceholderImage(drawable) .setPlaceholderImageScaleType(scaleType) .setFailureImage(drawable) .setFailureImageScaleType(scaleType) .setRoundingParams(RoundingParams().apply { roundAsCircle = isRound roundingMethod = RoundingParams.RoundingMethod.BITMAP_ONLY }) .setBackground(ContextCompat.getDrawable(context, backgroundColorId)) .build() // Load image url. controller = Fresco.newDraweeControllerBuilder().apply{ callerContext = context oldController = controller imgUrl?.let { setUri(Uri.parse(it)) } }.build() } /** * Changes Simple Drawee View Rounding params. * @param imgResId Image resource id. * @param isRound Is image round? * @param backgroundColorId Background color resource id. * @param scaleType Scale type. */ fun SimpleDraweeView.loadVectorDrawable(imgResId: Int, isRound: Boolean = false, backgroundColorId: Int = android.R.color.white, scaleType: ScalingUtils.ScaleType = ScalingUtils.ScaleType.CENTER_CROP) { val drawable = VectorDrawableCompat.create(resources, imgResId, context.theme) hierarchy = GenericDraweeHierarchyBuilder(context.resources) .setPlaceholderImage(drawable) .setPlaceholderImageScaleType(scaleType) .setRoundingParams(RoundingParams().apply { roundAsCircle = isRound roundingMethod = RoundingParams.RoundingMethod.BITMAP_ONLY }) .setBackground(ContextCompat.getDrawable(context, backgroundColorId)) .build() // Reset controller to avoid old images. controller = Fresco.newDraweeControllerBuilder().apply{ callerContext = context oldController = controller }.build() }
apache-2.0
805f8d920c3451c3b5c6c76b37e21c86
39.41958
107
0.641869
5.151515
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt
1
5052
// 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.intentions import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.ImportDescriptorResult import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.psi.psiUtil.isInImportDirective import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ClassQualifier class ImportAllMembersIntention : SelfTargetingIntention<KtElement>( KtElement::class.java, KotlinBundle.lazyMessage("import.members.with") ), HighPriorityAction { override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean { val receiverExpression = element.receiverExpression() ?: return false if (!receiverExpression.textRange.containsOffset(caretOffset)) return false val target = target(element, receiverExpression) ?: return false val targetFqName = target.importableFqName ?: return false if (receiverExpression.isInImportDirective()) return false val file = element.containingKtFile val project = file.project val dummyFileText = (file.packageDirective?.text ?: "") + "\n" + (file.importList?.text ?: "") val dummyFile = KtPsiFactory(project).createAnalyzableFile("Dummy.kt", dummyFileText, file) val helper = ImportInsertHelper.getInstance(project) if (helper.importDescriptor(dummyFile, target, forceAllUnderImport = true) == ImportDescriptorResult.FAIL) return false setTextGetter(KotlinBundle.lazyMessage("import.members.from.0", targetFqName.parent().asString())) return true } override fun applyTo(element: KtElement, editor: Editor?) = element.importReceiverMembers() companion object { fun KtElement.importReceiverMembers() { val target = target(this) ?: return val classFqName = target.importableFqName!!.parent() ImportInsertHelper.getInstance(project).importDescriptor(containingKtFile, target, forceAllUnderImport = true) val qualifiedExpressions = containingKtFile.collectDescendantsOfType<KtDotQualifiedExpression> { qualifiedExpression -> val qualifierName = qualifiedExpression.receiverExpression.getQualifiedElementSelector() as? KtNameReferenceExpression qualifierName?.getReferencedNameAsName() == classFqName.shortName() && target(qualifiedExpression)?.importableFqName ?.parent() == classFqName } val userTypes = containingKtFile.collectDescendantsOfType<KtUserType> { userType -> val receiver = userType.receiverExpression()?.getQualifiedElementSelector() as? KtNameReferenceExpression receiver?.getReferencedNameAsName() == classFqName.shortName() && target(userType)?.importableFqName ?.parent() == classFqName } //TODO: not deep ShortenReferences.DEFAULT.process(qualifiedExpressions + userTypes) } private fun target(qualifiedElement: KtElement, receiverExpression: KtExpression): DeclarationDescriptor? { val bindingContext = qualifiedElement.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) if (bindingContext[BindingContext.QUALIFIER, receiverExpression] !is ClassQualifier) { return null } val selector = qualifiedElement.getQualifiedElementSelector() as? KtNameReferenceExpression ?: return null return selector.mainReference.resolveToDescriptors(bindingContext).firstOrNull() } private fun target(qualifiedElement: KtElement): DeclarationDescriptor? { val receiverExpression = qualifiedElement.receiverExpression() ?: return null return target(qualifiedElement, receiverExpression) } private fun KtElement.receiverExpression(): KtExpression? = when (this) { is KtDotQualifiedExpression -> receiverExpression is KtUserType -> qualifier?.referenceExpression else -> null } } }
apache-2.0
4b505bc9c0e6373d3d80c69672c5a03f
52.178947
158
0.743072
5.740909
false
false
false
false
mdaniel/intellij-community
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/ide/IdeProductProvider.kt
1
1157
package com.intellij.ide.starter.ide import com.intellij.ide.starter.di.di import com.intellij.ide.starter.models.IdeInfo import com.intellij.ide.starter.models.IdeProduct import org.kodein.di.direct import org.kodein.di.instance import kotlin.reflect.full.declaredMemberProperties object IdeProductProvider { /** GoLand */ val GO: IdeInfo = di.direct.instance<IdeProduct>().GO /** IntelliJ Ultimate */ val IU: IdeInfo = di.direct.instance<IdeProduct>().IU /** IntelliJ Community */ val IC: IdeInfo = di.direct.instance<IdeProduct>().IC /** Android Studio */ val AI: IdeInfo = di.direct.instance<IdeProduct>().AI /** WebStorm */ val WS: IdeInfo = di.direct.instance<IdeProduct>().WS /** PhpStorm */ val PS: IdeInfo = di.direct.instance<IdeProduct>().PS /** DataGrip */ val DB: IdeInfo = di.direct.instance<IdeProduct>().DB /** RubyMine */ val RM: IdeInfo = di.direct.instance<IdeProduct>().RM /** PyCharm Professional */ val PY: IdeInfo = di.direct.instance<IdeProduct>().PY fun getProducts(): List<IdeInfo> = IdeProductProvider::class.declaredMemberProperties.map { it.get(IdeProductProvider) as IdeInfo } }
apache-2.0
7be99ee593b55bcc749ef1f62641201d
28.692308
133
0.72083
3.649842
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationStateV2.kt
2
3379
package org.thoughtcrime.securesms.notifications.v2 import android.app.PendingIntent import android.content.Context import android.content.Intent import org.thoughtcrime.securesms.notifications.DeleteNotificationReceiver import org.thoughtcrime.securesms.notifications.MarkReadReceiver import org.thoughtcrime.securesms.notifications.NotificationIds import org.thoughtcrime.securesms.recipients.Recipient /** * Hold all state for notifications for all conversations. */ data class NotificationStateV2(val conversations: List<NotificationConversation>) { val threadCount: Int = conversations.size val isEmpty: Boolean = conversations.isEmpty() val messageCount: Int by lazy { conversations.fold(0) { messageCount, conversation -> messageCount + conversation.messageCount } } val notificationItems: List<NotificationItemV2> by lazy { conversations.map { it.notificationItems } .flatten() .sorted() } val notificationIds: Set<Int> by lazy { conversations.map { it.notificationId } .toSet() } val mostRecentNotification: NotificationItemV2? get() = notificationItems.lastOrNull() val mostRecentSender: Recipient? get() = mostRecentNotification?.individualRecipient fun getNonVisibleConversation(visibleThreadId: Long): List<NotificationConversation> { return conversations.filterNot { it.threadId == visibleThreadId } } fun getConversation(threadId: Long): NotificationConversation? { return conversations.firstOrNull { it.threadId == threadId } } fun getDeleteIntent(context: Context): PendingIntent? { val ids = LongArray(messageCount) val mms = BooleanArray(ids.size) val threadIds: MutableList<Long> = mutableListOf() conversations.forEach { conversation -> threadIds += conversation.threadId conversation.notificationItems.forEachIndexed { index, notificationItem -> ids[index] = notificationItem.id mms[index] = notificationItem.isMms } } val intent = Intent(context, DeleteNotificationReceiver::class.java) .setAction(DeleteNotificationReceiver.DELETE_NOTIFICATION_ACTION) .putExtra(DeleteNotificationReceiver.EXTRA_IDS, ids) .putExtra(DeleteNotificationReceiver.EXTRA_MMS, mms) .putExtra(DeleteNotificationReceiver.EXTRA_THREAD_IDS, threadIds.toLongArray()) .makeUniqueToPreventMerging() return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } fun getMarkAsReadIntent(context: Context): PendingIntent? { val threadArray = LongArray(conversations.size) conversations.forEachIndexed { index, conversation -> threadArray[index] = conversation.threadId } val intent = Intent(context, MarkReadReceiver::class.java).setAction(MarkReadReceiver.CLEAR_ACTION) .putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, threadArray) .putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, NotificationIds.MESSAGE_SUMMARY) .makeUniqueToPreventMerging() return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } fun getThreadsWithMostRecentNotificationFromSelf(): Set<Long> { return conversations.filter { it.mostRecentNotification.individualRecipient.isSelf } .map { it.threadId } .toSet() } companion object { val EMPTY = NotificationStateV2(emptyList()) } }
gpl-3.0
6ab19254832c1b56882a38a9c1ba6cab
33.835052
103
0.756437
4.786119
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XChildWithOptionalParentEntityImpl.kt
2
9873
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XChildWithOptionalParentEntityImpl(val dataSource: XChildWithOptionalParentEntityData) : XChildWithOptionalParentEntity, WorkspaceEntityBase() { companion object { internal val OPTIONALPARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildWithOptionalParentEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( OPTIONALPARENT_CONNECTION_ID, ) } override val childProperty: String get() = dataSource.childProperty override val optionalParent: XParentEntity? get() = snapshot.extractOneToManyParent(OPTIONALPARENT_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: XChildWithOptionalParentEntityData?) : ModifiableWorkspaceEntityBase<XChildWithOptionalParentEntity, XChildWithOptionalParentEntityData>( result), XChildWithOptionalParentEntity.Builder { constructor() : this(XChildWithOptionalParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XChildWithOptionalParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isChildPropertyInitialized()) { error("Field XChildWithOptionalParentEntity#childProperty should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as XChildWithOptionalParentEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.childProperty != dataSource.childProperty) this.childProperty = dataSource.childProperty if (parents != null) { val optionalParentNew = parents.filterIsInstance<XParentEntity?>().singleOrNull() if ((optionalParentNew == null && this.optionalParent != null) || (optionalParentNew != null && this.optionalParent == null) || (optionalParentNew != null && this.optionalParent != null && (this.optionalParent as WorkspaceEntityBase).id != (optionalParentNew as WorkspaceEntityBase).id)) { this.optionalParent = optionalParentNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var childProperty: String get() = getEntityData().childProperty set(value) { checkModificationAllowed() getEntityData(true).childProperty = value changedProperty.add("childProperty") } override var optionalParent: XParentEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(OPTIONALPARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, OPTIONALPARENT_CONNECTION_ID)] as? XParentEntity } else { this.entityLinks[EntityLink(false, OPTIONALPARENT_CONNECTION_ID)] as? XParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, OPTIONALPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, OPTIONALPARENT_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToManyParentOfChild(OPTIONALPARENT_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, OPTIONALPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, OPTIONALPARENT_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, OPTIONALPARENT_CONNECTION_ID)] = value } changedProperty.add("optionalParent") } override fun getEntityClass(): Class<XChildWithOptionalParentEntity> = XChildWithOptionalParentEntity::class.java } } class XChildWithOptionalParentEntityData : WorkspaceEntityData<XChildWithOptionalParentEntity>() { lateinit var childProperty: String fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<XChildWithOptionalParentEntity> { val modifiable = XChildWithOptionalParentEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): XChildWithOptionalParentEntity { return getCached(snapshot) { val entity = XChildWithOptionalParentEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XChildWithOptionalParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return XChildWithOptionalParentEntity(childProperty, entitySource) { this.optionalParent = parents.filterIsInstance<XParentEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as XChildWithOptionalParentEntityData if (this.entitySource != other.entitySource) return false if (this.childProperty != other.childProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as XChildWithOptionalParentEntityData if (this.childProperty != other.childProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
21502131450d059a7749808ee403f15c
39.134146
297
0.709511
5.565389
false
false
false
false
YutaKohashi/FakeLineApp
app/src/main/java/jp/yuta/kohashi/fakelineapp/managers/permission/PermissionHelper.kt
1
11747
package jp.yuta.kohashi.fakelineapp.managers.permission import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.Settings import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.util.Log /** * Author : yutakohashi * Project name : FakeLineApp * Date : 29 / 08 / 2017 */ class PermissionHelper : OnActivityPermissionCallback, OnActivityForResult { private val TAG = PermissionHelper::class.java.simpleName private val REQUEST_OVERLAY_PERMISSION: Int = 1000 private val REQUEST_PERMISSIONS: Int = 1001 private val REQUEST_MY_APP_SETTINGS: Int = 1002 private var mContext: Activity? private var mFragment: Fragment? private var mForceAccepting: Boolean = false // default false private var mOnPermissionCallback: OnPermissionCallback private val OVER_MARSHMALLOW: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M private val IS_FROM_ACTIVITY: Boolean // use from activity? companion object { fun instance(context: Activity, callback: OnPermissionCallback? = null): PermissionHelper = PermissionHelper(context, callback) fun instance(fragment: Fragment, callback: OnPermissionCallback? = null): PermissionHelper = PermissionHelper(fragment, callback) } /** *when use this class from activity */ private constructor(context: Activity, callback: OnPermissionCallback? = null) { mContext = context mFragment = null mOnPermissionCallback = callback ?: if (mContext is OnPermissionCallback) mContext as OnPermissionCallback else throw IllegalArgumentException("OnPermissionCallbackが実装されていない") IS_FROM_ACTIVITY = true } /** * when use this class from fragment */ private constructor(fragment: Fragment, callback: OnPermissionCallback? = null) { mContext = null mFragment = fragment mOnPermissionCallback = callback ?: if (mFragment is OnPermissionCallback) mFragment as OnPermissionCallback else throw IllegalArgumentException("OnPermissionCallbackが実装されていない") IS_FROM_ACTIVITY = false } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == REQUEST_PERMISSIONS) { if (verifyIsGrantedPermissions(grantResults)) { mOnPermissionCallback.onGrantedPermission(permissions) } else { val deniedPermissions = getDeniedPermissions(permissions) var deniedPermissionFlg = false deniedPermissions.forEach { deniedPermission -> if (!isNeededExplanation(deniedPermission)) { mOnPermissionCallback.onReallyDeniedPermission(deniedPermission) deniedPermissionFlg = true } } if (!deniedPermissionFlg) { if (mForceAccepting) requestAfterExplanation(permissions) else mOnPermissionCallback.onDeniedPermission(permissions) } } } } /** * startActivityForResultで起動したintentの戻り値を取得する */ override fun onActivityResult(requestCode: Int) { if (OVER_MARSHMALLOW) { when (requestCode) { REQUEST_OVERLAY_PERMISSION -> { if (isGrantedSystemAlertPermission()) mOnPermissionCallback.onGrantedPermission(arrayOf(Manifest.permission.SYSTEM_ALERT_WINDOW)) else mOnPermissionCallback.onDeniedPermission(arrayOf(Manifest.permission.SYSTEM_ALERT_WINDOW)) } /** * */ REQUEST_MY_APP_SETTINGS -> { } } } else { mOnPermissionCallback.onPreGrantedPermission(Manifest.permission.SYSTEM_ALERT_WINDOW) } } fun setForceAccepting(forceAccepting: Boolean): PermissionHelper { mForceAccepting = forceAccepting return this } /** * permission request */ fun request(permission: String): PermissionHelper { if (OVER_MARSHMALLOW) { handleRequest(permission) } else { mOnPermissionCallback.onNoNeededPermission() } return this } fun request(permission: Array<String>): PermissionHelper { if (OVER_MARSHMALLOW) { val denies = getDeniedPermissions(permission) if (denies.count() == 0) mOnPermissionCallback.onGrantedPermission(permission) denies.forEach { permissionName -> handleRequest(permissionName) } } else { mOnPermissionCallback.onNoNeededPermission() } return this } private fun handleRequest(permission: String) { if (isDefinePermissionInManifest(permission)) { if (!permission.equals(Manifest.permission.SYSTEM_ALERT_WINDOW, true)) { if (isDeniedPermission(permission)) { if (isNeededExplanation(permission)) { mOnPermissionCallback.onNeedExplanationPermission(permission) } else { if (IS_FROM_ACTIVITY) ActivityCompat.requestPermissions(mContext!!, arrayOf(permission), REQUEST_PERMISSIONS) else mFragment!!.requestPermissions(arrayOf(permission), REQUEST_PERMISSIONS) } } else { mOnPermissionCallback.onPreGrantedPermission(permission) } } else { requestSystemAlertPermission() } } else { mOnPermissionCallback.onDeniedPermission(arrayOf(permission)) } } fun requestAfterExplanation(permissions: Array<String>) { val permissionsToRequest: MutableList<String> = mutableListOf() permissions.forEach { p -> if (isDeniedPermission(p)) permissionsToRequest.add(p) else mOnPermissionCallback.onPreGrantedPermission(p) } if (permissionsToRequest.isEmpty()) return if (IS_FROM_ACTIVITY) ActivityCompat.requestPermissions(mContext!!, permissionsToRequest.toTypedArray(), REQUEST_PERMISSIONS) else mFragment!!.requestPermissions(permissionsToRequest.toTypedArray(), REQUEST_PERMISSIONS) } fun requestAfterExplanation(permission: String) { requestAfterExplanation(arrayOf(permission)) } /** * 拒否されているpermissionのみ取得 */ fun getDeniedPermissions(permissions: Array<String>?): Array<String> { val declines: MutableList<String> = mutableListOf() permissions?.forEach { permissionName -> if (ActivityCompat.checkSelfPermission(if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context, permissionName) != PackageManager.PERMISSION_GRANTED) declines.add(permissionName) } return declines.toTypedArray() } /** * manifestファイルに定義されているか */ fun isDefinePermissionInManifest(permission: String): Boolean { getDefinePermissions()?.forEach { permissionName -> if (permissionName.equals(permission)) return true } return false } fun getDefinePermissions(): Array<String>? { return try { (if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context).packageManager.getPackageInfo((if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context).packageName, PackageManager.GET_PERMISSIONS).requestedPermissions } catch (e: PackageManager.NameNotFoundException) { null } } fun openMyApplicationSettings() { try { val intent = Intent().apply { action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) addCategory(Intent.CATEGORY_DEFAULT) data = Uri.parse("package:" + (if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context).packageName) } if (IS_FROM_ACTIVITY) mContext!!.startActivityForResult(intent, REQUEST_MY_APP_SETTINGS) else mFragment?.startActivityForResult(intent, REQUEST_MY_APP_SETTINGS) } catch (e: NullPointerException) { } } fun verifyIsGrantedPermissions(grantResults: IntArray): Boolean { if (grantResults.isEmpty()) return false grantResults.forEach { if (it != PackageManager.PERMISSION_GRANTED) return false } return true } //** //region SystemAlertPermission //** /** * SystemAlertPermissionの場合のみ通常のダイアログではできない */ fun requestSystemAlertPermission() { if (OVER_MARSHMALLOW) { try { if (!isGrantedSystemAlertPermission()) // systemalertpermimssion が許可されていない if (IS_FROM_ACTIVITY) mContext!!.startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + mContext!!.packageName)), REQUEST_OVERLAY_PERMISSION) else mFragment!!.startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + mFragment!!.context.packageName)), REQUEST_OVERLAY_PERMISSION) else mOnPermissionCallback.onPreGrantedPermission(Manifest.permission.SYSTEM_ALERT_WINDOW) } catch (e: Exception) { Log.e(TAG, "requestSystemAlertPermission : " + e.toString()) } } else { // marshmallow未満はデフォルトで許可 mOnPermissionCallback.onPreGrantedPermission(Manifest.permission.SYSTEM_ALERT_WINDOW) } } fun isGrantedSystemAlertPermission(): Boolean { return if (OVER_MARSHMALLOW) Settings.canDrawOverlays(if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context) else true } //** //endregion //** /** * permissionが拒否されているか */ fun isDeniedPermission(permissionsName: String): Boolean = ActivityCompat.checkSelfPermission(if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context, permissionsName) != PackageManager.PERMISSION_GRANTED /** * permissionが許可されているか */ fun isGrantedPermission(permissionsName: String): Boolean = ActivityCompat.checkSelfPermission(if (IS_FROM_ACTIVITY) mContext!! else mFragment!!.context, permissionsName) == PackageManager.PERMISSION_GRANTED /** * 許可ダイアログの再表示判定(永続的に不許可設定の場合、falseが返却される) */ fun isNeededExplanation(permissionName: String): Boolean = if (IS_FROM_ACTIVITY) ActivityCompat.shouldShowRequestPermissionRationale(mContext!!, permissionName) else mFragment!!.shouldShowRequestPermissionRationale(permissionName) /** * 設定画面でしか権限を設定できないときtrue * * * consider using [PermissionHelper.openMyApplicationSettings] to open settings screen */ fun isPermissionPermanentlyDenied(permission: String): Boolean = isDeniedPermission(permission) && !isNeededExplanation(permission) }
mit
ba074846e457fd9c34a6a84e02e2d2af
37.06
227
0.647806
4.992129
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/ui/components/BasicOptionButtonUI.kt
4
15231
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.components import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.OptionAction import com.intellij.openapi.ui.popup.JBPopupAdapter import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.util.Condition import com.intellij.ui.ScreenUtil import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBOptionButton.PROP_OPTIONS import com.intellij.ui.components.JBOptionButton.PROP_OPTION_TOOLTIP import com.intellij.ui.popup.ActionPopupStep import com.intellij.ui.popup.PopupFactoryImpl import com.intellij.ui.popup.PopupFactoryImpl.ActionGroupPopup.getActionItems import com.intellij.ui.popup.list.PopupListElementRenderer import com.intellij.util.ui.AbstractLayoutManager import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.scale import java.awt.* import java.awt.event.* import java.beans.PropertyChangeListener import java.util.function.Supplier import javax.swing.* import javax.swing.AbstractButton.MNEMONIC_CHANGED_PROPERTY import javax.swing.AbstractButton.TEXT_CHANGED_PROPERTY import javax.swing.JComponent.TOOL_TIP_TEXT_KEY import javax.swing.SwingUtilities.replaceUIActionMap import javax.swing.SwingUtilities.replaceUIInputMap import javax.swing.event.ChangeListener open class BasicOptionButtonUI : OptionButtonUI() { private var _optionButton: JBOptionButton? = null private var _mainButton: JButton? = null private var _arrowButton: JButton? = null protected val optionButton: JBOptionButton get() = _optionButton!! protected val mainButton: JButton get() = _mainButton!! protected val arrowButton: JButton get() = _arrowButton!! protected var popup: ListPopup? = null protected var showPopupAction: AnAction? = null protected var isPopupShowing: Boolean = false protected var propertyChangeListener: PropertyChangeListener? = null protected var changeListener: ChangeListener? = null protected var focusListener: FocusListener? = null protected var arrowButtonActionListener: ActionListener? = null protected var arrowButtonMouseListener: MouseListener? = null protected val isSimpleButton: Boolean get() = optionButton.isSimpleButton override fun installUI(c: JComponent) { _optionButton = c as JBOptionButton installPopup() installButtons() installListeners() installKeyboardActions() } override fun uninstallUI(c: JComponent) { uninstallKeyboardActions() uninstallListeners() uninstallButtons() uninstallPopup() _optionButton = null } override fun getPreferredSize(c: JComponent): Dimension = Dimension(mainButton.preferredSize.width + arrowButton.preferredSize.width, maxOf(mainButton.preferredSize.height, arrowButton.preferredSize.height)) protected open fun installPopup() { showPopupAction = DumbAwareAction.create { _ -> showPopup() } showPopupAction?.registerCustomShortcutSet(CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)), optionButton) } protected open fun uninstallPopup() { showPopupAction?.unregisterCustomShortcutSet(optionButton) showPopupAction = null popup?.let(Disposable::dispose) popup = null } protected open fun installButtons() { _mainButton = createMainButton() optionButton.add(mainButton) configureMainButton() _arrowButton = createArrowButton() optionButton.add(arrowButton) configureArrowButton() configureOptionButton() } protected open fun uninstallButtons() { unconfigureMainButton() unconfigureArrowButton() unconfigureOptionButton() _mainButton = null _arrowButton = null } protected open fun configureOptionButton() { optionButton.layout = createLayoutManager() } protected open fun unconfigureOptionButton() { optionButton.layout = null optionButton.removeAll() } protected open fun createMainButton(): JButton = MainButton() protected open fun configureMainButton() { mainButton.isFocusable = false } protected open fun unconfigureMainButton() { } protected open fun createArrowButton(): JButton = ArrowButton().apply { icon = AllIcons.General.ArrowDown } protected open fun configureArrowButton() { arrowButton.isFocusable = false arrowButton.preferredSize = arrowButtonPreferredSize arrowButton.isVisible = !isSimpleButton arrowButtonActionListener = createArrowButtonActionListener()?.apply(arrowButton::addActionListener) arrowButtonMouseListener = createArrowButtonMouseListener()?.apply(arrowButton::addMouseListener) } protected open fun unconfigureArrowButton() { arrowButton.removeActionListener(arrowButtonActionListener) arrowButton.removeMouseListener(arrowButtonMouseListener) arrowButtonActionListener = null arrowButtonMouseListener = null } protected open val arrowButtonPreferredSize: Dimension get() = JBUI.size(16) protected open fun createLayoutManager(): LayoutManager = OptionButtonLayout() protected open fun installListeners() { propertyChangeListener = createPropertyChangeListener()?.apply(optionButton::addPropertyChangeListener) changeListener = createChangeListener()?.apply(optionButton::addChangeListener) focusListener = createFocusListener()?.apply(optionButton::addFocusListener) } protected open fun uninstallListeners() { optionButton.removePropertyChangeListener(propertyChangeListener) optionButton.removeChangeListener(changeListener) optionButton.removeFocusListener(focusListener) propertyChangeListener = null changeListener = null focusListener = null } protected open fun createPropertyChangeListener(): PropertyChangeListener? = PropertyChangeListener { when (it.propertyName) { "action" -> mainButton.action = optionButton.action TEXT_CHANGED_PROPERTY -> mainButton.text = optionButton.text MNEMONIC_CHANGED_PROPERTY -> mainButton.mnemonic = optionButton.mnemonic TOOL_TIP_TEXT_KEY, PROP_OPTION_TOOLTIP -> updateTooltip() PROP_OPTIONS -> { closePopup() updateTooltip() updateOptions() } } } protected open fun createChangeListener(): ChangeListener? = ChangeListener { arrowButton.isEnabled = optionButton.isEnabled // mainButton is updated from corresponding Action instance } protected open fun createFocusListener(): FocusListener? = object : FocusAdapter() { override fun focusLost(e: FocusEvent?) { repaint() } override fun focusGained(e: FocusEvent?) { repaint() } private fun repaint() { mainButton.repaint() arrowButton.repaint() } } protected open fun createArrowButtonActionListener(): ActionListener? = ActionListener { togglePopup() } protected open fun createArrowButtonMouseListener(): MouseListener? = object : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (SwingUtilities.isLeftMouseButton(e)) { e.consume() arrowButton.doClick() } } } protected open fun installKeyboardActions() { replaceUIActionMap(optionButton, mainButton.actionMap) replaceUIInputMap(optionButton, JComponent.WHEN_FOCUSED, mainButton.inputMap) } protected open fun uninstallKeyboardActions() { replaceUIActionMap(optionButton, null) replaceUIInputMap(optionButton, JComponent.WHEN_FOCUSED, null) } override fun showPopup(toSelect: Action?, ensureSelection: Boolean) { if (!isSimpleButton) { isPopupShowing = true popup = createPopup(toSelect, ensureSelection).apply { // use invokeLater() to update flag "after" popup is auto-closed - to ensure correct togglePopup() behaviour on arrow button press setFinalRunnable { getApplication().invokeLater { isPopupShowing = false } } addListener(object : JBPopupAdapter() { override fun beforeShown(event: LightweightWindowEvent) { val popup = event.asPopup() val screen = ScreenUtil.getScreenRectangle(optionButton.locationOnScreen) val above = screen.height < popup.size.height + showPopupBelowLocation.screenPoint.y if (above) { val point = Point(showPopupAboveLocation.screenPoint) point.translate(0, -popup.size.height) popup.setLocation(point) } } override fun onClosed(event: LightweightWindowEvent) { // final runnable is not called when some action is invoked - so we handle this case here separately if (event.isOk) { isPopupShowing = false } } }) show(showPopupBelowLocation) } } } override fun closePopup() { popup?.cancel() } override fun togglePopup() { if (isPopupShowing) { closePopup() } else { showPopup() } } protected open val showPopupXOffset: Int get() = 0 protected open val showPopupBelowLocation: RelativePoint get() = RelativePoint(optionButton, Point(showPopupXOffset, optionButton.height + scale(6))) protected open val showPopupAboveLocation: RelativePoint get() = RelativePoint(optionButton, Point(showPopupXOffset, -scale(6))) protected open fun createPopup(toSelect: Action?, ensureSelection: Boolean): ListPopup { val (actionGroup, mapping) = createActionMapping() val dataContext = createActionDataContext() val actionItems = getActionItems(actionGroup, dataContext, false, false, true, true, ActionPlaces.UNKNOWN) val defaultSelection = if (toSelect != null) Condition<AnAction> { mapping[it] == toSelect } else null return OptionButtonPopup(OptionButtonPopupStep(actionItems, defaultSelection), dataContext, toSelect != null || ensureSelection) } protected open fun createActionDataContext(): DataContext = DataManager.getInstance().getDataContext(optionButton) protected open fun createActionMapping(): Pair<ActionGroup, Map<AnAction, Action>> { val mapping = optionButton.options?.associateBy(this@BasicOptionButtonUI::createAnAction) ?: emptyMap() val actionGroup = DefaultActionGroup().apply { mapping.keys.forEachIndexed { index, it -> if (index > 0) addSeparator() add(it) } } return Pair(actionGroup, mapping) } protected open fun createAnAction(action: Action): AnAction = action.getValue(OptionAction.AN_ACTION) as? AnAction ?: ActionDelegate(action) private fun updateTooltip() { val toolTip = if (!isSimpleButton) optionButton.optionTooltipText else optionButton.toolTipText mainButton.toolTipText = toolTip arrowButton.toolTipText = toolTip } protected open fun updateOptions() { arrowButton.isVisible = !isSimpleButton } open inner class BaseButton : JButton() { override fun hasFocus(): Boolean = optionButton.hasFocus() override fun isDefaultButton(): Boolean = optionButton.isDefaultButton override fun paint(g: Graphics): Unit = if (isSimpleButton) super.paint(g) else cloneAndPaint(g) { paintNotSimple(it) } open fun paintNotSimple(g: Graphics2D): Unit = super.paint(g) override fun paintBorder(g: Graphics): Unit = if (isSimpleButton) super.paintBorder(g) else cloneAndPaint(g) { paintBorderNotSimple(it) } open fun paintBorderNotSimple(g: Graphics2D): Unit = super.paintBorder(g) } open inner class MainButton : BaseButton() open inner class ArrowButton : BaseButton() open inner class OptionButtonLayout : AbstractLayoutManager() { override fun layoutContainer(parent: Container) { val mainButtonWidth = optionButton.width - if (arrowButton.isVisible) arrowButton.preferredSize.width else 0 mainButton.bounds = Rectangle(0, 0, mainButtonWidth, optionButton.height) arrowButton.bounds = Rectangle(mainButtonWidth, 0, arrowButton.preferredSize.width, optionButton.height) } override fun preferredLayoutSize(parent: Container): Dimension = parent.preferredSize override fun minimumLayoutSize(parent: Container): Dimension = parent.minimumSize } open inner class OptionButtonPopup(step: ActionPopupStep, dataContext: DataContext, private val ensureSelection: Boolean) : PopupFactoryImpl.ActionGroupPopup(null, step, null, dataContext, ActionPlaces.UNKNOWN, -1) { init { list.background = background } override fun afterShow() { if (ensureSelection) super.afterShow() } protected val background: Color? get() = mainButton.background override fun createContent(): JComponent = super.createContent().also { list.clearSelection() // prevents first action selection if all actions are disabled list.border = JBUI.Borders.empty(2, 0) } override fun getListElementRenderer(): PopupListElementRenderer<Any> = object : PopupListElementRenderer<Any>(this) { override fun getBackground() = [email protected] override fun createSeparator() = super.createSeparator().apply { border = JBUI.Borders.empty(2, 6) } override fun getDefaultItemComponentBorder() = JBUI.Borders.empty(6, 8) } } open inner class OptionButtonPopupStep(actions: List<PopupFactoryImpl.ActionItem>, private val defaultSelection: Condition<AnAction>?) : ActionPopupStep(actions, null, Supplier<DataContext> { DataManager.getInstance().getDataContext(optionButton) }, null, true, defaultSelection, false, true) { // if there is no default selection condition - -1 should be returned, this way first enabled action should be selected by // OptionButtonPopup.afterShow() (if corresponding ensureSelection parameter is true) override fun getDefaultOptionIndex(): Int = defaultSelection?.let { super.getDefaultOptionIndex() } ?: -1 override fun isSpeedSearchEnabled(): Boolean = false } open inner class ActionDelegate(val action: Action) : DumbAwareAction() { init { isEnabledInModalContext = true templatePresentation.text = (action.getValue(Action.NAME) as? String).orEmpty() } override fun update(event: AnActionEvent) { event.presentation.isEnabled = action.isEnabled } override fun actionPerformed(event: AnActionEvent) { action.actionPerformed(ActionEvent(optionButton, ActionEvent.ACTION_PERFORMED, null)) } } companion object { @Suppress("UNUSED_PARAMETER") @JvmStatic fun createUI(c: JComponent): BasicOptionButtonUI = BasicOptionButtonUI() fun paintBackground(g: Graphics, c: JComponent) { g.color = c.background g.fillRect(0, 0, c.width, c.height) } fun cloneAndPaint(g: Graphics, block: (Graphics2D) -> Unit) { val g2 = g.create() as Graphics2D try { block(g2) } finally { g2.dispose() } } } }
apache-2.0
47eb9afea74d0b0745a6856681d51a2d
36.70297
151
0.735868
5.200068
false
false
false
false
marius-m/wt4
credits/src/main/kotlin/lt/markmerkk/credits/CreditsPresenter.kt
1
1843
package lt.markmerkk.credits import lt.markmerkk.repositories.CreditsRepository import org.slf4j.LoggerFactory import rx.Scheduler import rx.Subscription class CreditsPresenter( private val creditsRepository: CreditsRepository, private val ioScheduler: Scheduler, private val uiScheduler: Scheduler ): CreditsContract.Presenter { private var view: CreditsContract.View? = null private var entriesDisposable: Subscription? = null private var findEntryDisposable: Subscription? = null override fun onAttach(view: CreditsContract.View) { this.view = view entriesDisposable = creditsRepository.creditEntries() .subscribeOn(ioScheduler) .observeOn(uiScheduler) .subscribe({ entries -> val creditTitles = entries.map { it.title } this.view?.renderCreditEntries(creditTitles) findCreditDetails(creditTitles.first()) }, { error -> logger.warn("Error reading credit entries", error) }) } override fun onDetach() { this.view = null entriesDisposable?.unsubscribe() findEntryDisposable?.unsubscribe() } fun findCreditDetails(creditTitle: String) { findEntryDisposable?.unsubscribe() findEntryDisposable = creditsRepository.creditEntries() .subscribeOn(ioScheduler) .observeOn(uiScheduler) .subscribe({ entries -> val entry = entries .first { it.title == creditTitle } view?.showCreditDetails(entry) }, { error -> logger.warn("Error trying to look for entry", error) }) } companion object { val logger = LoggerFactory.getLogger(CreditsPresenter::class.java)!! } }
apache-2.0
995298158206dc868818f4aa15f6cffd
31.928571
76
0.629951
5.176966
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/render/RenderCactus.kt
1
4952
package mods.betterfoliage.client.render import mods.betterfoliage.BetterFoliageMod import mods.betterfoliage.client.Client import mods.betterfoliage.client.config.Config import mods.betterfoliage.client.render.column.ColumnTextureInfo import mods.betterfoliage.client.render.column.SimpleColumnInfo import mods.octarinecore.client.render.* import mods.octarinecore.client.resource.ModelRenderRegistryConfigurable import mods.octarinecore.common.Int3 import mods.octarinecore.common.Rotation import mods.octarinecore.common.config.ModelTextureList import mods.octarinecore.common.config.SimpleBlockMatcher import net.minecraft.block.BlockCactus import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.BlockRendererDispatcher import net.minecraft.client.renderer.BufferBuilder import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumFacing.* import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import org.apache.logging.log4j.Level object StandardCactusRegistry : ModelRenderRegistryConfigurable<ColumnTextureInfo>() { override val logger = BetterFoliageMod.logDetail override val matchClasses = SimpleBlockMatcher(BlockCactus::class.java) override val modelTextures = listOf(ModelTextureList("block/cactus", "top", "bottom", "side")) override fun processModel(state: IBlockState, textures: List<String>) = SimpleColumnInfo.Key(logger, Axis.Y, textures) init { MinecraftForge.EVENT_BUS.register(this) } } @SideOnly(Side.CLIENT) class RenderCactus : AbstractBlockRenderingHandler(BetterFoliageMod.MOD_ID) { val cactusStemRadius = 0.4375 val cactusArmRotation = listOf(NORTH, SOUTH, EAST, WEST).map { Rotation.rot90[it.ordinal] } val iconCross = iconStatic(BetterFoliageMod.LEGACY_DOMAIN, "blocks/better_cactus") val iconArm = iconSet(BetterFoliageMod.LEGACY_DOMAIN, "blocks/better_cactus_arm_%d") val modelStem = model { horizontalRectangle(x1 = -cactusStemRadius, x2 = cactusStemRadius, z1 = -cactusStemRadius, z2 = cactusStemRadius, y = 0.5) .scaleUV(cactusStemRadius * 2.0) .let { listOf(it.flipped.move(1.0 to DOWN), it) } .forEach { it.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y), edge = null)).add() } verticalRectangle(x1 = -0.5, z1 = cactusStemRadius, x2 = 0.5, z2 = cactusStemRadius, yBottom = -0.5, yTop = 0.5) .setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y), edge = null)) .toCross(UP).addAll() } val modelCross = modelSet(64) { modelIdx -> verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -0.5 * 1.41, yTop = 0.5 * 1.41) .setAoShader(edgeOrientedAuto(corner = cornerAoMaxGreen)) .scale(1.4) .transformV { v -> val perturb = xzDisk(modelIdx) * Config.cactus.sizeVariation Vertex(v.xyz + (if (v.uv.u < 0.0) perturb else -perturb), v.uv, v.aoShader) } .toCross(UP).addAll() } val modelArm = modelSet(64) { modelIdx -> verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.0, yTop = 1.0) .scale(Config.cactus.size).move(0.5 to UP) .setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y), edge = null)) .toCross(UP) { it.move(xzDisk(modelIdx) * Config.cactus.hOffset) }.addAll() } override fun afterPreStitch() { Client.log(Level.INFO, "Registered ${iconArm.num} cactus arm textures") } override fun isEligible(ctx: BlockContext): Boolean = Config.enabled && Config.cactus.enabled && Config.blocks.cactus.matchesClass(ctx.block) override fun render(ctx: BlockContext, dispatcher: BlockRendererDispatcher, renderer: BufferBuilder, layer: BlockRenderLayer): Boolean { // render the whole block on the cutout layer if (!layer.isCutout) return false // get AO data modelRenderer.updateShading(Int3.zero, allFaces) val icons = StandardCactusRegistry[ctx] ?: return renderWorldBlockBase(ctx, dispatcher, renderer, null) modelRenderer.render( renderer, modelStem.model, Rotation.identity, icon = { ctx, qi, q -> when(qi) { 0 -> icons.bottom(ctx, qi, q); 1 -> icons.top(ctx, qi, q); else -> icons.side(ctx, qi, q) } }, postProcess = noPost ) modelRenderer.render( renderer, modelCross[ctx.random(0)], Rotation.identity, icon = { _, _, _ -> iconCross.icon!!}, postProcess = noPost ) modelRenderer.render( renderer, modelArm[ctx.random(1)], cactusArmRotation[ctx.random(2) % 4], icon = { _, _, _ -> iconArm[ctx.random(3)]!!}, postProcess = noPost ) return true } }
mit
2009a156494af1162620c25397bf3083
43.621622
140
0.680533
3.554917
false
true
false
false
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/mirrors/signature/GenericDeclaration.kt
1
2270
/* * Copyright 2021 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.grip.mirrors.signature import io.michaelrocks.grip.commons.LazyList interface GenericDeclaration { val typeVariables: List<GenericType.TypeVariable> } internal interface MutableGenericDeclaration : GenericDeclaration { override val typeVariables: MutableList<GenericType.TypeVariable> } internal class InheritingGenericDeclaration( parent: GenericDeclaration = EmptyGenericDeclaration ) : MutableGenericDeclaration { override val typeVariables: MutableList<GenericType.TypeVariable> = if (parent.typeVariables.isEmpty()) LazyList() else parent.typeVariables.toMutableList() } internal object EmptyGenericDeclaration : GenericDeclaration { override val typeVariables: List<GenericType.TypeVariable> get() = emptyList() } internal fun GenericDeclaration(typeVariables: List<GenericType.TypeVariable>): GenericDeclaration { return object : GenericDeclaration { override val typeVariables: List<GenericType.TypeVariable> = typeVariables } } internal class LazyGenericDeclaration( builder: () -> GenericDeclaration ) : GenericDeclaration { private val delegate by lazy { builder() } override val typeVariables: List<GenericType.TypeVariable> get() = delegate.typeVariables } internal fun GenericDeclaration.inherit(genericDeclaration: GenericDeclaration): GenericDeclaration { return InheritingGenericDeclaration(this).apply { typeVariables.addAll(genericDeclaration.typeVariables) } } internal inline fun GenericDeclaration.inheritLazily( crossinline genericDeclaration: () -> GenericDeclaration ): GenericDeclaration { return LazyGenericDeclaration { inherit(genericDeclaration()) } }
apache-2.0
e7ef06e4adfa0e1fe445dcfb7ff2ba0a
32.880597
101
0.788987
5.044444
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/VKVideoTypes.kt
2
42830
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package vulkan import org.lwjgl.generator.* const val STD = "STD" val uint32_tb = PrimitiveType("uint32_t", PrimitiveMapping.BOOLEAN4) // vulkan_video_codec_h264std.h val StdVideoH264AspectRatioIdc = "StdVideoH264AspectRatioIdc".enumType val StdVideoH264CabacInitIdc = "StdVideoH264CabacInitIdc".enumType val StdVideoH264ChromaFormatIdc = "StdVideoH264ChromaFormatIdc".enumType val StdVideoH264DisableDeblockingFilterIdc = "StdVideoH264DisableDeblockingFilterIdc".enumType val StdVideoH264Level = "StdVideoH264Level".enumType val StdVideoH264MemMgmtControlOp = "StdVideoH264MemMgmtControlOp".enumType val StdVideoH264ModificationOfPicNumsIdc = "StdVideoH264ModificationOfPicNumsIdc".enumType val StdVideoH264NonVclNaluType = "StdVideoH264NonVclNaluType".enumType val StdVideoH264PictureType = "StdVideoH264PictureType".enumType val StdVideoH264PocType = "StdVideoH264PocType".enumType val StdVideoH264ProfileIdc = "StdVideoH264ProfileIdc".enumType val StdVideoH264SliceType = "StdVideoH264SliceType".enumType val StdVideoH264WeightedBipredIdc = "StdVideoH264WeightedBipredIdc".enumType val StdVideoH265PictureType = "StdVideoH265PictureType".enumType val StdVideoH265SliceType = "StdVideoH265SliceType".enumType val StdVideoH264SpsVuiFlags = struct(Module.VULKAN, "StdVideoH264SpsVuiFlags") { subpackage = "video" uint32_tb("aspect_ratio_info_present_flag", "", bits = 1) uint32_tb("overscan_info_present_flag", "", bits = 1) uint32_tb("overscan_appropriate_flag", "", bits = 1) uint32_tb("video_signal_type_present_flag", "", bits = 1) uint32_tb("video_full_range_flag", "", bits = 1) uint32_tb("color_description_present_flag", "", bits = 1) uint32_tb("chroma_loc_info_present_flag", "", bits = 1) uint32_tb("timing_info_present_flag", "", bits = 1) uint32_tb("fixed_frame_rate_flag", "", bits = 1) uint32_tb("bitstream_restriction_flag", "", bits = 1) uint32_tb("nal_hrd_parameters_present_flag", "", bits = 1) uint32_tb("vcl_hrd_parameters_present_flag", "", bits = 1) } val StdVideoH264HrdParameters = struct(Module.VULKAN, "StdVideoH264HrdParameters") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH264.*") uint8_t("cpb_cnt_minus1", "") uint8_t("bit_rate_scale", "") uint8_t("cpb_size_scale", "") uint32_t("bit_rate_value_minus1", "")["STD_VIDEO_H264_CPB_CNT_LIST_SIZE"] uint32_t("cpb_size_value_minus1", "")["STD_VIDEO_H264_CPB_CNT_LIST_SIZE"] uint8_t("cbr_flag", "")["STD_VIDEO_H264_CPB_CNT_LIST_SIZE"] uint32_t("initial_cpb_removal_delay_length_minus1", "") uint32_t("cpb_removal_delay_length_minus1", "") uint32_t("dpb_output_delay_length_minus1", "") uint32_t("time_offset_length", "") } val StdVideoH264SequenceParameterSetVui = struct(Module.VULKAN, "StdVideoH264SequenceParameterSetVui") { subpackage = "video" StdVideoH264SpsVuiFlags("flags", "") StdVideoH264AspectRatioIdc("aspect_ratio_idc", "") uint16_t("sar_width", "") uint16_t("sar_height", "") uint8_t("video_format", "") uint8_t("color_primaries", "") uint8_t("transfer_characteristics", "") uint8_t("matrix_coefficients", "") uint32_t("num_units_in_tick", "") uint32_t("time_scale", "") StdVideoH264HrdParameters.const.p( "pHrdParameters", "must be a valid {@code ptr} to {@code hrd_parameters}, if {@code nal_hrd_parameters_present_flag} or {@code vcl_hrd_parameters_present_flag} are set" ) uint8_t("max_num_reorder_frames", "") uint8_t("max_dec_frame_buffering", "") } val StdVideoH264SpsFlags = struct(Module.VULKAN, "StdVideoH264SpsFlags") { subpackage = "video" uint32_tb("constraint_set0_flag", "", bits = 1) uint32_tb("constraint_set1_flag", "", bits = 1) uint32_tb("constraint_set2_flag", "", bits = 1) uint32_tb("constraint_set3_flag", "", bits = 1) uint32_tb("constraint_set4_flag", "", bits = 1) uint32_tb("constraint_set5_flag", "", bits = 1) uint32_tb("direct_8x8_inference_flag", "", bits = 1) uint32_tb("mb_adaptive_frame_field_flag", "", bits = 1) uint32_tb("frame_mbs_only_flag", "", bits = 1) uint32_tb("delta_pic_order_always_zero_flag", "", bits = 1) uint32_tb("separate_colour_plane_flag", "", bits = 1) uint32_tb("gaps_in_frame_num_value_allowed_flag", "", bits = 1) uint32_tb("qpprime_y_zero_transform_bypass_flag", "", bits = 1) uint32_tb("frame_cropping_flag", "", bits = 1) uint32_tb("seq_scaling_matrix_present_flag", "", bits = 1) uint32_tb("vui_parameters_present_flag", "", bits = 1) } val StdVideoH264ScalingLists = struct(Module.VULKAN, "StdVideoH264ScalingLists") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH264.*") uint8_t( "scaling_list_present_mask", """ scaling_list_present_mask has one bit for each seq_scaling_list_present_flag[i] for SPS OR pic_scaling_list_present_flag[i] for PPS, bit 0 - 5 are for each entry of ScalingList4x4 bit 6 - 7 are for each entry plus 6 for ScalingList8x8 """ ) uint8_t( "use_default_scaling_matrix_mask", """ use_default_scaling_matrix_mask has one bit for each UseDefaultScalingMatrix4x4Flag[ i ] and UseDefaultScalingMatrix8x8Flag[ i - 6 ] for SPS OR PPS bit 0 - 5 are for each entry of ScalingList4x4 bit 6 - 7 are for each entry plus 6 for ScalingList8x8 """ ) uint8_t("ScalingList4x4", "")["STD_VIDEO_H264_SCALING_LIST_4X4_NUM_LISTS"]["STD_VIDEO_H264_SCALING_LIST_4X4_NUM_ELEMENTS"] uint8_t("ScalingList8x8", "")["STD_VIDEO_H264_SCALING_LIST_8X8_NUM_LISTS"]["STD_VIDEO_H264_SCALING_LIST_8X8_NUM_ELEMENTS"] } val StdVideoH264SequenceParameterSet = struct(Module.VULKAN, "StdVideoH264SequenceParameterSet") { subpackage = "video" StdVideoH264SpsFlags("flags", "") StdVideoH264ProfileIdc("profile_idc", "") StdVideoH264Level("level_idc", "") uint8_t("seq_parameter_set_id", "") StdVideoH264ChromaFormatIdc("chroma_format_idc", "") uint8_t("bit_depth_luma_minus8", "") uint8_t("bit_depth_chroma_minus8", "") uint8_t("log2_max_frame_num_minus4", "") StdVideoH264PocType("pic_order_cnt_type", "") uint8_t("log2_max_pic_order_cnt_lsb_minus4", "") int32_t("offset_for_non_ref_pic", "") int32_t("offset_for_top_to_bottom_field", "") AutoSize("pOffsetForRefFrame")..uint8_t("num_ref_frames_in_pic_order_cnt_cycle", "") uint8_t("max_num_ref_frames", "") uint32_t("pic_width_in_mbs_minus1", "") uint32_t("pic_height_in_map_units_minus1", "") uint32_t("frame_crop_left_offset", "") uint32_t("frame_crop_right_offset", "") uint32_t("frame_crop_top_offset", "") uint32_t("frame_crop_bottom_offset", "") nullable..int32_t.const.p( "pOffsetForRefFrame", """ a pointer representing the {@code offset_for_ref_frame} array with {@code num_ref_frames_in_pic_order_cnt_cycle} number of elements. If {@code pOffsetForRefFrame} has {@code nullptr} value, then {@code num_ref_frames_in_pic_order_cnt_cycle} must also be "0". """ ) StdVideoH264ScalingLists.const.p("pScalingLists", "must be a valid pointer if scaling_matrix_present_flag is set") StdVideoH264SequenceParameterSetVui.const.p("pSequenceParameterSetVui", "must be a valid pointer if StdVideoH264SpsFlags:vui_parameters_present_flag is set") } val StdVideoH264PpsFlags = struct(Module.VULKAN, "StdVideoH264PpsFlags") { subpackage = "video" uint32_tb("transform_8x8_mode_flag", "", bits = 1) uint32_tb("redundant_pic_cnt_present_flag", "", bits = 1) uint32_tb("constrained_intra_pred_flag", "", bits = 1) uint32_tb("deblocking_filter_control_present_flag", "", bits = 1) uint32_tb("weighted_bipred_idc_flag", "", bits = 1) uint32_tb("weighted_pred_flag", "", bits = 1) uint32_tb("pic_order_present_flag", "", bits = 1) uint32_tb("entropy_coding_mode_flag", "", bits = 1) uint32_tb("pic_scaling_matrix_present_flag", "", bits = 1) } val StdVideoH264PictureParameterSet = struct(Module.VULKAN, "StdVideoH264PictureParameterSet") { subpackage = "video" StdVideoH264PpsFlags("flags", "") uint8_t("seq_parameter_set_id", "") uint8_t("pic_parameter_set_id", "") uint8_t("num_ref_idx_l0_default_active_minus1", "") uint8_t("num_ref_idx_l1_default_active_minus1", "") StdVideoH264WeightedBipredIdc("weighted_bipred_idc", "") int8_t("pic_init_qp_minus26", "") int8_t("pic_init_qs_minus26", "") int8_t("chroma_qp_index_offset", "") int8_t("second_chroma_qp_index_offset", "") StdVideoH264ScalingLists.const.p("pScalingLists", "must be a valid pointer if StdVideoH264PpsFlags::pic_scaling_matrix_present_flag is set") } // vulkan_video_codec_h264std_decode.h val StdVideoDecodeH264PictureInfoFlags = struct(Module.VULKAN, "StdVideoDecodeH264PictureInfoFlags") { subpackage = "video" uint32_tb("field_pic_flag", "is field picture", bits = 1) uint32_tb("is_intra", "is intra picture", bits = 1) uint32_tb("IdrPicFlag", "instantaneous decoding refresh (IDR) picture", bits = 1) uint32_tb("bottom_field_flag", "bottom (true) or top (false) field if field_pic_flag is set", bits = 1) uint32_tb("is_reference", "this only applies to picture info, and not to the DPB lists", bits = 1) uint32_tb("complementary_field_pair", "complementary field pair, complementary non-reference field pair, complementary reference field pair", bits = 1) } val StdVideoDecodeH264PictureInfo = struct(Module.VULKAN, "StdVideoDecodeH264PictureInfo") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH264.*") StdVideoDecodeH264PictureInfoFlags("flags", "") uint8_t("seq_parameter_set_id", "selecting SPS from the Picture Parameters") uint8_t("pic_parameter_set_id", "selecting PPS from the Picture Parameters and the SPS") uint16_t("reserved", "for structure members 32-bit packing/alignment") uint16_t("frame_num", "7.4.3 Slice header semantics") uint16_t("idr_pic_id", "7.4.3 Slice header semantics") int32_t("PicOrderCnt", "topFieldOrderCnt and BottomFieldOrderCnt fields")["STD_VIDEO_DECODE_H264_FIELD_ORDER_COUNT_LIST_SIZE"] } val StdVideoDecodeH264ReferenceInfoFlags = struct(Module.VULKAN, "StdVideoDecodeH264ReferenceInfoFlags") { subpackage = "video" uint32_tb("top_field_flag", "reference is used for top field reference", bits = 1) uint32_tb("bottom_field_flag", "reference is used for bottom field reference", bits = 1) uint32_tb("used_for_long_term_reference", "this is a long term reference", bits = 1) uint32_tb("is_non_existing", "must be handled in accordance with 8.2.5.2: Decoding process for gaps in frame_num", bits = 1) } val StdVideoDecodeH264ReferenceInfo = struct(Module.VULKAN, "StdVideoDecodeH264ReferenceInfo") { subpackage = "video" StdVideoDecodeH264ReferenceInfoFlags("flags", "") uint16_t("FrameNum", "7.4.3.3 Decoded reference picture marking semantics") uint16_t("reserved", "for structure members 32-bit packing/alignment") int32_t("PicOrderCnt", "topFieldOrderCnt and BottomFieldOrderCnt fields")[2] } val StdVideoDecodeH264MvcElementFlags = struct(Module.VULKAN, "StdVideoDecodeH264MvcElementFlags") { subpackage = "video" uint32_tb("non_idr", "", bits = 1) uint32_tb("anchor_pic", "", bits = 1) uint32_tb("inter_view", "", bits = 1) } val StdVideoDecodeH264MvcElement = struct(Module.VULKAN, "StdVideoDecodeH264MvcElement") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH264.*") StdVideoDecodeH264MvcElementFlags("flags", "") uint16_t("viewOrderIndex", "") uint16_t("viewId", "") uint16_t("temporalId", "move out?") uint16_t("priorityId", "move out?") uint16_t("numOfAnchorRefsInL0", "") uint16_t("viewIdOfAnchorRefsInL0", "")["STD_VIDEO_DECODE_H264_MVC_REF_LIST_SIZE"] uint16_t("numOfAnchorRefsInL1", "") uint16_t("viewIdOfAnchorRefsInL1", "")["STD_VIDEO_DECODE_H264_MVC_REF_LIST_SIZE"] uint16_t("numOfNonAnchorRefsInL0", "") uint16_t("viewIdOfNonAnchorRefsInL0", "")["STD_VIDEO_DECODE_H264_MVC_REF_LIST_SIZE"] uint16_t("numOfNonAnchorRefsInL1", "") uint16_t("viewIdOfNonAnchorRefsInL1", "")["STD_VIDEO_DECODE_H264_MVC_REF_LIST_SIZE"] } val StdVideoDecodeH264Mvc = struct(Module.VULKAN, "StdVideoDecodeH264Mvc") { subpackage = "video" uint32_t("viewId0", "") AutoSize("pMvcElements")..uint32_t("mvcElementCount", "") StdVideoDecodeH264MvcElement.const.p("pMvcElements", "") } // vulkan_video_codec_h264std_encode.h val StdVideoEncodeH264WeightTableFlags = struct(Module.VULKAN, "StdVideoEncodeH264WeightTableFlags") { subpackage = "video" uint32_t("luma_weight_l0_flag", "") uint32_t("chroma_weight_l0_flag", "") uint32_t("luma_weight_l1_flag", "") uint32_t("chroma_weight_l1_flag", "") } val StdVideoEncodeH264WeightTable = struct(Module.VULKAN, "StdVideoEncodeH264WeightTable") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH264.*") StdVideoEncodeH264WeightTableFlags("flags", "") uint8_t("luma_log2_weight_denom", "") uint8_t("chroma_log2_weight_denom", "") int8_t("luma_weight_l0", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"] int8_t("luma_offset_l0", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"] int8_t("chroma_weight_l0", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"]["STD_VIDEO_H264_MAX_CHROMA_PLANES"] int8_t("chroma_offset_l0", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"]["STD_VIDEO_H264_MAX_CHROMA_PLANES"] int8_t("luma_weight_l1", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"] int8_t("luma_offset_l1", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"] int8_t("chroma_weight_l1", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"]["STD_VIDEO_H264_MAX_CHROMA_PLANES"] int8_t("chroma_offset_l1", "")["STD_VIDEO_H264_MAX_NUM_LIST_REF"]["STD_VIDEO_H264_MAX_CHROMA_PLANES"] } val StdVideoEncodeH264SliceHeaderFlags = struct(Module.VULKAN, "StdVideoEncodeH264SliceHeaderFlags") { subpackage = "video" uint32_tb("direct_spatial_mv_pred_flag", "", bits = 1) uint32_tb("num_ref_idx_active_override_flag", "", bits = 1) uint32_tb("no_output_of_prior_pics_flag", "", bits = 1) uint32_tb("adaptive_ref_pic_marking_mode_flag", "", bits = 1) uint32_tb("no_prior_references_available_flag", "", bits = 1) } val StdVideoEncodeH264PictureInfoFlags = struct(Module.VULKAN, "StdVideoEncodeH264PictureInfoFlags") { subpackage = "video" uint32_tb("idr_flag", "", bits = 1) uint32_tb("is_reference_flag", "", bits = 1) uint32_tb("used_for_long_term_reference", "", bits = 1) } val StdVideoEncodeH264ReferenceInfoFlags = struct(Module.VULKAN, "StdVideoEncodeH264ReferenceInfoFlags") { subpackage = "video" uint32_tb("used_for_long_term_reference", "", bits = 1) } val StdVideoEncodeH264RefMgmtFlags = struct(Module.VULKAN, "StdVideoEncodeH264RefMgmtFlags") { subpackage = "video" uint32_tb("ref_pic_list_modification_l0_flag", "", bits = 1) uint32_tb("ref_pic_list_modification_l1_flag", "", bits = 1) } val StdVideoEncodeH264RefListModEntry = struct(Module.VULKAN, "StdVideoEncodeH264RefListModEntry") { subpackage = "video" StdVideoH264ModificationOfPicNumsIdc("modification_of_pic_nums_idc", "") uint16_t("abs_diff_pic_num_minus1", "") uint16_t("long_term_pic_num", "") } val StdVideoEncodeH264RefPicMarkingEntry = struct(Module.VULKAN, "StdVideoEncodeH264RefPicMarkingEntry") { subpackage = "video" StdVideoH264MemMgmtControlOp("operation", "") uint16_t("difference_of_pic_nums_minus1", "") uint16_t("long_term_pic_num", "") uint16_t("long_term_frame_idx", "") uint16_t("max_long_term_frame_idx_plus1", "") } val StdVideoEncodeH264RefMemMgmtCtrlOperations = struct(Module.VULKAN, "StdVideoEncodeH264RefMemMgmtCtrlOperations") { subpackage = "video" StdVideoEncodeH264RefMgmtFlags("flags", "") AutoSize("pRefList0ModOperations")..uint8_t("refList0ModOpCount", "") StdVideoEncodeH264RefListModEntry.const.p("pRefList0ModOperations", "") AutoSize("pRefList1ModOperations")..uint8_t("refList1ModOpCount", "") StdVideoEncodeH264RefListModEntry.const.p("pRefList1ModOperations", "") AutoSize("pRefPicMarkingOperations")..uint8_t("refPicMarkingOpCount", "") StdVideoEncodeH264RefPicMarkingEntry.const.p("pRefPicMarkingOperations", "") } val StdVideoEncodeH264PictureInfo = struct(Module.VULKAN, "StdVideoEncodeH264PictureInfo") { subpackage = "video" StdVideoEncodeH264PictureInfoFlags("flags", "") uint8_t("seq_parameter_set_id", "") uint8_t("pic_parameter_set_id", "") StdVideoH264PictureType("pictureType", "") uint32_t("frame_num", "") int32_t("PicOrderCnt", "") } val StdVideoEncodeH264ReferenceInfo = struct(Module.VULKAN, "StdVideoEncodeH264ReferenceInfo") { subpackage = "video" StdVideoEncodeH264ReferenceInfoFlags("flags", "") uint32_t("FrameNum", "") int32_t("PicOrderCnt", "") uint16_t("long_term_pic_num", "") uint16_t("long_term_frame_idx", "") } val StdVideoEncodeH264SliceHeader = struct(Module.VULKAN, "StdVideoEncodeH264SliceHeader") { subpackage = "video" StdVideoEncodeH264SliceHeaderFlags("flags", "") uint32_t("first_mb_in_slice", "") StdVideoH264SliceType("slice_type", "") uint16_t("idr_pic_id", "") uint8_t("num_ref_idx_l0_active_minus1", "") uint8_t("num_ref_idx_l1_active_minus1", "") StdVideoH264CabacInitIdc("cabac_init_idc", "") StdVideoH264DisableDeblockingFilterIdc("disable_deblocking_filter_idc", "") int8_t("slice_alpha_c0_offset_div2", "") int8_t("slice_beta_offset_div2", "") StdVideoEncodeH264WeightTable.const.p("pWeightTable", "") } // vulkan_video_codec_h265std.h val StdVideoH265ChromaFormatIdc = "StdVideoH265ChromaFormatIdc".enumType val StdVideoH265Level = "StdVideoH265Level".enumType val StdVideoH265ProfileIdc = "StdVideoH265ProfileIdc".enumType val StdVideoH265DecPicBufMgr = struct(Module.VULKAN, "StdVideoH265DecPicBufMgr") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") uint32_t("max_latency_increase_plus1", "")["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] uint8_t("max_dec_pic_buffering_minus1", "")["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] uint8_t("max_num_reorder_pics", "")["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] } val StdVideoH265SubLayerHrdParameters = struct(Module.VULKAN, "StdVideoH265SubLayerHrdParameters") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") uint32_t("bit_rate_value_minus1", "")["STD_VIDEO_H265_CPB_CNT_LIST_SIZE"] uint32_t("cpb_size_value_minus1", "")["STD_VIDEO_H265_CPB_CNT_LIST_SIZE"] uint32_t("cpb_size_du_value_minus1", "")["STD_VIDEO_H265_CPB_CNT_LIST_SIZE"] uint32_t("bit_rate_du_value_minus1", "")["STD_VIDEO_H265_CPB_CNT_LIST_SIZE"] uint32_t("cbr_flag", "each bit represents a range of CpbCounts (bit 0 - cpb_cnt_minus1) per sub-layer") } val StdVideoH265HrdFlags = struct(Module.VULKAN, "StdVideoH265HrdFlags") { subpackage = "video" uint32_tb("nal_hrd_parameters_present_flag", "", bits = 1) uint32_tb("vcl_hrd_parameters_present_flag", "", bits = 1) uint32_tb("sub_pic_hrd_params_present_flag", "", bits = 1) uint32_tb("sub_pic_cpb_params_in_pic_timing_sei_flag", "", bits = 1) uint32_t("fixed_pic_rate_general_flag", "each bit represents a sublayer, bit 0 - vps_max_sub_layers_minus1", bits = 8) uint32_t("fixed_pic_rate_within_cvs_flag", "each bit represents a sublayer, bit 0 - vps_max_sub_layers_minus1", bits = 8) uint32_t("low_delay_hrd_flag", "each bit represents a sublayer, bit 0 - vps_max_sub_layers_minus1", bits = 8) } val StdVideoH265HrdParameters = struct(Module.VULKAN, "StdVideoH265HrdParameters") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") StdVideoH265HrdFlags("flags", "") uint8_t("tick_divisor_minus2", "") uint8_t("du_cpb_removal_delay_increment_length_minus1", "") uint8_t("dpb_output_delay_du_length_minus1", "") uint8_t("bit_rate_scale", "") uint8_t("cpb_size_scale", "") uint8_t("cpb_size_du_scale", "") uint8_t("initial_cpb_removal_delay_length_minus1", "") uint8_t("au_cpb_removal_delay_length_minus1", "") uint8_t("dpb_output_delay_length_minus1", "") uint8_t("cpb_cnt_minus1", "")["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] uint16_t("elemental_duration_in_tc_minus1", "")["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] StdVideoH265SubLayerHrdParameters.const.p( "pSubLayerHrdParametersNal", "NAL per layer {@code ptr} to {@code sub_layer_hrd_parameters}" )["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] StdVideoH265SubLayerHrdParameters.const.p( "pSubLayerHrdParametersVcl", "VCL per layer {@code ptr} to {@code sub_layer_hrd_parameters}" )["STD_VIDEO_H265_SUBLAYERS_MINUS1_LIST_SIZE"] } val StdVideoH265VpsFlags = struct(Module.VULKAN, "StdVideoH265VpsFlags") { subpackage = "video" uint32_tb("vps_temporal_id_nesting_flag", "", bits = 1) uint32_tb("vps_sub_layer_ordering_info_present_flag", "", bits = 1) uint32_tb("vps_timing_info_present_flag", "", bits = 1) uint32_tb("vps_poc_proportional_to_timing_flag", "", bits = 1) } val StdVideoH265VideoParameterSet = struct(Module.VULKAN, "StdVideoH265VideoParameterSet") { subpackage = "video" StdVideoH265VpsFlags("flags", "") uint8_t("vps_video_parameter_set_id", "") uint8_t("vps_max_sub_layers_minus1", "") uint32_t("vps_num_units_in_tick", "") uint32_t("vps_time_scale", "") uint32_t("vps_num_ticks_poc_diff_one_minus1", "") StdVideoH265DecPicBufMgr.const.p("pDecPicBufMgr", "") StdVideoH265HrdParameters.const.p("pHrdParameters", "") } val StdVideoH265ScalingLists = struct(Module.VULKAN, "StdVideoH265ScalingLists") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") uint8_t( "ScalingList4x4", "{@code scalingList[ 0 ][ MatrixID ][ i ] (sizeID = 0)}" )["STD_VIDEO_H265_SCALING_LIST_4X4_NUM_LISTS"]["STD_VIDEO_H265_SCALING_LIST_4X4_NUM_ELEMENTS"] uint8_t( "ScalingList8x8", "{@code scalingList[ 1 ][ MatrixID ][ i ] (sizeID = 1)}" )["STD_VIDEO_H265_SCALING_LIST_8X8_NUM_LISTS"]["STD_VIDEO_H265_SCALING_LIST_8X8_NUM_ELEMENTS"] uint8_t( "ScalingList16x16", "{@code scalingList[ 2 ][ MatrixID ][ i ] (sizeID = 2)}" )["STD_VIDEO_H265_SCALING_LIST_16X16_NUM_LISTS"]["STD_VIDEO_H265_SCALING_LIST_16X16_NUM_ELEMENTS"] uint8_t( "ScalingList32x32", "{@code scalingList[ 3 ][ MatrixID ][ i ] (sizeID = 3)}" )["STD_VIDEO_H265_SCALING_LIST_32X32_NUM_LISTS"]["STD_VIDEO_H265_SCALING_LIST_32X32_NUM_ELEMENTS"] uint8_t( "ScalingListDCCoef16x16", "{@code scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8, sizeID = 2}" )["STD_VIDEO_H265_SCALING_LIST_16X16_NUM_LISTS"] uint8_t( "ScalingListDCCoef32x32", "{@code scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8. sizeID = 3}" )["STD_VIDEO_H265_SCALING_LIST_32X32_NUM_LISTS"] } val StdVideoH265SpsVuiFlags = struct(Module.VULKAN, "StdVideoH265SpsVuiFlags") { subpackage = "video" uint32_tb("aspect_ratio_info_present_flag", "", bits = 1) uint32_tb("overscan_info_present_flag", "", bits = 1) uint32_tb("overscan_appropriate_flag", "", bits = 1) uint32_tb("video_signal_type_present_flag", "", bits = 1) uint32_tb("video_full_range_flag", "", bits = 1) uint32_tb("colour_description_present_flag", "", bits = 1) uint32_tb("chroma_loc_info_present_flag", "", bits = 1) uint32_tb("neutral_chroma_indication_flag", "", bits = 1) uint32_tb("field_seq_flag", "", bits = 1) uint32_tb("frame_field_info_present_flag", "", bits = 1) uint32_tb("default_display_window_flag", "", bits = 1) uint32_tb("vui_timing_info_present_flag", "", bits = 1) uint32_tb("vui_poc_proportional_to_timing_flag", "", bits = 1) uint32_tb("vui_hrd_parameters_present_flag", "", bits = 1) uint32_tb("bitstream_restriction_flag", "", bits = 1) uint32_tb("tiles_fixed_structure_flag", "", bits = 1) uint32_tb("motion_vectors_over_pic_boundaries_flag", "", bits = 1) uint32_tb("restricted_ref_pic_lists_flag", "", bits = 1) } val StdVideoH265SequenceParameterSetVui = struct(Module.VULKAN, "StdVideoH265SequenceParameterSetVui") { subpackage = "video" StdVideoH265SpsVuiFlags("flags", "") uint8_t("aspect_ratio_idc", "") uint16_t("sar_width", "") uint16_t("sar_height", "") uint8_t("video_format", "") uint8_t("colour_primaries", "") uint8_t("transfer_characteristics", "") uint8_t("matrix_coeffs", "") uint8_t("chroma_sample_loc_type_top_field", "") uint8_t("chroma_sample_loc_type_bottom_field", "") uint16_t("def_disp_win_left_offset", "") uint16_t("def_disp_win_right_offset", "") uint16_t("def_disp_win_top_offset", "") uint16_t("def_disp_win_bottom_offset", "") uint32_t("vui_num_units_in_tick", "") uint32_t("vui_time_scale", "") uint32_t("vui_num_ticks_poc_diff_one_minus1", "") StdVideoH265HrdParameters.const.p("pHrdParameters", "") uint16_t("min_spatial_segmentation_idc", "") uint8_t("max_bytes_per_pic_denom", "") uint8_t("max_bits_per_min_cu_denom", "") uint8_t("log2_max_mv_length_horizontal", "") uint8_t("log2_max_mv_length_vertical", "") } val StdVideoH265PredictorPaletteEntries = struct(Module.VULKAN, "StdVideoH265PredictorPaletteEntries") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") uint16_t("PredictorPaletteEntries", "")["STD_VIDEO_H265_PREDICTOR_PALETTE_COMPONENTS_LIST_SIZE"]["STD_VIDEO_H265_PREDICTOR_PALETTE_COMP_ENTRIES_LIST_SIZE"] } val StdVideoH265SpsFlags = struct(Module.VULKAN, "StdVideoH265SpsFlags") { subpackage = "video" uint32_tb("sps_temporal_id_nesting_flag", "", bits = 1) uint32_tb("separate_colour_plane_flag", "", bits = 1) uint32_tb("scaling_list_enabled_flag", "", bits = 1) uint32_tb("sps_scaling_list_data_present_flag", "", bits = 1) uint32_tb("amp_enabled_flag", "", bits = 1) uint32_tb("sample_adaptive_offset_enabled_flag", "", bits = 1) uint32_tb("pcm_enabled_flag", "", bits = 1) uint32_tb("pcm_loop_filter_disabled_flag", "", bits = 1) uint32_tb("long_term_ref_pics_present_flag", "", bits = 1) uint32_tb("sps_temporal_mvp_enabled_flag", "", bits = 1) uint32_tb("strong_intra_smoothing_enabled_flag", "", bits = 1) uint32_tb("vui_parameters_present_flag", "", bits = 1) uint32_tb("sps_extension_present_flag", "", bits = 1) uint32_tb("sps_range_extension_flag", "", bits = 1) uint32_tb("transform_skip_rotation_enabled_flag", "extension SPS flags, valid when #VIDEO_H265_PROFILE_IDC_FORMAT_RANGE_EXTENSIONS is set", bits = 1) uint32_tb("transform_skip_context_enabled_flag", "", bits = 1) uint32_tb("implicit_rdpcm_enabled_flag", "", bits = 1) uint32_tb("explicit_rdpcm_enabled_flag", "", bits = 1) uint32_tb("extended_precision_processing_flag", "", bits = 1) uint32_tb("intra_smoothing_disabled_flag", "", bits = 1) uint32_tb("high_precision_offsets_enabled_flag", "", bits = 1) uint32_tb("persistent_rice_adaptation_enabled_flag", "", bits = 1) uint32_tb("cabac_bypass_alignment_enabled_flag", "", bits = 1) uint32_tb("sps_scc_extension_flag", "", bits = 1) uint32_tb("sps_curr_pic_ref_enabled_flag", "extension SPS flags, valid when #VIDEO_H265_PROFILE_IDC_SCC_EXTENSIONS is set", bits = 1) uint32_tb("palette_mode_enabled_flag", "", bits = 1) uint32_tb("sps_palette_predictor_initializer_present_flag", "", bits = 1) uint32_tb("intra_boundary_filtering_disabled_flag", "", bits = 1) } val StdVideoH265SequenceParameterSet = struct(Module.VULKAN, "StdVideoH265SequenceParameterSet") { subpackage = "video" StdVideoH265SpsFlags("flags", "") StdVideoH265ProfileIdc("profile_idc", "") StdVideoH265Level("level_idc", "") uint32_t("pic_width_in_luma_samples", "") uint32_t("pic_height_in_luma_samples", "") uint8_t("sps_video_parameter_set_id", "") uint8_t("sps_max_sub_layers_minus1", "") uint8_t("sps_seq_parameter_set_id", "") uint8_t("chroma_format_idc", "") uint8_t("bit_depth_luma_minus8", "") uint8_t("bit_depth_chroma_minus8", "") uint8_t("log2_max_pic_order_cnt_lsb_minus4", "") uint8_t("sps_max_dec_pic_buffering_minus1", "") uint8_t("log2_min_luma_coding_block_size_minus3", "") uint8_t("log2_diff_max_min_luma_coding_block_size", "") uint8_t("log2_min_luma_transform_block_size_minus2", "") uint8_t("log2_diff_max_min_luma_transform_block_size", "") uint8_t("max_transform_hierarchy_depth_inter", "") uint8_t("max_transform_hierarchy_depth_intra", "") uint8_t("num_short_term_ref_pic_sets", "") uint8_t("num_long_term_ref_pics_sps", "") uint8_t("pcm_sample_bit_depth_luma_minus1", "") uint8_t("pcm_sample_bit_depth_chroma_minus1", "") uint8_t("log2_min_pcm_luma_coding_block_size_minus3", "") uint8_t("log2_diff_max_min_pcm_luma_coding_block_size", "") uint32_t("conf_win_left_offset", "") uint32_t("conf_win_right_offset", "") uint32_t("conf_win_top_offset", "") uint32_t("conf_win_bottom_offset", "") StdVideoH265DecPicBufMgr.const.p("pDecPicBufMgr", "") StdVideoH265ScalingLists.const.p("pScalingLists", "must be a valid pointer if sps_scaling_list_data_present_flag is set") StdVideoH265SequenceParameterSetVui.const.p( "pSequenceParameterSetVui", "must be a valid pointer if StdVideoH265SpsFlags:vui_parameters_present_flag is set palette_max_size;" ) uint8_t("palette_max_size", "extension SPS flags, valid when #VIDEO_H265_PROFILE_IDC_SCC_EXTENSIONS is set") uint8_t("delta_palette_max_predictor_size", "") uint8_t("motion_vector_resolution_control_idc", "") uint8_t("sps_num_palette_predictor_initializer_minus1", "") StdVideoH265PredictorPaletteEntries.const.p("pPredictorPaletteEntries", "must be a valid pointer if sps_palette_predictor_initializer_present_flag is set") } val StdVideoH265PpsFlags = struct(Module.VULKAN, "StdVideoH265PpsFlags") { subpackage = "video" uint32_tb("dependent_slice_segments_enabled_flag", "", bits = 1) uint32_tb("output_flag_present_flag", "", bits = 1) uint32_tb("sign_data_hiding_enabled_flag", "", bits = 1) uint32_tb("cabac_init_present_flag", "", bits = 1) uint32_tb("constrained_intra_pred_flag", "", bits = 1) uint32_tb("transform_skip_enabled_flag", "", bits = 1) uint32_tb("cu_qp_delta_enabled_flag", "", bits = 1) uint32_tb("pps_slice_chroma_qp_offsets_present_flag", "", bits = 1) uint32_tb("weighted_pred_flag", "", bits = 1) uint32_tb("weighted_bipred_flag", "", bits = 1) uint32_tb("transquant_bypass_enabled_flag", "", bits = 1) uint32_tb("tiles_enabled_flag", "", bits = 1) uint32_tb("entropy_coding_sync_enabled_flag", "", bits = 1) uint32_tb("uniform_spacing_flag", "", bits = 1) uint32_tb("loop_filter_across_tiles_enabled_flag", "", bits = 1) uint32_tb("pps_loop_filter_across_slices_enabled_flag", "", bits = 1) uint32_tb("deblocking_filter_control_present_flag", "", bits = 1) uint32_tb("deblocking_filter_override_enabled_flag", "", bits = 1) uint32_tb("pps_deblocking_filter_disabled_flag", "", bits = 1) uint32_tb("pps_scaling_list_data_present_flag", "", bits = 1) uint32_tb("lists_modification_present_flag", "", bits = 1) uint32_tb("slice_segment_header_extension_present_flag", "", bits = 1) uint32_tb("pps_extension_present_flag", "", bits = 1) uint32_tb("cross_component_prediction_enabled_flag", "extension PPS flags, valid when #VIDEO_H265_PROFILE_IDC_FORMAT_RANGE_EXTENSIONS is set", bits = 1) uint32_tb("chroma_qp_offset_list_enabled_flag", "", bits = 1) uint32_tb("pps_curr_pic_ref_enabled_flag", "extension PPS flags, valid when #VIDEO_H265_PROFILE_IDC_SCC_EXTENSIONS is set", bits = 1) uint32_tb("residual_adaptive_colour_transform_enabled_flag", "", bits = 1) uint32_tb("pps_slice_act_qp_offsets_present_flag", "", bits = 1) uint32_tb("pps_palette_predictor_initializer_present_flag", "", bits = 1) uint32_tb("monochrome_palette_flag", "", bits = 1) uint32_tb("pps_range_extension_flag", "", bits = 1) } val StdVideoH265PictureParameterSet = struct(Module.VULKAN, "StdVideoH265PictureParameterSet") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") StdVideoH265PpsFlags("flags", "") uint8_t("pps_pic_parameter_set_id", "") uint8_t("pps_seq_parameter_set_id", "") uint8_t("num_extra_slice_header_bits", "") uint8_t("num_ref_idx_l0_default_active_minus1", "") uint8_t("num_ref_idx_l1_default_active_minus1", "") int8_t("init_qp_minus26", "") uint8_t("diff_cu_qp_delta_depth", "") int8_t("pps_cb_qp_offset", "") int8_t("pps_cr_qp_offset", "") uint8_t("num_tile_columns_minus1", "") uint8_t("num_tile_rows_minus1", "") uint16_t("column_width_minus1", "")["STD_VIDEO_H265_CHROMA_QP_OFFSET_TILE_COLS_LIST_SIZE"] uint16_t("row_height_minus1", "")["STD_VIDEO_H265_CHROMA_QP_OFFSET_TILE_ROWS_LIST_SIZE"] int8_t("pps_beta_offset_div2", "") int8_t("pps_tc_offset_div2", "") uint8_t("log2_parallel_merge_level_minus2", "") StdVideoH265ScalingLists.const.p("pScalingLists", "must be a valid pointer if {@code pps_scaling_list_data_present_flag} is set") uint8_t("log2_max_transform_skip_block_size_minus2", "extension PPS, valid when #VIDEO_H265_PROFILE_IDC_FORMAT_RANGE_EXTENSIONS is set") uint8_t("diff_cu_chroma_qp_offset_depth", "") uint8_t("chroma_qp_offset_list_len_minus1", "") int8_t("cb_qp_offset_list", "")["STD_VIDEO_H265_CHROMA_QP_OFFSET_LIST_SIZE"] int8_t("cr_qp_offset_list", "")["STD_VIDEO_H265_CHROMA_QP_OFFSET_LIST_SIZE"] uint8_t("log2_sao_offset_scale_luma", "") uint8_t("log2_sao_offset_scale_chroma", "") int8_t("pps_act_y_qp_offset_plus5", "extension PPS, valid when std_video_h265_profile_idc_scc_extensions is set") int8_t("pps_act_cb_qp_offset_plus5", "") int8_t("pps_act_cr_qp_offset_plus5", "") uint8_t("pps_num_palette_predictor_initializer", "") uint8_t("luma_bit_depth_entry_minus8", "") uint8_t("chroma_bit_depth_entry_minus8", "") StdVideoH265PredictorPaletteEntries.const.p("pPredictorPaletteEntries", "must be a valid pointer if pps_palette_predictor_initializer_present_flag is set") } // vulkan_video_codec_h265std_decode.h val StdVideoDecodeH265PictureInfoFlags = struct(Module.VULKAN, "StdVideoDecodeH265PictureInfoFlags") { subpackage = "video" uint32_tb("IrapPicFlag", "", bits = 1) uint32_tb("IdrPicFlag", "", bits = 1) uint32_tb("IsReference", "", bits = 1) uint32_tb("short_term_ref_pic_set_sps_flag", "", bits = 1) } val StdVideoDecodeH265PictureInfo = struct(Module.VULKAN, "StdVideoDecodeH265PictureInfo") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") StdVideoDecodeH265PictureInfoFlags("flags", "") uint8_t("sps_seq_parameter_set_id", "") uint8_t("pps_pic_parameter_set_id", "") uint8_t("num_short_term_ref_pic_sets", "") int32_t("PicOrderCntVal", "") uint16_t("NumBitsForSTRefPicSetInSlice", "number of bits used in st_ref_pic_set() when short_term_ref_pic_set_sps_flag is 0; otherwise set to 0") uint8_t("NumDeltaPocsOfRefRpsIdx", "numDeltaPocs[ RefRpsIdx ] when short_term_ref_pic_set_sps_flag = 1, otherwise 0") uint8_t( "RefPicSetStCurrBefore", "slotIndex as used in VkVideoReferenceSlotKHR structures representing pReferenceSlots in VkVideoDecodeInfoKHR, 0xff for invalid slotIndex" )["STD_VIDEO_DECODE_H265_REF_PIC_SET_LIST_SIZE"] uint8_t( "RefPicSetStCurrAfter", "slotIndex as used in VkVideoReferenceSlotKHR structures representing pReferenceSlots in VkVideoDecodeInfoKHR, 0xff for invalid slotIndex" )["STD_VIDEO_DECODE_H265_REF_PIC_SET_LIST_SIZE"] uint8_t( "RefPicSetLtCurr", "slotIndex as used in VkVideoReferenceSlotKHR structures representing pReferenceSlots in VkVideoDecodeInfoKHR, 0xff for invalid slotIndex" )["STD_VIDEO_DECODE_H265_REF_PIC_SET_LIST_SIZE"] } val StdVideoDecodeH265ReferenceInfoFlags = struct(Module.VULKAN, "StdVideoDecodeH265ReferenceInfoFlags") { subpackage = "video" uint32_tb("used_for_long_term_reference", "", bits = 1) uint32_tb("unused_for_reference", "", bits = 1); uint32_tb("is_non_existing", "", bits = 1) } val StdVideoDecodeH265ReferenceInfo = struct(Module.VULKAN, "StdVideoDecodeH265ReferenceInfo") { subpackage = "video" StdVideoDecodeH265ReferenceInfoFlags("flags", "") int32_t("PicOrderCntVal", "") } // vulkan_video_code_h265std_encode val StdVideoEncodeH265WeightTableFlags = struct(Module.VULKAN, "StdVideoEncodeH265WeightTableFlags") { subpackage = "video" uint16_t("luma_weight_l0_flag", "") uint16_t("chroma_weight_l0_flag", "") uint16_t("luma_weight_l1_flag", "") uint16_t("chroma_weight_l1_flag", "") } val StdVideoEncodeH265WeightTable = struct(Module.VULKAN, "StdVideoEncodeH265WeightTable") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") StdVideoEncodeH265WeightTableFlags("flags", "") uint8_t("luma_log2_weight_denom", "") int8_t("delta_chroma_log2_weight_denom", "") int8_t("delta_luma_weight_l0", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"] int8_t("luma_offset_l0", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"] int8_t("delta_chroma_weight_l0", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"]["STD_VIDEO_H265_MAX_CHROMA_PLANES"] int8_t("delta_chroma_offset_l0", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"]["STD_VIDEO_H265_MAX_CHROMA_PLANES"] int8_t("delta_luma_weight_l1", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"] int8_t("luma_offset_l1", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"] int8_t("delta_chroma_weight_l1", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"]["STD_VIDEO_H265_MAX_CHROMA_PLANES"] int8_t("delta_chroma_offset_l1", "")["STD_VIDEO_H265_MAX_NUM_LIST_REF"]["STD_VIDEO_H265_MAX_CHROMA_PLANES"] } val StdVideoEncodeH265SliceSegmentHeaderFlags = struct(Module.VULKAN, "StdVideoEncodeH265SliceSegmentHeaderFlags") { subpackage = "video" uint32_tb("first_slice_segment_in_pic_flag", "", bits = 1) uint32_tb("no_output_of_prior_pics_flag", "", bits = 1) uint32_tb("dependent_slice_segment_flag", "", bits = 1) uint32_tb("pic_output_flag", "", bits = 1) uint32_tb("short_term_ref_pic_set_sps_flag", "", bits = 1) uint32_tb("slice_temporal_mvp_enable_flag", "", bits = 1) uint32_tb("slice_sao_luma_flag", "", bits = 1) uint32_tb("slice_sao_chroma_flag", "", bits = 1) uint32_tb("num_ref_idx_active_override_flag", "", bits = 1) uint32_tb("mvd_l1_zero_flag", "", bits = 1) uint32_tb("cabac_init_flag", "", bits = 1) uint32_tb("slice_deblocking_filter_disable_flag", "", bits = 1) uint32_tb("collocated_from_l0_flag", "", bits = 1) uint32_tb("slice_loop_filter_across_slices_enabled_flag", "", bits = 1) } val StdVideoEncodeH265SliceSegmentHeader = struct(Module.VULKAN, "StdVideoEncodeH265SliceSegmentHeader") { subpackage = "video" javaImport("static org.lwjgl.vulkan.video.STDVulkanVideoCodecH265.*") StdVideoEncodeH265SliceSegmentHeaderFlags("flags", "") StdVideoH265SliceType("slice_type", "") uint8_t("num_short_term_ref_pic_sets", "") uint32_t("slice_segment_address", "") uint8_t("short_term_ref_pic_set_idx", "") uint8_t("num_long_term_sps", "") uint8_t("num_long_term_pics", "") uint8_t("collocated_ref_idx", "") uint8_t("num_ref_idx_l0_active_minus1", "[0, 14]") uint8_t("num_ref_idx_l1_active_minus1", "[0, 14]") uint8_t("MaxNumMergeCand", "") int8_t("slice_cb_qp_offset", "[-12, 12]") int8_t("slice_cr_qp_offset", "[-12, 12]") int8_t("slice_beta_offset_div2", "[-6, 6]") int8_t("slice_tc_offset_div2", "[-6, 6]") int8_t("slice_act_y_qp_offset", "") int8_t("slice_act_cb_qp_offset", "") int8_t("slice_act_cr_qp_offset", "") StdVideoEncodeH265WeightTable.const.p("pWeightTable", "") } val StdVideoEncodeH265ReferenceModificationFlags = struct(Module.VULKAN, "StdVideoEncodeH265ReferenceModificationFlags") { subpackage = "video" uint32_tb("ref_pic_list_modification_flag_l0", "", bits = 1) uint32_tb("ref_pic_list_modification_flag_l1", "", bits = 1) } val StdVideoEncodeH265ReferenceModifications = struct(Module.VULKAN, "StdVideoEncodeH265ReferenceModifications") { subpackage = "video" StdVideoEncodeH265ReferenceModificationFlags("flags", "") AutoSize("pReferenceList0Modifications")..uint8_t("referenceList0ModificationsCount", "num_ref_idx_l0_active_minus1") uint8_t.const.p("pReferenceList0Modifications", "list_entry_l0") AutoSize("pReferenceList1Modifications")..uint8_t("referenceList1ModificationsCount", "num_ref_idx_l1_active_minus1") uint8_t.const.p("pReferenceList1Modifications", "list_entry_l1") } val StdVideoEncodeH265PictureInfoFlags = struct(Module.VULKAN, "StdVideoEncodeH265PictureInfoFlags") { subpackage = "video" uint32_tb("is_reference_flag", "", bits = 1) uint32_tb("IrapPicFlag", "", bits = 1) uint32_tb("long_term_flag", "", bits = 1) uint32_tb("discardable_flag", "", bits = 1) uint32_tb("cross_layer_bla_flag", "", bits = 1) } val StdVideoEncodeH265PictureInfo = struct(Module.VULKAN, "StdVideoEncodeH265PictureInfo") { subpackage = "video" StdVideoEncodeH265PictureInfoFlags("flags", "") StdVideoH265PictureType("PictureType", "") uint8_t("sps_video_parameter_set_id", "") uint8_t("pps_seq_parameter_set_id", "") uint8_t("pps_pic_parameter_set_id", "") int32_t("PicOrderCntVal", "") uint8_t("TemporalId", "") } val StdVideoEncodeH265ReferenceInfoFlags = struct(Module.VULKAN, "StdVideoEncodeH265ReferenceInfoFlags") { subpackage = "video" uint32_tb("used_for_long_term_reference", "", bits = 1) uint32_tb("unused_for_reference", "", bits = 1) } val StdVideoEncodeH265ReferenceInfo = struct(Module.VULKAN, "StdVideoEncodeH265ReferenceInfo") { subpackage = "video" StdVideoEncodeH265ReferenceInfoFlags("flags", "") int32_t("PicOrderCntVal", "") uint8_t("TemporalId", "") }
bsd-3-clause
d483180a46a9025822c099f2198f22ee
46.641824
161
0.6841
3.035006
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/basic/PointCloudExample.kt
2
2341
package graphics.scenery.tests.examples.basic import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.numerics.Random import graphics.scenery.primitives.PointCloud import graphics.scenery.attribute.material.Material /** * Simple example to demonstrate the drawing of a 3D point cloud. * * This example will draw a point cloud while 3 lights * circle around the scene. * * @author Kyle Harrington <[email protected]> */ class PointCloudExample : SceneryBase("PointCloudExample") { override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) renderer?.pushMode = true val hull = Box(Vector3f(20.0f, 20.0f, 20.0f), insideNormals = true) hull.material { diffuse = Vector3f(0.2f, 0.2f, 0.2f) cullingMode = Material.CullingMode.Front } scene.addChild(hull) val lights = Light.createLightTetrahedron<PointLight>(spread = 5.0f, radius = 15.0f) lights.forEach { light -> light.emissionColor = Random.random3DVectorFromRange(0.2f, 0.8f) light.intensity = 0.5f scene.addChild(light) } val cam: Camera = DetachedHeadCamera() cam.spatial { position = Vector3f(0.0f, 0.0f, 5.0f) } cam.perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(cam) val pointCloud = PointCloud() with(pointCloud) { readFromOBJ( TexturedCubeExample::class.java.getResource("models/sphere.obj").file, importMaterials = false) name = "Sphere Mesh" pointCloud.geometry { for(i in 0 until texcoords.limit()) { texcoords.put(i, Random.randomFromRange(10.0f, 25.0f)) } for(i in 0 until normals.limit()) { normals.put(i, Random.randomFromRange(0.2f, 0.8f)) } } setupPointCloud() scene.addChild(this) } } override fun inputSetup() { setupCameraModeSwitching(keybinding = "C") } companion object { @JvmStatic fun main(args: Array<String>) { PointCloudExample().main() } } }
lgpl-3.0
02617567195d2b3a24394ad0e662d33b
29.802632
120
0.614267
4.078397
false
false
false
false
Apolline-Lille/apolline-android
app/src/main/java/science/apolline/view/fragment/ViewPagerFragment.kt
1
5882
package science.apolline.view.fragment import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.salomonbrys.kodein.instance import kotlinx.android.synthetic.main.fragment_viewpager.* import org.jetbrains.anko.AnkoLogger import science.apolline.R import science.apolline.root.FragmentLifecycle import science.apolline.root.RootFragment import android.support.v4.view.ViewPager.OnPageChangeListener import org.jetbrains.anko.info import science.apolline.service.sensor.IOIOService import android.bluetooth.BluetoothAdapter import android.content.BroadcastReceiver import android.content.IntentFilter import com.github.mikephil.charting.jobs.MoveViewJob import science.apolline.utils.CheckUtility /** * Created by sparow on 2/27/2018. */ class ViewPagerFragment : RootFragment(), AnkoLogger { private val mFragmentIOIO by instance<IOIOFragment>() private val mFragmentChart by instance<ChartFragment>() private val mFragmentMaps by instance<MapFragment>() private lateinit var mAdapter: Adapter private var mServiceStatus: Boolean = false public lateinit var sensor_name : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED) activity!!.registerReceiver(mReceiver, filter) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_viewpager, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.sensor_name = arguments!!.getString("sensor_name") mAdapter = Adapter(childFragmentManager) setupViewPager(pager) tabs.setupWithViewPager(pager) pager.addOnPageChangeListener(pageChangeListener) pager.offscreenPageLimit = 3 pager.setOnTouchListener { _, _ -> true } } private val pageChangeListener = object : OnPageChangeListener { internal var currentPosition = 0 override fun onPageSelected(newPosition: Int) { val fragmentToShow = mAdapter.getItem(newPosition) as FragmentLifecycle fragmentToShow.onResumeFragment() val fragmentToHide = mAdapter.getItem(currentPosition) as FragmentLifecycle fragmentToHide.onPauseFragment() currentPosition = newPosition } override fun onPageScrolled(arg0: Int, arg1: Float, arg2: Int) {} override fun onPageScrollStateChanged(arg0: Int) {} } private fun setupViewPager(pager: ViewPager?) { val f1 = mFragmentIOIO mAdapter.addFragment(f1, "SENSOR") val f2 = mFragmentChart mAdapter.addFragment(f2, "CHART") val f3 = mFragmentMaps mAdapter.addFragment(f3, "MAP") pager?.adapter = mAdapter } private class Adapter(manager: FragmentManager) : FragmentPagerAdapter(manager) { val fragments = ArrayList<Fragment>() val titles = ArrayList<String>() override fun getItem(position: Int): Fragment = fragments[position] override fun getCount(): Int = fragments.size override fun getPageTitle(position: Int): CharSequence? = titles[position] fun addFragment(fragment: Fragment, title: String) { fragments.add(fragment) titles.add(title) } } override fun onStop() { MoveViewJob.getInstance(null, 0f, 0f, null, null) super.onStop() } override fun onDestroyView() { MoveViewJob.getInstance(null, 0f, 0f, null, null) super.onDestroyView() activity!!.unregisterReceiver(mReceiver) info("ViewPager onDestroyView") } override fun onDestroy() { MoveViewJob.getInstance(null, 0f, 0f, null, null) super.onDestroy() info("ViewPager onDestroyView") } override fun onAttach(context: Context?) { super.onAttach(context) if(CheckUtility.checkReandPhoneStatePermission(activity!!.applicationContext)){ activity!!.startService(Intent(activity, IOIOService::class.java)) } } private val mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action if (action == BluetoothAdapter.ACTION_STATE_CHANGED) { val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) when (state) { BluetoothAdapter.STATE_OFF -> { info("Bluetooth off") activity!!.stopService(Intent(activity, IOIOService::class.java)) } BluetoothAdapter.STATE_TURNING_OFF -> info("Turning Bluetooth off...") BluetoothAdapter.STATE_ON -> { info("Bluetooth on") if(CheckUtility.checkReandPhoneStatePermission(activity!!.applicationContext)){ activity!!.startService(Intent(activity, IOIOService::class.java)) } } BluetoothAdapter.STATE_TURNING_ON -> info("Turning Bluetooth on...") } } } } companion object { fun getServiceStatus(): Boolean { return IOIOService.getServiceStatus() } } }
gpl-3.0
77ca1598c0e61de1b31d9fd4b8e04c98
30.967391
116
0.66746
4.967905
false
false
false
false
google/ground-android
ground/src/androidTest/java/com/google/android/ground/DataBindingIdlingResource.kt
1
3777
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground import android.R import android.view.View import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.FragmentActivity import androidx.test.core.app.ActivityScenario import androidx.test.espresso.IdlingResource import java.util.* /** * Used to make Espresso work with DataBinding. Without it the tests will be flaky because * DataBinding uses Choreographer class to synchronize its view updates hence using this to monitor * a launched fragment in fragment scenario will make Espresso wait before doing additional checks */ class DataBindingIdlingResource : IdlingResource { // Holds whether isIdle was called and the result was false. We track this to avoid calling // onTransitionToIdle callbacks if Espresso never thought we were idle in the first place. private var wasNotIdle = false private var activity: FragmentActivity? = null override fun getName(): String = String.format("DataBinding $ID") override fun isIdleNow(): Boolean { var idle = false for (b in bindings) { if (b == null) { continue } if (!b.hasPendingBindings()) { idle = true break } } if (idle) { if (wasNotIdle) { // Notify observers to avoid Espresso race detector. for (cb in IDLING_CALLBACKS) { cb.onTransitionToIdle() } } wasNotIdle = false } else { wasNotIdle = true // Check next frame. if (activity != null) { activity!!.findViewById<View>(R.id.content).postDelayed({ this.isIdleNow }, 16) } } return idle } override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) { IDLING_CALLBACKS.add(callback) } /** Sets the activity from an [ActivityScenario] to be used from [DataBindingIdlingResource]. */ fun <T : FragmentActivity?> monitorActivity(activityScenario: ActivityScenario<T>) { activityScenario.onActivity { activity: T -> this.activity = activity } } private fun getBinding(view: View?): ViewDataBinding? { return DataBindingUtil.getBinding(view!!) } private val bindings: List<ViewDataBinding?> get() { val fragments = activity?.supportFragmentManager?.fragments ?: emptyList() val bindings: MutableList<ViewDataBinding?> = ArrayList() for (f in fragments) { val fv: View = f.view ?: continue bindings.add(getBinding(fv)) for (cf in f.childFragmentManager.fragments) { val cfv: View = cf.view ?: continue bindings.add(getBinding(cfv)) for (cf2 in cf.childFragmentManager.fragments) { val cf2v: View = cf2.view ?: continue bindings.add(getBinding(cf2v)) } } } return bindings } companion object { // Give it a unique id to work around an Espresso bug where you cannot register/unregister // an idling resource with the same name. private val ID = UUID.randomUUID().toString() // List of registered callbacks private val IDLING_CALLBACKS: MutableList<IdlingResource.ResourceCallback> = ArrayList() } }
apache-2.0
fe6139d3999a89f566fabdddb3458658
33.651376
99
0.693672
4.606098
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceAssociateFunctionInspection.kt
2
10878
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.getLastLambdaExpression import org.jetbrains.kotlin.idea.inspections.AssociateFunction.* import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType 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.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceAssociateFunctionInspection : AbstractKotlinInspection() { companion object { private val associateFunctionNames = listOf("associate", "associateTo") private val associateFqNames = listOf(FqName("kotlin.collections.associate"), FqName("kotlin.sequences.associate")) private val associateToFqNames = listOf(FqName("kotlin.collections.associateTo"), FqName("kotlin.sequences.associateTo")) fun getAssociateFunctionAndProblemHighlightType( dotQualifiedExpression: KtDotQualifiedExpression, context: BindingContext = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) ): Pair<AssociateFunction, ProblemHighlightType>? { val callExpression = dotQualifiedExpression.callExpression ?: return null val lambda = callExpression.lambda() ?: return null if (lambda.valueParameters.size > 1) return null val functionLiteral = lambda.functionLiteral if (functionLiteral.anyDescendantOfType<KtReturnExpression> { it.labelQualifier != null }) return null val lastStatement = functionLiteral.lastStatement() ?: return null val (keySelector, valueTransform) = lastStatement.pair(context) ?: return null val lambdaParameter = context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() ?: return null return when { keySelector.isReferenceTo(lambdaParameter, context) -> { val receiver = dotQualifiedExpression.receiverExpression.getResolvedCall(context)?.resultingDescriptor?.returnType ?: return null if ((KotlinBuiltIns.isArray(receiver) || KotlinBuiltIns.isPrimitiveArray(receiver)) && dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_4 ) return null ASSOCIATE_WITH to GENERIC_ERROR_OR_WARNING } valueTransform.isReferenceTo(lambdaParameter, context) -> ASSOCIATE_BY to GENERIC_ERROR_OR_WARNING else -> { if (functionLiteral.bodyExpression?.statements?.size != 1) return null ASSOCIATE_BY_KEY_AND_VALUE to INFORMATION } } } private fun KtExpression.isReferenceTo(descriptor: ValueParameterDescriptor, context: BindingContext): Boolean { return (this as? KtNameReferenceExpression)?.getResolvedCall(context)?.resultingDescriptor == descriptor } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = dotQualifiedExpressionVisitor(fun(dotQualifiedExpression) { if (dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return val callExpression = dotQualifiedExpression.callExpression ?: return val calleeExpression = callExpression.calleeExpression ?: return if (calleeExpression.text !in associateFunctionNames) return val context = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) val fqName = callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe ?: return val isAssociate = fqName in associateFqNames val isAssociateTo = fqName in associateToFqNames if (!isAssociate && !isAssociateTo) return val (associateFunction, highlightType) = getAssociateFunctionAndProblemHighlightType(dotQualifiedExpression, context) ?: return holder.registerProblemWithoutOfflineInformation( calleeExpression, KotlinBundle.message("replace.0.with.1", calleeExpression.text, associateFunction.name(isAssociateTo)), isOnTheFly, highlightType, ReplaceAssociateFunctionFix(associateFunction, isAssociateTo) ) }) } class ReplaceAssociateFunctionFix(private val function: AssociateFunction, private val hasDestination: Boolean) : LocalQuickFix { private val functionName = function.name(hasDestination) override fun getName() = KotlinBundle.message("replace.with.0", functionName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val dotQualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtDotQualifiedExpression>() ?: return val receiverExpression = dotQualifiedExpression.receiverExpression val callExpression = dotQualifiedExpression.callExpression ?: return val lambda = callExpression.lambda() ?: return val lastStatement = lambda.functionLiteral.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return val psiFactory = KtPsiFactory(dotQualifiedExpression) if (function == ASSOCIATE_BY_KEY_AND_VALUE) { val destination = if (hasDestination) { callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return } else { null } val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) appendFixedText("(") if (destination != null) { appendExpression(destination) appendFixedText(",") } appendLambda(lambda, keySelector) appendFixedText(",") appendLambda(lambda, valueTransform) appendFixedText(")") } dotQualifiedExpression.replace(newExpression) } else { lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) val valueArgumentList = callExpression.valueArgumentList if (valueArgumentList != null) { appendValueArgumentList(valueArgumentList) } if (callExpression.lambdaArguments.isNotEmpty()) { appendLambda(lambda) } } dotQualifiedExpression.replace(newExpression) } } private fun BuilderByPattern<KtExpression>.appendLambda(lambda: KtLambdaExpression, body: KtExpression? = null) { appendFixedText("{") lambda.valueParameters.firstOrNull()?.nameAsName?.also { appendName(it) appendFixedText("->") } if (body != null) { appendExpression(body) } else { lambda.bodyExpression?.allChildren?.let(this::appendChildRange) } appendFixedText("}") } private fun BuilderByPattern<KtExpression>.appendValueArgumentList(valueArgumentList: KtValueArgumentList) { appendFixedText("(") valueArgumentList.arguments.forEachIndexed { index, argument -> if (index > 0) appendFixedText(",") appendExpression(argument.getArgumentExpression()) } appendFixedText(")") } companion object { fun replaceLastStatementForAssociateFunction(callExpression: KtCallExpression, function: AssociateFunction) { val lastStatement = callExpression.lambda()?.functionLiteral?.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) } } } enum class AssociateFunction(val functionName: String) { ASSOCIATE_WITH("associateWith"), ASSOCIATE_BY("associateBy"), ASSOCIATE_BY_KEY_AND_VALUE("associateBy"); fun name(hasDestination: Boolean): String { return if (hasDestination) "${functionName}To" else functionName } } private fun KtCallExpression.lambda(): KtLambdaExpression? { return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression() } private fun KtFunctionLiteral.lastStatement(): KtExpression? { return bodyExpression?.statements?.lastOrNull() } private fun KtExpression.pair(context: BindingContext = analyze(BodyResolveMode.PARTIAL)): Pair<KtExpression, KtExpression>? { return when (this) { is KtBinaryExpression -> { if (operationReference.text != "to") return null val left = left ?: return null val right = right ?: return null left to right } is KtCallExpression -> { if (calleeExpression?.text != "Pair") return null if (valueArguments.size != 2) return null if (getResolvedCall(context)?.resultingDescriptor?.containingDeclaration?.fqNameSafe != FqName("kotlin.Pair")) return null val first = valueArguments[0]?.getArgumentExpression() ?: return null val second = valueArguments[1]?.getArgumentExpression() ?: return null first to second } else -> return null } }
apache-2.0
a5ca6cebb7c08d48d562cbecc27c5a7f
48.90367
158
0.693326
6.013267
false
false
false
false
flesire/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/BuildFilterServiceImpl.kt
1
14104
package net.nemerosa.ontrack.service import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.buildfilter.* import net.nemerosa.ontrack.model.exceptions.BuildFilterNotFoundException import net.nemerosa.ontrack.model.exceptions.BuildFilterNotLoggedException import net.nemerosa.ontrack.model.security.BranchFilterMgt import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.StandardBuildFilterData import net.nemerosa.ontrack.model.structure.StructureService import net.nemerosa.ontrack.repository.BuildFilterRepository import net.nemerosa.ontrack.repository.TBuildFilter import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDate import java.util.* @Service @Transactional class BuildFilterServiceImpl( buildFilterProviders: Collection<BuildFilterProvider<*>>, private val buildFilterRepository: BuildFilterRepository, private val structureService: StructureService, private val securityService: SecurityService ) : BuildFilterService { private val buildFilterProviders: Map<String, BuildFilterProvider<*>> = buildFilterProviders .associateBy { it.type } override fun defaultFilterProviderData(): BuildFilterProviderData<*> { return standardFilterProviderData(10).build() } override fun lastPromotedBuildsFilterData(): BuildFilterProviderData<*> { return getBuildFilterProviderByType<Any>(PromotionLevelBuildFilterProvider::class.java.name) ?.withData(null) ?: throw BuildFilterProviderNotFoundException(PromotionLevelBuildFilterProvider::class.java.name) } inner class DefaultStandardFilterProviderDataBuilder(count: Int) : StandardFilterProviderDataBuilder { private var data: StandardBuildFilterData = StandardBuildFilterData.of(count) override fun build(): BuildFilterProviderData<*> { val provider = getBuildFilterProviderByType<Any>(StandardBuildFilterProvider::class.java.name) ?: throw BuildFilterProviderNotFoundException(StandardBuildFilterProvider::class.java.name) @Suppress("UNCHECKED_CAST") return (provider as BuildFilterProvider<StandardBuildFilterData>).withData(data) } override fun withSincePromotionLevel(sincePromotionLevel: String): StandardFilterProviderDataBuilder { data = data.withSincePromotionLevel(sincePromotionLevel) return this } override fun withWithPromotionLevel(withPromotionLevel: String): StandardFilterProviderDataBuilder { data = data.withWithPromotionLevel(withPromotionLevel) return this } override fun withAfterDate(afterDate: LocalDate): StandardFilterProviderDataBuilder { data = data.withAfterDate(afterDate) return this } override fun withBeforeDate(beforeDate: LocalDate): StandardFilterProviderDataBuilder { data = data.withBeforeDate(beforeDate) return this } override fun withSinceValidationStamp(sinceValidationStamp: String): StandardFilterProviderDataBuilder { data = data.withSinceValidationStamp(sinceValidationStamp) return this } override fun withSinceValidationStampStatus(sinceValidationStampStatus: String): StandardFilterProviderDataBuilder { data = data.withSinceValidationStampStatus(sinceValidationStampStatus) return this } override fun withWithValidationStamp(withValidationStamp: String): StandardFilterProviderDataBuilder { data = data.withWithValidationStamp(withValidationStamp) return this } override fun withWithValidationStampStatus(withValidationStampStatus: String): StandardFilterProviderDataBuilder { data = data.withWithValidationStampStatus(withValidationStampStatus) return this } override fun withWithProperty(withProperty: String): StandardFilterProviderDataBuilder { data = data.withWithProperty(withProperty) return this } override fun withWithPropertyValue(withPropertyValue: String): StandardFilterProviderDataBuilder { data = data.withWithPropertyValue(withPropertyValue) return this } override fun withSinceProperty(sinceProperty: String): StandardFilterProviderDataBuilder { data = data.withSinceProperty(sinceProperty) return this } override fun withSincePropertyValue(sincePropertyValue: String): StandardFilterProviderDataBuilder { data = data.withSincePropertyValue(sincePropertyValue) return this } override fun withLinkedFrom(linkedFrom: String): StandardFilterProviderDataBuilder { data = data.withLinkedFrom(linkedFrom) return this } override fun withLinkedFromPromotion(linkedFromPromotion: String): StandardFilterProviderDataBuilder { data = data.withLinkedFromPromotion(linkedFromPromotion) return this } override fun withLinkedTo(linkedTo: String): StandardFilterProviderDataBuilder { data = data.withLinkedTo(linkedTo) return this } override fun withLinkedToPromotion(linkedToPromotion: String): StandardFilterProviderDataBuilder { data = data.withLinkedToPromotion(linkedToPromotion) return this } } override fun standardFilterProviderData(count: Int): StandardFilterProviderDataBuilder { return DefaultStandardFilterProviderDataBuilder(count) } override fun standardFilterProviderData(node: JsonNode): BuildFilterProviderData<*> { return getBuildFilterProviderData<Any>( StandardBuildFilterProvider::class.java.name, node ) } override fun getBuildFilters(branchId: ID): Collection<BuildFilterResource<*>> { val branch = structureService.getBranch(branchId) // Are we logged? val account = securityService.currentAccount return if (account != null) { // Gets the filters for this account and the branch buildFilterRepository.findForBranch(OptionalInt.of(account.id()), branchId.value) .mapNotNull { t -> loadBuildFilterResource<Any>(branch, t) } } // Not logged, no filter else { // Gets the filters for the branch buildFilterRepository.findForBranch(OptionalInt.empty(), branchId.get()) .mapNotNull { t -> loadBuildFilterResource<Any>(branch, t) } } } override fun getBuildFilterForms(branchId: ID): Collection<BuildFilterForm> { return buildFilterProviders.values .map { provider -> provider.newFilterForm(branchId) } } override fun <T> getBuildFilterProviderData(filterType: String, parameters: JsonNode): BuildFilterProviderData<T> { val buildFilterProvider = getBuildFilterProviderByType<T>(filterType) return buildFilterProvider ?.let { getBuildFilterProviderData(it, parameters) } ?: throw BuildFilterProviderNotFoundException(filterType) } override fun <T> getBuildFilterProviderData(filterType: String, parameters: T): BuildFilterProviderData<T> { val buildFilterProvider = getBuildFilterProviderByType<T>(filterType) return buildFilterProvider?.withData(parameters) ?: throw BuildFilterProviderNotFoundException(filterType) } override fun validateBuildFilterProviderData(branch: Branch, filterType: String, parameters: JsonNode): String? { val buildFilterProvider: BuildFilterProvider<*>? = getBuildFilterProviderByType<Any>(filterType) return if (buildFilterProvider != null) { validateBuildFilterProviderData(branch, buildFilterProvider, parameters) } else { BuildFilterProviderNotFoundException(filterType).message } } private fun <T> validateBuildFilterProviderData( branch: Branch, buildFilterProvider: BuildFilterProvider<T>, parameters: JsonNode ): String? { // Parsing val data: T = try { buildFilterProvider.parse(parameters).orElse(null) } catch (ex: Exception) { return "Cannot parse build filter data: ${ex.message}" } // Validation return buildFilterProvider.validateData(branch, data) } protected fun <T> getBuildFilterProviderData(provider: BuildFilterProvider<T>, parameters: JsonNode): BuildFilterProviderData<T> { val data = provider.parse(parameters) return if (data.isPresent) { BuildFilterProviderData.of(provider, data.get()) } else { throw BuildFilterProviderDataParsingException(provider.javaClass.name) } } @Throws(BuildFilterNotFoundException::class) override fun getEditionForm(branchId: ID, name: String): BuildFilterForm { return securityService.account .flatMap { account -> buildFilterRepository.findByBranchAndName(account.id(), branchId.value, name) } .orElse(null) ?.let { this.getBuildFilterForm<Any>(it) } ?: throw BuildFilterNotLoggedException() } private fun <T> getBuildFilterForm(t: TBuildFilter): BuildFilterForm? { val provider = getBuildFilterProviderByType<T>(t.type) return provider ?.parse(t.data) ?.map { data -> provider.getFilterForm( ID.of(t.branchId), data ) } ?.orElse(null) } override fun saveFilter(branchId: ID, shared: Boolean, name: String, type: String, parameters: JsonNode): Ack { // Checks the account if (shared) { val account = securityService.currentAccount // Gets the branch val branch = structureService.getBranch(branchId) // Checks access rights securityService.checkProjectFunction(branch, BranchFilterMgt::class.java) // Deletes any previous filter val currentAccountId = account.id() buildFilterRepository.findByBranchAndName(currentAccountId, branchId.get(), name).ifPresent { buildFilterRepository.delete(currentAccountId, branchId.get(), name, true) } // No account to be used return doSaveFilter(OptionalInt.empty(), branchId, name, type, parameters) } else { val account = securityService.currentAccount return if (account == null) { Ack.NOK } else { // Saves it for this account doSaveFilter(OptionalInt.of(account.id()), branchId, name, type, parameters) } } } private fun doSaveFilter(accountId: OptionalInt, branchId: ID, name: String, type: String, parameters: JsonNode): Ack { // Checks the provider val provider = getBuildFilterProviderByType<Any>(type) return if (provider == null) { Ack.NOK } // Excludes predefined filters else if (provider.isPredefined) { Ack.NOK } // Checks the data else if (!provider.parse(parameters).isPresent) { Ack.NOK } else { // Saving buildFilterRepository.save(accountId, branchId.value, name, type, parameters) } } override fun deleteFilter(branchId: ID, name: String): Ack { // Gets the branch val branch = structureService.getBranch(branchId) // If user is allowed to manage shared filters, this filter might have to be deleted from the shared filters // as well val sharedFilter = securityService.isProjectFunctionGranted(branch, BranchFilterMgt::class.java) // Deleting the filter return buildFilterRepository.delete(securityService.currentAccount.id(), branchId.get(), name, sharedFilter) } override fun copyToBranch(sourceBranchId: ID, targetBranchId: ID) { // Gets all the filters for the source branch buildFilterRepository.findForBranch(sourceBranchId.value).forEach { filter -> buildFilterRepository.save( filter.accountId, targetBranchId.get(), filter.name, filter.type, filter.data ) } } private fun <T> getBuildFilterProviderByType(type: String): BuildFilterProvider<T>? { @Suppress("UNCHECKED_CAST") return buildFilterProviders[type] as BuildFilterProvider<T> } private fun <T> loadBuildFilterResource(branch: Branch, t: TBuildFilter): BuildFilterResource<T>? { return getBuildFilterProviderByType<Any>(t.type) ?.let { @Suppress("UNCHECKED_CAST") loadBuildFilterResource(it as BuildFilterProvider<T>, branch, t.isShared, t.name, t.data) } } private fun <T> loadBuildFilterResource(provider: BuildFilterProvider<T>, branch: Branch, shared: Boolean, name: String, data: JsonNode): BuildFilterResource<T>? { return provider.parse(data) .map { parsedData -> BuildFilterResource( branch, shared, name, provider.type, parsedData, provider.validateData(branch, parsedData) ) }.orElse(null) } }
mit
c28041b5dcd620360a86a5b6acddbb20
41.481928
167
0.661089
5.243123
false
false
false
false
xmartlabs/Android-Base-Project
ui/src/androidTest/java/com/xmartlabs/bigbang/ui/recyclerview/multipleitems/BrandCarAdapter.kt
1
1760
package com.xmartlabs.bigbang.ui.recyclerview.multipleitems import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.MainThread import com.xmartlabs.bigbang.ui.common.recyclerview.BaseRecyclerViewAdapter import com.xmartlabs.bigbang.ui.common.recyclerview.SimpleItemRecycleItemType import com.xmartlabs.bigbang.ui.common.recyclerview.SingleItemBaseViewHolder import com.xmartlabs.bigbang.ui.recyclerview.common.Brand import com.xmartlabs.bigbang.ui.recyclerview.common.Car import com.xmartlabs.bigbang.ui.test.R class BrandCarAdapter : BaseRecyclerViewAdapter() { private val carItemType = object : SimpleItemRecycleItemType<Car, CarViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup) = CarViewHolder(inflateView(parent, R.layout.item_single)) } private val brandItemType = object : SimpleItemRecycleItemType<Brand, BrandViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup) = BrandViewHolder(inflateView(parent, R.layout.item_single)) } @MainThread fun setItems(brands: List<Brand>) { brands .forEach { addItem(brandItemType, it) it.cars.forEach { addItem(carItemType, it) } } notifyDataSetChanged() } class BrandViewHolder(view: View) : SingleItemBaseViewHolder<Brand>(view) { var title: TextView = view.findViewById(android.R.id.title) override fun bindItem(item: Brand) { super.bindItem(item) title.text = item.name } } class CarViewHolder(view: View) : SingleItemBaseViewHolder<Car>(view) { var title: TextView = view.findViewById(android.R.id.title) override fun bindItem(item: Car) { super.bindItem(item) title.text = item.model } } }
apache-2.0
80f193bad809796de85d79dc20efc16d
34.2
115
0.753409
4.131455
false
false
false
false
paplorinc/intellij-community
uast/uast-common/src/org/jetbrains/uast/declarations/UClassInitializer.kt
2
1920
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiClassInitializer import com.intellij.psi.PsiCodeBlock import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A class initializer wrapper to be used in [UastVisitor]. */ interface UClassInitializer : UDeclaration, PsiClassInitializer { override val psi: PsiClassInitializer /** * Returns the body of this class initializer. */ val uastBody: UExpression @Deprecated("Use uastBody instead.", ReplaceWith("uastBody")) override fun getBody(): PsiCodeBlock = psi.body override fun accept(visitor: UastVisitor) { if (visitor.visitInitializer(this)) return annotations.acceptList(visitor) uastBody.accept(visitor) visitor.afterVisitInitializer(this) } override fun asRenderString(): String = buildString { append(modifierList) appendln(uastBody.asRenderString().withMargin) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitClassInitializer(this, data) override fun asLogString(): String = log("isStatic = $isStatic") } interface UClassInitializerEx : UClassInitializer, UDeclarationEx { override val javaPsi: PsiClassInitializer }
apache-2.0
689e9938610ed8b5758d8ae6b096b612
31.016667
75
0.757292
4.454756
false
false
false
false
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/service/SwaggerUtils.kt
1
5012
package com.outbrain.ob1k.crud.service import com.outbrain.ob1k.crud.model.EFieldType import com.outbrain.ob1k.crud.model.EntityDescription import com.outbrain.ob1k.crud.model.EntityField import io.swagger.models.* import io.swagger.models.parameters.BodyParameter import io.swagger.models.parameters.PathParameter import io.swagger.models.parameters.QueryParameter import io.swagger.models.properties.* import io.swagger.models.utils.PropertyModelConverter private val className = CrudDispatcher::class.java.name private val classSimpleName = CrudDispatcher::class.java.simpleName fun com.outbrain.ob1k.crud.model.Model.registerToSwagger(swagger: Swagger, key: String) { val relativePath = key.substringBefore("{resource}") swagger.tag(Tag().name(classSimpleName).description(className)) data.forEach { val list = operation(it.resourceName, "list") .withRangeQueryParam() .withSortQueryParam() .withFilterQueryParam(it) .returningListOf(it) val create = operation(it.resourceName, "create").withBodyParam(it).returning(it) val get = operation(it.resourceName, "get").withIdPathParam().returning(it) val update = operation(it.resourceName, "update").withIdPathParam().withBodyParam(it).returning(it) val delete = operation(it.resourceName, "delete").withIdPathParam().returning200() val resourcePath = "$relativePath${it.resourceName}" if (it.editable) { swagger.path(resourcePath, Path().get(list).post(create)) swagger.path("$resourcePath/{id}", Path().get(get).put(update).delete(delete)) } else { swagger.path(resourcePath, Path().get(list)) swagger.path("$resourcePath/{id}", Path().get(get)) } } } private fun EntityDescription.asProperty() = fields .asSequence() .filter { it.type != EFieldType.REFERENCEMANY } .fold(ObjectProperty()) { obj, entity -> obj.property(entity.name, entity.asProperty()) } private fun Property.toSchema() = PropertyModelConverter().propertyToModel(this) private fun EntityDescription.asResponse() = Response().responseSchema(asProperty().toSchema()) private fun EntityDescription.asListResponse() = Response().responseSchema( ObjectProperty() .property("total", IntegerProperty()) .property("data", ArrayProperty().items(asProperty())) .toSchema()) private fun EntityDescription.asBodyParameter() = BodyParameter().name(resourceName).schema(asProperty().toSchema()) private fun EntityField.asProperty(): Property { return when (type) { EFieldType.NUMBER -> DecimalProperty() EFieldType.DATE -> DateProperty() EFieldType.BOOLEAN -> BooleanProperty() EFieldType.SELECT_BY_IDX, EFieldType.SELECT_BY_STRING -> { val stringProperty = StringProperty() stringProperty._enum(choices) stringProperty } else -> StringProperty() } } private fun Operation.withRangeQueryParam() = parameter(QueryParameter() .name("range") .type("array") .example("[0,9]") .minmax(2) .description("[from,to-inclusive]") .items(IntegerProperty()) .required(false)) private fun Operation.withFilterQueryParam(desc: EntityDescription) = parameter(QueryParameter() .name("filter") .type("string") .description("filter by example of ${desc.resourceName}") .example("{\"id\",\"abc\"}") .required(false)) private fun Operation.withSortQueryParam() = parameter(QueryParameter() .name("sort") .type("array") .description("[sort-by,ASC|DESC]") .example("[\"id\",\"ASC\"]") .items(StringProperty()) .minmax(2) .required(false)) private fun QueryParameter.minmax(n: Int): QueryParameter { minItems = n maxItems = n return this } private fun Operation.withIdPathParam() = parameter(PathParameter().name("id").type("string")) private fun Operation.withBodyParam(desc: EntityDescription) = parameter(desc.asBodyParameter()) private fun Operation.returning200() = responseChain(Response()) private fun Operation.returning(desc: EntityDescription) = responseChain(desc.asResponse()) private fun Operation.returningListOf(desc: EntityDescription) = responseChain(desc.asListResponse() .header("content-range", StringProperty() .example("0-9/150") .description("from-to/total"))) private fun Operation.responseChain(response: Response) = response(200, response) .response(401, Response().description("Unauthorized")) .response(403, Response().description("Forbidden")) .response(404, Response().description("Not Found")) private fun operation(resource: String, type: String) = Operation().summary("$className.$type-$resource").tag(classSimpleName).operationId("$className.$type-$resource")
apache-2.0
73d22f38d60b49705c8204e85cae9bd0
37.852713
120
0.677973
4.427562
false
false
false
false
AlmasB/FXTutorials
src/main/java/com/almasb/tutorialx1/CurveApp.kt
1
20991
package com.almasb.tutorialx1 import javafx.application.Application import javafx.geometry.Point2D import javafx.scene.Parent import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.canvas.GraphicsContext import javafx.scene.layout.Pane import javafx.scene.shape.Circle import javafx.stage.Stage import java.util.* /** * * * @author Almas Baimagambetov ([email protected]) */ class CurveApp : Application() { fun circ(point1: Point2D, point2: Point2D, point3: Point2D): Circle? { val ax = point1.x val ay = point1.y val bx = point2.x val by = point2.y val cx = point3.x val cy = point3.y var x = 0.0 var y = 0.0 //'''find the x,y and radius for the circle through the 3 points''' if (ax*by-ax*cy-cx*by+cy*bx-bx*ay+cx*ay != 0.0 ) { x = .5 * (-pow(ay, 2) * cy + pow(ay, 2) * by - ay * pow(bx, 2) -ay * pow(by, 2) + ay * pow(cy, 2) + ay * pow(cx, 2) - pow(cx, 2) * by + pow(ax, 2) * by + pow(bx, 2) * cy - pow(ax, 2) * cy - pow(cy, 2) * by + cy * pow(by, 2)) / (ax * by - ax * cy - cx * by + cy * bx - bx * ay + cx * ay) y = -.5 * (-pow(ax, 2) * cx + pow(ax, 2) * bx - ax * pow(by, 2) -ax * pow(bx, 2) + ax * pow(cx, 2) + ax * pow(cy, 2) - pow(cy, 2) * bx + pow(ay, 2) * bx + pow(by, 2) * cx -pow(ay, 2) * cx - pow(cx, 2) * bx + cx * pow(bx, 2)) / (ax * by - ax * cy - cx * by + cy * bx - bx * ay + cx * ay) } else { println("Fail") return null } val r = pow(pow(x-ax, 2.0)+pow(y-ay, 2.0), .5) return Circle(x, y, r) } fun findPoint(eq1: Circle, eq2: Circle, point1: Point2D, point2: Point2D): Point2D { //'''find the centroid of the overlapping part of two circles from their equations''' var thetabeg = Math.acos((point1.x-eq1.centerX)/eq1.radius) var thetaend = Math.acos((point2.x-eq1.centerX)/eq1.radius) val mid1x = eq1.radius*Math.cos((thetabeg+thetaend)/2)+eq1.centerX val thetaybeg = Math.asin((point1.y-eq1.centerY)/eq1.radius) val thetayend = Math.asin((point2.y-eq1.centerY)/eq1.radius) val mid1y = eq1.radius*Math.sin((thetaybeg+thetayend)/2)+eq1.centerY val thetabeg2 = Math.acos((point1.x-eq2.centerX)/eq2.radius) val thetaend2 = Math.acos((point2.x-eq2.centerX)/eq2.radius) val mid2x = eq2.radius*Math.cos((thetabeg2+thetaend2)/2)+eq2.centerX val thetaybeg2 = Math.asin((point1.y-eq2.centerY)/eq2.radius) val thetayend2 = Math.asin((point2.y-eq2.centerY)/eq2.radius) val mid2y = eq2.radius*Math.sin((thetaybeg2+thetayend2)/2)+eq2.centerY return Point2D((mid2x+mid1x)/2, (mid2y+mid1y)/2) } fun pow(x: Double, n: Double) = Math.pow(x, n) fun pow(x: Double, n: Int) = pow(x, n.toDouble()) fun p(i: Int, i1: Int): Point2D { return Point2D(i.toDouble(), i1.toDouble()) } fun draw(g: GraphicsContext) { val curve = mutableListOf<Point2D>( p(25,500), p(90,400), p(250,250), p(350,250), //p(300,276), p(362,215), p(400, 400), p(125, 500), p(25, 500) //,[445,122],[551,57],[560,23], [540, 10], [520,20],[500,50],[450,70] ) //bplot(curve, blank) for (j in 0..6 - 1) { val newpoints = ArrayList<Point2D>() for (i in 0..curve.size - 3 - 1) { val eq = circ(curve[i], curve[i + 1], curve[i + 2]) val eq2 = circ(curve[i + 1], curve[i + 2], curve[i + 3]) if (eq == null || eq2 == null) newpoints.add( Point2D((curve[i + 1].x + curve[i + 2].x) / 2, (curve[i+1].y+curve[i+2].y)/2 )) else newpoints.add(findPoint(eq, eq2, curve[i + 1], curve[i + 2])) } for (i in newpoints.indices) { //newpoints[i] = Point2D(Math.r) //point[0] = int(round(point[0])) //point[1] = int(round(point[1])) } for (m in 0..newpoints.size - 1) curve.add(2 * m + 2, newpoints[m]) } for (p in curve) { g.fillOval(p.x, p.y, 1.0, 1.0) } //plot(curve, blank) } fun draw2(g: GraphicsContext) { val points = mutableListOf<Point2D>( p(25,500), p(90,400), p(250,250), p(350,250), //p(300,276), p(362,215), p(400, 400), p(125, 500), p(25, 500) //,[445,122],[551,57],[560,23], [540, 10], [520,20],[500,50],[450,70] ) g.beginPath() // move to the first point g.moveTo(points[0].x, points[0].y); for (i in 1..points.size - 3) { var xc = (points[i].x + points[i + 1].x) / 2; var yc = (points[i].y + points[i + 1].y) / 2; g.quadraticCurveTo(points[i].x, points[i].y, xc, yc); } val i = points.size - 2 // curve through the last two points g.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y); g.closePath() g.stroke() points.forEach { g.fillOval(it.x, it.y, 5.0, 5.0) } } /* pubic static function drawCurve * Draws a single cubic Bézier curve * @param: * g:Graphics -Graphics on which to draw the curve * p1:Point -First point in the curve * p2:Point -Second point (control point) in the curve * p3:Point -Third point (control point) in the curve * p4:Point -Fourth point in the curve * @return: */ fun drawCurve(g:GraphicsContext, p1:Point2D, p2:Point2D, p3:Point2D, p4:Point2D) { // var bezier = new BezierSegment(p1,p2,p3,p4); // BezierSegment using the four points // g.moveTo(p1.x,p1.y); // // Construct the curve out of 100 segments (adjust number for less/more detail) // for (var t=.01;t<1.01;t+=.01){ // var val = bezier.getValue(t); // x,y on the curve for a given t // g.lineTo(val.x,val.y); // } } // FROM http://www.cartogrammar.com/blog/actionscript-curves-update/ /* public static function curveThroughPoints * Draws a smooth curve through a series of points. For a closed curve, make the first and last points the same. * @param: * g:Graphics -Graphics on which to draw the curve * p:Array -Array of Point instances * z:Number -A factor (between 0 and 1) to reduce the size of curves by limiting the distance of control points from anchor points. * For example, z=.5 limits control points to half the distance of the closer adjacent anchor point. * I put the option here, but I recommend sticking with .5 * angleFactor:Number -Adjusts the size of curves depending on how acute the angle between points is. Curves are reduced as acuteness * increases, and this factor controls by how much. * 1 = curves are reduced in direct proportion to acuteness * 0 = curves are not reduced at all based on acuteness * in between = the reduction is basically a percentage of the full reduction * moveTo:Bollean -Specifies whether to move to the first point in the curve rather than continuing drawing * from wherever drawing left off. * @return: */ fun curveThroughPoints(g:GraphicsContext, points:List<Point2D>/*of Points*/, z:Double = .5, angleFactor:Double = .75, moveTo:Boolean = true) { // try { // var p:Array = points.slice(); // Local copy of points array // var duplicates:Array = new Array(); // Array to hold indices of duplicate points // // Check to make sure array contains only Points // for (var i=0; i<p.length; i++){ // if (!(p[i] is Point)){ // throw new Error("Array must contain Point objects"); // } // // Check for the same point twice in a row // if (i > 0){ // if (p[i].x == p[i-1].x && p[i].y == p[i-1].y){ // duplicates.push(i); // add index of duplicate to duplicates array // } // } // } // // Loop through duplicates array and remove points from the points array // for (i=duplicates.length-1; i>=0; i--){ // p.splice(duplicates[i],1); // } // // Make sure z is between 0 and 1 (too messy otherwise) // if (z <= 0){ // z = .5; // } else if (z > 1){ // z = 1; // } // // Make sure angleFactor is between 0 and 1 // if (angleFactor < 0){ // angleFactor = 0; // } else if (angleFactor > 1){ // angleFactor = 1; // } // // // // // First calculate all the curve control points // // // // // None of this junk will do any good if there are only two points // if (p.length > 2){ g.beginPath() // Ordinarily, curve calculations will start with the second point and go through the second-to-last point var firstPt = 1; var lastPt = points.size - 1; // Check if this is a closed line (the first and last points are the same) if (points[0].x == points[points.size-1].x && points[0].y == points[points.size-1].y){ // Include first and last points in curve calculations firstPt = 0 lastPt = points.size } val controlPts = ArrayList<Pair<Point2D, Point2D> >() // An array to store the two control points (of a cubic Bézier curve) for each point for (i in 0..points.size - 1) { controlPts.add(Pair(Point2D.ZERO, Point2D.ZERO)) } // Loop through all the points (except the first and last if not a closed line) to get curve control points for each. for (i in firstPt..lastPt - 1) { // The previous, current, and next points var p0 = if (i-1 < 0) points[points.size-2] else points[i-1]; // If the first point (of a closed line), use the second-to-last point as the previous point var p1 = points[i]; var p2 = if (i+1 == points.size) points[1] else points[i+1]; // If the last point (of a closed line), use the second point as the next point var a = p0.distance(p1) // Distance from previous point to current point if (a < 0.001) a = .001; // Correct for near-zero distances, a cheap way to prevent division by zero var b = p1.distance(p2); // Distance from current point to next point if (b < 0.001) b = .001; var c = p0.distance(p2); // Distance from previous point to next point if (c < 0.001) c = .001; var cos = (b*b+a*a-c*c)/(2*b*a); // Make sure above value is between -1 and 1 so that Math.acos will work if (cos < -1) cos = -1.0; else if (cos > 1) cos = 1.0; var C = Math.acos(cos); // Angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point // Duplicate set of points. Start by giving previous and next points values RELATIVE to the current point. var aPt = Point2D(p0.x-p1.x,p0.y-p1.y); var bPt = Point2D(p1.x,p1.y); var cPt = Point2D(p2.x-p1.x,p2.y-p1.y); /* We'll be adding adding the vectors from the previous and next points to the current point, but we don't want differing magnitudes (i.e. line segment lengths) to affect the direction of the new vector. Therefore we make sure the segments we use, based on the duplicate points created above, are of equal length. The angle of the new vector will thus bisect angle C (defined above) and the perpendicular to this is nice for the line tangent to the curve. The curve control points will be along that tangent line. */ if (a > b){ //aPt.normalize(b); // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter. aPt = aPt.normalize().multiply(b) } else if (b > a){ //cPt.normalize(a); // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter. cPt = cPt.normalize().multiply(a) } // Offset aPt and cPt by the current point to get them back to their absolute position. aPt = aPt.add(p1.x,p1.y); cPt = cPt.add(p1.x,p1.y); // Get the sum of the two vectors, which is perpendicular to the line along which our curve control points will lie. var ax = bPt.x-aPt.x; // x component of the segment from previous to current point var ay = bPt.y-aPt.y; var bx = bPt.x-cPt.x; // x component of the segment from next to current point var by = bPt.y-cPt.y; var rx = ax + bx; // sum of x components var ry = ay + by; // Correct for three points in a line by finding the angle between just two of them if (rx == 0.0 && ry == 0.0){ rx = -bx; // Really not sure why this seems to have to be negative ry = by; } // Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be. if (ay == 0.0 && by == 0.0){ rx = 0.0; ry = 1.0; } else if (ax == 0.0 && bx == 0.0){ rx = 1.0; ry = 0.0; } var r = Math.sqrt(rx*rx+ry*ry); // length of the summed vector - not being used, but there it is anyway var theta = Math.atan2(ry,rx); // angle of the new vector var controlDist = Math.min(a,b)*z; // Distance of curve control points from current point: a fraction the length of the shorter adjacent triangle side var controlScaleFactor = C/Math.PI; // Scale the distance based on the acuteness of the angle. Prevents big loops around long, sharp-angled triangles. controlDist *= ((1.0-angleFactor) + angleFactor*controlScaleFactor); // Mess with this for some fine-tuning var controlAngle = theta+Math.PI/2; // The angle from the current point to control points: the new vector angle plus 90 degrees (tangent to the curve). var controlPoint2 = polar(controlDist, controlAngle); // Control point 2, curving to the next point. var controlPoint1 = polar(controlDist, controlAngle+Math.PI); // Control point 1, curving from the previous point (180 degrees away from control point 2). // Offset control points to put them in the correct absolute position controlPoint1 = controlPoint1.add(p1.x,p1.y); controlPoint2 = controlPoint2.add(p1.x,p1.y); /* Haven't quite worked out how this happens, but some control points will be reversed. In this case controlPoint2 will be farther from the next point than controlPoint1 is. Check for that and switch them if it's true. */ if (controlPoint2.distance(p2) > controlPoint1.distance(p2)){ controlPts[i] = Pair(controlPoint2,controlPoint1); // Add the two control points to the array in reverse order } else { controlPts[i] = Pair(controlPoint1,controlPoint2); // Otherwise add the two control points to the array in normal order } // Uncomment to draw lines showing where the control points are. /* g.moveTo(p1.x,p1.y); g.lineTo(controlPoint2.x,controlPoint2.y); g.moveTo(p1.x,p1.y); g.lineTo(controlPoint1.x,controlPoint1.y); */ } // // Now draw the curve // // If moveTo condition is false, this curve can connect to a previous curve on the same graphics. if (moveTo) g.moveTo(points[0].x, points[0].y); else g.lineTo(points[0].x, points[0].y); // If this isn't a closed line if (firstPt == 1){ // Draw a regular quadratic Bézier curve from the first to second points, using the first control point of the second point g.quadraticCurveTo(controlPts[1].first.x, controlPts[1].first.y, points[1].x, points[1].y); } var straightLines:Boolean = true; // Change to true if you want to use lineTo for straight lines of 3 or more points rather than curves. You'll get straight lines but possible sharp corners! // Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed. for (i in firstPt..lastPt - 2){ // Determine if multiple points in a row are in a straight line var isStraight:Boolean = ( ( i > 0 && Math.atan2(points[i].y-points[i-1].y, points[i].x-points[i-1].x) == Math.atan2(points[i+1].y-points[i].y, points[i+1].x - points[i].x) ) || ( i < points.size - 2 && Math.atan2(points[i+2].y-points[i+1].y,points[i+2].x-points[i+1].x) == Math.atan2(points[i+1].y-points[i].y,points[i+1].x-points[i].x) ) ); if (straightLines && isStraight){ g.lineTo(points[i+1].x,points[i+1].y); } else { // BezierSegment instance using the current point, its second control point, the next point's first control point, and the next point //var bezier:BezierSegment = new BezierSegment(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1]); // Construct the curve out of 100 segments (adjust number for less/more detail) var t = 0.01 while (t < 1.01) { val point = getBezierValue(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1], t) g.lineTo(point.x, point.y) t += 0.01 } // for (var t=.01;t<1.01;t+=.01){ // var v = bezier.getValue(t); // x,y on the curve for a given t // g.lineTo(v.x,v.y); // } } } // // If this isn't a closed line // if (lastPt == points.size-1){ // // Curve to the last point using the second control point of the penultimate point. // g.quadraticCurveTo(controlPts[i].second.x, controlPts[i].second.y, points[i+1].x, points[i+1].y); // } g.closePath() g.stroke() // // just draw a line if only two points // } else if (p.length == 2){ // g.moveTo(p[0].x,p[0].y); // g.lineTo(p[1].x,p[1].y); // } // } // // Catch error // catch (e) { // trace(e.getStackTrace()); // } } fun polar(len: Double, angle: Double): Point2D { return Point2D(len * Math.cos(angle), len * Math.sin(angle)) } fun getBezierValue(p1: Point2D, p2: Point2D, p3: Point2D, p4: Point2D, t: Double): Point2D { val x = Math.pow(1 - t, 3.0) * p1.x + 3 * t * Math.pow(1 - t, 2.0) * p2.x + 3 * t*t * (1 - t) * p3.x + t*t*t*p4.x val y = Math.pow(1 - t, 3.0) * p1.y + 3 * t * Math.pow(1 - t, 2.0) * p2.y + 3 * t*t * (1 - t) * p3.y + t*t*t*p4.y return Point2D(x, y) } fun createContent(): Parent { val pane = Pane() val canvas = Canvas(600.0, 600.0) val g = canvas.graphicsContext2D pane.children.add(canvas) //draw2(g) val points = mutableListOf<Point2D>( p(25,500), p(90,400), p(250,250), p(350,250), //p(300,276), p(362,215), p(400, 400), p(125, 500), p(25, 500) //,[445,122],[551,57],[560,23], [540, 10], [520,20],[500,50],[450,70] ) curveThroughPoints(g, points) points.forEach { g.fillOval(it.x, it.y, 5.0, 5.0) } return pane } override fun start(stage: Stage) { stage.scene = Scene(createContent()) stage.show() } } fun main(args: Array<String>) { Application.launch(CurveApp::class.java, *args) }
mit
15122a112b3397817eee1314010ec993
37.508257
198
0.540192
3.474669
false
false
false
false
google/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ScriptConfigurationManager.kt
1
7094
// 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.core.script import com.intellij.ide.scratch.ScratchUtil import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationResult import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import org.jetbrains.kotlin.utils.addToStdlib.cast import java.io.File import java.nio.file.Path import kotlin.io.path.isDirectory import kotlin.io.path.isRegularFile import kotlin.io.path.notExists import kotlin.io.path.pathString import kotlin.script.experimental.api.asSuccess import kotlin.script.experimental.api.makeFailureResult // NOTE: this service exists exclusively because ScriptDependencyManager // cannot be registered as implementing two services (state would be duplicated) internal class IdeScriptDependenciesProvider(project: Project) : ScriptDependenciesProvider(project) { override fun getScriptConfigurationResult(file: KtFile): ScriptCompilationConfigurationResult? { val configuration = getScriptConfiguration(file) val reports = IdeScriptReportSink.getReports(file) if (configuration == null && reports.isNotEmpty()) { return makeFailureResult(reports) } return configuration?.asSuccess(reports) } override fun getScriptConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? { // return only already loaded configurations OR force to load gradle-related configurations return if (DefaultScriptingSupport.getInstance(project).isLoadedFromCache(file) || !ScratchUtil.isScratch(file.virtualFile)) { ScriptConfigurationManager.getInstance(project).getConfiguration(file) } else { null } } } /** * **Please, note** that [ScriptConfigurationManager] should not be used directly. * Instead, consider using [org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptImplementationSwitcher]. * * Facade for loading and caching Kotlin script files configuration. * * This service also starts indexing of new dependency roots and runs highlighting * of opened files when configuration will be loaded or updated. */ interface ScriptConfigurationManager { fun loadPlugins() /** * Get cached configuration for [file] or load it. * May return null even configuration was loaded but was not yet applied. */ fun getConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? @Deprecated("Use getScriptClasspath(KtFile) instead") fun getScriptClasspath(file: VirtualFile): List<VirtualFile> /** * @see [getConfiguration] */ fun getScriptClasspath(file: KtFile): List<VirtualFile> /** * Check if configuration is already cached for [file] (in cache or FileAttributes). * The result may be true, even cached configuration is considered out-of-date. * * Supposed to be used to switch highlighting off for scripts without configuration * to avoid all file being highlighted in red. */ fun hasConfiguration(file: KtFile): Boolean /** * returns true when there is no configuration and highlighting should be suspended */ fun isConfigurationLoadingInProgress(file: KtFile): Boolean /** * Update caches that depends on script definitions and do update if necessary */ fun updateScriptDefinitionReferences() /////////////// // classpath roots info: fun getScriptSdk(file: VirtualFile): Sdk? fun getFirstScriptsSdk(): Sdk? fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope fun getScriptDependenciesClassFiles(file: VirtualFile): Collection<VirtualFile> fun getScriptDependenciesSourceFiles(file: VirtualFile): Collection<VirtualFile> fun getScriptSdkDependenciesClassFiles(file: VirtualFile): Collection<VirtualFile> fun getScriptSdkDependenciesSourceFiles(file: VirtualFile): Collection<VirtualFile> fun getAllScriptsDependenciesClassFilesScope(): GlobalSearchScope fun getAllScriptDependenciesSourcesScope(): GlobalSearchScope fun getAllScriptsDependenciesClassFiles(): Collection<VirtualFile> fun getAllScriptDependenciesSources(): Collection<VirtualFile> fun getAllScriptsSdkDependenciesClassFiles(): Collection<VirtualFile> fun getAllScriptSdkDependenciesSources(): Collection<VirtualFile> companion object { fun getServiceIfCreated(project: Project): ScriptConfigurationManager? = project.serviceIfCreated() @JvmStatic fun getInstance(project: Project): ScriptConfigurationManager = project.service() @JvmStatic fun allExtraRoots(project: Project): Collection<VirtualFile> { val manager = getInstance(project) return manager.getAllScriptsDependenciesClassFiles() + manager.getAllScriptDependenciesSources() } @JvmStatic fun compositeScriptConfigurationManager(project: Project) = getInstance(project).cast<CompositeScriptConfigurationManager>() fun toVfsRoots(roots: Iterable<File>): List<VirtualFile> = roots.mapNotNull { classpathEntryToVfs(it.toPath()) } // TODO: report this somewhere, but do not throw: assert(res != null, { "Invalid classpath entry '$this': exists: ${exists()}, is directory: $isDirectory, is file: $isFile" }) fun classpathEntryToVfs(path: Path): VirtualFile? = when { path.notExists() -> null path.isDirectory() -> StandardFileSystems.local()?.findFileByPath(path.pathString) path.isRegularFile() -> StandardFileSystems.jar()?.findFileByPath(path.pathString + URLUtil.JAR_SEPARATOR) else -> null } @TestOnly fun updateScriptDependenciesSynchronously(file: PsiFile) { // TODO: review the usages of this method defaultScriptingSupport(file.project).updateScriptDependenciesSynchronously(file) } private fun defaultScriptingSupport(project: Project) = compositeScriptConfigurationManager(project).default @TestOnly fun clearCaches(project: Project) { defaultScriptingSupport(project).updateScriptDefinitionsReferences() } } }
apache-2.0
fbc49220c09191892a17163b441ed2b9
43.062112
183
0.753313
5.243163
false
true
false
false
google/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/intentions/PackageSearchUnresolvedReferenceQuickFix.kt
1
2542
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.jetbrains.packagesearch.PackageSearchIcons import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.util.pkgsUiStateModifier class PackageSearchUnresolvedReferenceQuickFix(private val ref: PsiReference) : IntentionAction, LowPriorityAction, Iconable { private val classnamePattern = Regex("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+") override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { PackageSearchToolWindowFactory.activateToolWindow(project) { project.pkgsUiStateModifier.setSearchQuery(ref.canonicalText) } } override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = ref.element.run { isValid && classnamePattern.matches(text) } override fun getText() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action") @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... override fun getFamilyName() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.family") override fun getIcon(flags: Int) = PackageSearchIcons.Package override fun startInWriteAction() = false }
apache-2.0
fbb42f743e8197af49c9b80eb53980d1
46.074074
126
0.734068
5.043651
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToFunctionCallIntention.kt
3
6945
// 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.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class FoldIfToFunctionCallIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("lift.function.call.out.of.if"), ) { override fun applicabilityRange(element: KtIfExpression): TextRange? = if (canFoldToFunctionCall(element)) element.ifKeyword.textRange else null override fun applyTo(element: KtIfExpression, editor: Editor?) { foldToFunctionCall(element, editor) } companion object { fun branches(expression: KtExpression): List<KtExpression>? { val branches = when (expression) { is KtIfExpression -> expression.branches is KtWhenExpression -> expression.entries.map { it.expression } else -> emptyList() } val branchesSize = branches.size if (branchesSize < 2) return null return branches.filterNotNull().takeIf { it.size == branchesSize } } private fun canFoldToFunctionCall(element: KtExpression): Boolean { val branches = branches(element) ?: return false val callExpressions = branches.mapNotNull { it.callExpression() } if (branches.size != callExpressions.size) return false if (differentArgumentIndex(callExpressions) == null) return false val headCall = callExpressions.first() val tailCalls = callExpressions.drop(1) val context = headCall.analyze(BodyResolveMode.PARTIAL) val (headFunctionFqName, headFunctionParameters) = headCall.fqNameAndParameters(context) ?: return false return tailCalls.all { call -> val (fqName, parameters) = call.fqNameAndParameters(context) ?: return@all false fqName == headFunctionFqName && parameters.zip(headFunctionParameters).all { it.first == it.second } } } private fun foldToFunctionCall(element: KtExpression, editor: Editor?) { val branches = branches(element) ?: return val callExpressions = branches.mapNotNull { it.callExpression() } val headCall = callExpressions.first() val argumentIndex = differentArgumentIndex(callExpressions) ?: return val hasNamedArgument = callExpressions.any { call -> call.valueArguments.any { it.getArgumentName() != null } } val copiedIf = element.copy() as KtIfExpression copiedIf.branches.forEach { branch -> val call = branch.callExpression() ?: return val argument = call.valueArguments[argumentIndex].getArgumentExpression() ?: return call.getQualifiedExpressionForSelectorOrThis().replace(argument) } headCall.valueArguments[argumentIndex].getArgumentExpression()?.replace(copiedIf) if (hasNamedArgument) { headCall.valueArguments.forEach { if (it.getArgumentName() == null) AddNameToArgumentIntention.apply(it, givenResolvedCall = null, editor) } } element.replace(headCall.getQualifiedExpressionForSelectorOrThis()).reformatted() } private fun differentArgumentIndex(callExpressions: List<KtCallExpression>): Int? { val headCall = callExpressions.first() val headCalleeText = headCall.calleeText() val tailCalls = callExpressions.drop(1) if (headCall.valueArguments.any { it is KtLambdaArgument }) return null val headArguments = headCall.valueArguments.mapNotNull { it.getArgumentExpression()?.text } val headArgumentsSize = headArguments.size if (headArgumentsSize != headCall.valueArguments.size) return null val differentArgumentIndexes = tailCalls.mapNotNull { call -> if (call.calleeText() != headCalleeText) return@mapNotNull null val arguments = call.valueArguments.mapNotNull { it.getArgumentExpression()?.text } if (arguments.size != headArgumentsSize) return@mapNotNull null val differentArgumentIndexes = arguments.zip(headArguments).mapIndexedNotNull { index, (arg, headArg) -> if (arg != headArg) index else null } differentArgumentIndexes.singleOrNull() } if (differentArgumentIndexes.size != tailCalls.size || differentArgumentIndexes.distinct().size != 1) return null return differentArgumentIndexes.first() } private fun KtExpression?.callExpression(): KtCallExpression? { return when (val expression = if (this is KtBlockExpression) statements.singleOrNull() else this) { is KtCallExpression -> expression is KtQualifiedExpression -> expression.callExpression else -> null }?.takeIf { it.calleeExpression != null } } private fun KtCallExpression.calleeText(): String { val parent = this.parent val (receiver, op) = if (parent is KtQualifiedExpression) { parent.receiverExpression.text to parent.operationSign.value } else { "" to "" } return "$receiver$op${calleeExpression?.text.orEmpty()}" } private fun KtCallExpression.fqNameAndParameters(context: BindingContext): Pair<FqName, List<ValueParameterDescriptor>>? { val resolvedCall = getResolvedCall(context) ?: return null val fqName = resolvedCall.resultingDescriptor.fqNameOrNull() ?: return null val parameters = valueArguments.mapNotNull { (resolvedCall.getArgumentMapping(it) as? ArgumentMatch)?.valueParameter } return fqName to parameters } } }
apache-2.0
cb40a7ccff90d85eb2cb72475eeefdbc
51.218045
140
0.67689
5.511905
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/client/ClientSessionImpl.kt
1
6296
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.client import com.intellij.codeWithMe.ClientId import com.intellij.ide.plugins.ContainerDescriptor import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.Application import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.ComponentConfig import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.serviceContainer.PrecomputedExtensionModel import com.intellij.serviceContainer.executeRegisterTaskForOldContent import com.intellij.util.messages.MessageBus import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus private val LOG = logger<ClientSessionImpl>() @ApiStatus.Experimental @ApiStatus.Internal abstract class ClientSessionImpl( final override val clientId: ClientId, final override val type: ClientType, protected val sharedComponentManager: ClientAwareComponentManager ) : ComponentManagerImpl(null, false), ClientSession { override val isLightServiceSupported = false override val isMessageBusSupported = false init { @Suppress("LeakingThis") registerServiceInstance(ClientSession::class.java, this, fakeCorePluginDescriptor) } fun registerServices() { registerComponents() } fun preloadServices(syncScope: CoroutineScope) { assert(containerState.get() == ContainerState.PRE_INIT) val exceptionHandler = CoroutineExceptionHandler { _, exception -> LOG.error(exception) } this.preloadServices(modules = PluginManagerCore.getPluginSet().getEnabledModules(), activityPrefix = "client ", syncScope = syncScope + exceptionHandler, onlyIfAwait = false ) assert(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)) } override suspend fun preloadService(service: ServiceDescriptor): Job? { return ClientId.withClientId(clientId) { super.preloadService(service) } } override fun isServiceSuitable(descriptor: ServiceDescriptor): Boolean { return descriptor.client?.let { type.matches(it) } ?: false } /** * only per-client services are supported (no components, extensions, listeners) */ override fun registerComponents(modules: List<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: MutableList<in Runnable>?) { for (rootModule in modules) { registerServices(getContainerDescriptor(rootModule).services, rootModule) executeRegisterTaskForOldContent(rootModule) { module -> registerServices(getContainerDescriptor(module).services, module) } } } override fun isComponentSuitable(componentConfig: ComponentConfig): Boolean { LOG.error("components aren't supported") return false } override fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? { return doGetService(serviceClass, createIfNeeded, true) } fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean, fallbackToShared: Boolean): T? { val clientService = ClientId.withClientId(clientId) { super.doGetService(serviceClass, createIfNeeded) } if (clientService != null || !fallbackToShared) return clientService if (createIfNeeded && !type.isLocal) { val sessionsManager = sharedComponentManager.getService(ClientSessionsManager::class.java) val localSession = sessionsManager?.getSession(ClientId.localId) as? ClientSessionImpl if (localSession?.doGetService(serviceClass, createIfNeeded = true, fallbackToShared = false) != null) { LOG.error("$serviceClass is registered only for client=\"local\", " + "please provide a guest-specific implementation, or change to client=\"all\"") return null } } ClientId.withClientId(ClientId.localId) { return if (createIfNeeded) { sharedComponentManager.getService(serviceClass) } else { sharedComponentManager.getServiceIfCreated(serviceClass) } } } override fun getApplication(): Application? { return sharedComponentManager.getApplication() } override val componentStore: IComponentStore get() = sharedComponentManager.componentStore @Deprecated("sessions don't have their own message bus", level = DeprecationLevel.ERROR) override fun getMessageBus(): MessageBus { error("Not supported") } override fun toString(): String { return clientId.toString() } } @ApiStatus.Internal open class ClientAppSessionImpl( clientId: ClientId, clientType: ClientType, application: ApplicationImpl ) : ClientSessionImpl(clientId, clientType, application), ClientAppSession { override fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor { return pluginDescriptor.appContainerDescriptor } init { @Suppress("LeakingThis") registerServiceInstance(ClientAppSession::class.java, this, fakeCorePluginDescriptor) } } @ApiStatus.Internal open class ClientProjectSessionImpl( clientId: ClientId, clientType: ClientType, final override val project: ProjectImpl, ) : ClientSessionImpl(clientId, clientType, project), ClientProjectSession { override fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor { return pluginDescriptor.projectContainerDescriptor } init { registerServiceInstance(ClientProjectSession::class.java, this, fakeCorePluginDescriptor) registerServiceInstance(Project::class.java, project, fakeCorePluginDescriptor) } override val appSession: ClientAppSession get() = ClientSessionsManager.getAppSession(clientId)!! }
apache-2.0
46e8277dcbe7197da1c2c69c81cc468b
36.700599
120
0.753177
5.255426
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/operators/DropTest.kt
1
1447
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlin.test.* class DropTest : TestBase() { @Test fun testDrop() = runTest { val flow = flow { emit(1) emit(2) emit(3) } assertEquals(5, flow.drop(1).sum()) assertEquals(0, flow.drop(Int.MAX_VALUE).sum()) assertNull(flow.drop(Int.MAX_VALUE).singleOrNull()) assertEquals(3, flow.drop(1).take(2).drop(1).single()) } @Test fun testEmptyFlow() = runTest { assertEquals(0, flowOf<Int>().drop(1).sum()) } @Test fun testNegativeCount() { assertFailsWith<IllegalArgumentException> { emptyFlow<Int>().drop(-1) } } @Test fun testErrorCancelsUpstream() = runTest { val flow = flow { coroutineScope { launch(start = CoroutineStart.ATOMIC) { hang { expect(5) } } expect(2) emit(1) expect(3) emit(2) expectUnreached() } }.drop(1) .map<Int, Int> { expect(4) throw TestException() }.catch { emit(42) } expect(1) assertEquals(42, flow.single()) finish(6) } }
apache-2.0
faf1cb5c491f6c57374ef4e9df10f4ce
23.116667
102
0.498963
4.218659
false
true
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/admincards/CustomColumnCard.kt
1
5024
package com.faendir.acra.ui.view.app.tabs.admincards import com.faendir.acra.i18n.Messages import com.faendir.acra.model.App import com.faendir.acra.model.Permission import com.faendir.acra.navigation.ParseAppParameter import com.faendir.acra.navigation.View import com.faendir.acra.security.RequiresPermission import com.faendir.acra.security.SecurityUtils import com.faendir.acra.service.DataService import com.faendir.acra.ui.component.AdminCard import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.component.grid.ButtonRenderer import com.faendir.acra.ui.component.grid.column import com.faendir.acra.ui.ext.SizeUnit import com.faendir.acra.ui.ext.acrariumGrid import com.faendir.acra.ui.ext.content import com.faendir.acra.ui.ext.setHeight import com.faendir.acra.ui.ext.setMarginRight import com.faendir.acra.ui.ext.setMinHeight import com.vaadin.flow.component.button.Button import com.vaadin.flow.component.html.Div import com.vaadin.flow.component.icon.Icon import com.vaadin.flow.component.icon.VaadinIcon import com.vaadin.flow.component.textfield.TextField import com.vaadin.flow.data.binder.Binder import com.vaadin.flow.data.renderer.ComponentRenderer import java.util.* @View @RequiresPermission(Permission.Level.EDIT) class CustomColumnCard(dataService: DataService, @ParseAppParameter val app: App) : AdminCard(dataService) { init { content { setHeader(Translatable.createLabel(Messages.CUSTOM_COLUMNS)) acrariumGrid(app.configuration.customReportColumns) { setMinHeight(280, SizeUnit.PIXEL) setHeight(100, SizeUnit.PERCENTAGE) val column = column({ it }) { isSortable = true captionId = Messages.CUSTOM_COLUMNS setFlexGrow(1) } if (SecurityUtils.hasPermission(app, Permission.Level.EDIT)) { editor.binder = Binder(String::class.java) editor.isBuffered = true val regex = Regex("[\\w_-]+(\\.[\\w_-]+)*") val field = TextField().apply { isPreventInvalidInput = true pattern = regex.pattern } editor.binder.forField(field) .withValidator({ it.matches(regex) }, { getTranslation(Messages.ERROR_NOT_JSON_PATH) }) .bind({ it }, { old, value -> app.configuration.customReportColumns.apply { set(indexOf(old), value) } dataService.store(app) }) column.editorComponent = field val editButtons = Collections.newSetFromMap<Button>(WeakHashMap()) editor.addOpenListener { editButtons.forEach { it.isEnabled = !editor.isOpen } } editor.addCloseListener { editButtons.forEach { it.isEnabled = !editor.isOpen } } val save = Translatable.createButton(Messages.SAVE) { if (!field.isInvalid) { editor.save() app.configuration.customReportColumns.remove("") dataProvider.refreshAll() } }.with { setMarginRight(5.0, SizeUnit.PIXEL) } val cancel = Translatable.createButton(Messages.CANCEL) { editor.cancel() app.configuration.customReportColumns.remove("") dataProvider.refreshAll() } column(ButtonRenderer(VaadinIcon.EDIT, {editButtons.add(it)}) { editor.editItem(it) field.focus() recalculateColumnWidths() }) { editorComponent = Div(save, cancel) setFlexGrow(1) } column(ComponentRenderer { string -> Button(Icon(VaadinIcon.TRASH)) { app.configuration.customReportColumns.remove("") app.configuration.customReportColumns.remove(string) dataService.store(app) dataProvider.refreshAll() } }) appendFooterRow().getCell(columns[0]).setComponent( Translatable.createButton(Messages.ADD_COLUMN) { if (!app.configuration.customReportColumns.contains("")) { app.configuration.customReportColumns.add("") } dataProvider.refreshAll() editor.editItem("") }) } } } } }
apache-2.0
302d2dc815959f6671e3403cab6a4cdc
46.857143
111
0.553344
5.121305
false
true
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/GrCollectionConstructorConverter.kt
1
2424
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.typing import com.intellij.psi.CommonClassNames.JAVA_UTIL_COLLECTION import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil.isInheritor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ConversionResult import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isCompileStatic import org.jetbrains.plugins.groovy.lang.resolve.impl.getAllConstructors /** * Given a collection on the right hand side checks if the class on the left has collection constructor. * ``` * class C { * C(Collection a) {} * } * C c = new ArrayList() * ``` * @see org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM */ class GrCollectionConstructorConverter : GrTypeConverter() { override fun isConvertible(targetType: PsiType, actualType: PsiType, position: Position, context: GroovyPsiElement): ConversionResult? { if (position != Position.ASSIGNMENT && position != Position.RETURN_VALUE || isCompileStatic(context)) { return null } if (!isInheritor(actualType, JAVA_UTIL_COLLECTION)) { return null } val constructedType = targetType as? PsiClassType ?: return null val constructedClass = constructedType.resolve() ?: return null val hasConstructor = hasCollectionApplicableConstructor(constructedClass, context) return if (hasConstructor) ConversionResult.OK else null } companion object { fun hasCollectionApplicableConstructor(constructedClass: PsiClass, context: PsiElement): Boolean { val constructors = getAllConstructors(constructedClass, context) if (constructors.isEmpty()) { return false } val collectionType = createType(JAVA_UTIL_COLLECTION, context) return constructors.any { val parameter = it.parameterList.parameters.singleOrNull() parameter?.type?.isAssignableFrom(collectionType) ?: false } } } }
apache-2.0
83cd2848902d0a8f8d3f6337e235bb29
42.285714
140
0.768152
4.480591
false
false
false
false
leafclick/intellij-community
platform/workspaceModel-ide/src/com/intellij/workspace/jps/JpsProjectEntitiesLoader.kt
1
5698
package com.intellij.workspace.jps import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.workspace.api.LibraryTableId import com.intellij.workspace.api.TypedEntityStorageBuilder import com.intellij.workspace.api.toVirtualFileUrl import com.intellij.workspace.ide.JpsFileEntitySource import com.intellij.workspace.ide.JpsProjectStoragePlace import org.jdom.Element import java.io.File object JpsProjectEntitiesLoader { /** * [serializeArtifacts] specifies whether artifacts should be serialized or not. We need this until a legacy bridge implementation for * ArtifactManager is provided. * [serializeFacets] specifies whether facets should be serialized or not. We need this until a legacy bridge implementation for * FacetManager is provided. */ fun createProjectSerializers(storagePlace: JpsProjectStoragePlace, reader: JpsFileContentReader, serializeArtifacts: Boolean, serializeFacets: Boolean): JpsEntitiesSerializationData { return createProjectEntitiesSerializers(storagePlace, serializeArtifacts, serializeFacets).createSerializers(reader) } fun loadProject(storagePlace: JpsProjectStoragePlace, builder: TypedEntityStorageBuilder): JpsEntitiesSerializationData { val mainFactories = createProjectEntitiesSerializers(storagePlace, true, true) val reader = CachingJpsFileContentReader(storagePlace.baseDirectoryUrl) val data = mainFactories.createSerializers(reader) data.loadAll(reader, builder) return data } fun loadModule(moduleFile: File, storagePlace: JpsProjectStoragePlace, builder: TypedEntityStorageBuilder) { val source = JpsFileEntitySource.FileInDirectory(moduleFile.parentFile.toVirtualFileUrl(), storagePlace) loadModule(moduleFile, source, storagePlace, builder) } internal fun loadModule(moduleFile: File, source: JpsFileEntitySource.FileInDirectory, storagePlace: JpsProjectStoragePlace, builder: TypedEntityStorageBuilder) { val mainFactories = createProjectEntitiesSerializers(storagePlace, false, true) val reader = CachingJpsFileContentReader(storagePlace.baseDirectoryUrl) val moduleSerializerFactory = mainFactories.fileSerializerFactories.filterIsInstance<ModuleSerializersFactory>().single() val serializer = moduleSerializerFactory.createSerializer(source, moduleFile.toVirtualFileUrl()) serializer.loadEntities(builder, reader) } private fun createProjectEntitiesSerializers(storagePlace: JpsProjectStoragePlace, serializeArtifacts: Boolean, serializeFacets: Boolean): JpsEntitiesSerializerFactories { return when (storagePlace) { is JpsProjectStoragePlace.FileBased -> createIprProjectSerializers(storagePlace, serializeArtifacts, serializeFacets) is JpsProjectStoragePlace.DirectoryBased -> createDirectoryProjectSerializers(storagePlace, serializeArtifacts, serializeFacets) } } private fun createDirectoryProjectSerializers(storagePlace: JpsProjectStoragePlace.DirectoryBased, serializeArtifacts: Boolean, serializeFacets: Boolean): JpsEntitiesSerializerFactories { val projectDirUrl = storagePlace.projectDir.url val directorySerializersFactories = ArrayList<JpsDirectoryEntitiesSerializerFactory<*>>() directorySerializersFactories += JpsLibrariesDirectorySerializerFactory("$projectDirUrl/.idea/libraries") if (serializeArtifacts) { directorySerializersFactories += JpsArtifactsDirectorySerializerFactory("$projectDirUrl/.idea/artifacts") } return JpsEntitiesSerializerFactories(entityTypeSerializers = emptyList(), directorySerializersFactories = directorySerializersFactories, fileSerializerFactories = listOf(ModuleSerializersFactory("$projectDirUrl/.idea/modules.xml", serializeFacets)), storagePlace = storagePlace) } private fun createIprProjectSerializers(storagePlace: JpsProjectStoragePlace.FileBased, serializeArtifacts: Boolean, serializeFacets: Boolean): JpsEntitiesSerializerFactories { val projectFileSource = JpsFileEntitySource.ExactFile(storagePlace.iprFile, storagePlace) val projectFileUrl = projectFileSource.file val entityTypeSerializers = ArrayList<JpsFileEntityTypeSerializer<*>>() entityTypeSerializers += JpsLibrariesFileSerializer(projectFileUrl, projectFileSource, LibraryTableId.ProjectLibraryTableId) if (serializeArtifacts) { entityTypeSerializers += JpsArtifactsFileSerializer(projectFileUrl, projectFileSource) } return JpsEntitiesSerializerFactories(entityTypeSerializers, directorySerializersFactories = emptyList(), fileSerializerFactories = listOf(ModuleSerializersFactory(projectFileUrl.url, serializeFacets)), storagePlace = storagePlace) } } /** * @see com.intellij.core.CoreProjectLoader.loadStorageFile */ internal fun loadStorageFile(xmlFile: File, pathMacroManager: PathMacroManager) = FileStorageCoreUtil.load(JDOMUtil.load(xmlFile.toPath()), pathMacroManager) as Map<String, Element>
apache-2.0
7b490e83ee47e2c8dd5d16586885713f
57.142857
154
0.727624
6.100642
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/coroutines/CoroutineContextTest/testGetPlusFold.kt
2
2068
import kotlin.test.* import kotlin.coroutines.experimental.* data class CtxA(val i: Int) : AbstractCoroutineContextElement(CtxA) { companion object Key : CoroutineContext.Key<CtxA> } data class CtxB(val i: Int) : AbstractCoroutineContextElement(CtxB) { companion object Key : CoroutineContext.Key<CtxB> } data class CtxC(val i: Int) : AbstractCoroutineContextElement(CtxC) { companion object Key : CoroutineContext.Key<CtxC> } private fun assertContents(ctx: CoroutineContext, vararg elements: CoroutineContext.Element) { val set = ctx.fold(setOf<CoroutineContext>()) { a, b -> a + b } assertEquals(listOf(*elements), set.toList()) for (elem in elements) assertTrue(ctx[elem.key] == elem) } fun box() { var ctx: CoroutineContext = EmptyCoroutineContext assertContents(ctx) assertEquals("EmptyCoroutineContext", ctx.toString()) ctx += CtxA(1) assertContents(ctx, CtxA(1)) assertEquals("CtxA(i=1)", ctx.toString()) assertEquals(CtxA(1), ctx[CtxA]) assertEquals(null, ctx[CtxB]) assertEquals(null, ctx[CtxC]) ctx += CtxB(2) assertContents(ctx, CtxA(1), CtxB(2)) assertEquals("[CtxA(i=1), CtxB(i=2)]", ctx.toString()) assertEquals(CtxA(1), ctx[CtxA]) assertEquals(CtxB(2), ctx[CtxB]) assertEquals(null, ctx[CtxC]) ctx += CtxC(3) assertContents(ctx, CtxA(1), CtxB(2), CtxC(3)) assertEquals("[CtxA(i=1), CtxB(i=2), CtxC(i=3)]", ctx.toString()) assertEquals(CtxA(1), ctx[CtxA]) assertEquals(CtxB(2), ctx[CtxB]) assertEquals(CtxC(3), ctx[CtxC]) ctx += CtxB(4) assertContents(ctx, CtxA(1), CtxC(3), CtxB(4)) assertEquals("[CtxA(i=1), CtxC(i=3), CtxB(i=4)]", ctx.toString()) assertEquals(CtxA(1), ctx[CtxA]) assertEquals(CtxB(4), ctx[CtxB]) assertEquals(CtxC(3), ctx[CtxC]) ctx += CtxA(5) assertContents(ctx, CtxC(3), CtxB(4), CtxA(5)) assertEquals("[CtxC(i=3), CtxB(i=4), CtxA(i=5)]", ctx.toString()) assertEquals(CtxA(5), ctx[CtxA]) assertEquals(CtxB(4), ctx[CtxB]) assertEquals(CtxC(3), ctx[CtxC]) }
apache-2.0
7784b28a2ddf10f74fed9a72f9e7223f
31.825397
94
0.662959
3.176651
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/beginWithException.kt
2
891
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* suspend fun suspendHere(): Any = suspendCoroutineOrReturn { x -> } fun builder(c: suspend () -> Unit) { var exception: Throwable? = null c.createCoroutine(object : Continuation<Unit> { override val context = EmptyCoroutineContext override fun resume(data: Unit) { } override fun resumeWithException(e: Throwable) { exception = e } }).resumeWithException(RuntimeException("OK")) if (exception?.message != "OK") { throw RuntimeException("Unexpected result: ${exception?.message}") } } fun box(): String { var result = "OK" builder { suspendHere() result = "fail 1" } builder { result = "fail 2" } return result }
apache-2.0
bea847376229a90e3ac69e496a8dce4f
21.275
74
0.624018
4.61658
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ObjectGraphicInMultiMode.kt
1
4909
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.objectdetection import android.graphics.Canvas import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Paint.Style import android.graphics.PorterDuff import android.graphics.PorterDuffXfermode import android.graphics.RectF import android.graphics.Shader.TileMode import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay.Graphic import com.google.firebase.ml.md.R /** * Draws the detected detectedObject info over the camera preview for multiple objects detection mode. */ internal class ObjectGraphicInMultiMode( overlay: GraphicOverlay, private val detectedObject: DetectedObject, private val confirmationController: ObjectConfirmationController ) : Graphic(overlay) { private val boxPaint: Paint private val scrimPaint: Paint private val eraserPaint: Paint @ColorInt private val boxGradientStartColor: Int @ColorInt private val boxGradientEndColor: Int private val boxCornerRadius: Int private val minBoxLen: Int init { val resources = context.resources boxPaint = Paint().apply { style = Style.STROKE strokeWidth = resources.getDimensionPixelOffset( if (confirmationController.isConfirmed) { R.dimen.bounding_box_confirmed_stroke_width } else { R.dimen.bounding_box_stroke_width } ).toFloat() color = Color.WHITE } boxGradientStartColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_start) boxGradientEndColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_end) boxCornerRadius = resources.getDimensionPixelOffset(R.dimen.bounding_box_corner_radius) scrimPaint = Paint().apply { shader = LinearGradient( 0f, 0f, overlay.width.toFloat(), overlay.height.toFloat(), ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_start), ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_end), TileMode.MIRROR ) } eraserPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) } minBoxLen = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_radius) * 2 } override fun draw(canvas: Canvas) { var rect = overlay.translateRect(detectedObject.boundingBox) val boxWidth = rect.width() * confirmationController.progress val boxHeight = rect.height() * confirmationController.progress if (boxWidth < minBoxLen || boxHeight < minBoxLen) { // Don't draw the box if its length is too small, otherwise it will intersect with reticle so // the UI looks messy. return } val cx = (rect.left + rect.right) / 2 val cy = (rect.top + rect.bottom) / 2 rect = RectF( cx - boxWidth / 2f, cy - boxHeight / 2f, cx + boxWidth / 2f, cy + boxHeight / 2f ) if (confirmationController.isConfirmed) { // Draws the dark background scrim and leaves the detectedObject area clear. canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint) canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), eraserPaint) } boxPaint.shader = if (confirmationController.isConfirmed) { null } else { LinearGradient( rect.left, rect.top, rect.left, rect.bottom, boxGradientStartColor, boxGradientEndColor, TileMode.MIRROR ) } canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), boxPaint) } }
apache-2.0
df695d9b353706d923089c0f1b7aea75
36.473282
106
0.643919
4.779942
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/interfaces/permissions/PermissionsResponse.kt
2
541
package abi42_0_0.expo.modules.interfaces.permissions data class PermissionsResponse( val status: PermissionsStatus, val canAskAgain: Boolean = true ) { companion object { const val STATUS_KEY = "status" const val GRANTED_KEY = "granted" const val EXPIRES_KEY = "expires" const val CAN_ASK_AGAIN_KEY = "canAskAgain" const val SCOPE_KEY = "scope" const val PERMISSION_EXPIRES_NEVER = "never" const val SCOPE_IN_USE = "whenInUse" const val SCOPE_ALWAYS = "always" const val SCOPE_NONE = "none" } }
bsd-3-clause
68c08df72cddd8c1902f714d941c6701
29.055556
53
0.693161
3.680272
false
false
false
false
android/xAnd11
core/src/main/java/com/monksanctum/xand11/core/extension/ExtensionProtocol.kt
1
2252
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.monksanctum.xand11.extension import org.monksanctum.xand11.comm.* import org.monksanctum.xand11.comm.XProtoWriter.WriteException class ExtensionProtocol(private val mExtensionManager: ExtensionManager) : Dispatcher.PacketHandler { override val opCodes: ByteArray get() = HANDLED_OPS override fun handleRequest(client: Client, reader: PacketReader, writer: PacketWriter) { when (reader.majorOpCode) { Request.QUERY_EXTENSION.code -> handleQueryExtension(reader, writer) Request.LIST_EXTENSIONS.code -> handleListExtension(reader, writer) } } private fun handleQueryExtension(packet: PacketReader, writer: PacketWriter) { val n = packet.readCard16() packet.readPadding(2) val name = packet.readPaddedString(n) val info = mExtensionManager.queryExtension(name) try { info.write(writer) } catch (e: WriteException) { } } private fun handleListExtension(packet: PacketReader, writer: PacketWriter) { var count = 0 val exts = mExtensionManager.extensions writer.minorOpCode = exts.size.toByte() writer.writePadding(24) for (name in exts) { writer.writeString(name) writer.writeByte(0.toByte()) count += name.length + 1 } while (count++ % 4 != 0) { writer.writePadding(1) } } companion object { private val HANDLED_OPS = byteArrayOf(Request.QUERY_EXTENSION.code, Request.LIST_EXTENSIONS.code) } }
apache-2.0
bdaf48f6f6185a46d31737e2bc569276
33.1875
101
0.650977
4.339114
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/ExtractMethodHelper.kt
1
11724
// 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.refactoring.extractMethod.newImpl import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.NullableNotNullManager import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.codeInsight.generation.GenerateMembersUtil import com.intellij.codeInsight.intention.AddAnnotationPsiFix import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.codeStyle.VariableKind import com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper import com.intellij.psi.impl.source.DummyHolder import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.* import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.refactoring.extractMethod.newImpl.structures.InputParameter import com.intellij.refactoring.util.RefactoringUtil object ExtractMethodHelper { fun hasReferencesToScope(scope: List<PsiElement>, elements: List<PsiElement>): Boolean { val localVariables = scope.asSequence().flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiVariable::class.java) }.toSet() return elements.asSequence() .flatMap { element -> PsiTreeUtil.findChildrenOfType(element, PsiReferenceExpression::class.java) } .mapNotNull { reference -> reference.resolve() as? PsiVariable } .any { variable -> variable in localVariables } } @JvmStatic fun findEditorSelection(editor: Editor): TextRange? { val selectionModel = editor.selectionModel return if (selectionModel.hasSelection()) TextRange(selectionModel.selectionStart, selectionModel.selectionEnd) else null } fun isNullabilityAvailable(extractOptions: ExtractOptions): Boolean { val project = extractOptions.project val scope = extractOptions.elements.first().resolveScope val defaultNullable = NullableNotNullManager.getInstance(project).defaultNullable val annotationClass = JavaPsiFacade.getInstance(project).findClass(defaultNullable, scope) return annotationClass != null } fun wrapWithCodeBlock(elements: List<PsiElement>): List<PsiCodeBlock> { require(elements.isNotEmpty()) val codeBlock = PsiElementFactory.getInstance(elements.first().project).createCodeBlock() elements.forEach { codeBlock.add(it) } return listOf(codeBlock) } fun getReturnedExpression(returnOrYieldStatement: PsiStatement): PsiExpression? { return when (returnOrYieldStatement) { is PsiReturnStatement -> returnOrYieldStatement.returnValue is PsiYieldStatement -> returnOrYieldStatement.expression else -> null } } fun findUsedTypeParameters(source: PsiTypeParameterList?, searchScope: List<PsiElement>): List<PsiTypeParameter> { val typeParameterList = RefactoringUtil.createTypeParameterListWithUsedTypeParameters(source, *searchScope.toTypedArray()) return typeParameterList?.typeParameters.orEmpty().toList() } fun inputParameterOf(externalReference: ExternalReference): InputParameter { return InputParameter(externalReference.references, requireNotNull(externalReference.variable.name), externalReference.variable.type) } fun inputParameterOf(expressionGroup: List<PsiExpression>): InputParameter { require(expressionGroup.isNotEmpty()) val expression = expressionGroup.first() val objectType = PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.projectScope(expression.project)) return InputParameter(expressionGroup, guessName(expression), expressionGroup.first().type ?: objectType) } fun PsiElement.addSiblingAfter(element: PsiElement): PsiElement { return this.parent.addAfter(element, this) } fun getValidParentOf(element: PsiElement): PsiElement { val parent = element.parent val physicalParent = when (parent) { is DummyHolder -> parent.context null -> element.context else -> parent } return physicalParent ?: throw IllegalArgumentException() } fun normalizedAnchor(anchor: PsiMember): PsiMember { return if (anchor is PsiField) { MultipleFieldDeclarationHelper.findLastFieldInGroup(anchor.node).psi as? PsiField ?: anchor } else { anchor } } fun addNullabilityAnnotation(owner: PsiModifierListOwner, nullability: Nullability) { val nullabilityManager = NullableNotNullManager.getInstance(owner.project) val annotation = when (nullability) { Nullability.NOT_NULL -> nullabilityManager.defaultNotNull Nullability.NULLABLE -> nullabilityManager.defaultNullable else -> return } val target: PsiAnnotationOwner? = if (owner is PsiParameter) owner.typeElement else owner.modifierList if (target == null) return val annotationElement = AddAnnotationPsiFix.addPhysicalAnnotationIfAbsent(annotation, PsiNameValuePair.EMPTY_ARRAY, target) if (annotationElement != null) { JavaCodeStyleManager.getInstance(owner.project).shortenClassReferences(annotationElement) } } private fun findVariableReferences(element: PsiElement): Sequence<PsiVariable> { val references = PsiTreeUtil.findChildrenOfAnyType(element, PsiReferenceExpression::class.java) return references.asSequence().mapNotNull { reference -> (reference.resolve() as? PsiVariable) } } fun hasConflictResolve(name: String?, scopeToIgnore: List<PsiElement>): Boolean { require(scopeToIgnore.isNotEmpty()) if (name == null) return false val lastElement = scopeToIgnore.last() val helper = JavaPsiFacade.getInstance(lastElement.project).resolveHelper val resolvedRange = helper.resolveAccessibleReferencedVariable(name, lastElement.context)?.textRange ?: return false return resolvedRange !in TextRange(scopeToIgnore.first().textRange.startOffset, scopeToIgnore.last().textRange.endOffset) } fun uniqueNameOf(name: String?, scopeToIgnore: List<PsiElement>, reservedNames: List<String>): String? { require(scopeToIgnore.isNotEmpty()) if (name == null) return null val lastElement = scopeToIgnore.last() if (hasConflictResolve(name, scopeToIgnore) || name in reservedNames){ val styleManager = JavaCodeStyleManager.getInstance(lastElement.project) as JavaCodeStyleManagerImpl return styleManager.suggestUniqueVariableName(name, lastElement, true) } else { return name } } fun guessName(expression: PsiExpression): String { val codeStyleManager = JavaCodeStyleManager.getInstance(expression.project) as JavaCodeStyleManagerImpl return findVariableReferences(expression).mapNotNull { variable -> variable.name }.firstOrNull() ?: codeStyleManager.suggestSemanticNames(expression).firstOrNull() ?: "x" } fun createDeclaration(variable: PsiVariable): PsiDeclarationStatement { val factory = PsiElementFactory.getInstance(variable.project) val declaration = factory.createVariableDeclarationStatement(requireNotNull(variable.name), variable.type, null) val declaredVariable = declaration.declaredElements.first() as PsiVariable PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, variable.hasModifierProperty(PsiModifier.FINAL)) variable.annotations.forEach { annotation -> declaredVariable.modifierList?.add(annotation) } return declaration } fun getExpressionType(expression: PsiExpression): PsiType { val type = RefactoringUtil.getTypeByExpressionWithExpectedType(expression) return when { type != null -> type expression.parent is PsiExpressionStatement -> PsiType.VOID else -> PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.allScope(expression.project)) } } fun areSame(elements: List<PsiElement?>): Boolean { val first = elements.firstOrNull() return elements.all { element -> areSame(first, element) } } fun areSame(first: PsiElement?, second: PsiElement?): Boolean { return when { first != null && second != null -> PsiEquivalenceUtil.areElementsEquivalent(first, second) first == null && second == null -> true else -> false } } private fun boxedTypeOf(type: PsiType, context: PsiElement): PsiType { return (type as? PsiPrimitiveType)?.getBoxedType(context) ?: type } fun PsiModifierListOwner?.hasExplicitModifier(modifier: String): Boolean { return this?.modifierList?.hasExplicitModifier(modifier) == true } fun DataOutput.withBoxedType(): DataOutput { return when (this) { is VariableOutput -> copy(type = boxedTypeOf(type, variable)) is ExpressionOutput -> copy(type = boxedTypeOf(type, returnExpressions.first())) ArtificialBooleanOutput, is EmptyOutput -> this } } fun areSemanticallySame(statements: List<PsiStatement>): Boolean { if (statements.isEmpty()) return true if (! areSame(statements)) return false val returnExpressions = statements.mapNotNull { statement -> (statement as? PsiReturnStatement)?.returnValue } return returnExpressions.all { expression -> PsiUtil.isConstantExpression(expression) || expression.type == PsiType.NULL } } fun haveReferenceToScope(elements: List<PsiElement>, scope: List<PsiElement>): Boolean { val scopeRange = TextRange(scope.first().textRange.startOffset, scope.last().textRange.endOffset) return elements.asSequence() .flatMap { PsiTreeUtil.findChildrenOfAnyType(it, false, PsiJavaCodeReferenceElement::class.java).asSequence() } .mapNotNull { reference -> reference.resolve() } .any{ referencedElement -> referencedElement.textRange in scopeRange } } fun guessMethodName(options: ExtractOptions): List<String> { val project = options.project val initialMethodNames: MutableSet<String> = LinkedHashSet() val codeStyleManager = JavaCodeStyleManager.getInstance(project) as JavaCodeStyleManagerImpl val returnType = options.dataOutput.type val expression = options.elements.singleOrNull() as? PsiExpression if (expression != null || returnType !is PsiPrimitiveType) { codeStyleManager.suggestVariableName(VariableKind.FIELD, null, expression, returnType).names .forEach { name -> initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD) } } val outVariable = (options.dataOutput as? VariableOutput)?.variable if (outVariable != null) { val outKind = codeStyleManager.getVariableKind(outVariable) val propertyName = codeStyleManager.variableNameToPropertyName(outVariable.name!!, outKind) val names = codeStyleManager.suggestVariableName(VariableKind.FIELD, propertyName, null, outVariable.type).names names.forEach { name -> initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD) } } val normalizedType = (returnType as? PsiEllipsisType)?.toArrayType() ?: returnType val field = JavaPsiFacade.getElementFactory(project).createField("fieldNameToReplace", normalizedType) fun suggestGetterName(name: String): String { field.name = name return GenerateMembersUtil.suggestGetterName(field) } return initialMethodNames.filter { PsiNameHelper.getInstance(project).isIdentifier(it) } .map { propertyName -> suggestGetterName(propertyName) } } }
apache-2.0
f4987ea5ed06861cff0825f1db243318
46.278226
140
0.766121
5.012398
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/propertyDetection.kt
5
22366
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k import com.intellij.psi.* import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.j2k.ast.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName import org.jetbrains.kotlin.load.java.propertyNameBySetMethodName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.utils.addIfNotNull class PropertyInfo( val identifier: Identifier, val isVar: Boolean, val psiType: PsiType, val field: PsiField?, val getMethod: PsiMethod?, val setMethod: PsiMethod?, val isGetMethodBodyFieldAccess: Boolean, val isSetMethodBodyFieldAccess: Boolean, val modifiers: Modifiers, val specialSetterAccess: Modifier?, val superInfo: SuperInfo? ) { init { assert(field != null || getMethod != null || setMethod != null) if (isGetMethodBodyFieldAccess) { assert(field != null && getMethod != null) } if (isSetMethodBodyFieldAccess) { assert(field != null && setMethod != null) } } val name: String get() = identifier.name //TODO: what if annotations are not empty? val needExplicitGetter: Boolean get() { if (getMethod != null) { if (getMethod.hasModifierProperty(PsiModifier.NATIVE)) return true if (getMethod.body != null && !isGetMethodBodyFieldAccess) return true } return modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) } //TODO: what if annotations are not empty? val needExplicitSetter: Boolean get() { if (!isVar) return false if (specialSetterAccess != null) return true if (setMethod != null) { if (setMethod.hasModifierProperty(PsiModifier.NATIVE)) return true if (setMethod.body != null && !isSetMethodBodyFieldAccess) return true } return modifiers.contains(Modifier.EXTERNAL) || modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) } companion object { fun fromFieldWithNoAccessors(field: PsiField, converter: Converter): PropertyInfo { val isVar = field.isVar(converter.referenceSearcher) val isInObject = field.containingClass?.let { converter.shouldConvertIntoObject(it) } == true val modifiers = converter.convertModifiers(field, false, isInObject) return PropertyInfo( field.declarationIdentifier(), isVar, field.type, field, getMethod = null, setMethod = null, isGetMethodBodyFieldAccess = false, isSetMethodBodyFieldAccess = false, modifiers = modifiers, specialSetterAccess = null, superInfo = null ) } } } class PropertyDetectionCache(private val converter: Converter) { private val cache = HashMap<PsiClass, Map<PsiMember, PropertyInfo>>() operator fun get(psiClass: PsiClass): Map<PsiMember, PropertyInfo> { cache[psiClass]?.let { return it } assert(converter.inConversionScope(psiClass)) val detected = PropertyDetector(psiClass, converter).detectProperties() cache[psiClass] = detected return detected } } sealed class SuperInfo { class Property( val isVar: Boolean, val name: String, val hasAbstractModifier: Boolean //TODO: add visibility ) : SuperInfo() object Function : SuperInfo() fun isAbstract(): Boolean { return if (this is Property) hasAbstractModifier else false } } private class PropertyDetector( private val psiClass: PsiClass, private val converter: Converter ) { private val isOpenClass = converter.needOpenModifier(psiClass) fun detectProperties(): Map<PsiMember, PropertyInfo> { val propertyInfos = detectPropertyCandidates() val memberToPropertyInfo = buildMemberToPropertyInfoMap(propertyInfos) dropPropertiesWithConflictingAccessors(memberToPropertyInfo) dropPropertiesConflictingWithFields(memberToPropertyInfo) val mappedFields = memberToPropertyInfo.values .mapNotNull { it.field } .toSet() // map all other fields for (field in psiClass.fields) { if (field !in mappedFields) { memberToPropertyInfo[field] = PropertyInfo.fromFieldWithNoAccessors(field, converter) } } return memberToPropertyInfo } private fun detectPropertyCandidates(): List<PropertyInfo> { val methodsToCheck = ArrayList<Pair<PsiMethod, SuperInfo.Property?>>() for (method in psiClass.methods) { val name = method.name if (!name.startsWith("get") && !name.startsWith("set") && !name.startsWith("is")) continue val superInfo = superInfo(method) if (superInfo is SuperInfo.Function) continue methodsToCheck.add(method to (superInfo as SuperInfo.Property?)) } val propertyNamesWithConflict = HashSet<String>() val propertyNameToGetterInfo = detectGetters(methodsToCheck, propertyNamesWithConflict) val propertyNameToSetterInfo = detectSetters(methodsToCheck, propertyNameToGetterInfo.keys, propertyNamesWithConflict) val propertyNames = propertyNameToGetterInfo.keys + propertyNameToSetterInfo.keys val propertyInfos = ArrayList<PropertyInfo>() for (propertyName in propertyNames) { val getterInfo = propertyNameToGetterInfo[propertyName] var setterInfo = propertyNameToSetterInfo[propertyName] // no property without getter except for overrides if (getterInfo == null && setterInfo!!.method.hierarchicalMethodSignature.superSignatures.isEmpty()) continue if (setterInfo != null && getterInfo != null && setterInfo.method.parameterList.parameters.single().type != getterInfo.method.returnType) { setterInfo = null } var field = getterInfo?.field ?: setterInfo?.field if (field != null) { fun PsiReferenceExpression.canBeReplacedWithFieldAccess(): Boolean { if (getterInfo?.method?.isAncestor(this) != true && setterInfo?.method?.isAncestor(this) != true) return false // not inside property return qualifier == null || qualifier is PsiThisExpression //TODO: check it's correct this } if (getterInfo != null && getterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForReading(it) && !it.canBeReplacedWithFieldAccess() } ) { field = null } } else if (setterInfo != null && setterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForWriting(it) && !it.canBeReplacedWithFieldAccess() } ) { field = null } } } //TODO: no body for getter OR setter val isVar = if (setterInfo != null) true else if (getterInfo!!.superProperty != null && getterInfo.superProperty!!.isVar) true else field != null && field.isVar(converter.referenceSearcher) val type = getterInfo?.method?.returnType ?: setterInfo!!.method.parameterList.parameters.single()?.type!! val superProperty = getterInfo?.superProperty ?: setterInfo?.superProperty val isOverride = superProperty != null val modifiers = convertModifiers(field, getterInfo?.method, setterInfo?.method, isOverride) val propertyAccess = modifiers.accessModifier() val setterAccess = if (setterInfo != null) converter.convertModifiers(setterInfo.method, isMethodInOpenClass = false, isInObject = false).accessModifier() else if (field != null && field.isVar(converter.referenceSearcher)) converter.convertModifiers(field, isMethodInOpenClass = false, isInObject = false).accessModifier() else propertyAccess val specialSetterAccess = setterAccess?.takeIf { it != propertyAccess } val propertyInfo = PropertyInfo( Identifier.withNoPrototype(propertyName), isVar, type, field, getterInfo?.method, setterInfo?.method, field != null && getterInfo?.field == field, field != null && setterInfo?.field == field, modifiers, specialSetterAccess, superProperty ) propertyInfos.add(propertyInfo) } return propertyInfos } private fun buildMemberToPropertyInfoMap(propertyInfos: List<PropertyInfo>): MutableMap<PsiMember, PropertyInfo> { val memberToPropertyInfo = HashMap<PsiMember, PropertyInfo>() for (propertyInfo in propertyInfos) { val field = propertyInfo.field if (field != null) { if (memberToPropertyInfo.containsKey(field)) { // field already in use by other property continue } else { memberToPropertyInfo[field] = propertyInfo } } propertyInfo.getMethod?.let { memberToPropertyInfo[it] = propertyInfo } propertyInfo.setMethod?.let { memberToPropertyInfo[it] = propertyInfo } } return memberToPropertyInfo } private fun detectGetters( methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>, propertyNamesWithConflict: MutableSet<String> ): Map<String, AccessorInfo> { val propertyNameToGetterInfo = LinkedHashMap<String, AccessorInfo>() for ((method, superInfo) in methodsToCheck) { val info = getGetterInfo(method, superInfo) ?: continue val prevInfo = propertyNameToGetterInfo[info.propertyName] if (prevInfo != null) { propertyNamesWithConflict.add(info.propertyName) continue } propertyNameToGetterInfo[info.propertyName] = info } return propertyNameToGetterInfo } private fun detectSetters( methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>, propertyNamesFromGetters: Set<String>, propertyNamesWithConflict: MutableSet<String> ): Map<String, AccessorInfo> { val propertyNameToSetterInfo = LinkedHashMap<String, AccessorInfo>() for ((method, superInfo) in methodsToCheck) { val info = getSetterInfo(method, superInfo, propertyNamesFromGetters) ?: continue val prevInfo = propertyNameToSetterInfo[info.propertyName] if (prevInfo != null) { propertyNamesWithConflict.add(info.propertyName) continue } propertyNameToSetterInfo[info.propertyName] = info } return propertyNameToSetterInfo } private fun dropPropertiesWithConflictingAccessors(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) { val propertyInfos = memberToPropertyInfo.values.distinct() val mappedMethods = propertyInfos.mapNotNull { it.getMethod }.toSet() + propertyInfos.mapNotNull { it.setMethod }.toSet() //TODO: bases val prohibitedSignatures = psiClass.methods .filter { it !in mappedMethods } .map { it.getSignature(PsiSubstitutor.EMPTY) } .toSet() for (propertyInfo in propertyInfos) { if (propertyInfo.modifiers.contains(Modifier.OVERRIDE)) continue // cannot drop override //TODO: test this case val getterName = JvmAbi.getterName(propertyInfo.name) val getterSignature = MethodSignatureUtil.createMethodSignature(getterName, emptyArray(), emptyArray(), PsiSubstitutor.EMPTY) if (getterSignature in prohibitedSignatures) { memberToPropertyInfo.dropProperty(propertyInfo) continue } if (propertyInfo.isVar) { val setterName = JvmAbi.setterName(propertyInfo.name) val setterSignature = MethodSignatureUtil.createMethodSignature( setterName, arrayOf(propertyInfo.psiType), emptyArray(), PsiSubstitutor.EMPTY ) if (setterSignature in prohibitedSignatures) { memberToPropertyInfo.dropProperty(propertyInfo) continue } } } } private fun dropPropertiesConflictingWithFields(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) { val fieldsByName = psiClass.fields.associateBy { it.name } //TODO: fields from base fun isPropertyNameInUse(name: String): Boolean { val field = fieldsByName[name] ?: return false return !memberToPropertyInfo.containsKey(field) } var repeatLoop: Boolean do { repeatLoop = false for (propertyInfo in memberToPropertyInfo.values.distinct()) { if (isPropertyNameInUse(propertyInfo.name)) { //TODO: what about overrides in this case? memberToPropertyInfo.dropProperty(propertyInfo) if (propertyInfo.field != null) { repeatLoop = true // need to repeat loop because a new field appeared } } } } while (repeatLoop) } private fun MutableMap<PsiMember, PropertyInfo>.dropProperty(propertyInfo: PropertyInfo) { propertyInfo.field?.let { remove(it) } propertyInfo.getMethod?.let { remove(it) } propertyInfo.setMethod?.let { remove(it) } } private fun convertModifiers(field: PsiField?, getMethod: PsiMethod?, setMethod: PsiMethod?, isOverride: Boolean): Modifiers { val fieldModifiers = field?.let { converter.convertModifiers(it, isMethodInOpenClass = false, isInObject = false) } ?: Modifiers.Empty val getterModifiers = getMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty val setterModifiers = setMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty val modifiers = ArrayList<Modifier>() //TODO: what if one is abstract and another is not? val isGetterAbstract = getMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true val isSetterAbstract = setMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true if (field == null && isGetterAbstract && isSetterAbstract) { modifiers.add(Modifier.ABSTRACT) } if (getterModifiers.contains(Modifier.OPEN) || setterModifiers.contains(Modifier.OPEN)) { modifiers.add(Modifier.OPEN) } if (isOverride) { modifiers.add(Modifier.OVERRIDE) } when { getMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) setMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) else -> modifiers.addIfNotNull(fieldModifiers.accessModifier()) } val prototypes = listOfNotNull<PsiElement>(field, getMethod, setMethod) .map { PrototypeInfo(it, CommentsAndSpacesInheritance.NO_SPACES) } return Modifiers(modifiers).assignPrototypes(*prototypes.toTypedArray()) } private class AccessorInfo( val method: PsiMethod, val field: PsiField?, val kind: AccessorKind, val propertyName: String, val superProperty: SuperInfo.Property? ) private fun getGetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?): AccessorInfo? { val propertyName = propertyNameByGetMethod(method) ?: return null val field = fieldFromGetterBody(method) return AccessorInfo(method, field, AccessorKind.GETTER, propertyName, superProperty) } private fun getSetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?, propertyNamesFromGetters: Set<String>): AccessorInfo? { val allowedPropertyNames = if (superProperty != null) setOf(superProperty.name) else propertyNamesFromGetters val propertyName = propertyNameBySetMethod(method, allowedPropertyNames) ?: return null val field = fieldFromSetterBody(method) return AccessorInfo(method, field, AccessorKind.SETTER, propertyName, superProperty) } private fun superInfo(getOrSetMethod: PsiMethod): SuperInfo? { //TODO: multiple val superMethod = converter.services.superMethodsSearcher.findDeepestSuperMethods(getOrSetMethod).firstOrNull() ?: return null val containingClass = superMethod.containingClass!! return when { converter.inConversionScope(containingClass) -> { val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod] if (propertyInfo != null) { SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) } else { SuperInfo.Function } } superMethod is KtLightMethod -> { val origin = superMethod.kotlinOrigin if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD)) else SuperInfo.Function } else -> { SuperInfo.Function } } } private fun propertyNameByGetMethod(method: PsiMethod): String? { if (method.isConstructor) return null if (method.parameterList.parametersCount != 0) return null val name = method.name if (!Name.isValidIdentifier(name)) return null val propertyName = propertyNameByGetMethodName(Name.identifier(name))?.identifier ?: return null val returnType = method.returnType ?: return null if (returnType.canonicalText == "void") return null if (method.typeParameters.isNotEmpty()) return null return propertyName } private fun propertyNameBySetMethod(method: PsiMethod, allowedNames: Set<String>): String? { if (method.isConstructor) return null if (method.parameterList.parametersCount != 1) return null val name = method.name if (!Name.isValidIdentifier(name)) return null val propertyName1 = propertyNameBySetMethodName(Name.identifier(name), false)?.identifier val propertyName2 = propertyNameBySetMethodName(Name.identifier(name), true)?.identifier val propertyName = if (propertyName1 != null && propertyName1 in allowedNames) propertyName1 else if (propertyName2 != null && propertyName2 in allowedNames) propertyName2 else return null if (method.returnType?.canonicalText != "void") return null if (method.typeParameters.isNotEmpty()) return null return propertyName } private fun fieldFromGetterBody(getter: PsiMethod): PsiField? { val body = getter.body ?: return null val returnStatement = (body.statements.singleOrNull() as? PsiReturnStatement) ?: return null val isStatic = getter.hasModifierProperty(PsiModifier.STATIC) val field = fieldByExpression(returnStatement.returnValue, isStatic) ?: return null if (field.type != getter.returnType) return null if (converter.typeConverter.variableMutability(field) != converter.typeConverter.methodMutability(getter)) return null return field } private fun fieldFromSetterBody(setter: PsiMethod): PsiField? { val body = setter.body ?: return null val statement = (body.statements.singleOrNull() as? PsiExpressionStatement) ?: return null val assignment = statement.expression as? PsiAssignmentExpression ?: return null if (assignment.operationTokenType != JavaTokenType.EQ) return null val isStatic = setter.hasModifierProperty(PsiModifier.STATIC) val field = fieldByExpression(assignment.lExpression, isStatic) ?: return null val parameter = setter.parameterList.parameters.single() if ((assignment.rExpression as? PsiReferenceExpression)?.resolve() != parameter) return null if (field.type != parameter.type) return null return field } private fun fieldByExpression(expression: PsiExpression?, static: Boolean): PsiField? { val refExpr = expression as? PsiReferenceExpression ?: return null if (static) { if (!refExpr.isQualifierEmptyOrClass(psiClass)) return null } else { if (!refExpr.isQualifierEmptyOrThis()) return null } val field = refExpr.resolve() as? PsiField ?: return null if (field.containingClass != psiClass || field.hasModifierProperty(PsiModifier.STATIC) != static) return null return field } }
apache-2.0
f7894f860232c28e4ce05eb7c1f61177
41.281664
158
0.63914
5.25764
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/viewmodels/SignupViewModelTest.kt
1
5329
package com.kickstarter.viewmodels import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.utils.EventName import com.kickstarter.mock.factories.ApiExceptionFactory import com.kickstarter.mock.factories.ConfigFactory.config import com.kickstarter.mock.services.MockApiClient import com.kickstarter.services.ApiClientType import com.kickstarter.services.apiresponses.AccessTokenEnvelope import com.kickstarter.services.apiresponses.ErrorEnvelope.Companion.builder import org.junit.Test import rx.Observable import rx.observers.TestSubscriber class SignupViewModelTest : KSRobolectricTestCase() { @Test fun testSignupViewModel_FormValidation() { val environment = environment() environment.currentConfig()?.config(config()) val vm = SignupViewModel.ViewModel(environment) val formIsValidTest = TestSubscriber<Boolean>() vm.outputs.formIsValid().subscribe(formIsValidTest) vm.inputs.name("brandon") formIsValidTest.assertNoValues() vm.inputs.email("incorrect@kickstarter") formIsValidTest.assertNoValues() vm.inputs.password("danisawesome") formIsValidTest.assertValues(false) vm.inputs.email("[email protected]") formIsValidTest.assertValues(false, true) } @Test fun testSignupViewModel_SuccessfulSignup() { val environment = environment() environment.currentConfig()?.config(config()) val vm = SignupViewModel.ViewModel(environment) val signupSuccessTest = TestSubscriber<Void>() vm.outputs.signupSuccess().subscribe(signupSuccessTest) val formSubmittingTest = TestSubscriber<Boolean>() vm.outputs.formSubmitting().subscribe(formSubmittingTest) vm.inputs.name("brandon") vm.inputs.email("[email protected]") vm.inputs.email("incorrect@kickstarter") vm.inputs.password("danisawesome") vm.inputs.sendNewslettersClick(true) vm.inputs.signupClick() formSubmittingTest.assertValues(true, false) signupSuccessTest.assertValueCount(1) segmentTrack.assertValues(EventName.PAGE_VIEWED.eventName, EventName.CTA_CLICKED.eventName) } @Test fun testSignupViewModel_ApiValidationError() { val apiClient: ApiClientType = object : MockApiClient() { override fun signup( name: String, email: String, password: String, passwordConfirmation: String, sendNewsletters: Boolean ): Observable<AccessTokenEnvelope> { return Observable.error( ApiExceptionFactory.apiError( builder().httpCode(422).build() ) ) } } val environment = environment().toBuilder().apiClient(apiClient).build() val vm = SignupViewModel.ViewModel(environment) val signupSuccessTest = TestSubscriber<Void>() vm.outputs.signupSuccess().subscribe(signupSuccessTest) val signupErrorTest = TestSubscriber<String>() vm.outputs.errorString().subscribe(signupErrorTest) val formSubmittingTest = TestSubscriber<Boolean>() vm.outputs.formSubmitting().subscribe(formSubmittingTest) vm.inputs.name("brandon") vm.inputs.email("[email protected]") vm.inputs.email("incorrect@kickstarter") vm.inputs.password("danisawesome") vm.inputs.sendNewslettersClick(true) vm.inputs.signupClick() formSubmittingTest.assertValues(true, false) signupSuccessTest.assertValueCount(0) signupErrorTest.assertValueCount(1) segmentTrack.assertValues(EventName.PAGE_VIEWED.eventName, EventName.CTA_CLICKED.eventName) } @Test fun testSignupViewModel_ApiError() { val apiClient: ApiClientType = object : MockApiClient() { override fun signup( name: String, email: String, password: String, passwordConfirmation: String, sendNewsletters: Boolean ): Observable<AccessTokenEnvelope> { return Observable.error(ApiExceptionFactory.badRequestException()) } } val environment = environment().toBuilder().apiClient(apiClient).build() val vm = SignupViewModel.ViewModel(environment) val signupSuccessTest = TestSubscriber<Void>() vm.outputs.signupSuccess().subscribe(signupSuccessTest) val signupErrorTest = TestSubscriber<String>() vm.outputs.errorString().subscribe(signupErrorTest) val formSubmittingTest = TestSubscriber<Boolean>() vm.outputs.formSubmitting().subscribe(formSubmittingTest) vm.inputs.name("brandon") vm.inputs.email("[email protected]") vm.inputs.email("incorrect@kickstarter") vm.inputs.password("danisawesome") vm.inputs.sendNewslettersClick(true) vm.inputs.signupClick() formSubmittingTest.assertValues(true, false) signupSuccessTest.assertValueCount(0) signupErrorTest.assertValueCount(1) segmentTrack.assertValues(EventName.PAGE_VIEWED.eventName, EventName.CTA_CLICKED.eventName) } }
apache-2.0
c012fb4afbe48fc6def623a57907782c
32.727848
99
0.676112
4.966449
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/data/local/implementation/RealmTaskLocalRepository.kt
1
9596
package com.habitrpg.android.habitica.data.local.implementation import com.habitrpg.android.habitica.data.local.TaskLocalRepository import com.habitrpg.android.habitica.models.tasks.* import com.habitrpg.android.habitica.models.user.User import io.reactivex.Flowable import io.reactivex.Maybe import io.realm.Realm import io.realm.RealmObject import io.realm.RealmResults import io.realm.Sort class RealmTaskLocalRepository(realm: Realm) : RealmBaseLocalRepository(realm), TaskLocalRepository { override fun getTasks(taskType: String, userID: String): Flowable<RealmResults<Task>> { if (realm.isClosed) { return Flowable.empty() } return realm.where(Task::class.java) .equalTo("type", taskType) .equalTo("userId", userID) .sort("position", Sort.ASCENDING, "dateCreated", Sort.DESCENDING) .findAll() .asFlowable() .filter { it.isLoaded } .retry(1) } override fun getTasks(userId: String): Flowable<RealmResults<Task>> { if (realm.isClosed) { return Flowable.empty() } return realm.where(Task::class.java).equalTo("userId", userId) .sort("position", Sort.ASCENDING, "dateCreated", Sort.DESCENDING) .findAll() .asFlowable() .filter { it.isLoaded } } override fun saveTasks(userId: String, tasksOrder: TasksOrder, tasks: TaskList) { val sortedTasks = ArrayList<Task>() sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.habits)) sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.dailys)) sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.todos)) sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.rewards)) removeOldTasks(userId, sortedTasks) val allChecklistItems = ArrayList<ChecklistItem>() sortedTasks.forEach { it.checklist?.let { it1 -> allChecklistItems.addAll(it1) } } removeOldChecklists(allChecklistItems) val allReminders = ArrayList<RemindersItem>() sortedTasks.forEach { it.reminders?.let { it1 -> allReminders.addAll(it1) } } removeOldReminders(allReminders) executeTransaction { realm1 -> realm1.insertOrUpdate(sortedTasks) } } override fun saveCompletedTodos(userId: String, tasks: MutableCollection<Task>) { removeCompletedTodos(userId, tasks) executeTransaction { realm1 -> realm1.insertOrUpdate(tasks) } } private fun sortTasks(taskMap: MutableMap<String, Task>, taskOrder: List<String>): List<Task> { val taskList = ArrayList<Task>() var position = 0 for (taskId in taskOrder) { val task = taskMap[taskId] if (task != null) { task.position = position taskList.add(task) position++ taskMap.remove(taskId) } } for (task in taskMap.values) { task.position = position taskList.add(task) position++ } return taskList } private fun removeOldTasks(userID: String, onlineTaskList: List<Task>) { if (realm.isClosed) return val localTasks = realm.where(Task::class.java) .equalTo("userId", userID) .beginGroup() .beginGroup() .equalTo("type", Task.TYPE_TODO) .equalTo("completed", false) .endGroup() .or() .notEqualTo("type", Task.TYPE_TODO) .endGroup() .findAll() .createSnapshot() val tasksToDelete = localTasks.filterNot { onlineTaskList.contains(it) } executeTransaction { for (localTask in tasksToDelete) { localTask.checklist?.deleteAllFromRealm() localTask.reminders?.deleteAllFromRealm() localTask.deleteFromRealm() } } } private fun removeCompletedTodos(userID: String, onlineTaskList: MutableCollection<Task>) { val localTasks = realm.where(Task::class.java) .equalTo("userId", userID) .equalTo("type", Task.TYPE_TODO) .equalTo("completed", true) .findAll() .createSnapshot() val tasksToDelete = localTasks.filterNot { onlineTaskList.contains(it) } executeTransaction { for (localTask in tasksToDelete) { localTask.checklist?.deleteAllFromRealm() localTask.reminders?.deleteAllFromRealm() localTask.deleteFromRealm() } } } private fun removeOldChecklists(onlineItems: List<ChecklistItem>) { val localItems = realm.where(ChecklistItem::class.java).findAll().createSnapshot() val itemsToDelete = localItems.filterNot { onlineItems.contains(it) } executeTransaction { for (item in itemsToDelete) { item.deleteFromRealm() } } } private fun removeOldReminders(onlineReminders: List<RemindersItem>) { val localReminders = realm.where(RemindersItem::class.java).findAll().createSnapshot() val itemsToDelete = localReminders.filterNot { onlineReminders.contains(it) } executeTransaction { for (item in itemsToDelete) { item.deleteFromRealm() } } } override fun deleteTask(taskID: String) { val task = realm.where(Task::class.java).equalTo("id", taskID).findFirstAsync() executeTransaction { if (task.isManaged) { task.deleteFromRealm() } } } override fun getTask(taskId: String): Flowable<Task> { if (realm.isClosed) { return Flowable.empty() } return realm.where(Task::class.java).equalTo("id", taskId).findFirstAsync().asFlowable<RealmObject>() .filter { realmObject -> realmObject.isLoaded } .cast(Task::class.java) } override fun getTaskCopy(taskId: String): Flowable<Task> { return getTask(taskId) .map { task -> return@map if (task.isManaged && task.isValid) { realm.copyFromRealm(task) } else { task } } } override fun markTaskCompleted(taskId: String, isCompleted: Boolean) { val task = realm.where(Task::class.java).equalTo("id", taskId).findFirstAsync() executeTransaction { task.completed = true } } override fun saveReminder(remindersItem: RemindersItem) { executeTransaction { it.insertOrUpdate(remindersItem) } } override fun swapTaskPosition(firstPosition: Int, secondPosition: Int) { val firstTask = realm.where(Task::class.java).equalTo("position", firstPosition).findFirst() val secondTask = realm.where(Task::class.java).equalTo("position", secondPosition).findFirst() if (firstTask != null && secondTask != null && firstTask.isValid && secondTask.isValid) { executeTransaction { firstTask.position = secondPosition secondTask.position = firstPosition } } } override fun getTaskAtPosition(taskType: String, position: Int): Flowable<Task> { return realm.where(Task::class.java).equalTo("type", taskType).equalTo("position", position).findFirstAsync().asFlowable<RealmObject>() .filter { realmObject -> realmObject.isLoaded } .cast(Task::class.java) } override fun updateIsdue(daily: TaskList): Maybe<TaskList> { return Flowable.just(realm.where(Task::class.java).equalTo("type", "daily").findAll()) .firstElement() .map { tasks -> realm.beginTransaction() tasks.filter { daily.tasks.containsKey(it.id) }.forEach { it.isDue = daily.tasks[it.id]?.isDue } realm.commitTransaction() daily } } override fun updateTaskPositions(taskOrder: List<String>) { if (taskOrder.isNotEmpty()) { val tasks = realm.where(Task::class.java).`in`("id", taskOrder.toTypedArray()).findAll() executeTransaction { _ -> tasks.filter { taskOrder.contains(it.id) }.forEach { it.position = taskOrder.indexOf(it.id) } } } } override fun getErroredTasks(userID: String): Flowable<RealmResults<Task>> { return realm.where(Task::class.java) .equalTo("userId", userID) .equalTo("hasErrored", true) .sort("position") .findAll() .asFlowable() .filter { it.isLoaded } .retry(1) } override fun getUser(userID: String): Flowable<User> { return realm.where(User::class.java) .equalTo("id", userID) .findAll() .asFlowable() .filter { realmObject -> realmObject.isLoaded && realmObject.isValid && !realmObject.isEmpty() } .map { users -> users.first() } } }
gpl-3.0
7765d31fb014fd435d24a03dfb5b3732
38.319328
143
0.573155
4.910952
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/export/project/ProjectLoaderV13.kt
1
21488
package com.cout970.modeler.core.export.project import com.cout970.modeler.api.animation.* import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.ITransformation import com.cout970.modeler.api.model.`object`.* import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.modeler.api.model.selection.IObjectRef import com.cout970.modeler.core.animation.* import com.cout970.modeler.core.export.* import com.cout970.modeler.core.log.print import com.cout970.modeler.core.model.Model import com.cout970.modeler.core.model.`object`.GroupTree import com.cout970.modeler.core.model.`object`.Object import com.cout970.modeler.core.model.`object`.ObjectCube import com.cout970.modeler.core.model.`object`.biMultimapOf import com.cout970.modeler.core.model.material.ColoredMaterial import com.cout970.modeler.core.model.material.MaterialNone import com.cout970.modeler.core.model.material.TexturedMaterial import com.cout970.modeler.core.model.mesh.FaceIndex import com.cout970.modeler.core.model.mesh.Mesh import com.cout970.modeler.core.model.selection.ObjectRefNone import com.cout970.modeler.core.project.ProjectProperties import com.cout970.modeler.core.resource.ResourcePath import com.cout970.modeler.util.toResourcePath import com.cout970.vector.api.IQuaternion import com.cout970.vector.api.IVector2 import com.cout970.vector.api.IVector3 import com.google.gson.* import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.toImmutableMap import org.apache.commons.io.FilenameUtils import org.apache.commons.io.IOUtils import java.io.File import java.lang.reflect.Type import java.net.URI import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream object ProjectLoaderV13 { const val VERSION = "1.3" val gson = GsonBuilder() .setExclusionStrategies(ProjectExclusionStrategy()) .setPrettyPrinting() .enableComplexMapKeySerialization() .registerTypeAdapter(UUID::class.java, UUIDSerializer()) .registerTypeAdapter(IVector3::class.java, Vector3Serializer()) .registerTypeAdapter(IVector2::class.java, Vector2Serializer()) .registerTypeAdapter(IQuaternion::class.java, QuaternionSerializer()) .registerTypeAdapter(IGroupRef::class.java, GroupRefSerializer()) .registerTypeAdapter(IMaterialRef::class.java, MaterialRefSerializer()) .registerTypeAdapter(IObjectRef::class.java, ObjectRefSerializer()) .registerTypeAdapter(ITransformation::class.java, TransformationSerializer()) .registerTypeAdapter(ImmutableMap::class.java, ImmutableMapSerializer()) .registerTypeAdapter(ImmutableGroupTree::class.java, ImmutableGroupTreeSerializer()) .registerTypeAdapter(IModel::class.java, ModelSerializer()) .registerTypeAdapter(IMaterial::class.java, MaterialSerializer()) .registerTypeAdapter(IObject::class.java, ObjectSerializer()) .registerTypeAdapter(IGroupTree::class.java, GroupTreeSerializer()) .registerTypeAdapter(IGroup::class.java, serializerOf<Group>()) .registerTypeAdapter(IMesh::class.java, MeshSerializer()) .registerTypeAdapter(IAnimation::class.java, AnimationSerializer()) .registerTypeAdapter(IAnimationRef::class.java, AnimationRefSerializer()) .registerTypeAdapter(AnimationTarget::class.java, AnimationTargetSerializer()) .create()!! fun loadProject(zip: ZipFile, path: String): ProgramSave { val properties = zip.load<ProjectProperties>("project.json", gson) ?: throw IllegalStateException("Missing file 'project.json' inside '$path'") val model = zip.load<IModel>("model.json", gson) ?: throw IllegalStateException("Missing file 'model.json' inside '$path'") val animations = zip.load<List<IAnimation>>("animation.json", gson) ?: emptyList() checkIntegrity(listOf(model.objectMap, model.materialMap, model.groupMap, model.tree, model.animationMap)) checkIntegrity(listOf(animations)) val finalModel = animations.fold(model) { tmpModel, anim -> tmpModel.addAnimation(anim) } return ProgramSave(VERSION, properties, finalModel, emptyList()) } fun saveProject(path: String, save: ProgramSave) { val file = File(path) val tmp = createTempFile(directory = file.parentFile) val zip = ZipOutputStream(tmp.outputStream()) zip.let { save.textures.forEach { mat -> try { val name = FilenameUtils.getName(mat.path.uri.toURL().path) it.putNextEntry(ZipEntry("textures/$name")) IOUtils.copy(mat.path.inputStream(), it) } catch (e: Exception) { e.print() } finally { it.closeEntry() } } it.putNextEntry(ZipEntry("version.json")) it.write(gson.toJson(save.version).toByteArray()) it.closeEntry() it.putNextEntry(ZipEntry("project.json")) it.write(gson.toJson(save.projectProperties).toByteArray()) it.closeEntry() val model = save.textures.fold(save.model) { acc, mat -> val name = FilenameUtils.getName(mat.path.uri.toURL().path) val newPath = File(path).toResourcePath().enterZip("textures/$name") acc.modifyMaterial(mat.copy(path = newPath)) } it.putNextEntry(ZipEntry("model.json")) it.write(gson.toJson(model, IModel::class.java).toByteArray()) it.closeEntry() } zip.close() Files.copy(tmp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) if (tmp != file) { tmp.delete() } } class ModelSerializer : JsonSerializer<IModel>, JsonDeserializer<IModel> { override fun serialize(src: IModel, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonObject().apply { add("objectMap", context.serializeT(src.objectMap)) add("materialMap", context.serializeT(src.materialMap)) add("groupMap", context.serializeT(src.groupMap)) add("animationMap", context.serializeT(src.animationMap)) add("groupTree", context.serializeT(src.tree)) } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IModel { val obj = json.asJsonObject return Model.of( objectMap = context.deserializeT(obj["objectMap"]), materialMap = context.deserializeT(obj["materialMap"]), groupMap = context.deserializeT(obj["groupMap"]), groupTree = context.deserializeT(obj["groupTree"]), animationMap = obj["animationMap"]?.let { context.deserializeT<Map<IAnimationRef, IAnimation>>(it) .filter { (key, value) -> key == value.ref } } ?: emptyMap() ) } } class MaterialSerializer : JsonSerializer<IMaterial>, JsonDeserializer<IMaterial> { override fun serialize(src: IMaterial, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonObject().apply { addProperty("name", src.name) when (src) { is TexturedMaterial -> { addProperty("type", "texture") addProperty("path", src.path.uri.toString()) add("id", context.serializeT(src.id)) } is ColoredMaterial -> { addProperty("type", "color") add("color", context.serializeT(src.color)) add("id", context.serializeT(src.id)) } else -> addProperty("type", "none") } } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IMaterial { val obj = json.asJsonObject if (obj.has("type")) { return when (obj["type"].asString) { "texture" -> { val id = context.deserialize<UUID>(obj["id"], UUID::class.java) TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id) } "color" -> { val id = context.deserialize<UUID>(obj["id"], UUID::class.java) ColoredMaterial(obj["name"].asString, context.deserializeT(obj["color"]), id) } else -> MaterialNone } } return when { obj["name"].asString == "noTexture" -> MaterialNone else -> { val id = context.deserialize<UUID>(obj["id"], UUID::class.java) TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id) } } } } class ObjectSerializer : JsonSerializer<IObject>, JsonDeserializer<IObject> { override fun serialize(src: IObject, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return context.serialize(src).asJsonObject.apply { addProperty("class", src.javaClass.simpleName) } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IObject { val obj = json.asJsonObject return when (obj["class"].asString) { "ObjectCube" -> { ObjectCube( name = context.deserialize(obj["name"], String::class.java), transformation = context.deserialize(obj["transformation"], ITransformation::class.java), material = context.deserialize(obj["material"], IMaterialRef::class.java), textureOffset = context.deserialize(obj["textureOffset"], IVector2::class.java), textureSize = context.deserialize(obj["textureSize"], IVector2::class.java), mirrored = context.deserialize(obj["mirrored"], Boolean::class.java), visible = context.deserialize(obj["visible"], Boolean::class.java), id = context.deserialize(obj["id"], UUID::class.java) ) } "Object" -> Object( name = context.deserialize(obj["name"], String::class.java), mesh = context.deserialize(obj["mesh"], IMesh::class.java), material = context.deserialize(obj["material"], IMaterialRef::class.java), transformation = context.deserialize(obj["transformation"], ITransformation::class.java), visible = context.deserialize(obj["visible"], Boolean::class.java), id = context.deserialize(obj["id"], UUID::class.java) ) else -> throw IllegalStateException("Unknown Class: ${obj["class"]}") } } } class GroupTreeSerializer : JsonSerializer<IGroupTree>, JsonDeserializer<IGroupTree> { data class Aux(val key: IGroupRef, val value: Set<IGroupRef>) data class Aux2(val key: IGroupRef, val value: IGroupRef) override fun serialize(src: IGroupTree, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val tree = src as GroupTree return JsonObject().apply { add("childMap", JsonArray().also { array -> tree.childMap.map { Aux(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) } }) add("parentMap", JsonArray().also { array -> tree.parentMap.map { Aux2(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) } }) } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IGroupTree { if (json.isJsonNull) return GroupTree.emptyTree() val obj = json.asJsonObject val childMapArray = obj["childMap"].asJsonArray val parentMapArray = obj["parentMap"].asJsonArray val childMap = childMapArray .map { context.deserialize(it, Aux::class.java) as Aux } .map { it.key to it.value } .toMap() .toImmutableMap() val parentMap = parentMapArray .map { context.deserialize(it, Aux2::class.java) as Aux2 } .map { it.key to it.value } .toMap() .toImmutableMap() return GroupTree(parentMap, childMap) } } class MeshSerializer : JsonSerializer<IMesh>, JsonDeserializer<IMesh> { override fun serialize(src: IMesh, typeOfSrc: Type?, context: JsonSerializationContext): JsonElement { val pos = context.serializeT(src.pos) val tex = context.serializeT(src.tex) val faces = JsonArray().apply { src.faces.forEach { face -> add(JsonArray().apply { repeat(face.vertexCount) { add(JsonArray().apply { add(face.pos[it]); add(face.tex[it]) }) } }) } } return JsonObject().apply { add("pos", pos) add("tex", tex) add("faces", faces) } } override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext): IMesh { val obj = json.asJsonObject val pos = context.deserializeT<List<IVector3>>(obj["pos"]) val tex = context.deserializeT<List<IVector2>>(obj["tex"]) val faces = obj["faces"].asJsonArray.map { face -> val vertex = face.asJsonArray val posIndices = ArrayList<Int>(vertex.size()) val texIndices = ArrayList<Int>(vertex.size()) repeat(vertex.size()) { val pair = vertex[it].asJsonArray posIndices.add(pair[0].asInt) texIndices.add(pair[1].asInt) } FaceIndex.from(posIndices, texIndices) } return Mesh(pos, tex, faces) } } class AnimationSerializer : JsonSerializer<IAnimation>, JsonDeserializer<IAnimation> { override fun serialize(src: IAnimation, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonObject().apply { add("id", context.serializeT(src.id)) addProperty("name", src.name) addProperty("timeLength", src.timeLength) add("channels", src.channels.values.toJsonArray { v -> JsonObject().apply { add("id", context.serializeT(v.id)) addProperty("name", v.name) addProperty("interpolation", v.interpolation.name) addProperty("enabled", v.enabled) addProperty("type", v.type.toString()) add("keyframes", v.keyframes.toJsonArray { JsonObject().apply { addProperty("time", it.time) add("value", context.serializeT(it.value)) } }) } }) add("mapping", src.channelMapping.entries.toJsonArray { (key, value) -> JsonObject().apply { add("key", context.serializeT(key.id)) add("value", context.serializeT(value)) } }) } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IAnimation { if (json.isJsonNull) return Animation.of() val obj = json.asJsonObject val name = if (obj.has("name")) obj["name"].asString else "animation" val id = if (obj.has("id")) context.deserializeT<UUID>(obj["id"]) else UUID.randomUUID() val channelMapping = obj["mapping"].asJsonArray .map { it.asJsonObject } .map { context.deserializeT<UUID>(it["key"]) to context.deserializeT<AnimationTarget>(it["value"]) } .map { (ChannelRef(it.first) as IChannelRef) to it.second } .toMap() val channels = obj["channels"].asJsonArray.map { elem -> val channel = elem.asJsonObject val interName = channel["interpolation"].asString val keyframesJson = channel["keyframes"].asJsonArray val type = if (channel.has("type")) { ChannelType.valueOf(channel["type"].asString) } else { ChannelType.TRANSLATION } val keyframes = keyframesJson.map { it.asJsonObject }.map { Keyframe( time = it["time"].asFloat, value = context.deserializeT(it["value"]) ) } Channel( name = channel["name"].asString, interpolation = InterpolationMethod.valueOf(interName), enabled = channel["enabled"].asBoolean, keyframes = keyframes, type = type, id = context.deserializeT(channel["id"]) ) } return Animation( channels = channels.associateBy { it.ref }, timeLength = obj["timeLength"].asFloat, channelMapping = channelMapping, name = name, id = id ) } } class ImmutableGroupTreeSerializer : JsonSerializer<ImmutableGroupTree>, JsonDeserializer<ImmutableGroupTree> { data class Aux(val key: IGroupRef, val value: List<IObjectRef>) data class Aux2(val key: IGroupRef, val value: List<IGroupRef>) override fun serialize(src: ImmutableGroupTree, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val a = src.objects.map { Aux(it.first, it.second) } val b = src.groups.map { Aux2(it.first, it.second) } return JsonObject().apply { add("objects", context.serializeT(a)) add("groups", context.serializeT(b)) } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ImmutableGroupTree { val obj = json.asJsonObject val objects = obj["objects"].asJsonArray val groups = obj["groups"].asJsonArray return ImmutableGroupTree( biMultimapOf(*objects.map { context.deserializeT<Aux>(it) }.map { it.key to it.value }.toTypedArray()), biMultimapOf(*groups.map { context.deserializeT<Aux2>(it) }.map { it.key to it.value }.toTypedArray()) ) } } class AnimationTargetSerializer : JsonSerializer<AnimationTarget>, JsonDeserializer<AnimationTarget> { override fun serialize(src: AnimationTarget, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return when (src) { is AnimationTargetGroup -> JsonObject().apply { addProperty("type", "group") add("ref", context.serializeT(src.ref)) } is AnimationTargetObject -> JsonObject().apply { addProperty("type", "objects") add("refs", JsonArray().apply { src.refs.forEach { add(context.serializeT(it)) } }) } } } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): AnimationTarget { if (!json.isJsonObject) return AnimationTargetObject(listOf(ObjectRefNone)) val obj = json.asJsonObject if (!obj.has("type")) return AnimationTargetObject(listOf(ObjectRefNone)) return when (obj["type"].asString) { "group" -> AnimationTargetGroup(context.deserializeT(obj["ref"])) "object" -> AnimationTargetObject(listOf(context.deserializeT(obj["ref"]))) "objects" -> AnimationTargetObject(obj["refs"].asJsonArray.map { context.deserializeT<IObjectRef>(it) }) else -> error("Invalid AnimationTarget type: ${obj["type"].asString}") } } } }
gpl-3.0
395e3c0fd053531b7a93a6f391a3b22d
42.944785
128
0.579486
4.994886
false
false
false
false
zdary/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceEntityStorageImpl.kt
1
54125
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.google.common.collect.ArrayListMultimap import com.google.common.collect.HashBiMap import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ObjectUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.Compressor import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.exceptions.AddDiffException import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException import com.intellij.workspaceModel.storage.impl.exceptions.ReplaceBySourceException import com.intellij.workspaceModel.storage.impl.external.EmptyExternalEntityMapping import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex import it.unimi.dsi.fastutil.ints.IntSet import java.io.File import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import kotlin.io.path.name import kotlin.reflect.KClass import kotlin.reflect.KProperty1 internal data class EntityReferenceImpl<E : WorkspaceEntity>(private val id: EntityId) : EntityReference<E>() { override fun resolve(storage: WorkspaceEntityStorage): E? { @Suppress("UNCHECKED_CAST") return (storage as AbstractEntityStorage).entityDataById(id)?.createEntity(storage) as? E } } internal class WorkspaceEntityStorageImpl constructor( override val entitiesByType: ImmutableEntitiesBarrel, override val refs: RefsTable, override val indexes: StorageIndexes, consistencyCheckingMode: ConsistencyCheckingMode ) : AbstractEntityStorage(consistencyCheckingMode) { // This cache should not be transferred to other versions of storage private val persistentIdCache = ConcurrentHashMap<PersistentEntityId<*>, WorkspaceEntity>() @Suppress("UNCHECKED_CAST") override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entity = persistentIdCache.getOrPut(id) { super.resolve(id) ?: NULl_ENTITY } return if (entity !== NULl_ENTITY) entity as E else null } companion object { private val NULl_ENTITY = ObjectUtils.sentinel("null entity", WorkspaceEntity::class.java) val EMPTY = WorkspaceEntityStorageImpl(ImmutableEntitiesBarrel.EMPTY, RefsTable(), StorageIndexes.EMPTY, ConsistencyCheckingMode.default()) } } internal class WorkspaceEntityStorageBuilderImpl( override val entitiesByType: MutableEntitiesBarrel, override val refs: MutableRefsTable, override val indexes: MutableStorageIndexes, consistencyCheckingMode: ConsistencyCheckingMode ) : WorkspaceEntityStorageBuilder, AbstractEntityStorage(consistencyCheckingMode) { internal val changeLog = WorkspaceBuilderChangeLog() internal fun incModificationCount() { this.changeLog.modificationCount++ } override val modificationCount: Long get() = this.changeLog.modificationCount override fun <M : ModifiableWorkspaceEntity<T>, T : WorkspaceEntity> addEntity(clazz: Class<M>, source: EntitySource, initializer: M.() -> Unit): T { // Extract entity classes val unmodifiableEntityClass = ClassConversion.modifiableEntityToEntity(clazz.kotlin).java val entityDataClass = ClassConversion.entityToEntityData(unmodifiableEntityClass.kotlin) val unmodifiableEntityClassId = unmodifiableEntityClass.toClassId() // Construct entity data val pEntityData = entityDataClass.java.getDeclaredConstructor().newInstance() pEntityData.entitySource = source // Add entity data to the structure entitiesByType.add(pEntityData, unmodifiableEntityClassId) // Wrap it with modifiable and execute initialization code @Suppress("UNCHECKED_CAST") val modifiableEntity = pEntityData.wrapAsModifiable(this) as M // create modifiable after adding entity data to set (modifiableEntity as ModifiableWorkspaceEntityBase<*>).allowModifications { modifiableEntity.initializer() } // Check for persistent id uniqueness pEntityData.persistentId(this)?.let { persistentId -> val ids = indexes.persistentIdIndex.getIdsByEntry(persistentId) if (ids != null && ids.isNotEmpty()) { // Oh oh. This persistent id exists already // Fallback strategy: remove existing entity with all it's references val existingEntityData = entityDataByIdOrDie(ids.single()) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error(""" addEntity: persistent id already exists. Replacing entity with the new one. Persistent id: $persistentId Existing entity data: $existingEntityData New entity data: $pEntityData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(persistentId)) } } // Add the change to changelog createAddEvent(pEntityData) // Update indexes indexes.entityAdded(pEntityData, this) LOG.debug { "New entity added: $clazz-${pEntityData.id}" } return pEntityData.createEntity(this) } override fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T { // Get entity data that will be modified @Suppress("UNCHECKED_CAST") val copiedData = entitiesByType.getEntityDataForModification((e as WorkspaceEntityBase).id) as WorkspaceEntityData<T> @Suppress("UNCHECKED_CAST") val modifiableEntity = copiedData.wrapAsModifiable(this) as M val beforePersistentId = if (e is WorkspaceEntityWithPersistentId) e.persistentId() else null val entityId = e.id val beforeParents = this.refs.getParentRefsOfChild(entityId) val beforeChildren = this.refs.getChildrenRefsOfParentBy(entityId).flatMap { (key, value) -> value.map { key to it } } // Execute modification code (modifiableEntity as ModifiableWorkspaceEntityBase<*>).allowModifications { modifiableEntity.change() } // Check for persistent id uniqueness if (beforePersistentId != null) { val newPersistentId = copiedData.persistentId(this) if (newPersistentId != null) { val ids = indexes.persistentIdIndex.getIdsByEntry(newPersistentId) if (beforePersistentId != newPersistentId && ids != null && ids.isNotEmpty()) { // Oh oh. This persistent id exists already. // Remove an existing entity and replace it with the new one. val existingEntityData = entityDataByIdOrDie(ids.single()) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error(""" modifyEntity: persistent id already exists. Replacing entity with the new one. Old entity: $existingEntityData Persistent id: $copiedData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(newPersistentId)) } } else { LOG.error("Persistent id expected for entity: $copiedData") } } // Add an entry to changelog addReplaceEvent(this, entityId, beforeChildren, beforeParents, copiedData) val updatedEntity = copiedData.createEntity(this) updatePersistentIdIndexes(updatedEntity, beforePersistentId, copiedData) return updatedEntity } internal fun <T : WorkspaceEntity> updatePersistentIdIndexes(updatedEntity: WorkspaceEntity, beforePersistentId: PersistentEntityId<*>?, copiedData: WorkspaceEntityData<T>) { val entityId = (updatedEntity as WorkspaceEntityBase).id if (updatedEntity is WorkspaceEntityWithPersistentId) { val newPersistentId = updatedEntity.persistentId() if (beforePersistentId != null && beforePersistentId != newPersistentId) { indexes.persistentIdIndex.index(entityId, newPersistentId) updateComposedIds(beforePersistentId, newPersistentId) } } indexes.simpleUpdateSoftReferences(copiedData) } private fun updateComposedIds(beforePersistentId: PersistentEntityId<*>, newPersistentId: PersistentEntityId<*>) { val idsWithSoftRef = HashSet(indexes.softLinks.getIdsByEntry(beforePersistentId)) for (entityId in idsWithSoftRef) { val entity = this.entitiesByType.getEntityDataForModification(entityId) val editingBeforePersistentId = entity.persistentId(this) (entity as SoftLinkable).updateLink(beforePersistentId, newPersistentId) // Add an entry to changelog this.changeLog.addReplaceEvent(entityId, entity, emptyList(), emptyList(), emptyMap()) updatePersistentIdIndexes(entity.createEntity(this), editingBeforePersistentId, entity) } } override fun <T : WorkspaceEntity> changeSource(e: T, newSource: EntitySource): T { @Suppress("UNCHECKED_CAST") val copiedData = entitiesByType.getEntityDataForModification((e as WorkspaceEntityBase).id) as WorkspaceEntityData<T> copiedData.entitySource = newSource val entityId = copiedData.createEntityId() this.changeLog.addChangeSourceEvent(entityId, copiedData) indexes.entitySourceIndex.index(entityId, newSource) newSource.virtualFileUrl?.let { indexes.virtualFileIndex.index(entityId, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) } return copiedData.createEntity(this) } override fun removeEntity(e: WorkspaceEntity) { LOG.debug { "Removing ${e.javaClass}..." } e as WorkspaceEntityBase val removedEntities = removeEntity(e.id) removedEntities.forEach { LOG.debug { "Cascade removing: ${ClassToIntConverter.getClassOrDie(it.clazz)}-${it.arrayId}" } this.changeLog.addRemoveEvent(it) } } private fun ArrayListMultimap<Any, Pair<WorkspaceEntityData<out WorkspaceEntity>, EntityId>>.find(entity: WorkspaceEntityData<out WorkspaceEntity>, storage: AbstractEntityStorage): Pair<WorkspaceEntityData<out WorkspaceEntity>, EntityId>? { val possibleValues = this[entity.identificator(storage)] val persistentId = entity.persistentId(storage) return if (persistentId != null) { possibleValues.singleOrNull() } else { possibleValues.find { it.first == entity } } } /** * * Here: identificator means [hashCode] or ([PersistentEntityId] in case it exists) * * Plan of [replaceBySource]: * - Traverse all entities of the current builder and save the matched (by [sourceFilter]) to map by identificator. * - In the current builder, remove all references *between* matched entities. If a matched entity has a reference to an unmatched one, * save the unmatched entity to map by identificator. * We'll check if the reference to unmatched reference is still valid after replacing. * - Traverse all matched entities in the [replaceWith] storage. Detect if the particular entity exists in current builder using identificator. * Perform add / replace operation if necessary (remove operation will be later). * - Remove all entities that weren't found in [replaceWith] storage. * - Restore entities between matched and unmatched entities. At this point the full action may fail (e.g. if an entity in [replaceWith] * has a reference to an entity that doesn't exist in current builder. * - Restore references between matched entities. * * * TODO Spacial cases: when source filter returns true for all entity sources. */ override fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: WorkspaceEntityStorage) { replaceWith as AbstractEntityStorage val initialStore = if (consistencyCheckingMode != ConsistencyCheckingMode.DISABLED) this.toStorage() else null LOG.debug { "Performing replace by source" } // Map of entities in THIS builder with the entitySource that matches the predicate. Key is either hashCode or PersistentId val localMatchedEntities = ArrayListMultimap.create<Any, Pair<WorkspaceEntityData<out WorkspaceEntity>, EntityId>>() // Map of entities in replaceWith store with the entitySource that matches the predicate. Key is either hashCode or PersistentId val replaceWithMatchedEntities = ArrayListMultimap.create<Any, EntityId>() // Map of entities in THIS builder that have a reference to matched entity. Key is either hashCode or PersistentId val localUnmatchedReferencedNodes = ArrayListMultimap.create<Any, EntityId>() // Association of the EntityId in the local store to the EntityId in the remote store val replaceMap = HashBiMap.create<EntityId, EntityId>() LOG.debug { "1) Traverse all entities and store matched only" } this.indexes.entitySourceIndex.entries().filter { sourceFilter(it) }.forEach { entitySource -> this.indexes.entitySourceIndex.getIdsByEntry(entitySource)?.forEach { val entityData = this.entityDataByIdOrDie(it) localMatchedEntities.put(entityData.identificator(this), entityData to it) } } LOG.debug { "1.1) Cleanup references" } // If the reference leads to the matched entity, we can safely remove this reference. // If the reference leads to the unmatched entity, we should save the entity to try to restore the reference later. for ((_, entityId) in localMatchedEntities.values()) { // Traverse parents of the entity for ((connectionId, parentId) in this.refs.getParentRefsOfChild(entityId)) { val parentEntity = this.entityDataByIdOrDie(parentId) if (sourceFilter(parentEntity.entitySource)) { // Remove the connection between matched entities this.refs.removeParentToChildRef(connectionId, parentId, entityId) } else { // Save the entity for restoring reference to it later localUnmatchedReferencedNodes.put(parentEntity.identificator(this), parentId) } } // TODO: 29.04.2020 Do we need iterate over children and parents? Maybe only parents would be enough? // Traverse children of the entity for ((connectionId, childrenIds) in this.refs.getChildrenRefsOfParentBy(entityId)) { for (childId in childrenIds) { val childEntity = this.entityDataByIdOrDie(childId) if (sourceFilter(childEntity.entitySource)) { // Remove the connection between matched entities this.refs.removeParentToChildRef(connectionId, entityId, childId) } else { // Save the entity for restoring reference to it later localUnmatchedReferencedNodes.put(childEntity.identificator(this), childId) } } } } LOG.debug { "2) Traverse entities of replaceWith store" } // 2) Traverse entities of the enemy // and trying to detect whenever the entity already present in the local builder or not. // If the entity already exists we optionally perform replace operation (or nothing), // otherwise we add the entity. // Local entities that don't exist in replaceWith store will be removed later. for (replaceWithEntitySource in replaceWith.indexes.entitySourceIndex.entries().filter { sourceFilter(it) }) { val entityDataList = replaceWith.indexes.entitySourceIndex .getIdsByEntry(replaceWithEntitySource) ?.map { replaceWith.entityDataByIdOrDie(it) to it } ?: continue for ((matchedEntityData, matchedEntityId) in entityDataList) { replaceWithMatchedEntities.put(matchedEntityData.identificator(replaceWith), matchedEntityId) // Find if the entity exists in local store val localNodeAndId = localMatchedEntities.find(matchedEntityData, replaceWith) // We should check if the issue still exists in this builder because it can be removed if it's referenced by another entity // that had persistent id clash. val entityStillExists = localNodeAndId?.second?.let { this.entityDataById(it) != null } ?: false if (entityStillExists && localNodeAndId != null) { val (localNode, localNodeEntityId) = localNodeAndId // This entity already exists. Store the association of EntityIdss replaceMap[localNodeEntityId] = matchedEntityId val dataDiffersByProperties = !localNode.equalsIgnoringEntitySource(matchedEntityData) val dataDiffersByEntitySource = localNode.entitySource != matchedEntityData.entitySource if (localNode.hasPersistentId() && (dataDiffersByEntitySource || dataDiffersByProperties) && matchedEntityData.entitySource !is DummyParentEntitySource) { // Entity exists in local store, but has changes. Generate replace operation replaceOperation(matchedEntityData, replaceWith, localNode, matchedEntityId, dataDiffersByProperties, dataDiffersByEntitySource) } if (localNode == matchedEntityData) { this.indexes.updateExternalMappingForEntityId(matchedEntityId, localNodeEntityId, replaceWith.indexes) } // Remove added entity localMatchedEntities.remove(localNode.identificator(this), localNodeAndId) } else { // This is a new entity for this store. Perform add operation val persistentId = matchedEntityData.persistentId(this) if (persistentId != null) { val existingEntity = this.indexes.persistentIdIndex.getIdsByEntry(persistentId)?.firstOrNull() if (existingEntity != null) { // Bad news, we have this persistent id already. CPP-22547 // This may happened if local entity has entity source and remote entity has a different entity source // Technically we should throw an exception, but now we just remove local entity // Entity exists in local store, but has changes. Generate replace operation val localNode = this.entityDataByIdOrDie(existingEntity) val dataDiffersByProperties = !localNode.equalsIgnoringEntitySource(matchedEntityData) val dataDiffersByEntitySource = localNode.entitySource != matchedEntityData.entitySource replaceOperation(matchedEntityData, replaceWith, localNode, matchedEntityId, dataDiffersByProperties, dataDiffersByEntitySource) replaceMap[existingEntity] = matchedEntityId continue } } val entityClass = ClassConversion.entityDataToEntity(matchedEntityData.javaClass).toClassId() val newEntity = this.entitiesByType.cloneAndAdd(matchedEntityData, entityClass) val newEntityId = matchedEntityId.copy(arrayId = newEntity.id) replaceMap[newEntityId] = matchedEntityId this.indexes.virtualFileIndex.updateIndex(matchedEntityId, newEntityId, replaceWith.indexes.virtualFileIndex) replaceWith.indexes.entitySourceIndex.getEntryById(matchedEntityId)?.also { this.indexes.entitySourceIndex.index(newEntityId, it) } replaceWith.indexes.persistentIdIndex.getEntryById(matchedEntityId)?.also { this.indexes.persistentIdIndex.index(newEntityId, it) } this.indexes.updateExternalMappingForEntityId(matchedEntityId, newEntityId, replaceWith.indexes) if (newEntity is SoftLinkable) indexes.updateSoftLinksIndex(newEntity) createAddEvent(newEntity) } } } LOG.debug { "3) Remove old entities" } // After previous operation localMatchedEntities contain only entities that exist in local store, but don't exist in replaceWith store. // Those entities should be just removed. for ((localEntity, entityId) in localMatchedEntities.values()) { val entityClass = ClassConversion.entityDataToEntity(localEntity.javaClass).toClassId() this.entitiesByType.remove(localEntity.id, entityClass) indexes.removeFromIndices(entityId) if (localEntity is SoftLinkable) indexes.removeFromSoftLinksIndex(localEntity) this.changeLog.addRemoveEvent(entityId) } val lostChildren = HashSet<EntityId>() LOG.debug { "4) Restore references between matched and unmatched entities" } // At this moment the operation may fail because of inconsistency. // E.g. after this operation we can't have non-null references without corresponding entity. // This may happen if we remove the matched entity, but don't have a replacement for it. for (unmatchedId in localUnmatchedReferencedNodes.values()) { val replaceWithUnmatchedEntity = replaceWith.entityDataById(unmatchedId) if (replaceWithUnmatchedEntity == null || replaceWithUnmatchedEntity != this.entityDataByIdOrDie(unmatchedId)) { // Okay, replaceWith storage doesn't have this "unmatched" entity at all. // TODO: 14.04.2020 Don't forget about entities with persistence id for ((connectionId, parentId) in this.refs.getParentRefsOfChild(unmatchedId)) { val parent = this.entityDataById(parentId) // TODO: 29.04.2020 Review and write tests if (parent == null) { if (connectionId.canRemoveParent()) { this.refs.removeParentToChildRef(connectionId, parentId, unmatchedId) } else { this.refs.removeParentToChildRef(connectionId, parentId, unmatchedId) lostChildren += unmatchedId } } } for ((connectionId, childIds) in this.refs.getChildrenRefsOfParentBy(unmatchedId)) { for (childId in childIds) { val child = this.entityDataById(childId) if (child == null) { if (connectionId.canRemoveChild()) { this.refs.removeParentToChildRef(connectionId, unmatchedId, childId) } else rbsFailedAndReport("Cannot remove link to child entity. $connectionId", sourceFilter, initialStore, replaceWith) } } } } else { // ----------------- Update parent references --------------- val removedConnections = HashMap<ConnectionId, EntityId>() // Remove parents in local store for ((connectionId, parentId) in this.refs.getParentRefsOfChild(unmatchedId)) { val parentData = this.entityDataById(parentId) if (parentData != null && !sourceFilter(parentData.entitySource)) continue this.refs.removeParentToChildRef(connectionId, parentId, unmatchedId) removedConnections[connectionId] = parentId } // Transfer parents from replaceWith storage for ((connectionId, parentId) in replaceWith.refs.getParentRefsOfChild(unmatchedId)) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(parentId).entitySource)) continue val localParentId = replaceMap.inverse().getValue(parentId) this.refs.updateParentOfChild(connectionId, unmatchedId, localParentId) removedConnections.remove(connectionId) } // TODO: 05.06.2020 The similar logic should exist for children references // Check not restored connections for ((connectionId, parentId) in removedConnections) { if (!connectionId.canRemoveParent()) rbsFailedAndReport("Cannot restore connection to $parentId; $connectionId", sourceFilter, initialStore, replaceWith) } // ----------------- Update children references ----------------------- for ((connectionId, childrenId) in this.refs.getChildrenRefsOfParentBy(unmatchedId)) { for (childId in childrenId) { val childData = this.entityDataById(childId) if (childData != null && !sourceFilter(childData.entitySource)) continue this.refs.removeParentToChildRef(connectionId, unmatchedId, childId) } } for ((connectionId, childrenId) in replaceWith.refs.getChildrenRefsOfParentBy(unmatchedId)) { for (childId in childrenId) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(childId).entitySource)) continue val localChildId = replaceMap.inverse().getValue(childId) this.refs.updateParentOfChild(connectionId, localChildId, unmatchedId) } } } } // Some children left without parents. We should delete these children as well. for (entityId in lostChildren) { if (this.refs.getParentRefsOfChild(entityId).any { !it.key.isChildNullable }) { rbsFailedAndReport("Trying to remove lost children. Cannot perform operation because some parents have strong ref to this child", sourceFilter, initialStore, replaceWith) } removeEntity(entityId) } LOG.debug { "5) Restore references in matching ids" } for (nodeId in replaceWithMatchedEntities.values()) { for ((connectionId, parentId) in replaceWith.refs.getParentRefsOfChild(nodeId)) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(parentId).entitySource)) { // replaceWith storage has a link to unmatched entity. We should check if we can "transfer" this link to the current storage if (!connectionId.isParentNullable) { val localParent = this.entityDataById(parentId) if (localParent == null) rbsFailedAndReport( "Cannot link entities. Child entity doesn't have a parent after operation; $connectionId", sourceFilter, initialStore, replaceWith) val localChildId = replaceMap.inverse().getValue(nodeId) this.refs.updateParentOfChild(connectionId, localChildId, parentId) } continue } val localChildId = replaceMap.inverse().getValue(nodeId) val localParentId = replaceMap.inverse().getValue(parentId) this.refs.updateParentOfChild(connectionId, localChildId, localParentId) } } // Assert consistency if (!this.brokenConsistency && !replaceWith.brokenConsistency) { this.assertConsistencyInStrictMode("Check after replaceBySource", sourceFilter, initialStore, replaceWith) } else { this.brokenConsistency = true } LOG.debug { "Replace by source finished" } } private fun replaceOperation(matchedEntityData: WorkspaceEntityData<out WorkspaceEntity>, replaceWith: AbstractEntityStorage, localNode: WorkspaceEntityData<out WorkspaceEntity>, matchedEntityId: EntityId, dataDiffersByProperties: Boolean, dataDiffersByEntitySource: Boolean) { val clonedEntity = matchedEntityData.clone() val persistentIdBefore = matchedEntityData.persistentId(replaceWith) ?: error("PersistentId expected for $matchedEntityData") clonedEntity.id = localNode.id val clonedEntityId = matchedEntityId.copy(arrayId = clonedEntity.id) this.entitiesByType.replaceById(clonedEntity, clonedEntityId.clazz) updatePersistentIdIndexes(clonedEntity.createEntity(this), persistentIdBefore, clonedEntity) this.indexes.virtualFileIndex.updateIndex(matchedEntityId, clonedEntityId, replaceWith.indexes.virtualFileIndex) replaceWith.indexes.entitySourceIndex.getEntryById(matchedEntityId)?.also { this.indexes.entitySourceIndex.index(clonedEntityId, it) } this.indexes.updateExternalMappingForEntityId(matchedEntityId, clonedEntityId, replaceWith.indexes) if (dataDiffersByProperties) { this.changeLog.addReplaceEvent(clonedEntityId, clonedEntity, emptyList(), emptyList(), emptyMap()) } if (dataDiffersByEntitySource) { this.changeLog.addChangeSourceEvent(clonedEntityId, clonedEntity) } } private fun rbsFailedAndReport(message: String, sourceFilter: (EntitySource) -> Boolean, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage) { reportConsistencyIssue(message, ReplaceBySourceException(message), sourceFilter, left, right, this) } internal fun addDiffAndReport(message: String, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage) { reportConsistencyIssue(message, AddDiffException(message), null, left, right, this) } sealed class EntityDataChange<T : WorkspaceEntityData<out WorkspaceEntity>> { data class Added<T : WorkspaceEntityData<out WorkspaceEntity>>(val entity: T) : EntityDataChange<T>() data class Removed<T : WorkspaceEntityData<out WorkspaceEntity>>(val entity: T) : EntityDataChange<T>() data class Replaced<T : WorkspaceEntityData<out WorkspaceEntity>>(val oldEntity: T, val newEntity: T) : EntityDataChange<T>() } override fun collectChanges(original: WorkspaceEntityStorage): Map<Class<*>, List<EntityChange<*>>> { val originalImpl = original as AbstractEntityStorage val res = HashMap<Class<*>, MutableList<EntityChange<*>>>() for ((entityId, change) in this.changeLog.changeLog) { when (change) { is ChangeEntry.AddEntity<*> -> { val addedEntity = change.entityData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Added(addedEntity)) } is ChangeEntry.RemoveEntity -> { val removedData = originalImpl.entityDataById(change.id) ?: continue val removedEntity = removedData.createEntity(originalImpl) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Removed(removedEntity)) } is ChangeEntry.ReplaceEntity<*> -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ChangeEntitySource<*> -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ReplaceAndChangeSource<*> -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.dataChange.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } } } return res } override fun toStorage(): WorkspaceEntityStorageImpl { val newEntities = entitiesByType.toImmutable() val newRefs = refs.toImmutable() val newIndexes = indexes.toImmutable() return WorkspaceEntityStorageImpl(newEntities, newRefs, newIndexes, consistencyCheckingMode) } override fun isEmpty(): Boolean = this.changeLog.changeLog.isEmpty() override fun addDiff(diff: WorkspaceEntityStorageDiffBuilder) { diff as WorkspaceEntityStorageBuilderImpl AddDiffOperation(this, diff).addDiff() } @Suppress("UNCHECKED_CAST") override fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T> { val mapping = indexes.externalMappings.computeIfAbsent( identifier) { MutableExternalEntityMappingImpl<T>() } as MutableExternalEntityMappingImpl<T> mapping.setTypedEntityStorage(this) return mapping } override fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex { val virtualFileIndex = indexes.virtualFileIndex virtualFileIndex.setTypedEntityStorage(this) return virtualFileIndex } fun removeExternalMapping(identifier: String) { indexes.externalMappings[identifier]?.clearMapping() } // modificationCount is not incremented internal fun removeEntity(idx: EntityId): Collection<EntityId> { val accumulator: MutableSet<EntityId> = mutableSetOf(idx) accumulateEntitiesToRemove(idx, accumulator) for (id in accumulator) { val entityData = entityDataById(id) if (entityData is SoftLinkable) indexes.removeFromSoftLinksIndex(entityData) entitiesByType.remove(id.arrayId, id.clazz) } // Update index // Please don't join it with the previous loop for (id in accumulator) indexes.removeFromIndices(id) return accumulator } private fun WorkspaceEntityData<*>.hasPersistentId(): Boolean { val entity = this.createEntity(this@WorkspaceEntityStorageBuilderImpl) return entity is WorkspaceEntityWithPersistentId } private fun WorkspaceEntityData<*>.identificator(storage: AbstractEntityStorage): Any { return this.persistentId(storage) ?: this.hashCode() } internal fun <T : WorkspaceEntity> createAddEvent(pEntityData: WorkspaceEntityData<T>) { val entityId = pEntityData.createEntityId() this.changeLog.addAddEvent(entityId, pEntityData) } /** * Cleanup references and accumulate hard linked entities in [accumulator] */ private fun accumulateEntitiesToRemove(id: EntityId, accumulator: MutableSet<EntityId>) { val children = refs.getChildrenRefsOfParentBy(id) for ((connectionId, childrenIds) in children) { for (childId in childrenIds) { if (childId in accumulator) continue accumulator.add(childId) accumulateEntitiesToRemove(childId, accumulator) refs.removeRefsByParent(connectionId, id) } } val parents = refs.getParentRefsOfChild(id) for ((connectionId, parent) in parents) { refs.removeParentToChildRef(connectionId, parent, id) } } companion object { private val LOG = logger<WorkspaceEntityStorageBuilderImpl>() fun create(consistencyCheckingMode: ConsistencyCheckingMode): WorkspaceEntityStorageBuilderImpl { return from(WorkspaceEntityStorageImpl.EMPTY, consistencyCheckingMode) } fun from(storage: WorkspaceEntityStorage, consistencyCheckingMode: ConsistencyCheckingMode): WorkspaceEntityStorageBuilderImpl { storage as AbstractEntityStorage return when (storage) { is WorkspaceEntityStorageImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType) val copiedRefs = MutableRefsTable.from(storage.refs) val copiedIndex = storage.indexes.toMutable() WorkspaceEntityStorageBuilderImpl(copiedBarrel, copiedRefs, copiedIndex, consistencyCheckingMode) } is WorkspaceEntityStorageBuilderImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType.toImmutable()) val copiedRefs = MutableRefsTable.from(storage.refs.toImmutable()) val copiedIndexes = storage.indexes.toMutable() WorkspaceEntityStorageBuilderImpl(copiedBarrel, copiedRefs, copiedIndexes, consistencyCheckingMode) } } } internal fun <T : WorkspaceEntity> addReplaceEvent(builder: WorkspaceEntityStorageBuilderImpl, entityId: EntityId, beforeChildren: List<Pair<ConnectionId, EntityId>>, beforeParents: Map<ConnectionId, EntityId>, copiedData: WorkspaceEntityData<T>) { val parents = builder.refs.getParentRefsOfChild(entityId) val unmappedChildren = builder.refs.getChildrenRefsOfParentBy(entityId) val children = unmappedChildren.flatMap { (key, value) -> value.map { key to it } } // Collect children changes val addedChildren = (children.toSet() - beforeChildren.toSet()).toList() val removedChildren = (beforeChildren.toSet() - children.toSet()).toList() // Collect parent changes val parentsMapRes: MutableMap<ConnectionId, EntityId?> = beforeParents.toMutableMap() for ((connectionId, parentId) in parents) { val existingParent = parentsMapRes[connectionId] if (existingParent != null) { if (existingParent == parentId) { parentsMapRes.remove(connectionId, parentId) } else { parentsMapRes[connectionId] = parentId } } else { parentsMapRes[connectionId] = parentId } } val removedKeys = beforeParents.keys - parents.keys removedKeys.forEach { parentsMapRes[it] = null } builder.changeLog.addReplaceEvent(entityId, copiedData, addedChildren, removedChildren, parentsMapRes) } } } internal sealed class AbstractEntityStorage(internal val consistencyCheckingMode: ConsistencyCheckingMode) : WorkspaceEntityStorage { internal abstract val entitiesByType: EntitiesBarrel internal abstract val refs: AbstractRefsTable internal abstract val indexes: StorageIndexes internal var brokenConsistency: Boolean = false override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> { @Suppress("UNCHECKED_CAST") return entitiesByType[entityClass.toClassId()]?.all()?.map { it.createEntity(this) } as? Sequence<E> ?: emptySequence() } internal fun entityDataById(id: EntityId): WorkspaceEntityData<out WorkspaceEntity>? = entitiesByType[id.clazz]?.get(id.arrayId) internal fun entityDataByIdOrDie(id: EntityId): WorkspaceEntityData<out WorkspaceEntity> { return entitiesByType[id.clazz]?.get(id.arrayId) ?: error("Cannot find an entity by id $id") } override fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>, property: KProperty1<R, EntityReference<E>>): Sequence<R> { TODO() //return entities(entityClass.java).filter { property.get(it).resolve(this) == e } } override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> { val classId = entityClass.toClassId() @Suppress("UNCHECKED_CAST") return indexes.softLinks.getIdsByEntry(id).asSequence() .filter { it.clazz == classId } .map { entityDataByIdOrDie(it).createEntity(this) as R } } override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null if (entityIds.isEmpty()) return null if (entityIds.size > 1) { val entities = entityIds.associateWith { this.entityDataById(it) }.entries.joinToString( "\n") { (k, v) -> "$k : $v : EntitySource: ${v?.entitySource}" } LOG.error("""Cannot resolve persistent id $id. The store contains ${entityIds.size} associated entities: |$entities |Broken consistency: $brokenConsistency """.trimMargin()) @Suppress("UNCHECKED_CAST") return entityDataById(entityIds.first())?.createEntity(this) as E? } val entityId = entityIds.single() @Suppress("UNCHECKED_CAST") return entityDataById(entityId)?.createEntity(this) as E? } // Do not remove cast to Class<out TypedEntity>. kotlin fails without it @Suppress("USELESS_CAST") override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source -> indexes.entitySourceIndex .getIdsByEntry(source)!!.map { this.entityDataByIdOrDie(it).createEntity(this) } .groupBy { it.javaClass as Class<out WorkspaceEntity> } } } @Suppress("UNCHECKED_CAST") override fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T> { val index = indexes.externalMappings[identifier] as? ExternalEntityMappingImpl<T> if (index == null) return EmptyExternalEntityMapping as ExternalEntityMapping<T> index.setTypedEntityStorage(this) return index } override fun getVirtualFileUrlIndex(): VirtualFileUrlIndex { indexes.virtualFileIndex.setTypedEntityStorage(this) return indexes.virtualFileIndex } override fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E> = EntityReferenceImpl((e as WorkspaceEntityBase).id) internal fun assertConsistency() { entitiesByType.assertConsistency(this) // Rules: // 1) Refs should not have links without a corresponding entity // 1.1) For abstract containers: EntityId has the class of ConnectionId // 2) There is no child without a parent under the hard reference refs.oneToManyContainer.forEach { (connectionId, map) -> // Assert correctness of connection id assert(connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY) // 1) Refs should not have links without a corresponding entity map.forEachKey { childId, parentId -> assertResolvable(connectionId.parentClass, parentId) assertResolvable(connectionId.childClass, childId) } // 2) All children should have a parent if the connection has a restriction for that if (!connectionId.isParentNullable) { checkStrongConnection(map.keys, connectionId.childClass, connectionId.parentClass) } } refs.oneToOneContainer.forEach { (connectionId, map) -> // Assert correctness of connection id assert(connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ONE) // 1) Refs should not have links without a corresponding entity map.forEachKey { childId, parentId -> assertResolvable(connectionId.parentClass, parentId) assertResolvable(connectionId.childClass, childId) } // 2) Connections satisfy connectionId requirements if (!connectionId.isParentNullable) checkStrongConnection(map.keys, connectionId.childClass, connectionId.parentClass) if (!connectionId.isChildNullable) checkStrongConnection(map.values, connectionId.parentClass, connectionId.childClass) } refs.oneToAbstractManyContainer.forEach { (connectionId, map) -> // Assert correctness of connection id assert(connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) map.forEach { (childId, parentId) -> // 1) Refs should not have links without a corresponding entity assertResolvable(parentId.clazz, parentId.arrayId) assertResolvable(childId.clazz, childId.arrayId) // 1.1) For abstract containers: EntityId has the class of ConnectionId assertCorrectEntityClass(connectionId.parentClass, parentId) assertCorrectEntityClass(connectionId.childClass, childId) } // 2) Connections satisfy connectionId requirements if (!connectionId.isParentNullable) { checkStrongAbstractConnection(map.keys.toMutableSet(), map.keys.toMutableSet().map { it.clazz }.toSet(), connectionId.debugStr()) } } refs.abstractOneToOneContainer.forEach { (connectionId, map) -> // Assert correctness of connection id assert(connectionId.connectionType == ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE) map.forEach { (childId, parentId) -> // 1) Refs should not have links without a corresponding entity assertResolvable(parentId.clazz, parentId.arrayId) assertResolvable(childId.clazz, childId.arrayId) // 1.1) For abstract containers: EntityId has the class of ConnectionId assertCorrectEntityClass(connectionId.parentClass, parentId) assertCorrectEntityClass(connectionId.childClass, childId) } // 2) Connections satisfy connectionId requirements if (!connectionId.isParentNullable) { checkStrongAbstractConnection(map.keys.toMutableSet(), map.keys.toMutableSet().map { it.clazz }.toSet(), connectionId.debugStr()) } if (!connectionId.isChildNullable) { checkStrongAbstractConnection(map.values.toMutableSet(), map.values.toMutableSet().map { it.clazz }.toSet(), connectionId.debugStr()) } } indexes.assertConsistency(this) } private fun checkStrongConnection(connectionKeys: IntSet, entityFamilyClass: Int, connectionTo: Int) { if (connectionKeys.isEmpty()) return var counter = 0 val entityFamily = entitiesByType.entityFamilies[entityFamilyClass] ?: error("Entity family ${entityFamilyClass.findWorkspaceEntity()} doesn't exist") entityFamily.entities.forEachIndexed { i, entity -> if (entity == null) return@forEachIndexed assert(i in connectionKeys) { "Entity $entity doesn't have a correct connection to ${connectionTo.findWorkspaceEntity()}" } counter++ } assert(counter == connectionKeys.size) { "Store is inconsistent" } } private fun checkStrongAbstractConnection(connectionKeys: Set<EntityId>, entityFamilyClasses: Set<Int>, debugInfo: String) { val keys = connectionKeys.toMutableSet() entityFamilyClasses.forEach { entityFamilyClass -> checkAllStrongConnections(entityFamilyClass, keys, debugInfo) } assert(keys.isEmpty()) { "Store is inconsistent. $debugInfo" } } private fun checkAllStrongConnections(entityFamilyClass: Int, keys: MutableSet<EntityId>, debugInfo: String) { val entityFamily = entitiesByType.entityFamilies[entityFamilyClass] ?: error("Entity family doesn't exist. $debugInfo") entityFamily.entities.forEach { entity -> if (entity == null) return@forEach val removed = keys.remove(entity.createEntityId()) assert(removed) { "Entity $entity doesn't have a correct connection. $debugInfo" } } } internal fun assertConsistencyInStrictMode(message: String, sourceFilter: ((EntitySource) -> Boolean)?, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage?) { if (consistencyCheckingMode != ConsistencyCheckingMode.DISABLED) { try { this.assertConsistency() } catch (e: Throwable) { brokenConsistency = true val storage = if (this is WorkspaceEntityStorageBuilder) this.toStorage() as AbstractEntityStorage else this val report = { reportConsistencyIssue(message, e, sourceFilter, left, right, storage) } if (consistencyCheckingMode == ConsistencyCheckingMode.ASYNCHRONOUS) { consistencyChecker.execute(report) } else { report() } } } } fun reportConsistencyIssue(message: String, e: Throwable, sourceFilter: ((EntitySource) -> Boolean)?, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage?, resulting: WorkspaceEntityStorage) { val entitySourceFilter = if (sourceFilter != null) { val allEntitySources = (left as? AbstractEntityStorage)?.indexes?.entitySourceIndex?.entries()?.toHashSet() ?: hashSetOf() allEntitySources.addAll((right as? AbstractEntityStorage)?.indexes?.entitySourceIndex?.entries() ?: emptySet()) allEntitySources.sortedBy { it.toString() }.fold("") { acc, source -> acc + if (sourceFilter(source)) "1" else "0" } } else null var _message = "$message\n\nEntity source filter: $entitySourceFilter" _message += "\n\nVersion: ${EntityStorageSerializerImpl.SERIALIZER_VERSION}" val zipFile = if (consistencyCheckingMode != ConsistencyCheckingMode.DISABLED) { val dumpDirectory = getStoreDumpDirectory() _message += "\nSaving store content at: $dumpDirectory" serializeContentToFolder(dumpDirectory, left, right, resulting) } else null if (zipFile != null) { val attachment = Attachment("workspaceModelDump.zip", zipFile.readBytes(), "Zip of workspace model store") attachment.isIncluded = true LOG.error(_message, e, attachment) } else { LOG.error(_message, e) } } private fun serializeContentToFolder(contentFolder: Path, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage?, resulting: WorkspaceEntityStorage): File? { left?.let { serializeEntityStorage(contentFolder.resolve("Left_Store"), it) } right?.let { serializeEntityStorage(contentFolder.resolve("Right_Store"), it) } serializeEntityStorage(contentFolder.resolve("Res_Store"), resulting) serializeContent(contentFolder.resolve("ClassToIntConverter")) { serializer, stream -> serializer.serializeClassToIntConverter(stream) } if (right is WorkspaceEntityStorageBuilder) { serializeContent(contentFolder.resolve("Right_Diff_Log")) { serializer, stream -> right as WorkspaceEntityStorageBuilderImpl serializer.serializeDiffLog(stream, right.changeLog) } } return if (!executingOnTC()) { val zipFile = contentFolder.parent.resolve(contentFolder.name + ".zip").toFile() Compressor.Zip(zipFile).use { it.addDirectory(contentFolder.toFile()) } FileUtil.delete(contentFolder) zipFile } else null } private fun assertResolvable(clazz: Int, id: Int) { assert(entitiesByType[clazz]?.get(id) != null) { "Reference to ${clazz.findEntityClass<WorkspaceEntity>()}-:-$id cannot be resolved" } } private fun assertCorrectEntityClass(connectionClass: Int, entityId: EntityId) { assert(connectionClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(entityId.clazz.findEntityClass<WorkspaceEntity>())) { "Entity storage with connection class ${connectionClass.findEntityClass<WorkspaceEntity>()} contains entity data of wrong type $entityId" } } companion object { val LOG = logger<AbstractEntityStorage>() private val consistencyChecker = AppExecutorUtil.createBoundedApplicationPoolExecutor("Check workspace model consistency", 1) } } /** This function exposes `brokenConsistency` property to the outside and should be removed along with the property itself */ val WorkspaceEntityStorage.isConsistent: Boolean get() = !(this as AbstractEntityStorage).brokenConsistency internal object ClassConversion { private val modifiableToEntityCache = HashMap<KClass<*>, KClass<*>>() private val entityToEntityDataCache = HashMap<KClass<*>, KClass<*>>() private val entityDataToEntityCache = HashMap<Class<*>, Class<*>>() private val entityDataToModifiableEntityCache = HashMap<KClass<*>, KClass<*>>() private val packageCache = HashMap<KClass<*>, String>() fun <M : ModifiableWorkspaceEntity<T>, T : WorkspaceEntity> modifiableEntityToEntity(clazz: KClass<out M>): KClass<T> { @Suppress("UNCHECKED_CAST") return modifiableToEntityCache.getOrPut(clazz) { try { Class.forName(getPackage(clazz) + clazz.java.simpleName.drop(10), true, clazz.java.classLoader).kotlin } catch (e: ClassNotFoundException) { error("Cannot get modifiable class for $clazz") } } as KClass<T> } @Suppress("UNCHECKED_CAST") fun <T : WorkspaceEntity> entityToEntityData(clazz: KClass<out T>): KClass<WorkspaceEntityData<T>> { return entityToEntityDataCache.getOrPut(clazz) { (Class.forName(clazz.java.name + "Data", true, clazz.java.classLoader) as Class<WorkspaceEntityData<T>>).kotlin } as KClass<WorkspaceEntityData<T>> } @Suppress("UNCHECKED_CAST") fun <M : WorkspaceEntityData<out T>, T : WorkspaceEntity> entityDataToEntity(clazz: Class<out M>): Class<T> { return entityDataToEntityCache.getOrPut(clazz) { (Class.forName(clazz.name.dropLast(4), true, clazz.classLoader) as Class<T>) } as Class<T> } @Suppress("UNCHECKED_CAST") fun <D : WorkspaceEntityData<T>, T : WorkspaceEntity> entityDataToModifiableEntity(clazz: KClass<out D>): KClass<ModifiableWorkspaceEntity<T>> { return entityDataToModifiableEntityCache.getOrPut(clazz) { Class.forName(getPackage(clazz) + "Modifiable" + clazz.java.simpleName.dropLast(4), true, clazz.java.classLoader).kotlin as KClass<ModifiableWorkspaceEntity<T>> } as KClass<ModifiableWorkspaceEntity<T>> } private fun getPackage(clazz: KClass<*>): String = packageCache.getOrPut(clazz) { clazz.java.name.dropLastWhile { it != '.' } } }
apache-2.0
3c89097be98a1c357d11716f26f53f8a
46.85588
192
0.700988
5.118203
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/UsageReplacementStrategy.kt
1
7882
// 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.codeInliner import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.ModalityUiUtil import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.targetDescriptors import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention import org.jetbrains.kotlin.idea.references.KtSimpleReference import org.jetbrains.kotlin.idea.stubindex.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs interface UsageReplacementStrategy { fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? companion object { val KEY = Key<Unit>("UsageReplacementStrategy.replaceUsages") } } private val LOG = Logger.getInstance(UsageReplacementStrategy::class.java) fun UsageReplacementStrategy.replaceUsagesInWholeProject( targetPsiElement: PsiElement, @NlsContexts.DialogTitle progressTitle: String, commandName: String ) { val project = targetPsiElement.project ProgressManager.getInstance().run( object : Task.Modal(project, progressTitle, true) { override fun run(indicator: ProgressIndicator) { val usages = runReadAction { val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project) ReferencesSearch.search(targetPsiElement, searchScope) .filterIsInstance<KtSimpleReference<KtReferenceExpression>>() .map { ref -> ref.expression } } ModalityUiUtil.invokeLaterIfNeeded( { project.executeWriteCommand(commandName) { [email protected](usages) } }, ModalityState.NON_MODAL ) } }) } fun UsageReplacementStrategy.replaceUsages(usages: Collection<KtReferenceExpression>) { val usagesByFile = usages.groupBy { it.containingFile } for ((file, usagesInFile) in usagesByFile) { usagesInFile.forEach { it.putCopyableUserData(UsageReplacementStrategy.KEY, Unit) } // we should delete imports later to not affect other usages val importsToDelete = mutableListOf<KtImportDirective>() var usagesToProcess = usagesInFile while (usagesToProcess.isNotEmpty()) { if (processUsages(usagesToProcess, importsToDelete)) break // some usages may get invalidated we need to find them in the tree usagesToProcess = file.collectDescendantsOfType { it.getCopyableUserData(UsageReplacementStrategy.KEY) != null } } file.forEachDescendantOfType<KtSimpleNameExpression> { it.putCopyableUserData(UsageReplacementStrategy.KEY, null) } importsToDelete.forEach { it.delete() } } } /** * @return false if some usages were invalidated */ private fun UsageReplacementStrategy.processUsages( usages: List<KtReferenceExpression>, importsToDelete: MutableList<KtImportDirective>, ): Boolean { val sortedUsages = usages.sortedWith { element1, element2 -> if (element1.parent.textRange.intersects(element2.parent.textRange)) { compareValuesBy(element2, element1) { it.startOffset } } else { compareValuesBy(element1, element2) { it.startOffset } } } var invalidUsagesFound = false for (usage in sortedUsages) { try { if (!usage.isValid) { invalidUsagesFound = true continue } val specialUsage = unwrapSpecialUsageOrNull(usage) if (specialUsage != null) { createReplacer(specialUsage)?.invoke() continue } //TODO: keep the import if we don't know how to replace some of the usages val importDirective = usage.getStrictParentOfType<KtImportDirective>() if (importDirective != null) { if (!importDirective.isAllUnder && importDirective.targetDescriptors().size == 1) { importsToDelete.add(importDirective) } continue } createReplacer(usage)?.invoke()?.parent?.parent?.parent?.reformatted(true) } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } } return !invalidUsagesFound } fun unwrapSpecialUsageOrNull( usage: KtReferenceExpression ): KtSimpleNameExpression? { if (usage !is KtSimpleNameExpression) return null when (val usageParent = usage.parent) { is KtCallableReferenceExpression -> { if (usageParent.callableReference != usage) return null val (name, descriptor) = usage.nameAndDescriptor return ConvertReferenceToLambdaIntention.applyTo(usageParent)?.let { findNewUsage(it, name, descriptor) } } is KtCallElement -> { for (valueArgument in usageParent.valueArguments.asReversed()) { val callableReferenceExpression = valueArgument.getArgumentExpression() as? KtCallableReferenceExpression ?: continue ConvertReferenceToLambdaIntention.applyTo(callableReferenceExpression) } val lambdaExpressions = usageParent.valueArguments.mapNotNull { it.getArgumentExpression() as? KtLambdaExpression } if (lambdaExpressions.isEmpty()) return null val (name, descriptor) = usage.nameAndDescriptor val grandParent = usageParent.parent for (lambdaExpression in lambdaExpressions) { val functionDescriptor = lambdaExpression.functionLiteral.resolveToDescriptorIfAny() as? FunctionDescriptor ?: continue if (functionDescriptor.valueParameters.isNotEmpty()) { SpecifyExplicitLambdaSignatureIntention.applyTo(lambdaExpression) } } return grandParent.safeAs<KtElement>()?.let { findNewUsage(it, name, descriptor) } } } return null } private val KtSimpleNameExpression.nameAndDescriptor get() = getReferencedName() to resolveToCall()?.candidateDescriptor private fun findNewUsage( element: KtElement, targetName: String?, targetDescriptor: DeclarationDescriptor? ): KtSimpleNameExpression? = element.findDescendantOfType { it.getReferencedName() == targetName && compareDescriptors(it.project, targetDescriptor, it.resolveToCall()?.candidateDescriptor) }
apache-2.0
e7f4980f7e2385739bfbf6a3bd548eda
40.052083
158
0.6983
5.454671
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/EntryLinksAdapter.kt
1
4378
package io.github.feelfreelinux.wykopmobilny.ui.adapters import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.base.adapter.EndlessProgressAdapter import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry import io.github.feelfreelinux.wykopmobilny.models.dataclass.EntryLink import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.BlockedViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.EntryViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.LinkViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.SimpleLinkViewHolder import io.github.feelfreelinux.wykopmobilny.ui.fragments.entries.EntryActionListener import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinkActionListener import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi import javax.inject.Inject class EntryLinksAdapter @Inject constructor( val userManagerApi: UserManagerApi, val settingsPreferencesApi: SettingsPreferencesApi, val navigatorApi: NewNavigatorApi, val linkHandlerApi: WykopLinkHandlerApi ) : EndlessProgressAdapter<androidx.recyclerview.widget.RecyclerView.ViewHolder, EntryLink>() { // Required field, interacts with presenter. Otherwise will throw exception lateinit var entryActionListener: EntryActionListener lateinit var linkActionListener: LinkActionListener override fun getViewType(position: Int): Int { val entryLink = dataset[position] return if (entryLink?.DATA_TYPE == EntryLink.TYPE_ENTRY) { EntryViewHolder.getViewTypeForEntry(entryLink.entry!!) } else { LinkViewHolder.getViewTypeForLink(entryLink!!.link!!, settingsPreferencesApi) } } override fun addData(items: List<EntryLink>, shouldClearAdapter: Boolean) { super.addData( items.asSequence().filterNot { settingsPreferencesApi.hideBlacklistedViews && if (it.entry != null) it.entry!!.isBlocked else it.link!!.isBlocked }.toList(), shouldClearAdapter ) } override fun constructViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder { return when (viewType) { LinkViewHolder.TYPE_IMAGE, LinkViewHolder.TYPE_NOIMAGE -> LinkViewHolder.inflateView(parent, viewType, userManagerApi, settingsPreferencesApi, navigatorApi, linkActionListener) EntryViewHolder.TYPE_BLOCKED, LinkViewHolder.TYPE_BLOCKED -> BlockedViewHolder.inflateView(parent, { notifyItemChanged(it) }) else -> EntryViewHolder.inflateView( parent, viewType, userManagerApi, settingsPreferencesApi, navigatorApi, linkHandlerApi, entryActionListener, null ) } } override fun bindHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) { when (holder) { is EntryViewHolder -> { dataset[position]?.entry?.let { holder.bindView(it) } } is LinkViewHolder -> dataset[position]?.link?.let { holder.bindView(it) } is BlockedViewHolder -> { val data = dataset[position] data?.link?.let { holder.bindView(it) } data?.entry?.let { holder.bindView(it) } } is SimpleLinkViewHolder -> dataset[position]!!.link?.let { holder.bindView(it) } } } fun updateEntry(entry: Entry) { val position = dataset.indexOfFirst { it!!.entry?.id == entry.id } dataset[position]!!.entry = entry notifyItemChanged(position) } fun updateLink(link: Link) { val position = dataset.indexOfFirst { it!!.link?.id == link.id } dataset[position]!!.link = link notifyItemChanged(position) } }
mit
ac8a84b9d25244174af053a94377df8a
44.614583
173
0.69735
5.014891
false
false
false
false
lsmaira/gradle
buildSrc/subprojects/configuration/src/main/kotlin/org/gradle/gradlebuild/dependencies/DependenciesMetadataRulesPlugin.kt
1
9836
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.gradlebuild.dependencies import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import library import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.ComponentMetadataContext import org.gradle.api.artifacts.ComponentMetadataRule import org.gradle.api.artifacts.ConfigurationContainer import org.gradle.api.artifacts.dsl.ComponentMetadataHandler import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.extra import java.io.File import javax.inject.Inject import kotlin.reflect.KClass open class DependenciesMetadataRulesPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { dependencies { components { // Gradle distribution - minify: remove unused transitive dependencies withModule(library("maven3"), MavenDependencyCleaningRule::class.java) withLibraryDependencies(library("awsS3_core"), DependencyRemovalByNameRule::class, setOf("jackson-dataformat-cbor")) withLibraryDependencies(library("jgit"), DependencyRemovalByGroupRule::class, setOf("com.googlecode.javaewah")) withLibraryDependencies(library("maven3_wagon_http_shared"), DependencyRemovalByGroupRule::class, setOf("org.jsoup")) withLibraryDependencies(library("aether_connector"), DependencyRemovalByGroupRule::class, setOf("org.sonatype.sisu")) withLibraryDependencies(library("maven3_compat"), DependencyRemovalByGroupRule::class, setOf("org.sonatype.sisu")) withLibraryDependencies(library("maven3_plugin_api"), DependencyRemovalByGroupRule::class, setOf("org.sonatype.sisu")) // Read capabilities declared in capabilities.json readCapabilitiesFromJson() withModule("org.spockframework:spock-core", ReplaceCglibNodepWithCglibRule::class.java) // Prevent Spock from pulling in Groovy and third-party dependencies - see https://github.com/spockframework/spock/issues/899 withLibraryDependencies("org.spockframework:spock-core", DependencyRemovalByNameRule::class, setOf("groovy-groovysh", "groovy-json", "groovy-macro", "groovy-nio", "groovy-sql", "groovy-templates", "groovy-test", "groovy-xml")) withLibraryDependencies("cglib:cglib", DependencyRemovalByNameRule::class, setOf("ant")) // asciidoctorj depends on a lot of stuff, which causes `Can't create process, argument list too long` on Windows withLibraryDependencies("org.gradle:sample-discovery", DependencyRemovalByNameRule::class, setOf("asciidoctorj", "asciidoctorj-api")) withModule("jaxen:jaxen", DowngradeXmlApisRule::class.java) withModule("jdom:jdom", DowngradeXmlApisRule::class.java) withModule("xalan:xalan", DowngradeXmlApisRule::class.java) withModule("jaxen:jaxen", DowngradeXmlApisRule::class.java) // Test dependencies - minify: remove unused transitive dependencies withLibraryDependencies("org.gradle.org.littleshoot:littleproxy", DependencyRemovalByNameRule::class, setOf("barchart-udt-bundle", "guava", "commons-cli")) } } } private fun Project.readCapabilitiesFromJson() { val extra = gradle.rootProject.extra val capabilities: List<CapabilitySpec> if (extra.has("capabilities")) { @Suppress("unchecked_cast") capabilities = extra["capabilities"] as List<CapabilitySpec> } else { val capabilitiesFile = gradle.rootProject.file("gradle/dependency-management/capabilities.json") if (capabilitiesFile.exists()) { capabilities = readCapabilities(capabilitiesFile) } else { capabilities = emptyList() } extra["capabilities"] = capabilities } capabilities.forEach { it.configure(dependencies.components, configurations) } } private fun readCapabilities(source: File): List<CapabilitySpec> { val gson = Gson() val reader = JsonReader(source.reader(Charsets.UTF_8)) try { reader.isLenient = true return gson.fromJson<List<CapabilitySpec>>(reader) } finally { reader.close() } } } inline fun <reified T> Gson.fromJson(json: JsonReader) = this.fromJson<T>(json, object : TypeToken<T>() {}.type) open class CapabilityRule @Inject constructor( val name: String, val version: String ) : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withCapabilities { addCapability("org.gradle.internal.capability", name, version) } } } } class CapabilitySpec { lateinit var name: String lateinit var providedBy: Set<String> lateinit var selected: String var upgrade: String? = null internal fun configure(components: ComponentMetadataHandler, configurations: ConfigurationContainer) { if (upgrade != null) { configurations.forceUpgrade(selected, upgrade!!) } else { providedBy.forEachIndexed { idx, provider -> if (provider != selected) { components.declareSyntheticCapability(provider, idx.toString()) } } components.declareCapabilityPreference(selected) } } private fun ComponentMetadataHandler.declareSyntheticCapability(provider: String, version: String) { withModule(provider, CapabilityRule::class.java, { params(name) params(version) }) } private fun ComponentMetadataHandler.declareCapabilityPreference(module: String) { withModule(module, CapabilityRule::class.java, { params(name) params("${providedBy.size + 1}") }) } /** * For all modules providing a capability, always use the preferred module, even if there's no conflict. * In other words, will forcefully upgrade all modules providing a capability to a selected module. * * @param to the preferred module */ private fun ConfigurationContainer.forceUpgrade(to: String, version: String) = all { resolutionStrategy.dependencySubstitution { all { if (providedBy.contains(requested.toString())) { useTarget("$to:$version", "Forceful upgrade of capability $name") } } } } } open class DependencyRemovalByNameRule @Inject constructor( val moduleToRemove: Set<String> ) : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withDependencies { removeAll { moduleToRemove.contains(it.name) } } } } } open class DependencyRemovalByGroupRule @Inject constructor( val groupsToRemove: Set<String> ) : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withDependencies { removeAll { groupsToRemove.contains(it.group) } } } } } open class MavenDependencyCleaningRule : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withDependencies { removeAll { it.name != "maven-settings-builder" && it.name != "maven-model" && it.name != "maven-model-builder" && it.name != "maven-artifact" && it.name != "maven-aether-provider" && it.group != "org.sonatype.aether" } } } } } fun ComponentMetadataHandler.withLibraryDependencies(module: String, kClass: KClass<out ComponentMetadataRule>, modulesToRemove: Set<String>) { withModule(module, kClass.java, { params(modulesToRemove) }) } open class DowngradeXmlApisRule : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withDependencies { filter { it.group == "xml-apis" }.forEach { it.version { require("1.4.01") } it.because("Gradle has trouble with the versioning scheme and pom redirects in higher versions") } } } } } open class ReplaceCglibNodepWithCglibRule : ComponentMetadataRule { override fun execute(context: ComponentMetadataContext) { context.details.allVariants { withDependencies { filter { it.name == "cglib-nodep" }.forEach { add("${it.group}:cglib:3.2.7") } removeAll { it.name == "cglib-nodep" } } } } }
apache-2.0
b9d51557465dab6195148dff1bbd038c
37.421875
153
0.642944
4.717506
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt
1
11442
// 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.intentions.branchedTransformations import org.jetbrains.kotlin.cfg.WhenChecker import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.intentions.branches import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf object BranchedFoldingUtils { private fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? { fun checkAssignment(expression: KtBinaryExpression): Boolean { if (expression.operationToken !in KtTokens.ALL_ASSIGNMENTS) return false val left = expression.left as? KtNameReferenceExpression ?: return false if (expression.right == null) return false val parent = expression.parent if (parent is KtBlockExpression) { return !KtPsiUtil.checkVariableDeclarationInBlock(parent, left.text) } return true } return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.takeIf(::checkAssignment) } fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? = (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.takeIf { it.returnedExpression != null && it.returnedExpression !is KtLambdaExpression && it.getTargetLabel() == null } private fun KtBinaryExpression.checkAssignmentsMatch( other: KtBinaryExpression, leftType: KotlinType, rightTypeConstructor: TypeConstructor ): Boolean { val left = this.left ?: return false val otherLeft = other.left ?: return false if (left.text != otherLeft.text || operationToken != other.operationToken || left.mainReference?.resolve() != otherLeft.mainReference?.resolve() ) return false val rightType = other.rightType() ?: return false return rightType.constructor == rightTypeConstructor || (operationToken == KtTokens.EQ && rightType.isSubtypeOf(leftType)) } private fun KtBinaryExpression.rightType(): KotlinType? { val right = this.right ?: return null val context = this.analyze() val diagnostics = context.diagnostics fun hasTypeMismatchError(e: KtExpression) = diagnostics.forElement(e).any { it.factory == Errors.TYPE_MISMATCH } if (hasTypeMismatchError(this) || hasTypeMismatchError(right)) return null return right.getType(context) } internal fun getFoldableAssignmentNumber(expression: KtExpression?): Int { expression ?: return -1 val assignments = linkedSetOf<KtBinaryExpression>() fun collectAssignmentsAndCheck(e: KtExpression?): Boolean = when (e) { is KtWhenExpression -> { val entries = e.entries !e.hasMissingCases() && entries.isNotEmpty() && entries.all { entry -> val assignment = getFoldableBranchedAssignment(entry.expression)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(entry.expression?.lastBlockStatementOrThis()) } } is KtIfExpression -> { val branches = e.branches val elseBranch = branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` branches.size > 1 && elseBranch != null && branches.all { branch -> val assignment = getFoldableBranchedAssignment(branch)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(branch?.lastBlockStatementOrThis()) } } is KtTryExpression -> { e.tryBlockAndCatchBodies().all { val assignment = getFoldableBranchedAssignment(it)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(it?.lastBlockStatementOrThis()) } } is KtCallExpression -> { e.analyze().getType(e)?.isNothing() ?: false } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression, is KtReturnExpression -> true else -> false } if (!collectAssignmentsAndCheck(expression)) return -1 val firstAssignment = assignments.firstOrNull { !it.right.isNullExpression() } ?: assignments.firstOrNull() ?: return 0 val leftType = firstAssignment.left?.let { it.getType(it.analyze(BodyResolveMode.PARTIAL)) } ?: return 0 val rightTypeConstructor = firstAssignment.rightType()?.constructor ?: return -1 if (assignments.any { !firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) }) { return -1 } if (expression.anyDescendantOfType<KtBinaryExpression>( predicate = { if (it.operationToken in KtTokens.ALL_ASSIGNMENTS) if (it.getNonStrictParentOfType<KtFinallySection>() != null) firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) else it !in assignments else false } ) ) { return -1 } return assignments.size } private fun getFoldableReturns(branches: List<KtExpression?>): List<KtReturnExpression>? = branches.fold<KtExpression?, MutableList<KtReturnExpression>?>(mutableListOf()) { prevList, branch -> if (prevList == null) return@fold null val foldableBranchedReturn = getFoldableBranchedReturn(branch) if (foldableBranchedReturn != null) { prevList.add(foldableBranchedReturn) } else { val currReturns = getFoldableReturns(branch?.lastBlockStatementOrThis()) ?: return@fold null prevList += currReturns } prevList } internal fun getFoldableReturns(expression: KtExpression?): List<KtReturnExpression>? = when (expression) { is KtWhenExpression -> { val entries = expression.entries when { expression.hasMissingCases() -> null entries.isEmpty() -> null else -> getFoldableReturns(entries.map { it.expression }) } } is KtIfExpression -> { val branches = expression.branches when { branches.isEmpty() -> null branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` == null -> null else -> getFoldableReturns(branches) } } is KtTryExpression -> { if (expression.finallyBlock?.finalExpression?.let { getFoldableReturns(listOf(it)) }?.isNotEmpty() == true) null else getFoldableReturns(expression.tryBlockAndCatchBodies()) } is KtCallExpression -> { if (expression.analyze().getType(expression)?.isNothing() == true) emptyList() else null } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression -> emptyList() else -> null } private fun getFoldableReturnNumber(expression: KtExpression?) = getFoldableReturns(expression)?.size ?: -1 fun canFoldToReturn(expression: KtExpression?): Boolean = getFoldableReturnNumber(expression) > 0 fun tryFoldToAssignment(expression: KtExpression) { var lhs: KtExpression? = null var op: String? = null val psiFactory = KtPsiFactory(expression) fun KtBinaryExpression.replaceWithRHS() { if (lhs == null || op == null) { lhs = left!!.copy() as KtExpression op = operationReference.text } val rhs = right!! if (rhs is KtLambdaExpression && this.parent !is KtBlockExpression) { replace(psiFactory.createSingleStatementBlock(rhs)) } else { replace(rhs) } } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> getFoldableBranchedAssignment(entry.expression)?.replaceWithRHS() ?: lift(entry.expression?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedAssignment(branch)?.replaceWithRHS() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedAssignment(it)?.replaceWithRHS() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) if (lhs != null && op != null) { expression.replace(psiFactory.createExpressionByPattern("$0 $1 $2", lhs!!, op!!, expression)) } } fun foldToReturn(expression: KtExpression): KtExpression { fun KtReturnExpression.replaceWithReturned() { replace(returnedExpression!!) } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> val entryExpr = entry.expression getFoldableBranchedReturn(entryExpr)?.replaceWithReturned() ?: lift(entryExpr?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedReturn(branch)?.replaceWithReturned() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedReturn(it)?.replaceWithReturned() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) return expression.replaced(KtPsiFactory(expression).createExpressionByPattern("return $0", expression)) } private fun KtTryExpression.tryBlockAndCatchBodies(): List<KtExpression?> = listOf(tryBlock) + catchClauses.map { it.catchBody } private fun KtWhenExpression.hasMissingCases(): Boolean = !KtPsiUtil.checkWhenExpressionHasSingleElse(this) && WhenChecker.getMissingCases(this, safeAnalyzeNonSourceRootCode()).isNotEmpty() }
apache-2.0
0f60eb93ec68e1a0c30be0c6803e9338
46.477178
158
0.632057
5.778788
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/EmojiCompatStatus.kt
3
3567
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.platform import androidx.annotation.VisibleForTesting import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.emoji2.text.EmojiCompat /** * Tests may provide alternative global implementations for [EmojiCompatStatus] using this delegate. */ internal interface EmojiCompatStatusDelegate { val fontLoaded: State<Boolean> } /** * Used for observing emojicompat font loading status from compose. */ internal object EmojiCompatStatus : EmojiCompatStatusDelegate { private var delegate: EmojiCompatStatusDelegate = DefaultImpl() /** * True if the emoji2 font is currently loaded and processing will be successful * * False when emoji2 may complete loading in the future. */ override val fontLoaded: State<Boolean> get() = delegate.fontLoaded /** * Do not call. * * This is for tests that want to control EmojiCompatStatus behavior. */ @VisibleForTesting internal fun setDelegateForTesting(newDelegate: EmojiCompatStatusDelegate?) { delegate = newDelegate ?: DefaultImpl() } } /** * is-a state, but doesn't cause an observation when read */ private class ImmutableBool(override val value: Boolean) : State<Boolean> private val Falsey = ImmutableBool(false) private class DefaultImpl : EmojiCompatStatusDelegate { private var loadState: State<Boolean>? init { loadState = if (EmojiCompat.isConfigured()) { getFontLoadState() } else { // EC isn't configured yet, will check again in getter null } } override val fontLoaded: State<Boolean> get() = if (loadState != null) { loadState!! } else { // EC wasn't configured last time, check again and update loadState if it's ready if (EmojiCompat.isConfigured()) { loadState = getFontLoadState() loadState!! } else { // ec disabled path // no observations allowed, this is pre init Falsey } } private fun getFontLoadState(): State<Boolean> { val ec = EmojiCompat.get() return if (ec.loadState == EmojiCompat.LOAD_STATE_SUCCEEDED) { ImmutableBool(true) } else { val mutableLoaded = mutableStateOf(false) val initCallback = object : EmojiCompat.InitCallback() { override fun onInitialized() { mutableLoaded.value = true // update previous observers loadState = ImmutableBool(true) // never observe again } override fun onFailed(throwable: Throwable?) { loadState = Falsey // never observe again } } ec.registerInitCallback(initCallback) mutableLoaded } } }
apache-2.0
d95199219ebb6cf9f8d44278dcd798d6
31.427273
100
0.644239
4.839891
false
false
false
false
androidx/androidx
compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/viewinterop/ResizeComposeViewDemo.kt
3
2632
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.demos.viewinterop import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.Text 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 import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.round import androidx.compose.ui.viewinterop.AndroidView @Composable fun ResizeComposeViewDemo() { var size by remember { mutableStateOf(IntSize(0, 0)) } Box( Modifier .fillMaxSize() .pointerInput(Unit) { awaitPointerEventScope { while (true) { val event = awaitPointerEvent() event.changes.forEach { it.consume() } val change = event.changes.firstOrNull() if (change != null) { val position = change.position.round() size = IntSize(position.x, position.y) } } } }) { with(LocalDensity.current) { AndroidView(factory = { context -> ComposeView(context).apply { setContent { Box(Modifier.fillMaxSize().background(Color.Blue)) } } }, modifier = Modifier.size(size.width.toDp(), size.height.toDp())) Text("Touch the screen to change the size of the child ComposeView") } } }
apache-2.0
3e179dca9b07a1f717ad622181656ff5
38.298507
80
0.653116
4.856089
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt
4
2814
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.ui import com.intellij.ide.util.AbstractTreeClassChooserDialog import com.intellij.ide.util.TreeChooser import com.intellij.ide.util.gotoByName.GotoFileModel import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources import org.jetbrains.kotlin.idea.projectView.KtClassOrObjectTreeNode import org.jetbrains.kotlin.idea.projectView.KtFileTreeNode import org.jetbrains.kotlin.psi.KtFile import javax.swing.tree.DefaultMutableTreeNode class KotlinFileChooserDialog( @NlsContexts.DialogTitle title: String, project: Project, searchScope: GlobalSearchScope?, packageName: String? ) : AbstractTreeClassChooserDialog<KtFile>( title, project, searchScope ?: project.projectScope().restrictToKotlinSources(), KtFile::class.java, ScopeAwareClassFilter(searchScope, packageName), null, null, false, false ) { override fun getSelectedFromTreeUserObject(node: DefaultMutableTreeNode): KtFile? = when (val userObject = node.userObject) { is KtFileTreeNode -> userObject.ktFile is KtClassOrObjectTreeNode -> { val containingFile = userObject.value.containingKtFile if (containingFile.declarations.size == 1) containingFile else null } else -> null } override fun getClassesByName(name: String, checkBoxState: Boolean, pattern: String, searchScope: GlobalSearchScope): List<KtFile> { return FilenameIndex.getFilesByName(project, name, searchScope).filterIsInstance<KtFile>() } override fun createChooseByNameModel() = GotoFileModel(this.project) /** * Base class [AbstractTreeClassChooserDialog] unfortunately doesn't filter the file tree according to the provided "scope". * As a workaround we use filter preventing wrong file selection. */ private class ScopeAwareClassFilter(val searchScope: GlobalSearchScope?, val packageName: String?) : TreeChooser.Filter<KtFile> { override fun isAccepted(element: KtFile?): Boolean { if (element == null) return false if (searchScope == null && packageName == null) return true val matchesSearchScope = searchScope?.accept(element.virtualFile) ?: true val matchesPackage = packageName?.let { element.packageFqName.asString() == it } ?: true return matchesSearchScope && matchesPackage } } }
apache-2.0
100e94e5ba1eda39711ecdf365b908e5
42.307692
158
0.745913
4.843373
false
false
false
false
GunoH/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/autoimport/ExternalSystemProjectAware.kt
2
2451
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.Event.CREATE import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.ReloadStatus.JUST_FINISHED import org.jetbrains.annotations.ApiStatus interface ExternalSystemProjectAware { val projectId: ExternalSystemProjectId /** * Collects settings files which will be watched. * This property can be called from any thread context to reduce UI freezes and CPU usage. * Result will be cached, so settings files should be equals between reloads. */ val settingsFiles: Set<String> fun subscribe(listener: ExternalSystemProjectListener, parentDisposable: Disposable) fun reloadProject(context: ExternalSystemProjectReloadContext) /** * Experimental. Please see implementation limitations. * * This function allows ignoring settings files events. For example Idea can ignore external * changes during reload. * * Note: All ignored modifications cannot be reverted. So if we ignore only create events * then if settings file was created and removed then we mark project status as modified, * because we can restore only delete event by CRCs. * * Note: Now create event and register settings file (file appear in settings files list) event * is same (also for delete and unregister), because we cannot find settings file if it doesn't * exist in file system. Usually settings files list forms during file system scanning. * * Note: This function will be called on EDT. Please make only trivial checks like: * ```context.modificationType == EXTERNAL && path.endsWith(".my-ext")``` * * Note: [ReloadStatus.JUST_FINISHED] is used to ignore create events during reload. But we cannot * replace it by [ReloadStatus.IN_PROGRESS], because we should merge create and all next update * events into one create event and ignore all of them. So [ReloadStatus.JUST_FINISHED] true only * at the end of reload. */ @ApiStatus.Experimental fun isIgnoredSettingsFileEvent(path: String, context: ExternalSystemSettingsFilesModificationContext): Boolean = context.reloadStatus == JUST_FINISHED && context.event == CREATE }
apache-2.0
08c90b6bae97c185f7d0214aab1fd37d
49.040816
127
0.775602
4.941532
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/AnalysisConfig.kt
2
4018
/* * 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 com.intellij.diagnostic.hprof.analysis class AnalysisConfig( val perClassOptions: PerClassOptions, val histogramOptions: HistogramOptions = HistogramOptions(), val disposerOptions: DisposerOptions = DisposerOptions(), val traverseOptions: TraverseOptions = TraverseOptions(), val metaInfoOptions: MetaInfoOptions = MetaInfoOptions(), val dominatorTreeOptions: DominatorTreeOptions = DominatorTreeOptions() ) { class PerClassOptions( val classNames: List<String>, val includeClassList: Boolean = true, val treeDisplayOptions: TreeDisplayOptions = TreeDisplayOptions.default() ) class TreeDisplayOptions( val minimumObjectSize: Int = 30_000_000, val minimumObjectCount: Int = 50_000, val minimumSubgraphSize: Long = 100_000_000, val minimumObjectCountPercent: Int = 15, val maximumTreeDepth: Int = 80, val maximumIndent: Int = 40, val minimumPaths: Int = 2, val headLimit: Int = 100, val tailLimit: Int = 25, val smartIndent: Boolean = true, val showSize: Boolean = true ) { companion object { fun default() = TreeDisplayOptions() fun all(smartIndent: Boolean = true, showSize: Boolean = true) = TreeDisplayOptions(minimumObjectSize = 0, minimumObjectCount = 0, minimumSubgraphSize = 0, minimumObjectCountPercent = 0, headLimit = Int.MAX_VALUE, tailLimit = 0, minimumPaths = Int.MAX_VALUE, smartIndent = smartIndent, showSize = showSize) } } class HistogramOptions( val includeByCount: Boolean = true, val includeBySize: Boolean = true, val includeSummary: Boolean = true, val classByCountLimit: Int = 50, val classBySizeLimit: Int = 10 ) class DisposerOptions( val includeDisposerTree: Boolean = true, val includeDisposerTreeSummary: Boolean = true, val includeDisposedObjectsSummary: Boolean = true, val includeDisposedObjectsDetails: Boolean = true, val disposedObjectsDetailsTreeDisplayOptions: TreeDisplayOptions = TreeDisplayOptions(minimumSubgraphSize = 5_000_000, headLimit = 70, tailLimit = 5), val disposerTreeSummaryOptions: DisposerTreeSummaryOptions = DisposerTreeSummaryOptions() ) class DisposerTreeSummaryOptions( val maxDepth: Int = 20, val headLimit: Int = 400, val nodeCutoff: Int = 20 ) class TraverseOptions( val onlyStrongReferences: Boolean = false, val includeClassesAsRoots: Boolean = true, val includeDisposerRelationships: Boolean = true, val includeFieldInformation: Boolean = true ) class MetaInfoOptions( val include: Boolean = true ) class DominatorTreeOptions( val includeDominatorTree: Boolean = true, val maxDominatorIterations: Int = 2_000, val minNodeSize: Int = 100_000, val maxDepth: Int = 30, val headLimit: Int = 5_000, val diskSpaceThreshold: Long = 500_000_000L ) companion object { fun getDefaultConfig(nominatedClasses: List<String>) = AnalysisConfig(PerClassOptions(nominatedClasses)) } }
apache-2.0
819f3d5527b5c823ec5bf5058954afcc
35.527273
122
0.658288
4.550396
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt
1
19912
// 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.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionSorter import com.intellij.codeInsight.completion.CompletionUtil import com.intellij.codeInsight.completion.impl.CamelHumpMatcher import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.patterns.PatternCondition import com.intellij.patterns.StandardPatterns import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.project.ModuleOrigin import org.jetbrains.kotlin.idea.caches.project.OriginCapability import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getResolveScope import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.platform.isMultiPlatform import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class CompletionSessionConfiguration( val useBetterPrefixMatcherForNonImportedClasses: Boolean, val nonAccessibleDeclarations: Boolean, val javaGettersAndSetters: Boolean, val javaClassesNotToBeUsed: Boolean, val staticMembers: Boolean, val dataClassComponentFunctions: Boolean ) fun CompletionSessionConfiguration(parameters: CompletionParameters) = CompletionSessionConfiguration( useBetterPrefixMatcherForNonImportedClasses = parameters.invocationCount < 2, nonAccessibleDeclarations = parameters.invocationCount >= 2, javaGettersAndSetters = parameters.invocationCount >= 2, javaClassesNotToBeUsed = parameters.invocationCount >= 2, staticMembers = parameters.invocationCount >= 2, dataClassComponentFunctions = parameters.invocationCount >= 2 ) abstract class CompletionSession( protected val configuration: CompletionSessionConfiguration, originalParameters: CompletionParameters, resultSet: CompletionResultSet ) { init { CompletionBenchmarkSink.instance.onCompletionStarted(this) } protected val parameters = run { val fixedPosition = addParamTypesIfNeeded(originalParameters.position) originalParameters.withPosition(fixedPosition, fixedPosition.textOffset) } protected val toFromOriginalFileMapper = ToFromOriginalFileMapper.create(this.parameters) protected val position = this.parameters.position protected val file = position.containingFile as KtFile protected val resolutionFacade = file.getResolutionFacade() protected val moduleDescriptor = resolutionFacade.moduleDescriptor protected val project = position.project protected val isJvmModule = TargetPlatformDetector.getPlatform(originalParameters.originalFile as KtFile).isJvm() protected val isDebuggerContext = file is KtCodeFragment protected val nameExpression: KtSimpleNameExpression? protected val expression: KtExpression? init { val reference = (position.parent as? KtSimpleNameExpression)?.mainReference if (reference != null) { if (reference.expression is KtLabelReferenceExpression) { this.nameExpression = null this.expression = reference.expression.parent.parent as? KtExpressionWithLabel } else { this.nameExpression = reference.expression this.expression = nameExpression } } else { this.nameExpression = null this.expression = null } } protected val bindingContext = CompletionBindingContextProvider.getInstance(project).getBindingContext(position, resolutionFacade) protected val inDescriptor = position.getResolutionScope(bindingContext, resolutionFacade).ownerDescriptor private val kotlinIdentifierStartPattern = StandardPatterns.character().javaIdentifierStart().andNot(singleCharPattern('$')) private val kotlinIdentifierPartPattern = StandardPatterns.character().javaIdentifierPart().andNot(singleCharPattern('$')) protected val prefix = CompletionUtil.findIdentifierPrefix( originalParameters.position.containingFile, originalParameters.offset, kotlinIdentifierPartPattern or singleCharPattern('@'), kotlinIdentifierStartPattern )!! protected val prefixMatcher = CamelHumpMatcher(prefix) protected val descriptorNameFilter: (String) -> Boolean = prefixMatcher.asStringNameFilter() protected val isVisibleFilter: (DeclarationDescriptor) -> Boolean = { isVisibleDescriptor(it, completeNonAccessible = configuration.nonAccessibleDeclarations) } protected val isVisibleFilterCheckAlways: (DeclarationDescriptor) -> Boolean = { isVisibleDescriptor(it, completeNonAccessible = false) } protected val referenceVariantsHelper = ReferenceVariantsHelper( bindingContext, resolutionFacade, moduleDescriptor, isVisibleFilter, NotPropertiesService.getNotProperties(position) ) protected val callTypeAndReceiver = if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression) protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression, callTypeAndReceiver) } protected val basicLookupElementFactory = BasicLookupElementFactory(project, InsertHandlerProvider(callTypeAndReceiver.callType, parameters.editor) { expectedInfos }) // LookupElementsCollector instantiation is deferred because virtual call to createSorter uses data from derived classes protected val collector: LookupElementsCollector by lazy(LazyThreadSafetyMode.NONE) { LookupElementsCollector( { CompletionBenchmarkSink.instance.onFlush(this) }, prefixMatcher, originalParameters, resultSet, createSorter(), (file as? KtCodeFragment)?.extraCompletionFilter, moduleDescriptor.platform.isMultiPlatform() ) } protected val searchScope: GlobalSearchScope = getResolveScope(originalParameters.originalFile as KtFile) protected fun indicesHelper(mayIncludeInaccessible: Boolean): KotlinIndicesHelper { val filter = if (mayIncludeInaccessible) isVisibleFilter else isVisibleFilterCheckAlways return KotlinIndicesHelper( resolutionFacade, searchScope, filter, filterOutPrivate = !mayIncludeInaccessible, declarationTranslator = { toFromOriginalFileMapper.toSyntheticFile(it) }, file = file ) } private fun isVisibleDescriptor(descriptor: DeclarationDescriptor, completeNonAccessible: Boolean): Boolean { if (!configuration.javaClassesNotToBeUsed && descriptor is ClassDescriptor) { if (descriptor.importableFqName?.let(::isJavaClassNotToBeUsedInKotlin) == true) return false } if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false if (descriptor is DeclarationDescriptorWithVisibility) { val visible = descriptor.isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade) if (visible) return true return completeNonAccessible && (!descriptor.isFromLibrary() || isDebuggerContext) } if (descriptor.isExcludedFromAutoImport(project, file)) return false return true } private fun DeclarationDescriptor.isFromLibrary(): Boolean { if (module.getCapability(OriginCapability) == ModuleOrigin.LIBRARY) return true if (this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { return overriddenDescriptors.all { it.isFromLibrary() } } return false } private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean { val owner = typeParameter.containingDeclaration var parent: DeclarationDescriptor? = inDescriptor while (parent != null) { if (parent == owner) return true if (parent is ClassDescriptor && !parent.isInner) return false parent = parent.containingDeclaration } return true } protected fun flushToResultSet() { collector.flushToResultSet() } fun complete(): Boolean { return try { _complete().also { CompletionBenchmarkSink.instance.onCompletionEnded(this, false) } } catch (pce: ProcessCanceledException) { CompletionBenchmarkSink.instance.onCompletionEnded(this, true) throw pce } } private fun _complete(): Boolean { // we restart completion when prefix becomes "get" or "set" to ensure that properties get lower priority comparing to get/set functions (see KT-12299) val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("get or set prefix") { override fun accepts(prefix: String, context: ProcessingContext?) = prefix == "get" || prefix == "set" }) collector.restartCompletionOnPrefixChange(prefixPattern) val statisticsContext = calcContextForStatisticsInfo() if (statisticsContext != null) { collector.addLookupElementPostProcessor { lookupElement -> // we should put data into the original element because of DecoratorCompletionStatistician lookupElement.putUserDataDeep(STATISTICS_INFO_CONTEXT_KEY, statisticsContext) lookupElement } } doComplete() flushToResultSet() return !collector.isResultEmpty } fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) { collector.addLookupElementPostProcessor(processor) } protected abstract fun doComplete() protected abstract val descriptorKindFilter: DescriptorKindFilter? protected abstract val expectedInfos: Collection<ExpectedInfo> protected val importableFqNameClassifier = ImportableFqNameClassifier(file) @Suppress("InvalidBundleOrProperty") //workaround to avoid false-positive: KTIJ-19892 protected open fun createSorter(): CompletionSorter { var sorter = CompletionSorter.defaultSorter(parameters, prefixMatcher)!! sorter = sorter.weighBefore( "stats", DeprecatedWeigher, PriorityWeigher, PreferGetSetMethodsToPropertyWeigher, NotImportedWeigher(importableFqNameClassifier), NotImportedStaticMemberWeigher(importableFqNameClassifier), KindWeigher, CallableWeigher ) sorter = sorter.weighAfter("stats", VariableOrFunctionWeigher, ImportedWeigher(importableFqNameClassifier)) val preferContextElementsWeigher = PreferContextElementsWeigher(inDescriptor) sorter = if (callTypeAndReceiver is CallTypeAndReceiver.SUPER_MEMBERS) { // for completion after "super." strictly prefer the current member sorter.weighBefore("kotlin.deprecated", preferContextElementsWeigher) } else { sorter.weighBefore("kotlin.proximity", preferContextElementsWeigher) } sorter = sorter.weighBefore("middleMatching", PreferMatchingItemWeigher) // we insert one more RealPrefixMatchingWeigher because one inserted in default sorter is placed in a bad position (after "stats") sorter = sorter.weighAfter("lift.shorter", RealPrefixMatchingWeigher()) sorter = sorter.weighAfter("kotlin.proximity", ByNameAlphabeticalWeigher, PreferLessParametersWeigher) sorter = sorter.weighBefore("prefix", KotlinUnwantedLookupElementWeigher) sorter = if (expectedInfos.all { it.fuzzyType?.type?.isUnit() == true }) { sorter.weighBefore("prefix", PreferDslMembers) } else { sorter.weighAfter("kotlin.preferContextElements", PreferDslMembers) } return sorter } protected fun calcContextForStatisticsInfo(): String? { if (expectedInfos.isEmpty()) return null var context = expectedInfos .mapNotNull { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName } .distinct() .singleOrNull() ?.let { "expectedType=$it" } if (context == null) { context = expectedInfos .mapNotNull { it.expectedName } .distinct() .singleOrNull() ?.let { "expectedName=$it" } } return context } protected val referenceVariantsCollector = if (nameExpression != null) { ReferenceVariantsCollector( referenceVariantsHelper, indicesHelper(true), prefixMatcher, nameExpression, callTypeAndReceiver, resolutionFacade, bindingContext, importableFqNameClassifier, configuration ) } else { null } protected fun ReferenceVariants.excludeNonInitializedVariable(): ReferenceVariants { return ReferenceVariants(referenceVariantsHelper.excludeNonInitializedVariable(imported, position), notImportedExtensions) } protected fun referenceVariantsWithSingleFunctionTypeParameter(): ReferenceVariants? { val variants = referenceVariantsCollector?.allCollected ?: return null val filter = { descriptor: DeclarationDescriptor -> descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(descriptor) } return ReferenceVariants(variants.imported.filter(filter), variants.notImportedExtensions.filter(filter)) } protected fun getRuntimeReceiverTypeReferenceVariants(lookupElementFactory: LookupElementFactory): Pair<ReferenceVariants, LookupElementFactory>? { val evaluator = file.getCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) ?: return null val referenceVariants = referenceVariantsCollector?.allCollected ?: return null val explicitReceiver = callTypeAndReceiver.receiver as? KtExpression ?: return null val type = bindingContext.getType(explicitReceiver) ?: return null if (!TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)) return null val runtimeType = evaluator(explicitReceiver) if (runtimeType == null || runtimeType == type) return null val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType, bindingContext) val (variants, notImportedExtensions) = ReferenceVariantsCollector( referenceVariantsHelper, indicesHelper(true), prefixMatcher, nameExpression!!, callTypeAndReceiver, resolutionFacade, bindingContext, importableFqNameClassifier, configuration, runtimeReceiver = expressionReceiver ).collectReferenceVariants(descriptorKindFilter!!) val filteredVariants = filterVariantsForRuntimeReceiverType(variants, referenceVariants.imported) val filteredNotImportedExtensions = filterVariantsForRuntimeReceiverType(notImportedExtensions, referenceVariants.notImportedExtensions) val runtimeVariants = ReferenceVariants(filteredVariants, filteredNotImportedExtensions) return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType, 0)))) } private fun <TDescriptor : DeclarationDescriptor> filterVariantsForRuntimeReceiverType( runtimeVariants: Collection<TDescriptor>, baseVariants: Collection<TDescriptor> ): Collection<TDescriptor> { val baseVariantsByName = baseVariants.groupBy { it.name } val result = ArrayList<TDescriptor>() for (variant in runtimeVariants) { val candidates = baseVariantsByName[variant.name] if (candidates == null || candidates.none { compareDescriptors(project, variant, it) }) { result.add(variant) } } return result } protected open fun shouldCompleteTopLevelCallablesFromIndex(): Boolean { if (nameExpression == null) return false if ((descriptorKindFilter?.kindMask ?: 0).and(DescriptorKindFilter.CALLABLES_MASK) == 0) return false if (callTypeAndReceiver is CallTypeAndReceiver.IMPORT_DIRECTIVE) return false return callTypeAndReceiver.receiver == null } protected fun processTopLevelCallables(processor: (CallableDescriptor) -> Unit) { val shadowedFilter = ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, nameExpression!!, callTypeAndReceiver) ?.createNonImportedDeclarationsFilter<CallableDescriptor>(referenceVariantsCollector!!.allCollected.imported) indicesHelper(true).processTopLevelCallables({ prefixMatcher.prefixMatches(it) }) { if (shadowedFilter != null) { shadowedFilter(listOf(it)).singleOrNull()?.let(processor) } else { processor(it) } } } protected fun withCollectRequiredContextVariableTypes(action: (LookupElementFactory) -> Unit): Collection<FuzzyType> { val provider = CollectRequiredTypesContextVariablesProvider() val lookupElementFactory = createLookupElementFactory(provider) action(lookupElementFactory) return provider.requiredTypes } protected fun withContextVariablesProvider(contextVariablesProvider: ContextVariablesProvider, action: (LookupElementFactory) -> Unit) { val lookupElementFactory = createLookupElementFactory(contextVariablesProvider) action(lookupElementFactory) } protected open fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory { return LookupElementFactory( basicLookupElementFactory, receiverTypes, callTypeAndReceiver.callType, inDescriptor, contextVariablesProvider ) } protected fun detectReceiverTypes( bindingContext: BindingContext, nameExpression: KtSimpleNameExpression, callTypeAndReceiver: CallTypeAndReceiver<*, *> ): List<ReceiverType>? { var receiverTypes = callTypeAndReceiver.receiverTypesWithIndex( bindingContext, nameExpression, moduleDescriptor, resolutionFacade, stableSmartCastsOnly = true, /* we don't include smart cast receiver types for "unstable" receiver value to mark members grayed */ withImplicitReceiversWhenExplicitPresent = true ) if (callTypeAndReceiver is CallTypeAndReceiver.SAFE || isDebuggerContext) { receiverTypes = receiverTypes?.map { ReceiverType(it.type.makeNotNullable(), it.receiverIndex) } } return receiverTypes } }
apache-2.0
82e33f596f0c229042b0e6195606d932
45.632319
158
0.733879
5.981376
false
false
false
false
mhshams/yekan
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/Future.kt
2
1105
package io.vertx.kotlin.core import io.vertx.core.AsyncResult import io.vertx.kotlin.core.internal.Delegator import io.vertx.kotlin.core.internal.KotlinAsyncHandler /** */ class Future<T>(override val delegate: io.vertx.core.Future<T>) : Delegator<io.vertx.core.Future<T>> { companion object { fun future<T>(): Future<T> = Future(io.vertx.core.Future.future()) fun succeededFuture<T>(): Future<T> = Future(io.vertx.core.Future.succeededFuture()) fun succeededFuture<T>(result: T): Future<T> = Future(io.vertx.core.Future.succeededFuture(result)) fun failedFuture<T>(failureMessage: String): Future<T> = Future(io.vertx.core.Future.failedFuture(failureMessage)) } fun isComplete(): Boolean = delegate.isComplete() fun setHandler(handler: (AsyncResult<T>) -> Unit) { delegate.setHandler(KotlinAsyncHandler(handler, { it })) } fun complete(result: T) { delegate.complete(result) } fun complete() { delegate.complete() } fun fail(failureMessage: String) { delegate.fail(failureMessage) } }
apache-2.0
96dc2bd1d496b25a1301fdc459ed91d3
28.864865
122
0.678733
3.810345
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/RequestBuilder.kt
1
5154
package ch.rmy.android.http_shortcuts.http import ch.rmy.android.framework.extensions.runIfNotNull import ch.rmy.android.http_shortcuts.exceptions.InvalidBearerAuthException import ch.rmy.android.http_shortcuts.exceptions.InvalidHeaderException import ch.rmy.android.http_shortcuts.exceptions.InvalidUrlException import ch.rmy.android.http_shortcuts.http.RequestUtil.FORM_MULTIPART_CONTENT_TYPE import ch.rmy.android.http_shortcuts.http.RequestUtil.FORM_URLENCODE_CONTENT_TYPE import ch.rmy.android.http_shortcuts.http.RequestUtil.encode import ch.rmy.android.http_shortcuts.http.RequestUtil.getMediaType import okhttp3.Credentials import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.internal.http.HttpMethod import java.io.InputStream import java.net.URISyntaxException import java.nio.charset.StandardCharsets.UTF_8 class RequestBuilder(private val method: String, url: String) { private val requestBuilder = Request.Builder() .also { try { it.url(url) } catch (e: IllegalArgumentException) { throw InvalidUrlException(url, e.message) } catch (e: URISyntaxException) { throw InvalidUrlException(url) } } private var body: String? = null private var bodyStream: InputStream? = null private var bodyLength: Long? = null private var contentType: String? = null private var userAgent: String? = null private val parameters = mutableListOf<Parameter>() fun basicAuth(username: String, password: String) = also { requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, Credentials.basic(username, password, UTF_8)) } fun bearerAuth(authToken: String) = also { try { requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, "Bearer $authToken") } catch (e: IllegalArgumentException) { throw InvalidBearerAuthException(authToken) } } fun body(body: String) = also { this.body = body } fun body(inputStream: InputStream, length: Long?) = also { this.bodyStream = inputStream this.bodyLength = length } fun parameter(name: String, value: String) = also { parameters.add(Parameter.StringParameter(name, value)) } fun fileParameter( name: String, fileName: String, type: String, data: InputStream, length: Long?, ) = also { parameters.add( Parameter.FileParameter( name, fileName, type, data, length, ) ) } fun header(name: String, value: String) = also { try { requestBuilder.addHeader(name, value) } catch (e: IllegalArgumentException) { throw InvalidHeaderException("$name: $value") } when { name.equals(HttpHeaders.CONTENT_TYPE, ignoreCase = true) -> { contentType = value } name.equals(HttpHeaders.USER_AGENT, ignoreCase = true) -> { userAgent = null } } } fun userAgent(userAgent: String) = also { this.userAgent = userAgent } fun contentType(contentType: String?) = also { this.contentType = contentType } fun build(): Request = requestBuilder .run { method( method, if (HttpMethod.permitsRequestBody(method)) { getBody() } else null, ) } .runIfNotNull(userAgent) { header(HttpHeaders.USER_AGENT, it) } .build() sealed class Parameter(val name: String) { class StringParameter( name: String, val value: String, ) : Parameter(name) class FileParameter( name: String, val fileName: String, val type: String, val data: InputStream, val length: Long?, ) : Parameter(name) } private fun getBody(): RequestBody = when { contentType == FORM_MULTIPART_CONTENT_TYPE -> FormMultipartRequestBody(parameters) contentType == FORM_URLENCODE_CONTENT_TYPE -> constructBodyFromString(constructFormUrlEncodedBody()) bodyStream != null -> constructBodyFromStream(bodyStream!!, bodyLength) else -> constructBodyFromString(body ?: "") } private fun constructBodyFromString(string: String): RequestBody = string.toByteArray().let { content -> content.toRequestBody(getMediaType(contentType), 0, content.size) } private fun constructBodyFromStream(stream: InputStream, length: Long?): RequestBody = StreamRequestBody(contentType, stream, length) private fun constructFormUrlEncodedBody(): String = parameters .filterIsInstance<Parameter.StringParameter>() .joinToString(separator = "&") { parameter -> encode(parameter.name) + '=' + encode(parameter.value) } }
mit
f64baeaf945749f12d2a0fa96244d7fb
31.828025
108
0.623205
4.825843
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/group_editor/GroupEditorFragment.kt
1
3023
package com.ivanovsky.passnotes.presentation.group_editor import android.os.Bundle import android.view.* import androidx.lifecycle.observe import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.databinding.GroupEditorFragmentBinding import com.ivanovsky.passnotes.presentation.core.FragmentWithDoneButton import com.ivanovsky.passnotes.presentation.core.DatabaseInteractionWatcher import com.ivanovsky.passnotes.presentation.core.extensions.getMandarotyArgument import com.ivanovsky.passnotes.presentation.core.extensions.hideKeyboard import com.ivanovsky.passnotes.presentation.core.extensions.setupActionBar import com.ivanovsky.passnotes.presentation.core.extensions.withArguments import org.koin.androidx.viewmodel.ext.android.viewModel class GroupEditorFragment : FragmentWithDoneButton() { private val viewModel: GroupEditorViewModel by viewModel() private val args: GroupEditorArgs by lazy { getMandarotyArgument(ARGS) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setupActionBar { title = getScreenTitle() setHomeAsUpIndicator(null) setDisplayHomeAsUpEnabled(true) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return GroupEditorFragmentBinding.inflate(inflater, container, false) .also { it.lifecycleOwner = viewLifecycleOwner it.viewModel = viewModel } .root } override fun onDoneMenuClicked() { viewModel.onDoneButtonClicked() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { viewModel.navigateBack() true } else -> { super.onOptionsItemSelected(item) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycle.addObserver(DatabaseInteractionWatcher(this)) subscribeToLiveData() viewModel.start(args) } private fun subscribeToLiveData() { viewModel.doneButtonVisibility.observe(viewLifecycleOwner) { isVisible -> setDoneButtonVisibility(isVisible) } viewModel.hideKeyboardEvent.observe(viewLifecycleOwner) { hideKeyboard() } } private fun getScreenTitle(): String { return when(args) { is GroupEditorArgs.NewGroup -> getString(R.string.new_group) is GroupEditorArgs.EditGroup -> getString(R.string.edit_group) } } companion object { private const val ARGS = "args" fun newInstance(args: GroupEditorArgs) = GroupEditorFragment().withArguments { putParcelable(ARGS, args) } } }
gpl-2.0
d847c1bb3d5fdc1ec5b58773c81352c6
31.516129
86
0.684089
5.239168
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/template/CommonTagHandler.kt
1
3899
package com.jtransc.ast.template import com.jtransc.ast.* import com.jtransc.error.InvalidOperationException import com.jtransc.error.invalidOp import java.util.* object CommonTagHandler { val ALIASES = listOf("SINIT", "CONSTRUCTOR", "SMETHOD", "IMETHOD", "METHOD", "SFIELD", "IFIELD", "FIELD", "CLASS") private fun getOrReplaceVar(name: String, params: HashMap<String, Any?>): String { val out = if (name.startsWith("#")) { params[name.substring(1)].toString() } else { name } return out } interface Result { val ref: AstRef } data class SINIT(val method: AstMethod) : Result { override val ref = method.ref } data class CONSTRUCTOR(override val ref: AstMethodRef, val method: AstMethod) : Result { } data class METHOD(override val ref: AstMethodRef, val method: AstMethod, val isStatic: Boolean, val includeDot: Boolean) : Result { } data class FIELD(override val ref: AstFieldRef, val field: AstField, val isStatic: Boolean, val includeDot: Boolean) : Result data class CLASS(val clazz: AstClass) : Result { override val ref = clazz.ref } data class CLASS_REF(val clazz: FqName) : Result { override val ref = clazz.ref } private fun resolveClassName(str: String, params: HashMap<String, Any?>): FqName = str.replace('@', '$').fqname fun getRef(program: AstProgram, type: String, desc: String, params: HashMap<String, Any?>): Result { val dataParts = desc.split(':').map { getOrReplaceVar(it, params) } val desc2 = dataParts.joinToString(":") val classFqname = resolveClassName(dataParts[0], params) if (!program.contains(classFqname)) { invalidOp("evalReference: Can't find class '$classFqname' (I)") } val clazz = program[classFqname] val types = program.types val tag = type.toUpperCase() try { return when (tag) { "SINIT" -> SINIT(clazz.getMethod("<clinit>", "()V")!!) "CONSTRUCTOR" -> { if (dataParts.size >= 2) { val ref = AstMethodRef(clazz.name, "<init>", types.demangleMethod(dataParts[1])) CONSTRUCTOR(ref, program[ref] ?: invalidOp("Can't find ref $ref")) } else { val methods = clazz.constructors if (methods.isEmpty()) invalidOp("evalReference: Can't find constructor $desc2") if (methods.size > 1) invalidOp("evalReference: Several signatures for constructor $desc2, please specify signature") val method = methods.first() CONSTRUCTOR(method.ref, method) } } "SMETHOD", "METHOD", "IMETHOD" -> { val isStatic = (tag == "SMETHOD") val includeDot = (tag == "IMETHOD") if (dataParts.size >= 3) { val ref = AstMethodRef(clazz.name, dataParts[1], types.demangleMethod(dataParts[2])) METHOD(ref, program[ref] ?: invalidOp("Can't find ref $ref"), isStatic = isStatic, includeDot = includeDot) } else { val methods = clazz.getMethodsInAncestorsAndInterfaces(dataParts[1]) if (methods.isEmpty()) invalidOp("evalReference: Can't find method $desc2") if (methods.size > 1) invalidOp("evalReference: Several signatures, please specify signature") val method = methods.first() METHOD(method.ref, method, isStatic = isStatic, includeDot = includeDot) } } "SFIELD", "FIELD", "IFIELD" -> { val field = clazz.locateField(dataParts[1]) ?: invalidOp("evalReference: Can't find field $desc2") val isStatic = (tag == "SFIELD") val includeDot = (tag == "IFIELD") FIELD(field.ref, field, isStatic = isStatic, includeDot = includeDot) } "CLASS" -> CLASS(clazz) else -> invalidOp("evalReference: Unknown type!") } } catch (e: Throwable) { throw InvalidOperationException("Invalid: $type $desc : ${e.message}", e) } } fun getClassRef(program: AstProgram, type: String, desc: String, params: HashMap<String, Any?>): FqName { val dataParts = desc.split(':').map { getOrReplaceVar(it, params) } return resolveClassName(dataParts[0], params) } }
apache-2.0
be874fa70fc884221d3b9ba33538b4a6
38.795918
132
0.677353
3.468861
false
false
false
false
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/actions/vtype/vevent/VEventAction.kt
1
2592
package de.markusfisch.android.binaryeye.actions.vtype.vevent import android.content.Context import android.content.Intent import android.os.Build import android.provider.CalendarContract import android.support.annotation.RequiresApi import de.markusfisch.android.binaryeye.R import de.markusfisch.android.binaryeye.actions.IntentAction import de.markusfisch.android.binaryeye.actions.vtype.VTypeParser import java.text.SimpleDateFormat import java.util.* object VEventAction : IntentAction() { override val iconResId: Int get() = R.drawable.ic_action_vevent override val titleResId: Int get() = R.string.vevent_add override val errorMsg: Int get() = R.string.vevent_failed override fun canExecuteOn(data: ByteArray): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return false } val type = VTypeParser.parseVType(String(data)) return type == "VEVENT" || type == "VCALENDAR" } @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) override suspend fun createIntent(context: Context, data: ByteArray): Intent? { val info = VTypeParser.parseMap(String(data)) return Intent(Intent.ACTION_EDIT).apply { type = "vnd.android.cursor.item/event" info["SUMMARY"]?.singleOrNull()?.also { title -> putExtra(CalendarContract.Events.TITLE, title.value) } info["DESCRIPTION"]?.singleOrNull()?.also { description -> putExtra(CalendarContract.Events.DESCRIPTION, description.value) } info["LOCATION"]?.singleOrNull()?.also { location -> putExtra(CalendarContract.Events.EVENT_LOCATION, location.value) } info["DTSTART"]?.singleOrNull()?.also { eventStart -> dateFormats.simpleFindParse(eventStart.value)?.also { putExtra( CalendarContract.EXTRA_EVENT_BEGIN_TIME, it.time ) } } info["DTEND"]?.singleOrNull()?.also { eventEnd -> dateFormats.simpleFindParse(eventEnd.value)?.also { putExtra( CalendarContract.EXTRA_EVENT_END_TIME, it.time ) } } } } } private val dateFormats = listOf( "yyyy-MM-dd'T'HH:mm:ssXXX", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ssz", "yyyy-MM-dd'T'HH:mm:ss", "yyyyMMdd'T'HHmmssXXX", "yyyyMMdd'T'HHmmssZ", "yyyyMMdd'T'HHmmssz", "yyyyMMdd'T'HHmmss", "yyyy-MM-dd", "yyyyMMdd" ) private fun List<String>.simpleFindParse(date: String): Date? { for (pattern in this) { return SimpleDateFormat( pattern, Locale.getDefault() ).simpleParse(date) ?: continue } return null } private fun SimpleDateFormat.simpleParse(date: String): Date? = try { parse(date) } catch (e: Exception) { null }
mit
0cddcb212e07eadc34405ab2f567e02c
27.173913
80
0.718364
3.260377
false
false
false
false
Wackalooon/EcoMeter
app/src/main/java/com/wackalooon/ecometer/home/HomeFragment.kt
1
2525
package com.wackalooon.ecometer.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import com.wackalooon.ecometer.R import com.wackalooon.ecometer.base.BaseView import com.wackalooon.ecometer.home.adapter.HomeAdapter import com.wackalooon.ecometer.home.adapter.HomeItemDiffCallback import com.wackalooon.ecometer.home.model.HomeEvent import com.wackalooon.ecometer.home.model.HomeItem import com.wackalooon.ecometer.home.model.HomeState import kotlinx.android.synthetic.main.screen_home.* import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch class HomeFragment : BaseView<HomeState>() { private val viewModel: HomeViewModel by viewModels { viewModelFactory } lateinit var adapter: HomeAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.screen_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() subscribeToChanges() } override fun onStart() { super.onStart() viewModel.offerEvent(HomeEvent.LoadMeterDetails) } private fun subscribeToChanges() = launch { viewModel.stateChannel.consumeEach(::render) } private fun setupRecyclerView() { val layoutManager = LinearLayoutManager(activity!!) items_list.layoutManager = layoutManager items_list.isClickable = true adapter = HomeAdapter(HomeItemDiffCallback()) { viewModel.offerEvent(HomeEvent.HomeItemClick) } items_list.adapter = adapter } override fun render(state: HomeState) { state.apply { renderLoadingState(isLoading) renderData(data) renderError(error) } } private fun renderLoadingState(isLoading: Boolean) { if (isLoading) { loading_progress.show() } else { loading_progress.hide() } } private fun renderData(data: List<HomeItem>) { adapter.submitList(data) } private fun renderError(error: String?) { if (error.isNullOrEmpty()) { return } Toast.makeText(activity, error, Toast.LENGTH_SHORT).show() } }
apache-2.0
ad955a7cfb27db9834e1ba9f566bde06
29.792683
116
0.710099
4.641544
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/tv/contactrequest/TVContactRequestDetailPresenter.kt
1
1479
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Hadrien De Sousa <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.tv.contactrequest import androidx.leanback.widget.AbstractDetailsDescriptionPresenter import net.jami.smartlist.ConversationItemViewModel class TVContactRequestDetailPresenter : AbstractDetailsDescriptionPresenter() { override fun onBindDescription(viewHolder: ViewHolder, item: Any) { val viewModel = item as ConversationItemViewModel? if (viewModel != null) { val id = viewModel.uriTitle val displayName = viewModel.contactName viewHolder.title.text = displayName if (displayName != id) viewHolder.subtitle.text = id } } }
gpl-3.0
6b1a1794700299310a27d623b27653ac
40.111111
79
0.719405
4.414925
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/rest/XWikiInterceptor.kt
1
3346
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.android.sync.rest import kotlinx.coroutines.launch import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import org.xwiki.android.sync.appCoroutineScope import org.xwiki.android.sync.contactdb.UserAccountId import org.xwiki.android.sync.contactdb.abstracts.UserAccountsCookiesRepository import java.io.IOException private const val HEADER_CONTENT_TYPE = "Content-type" private const val HEADER_ACCEPT = "Accept" private const val HEADER_COOKIE = "Cookie" private const val CONTENT_TYPE = "application/json" /** * Must be used for each [okhttp3.OkHttpClient] which you will create in * [BaseApiManager] bounds. * * @version $Id: 374209a130ca477ae567048f6f4a129ace2ea0d1 $ */ class XWikiInterceptor( private val userAccountId: UserAccountId, private val userAccountsCookiesRepository: UserAccountsCookiesRepository, private val token: String? ) : Interceptor { /** * Add query parameter **media=json**, headers [.HEADER_ACCEPT]=[.CONTENT_TYPE] * and [.HEADER_CONTENT_TYPE]=[.CONTENT_TYPE], also of [.getCookie] will * not be null - header [.HEADER_COOKIE] will be added with value from * [.getCookie]. * * @param chain * @return Response from server with parameters * @throws IOException */ @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val chainRequest = chain.request() var cookie: String? = null appCoroutineScope.launch { cookie = userAccountsCookiesRepository[userAccountId] } val originalHttpUrl = chainRequest.url() val url = originalHttpUrl.newBuilder() .addQueryParameter("media", "json") .build() var builder = Request.Builder() if(token.isNullOrEmpty() || token.contains("JSESSIONID")) { builder = chainRequest .newBuilder() .header(HEADER_CONTENT_TYPE, CONTENT_TYPE) .header(HEADER_ACCEPT, CONTENT_TYPE) .url(url) if (!cookie.isNullOrEmpty()) { builder.header(HEADER_COOKIE, cookie.toString()) } } else { builder = chainRequest .newBuilder() .addHeader("Authorization", "Bearer $token") .url(url) } val request = builder.build() return chain.proceed(request) } }
lgpl-2.1
815f6a242cc15030fa246594355a65a7
33.854167
83
0.678123
4.368146
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/CodeGenerator.kt
3
9698
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.accessors import org.gradle.api.plugins.ExtensionAware import org.gradle.kotlin.dsl.support.unsafeLazy import org.jetbrains.kotlin.lexer.KotlinLexer import org.jetbrains.kotlin.lexer.KtTokens internal data class AccessorScope( private val targetTypesByName: HashMap<AccessorNameSpec, HashSet<TypeAccessibility.Accessible>> = hashMapOf() ) { fun uniqueAccessorsFor(entries: Iterable<ProjectSchemaEntry<TypeAccessibility>>): Sequence<TypedAccessorSpec> = uniqueAccessorsFrom(entries.asSequence().mapNotNull(::typedAccessorSpec)) fun uniqueAccessorsFrom(accessorSpecs: Sequence<TypedAccessorSpec>): Sequence<TypedAccessorSpec> = accessorSpecs.filter(::add) private fun add(accessorSpec: TypedAccessorSpec) = targetTypesOf(accessorSpec.name).add(accessorSpec.receiver) private fun targetTypesOf(accessorNameSpec: AccessorNameSpec): HashSet<TypeAccessibility.Accessible> = targetTypesByName.computeIfAbsent(accessorNameSpec) { hashSetOf() } } internal fun extensionAccessor(spec: TypedAccessorSpec): String = spec.run { when (type) { is TypeAccessibility.Accessible -> accessibleExtensionAccessorFor(receiver.type.kotlinString, name, type.type.kotlinString) is TypeAccessibility.Inaccessible -> inaccessibleExtensionAccessorFor(receiver.type.kotlinString, name, type) } } private fun accessibleExtensionAccessorFor(targetType: String, name: AccessorNameSpec, type: String): String = name.run { """ /** * Retrieves the [$original][$type] extension. */ val $targetType.`$kotlinIdentifier`: $type get() = $thisExtensions.getByName("$stringLiteral") as $type /** * Configures the [$original][$type] extension. */ fun $targetType.`$kotlinIdentifier`(configure: Action<$type>): Unit = $thisExtensions.configure("$stringLiteral", configure) """ } private fun inaccessibleExtensionAccessorFor(targetType: String, name: AccessorNameSpec, typeAccess: TypeAccessibility.Inaccessible): String = name.run { """ /** * Retrieves the `$original` extension. * * ${documentInaccessibilityReasons(name, typeAccess)} */ val $targetType.`$kotlinIdentifier`: Any get() = $thisExtensions.getByName("$stringLiteral") /** * Configures the `$original` extension. * * ${documentInaccessibilityReasons(name, typeAccess)} */ fun $targetType.`$kotlinIdentifier`(configure: Action<Any>): Unit = $thisExtensions.configure("$stringLiteral", configure) """ } internal fun conventionAccessor(spec: TypedAccessorSpec): String = spec.run { when (type) { is TypeAccessibility.Accessible -> accessibleConventionAccessorFor(receiver.type.kotlinString, name, type.type.kotlinString) is TypeAccessibility.Inaccessible -> inaccessibleConventionAccessorFor(receiver.type.kotlinString, name, type) } } private fun accessibleConventionAccessorFor(targetType: String, name: AccessorNameSpec, type: String): String = name.run { """ /** * Retrieves the [$original][$type] convention. * * @deprecated The concept of conventions is deprecated. Use extensions instead. */ val $targetType.`$kotlinIdentifier`: $type get() = $thisConvention.getPluginByName<$type>("$stringLiteral") /** * Configures the [$original][$type] convention. * * @deprecated The concept of conventions is deprecated. Use extensions instead. */ fun $targetType.`$kotlinIdentifier`(configure: Action<$type>): Unit = configure.execute(`$stringLiteral`) """ } private fun inaccessibleConventionAccessorFor(targetType: String, name: AccessorNameSpec, typeAccess: TypeAccessibility.Inaccessible): String = name.run { """ /** * Retrieves the `$original` convention. * * ${documentInaccessibilityReasons(name, typeAccess)} * * @deprecated The concept of conventions is deprecated. Use extensions instead. */ val $targetType.`$kotlinIdentifier`: Any get() = $thisConvention.getPluginByName<Any>("$stringLiteral") /** * Configures the `$original` convention. * * ${documentInaccessibilityReasons(name, typeAccess)} * * @deprecated The concept of conventions is deprecated. Use extensions instead. */ fun $targetType.`$kotlinIdentifier`(configure: Action<Any>): Unit = configure(`$stringLiteral`) """ } internal fun existingTaskAccessor(spec: TypedAccessorSpec): String = spec.run { when (type) { is TypeAccessibility.Accessible -> accessibleExistingTaskAccessorFor(name, type.type.kotlinString) is TypeAccessibility.Inaccessible -> inaccessibleExistingTaskAccessorFor(name, type) } } private fun accessibleExistingTaskAccessorFor(name: AccessorNameSpec, type: String): String = name.run { """ /** * Provides the existing [$original][$type] task. */ val TaskContainer.`$kotlinIdentifier`: TaskProvider<$type> get() = named<$type>("$stringLiteral") """ } private fun inaccessibleExistingTaskAccessorFor(name: AccessorNameSpec, typeAccess: TypeAccessibility.Inaccessible): String = name.run { """ /** * Provides the existing `$original` task. * * ${documentInaccessibilityReasons(name, typeAccess)} */ val TaskContainer.`$kotlinIdentifier`: TaskProvider<Task> get() = named("$stringLiteral") """ } internal fun existingContainerElementAccessor(spec: TypedAccessorSpec): String = spec.run { when (type) { is TypeAccessibility.Accessible -> accessibleExistingContainerElementAccessorFor(receiver.type.kotlinString, name, type.type.kotlinString) is TypeAccessibility.Inaccessible -> inaccessibleExistingContainerElementAccessorFor(receiver.type.kotlinString, name, type) } } private fun accessibleExistingContainerElementAccessorFor(targetType: String, name: AccessorNameSpec, type: String): String = name.run { """ /** * Provides the existing [$original][$type] element. */ val $targetType.`$kotlinIdentifier`: NamedDomainObjectProvider<$type> get() = named<$type>("$stringLiteral") """ } private fun inaccessibleExistingContainerElementAccessorFor(containerType: String, name: AccessorNameSpec, elementType: TypeAccessibility.Inaccessible): String = name.run { """ /** * Provides the existing `$original` element. * * ${documentInaccessibilityReasons(name, elementType)} */ val $containerType.`$kotlinIdentifier`: NamedDomainObjectProvider<Any> get() = named("$stringLiteral") """ } private val thisExtensions = "(this as ${ExtensionAware::class.java.name}).extensions" @Suppress("deprecation") private val thisConvention = "((this as? Project)?.convention ?: (this as ${org.gradle.api.internal.HasConvention::class.java.name}).convention)" internal data class AccessorNameSpec(val original: String) { val kotlinIdentifier get() = original val stringLiteral by unsafeLazy { stringLiteralFor(original) } } internal data class TypedAccessorSpec( val receiver: TypeAccessibility.Accessible, val name: AccessorNameSpec, val type: TypeAccessibility ) private fun stringLiteralFor(original: String) = escapeStringTemplateDollarSign(original) private fun escapeStringTemplateDollarSign(string: String) = string.replace("${'$'}", "${'$'}{'${'$'}'}") private fun accessorNameSpec(originalName: String) = AccessorNameSpec(originalName) internal fun typedAccessorSpec(schemaEntry: ProjectSchemaEntry<TypeAccessibility>) = schemaEntry.takeIf { isLegalAccessorName(it.name) }?.target?.run { when (this) { is TypeAccessibility.Accessible -> TypedAccessorSpec(this, accessorNameSpec(schemaEntry.name), schemaEntry.type) is TypeAccessibility.Inaccessible -> null } } private fun documentInaccessibilityReasons(name: AccessorNameSpec, typeAccess: TypeAccessibility.Inaccessible): String = "`${name.kotlinIdentifier}` is not accessible in a type safe way because:\n${typeAccess.reasons.joinToString("\n") { reason -> " * - ${reason.explanation}" }}" internal fun isLegalAccessorName(name: String): Boolean = isKotlinIdentifier("`$name`") && name.indexOfAny(invalidNameChars) < 0 private val invalidNameChars = charArrayOf('.', '/', '\\') private fun isKotlinIdentifier(candidate: String): Boolean = KotlinLexer().run { start(candidate) tokenStart == 0 && tokenEnd == candidate.length && tokenType == KtTokens.IDENTIFIER }
apache-2.0
2172a997316a8d8bd21c279c80b21b72
30.083333
164
0.680243
4.613701
false
false
false
false
AK-47-D/cms
src/main/kotlin/com/ak47/cms/cms/entity/FinanceInfoCalendar.kt
1
1255
package com.ak47.cms.cms.entity import java.util.* import javax.persistence.* /** * 财经日历 */ @Entity @Table(name = "finance_info_calendar", indexes = arrayOf(Index(name = "item_id", unique = true, columnList = "item_id"))) class FinanceInfoCalendar { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long = -1 @Column(name = "item_id", unique = true) var item_id = "" @Column(name = "importance") var importance = 0 @Column(name = "previous") var previous = "" @Column(name = "actual") var actual = "" @Column(name = "forecast") var forecast = "" @Column(name = "revised") var revised = "" @Column(name = "stars") var stars = -1 @Column(name = "timestamp") var timestamp = Date() @Column(name = "title") var title = "" @Column(name = "accurate_flag") var accurate_flag = "" @Column(name = "calendar_type") var calendar_type = "" @Column(name = "category_id") var category_id = "" @Column(name = "country") var country = "" @Column(name = "currency") var currency = "" @Column(name = "flag_url") var flagURL = "" @Column(name = "date_stamp") var date_stamp = Date() }
apache-2.0
bc41bb2bfb1cf1a6bf6841f228fb1e03
16.828571
121
0.578188
3.425824
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchInsertStatement.kt
1
3252
package org.jetbrains.exposed.sql.statements import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.isAutoInc import org.jetbrains.exposed.sql.vendors.currentDialect import java.sql.ResultSet import java.util.* open class BatchInsertStatement(table: Table, ignore: Boolean = false): InsertStatement<List<Map<Column<*>, Any>>>(table, ignore) { override val flushCache: Boolean = false // REVIEW override val isAlwaysBatch = true val data = ArrayList<MutableMap<Column<*>, Any?>>() fun addBatch() { if (data.isNotEmpty()) { data[data.size - 1] = LinkedHashMap(values) values.clear() } data.add(values) arguments = null } private var arguments: List<List<Pair<Column<*>, Any?>>>? = null get() = field ?: data.map { single -> valuesAndDefaults().keys.map { it to (single[it] ?: it.defaultValueFun?.invoke() ?: it.dbDefaultValue?.let { DefaultValueMarker }) } }.apply { field = this } override fun arguments() = arguments!!.map { it.map { it.first.columnType to it.second }.filter { it.second != DefaultValueMarker} } override fun generatedKeyFun(rs: ResultSet, inserted: Int): List<Map<Column<*>, Any>>? { val autoGeneratedKeys = arrayListOf<MutableMap<Column<*>, Any>>() val firstAutoIncColumn = table.columns.firstOrNull { it.columnType.isAutoInc } if (firstAutoIncColumn != null) { while (rs.next()) { autoGeneratedKeys.add(hashMapOf(firstAutoIncColumn to rs.getObject(1))) } if (inserted > 1 && !currentDialect.supportsMultipleGeneratedKeys) { // H2/SQLite only returns one last generated key... (autoGeneratedKeys[0][firstAutoIncColumn] as? Number)?.toLong()?.let { var id = it while (autoGeneratedKeys.size < inserted) { id -= 1 autoGeneratedKeys.add(0, hashMapOf(firstAutoIncColumn to id)) } } } /** FIXME: https://github.com/JetBrains/Exposed/issues/129 * doesn't work with MySQL `INSERT ... ON DUPLICATE UPDATE` */ // assert(isIgnore || autoGeneratedKeys.isEmpty() || autoGeneratedKeys.size == inserted) { // "Number of autoincs (${autoGeneratedKeys.size}) doesn't match number of batch entries ($inserted)" // } } // REVIEW arguments!!.forEachIndexed { i, pairs -> pairs.forEach { (col, value) -> val itemIndx = i if (!col.columnType.isAutoInc) { val map = autoGeneratedKeys.getOrElse(itemIndx) { hashMapOf<Column<*>, Any>().apply { autoGeneratedKeys.add(itemIndx, this) } } if (col.defaultValueFun != null && value != null && data[itemIndx][col] == null) { map[col] = value } } } } return autoGeneratedKeys } }
mit
0f23e75562ac7f1df8fafcd37423a2ab
38.180723
136
0.557503
4.632479
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/CharacterCommand.kt
1
4067
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.command.character.card.CharacterCardCommand import com.rpkit.characters.bukkit.command.character.create.CharacterNewCommand import com.rpkit.characters.bukkit.command.character.delete.CharacterDeleteCommand import com.rpkit.characters.bukkit.command.character.hide.CharacterHideCommand import com.rpkit.characters.bukkit.command.character.list.CharacterListCommand import com.rpkit.characters.bukkit.command.character.set.CharacterSetCommand import com.rpkit.characters.bukkit.command.character.switch.CharacterSwitchCommand import com.rpkit.characters.bukkit.command.character.unhide.CharacterUnhideCommand import com.rpkit.core.bukkit.command.toBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Character command. * Parent command for all character management commands. */ class CharacterCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor { private val characterSetCommand = CharacterSetCommand(plugin) private val characterHideCommand = CharacterHideCommand(plugin).toBukkit() private val characterUnhideCommand = CharacterUnhideCommand(plugin).toBukkit() private val characterCardCommand = CharacterCardCommand(plugin) private val characterSwitchCommand = CharacterSwitchCommand(plugin) private val characterListCommand = CharacterListCommand(plugin) private val characterNewCommand = CharacterNewCommand(plugin) private val characterDeleteCommand = CharacterDeleteCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() if (args[0].equals("set", ignoreCase = true)) { return characterSetCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("hide", ignoreCase = true)) { return characterHideCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("unhide", ignoreCase = true)) { return characterUnhideCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("card", ignoreCase = true) || args[0].equals("show", ignoreCase = true) || args[0].equals("view", ignoreCase = true)) { return characterCardCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("switch", ignoreCase = true)) { return characterSwitchCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("list", ignoreCase = true)) { return characterListCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("new", ignoreCase = true) || args[0].equals("create", ignoreCase = true)) { return characterNewCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("delete", ignoreCase = true)) { return characterDeleteCommand.onCommand(sender, command, label, newArgs) } else { sender.sendMessage(plugin.messages["character-usage"]) } } else { sender.sendMessage(plugin.messages["character-usage"]) } return true } }
apache-2.0
777884d3f69a135283e2684c50b86491
52.513158
157
0.723875
4.539063
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/db/WidgetTable.kt
1
1772
package fr.geobert.efficio.db import android.content.ContentValues import android.content.Context import android.database.Cursor object WidgetTable : BaseTable() { override val TABLE_NAME: String = "widgets" val TAG = "WidgetTable" val COL_WIDGET_ID = "widget_id" val COL_STORE_ID = "store_id" val COL_OPACITY = "opacity" val TABLE_JOINED = "$TABLE_NAME " + "${leftOuterJoin(TABLE_NAME, COL_STORE_ID, StoreTable.TABLE_NAME)} " val RESTRICT_TO_WIDGET = "(${WidgetTable.TABLE_NAME}.${WidgetTable.COL_WIDGET_ID} = ?)" override fun CREATE_COLUMNS(): String = "$COL_WIDGET_ID INTEGER NOT NULL, " + "$COL_STORE_ID INTEGER NOT NULL, " + "$COL_OPACITY FLOAT NOT NULL" override val COLS_TO_QUERY: Array<String> = arrayOf(COL_STORE_ID, COL_OPACITY, "${StoreTable.TABLE_NAME}.${StoreTable.COL_NAME}") fun create(ctx: Context, widgetId: Int, storeId: Long, opacity: Float): Long { val v = ContentValues() v.put(COL_WIDGET_ID, widgetId) v.put(COL_STORE_ID, storeId) v.put(COL_OPACITY, opacity) return insert(ctx, v) } fun delete(ctx: Context, widgetId: Int): Int { return super.delete(ctx, widgetId.toLong()) } fun getWidgetInfo(ctx: Context, widgetId: Int): Cursor? { return ctx.contentResolver.query(WidgetTable.CONTENT_URI, WidgetTable.COLS_TO_QUERY, RESTRICT_TO_WIDGET, arrayOf(widgetId.toString()), null) } fun update(ctx: Context, widgetId: Int, storeId: Long, opacity: Float): Int { val v = ContentValues() v.put(COL_STORE_ID, storeId) v.put(COL_OPACITY, opacity) return ctx.contentResolver.update(WidgetTable.CONTENT_URI, v, "widget_id = $widgetId", null) } }
gpl-2.0
55cce844c26f76a9640290c58fc802f2
35.9375
133
0.64842
3.623722
false
false
false
false
waicool20/SikuliCef
src/main/kotlin/com/waicool20/sikulicef/wrappers/CefRegion.kt
1
10501
/* * GPLv3 License * Copyright (c) SikuliCef by waicool20 * * 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 * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.waicool20.sikulicef.wrappers import com.waicool20.sikulicef.graphical.CefHighlighter import com.waicool20.sikulicef.input.CefKeyBoard import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.delay import org.sikuli.basics.Settings import org.sikuli.script.* import java.awt.Rectangle import java.awt.event.KeyEvent import java.util.concurrent.TimeUnit open class CefRegion(xPos: Int, yPos: Int, width: Int, height: Int, screen: IScreen? = CefScreen.getScreen()) : Region() { constructor(region: Region, screen: IScreen? = CefScreen.getScreen()) : this(region.x, region.y, region.w, region.h, screen) constructor(rect: Rectangle, screen: IScreen? = CefScreen.getScreen()) : this(rect.x, rect.y, rect.width, rect.height, screen) init { x = xPos y = yPos w = width h = height if (screen != null) this.screen = screen } private val mouse by lazy { (this.screen as CefScreen).mouse } private val keyboard by lazy { (this.screen as CefScreen).keyboard } override fun setLocation(loc: Location): CefRegion { x = loc.x y = loc.y return this } override fun setROI() = setROI(screen.bounds) override fun setROI(rect: Rectangle) = with(rect) { setROI(x, y, width, height) } override fun setROI(region: Region) = with(region) { setROI(x, y, w, h) } override fun setROI(X: Int, Y: Int, W: Int, H: Int) { x = X y = Y w = if (W > 1) W else 1 h = if (H > 1) H else 1 } override fun getCenter() = Location(x + (w / 2), y + (h / 2)) override fun getTopLeft() = Location(x, y) override fun getTopRight() = Location(x + w - 1, y) override fun getBottomLeft() = Location(x, y + h - 1) override fun getBottomRight() = Location(x + w - 1, y + h - 1) override fun getLastMatch() = super.getLastMatch()?.let(::CefMatch) override fun getLastMatches() = super.getLastMatches().asSequence().toList().map(::CefMatch).iterator() override fun offset(loc: Location?) = CefRegion(super.offset(loc), screen) override fun above() = CefRegion(super.above(), screen) override fun below() = CefRegion(super.below(), screen) override fun left() = CefRegion(super.left(), screen) override fun right() = CefRegion(super.right(), screen) override fun above(height: Int) = CefRegion(super.above(height), screen) override fun below(height: Int) = CefRegion(super.below(height), screen) override fun left(width: Int) = CefRegion(super.left(width), screen) override fun right(width: Int) = CefRegion(super.right(width), screen) /* Search operations */ override fun <PSI : Any?> find(target: PSI) = super.find(target)?.let(::CefMatch) override fun <PSI : Any?> findAll(target: PSI) = super.findAll(target).asSequence().toList().map(::CefMatch).iterator() override fun <PSI : Any?> wait(target: PSI) = super.wait(target).let(::CefMatch) override fun <PSI : Any?> wait(target: PSI, timeout: Double) = super.wait(target, timeout)?.let(::CefMatch) override fun <PSI : Any?> exists(target: PSI) = super.exists(target)?.let(::CefMatch) override fun <PSI : Any?> exists(target: PSI, timeout: Double) = super.exists(target, timeout)?.let(::CefMatch) //<editor-fold desc="Mouse and KeyboardActions"> override fun click(): Int = click(center, 0) override fun <PFRML : Any?> click(target: PFRML): Int = click(target, 0) override fun <PFRML : Any?> click(target: PFRML, modifiers: Int): Int = try { getLocationFromTarget(target)?.let { mouse.click(it, Mouse.LEFT, modifiers) 1 } ?: 0 } catch (e: FindFailed) { 0 } override fun doubleClick(): Int = doubleClick(center, 0) override fun <PFRML : Any?> doubleClick(target: PFRML): Int = doubleClick(target, 0) override fun <PFRML : Any?> doubleClick(target: PFRML, modifiers: Int): Int = try { getLocationFromTarget(target)?.let { mouse.doubleClick(it, Mouse.LEFT, modifiers) 1 } ?: 0 } catch (e: FindFailed) { 0 } override fun rightClick(): Int = rightClick(center, 0) override fun <PFRML : Any?> rightClick(target: PFRML): Int = rightClick(target, 0) override fun <PFRML : Any?> rightClick(target: PFRML, modifiers: Int): Int = try { getLocationFromTarget(target)?.let { mouse.click(it, Mouse.RIGHT, modifiers) 1 } ?: 0 } catch (e: FindFailed) { 0 } override fun hover(): Int = hover(center) override fun <PFRML : Any?> hover(target: PFRML): Int = try { getLocationFromTarget(target)?.let { mouse.moveTo(it) 1 } ?: 0 } catch (e: FindFailed) { 0 } override fun <PFRML : Any?> dragDrop(target: PFRML): Int = dragDrop(lastMatch, target) override fun <PFRML : Any?> dragDrop(t1: PFRML, t2: PFRML): Int = getLocationFromTarget(t1)?.let { l1 -> getLocationFromTarget(t2)?.let { mouse.dragDrop(l1, it) } } ?: 0 override fun <PFRML : Any?> drag(target: PFRML): Int = getLocationFromTarget(target)?.let { mouse.drag(it) } ?: 0 override fun <PFRML : Any?> dropAt(target: PFRML): Int = getLocationFromTarget(target)?.let { mouse.dropAt(it) } ?: 0 override fun type(text: String): Int = type(text, 0) override fun type(text: String, modifiers: String): Int = type(text, CefKeyBoard.parseModifiers(modifiers)) override fun type(text: String, modifiers: Int): Int { keyboard.type(null, text, modifiers) return 1 } override fun <PFRML : Any?> type(target: PFRML, text: String): Int = type(target, text, 0) override fun <PFRML : Any?> type(target: PFRML, text: String, modifiers: String): Int = type(target, text, CefKeyBoard.parseModifiers(modifiers)) override fun <PFRML : Any?> type(target: PFRML, text: String, modifiers: Int): Int = try { keyboard.type(getLocationFromTarget(target), text, modifiers) 1 } catch (e: FindFailed) { 0 } override fun paste(text: String): Int = paste(null, text) override fun <PFRML : Any?> paste(target: PFRML, text: String): Int { if (text.isEmpty() || (target != null && click(target) == 1)) return 1 (screen as CefScreen).clipboard = text keyboard.atomicAction { keyDown(Key.getHotkeyModifier()) keyDown(KeyEvent.VK_V) keyUp(KeyEvent.VK_V) keyUp(Key.getHotkeyModifier()) } return 0 } //</editor-fold> //<editor-fold desc="Low-level Mouse and Keyboard Actions"> override fun mouseDown(buttons: Int) = mouse.mouseDown(buttons) override fun mouseUp() { mouse.mouseUp() } override fun mouseUp(buttons: Int) { mouse.mouseUp(buttons) } override fun mouseMove(): Int = if (lastMatch != null) mouseMove(lastMatch) else 0 override fun mouseMove(xoff: Int, yoff: Int): Int = mouseMove(Location(x + xoff, y + yoff)) override fun <PFRML : Any?> mouseMove(target: PFRML): Int = try { getLocationFromTarget(target)?.let { mouse.moveTo(it) 1 } ?: 0 } catch (e: FindFailed) { 0 } override fun wheel(direction: Int, steps: Int): Int = wheel(mouse.getCurrentMouseLocation(), direction, steps) override fun <PFRML : Any?> wheel(target: PFRML, direction: Int, steps: Int): Int = wheel(target, direction, steps, Mouse.WHEEL_STEP_DELAY) override fun <PFRML : Any?> wheel(target: PFRML, direction: Int, steps: Int, stepDelay: Int): Int = getLocationFromTarget(target)?.let { mouse.spinWheel(it, direction, steps, stepDelay) 1 } ?: 0 override fun keyDown(keycode: Int) = keyboard.keyDown(keycode) override fun keyDown(keys: String) = keyboard.keyDown(keys) override fun keyUp() = keyboard.keyUp() override fun keyUp(keycode: Int) = keyboard.keyUp(keycode) override fun keyUp(keys: String) = keyboard.keyUp(keys) //</editor-fold> //<editor-fold desc="Highlight Action"> private val highlighter by lazy { CefHighlighter(this) } override fun highlight(): Region = highlight("") override fun highlight(color: String): Region { highlighter.setColor(color) highlighter.toggle() return this } override fun highlight(secs: Int): Region = highlight(secs, "") override fun highlight(secs: Float): Region = highlight(secs, "") override fun highlight(secs: Int, color: String): Region = highlight(secs.toFloat(), color) override fun highlight(secs: Float, color: String): Region { highlight(color) async(CommonPool) { delay((if (secs < 0.1) Settings.SlowMotionDelay else secs * 1000L).toLong(), TimeUnit.MILLISECONDS) highlight() } return this } //</editor-fold> override fun <PSIMRL> getLocationFromTarget(target: PSIMRL): Location? = when (target) { is Pattern, is String, is Image -> find(target)?.target is Match -> target.target is CefRegion -> target.center is Region -> target.center is Location -> target else -> throw FindFailed("") }?.setOtherScreen(screen) }
gpl-3.0
a0d4d5764713ba2f485f43a817e2b088
38.927757
143
0.615941
3.913902
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/reminders/ReminderState.kt
1
2748
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.reminders import android.annotation.SuppressLint import android.content.Context import com.github.quarck.calnotify.utils.PersistentStorageBase class ReminderState(ctx: Context) : PersistentStorageBase(ctx, PREFS_NAME) { var reminderLastFireTime by LongProperty(0, REMINDER_LAST_FIRE_TIME_KEY) var numRemindersFired by IntProperty(0, NUM_REMINDERS_FIRED_KEY) var quietHoursOneTimeReminderEnabled by BooleanProperty(false, QUIET_HOURS_ONE_TIME_REMINDER_KEY) var nextFireExpectedAt by LongProperty(0, NEXT_FIRE_EXPECTED_AT_KEY) var currentReminderPatternIndex by IntProperty(0, CURRENT_REMINDER_PATTERN_IDX_KEY) @SuppressLint("CommitPrefEdits") fun onReminderFired(currentTime: Long) { val quietHoursOneTime = quietHoursOneTimeReminderEnabled val numReminders = numRemindersFired val currentIdx = currentReminderPatternIndex val editor = edit() if (quietHoursOneTime) editor.putBoolean(QUIET_HOURS_ONE_TIME_REMINDER_KEY, false) else editor.putInt(NUM_REMINDERS_FIRED_KEY, numReminders + 1) editor.putLong(REMINDER_LAST_FIRE_TIME_KEY, currentTime) editor.putInt(CURRENT_REMINDER_PATTERN_IDX_KEY, currentIdx + 1) editor.commit() } fun onUserInteraction(currentTime: Long) { // update last fire time to prevent from firing too yearly reminderLastFireTime = currentTime } fun onNewEventFired() { currentReminderPatternIndex = 0; } companion object { const val PREFS_NAME: String = "reminder_state" const val REMINDER_LAST_FIRE_TIME_KEY = "A" const val NUM_REMINDERS_FIRED_KEY = "B" const val QUIET_HOURS_ONE_TIME_REMINDER_KEY = "C" const val NEXT_FIRE_EXPECTED_AT_KEY = "D" const val CURRENT_REMINDER_PATTERN_IDX_KEY = "E" } }
gpl-3.0
3425a7b6fd3519d6c9ef89c0ed71b92f
32.925926
101
0.712882
4.065089
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/utils/SystemUtils.kt
1
7258
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.utils import android.annotation.SuppressLint import android.app.AlarmManager import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.AudioManager import android.os.Build import android.os.PowerManager import android.os.Vibrator import android.widget.TimePicker import com.github.quarck.calnotify.Consts import com.github.quarck.calnotify.logs.DevLog @Suppress("UNCHECKED_CAST") fun <T> Context.service(svc: String) = getSystemService(svc) as T val Context.alarmManager: AlarmManager get() = service(Context.ALARM_SERVICE) val Context.audioManager: AudioManager get() = service(Context.AUDIO_SERVICE) val Context.powerManager: PowerManager get() = service(Context.POWER_SERVICE) val Context.vibratorService: Vibrator get() = service(Context.VIBRATOR_SERVICE) val Context.notificationManager: NotificationManager get() = service(Context.NOTIFICATION_SERVICE) fun wakeLocked(pm: PowerManager, timeout: Long, levelAndFlags: Int, tag: String, fn: () -> Unit) { val wakeLock = pm.newWakeLock(levelAndFlags, tag) ?: throw Exception("Failed to acquire wakelock") try { wakeLock.acquire(timeout) fn() } finally { try { wakeLock.release() } catch (ex: Exception) { // ignore } } } fun partialWakeLocked(ctx: Context, timeout: Long, tag: String, fn: () -> Unit) = wakeLocked(ctx.powerManager, timeout, PowerManager.PARTIAL_WAKE_LOCK, tag, fn) val isMarshmallowOrAbove: Boolean get() = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M val isLollipopOrAbove: Boolean get() = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP val isKitkatOrAbove: Boolean get() = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT @SuppressLint("NewApi") fun AlarmManager.setExactAndAlarm( context: Context, useSetAlarmClock: Boolean, // settings: Settings, triggerAtMillis: Long, roughIntentClass: Class<*>, // ignored on KitKat and below exactIntentClass: Class<*>, alarmInfoIntent: Class<*> ) { val LOG_TAG = "AlarmManager.setExactAndAlarm" if (isMarshmallowOrAbove) { // setExactAndAllowWhileIdle supposed to work during idle / doze standby, but it is very non-precise // so set it as a "first thing", followed by more precise alarm val intent = Intent(context, roughIntentClass); val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis + Consts.ALARM_THRESHOLD / 3, pendingIntent); // add more precise alarm, depending on the setting it is a setAlarmClock or "setExact" // setAlarmClock is very precise, but it shows UI indicating that alarm is pending // on the other hand setExact is more precise than setExactAndAllowWhileIdle, but it can't // fire during doze / standby val intentExact = Intent(context, exactIntentClass); val pendingIntentExact = PendingIntent.getBroadcast(context, 0, intentExact, PendingIntent.FLAG_UPDATE_CURRENT) //if (settings.useSetAlarmClock) { if (useSetAlarmClock) { val intentInfo = Intent(context, alarmInfoIntent); val pendingIntentInfo = PendingIntent.getActivity(context, 0, intentInfo, PendingIntent.FLAG_UPDATE_CURRENT) val alarmClockInfo = AlarmManager.AlarmClockInfo(triggerAtMillis, pendingIntentInfo) setAlarmClock( alarmClockInfo, pendingIntentExact) DevLog.info(LOG_TAG, "alarm scheduled for $triggerAtMillis using setExactAndAllowWhileIdle(T+8s) + setAlarmClock(T+0)") } else { setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntentExact); DevLog.info(LOG_TAG, "alarm scheduled for $triggerAtMillis using setExactAndAllowWhileIdle(T+8s) + setExact(T+0)") } } else { val intent = Intent(context, exactIntentClass); val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) if (isKitkatOrAbove) { // KitKat way setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent); DevLog.info(LOG_TAG, "alarm scheduled for $triggerAtMillis using setExact(T+0)") } else { // Ancient way set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent); DevLog.info(LOG_TAG, "alarm scheduled for $triggerAtMillis using set(T+0)") } } } fun AlarmManager.cancelExactAndAlarm( context: Context, roughIntentClass: Class<*>, exactIntentClass: Class<*> ) { val LOG_TAG = "AlarmManager.cancelExactAndAlarm" // reverse of the prev guy val intent = Intent(context, roughIntentClass); val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) cancel(pendingIntent); if (isMarshmallowOrAbove) { val intentExact = Intent(context, exactIntentClass); val pendingIntentExact = PendingIntent.getBroadcast(context, 0, intentExact, PendingIntent.FLAG_UPDATE_CURRENT) cancel(pendingIntentExact) } DevLog.info(LOG_TAG, "Cancelled alarm") } @Suppress("DEPRECATION") var TimePicker.hourCompat: Int get() { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) this.hour else this.currentHour } set(value) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) this.hour = value else this.currentHour = value } @Suppress("DEPRECATION") var TimePicker.minuteCompat: Int get() { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) this.minute else this.currentMinute } set(value) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) this.minute = value else this.currentMinute = value } val Exception.detailed: String get() { return "${this}: ${this.message}, stack: ${this.stackTrace.joinToString("\n")}" }
gpl-3.0
d222cb4685026d7bebef62dca1ee8ffd
34.578431
131
0.684899
4.229604
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/activities/RoomImageDialogActivity.kt
1
3731
package be.digitalia.fosdem.activities import android.content.ActivityNotFoundException import android.net.Uri import android.os.Bundle import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.browser.customtabs.CustomTabsIntent import androidx.core.content.ContextCompat import androidx.core.text.set import androidx.lifecycle.LifecycleOwner import be.digitalia.fosdem.R import be.digitalia.fosdem.api.FosdemApi import be.digitalia.fosdem.api.FosdemUrls import be.digitalia.fosdem.utils.configureToolbarColors import be.digitalia.fosdem.utils.invertImageColors import be.digitalia.fosdem.utils.isLightTheme import be.digitalia.fosdem.utils.launchAndRepeatOnLifecycle import be.digitalia.fosdem.utils.toSlug import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject /** * A special Activity which is displayed like a dialog and shows a room image. * Specify the room name and the room image id as Intent extras. * * @author Christophe Beyls */ @AndroidEntryPoint class RoomImageDialogActivity : AppCompatActivity(R.layout.dialog_room_image) { @Inject lateinit var api: FosdemApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent val roomName = intent.getStringExtra(EXTRA_ROOM_NAME)!! title = roomName findViewById<ImageView>(R.id.room_image).apply { if (!context.isLightTheme) { invertImageColors() } setImageResource(intent.getIntExtra(EXTRA_ROOM_IMAGE_RESOURCE_ID, 0)) } configureToolbar(api, this, findViewById(R.id.toolbar), roomName) } companion object { const val EXTRA_ROOM_NAME = "roomName" const val EXTRA_ROOM_IMAGE_RESOURCE_ID = "imageResId" fun configureToolbar(api: FosdemApi, owner: LifecycleOwner, toolbar: Toolbar, roomName: String) { toolbar.title = roomName if (roomName.isNotEmpty()) { val context = toolbar.context toolbar.inflateMenu(R.menu.room_image_dialog) toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.navigation -> { val localNavigationUrl = FosdemUrls.getLocalNavigationToLocation(roomName.toSlug()) try { CustomTabsIntent.Builder() .configureToolbarColors(context, R.color.light_color_primary) .setShowTitle(true) .build() .launchUrl(context, Uri.parse(localNavigationUrl)) } catch (ignore: ActivityNotFoundException) { } true } else -> false } } owner.launchAndRepeatOnLifecycle { // Display the room status as subtitle api.roomStatuses.collect { statuses -> toolbar.subtitle = statuses[roomName]?.let { roomStatus -> SpannableString(context.getString(roomStatus.nameResId)).apply { this[0, length] = ForegroundColorSpan(ContextCompat.getColor(context, roomStatus.colorResId)) } } } } } } } }
apache-2.0
8e961a327dd69374f6a5e83627c859d6
38.702128
125
0.607076
5.210894
false
false
false
false
raniejade/kspec
kspec-core/src/main/kotlin/io/polymorphicpanda/kspec/tag/Taggable.kt
1
1208
package io.polymorphicpanda.kspec.tag import kotlin.reflect.KClass /** * @author Ranie Jade Ramiso */ abstract class Taggable(tags: Set<Tag<*>>) { abstract val parent: Taggable? val tags: Map<KClass<*>, Tag<*>> = tags.groupBy { it.javaClass.kotlin as KClass<*> }.mapValues { it.value.first() } fun <T: KClass<out Tag<*>>> contains(tags: Collection<T>): Boolean { return this.tags.any { tags.contains(it.key) } || parent?.contains(tags) ?: false } fun <T: KClass<out Tag<*>>> containsAll(tags: Collection<T>): Boolean { var result = false if (this.tags.isNotEmpty()) { result = this.tags.all { tags.contains(it.key) } } if (!result) { result = parent?.containsAll(tags) ?: false } return result } fun <T: KClass<out Tag<*>>> contains(vararg tags: T) = contains(setOf(*tags)) inline fun <reified T: Tag<*>> get(): T? { if (tags.containsKey(T::class)) { return tags[T::class] as T } else if (parent != null && parent!!.tags.containsKey(T::class)) { return parent!!.tags[T::class] as T } return null } }
mit
c626dbc2f62a0180362e919b85847979
26.454545
81
0.562086
3.847134
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/module_tests/RtpReceiverHarness.kt
1
2574
/* * Copyright @ 2018 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.module_tests import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.RtpReceiver import org.jitsi.nlj.resources.logging.StdoutLogger import org.jitsi.nlj.util.safeShutdown import org.jitsi.test_utils.Pcaps import org.jitsi.utils.secs import java.time.Clock import java.util.concurrent.Executors import java.util.logging.Level import kotlin.system.measureTimeMillis /** * Feed media data from a PCAP file through N receivers. This harness * allows: * 1) Changing the PCAP file to feed in different data * 2) Changing the number of RTP Receivers we feed the incoming data to * 3) Changing the number of threads used for all of the receivers * * This can give a sense of how many threads would be necessary to run * N receivers given a certain input bit rate (determined by the PCAP file) */ fun main() { val pcap = Pcaps.Incoming.ONE_PARTICIPANT_RTP_RTCP_SIM_RTX val producer = PcapPacketProducer(pcap.filePath) val backgroundExecutor = Executors.newSingleThreadScheduledExecutor() val executor = Executors.newSingleThreadExecutor() val numReceivers = 1 val receivers = mutableListOf<RtpReceiver>() repeat(numReceivers) { val receiver = ReceiverFactory.createReceiver( executor, backgroundExecutor, pcap.srtpData, pcap.payloadTypes, pcap.headerExtensions, pcap.ssrcAssociations, logger = StdoutLogger("receiver", Level.ALL) ) receivers.add(receiver) } producer.subscribe { pkt -> val packetInfo = PacketInfo(pkt) packetInfo.receivedTime = Clock.systemUTC().instant() receivers.forEach { it.enqueuePacket(packetInfo.clone()) } } val time = measureTimeMillis { producer.run() } println("took $time ms") receivers.forEach(RtpReceiver::stop) executor.safeShutdown(10.secs) backgroundExecutor.safeShutdown(10.secs) receivers.forEach { println(it.getNodeStats().prettyPrint()) } }
apache-2.0
151aedbc4c3bb130fe47efe8d5c11e96
34.260274
76
0.727661
4.111821
false
false
false
false
HughG/partial-order
partial-order-app/src/main/kotlin/org/tameter/kotlin/js/Error.kt
1
801
/* * Copyright (c) 2017 Hugh Greene ([email protected]). */ package org.tameter.kotlin.js import kotlin.js.* var Throwable.stack: String get() { val stack = this.asDynamic().stack return if (stack == undefined) { "(stack is undefined)" } else { stack } } set(value) { this.asDynamic().stack = value } fun logError(err: Throwable) { val errJson = err.unsafeCast<Json>() val errObjectString = err.objectKeys .map { "${it}: ${errJson[it]}" } .joinToString(prefix = "[", separator = ", ", postfix = "]") console.log("Caught $errObjectString") console.log("${err.message}: ${err.stack}") } inline fun doOrLogError(block: () -> Unit) { try { block() } catch (e: Throwable) { logError(e) } }
mit
3bf0a1b1a45158872318bd6cfbda1d90
23.30303
80
0.574282
3.608108
false
false
false
false
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/extras/branches/BranchesFragment.kt
1
4268
package com.fastaccess.ui.modules.repos.extras.branches import android.content.Context import android.os.Bundle import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import android.view.View import butterknife.BindView import com.fastaccess.R import com.fastaccess.data.dao.BranchesModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.provider.rest.loadmore.OnLoadMore import com.fastaccess.ui.adapter.BranchesAdapter import com.fastaccess.ui.base.BaseFragment import com.fastaccess.ui.modules.repos.extras.branches.pager.BranchesPagerListener import com.fastaccess.ui.widgets.StateLayout import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView import com.fastaccess.ui.widgets.recyclerview.scroll.RecyclerViewFastScroller /** * Created by Kosh on 06 Jul 2017, 9:48 PM */ class BranchesFragment : BaseFragment<BranchesMvp.View, BranchesPresenter>(), BranchesMvp.View { @BindView(R.id.recycler) lateinit var recycler: DynamicRecyclerView @BindView(R.id.refresh) lateinit var refresh: SwipeRefreshLayout @BindView(R.id.stateLayout) lateinit var stateLayout: StateLayout @BindView(R.id.fastScroller) lateinit var fastScroller: RecyclerViewFastScroller private var onLoadMore: OnLoadMore<Boolean>? = null private var branchCallback: BranchesPagerListener? = null private val adapter by lazy { BranchesAdapter(presenter.branches, presenter) } override fun onAttach(context: Context) { super.onAttach(context) branchCallback = if (parentFragment is BranchesPagerListener) { parentFragment as BranchesPagerListener } else context as BranchesPagerListener } override fun onDetach() { branchCallback = null super.onDetach() } override fun fragmentLayout(): Int = R.layout.small_grid_refresh_list override fun providePresenter(): BranchesPresenter = BranchesPresenter() override fun onNotifyAdapter(branches: ArrayList<BranchesModel>, page: Int) { hideProgress() if (page == 1) adapter.insertItems(branches) else adapter.addItems(branches) } override fun onBranchSelected(item: BranchesModel?) { branchCallback?.onItemSelect(item!!) } override fun getLoadMore(): OnLoadMore<Boolean> { if (onLoadMore == null) { onLoadMore = OnLoadMore(presenter) } return onLoadMore!! } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { getLoadMore().initialize(presenter.currentPage, presenter.previousTotal) stateLayout.setEmptyText(R.string.no_branches) refresh.setOnRefreshListener { presenter.onCallApi(1, null) } recycler.setEmptyView(stateLayout, refresh) stateLayout.setOnReloadListener { presenter.onCallApi(1, null) } recycler.adapter = adapter recycler.addOnScrollListener(getLoadMore()) recycler.addDivider() if (savedInstanceState == null) { arguments?.let { presenter.onFragmentCreated(it) } } fastScroller.attachRecyclerView(recycler) } override fun showProgress(resId: Int) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() stateLayout.showReload(adapter.itemCount) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showMessage(titleRes: String, msgRes: String) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showErrorMessage(msgRes: String) { hideProgress() super.showErrorMessage(msgRes) } companion object { fun newInstance(login: String, repoId: String, branch: Boolean): BranchesFragment { val fragment = BranchesFragment() fragment.arguments = Bundler.start() .put(BundleConstant.ID, repoId) .put(BundleConstant.EXTRA, login) .put(BundleConstant.EXTRA_TYPE, branch) .end() return fragment } } }
gpl-3.0
eab50aa7856d0f8cf3ca56d5f5077536
34.575
96
0.704545
4.905747
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/squareup/SquareUpAuthInterceptor.kt
1
3311
package com.baulsupp.okurl.services.squareup import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.completion.ApiCompleter import com.baulsupp.okurl.completion.BaseUrlCompleter import com.baulsupp.okurl.completion.CompletionVariableCache import com.baulsupp.okurl.completion.UrlList import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.query import com.baulsupp.okurl.secrets.Secrets import com.baulsupp.okurl.services.squareup.model.LocationList import com.baulsupp.okurl.services.squareup.model.User import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response class SquareUpAuthInterceptor : Oauth2AuthInterceptor() { override val serviceDefinition = Oauth2ServiceDefinition( "connect.squareup.com", "SquareUp API", "squareup", "https://docs.connect.squareup.com/api/connect/v2/", "https://connect.squareup.com/apps" ) override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response { var request = chain.request() val token = credentials.accessToken val reqBuilder = request.newBuilder().addHeader("Authorization", "Bearer $token") if (request.header("Accept") == null) { reqBuilder.addHeader("Accept", "application/json") } request = reqBuilder.build() return chain.proceed(request) } override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials = ValidatedCredentials( client.query<User>( "https://connect.squareup.com/v1/me", TokenValue(credentials) ).name ) override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { val clientId = Secrets.prompt("SquareUp Application Id", "squareup.clientId", "", false) val clientSecret = Secrets.prompt( "SquareUp Application Secret", "squareup.clientSecret", "", true ) val scopes = Secrets.promptArray( "Scopes", "squareup.scopes", listOf( "MERCHANT_PROFILE_READ", "PAYMENTS_READ", "SETTLEMENTS_READ", "BANK_ACCOUNTS_READ" ) ) return SquareUpAuthFlow.login(client, outputHandler, clientId, clientSecret, scopes) } override suspend fun apiCompleter( prefix: String, client: OkHttpClient, credentialsStore: CredentialsStore, completionVariableCache: CompletionVariableCache, tokenSet: Token ): ApiCompleter { val urlList = UrlList.fromResource(name()) val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache) completer.withCachedVariable(name(), "location") { credentialsStore.get(serviceDefinition, tokenSet)?.let { client.query<LocationList>( "https://connect.squareup.com/v2/locations", tokenSet ).locations.map { it.id } } } return completer } }
apache-2.0
2173fe8ae54d8e1122034fa58e5a506b
32.11
97
0.739354
4.468286
false
false
false
false
f-droid/fdroidclient
libs/database/src/main/java/org/fdroid/index/RepoUpdater.kt
1
3281
package org.fdroid.index import mu.KotlinLogging import org.fdroid.CompatibilityChecker import org.fdroid.database.FDroidDatabase import org.fdroid.database.Repository import org.fdroid.download.DownloaderFactory import org.fdroid.index.v1.IndexV1Updater import org.fdroid.index.v2.IndexV2Updater import java.io.File import java.io.FileNotFoundException /** * Updates a [Repository] with a downloaded index, detects changes and chooses the right * [IndexUpdater] automatically. */ public class RepoUpdater( tempDir: File, db: FDroidDatabase, downloaderFactory: DownloaderFactory, repoUriBuilder: RepoUriBuilder = defaultRepoUriBuilder, compatibilityChecker: CompatibilityChecker, listener: IndexUpdateListener, ) { private val log = KotlinLogging.logger {} private val tempFileProvider = TempFileProvider { File.createTempFile("dl-", "", tempDir) } /** * A list of [IndexUpdater]s to try, sorted by newest first. */ private val indexUpdater = listOf( IndexV2Updater( database = db, tempFileProvider = tempFileProvider, downloaderFactory = downloaderFactory, repoUriBuilder = repoUriBuilder, compatibilityChecker = compatibilityChecker, listener = listener, ), IndexV1Updater( database = db, tempFileProvider = tempFileProvider, downloaderFactory = downloaderFactory, repoUriBuilder = repoUriBuilder, compatibilityChecker = compatibilityChecker, listener = listener, ), ) /** * Updates the given [repo]. * If [Repository.certificate] is null, * the repo is considered to be new this being the first update. */ public fun update( repo: Repository, fingerprint: String? = null, ): IndexUpdateResult { return if (repo.certificate == null) { // This is a new repo without a certificate updateNewRepo(repo, fingerprint) } else { update(repo) } } private fun updateNewRepo( repo: Repository, expectedSigningFingerprint: String?, ): IndexUpdateResult = update(repo) { updater -> updater.updateNewRepo(repo, expectedSigningFingerprint) } private fun update(repo: Repository): IndexUpdateResult = update(repo) { updater -> updater.update(repo) } private fun update( repo: Repository, doUpdate: (IndexUpdater) -> IndexUpdateResult, ): IndexUpdateResult { indexUpdater.forEach { updater -> // don't downgrade to older updaters if repo used new format already val repoFormatVersion = repo.formatVersion if (repoFormatVersion != null && repoFormatVersion > updater.formatVersion) { val updaterVersion = updater.formatVersion.name log.warn { "Not using updater $updaterVersion for repo ${repo.address}" } return@forEach } val result = doUpdate(updater) if (result != IndexUpdateResult.NotFound) return result } return IndexUpdateResult.Error(FileNotFoundException("No files found for ${repo.address}")) } }
gpl-3.0
37fe87641929fa8c18070d8ddad5d12b
32.479592
99
0.651021
4.904335
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/tab/model/PdfTab.kt
1
728
package jp.toastkid.yobidashi.tab.model import java.util.UUID /** * PDF tab. * * @author toastkidjp */ class PdfTab: Tab { private val pdfTab: Boolean = true private var titleStr: String = "PDF Viewer" private var path: String = "" private val id: String = UUID.randomUUID().toString() private var position: Int = 0 override fun id(): String = id override fun setScrolled(scrollY: Int) { position = scrollY } override fun getScrolled(): Int = position override fun title(): String = titleStr override fun getUrl(): String = path fun setTitle(title: String) { titleStr = title } fun setPath(path: String) { this.path = path } }
epl-1.0
2a7aaf9a2f324f833f490409b657f121
16.780488
57
0.625
4.089888
false
false
false
false
Forinil/JavaScriptLogger
javascript-logger-servlet/src/main/kotlin/com/github/forinil/javascriptlogger/servlet/LoggerServlet.kt
1
3501
package com.github.forinil.javascriptlogger.servlet import org.slf4j.LoggerFactory import java.io.IOException import javax.servlet.ServletException import javax.servlet.annotation.WebServlet import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import com.fasterxml.jackson.databind.ObjectMapper import com.github.forinil.javascriptlogger.servlet.util.LogData import com.github.forinil.javascriptlogger.servlet.util.ResponseData import com.github.forinil.javascriptlogger.servlet.util.ResponseStatus import org.slf4j.event.Level /** * Created by Konrad Botor on 15.04.2017T15:42 * in package com.github.forinil.javascriptlogger.servlet in project JavaScriptLogger. */ @WebServlet(name = "LoggerServlet", displayName = "LoggerServlet", description = "Logger Servlet", loadOnStartup = 1, urlPatterns = arrayOf("/logger")) open class LoggerServlet: HttpServlet() { private val logger = LoggerFactory.getLogger(LoggerServlet::class.java) private val mapper = ObjectMapper() private val messageTemplate = "{}::{} - {}" private val errorTemplate = messageTemplate + " - {}" @Throws(ServletException::class) override fun init() { logger.trace("init") super.init() } @Throws(ServletException::class, IOException::class) override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { logger.trace("doPost") // Parse request val request = mapper.readValue(req.reader, LogData::class.java) val level: Level try { level = getLevel(request) logger.trace("Data received: {}", request) } catch(e: Exception) { logger.error("Unknown log level", e) sendResponse(resp, ResponseData(ResponseStatus.FAILURE, "Unknown log level")) return } when (level) { Level.INFO -> logger.info(messageTemplate, request.page, request.function, request.message) Level.TRACE -> logger.trace(messageTemplate, request.page, request.function, request.message) Level.DEBUG -> logger.debug(messageTemplate, request.page, request.function, request.message) Level.WARN -> logger.warn(messageTemplate, request.page, request.function, request.message) Level.ERROR -> logger.error(errorTemplate, request.page, request.function, request.message, request.errorCode) else -> { logger.error("Unknown log level in request: {}", request) sendResponse(resp, ResponseData(ResponseStatus.FAILURE, "Unknown log level")) return } } // Send response sendResponse(resp, ResponseData()) } private fun sendResponse(resp: HttpServletResponse, resonseData: ResponseData) { resp.contentType = "application/json" val out = resp.writer out.println(mapper.writeValueAsString(resonseData)) } private fun getLevel(logData: LogData): Level { when (logData.level) { Level.ERROR.toString() -> return Level.ERROR Level.WARN.toString() -> return Level.WARN Level.INFO.toString() -> return Level.INFO Level.DEBUG.toString() -> return Level.DEBUG Level.TRACE.toString() -> return Level.TRACE else -> throw IllegalArgumentException("Unknown log level: %s".format(logData.level)) } } }
agpl-3.0
03d8f63f7c8246ce2bd1a1b0ae803c22
39.252874
122
0.67495
4.606579
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/parser/postproc/parameters.kt
1
3516
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.parser.postproc import compiler.InternalCompilerError import compiler.ast.ParameterList import compiler.ast.VariableDeclaration import compiler.ast.type.TypeModifier import compiler.ast.type.TypeReference import compiler.lexer.* import compiler.parser.rule.Rule import compiler.parser.rule.RuleMatchingResult import compiler.transact.Position import compiler.transact.TransactionalSequence import java.util.* fun ParameterDeclarationPostProcessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<VariableDeclaration> { return rule .flatten() .mapResult(::toAST_ParameterDeclaration) } private fun toAST_ParameterDeclaration(input: TransactionalSequence<Any, Position>): VariableDeclaration { var declarationKeyword: Keyword? = null var typeModifier: TypeModifier? = null var name: IdentifierToken var type: TypeReference? = null var next = input.next()!! if (next is KeywordToken) { declarationKeyword = next.keyword next = input.next()!! } if (next is TypeModifier) { typeModifier = next next = input.next()!! } name = next as IdentifierToken if (input.peek() == OperatorToken(Operator.COLON)) { input.next() type = input.next()!! as TypeReference } return VariableDeclaration( name.sourceLocation, typeModifier, name, type, declarationKeyword == Keyword.VAR, null ) } fun ParameterListPostprocessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<ParameterList> { return rule .flatten() .mapResult(::toAST_ParameterList) } private fun toAST_ParameterList(tokens: TransactionalSequence<Any, Position>): ParameterList { // skip PARANT_OPEN tokens.next()!! val parameters: MutableList<VariableDeclaration> = LinkedList() while (tokens.hasNext()) { var next = tokens.next()!! if (next == OperatorToken(Operator.PARANT_CLOSE)) { return ParameterList(parameters) } parameters.add(next as VariableDeclaration) tokens.mark() next = tokens.next()!! if (next == OperatorToken(Operator.PARANT_CLOSE)) { tokens.commit() return ParameterList(parameters) } if (next == OperatorToken(Operator.COMMA)) { tokens.commit() } else if (next !is VariableDeclaration) { tokens.rollback() next as Token throw InternalCompilerError("Unexpected ${next.toStringWithoutLocation()} in parameter list, expecting OPERATOR PARANT_CLOSE or OPERATOR COMMA") } } throw InternalCompilerError("This line should never have been reached :(") }
lgpl-3.0
01e72b508cfdd8780b1bf500d9d2102d
30.115044
156
0.687998
4.694259
false
false
false
false
sensefly-sa/dynamodb-to-s3
src/main/kotlin/io/sensefly/dynamodbtos3/BackupTable.kt
1
3896
package io.sensefly.dynamodbtos3 import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity import com.amazonaws.services.dynamodbv2.model.ScanRequest import com.codahale.metrics.MetricRegistry import com.fasterxml.jackson.databind.ObjectMapper import com.google.common.base.Stopwatch import io.sensefly.dynamodbtos3.reader.ReadLimit import io.sensefly.dynamodbtos3.reader.ReadLimitFactory import io.sensefly.dynamodbtos3.writer.WriterFactory import org.slf4j.LoggerFactory import org.springframework.boot.actuate.metrics.GaugeService import org.springframework.stereotype.Component import java.text.NumberFormat import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.concurrent.TimeUnit.NANOSECONDS import javax.inject.Inject @Component class BackupTable @Inject constructor( private val readLimitFactory: ReadLimitFactory, private val amazonDynamoDB: AmazonDynamoDB, private val objectMapper: ObjectMapper, private val writerFactory: WriterFactory<*>, private val metricRegistry: MetricRegistry, private val gaugeService: GaugeService) { companion object { const val DEFAULT_PATTERN = "yyyy/MM/dd" private const val LOG_PROGRESS_FREQ = 10_000 } private val log = LoggerFactory.getLogger(javaClass) fun backup(tableName: String, bucket: String, readPercentage: Double, pattern: String = DEFAULT_PATTERN) { backup(tableName, bucket, readLimitFactory.fromPercentage(tableName, readPercentage), pattern) } fun backup(tableName: String, bucket: String, readCapacity: Int, pattern: String = DEFAULT_PATTERN) { backup(tableName, bucket, readLimitFactory.fromCapacity(readCapacity), pattern) } private fun backup(tableName: String, bucket: String, readLimit: ReadLimit, pattern: String) { val stopwatch = Stopwatch.createStarted() val dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern)) val filePath = "$dir/$tableName.json" log.info("Start {} backup with {} limit to {}/{}", tableName, readLimit.limit, bucket, filePath) val scanRequest = ScanRequest() .withTableName(tableName) .withLimit(readLimit.limit) .withConsistentRead(false) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) var count = 0 var lastPrint = LOG_PROGRESS_FREQ writerFactory.get(bucket, filePath).use { writer -> do { val scanResult = amazonDynamoDB.scan(scanRequest) if (scanResult.items.isNotEmpty()) { val lines = scanResult.items.joinToString(System.lineSeparator(), postfix = System.lineSeparator()) { item -> objectMapper.writeValueAsString(item) } writer.write(lines) } count += scanResult.items.size if (count > lastPrint) { log.info("[{}] {} items sent ({})", tableName, NumberFormat.getInstance().format(lastPrint), stopwatch) lastPrint += LOG_PROGRESS_FREQ } scanRequest.exclusiveStartKey = scanResult.lastEvaluatedKey // scanResult.consumedCapacity is null with LocalDynamoDB val consumedCapacity = if (scanResult.consumedCapacity == null) 100.0 else scanResult.consumedCapacity.capacityUnits val consumed = Math.round(consumedCapacity * 10).toInt() val wait = readLimit.rateLimiter.acquire(consumed) gaugeService.submit("$tableName-backup-items", count.toDouble()) metricRegistry.timer("$tableName-backup-duration") .update(stopwatch.elapsed(NANOSECONDS), NANOSECONDS) log.debug("consumed: {}, wait: {}, capacity: {}, count: {}", consumed, wait, consumedCapacity, count) } while (scanResult.lastEvaluatedKey != null) } log.info("Backup {} table ({} items) completed in {}", tableName, NumberFormat.getInstance().format(count), stopwatch) } }
bsd-3-clause
0fc2fc16b63f2f4e17bc761384aa2346
40.010526
124
0.734856
4.382452
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/model/Documentable.kt
1
20656
package org.jetbrains.dokka.model import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.doc.DocumentationNode import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.model.properties.WithExtraProperties interface AnnotationTarget abstract class Documentable : WithChildren<Documentable>, AnnotationTarget { abstract val name: String? abstract val dri: DRI abstract val documentation: SourceSetDependent<DocumentationNode> abstract val sourceSets: Set<DokkaSourceSet> abstract val expectPresentInSet: DokkaSourceSet? abstract override val children: List<Documentable> override fun toString(): String = "${javaClass.simpleName}($dri)" override fun equals(other: Any?) = other is Documentable && this.dri == other.dri // TODO: https://github.com/Kotlin/dokka/pull/667#discussion_r382555806 override fun hashCode() = dri.hashCode() } typealias SourceSetDependent<T> = Map<DokkaSourceSet, T> interface WithSources { val sources: SourceSetDependent<DocumentableSource> } interface WithScope { val functions: List<DFunction> val properties: List<DProperty> val classlikes: List<DClasslike> } interface WithVisibility { val visibility: SourceSetDependent<Visibility> } interface WithType { val type: Bound } interface WithAbstraction { val modifier: SourceSetDependent<Modifier> } sealed class Modifier(val name: String) sealed class KotlinModifier(name: String) : Modifier(name) { object Abstract : KotlinModifier("abstract") object Open : KotlinModifier("open") object Final : KotlinModifier("final") object Sealed : KotlinModifier("sealed") object Empty : KotlinModifier("") } sealed class JavaModifier(name: String) : Modifier(name) { object Abstract : JavaModifier("abstract") object Final : JavaModifier("final") object Empty : JavaModifier("") } interface WithCompanion { val companion: DObject? } interface WithConstructors { val constructors: List<DFunction> } interface WithGenerics { val generics: List<DTypeParameter> } interface WithSupertypes { val supertypes: SourceSetDependent<List<TypeConstructorWithKind>> } interface WithIsExpectActual { val isExpectActual: Boolean } interface Callable : WithVisibility, WithType, WithAbstraction, WithSources, WithIsExpectActual { val receiver: DParameter? } sealed class DClasslike : Documentable(), WithScope, WithVisibility, WithSources, WithIsExpectActual data class DModule( override val name: String, val packages: List<DPackage>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet? = null, override val sourceSets: Set<DokkaSourceSet>, override val extra: PropertyContainer<DModule> = PropertyContainer.empty() ) : Documentable(), WithExtraProperties<DModule> { override val dri: DRI = DRI.topLevel override val children: List<Documentable> get() = packages override fun withNewExtras(newExtras: PropertyContainer<DModule>) = copy(extra = newExtras) } data class DPackage( override val dri: DRI, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, val typealiases: List<DTypeAlias>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet? = null, override val sourceSets: Set<DokkaSourceSet>, override val extra: PropertyContainer<DPackage> = PropertyContainer.empty() ) : Documentable(), WithScope, WithExtraProperties<DPackage> { val packageName: String = dri.packageName.orEmpty() /** * !!! WARNING !!! * This name is not guaranteed to be a be a canonical/real package name. * e.g. this will return a human readable version for root packages. * Use [packageName] or `dri.packageName` instead to obtain the real packageName */ override val name: String = packageName.ifBlank { "[root]" } override val children: List<Documentable> = properties + functions + classlikes + typealiases override fun withNewExtras(newExtras: PropertyContainer<DPackage>) = copy(extra = newExtras) } data class DClass( override val dri: DRI, override val name: String, override val constructors: List<DFunction>, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val sources: SourceSetDependent<DocumentableSource>, override val visibility: SourceSetDependent<Visibility>, override val companion: DObject?, override val generics: List<DTypeParameter>, override val supertypes: SourceSetDependent<List<TypeConstructorWithKind>>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val modifier: SourceSetDependent<Modifier>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DClass> = PropertyContainer.empty() ) : DClasslike(), WithAbstraction, WithCompanion, WithConstructors, WithGenerics, WithSupertypes, WithExtraProperties<DClass> { override val children: List<Documentable> get() = (functions + properties + classlikes + constructors) override fun withNewExtras(newExtras: PropertyContainer<DClass>) = copy(extra = newExtras) } data class DEnum( override val dri: DRI, override val name: String, val entries: List<DEnumEntry>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val visibility: SourceSetDependent<Visibility>, override val companion: DObject?, override val constructors: List<DFunction>, override val supertypes: SourceSetDependent<List<TypeConstructorWithKind>>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DEnum> = PropertyContainer.empty() ) : DClasslike(), WithCompanion, WithConstructors, WithSupertypes, WithExtraProperties<DEnum> { override val children: List<Documentable> get() = (entries + functions + properties + classlikes + constructors) override fun withNewExtras(newExtras: PropertyContainer<DEnum>) = copy(extra = newExtras) } data class DEnumEntry( override val dri: DRI, override val name: String, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val sourceSets: Set<DokkaSourceSet>, override val extra: PropertyContainer<DEnumEntry> = PropertyContainer.empty() ) : Documentable(), WithScope, WithExtraProperties<DEnumEntry> { override val children: List<Documentable> get() = (functions + properties + classlikes) override fun withNewExtras(newExtras: PropertyContainer<DEnumEntry>) = copy(extra = newExtras) } data class DFunction( override val dri: DRI, override val name: String, val isConstructor: Boolean, val parameters: List<DParameter>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val visibility: SourceSetDependent<Visibility>, override val type: Bound, override val generics: List<DTypeParameter>, override val receiver: DParameter?, override val modifier: SourceSetDependent<Modifier>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DFunction> = PropertyContainer.empty() ) : Documentable(), Callable, WithGenerics, WithExtraProperties<DFunction> { override val children: List<Documentable> get() = parameters override fun withNewExtras(newExtras: PropertyContainer<DFunction>) = copy(extra = newExtras) } data class DInterface( override val dri: DRI, override val name: String, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val visibility: SourceSetDependent<Visibility>, override val companion: DObject?, override val generics: List<DTypeParameter>, override val supertypes: SourceSetDependent<List<TypeConstructorWithKind>>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DInterface> = PropertyContainer.empty() ) : DClasslike(), WithCompanion, WithGenerics, WithSupertypes, WithExtraProperties<DInterface> { override val children: List<Documentable> get() = (functions + properties + classlikes) override fun withNewExtras(newExtras: PropertyContainer<DInterface>) = copy(extra = newExtras) } data class DObject( override val name: String?, override val dri: DRI, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val visibility: SourceSetDependent<Visibility>, override val supertypes: SourceSetDependent<List<TypeConstructorWithKind>>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DObject> = PropertyContainer.empty() ) : DClasslike(), WithSupertypes, WithExtraProperties<DObject> { override val children: List<Documentable> get() = (functions + properties + classlikes) override fun withNewExtras(newExtras: PropertyContainer<DObject>) = copy(extra = newExtras) } data class DAnnotation( override val name: String, override val dri: DRI, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val functions: List<DFunction>, override val properties: List<DProperty>, override val classlikes: List<DClasslike>, override val visibility: SourceSetDependent<Visibility>, override val companion: DObject?, override val constructors: List<DFunction>, override val generics: List<DTypeParameter>, override val sourceSets: Set<DokkaSourceSet>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DAnnotation> = PropertyContainer.empty() ) : DClasslike(), WithCompanion, WithConstructors, WithExtraProperties<DAnnotation>, WithGenerics { override val children: List<Documentable> get() = (functions + properties + classlikes + constructors) override fun withNewExtras(newExtras: PropertyContainer<DAnnotation>) = copy(extra = newExtras) } data class DProperty( override val dri: DRI, override val name: String, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sources: SourceSetDependent<DocumentableSource>, override val visibility: SourceSetDependent<Visibility>, override val type: Bound, override val receiver: DParameter?, val setter: DFunction?, val getter: DFunction?, override val modifier: SourceSetDependent<Modifier>, override val sourceSets: Set<DokkaSourceSet>, override val generics: List<DTypeParameter>, override val isExpectActual: Boolean, override val extra: PropertyContainer<DProperty> = PropertyContainer.empty() ) : Documentable(), Callable, WithExtraProperties<DProperty>, WithGenerics { override val children: List<Nothing> get() = emptyList() override fun withNewExtras(newExtras: PropertyContainer<DProperty>) = copy(extra = newExtras) } // TODO: treat named Parameters and receivers differently data class DParameter( override val dri: DRI, override val name: String?, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val type: Bound, override val sourceSets: Set<DokkaSourceSet>, override val extra: PropertyContainer<DParameter> = PropertyContainer.empty() ) : Documentable(), WithExtraProperties<DParameter>, WithType { override val children: List<Nothing> get() = emptyList() override fun withNewExtras(newExtras: PropertyContainer<DParameter>) = copy(extra = newExtras) } data class DTypeParameter( val variantTypeParameter: Variance<TypeParameter>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, val bounds: List<Bound>, override val sourceSets: Set<DokkaSourceSet>, override val extra: PropertyContainer<DTypeParameter> = PropertyContainer.empty() ) : Documentable(), WithExtraProperties<DTypeParameter> { constructor( dri: DRI, name: String, presentableName: String?, documentation: SourceSetDependent<DocumentationNode>, expectPresentInSet: DokkaSourceSet?, bounds: List<Bound>, sourceSets: Set<DokkaSourceSet>, extra: PropertyContainer<DTypeParameter> = PropertyContainer.empty() ) : this( Invariance(TypeParameter(dri, name, presentableName)), documentation, expectPresentInSet, bounds, sourceSets, extra ) override val dri: DRI by variantTypeParameter.inner::dri override val name: String by variantTypeParameter.inner::name override val children: List<Nothing> get() = emptyList() override fun withNewExtras(newExtras: PropertyContainer<DTypeParameter>) = copy(extra = newExtras) } data class DTypeAlias( override val dri: DRI, override val name: String, override val type: Bound, val underlyingType: SourceSetDependent<Bound>, override val visibility: SourceSetDependent<Visibility>, override val documentation: SourceSetDependent<DocumentationNode>, override val expectPresentInSet: DokkaSourceSet?, override val sourceSets: Set<DokkaSourceSet>, override val generics: List<DTypeParameter>, override val extra: PropertyContainer<DTypeAlias> = PropertyContainer.empty() ) : Documentable(), WithType, WithVisibility, WithExtraProperties<DTypeAlias>, WithGenerics { override val children: List<Nothing> get() = emptyList() override fun withNewExtras(newExtras: PropertyContainer<DTypeAlias>) = copy(extra = newExtras) } sealed class Projection sealed class Bound : Projection() data class TypeParameter( val dri: DRI, val name: String, val presentableName: String? = null, override val extra: PropertyContainer<TypeParameter> = PropertyContainer.empty() ) : Bound(), AnnotationTarget, WithExtraProperties<TypeParameter> { override fun withNewExtras(newExtras: PropertyContainer<TypeParameter>): TypeParameter = copy(extra = extra) } sealed class TypeConstructor : Bound(), AnnotationTarget { abstract val dri: DRI abstract val projections: List<Projection> abstract val presentableName: String? } data class GenericTypeConstructor( override val dri: DRI, override val projections: List<Projection>, override val presentableName: String? = null, override val extra: PropertyContainer<GenericTypeConstructor> = PropertyContainer.empty() ) : TypeConstructor(), WithExtraProperties<GenericTypeConstructor> { override fun withNewExtras(newExtras: PropertyContainer<GenericTypeConstructor>): GenericTypeConstructor = copy(extra = newExtras) } data class FunctionalTypeConstructor( override val dri: DRI, override val projections: List<Projection>, val isExtensionFunction: Boolean = false, val isSuspendable: Boolean = false, override val presentableName: String? = null, override val extra: PropertyContainer<FunctionalTypeConstructor> = PropertyContainer.empty(), ) : TypeConstructor(), WithExtraProperties<FunctionalTypeConstructor> { override fun withNewExtras(newExtras: PropertyContainer<FunctionalTypeConstructor>): FunctionalTypeConstructor = copy(extra = newExtras) } // kotlin.annotation.AnnotationTarget.TYPEALIAS data class TypeAliased( val typeAlias: Bound, val inner: Bound, override val extra: PropertyContainer<TypeAliased> = PropertyContainer.empty() ) : Bound(), AnnotationTarget, WithExtraProperties<TypeAliased> { override fun withNewExtras(newExtras: PropertyContainer<TypeAliased>): TypeAliased = copy(extra = newExtras) } data class PrimitiveJavaType( val name: String, override val extra: PropertyContainer<PrimitiveJavaType> = PropertyContainer.empty() ) : Bound(), AnnotationTarget, WithExtraProperties<PrimitiveJavaType> { override fun withNewExtras(newExtras: PropertyContainer<PrimitiveJavaType>): PrimitiveJavaType = copy(extra = newExtras) } data class JavaObject(override val extra: PropertyContainer<JavaObject> = PropertyContainer.empty()) : Bound(), AnnotationTarget, WithExtraProperties<JavaObject> { override fun withNewExtras(newExtras: PropertyContainer<JavaObject>): JavaObject = copy(extra = newExtras) } data class UnresolvedBound( val name: String, override val extra: PropertyContainer<UnresolvedBound> = PropertyContainer.empty() ) : Bound(), AnnotationTarget, WithExtraProperties<UnresolvedBound> { override fun withNewExtras(newExtras: PropertyContainer<UnresolvedBound>): UnresolvedBound = copy(extra = newExtras) } // The following Projections are not AnnotationTargets; they cannot be annotated. data class Nullable(val inner: Bound) : Bound() /** * It introduces [definitely non-nullable types](https://github.com/Kotlin/KEEP/blob/c72601cf35c1e95a541bb4b230edb474a6d1d1a8/proposals/definitely-non-nullable-types.md) */ data class DefinitelyNonNullable(val inner: Bound) : Bound() sealed class Variance<out T : Bound> : Projection() { abstract val inner: T } data class Covariance<out T : Bound>(override val inner: T) : Variance<T>() { override fun toString() = "out" } data class Contravariance<out T : Bound>(override val inner: T) : Variance<T>() { override fun toString() = "in" } data class Invariance<out T : Bound>(override val inner: T) : Variance<T>() { override fun toString() = "" } object Star : Projection() object Void : Bound() object Dynamic : Bound() fun Variance<TypeParameter>.withDri(dri: DRI) = when (this) { is Contravariance -> Contravariance(TypeParameter(dri, inner.name, inner.presentableName)) is Covariance -> Covariance(TypeParameter(dri, inner.name, inner.presentableName)) is Invariance -> Invariance(TypeParameter(dri, inner.name, inner.presentableName)) } fun Documentable.dfs(predicate: (Documentable) -> Boolean): Documentable? = if (predicate(this)) { this } else { this.children.asSequence().mapNotNull { it.dfs(predicate) }.firstOrNull() } sealed class Visibility(val name: String) sealed class KotlinVisibility(name: String) : Visibility(name) { object Public : KotlinVisibility("public") object Private : KotlinVisibility("private") object Protected : KotlinVisibility("protected") object Internal : KotlinVisibility("internal") } sealed class JavaVisibility(name: String) : Visibility(name) { object Public : JavaVisibility("public") object Private : JavaVisibility("private") object Protected : JavaVisibility("protected") object Default : JavaVisibility("") } fun <T> SourceSetDependent<T>?.orEmpty(): SourceSetDependent<T> = this ?: emptyMap() interface DocumentableSource { val path: String } data class TypeConstructorWithKind(val typeConstructor: TypeConstructor, val kind: ClassKind)
apache-2.0
5ce1d2c4fddc7a8fe3bea51d00929151
38.570881
169
0.751259
4.837471
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/preferences/persistent/PersistentUriPreference.kt
1
967
package com.garpr.android.preferences.persistent import com.garpr.android.extensions.toJavaUri import com.garpr.android.preferences.KeyValueStore import java.net.URI as JavaUri class PersistentUriPreference( key: String, defaultValue: JavaUri?, keyValueStore: KeyValueStore ) : BasePersistentPreference<JavaUri>( key, defaultValue, keyValueStore ) { private val backingPreference = PersistentStringPreference( key = key, defaultValue = null, keyValueStore = keyValueStore ) override val exists: Boolean get() = backingPreference.exists || defaultValue != null override fun get(): JavaUri? { return if (backingPreference.exists) { backingPreference.get().toJavaUri() } else { defaultValue } } override fun performSet(newValue: JavaUri) { backingPreference.set(newValue.toString()) } }
unlicense
685e160a9f7ba0b48222e6699241e63f
24.447368
64
0.651499
4.908629
false
false
false
false
bric3/mockito
subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt
6
4868
/** * Copyright (c) 2017 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.kotlin import kotlinx.coroutines.runBlocking import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.IsEqual import org.junit.Test import org.mockito.Mockito.* /** * Test for mocking and verifying Kotlin suspending functions. */ class SuspendTest { interface SuspendableInterface { suspend fun suspendFunction(x: Int): Int suspend fun suspendFunctionWithDefault(x: Int = 1): Int } open class SuspendableClass : SuspendableInterface { suspend override fun suspendFunction(x: Int): Int = error("not implemented") suspend override fun suspendFunctionWithDefault(x: Int): Int = error("not implemented") suspend open fun suspendClassFunctionWithDefault(x: Int = 1): Int = error("not implemented") } class FinalSuspendableClass { suspend fun fetch(): Int { fetchConcrete() return 2 } suspend fun fetchConcrete() = 1 } open class CallsSuspendable(private val suspendable: SuspendableInterface) { fun callSuspendable(x: Int) = runBlocking { suspendable.suspendFunction(x) } fun suspendFunctionWithDefault() = runBlocking { suspendable.suspendFunctionWithDefault() } fun suspendFunctionWithDefault(x: Int) = runBlocking { suspendable.suspendFunctionWithDefault(x) } } class CallsSuspendableClass(private val suspendable: SuspendableClass) : CallsSuspendable(suspendable) { fun suspendClassFunctionWithDefault() = runBlocking { suspendable.suspendClassFunctionWithDefault() } fun suspendClassFunctionWithDefault(x: Int) = runBlocking { suspendable.suspendClassFunctionWithDefault(x) } } @Test fun shouldMockSuspendInterfaceFunction() = runBlocking<Unit> { val mockSuspendable: SuspendableInterface = mock(SuspendableInterface::class.java) val callsSuspendable = CallsSuspendable(mockSuspendable) `when`(mockSuspendable.suspendFunction(1)).thenReturn(2) `when`(mockSuspendable.suspendFunction(intThat { it >= 2 })).thenReturn(4) assertThat(callsSuspendable.callSuspendable(1), IsEqual(2)) assertThat(callsSuspendable.callSuspendable(2), IsEqual(4)) verify(mockSuspendable).suspendFunction(1) verify(mockSuspendable).suspendFunction(2) } @Test fun shouldMockSuspendInterfaceFunctionWithDefault() = runBlocking<Unit> { val mockSuspendable: SuspendableInterface = mock(SuspendableInterface::class.java) val callsSuspendable = CallsSuspendable(mockSuspendable) `when`(mockSuspendable.suspendFunctionWithDefault()).thenReturn(2) `when`(mockSuspendable.suspendFunctionWithDefault(intThat { it >= 2 })).thenReturn(4) assertThat(callsSuspendable.suspendFunctionWithDefault(), IsEqual(2)) assertThat(callsSuspendable.suspendFunctionWithDefault(2), IsEqual(4)) verify(mockSuspendable).suspendFunctionWithDefault() verify(mockSuspendable).suspendFunctionWithDefault(2) } @Test fun shouldMockSuspendClassFunction() = runBlocking<Unit> { val mockSuspendable: SuspendableClass = mock(SuspendableClass::class.java) val callsSuspendable = CallsSuspendable(mockSuspendable) `when`(mockSuspendable.suspendFunction(1)).thenReturn(2) `when`(mockSuspendable.suspendFunction(intThat { it >= 2 })).thenReturn(4) assertThat(callsSuspendable.callSuspendable(1), IsEqual(2)) assertThat(callsSuspendable.callSuspendable(2), IsEqual(4)) verify(mockSuspendable).suspendFunction(1) verify(mockSuspendable).suspendFunction(2) } @Test fun shouldMockSuspendClassFunctionWithDefault() = runBlocking<Unit> { val mockSuspendable: SuspendableClass = mock(SuspendableClass::class.java) val callsSuspendable = CallsSuspendableClass(mockSuspendable) `when`(mockSuspendable.suspendClassFunctionWithDefault()).thenReturn(2) `when`(mockSuspendable.suspendClassFunctionWithDefault(intThat { it >= 2 })).thenReturn(4) assertThat(callsSuspendable.suspendClassFunctionWithDefault(), IsEqual(2)) assertThat(callsSuspendable.suspendClassFunctionWithDefault(2), IsEqual(4)) verify(mockSuspendable).suspendClassFunctionWithDefault() verify(mockSuspendable).suspendClassFunctionWithDefault(2) } @Test fun shouldMockFinalSuspendableClass() = runBlocking<Unit> { val mockClass = mock(FinalSuspendableClass::class.java) `when`(mockClass.fetch()).thenReturn(10) assertThat(mockClass.fetch(), IsEqual(10)) verify(mockClass).fetch() } }
mit
002322df68ceea2f2bee5d6dcd98dd14
37.03125
108
0.711175
4.815035
false
true
false
false