content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.swmansion.gesturehandler
import android.graphics.Matrix
import android.graphics.PointF
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import java.util.*
class GestureHandlerOrchestrator(
private val wrapperView: ViewGroup,
private val handlerRegistry: GestureHandlerRegistry,
private val viewConfigHelper: ViewConfigurationHelper,
) {
/**
* Minimum alpha (value from 0 to 1) that should be set to a view so that it can be treated as a
* gesture target. E.g. if set to 0.1 then views that less than 10% opaque will be ignored when
* traversing view hierarchy and looking for gesture handlers.
*/
var minimumAlphaForTraversal = DEFAULT_MIN_ALPHA_FOR_TRAVERSAL
private val gestureHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val awaitingHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val preparedHandlers = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private val handlersToCancel = arrayOfNulls<GestureHandler<*>?>(SIMULTANEOUS_GESTURE_HANDLER_LIMIT)
private var gestureHandlersCount = 0
private var awaitingHandlersCount = 0
private var isHandlingTouch = false
private var handlingChangeSemaphore = 0
private var finishedHandlersCleanupScheduled = false
private var activationIndex = 0
/**
* Should be called from the view wrapper
*/
fun onTouchEvent(event: MotionEvent): Boolean {
isHandlingTouch = true
val action = event.actionMasked
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
extractGestureHandlers(event)
} else if (action == MotionEvent.ACTION_CANCEL) {
cancelAll()
}
deliverEventToGestureHandlers(event)
isHandlingTouch = false
if (finishedHandlersCleanupScheduled && handlingChangeSemaphore == 0) {
cleanupFinishedHandlers()
}
return true
}
private fun scheduleFinishedHandlersCleanup() {
if (isHandlingTouch || handlingChangeSemaphore != 0) {
finishedHandlersCleanupScheduled = true
} else {
cleanupFinishedHandlers()
}
}
private inline fun compactHandlersIf(handlers: Array<GestureHandler<*>?>, count: Int, predicate: (handler: GestureHandler<*>?) -> Boolean): Int {
var out = 0
for (i in 0 until count) {
if (predicate(handlers[i])) {
handlers[out++] = handlers[i]
}
}
return out
}
private fun cleanupFinishedHandlers() {
var shouldCleanEmptyCells = false
for (i in gestureHandlersCount - 1 downTo 0) {
val handler = gestureHandlers[i]!!
if (isFinished(handler.state) && !handler.isAwaiting) {
gestureHandlers[i] = null
shouldCleanEmptyCells = true
handler.reset()
handler.apply {
isActive = false
isAwaiting = false
activationIndex = Int.MAX_VALUE
}
}
}
if (shouldCleanEmptyCells) {
gestureHandlersCount = compactHandlersIf(gestureHandlers, gestureHandlersCount) { handler ->
handler != null
}
}
finishedHandlersCleanupScheduled = false
}
private fun hasOtherHandlerToWaitFor(handler: GestureHandler<*>): Boolean {
for (i in 0 until gestureHandlersCount) {
val otherHandler = gestureHandlers[i]!!
if (!isFinished(otherHandler.state) && shouldHandlerWaitForOther(handler, otherHandler)) {
return true
}
}
return false
}
private fun tryActivate(handler: GestureHandler<*>) {
// see if there is anyone else who we need to wait for
if (hasOtherHandlerToWaitFor(handler)) {
addAwaitingHandler(handler)
} else {
// we can activate handler right away
makeActive(handler)
handler.isAwaiting = false
}
}
private fun cleanupAwaitingHandlers() {
awaitingHandlersCount = compactHandlersIf(awaitingHandlers, awaitingHandlersCount) { handler ->
handler!!.isAwaiting
}
}
/*package*/
fun onHandlerStateChange(handler: GestureHandler<*>, newState: Int, prevState: Int) {
handlingChangeSemaphore += 1
if (isFinished(newState)) {
// if there were handlers awaiting completion of this handler, we can trigger active state
for (i in 0 until awaitingHandlersCount) {
val otherHandler = awaitingHandlers[i]
if (shouldHandlerWaitForOther(otherHandler!!, handler)) {
if (newState == GestureHandler.STATE_END) {
// gesture has ended, we need to kill the awaiting handler
otherHandler.cancel()
otherHandler.isAwaiting = false
} else {
// gesture has failed recognition, we may try activating
tryActivate(otherHandler)
}
}
}
cleanupAwaitingHandlers()
}
if (newState == GestureHandler.STATE_ACTIVE) {
tryActivate(handler)
} else if (prevState == GestureHandler.STATE_ACTIVE || prevState == GestureHandler.STATE_END) {
if (handler.isActive) {
handler.dispatchStateChange(newState, prevState)
}
} else {
handler.dispatchStateChange(newState, prevState)
}
handlingChangeSemaphore -= 1
scheduleFinishedHandlersCleanup()
}
private fun makeActive(handler: GestureHandler<*>) {
val currentState = handler.state
with(handler) {
isAwaiting = false
isActive = true
activationIndex = [email protected]++
}
var toCancelCount = 0
// Cancel all handlers that are required to be cancel upon current handler's activation
for (i in 0 until gestureHandlersCount) {
val otherHandler = gestureHandlers[i]!!
if (shouldHandlerBeCancelledBy(otherHandler, handler)) {
handlersToCancel[toCancelCount++] = otherHandler
}
}
for (i in toCancelCount - 1 downTo 0) {
handlersToCancel[i]!!.cancel()
}
// Clear all awaiting handlers waiting for the current handler to fail
for (i in awaitingHandlersCount - 1 downTo 0) {
val otherHandler = awaitingHandlers[i]!!
if (shouldHandlerBeCancelledBy(otherHandler, handler)) {
otherHandler.cancel()
otherHandler.isAwaiting = false
}
}
cleanupAwaitingHandlers()
// Dispatch state change event if handler is no longer in the active state we should also
// trigger END state change and UNDETERMINED state change if necessary
handler.dispatchStateChange(GestureHandler.STATE_ACTIVE, GestureHandler.STATE_BEGAN)
if (currentState != GestureHandler.STATE_ACTIVE) {
handler.dispatchStateChange(GestureHandler.STATE_END, GestureHandler.STATE_ACTIVE)
if (currentState != GestureHandler.STATE_END) {
handler.dispatchStateChange(GestureHandler.STATE_UNDETERMINED, GestureHandler.STATE_END)
}
}
}
private fun deliverEventToGestureHandlers(event: MotionEvent) {
// Copy handlers to "prepared handlers" array, because the list of active handlers can change
// as a result of state updates
val handlersCount = gestureHandlersCount
gestureHandlers.copyInto(preparedHandlers, 0, 0, handlersCount)
// We want to deliver events to active handlers first in order of their activation (handlers
// that activated first will first get event delivered). Otherwise we deliver events in the
// order in which handlers has been added ("most direct" children goes first). Therefore we rely
// on Arrays.sort providing a stable sort (as children are registered in order in which they
// should be tested)
preparedHandlers.sortWith(handlersComparator, 0, handlersCount)
for (i in 0 until handlersCount) {
deliverEventToGestureHandler(preparedHandlers[i]!!, event)
}
}
private fun cancelAll() {
for (i in awaitingHandlersCount - 1 downTo 0) {
awaitingHandlers[i]!!.cancel()
}
// Copy handlers to "prepared handlers" array, because the list of active handlers can change
// as a result of state updates
val handlersCount = gestureHandlersCount
for (i in 0 until handlersCount) {
preparedHandlers[i] = gestureHandlers[i]
}
for (i in handlersCount - 1 downTo 0) {
preparedHandlers[i]!!.cancel()
}
}
private fun deliverEventToGestureHandler(handler: GestureHandler<*>, event: MotionEvent) {
if (!isViewAttachedUnderWrapper(handler.view)) {
handler.cancel()
return
}
if (!handler.wantEvents()) {
return
}
val action = event.actionMasked
val coords = tempCoords
extractCoordsForView(handler.view, event, coords)
val oldX = event.x
val oldY = event.y
// TODO: we may consider scaling events if necessary using MotionEvent.transform
// for now the events are only offset to the top left corner of the view but if
// view or any ot the parents is scaled the other pointers position will not reflect
// their actual place in the view. On the other hand not scaling seems like a better
// approach when we want to use pointer coordinates to calculate velocity or distance
// for pinch so I don't know yet if we should transform or not...
event.setLocation(coords[0], coords[1])
if (handler.needsPointerData) {
handler.updatePointerData(event)
}
if (!handler.isAwaiting || action != MotionEvent.ACTION_MOVE) {
handler.handle(event)
if (handler.isActive) {
handler.dispatchHandlerUpdate(event)
}
// if event was of type UP or POINTER_UP we request handler to stop tracking now that
// the event has been dispatched
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
val pointerId = event.getPointerId(event.actionIndex)
handler.stopTrackingPointer(pointerId)
}
}
event.setLocation(oldX, oldY)
}
/**
* isViewAttachedUnderWrapper checks whether all of parents for view related to handler
* view are attached. Since there might be an issue rarely observed when view
* has been detached and handler's state hasn't been change to canceled, failed or
* ended yet. Probably it's a result of some race condition and stopping delivering
* for this handler and changing its state to failed of end appear to be good enough solution.
*/
private fun isViewAttachedUnderWrapper(view: View?): Boolean {
if (view == null) {
return false
}
if (view === wrapperView) {
return true
}
var parent = view.parent
while (parent != null && parent !== wrapperView) {
parent = parent.parent
}
return parent === wrapperView
}
private fun extractCoordsForView(view: View?, event: MotionEvent, outputCoords: FloatArray) {
if (view === wrapperView) {
outputCoords[0] = event.x
outputCoords[1] = event.y
return
}
require(!(view == null || view.parent !is ViewGroup)) { "Parent is null? View is no longer in the tree" }
val parent = view.parent as ViewGroup
extractCoordsForView(parent, event, outputCoords)
val childPoint = tempPoint
transformTouchPointToViewCoords(outputCoords[0], outputCoords[1], parent, view, childPoint)
outputCoords[0] = childPoint.x
outputCoords[1] = childPoint.y
}
private fun addAwaitingHandler(handler: GestureHandler<*>) {
for (i in 0 until awaitingHandlersCount) {
if (awaitingHandlers[i] === handler) {
return
}
}
check(awaitingHandlersCount < awaitingHandlers.size) { "Too many recognizers" }
awaitingHandlers[awaitingHandlersCount++] = handler
with(handler) {
isAwaiting = true
activationIndex = [email protected]++
}
}
private fun recordHandlerIfNotPresent(handler: GestureHandler<*>, view: View) {
for (i in 0 until gestureHandlersCount) {
if (gestureHandlers[i] === handler) {
return
}
}
check(gestureHandlersCount < gestureHandlers.size) { "Too many recognizers" }
gestureHandlers[gestureHandlersCount++] = handler
handler.isActive = false
handler.isAwaiting = false
handler.activationIndex = Int.MAX_VALUE
handler.prepare(view, this)
}
private fun isViewOverflowingParent(view: View): Boolean {
val parent = view.parent as? ViewGroup ?: return false
val matrix = view.matrix
val localXY = matrixTransformCoords
localXY[0] = 0f
localXY[1] = 0f
matrix.mapPoints(localXY)
val left = localXY[0] + view.left
val top = localXY[1] + view.top
return left < 0f || left + view.width > parent.width || top < 0f || top + view.height > parent.height
}
private fun extractAncestorHandlers(view: View, coords: FloatArray, pointerId: Int): Boolean {
var found = false
var parent = view.parent
while (parent != null) {
if (parent is ViewGroup) {
val parentViewGroup: ViewGroup = parent
handlerRegistry.getHandlersForView(parent)?.let {
for (handler in it) {
if (handler.isEnabled && handler.isWithinBounds(view, coords[0], coords[1])) {
found = true
recordHandlerIfNotPresent(handler, parentViewGroup)
handler.startTrackingPointer(pointerId)
}
}
}
}
parent = parent.parent
}
return found
}
private fun recordViewHandlersForPointer(view: View, coords: FloatArray, pointerId: Int): Boolean {
var found = false
handlerRegistry.getHandlersForView(view)?.let {
val size = it.size
for (i in 0 until size) {
val handler = it[i]
if (handler.isEnabled && handler.isWithinBounds(view, coords[0], coords[1])) {
recordHandlerIfNotPresent(handler, view)
handler.startTrackingPointer(pointerId)
found = true
}
}
}
// if the pointer is inside the view but it overflows its parent, handlers attached to the parent
// might not have been extracted (pointer might be in a child, but may be outside parent)
if (coords[0] in 0f..view.width.toFloat() && coords[1] in 0f..view.height.toFloat()
&& isViewOverflowingParent(view) && extractAncestorHandlers(view, coords, pointerId)) {
found = true
}
return found
}
private fun extractGestureHandlers(event: MotionEvent) {
val actionIndex = event.actionIndex
val pointerId = event.getPointerId(actionIndex)
tempCoords[0] = event.getX(actionIndex)
tempCoords[1] = event.getY(actionIndex)
traverseWithPointerEvents(wrapperView, tempCoords, pointerId)
extractGestureHandlers(wrapperView, tempCoords, pointerId)
}
private fun extractGestureHandlers(viewGroup: ViewGroup, coords: FloatArray, pointerId: Int): Boolean {
val childrenCount = viewGroup.childCount
for (i in childrenCount - 1 downTo 0) {
val child = viewConfigHelper.getChildInDrawingOrderAtIndex(viewGroup, i)
if (canReceiveEvents(child)) {
val childPoint = tempPoint
transformTouchPointToViewCoords(coords[0], coords[1], viewGroup, child, childPoint)
val restoreX = coords[0]
val restoreY = coords[1]
coords[0] = childPoint.x
coords[1] = childPoint.y
var found = false
if (!isClipping(child) || isTransformedTouchPointInView(coords[0], coords[1], child)) {
// we only consider the view if touch is inside the view bounds or if the view's children
// can render outside of the view bounds (overflow visible)
found = traverseWithPointerEvents(child, coords, pointerId)
}
coords[0] = restoreX
coords[1] = restoreY
if (found) {
return true
}
}
}
return false
}
private fun traverseWithPointerEvents(view: View, coords: FloatArray, pointerId: Int): Boolean =
when (viewConfigHelper.getPointerEventsConfigForView(view)) {
PointerEventsConfig.NONE -> {
// This view and its children can't be the target
false
}
PointerEventsConfig.BOX_ONLY -> {
// This view is the target, its children don't matter
(recordViewHandlersForPointer(view, coords, pointerId)
|| shouldHandlerlessViewBecomeTouchTarget(view, coords))
}
PointerEventsConfig.BOX_NONE -> {
// This view can't be the target, but its children might
if (view is ViewGroup) {
extractGestureHandlers(view, coords, pointerId)
} else false
}
PointerEventsConfig.AUTO -> {
// Either this view or one of its children is the target
val found = if (view is ViewGroup) {
extractGestureHandlers(view, coords, pointerId)
} else false
(recordViewHandlersForPointer(view, coords, pointerId)
|| found || shouldHandlerlessViewBecomeTouchTarget(view, coords))
}
}
private fun canReceiveEvents(view: View) =
view.visibility == View.VISIBLE && view.alpha >= minimumAlphaForTraversal
// if view is not a view group it is clipping, otherwise we check for `getClipChildren` flag to
// be turned on and also confirm with the ViewConfigHelper implementation
private fun isClipping(view: View) =
view !is ViewGroup || viewConfigHelper.isViewClippingChildren(view)
companion object {
// The limit doesn't necessarily need to exists, it was just simpler to implement it that way
// it is also more allocation-wise efficient to have a fixed limit
private const val SIMULTANEOUS_GESTURE_HANDLER_LIMIT = 20
// Be default fully transparent views can receive touch
private const val DEFAULT_MIN_ALPHA_FOR_TRAVERSAL = 0f
private val tempPoint = PointF()
private val matrixTransformCoords = FloatArray(2)
private val inverseMatrix = Matrix()
private val tempCoords = FloatArray(2)
private val handlersComparator = Comparator<GestureHandler<*>?> { a, b ->
return@Comparator if (a.isActive && b.isActive || a.isAwaiting && b.isAwaiting) {
// both A and B are either active or awaiting activation, in which case we prefer one that
// has activated (or turned into "awaiting" state) earlier
Integer.signum(b.activationIndex - a.activationIndex)
} else if (a.isActive) {
-1 // only A is active
} else if (b.isActive) {
1 // only B is active
} else if (a.isAwaiting) {
-1 // only A is awaiting, B is inactive
} else if (b.isAwaiting) {
1 // only B is awaiting, A is inactive
} else {
0 // both A and B are inactive, stable order matters
}
}
private fun shouldHandlerlessViewBecomeTouchTarget(view: View, coords: FloatArray): Boolean {
// The following code is to match the iOS behavior where transparent parts of the views can
// pass touch events through them allowing sibling nodes to handle them.
// TODO: this is not an ideal solution as we only consider ViewGroups that has no background set
// TODO: ideally we should determine the pixel color under the given coordinates and return
// false if the color is transparent
val isLeafOrTransparent = view !is ViewGroup || view.getBackground() != null
return isLeafOrTransparent && isTransformedTouchPointInView(coords[0], coords[1], view)
}
private fun transformTouchPointToViewCoords(
x: Float,
y: Float,
parent: ViewGroup,
child: View,
outLocalPoint: PointF,
) {
var localX = x + parent.scrollX - child.left
var localY = y + parent.scrollY - child.top
val matrix = child.matrix
if (!matrix.isIdentity) {
val localXY = matrixTransformCoords
localXY[0] = localX
localXY[1] = localY
matrix.invert(inverseMatrix)
inverseMatrix.mapPoints(localXY)
localX = localXY[0]
localY = localXY[1]
}
outLocalPoint[localX] = localY
}
private fun isTransformedTouchPointInView(x: Float, y: Float, child: View) =
x in 0f..child.width.toFloat() && y in 0f..child.height.toFloat()
private fun shouldHandlerWaitForOther(handler: GestureHandler<*>, other: GestureHandler<*>): Boolean {
return handler !== other && (handler.shouldWaitForHandlerFailure(other)
|| other.shouldRequireToWaitForFailure(handler))
}
private fun canRunSimultaneously(a: GestureHandler<*>, b: GestureHandler<*>) =
a === b || a.shouldRecognizeSimultaneously(b) || b.shouldRecognizeSimultaneously(a)
private fun shouldHandlerBeCancelledBy(handler: GestureHandler<*>, other: GestureHandler<*>): Boolean {
if (!handler.hasCommonPointers(other)) {
// if two handlers share no common pointer one can never trigger cancel for the other
return false
}
if (canRunSimultaneously(handler, other)) {
// if handlers are allowed to run simultaneously, when first activates second can still remain
// in began state
return false
}
return if (handler !== other &&
(handler.isAwaiting || handler.state == GestureHandler.STATE_ACTIVE)) {
// in every other case as long as the handler is about to be activated or already in active
// state, we delegate the decision to the implementation of GestureHandler#shouldBeCancelledBy
handler.shouldBeCancelledBy(other)
} else true
}
private fun isFinished(state: Int) =
state == GestureHandler.STATE_CANCELLED
|| state == GestureHandler.STATE_FAILED
|| state == GestureHandler.STATE_END
}
}
| android/lib/src/main/java/com/swmansion/gesturehandler/GestureHandlerOrchestrator.kt | 1882461091 |
package com.planbase.pdf.lm2.contents
import TestManual2.Companion.BULLET_TEXT_STYLE
import TestManual2.Companion.CMYK_LIGHT_GREEN
import TestManual2.Companion.a6PortraitBody
import TestManuallyPdfLayoutMgr.Companion.RGB_DARK_GRAY
import TestManuallyPdfLayoutMgr.Companion.RGB_LIGHT_GREEN
import TestManuallyPdfLayoutMgr.Companion.letterLandscapeBody
import com.planbase.pdf.lm2.PdfLayoutMgr
import com.planbase.pdf.lm2.attributes.Orientation.*
import com.planbase.pdf.lm2.attributes.Align.TOP_LEFT
import com.planbase.pdf.lm2.attributes.BorderStyle
import com.planbase.pdf.lm2.attributes.BoxStyle
import com.planbase.pdf.lm2.attributes.CellStyle
import com.planbase.pdf.lm2.attributes.DimAndPageNums
import com.planbase.pdf.lm2.attributes.LineStyle
import com.planbase.pdf.lm2.attributes.Padding
import com.planbase.pdf.lm2.attributes.TextStyle
import com.planbase.pdf.lm2.utils.CMYK_BLACK
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import com.planbase.pdf.lm2.utils.RGB_BLACK
import junit.framework.TestCase.assertEquals
import org.apache.pdfbox.pdmodel.common.PDRectangle
import org.apache.pdfbox.pdmodel.font.PDType1Font
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB
import org.junit.Test
import java.io.FileOutputStream
const val twoHundred:Double = 200.0
val cellStyle = CellStyle(
TOP_LEFT, BoxStyle(Padding(2.0),
RGB_LIGHT_GREEN,
BorderStyle(RGB_DARK_GRAY)))
val textStyle = TextStyle(PDType1Font.COURIER, 12.0, RGB_BLACK)
val hello = Text(textStyle, "Hello")
//val helloSpace = Text(textStyle, "Hello ")
val helloHello = Text(textStyle, "Hello Hello")
val helloHelloWidth:Double = helloHello.maxWidth() * 0.7
class CellTest {
@Test fun testBasics() {
val cell = Cell(cellStyle, twoHundred, listOf(hello))
val wrappedCell:WrappedCell = cell.wrap()
assertEquals(textStyle.lineHeight + cellStyle.boxStyle.topBottomInteriorSp(),
wrappedCell.dim.height)
}
@Test fun testOneWrappedLine() {
val cell = Cell(cellStyle, helloHelloWidth, listOf(helloHello))
val wrappedCell:WrappedCell = cell.wrap()
assertEquals((textStyle.lineHeight * 2) + cellStyle.boxStyle.topBottomInteriorSp(),
wrappedCell.dim.height)
}
@Test fun testWrapTable() {
val pageMgr = PdfLayoutMgr(PDDeviceRGB.INSTANCE, Dim(PDRectangle.LETTER))
val lp = pageMgr.startPageGrouping(LANDSCAPE, letterLandscapeBody)
val cellStyle = CellStyle(
TOP_LEFT, BoxStyle(Padding(2.0),
RGB_LIGHT_GREEN,
BorderStyle(RGB_DARK_GRAY)))
val theText = Text(TextStyle(PDType1Font.COURIER, 12.0, RGB_BLACK), "Line 1")
val squareDim = 120.0
val tB = Table()
val trb: TableRow = tB.addCellWidths(listOf(squareDim))
.minRowHeight(squareDim)
.startRow()
val cell = Cell(cellStyle, squareDim, listOf(theText))
trb.cell(cell.cellStyle, listOf(theText))
assertEquals(squareDim, trb.minRowHeight)
// println("trb=" + trb)
val wrappedCell:WrappedCell = cell.wrap()
// println("wrappedCell=$wrappedCell")
assertEquals(theText.textStyle.lineHeight + cellStyle.boxStyle.topBottomInteriorSp(),
wrappedCell.dim.height)
val table: Table = trb.endRow()
// println("lp=$lp")
// println("lp.yBodyTop()=${lp.yBodyTop()}")
val dim: DimAndPageNums = table.wrap().render(lp, Coord(40.0, lp.yBodyTop()))
// println("lp.yBodyTop()=${lp.yBodyTop()}")
// println("xya=$xya")
assertEquals(squareDim, dim.dim.height)
pageMgr.commit()
// val os = FileOutputStream("testCell1.pdf")
// pageMgr.save(os)
}
// Note: very similar to TableTest.testNestedTablesAcrossPageBreak() but this is more specific and failed
// in a useful way 2018-11-15.
@Test fun testNestedCellsAcrossPageBreak() {
val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(PDRectangle.A6))
val lp = pageMgr.startPageGrouping(PORTRAIT, a6PortraitBody)
val testBorderStyle = BorderStyle(LineStyle(CMYK_BLACK, 0.1))
val bulletCell = Cell(CellStyle(TOP_LEFT, BoxStyle(Padding.NO_PADDING, null, testBorderStyle)), 230.0,
listOf(Text(BULLET_TEXT_STYLE,
"Some text with a bullet. " +
"Some text with a bullet. " +
"Some text with a bullet. " +
"Some text with a bullet. "),
Cell(CellStyle(TOP_LEFT, BoxStyle(Padding.NO_PADDING, CMYK_LIGHT_GREEN, BorderStyle.NO_BORDERS)),
203.0,
listOf(Text(BULLET_TEXT_STYLE,
"Subtext is an under and often distinct theme in a piece of writing or convers. " +
"Subtext is an under and often distinct theme in a piece of writing or convers. " +
"Subtext is an under and often distinct theme in a piece of writing or convers. ")),
25.0)
))
val wrappedCell: WrappedCell = bulletCell.wrap()
// TODO: Replace magic numbers with calculations like this:
// val bullTxtLineHeight = BULLET_TEXT_STYLE.lineHeight
// println("bullTxtLineHeight=$bullTxtLineHeight")
// println("bullTxtLineHeight * 3.0 =${bullTxtLineHeight * 3.0}")
// println("bullTxtLineHeight * 7.0 =${bullTxtLineHeight * 7.0}")
// println("wrappedCell=\n$wrappedCell")
Dim.assertEquals(Dim(230.0, 124.948), wrappedCell.dim, 0.0000000001)
val startCoord = Coord(0.0, 140.0)
val after:DimAndPageNums = wrappedCell.renderCustom(lp, startCoord, 0.0, reallyRender = true,
preventWidows = false)
Dim.assertEquals(Dim(230.0, 186.23203), after.dim, 0.0001)
pageMgr.commit()
// We're just going to write to a file.
val os = FileOutputStream("testNestedCellsAcrossPageBreak.pdf")
// Commit it to the output stream!
pageMgr.save(os)
}
} | src/test/java/com/planbase/pdf/lm2/contents/CellTest.kt | 1044577910 |
package com.zeyad.rxredux.screens
import android.os.Parcelable
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Parcelize
open class User(@PrimaryKey
var login: String = "",
var id: Long = 0,
var avatarUrl: String = "") : RealmObject(), Parcelable {
companion object {
const val LOGIN = "login"
private const val ID = "id"
private const val AVATAR_URL = "avatar_url"
}
}
| app/src/main/java/com/zeyad/rxredux/screens/User.kt | 254277887 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.util.SystemInfo
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.UsefulTestCase
import com.intellij.ui.UiTestRule
import com.intellij.ui.changeLafIfNeed
import com.intellij.ui.layout.migLayout.patched.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.*
import org.junit.Assume.assumeTrue
import org.junit.rules.TestName
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.nio.file.Paths
import javax.swing.JPanel
/**
* Set `test.update.snapshots=true` to automatically update snapshots if need.
*/
@RunWith(Parameterized::class)
class UiDslTest {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun lafNames() = listOf("Darcula", "IntelliJ")
@JvmField
@ClassRule
val appRule = ProjectRule()
@JvmField
@ClassRule
val uiRule = UiTestRule(Paths.get(PlatformTestUtil.getPlatformTestDataPath(), "ui", "layout"))
init {
System.setProperty("idea.ui.set.password.echo.char", "true")
}
}
@Suppress("MemberVisibilityCanBePrivate")
@Parameterized.Parameter
lateinit var lafName: String
@Rule
@JvmField
val testName = TestName()
@Before
fun beforeMethod() = runBlocking {
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
// let's for now to see how it is going on macOS
assumeTrue("macOS or Windows 10 are required", SystemInfo.isMacOSHighSierra /* || SystemInfo.isWin10OrNewer */)
}
System.setProperty("idea.ui.comment.copyable", "false")
changeLafIfNeed(lafName)
}
@After
fun afterMethod() {
System.clearProperty("idea.ui.comment.copyable")
}
@Test
fun `align fields in the nested grid`() {
doTest { alignFieldsInTheNestedGrid() }
}
@Test
fun `align fields`() {
doTest { labelRowShouldNotGrow() }
}
@Test
fun cell() {
doTest { cellPanel() }
}
@Test
fun `note row in the dialog`() {
doTest { noteRowInTheDialog() }
}
@Test
fun `visual paddings`() {
doTest { visualPaddingsPanel() }
}
@Test
fun `vertical buttons`() {
doTest { withVerticalButtons() }
}
@Test
fun `do not add visual paddings for titled border`() {
doTest { commentAndPanel() }
}
@Test
fun `checkbox that acts as label`() {
doTest { checkBoxFollowedBySpinner() }
}
@Test
fun `titled rows`() {
// failed on TC but for now no 10.14 agents to test
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
// let's for now to see how it is going on macOS
assumeTrue("macOS 10.14 or Windows 10 are required", SystemInfo.isMacOSMojave /* || SystemInfo.isWin10OrNewer */)
}
doTest { titledRows() }
}
@Test
fun `titled row`() {
// failed on TC but for now no 10.14 agents to test
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
// let's for now to see how it is going on macOS
assumeTrue("macOS 10.14 or Windows 10 are required", SystemInfo.isMacOSMojave /* || SystemInfo.isWin10OrNewer */)
}
doTest { titledRow() }
}
private fun doTest(panelCreator: () -> JPanel) {
runBlocking {
withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
val panel = panelCreator()
// otherwise rectangles are not set
(panel.layout as MigLayout).isDebugEnabled = true
uiRule.validate(panel, testName, lafName)
}
}
}
} | platform/platform-tests/testSrc/com/intellij/ui/layout/UiDslTest.kt | 554404433 |
/*
* Copyright 2016-2019 Julien Guerinet
*
* 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.guerinet.suitcase.ui.extensions
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
/**
* ImageView extensions
* @author Julien Guerinet
* @since 2.3.0
*/
/**
* Sets the tint with the [color]
*/
fun ImageView.setTint(@ColorInt color: Int) = setImageDrawable(drawable.setTintCompat(color))
/**
* Sets the tint with the [colorId]
*/
fun ImageView.setTintId(@ColorRes colorId: Int) = setTint(ContextCompat.getColor(context, colorId))
/**
* Sets the [resourceId] on the Image using the Compat functions
*/
fun ImageView.setResourceCompat(resourceId: Int) {
setImageDrawable(AppCompatResources.getDrawable(context, resourceId))
}
| ui/src/main/java/com/guerinet/suitcase/ui/extensions/ImageViewExt.kt | 4196122336 |
// 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.script
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
override val id = "ScriptTemplatesFromDependenciesProvider"
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val connection = project.messageBus.connect()
connection.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
}
},
)
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val pluginDisposable = KotlinPluginDisposable.getInstance(project)
val (templates, classpath) =
ReadAction.nonBlocking(Callable {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
val files = mutableSetOf<VirtualFile>()
FileTypeIndex.processFiles(ScriptDefinitionMarkerFileType, {
indicator.checkCanceled()
files.add(it)
true
}, project.allScope())
getTemplateClassPath(files, indicator)
})
})
.expireWith(pluginDisposable)
.wrapProgress(indicator)
.executeSynchronously() ?: return onEarlyEnd()
try {
indicator.checkCanceled()
if (pluginDisposable.disposed || !inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
indicator.checkCanceled()
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>, indicator: ProgressIndicator): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
indicator.checkCanceled()
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getRootFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
indicator.checkCanceled()
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 1596465342 |
// 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.project
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.SimplePersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.util.xmlb.annotations.Property
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Property(style = Property.Style.ATTRIBUTE)
class ExternalStorageConfiguration : BaseState() {
var enabled by property(false)
}
/**
* This class isn't used in the new implementation of project model, which is based on [Workspace Model][com.intellij.workspaceModel.ide].
* It shouldn't be used directly, its interface [ExternalStorageConfigurationManager] should be used instead.
*/
@State(name = "ExternalStorageConfigurationManager")
internal class ExternalStorageConfigurationManagerImpl(private val project: Project) : SimplePersistentStateComponent<ExternalStorageConfiguration>(ExternalStorageConfiguration()), ExternalStorageConfigurationManager {
override fun isEnabled(): Boolean = state.enabled
/**
* Internal use only. Call ExternalProjectsManagerImpl.setStoreExternally instead.
*/
override fun setEnabled(value: Boolean) {
state.enabled = value
if (project.isDefault) return
val app = ApplicationManager.getApplication()
app.invokeAndWait { app.runWriteAction(::updateEntitySource) }
}
override fun loadState(state: ExternalStorageConfiguration) {
super.loadState(state)
if (project.isDefault) {
return
}
project.coroutineScope.launch(Dispatchers.EDT) {
ApplicationManager.getApplication().runWriteAction(::updateEntitySource)
}
}
private fun updateEntitySource() {
val value = state.enabled
WorkspaceModel.getInstance(project).updateProjectModel { updater ->
val entitiesMap = updater.entitiesBySource { it is JpsImportedEntitySource && it.storedExternally != value }
entitiesMap.values.asSequence().flatMap { it.values.asSequence().flatMap { entities -> entities.asSequence() } }.forEach { entity ->
val source = entity.entitySource
if (source is JpsImportedEntitySource) {
updater.modifyEntity(ModifiableWorkspaceEntity::class.java, entity) {
this.entitySource = JpsImportedEntitySource(source.internalFile, source.externalSystemId, value)
}
}
}
}
}
} | platform/configuration-store-impl/src/ExternalStorageConfigurationManagerImpl.kt | 3703869129 |
// 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.workspaceModel.ide.impl
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.ide.CustomModuleEntitySource
import com.intellij.workspaceModel.ide.JpsFileDependentEntitySource
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.FacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity
/**
* This class is used to reuse [JpsFileEntitySource.FileInDirectory] instances when project is synchronized with JPS files after loading
* storage from binary cache.
*/
class FileInDirectorySourceNames private constructor(entitiesBySource: Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>) {
private val mainEntityToSource: Map<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>
init {
val sourcesMap = HashMap<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>()
for ((source, entities) in entitiesBySource) {
val (type, entityName) = when {
ModuleEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(ModuleEntity::class.java).first() as ModuleEntity).name
FacetEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(FacetEntity::class.java).first() as FacetEntity).module.name
LibraryEntity::class.java in entities -> LibraryEntity::class.java to (entities.getValue(LibraryEntity::class.java).first() as LibraryEntity).name
ArtifactEntity::class.java in entities -> ArtifactEntity::class.java to (entities.getValue(ArtifactEntity::class.java).first() as ArtifactEntity).name
else -> null to null
}
if (type != null && entityName != null) {
val fileName = when {
// At external storage libs and artifacts store in its own file and at [JpsLibrariesExternalFileSerializer]/[JpsArtifactEntitiesSerializer]
// we can distinguish them only by directly entity name
(type == LibraryEntity::class.java || type == ArtifactEntity::class.java) && (source as? JpsImportedEntitySource)?.storedExternally == true -> entityName
// Module file stored at external and internal modules.xml has .iml file extension
type == ModuleEntity::class.java -> "$entityName.iml"
// In internal store (i.e. under `.idea` folder) each library or artifact has its own file, and we can distinguish them only by file name
else -> FileUtil.sanitizeFileName(entityName) + ".xml"
}
sourcesMap[type to fileName] = getInternalFileSource(source) as JpsFileEntitySource.FileInDirectory
}
}
mainEntityToSource = sourcesMap
}
fun findSource(entityClass: Class<out WorkspaceEntity>, fileName: String): JpsFileEntitySource.FileInDirectory? =
mainEntityToSource[entityClass to fileName]
companion object {
fun from(storage: EntityStorage) = FileInDirectorySourceNames(
storage.entitiesBySource { getInternalFileSource(it) is JpsFileEntitySource.FileInDirectory }
)
fun empty() = FileInDirectorySourceNames(emptyMap())
private fun getInternalFileSource(source: EntitySource) = when (source) {
is JpsFileDependentEntitySource -> source.originalSource
is CustomModuleEntitySource -> source.internalSource
is JpsFileEntitySource -> source
else -> null
}
}
}
| platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/FileInDirectorySourceNames.kt | 689738117 |
package quickbeer.android.feature.search
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
class SearchPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount(): Int {
return 4
}
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> SearchBeersFragment()
1 -> SearchBrewersFragment()
2 -> SearchStylesFragment()
else -> SearchCountriesFragment()
}
}
}
| app/src/main/java/quickbeer/android/feature/search/SearchPagerAdapter.kt | 1295377233 |
package org.jetbrains.haskell.debugger.protocol
import org.jetbrains.haskell.debugger.parser.ParseResult
/**
* Created by vlad on 7/17/14.
*/
/**
* Command like setting breakpoint
*/
abstract class RealTimeCommand<R : ParseResult?>(callback: CommandCallback<R>?) : AbstractCommand<R>(callback) | plugin/src/org/jetbrains/haskell/debugger/protocol/RealTimeCommand.kt | 1997656283 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.gradle
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import org.intellij.lang.annotations.Language
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.util.JpsPathUtil
import org.jetbrains.kotlin.config.ExternalSystemTestRunTask
import org.jetbrains.kotlin.idea.base.facet.externalSystemTestRunTasks
import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.gradleJava.configuration.kotlinGradleProjectDataOrFail
import org.jetbrains.kotlin.idea.gradleTooling.KotlinImportingDiagnostic
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
import org.jetbrains.plugins.gradle.util.GradleUtil
import java.io.File
import kotlin.test.fail
class MessageCollector {
private val builder = StringBuilder()
fun report(message: String) {
builder.append(message).append("\n\n")
}
fun check() {
val message = builder.toString()
if (message.isNotEmpty()) {
fail("\n\n" + message)
}
}
}
class ProjectInfo(
project: Project,
internal val projectPath: String,
internal val exhaustiveModuleList: Boolean,
internal val exhaustiveSourceSourceRootList: Boolean,
internal val exhaustiveDependencyList: Boolean,
internal val exhaustiveTestsList: Boolean
) {
val messageCollector = MessageCollector()
private val moduleManager = ModuleManager.getInstance(project)
private val expectedModuleNames = HashSet<String>()
private var allModulesAsserter: (ModuleInfo.() -> Unit)? = null
private val moduleInfos = moduleManager.modules.associateWith { module -> ModuleInfo(module, this) }
@Deprecated("Use .forEachModule instead. This method is error prone and has to be called before 'module(..)' in order to run")
fun allModules(body: ModuleInfo.() -> Unit) {
assert(allModulesAsserter == null)
allModulesAsserter = body
}
fun forEachModule(body: ModuleInfo.() -> Unit) {
moduleInfos.values.forEach { moduleInfo ->
moduleInfo.run(body)
}
}
fun module(name: String, isOptional: Boolean = false, body: ModuleInfo.() -> Unit = {}) {
val module = moduleManager.findModuleByName(name)
if (module == null) {
if (!isOptional) {
messageCollector.report("No module found: '$name' in ${moduleManager.modules.map { it.name }}")
}
return
}
val moduleInfo = moduleInfos.getValue(module)
allModulesAsserter?.let { moduleInfo.it() }
moduleInfo.run(body)
expectedModuleNames += name
}
fun run(body: ProjectInfo.() -> Unit = {}) {
body()
if (exhaustiveModuleList) {
val actualNames = moduleManager.modules.map { it.name }.sorted()
val expectedNames = expectedModuleNames.sorted()
if (actualNames != expectedNames) {
messageCollector.report("Expected module list $expectedNames doesn't match the actual one: $actualNames")
}
}
messageCollector.check()
}
}
class ModuleInfo(val module: Module, val projectInfo: ProjectInfo) {
private val rootModel = module.rootManager
private val expectedDependencyNames = HashSet<String>()
private val expectedDependencies = HashSet<OrderEntry>()
private val expectedSourceRoots = HashSet<String>()
private val expectedExternalSystemTestTasks = ArrayList<ExternalSystemTestRunTask>()
private val assertions = mutableListOf<(ModuleInfo) -> Unit>()
private var mustHaveSdk: Boolean = true
private val sourceFolderByPath by lazy {
rootModel.contentEntries.asSequence()
.flatMap { it.sourceFolders.asSequence() }
.mapNotNull {
val path = it.file?.path ?: return@mapNotNull null
FileUtil.getRelativePath(projectInfo.projectPath, path, '/')!! to it
}
.toMap()
}
fun report(text: String) {
projectInfo.messageCollector.report("Module '${module.name}': $text")
}
private fun checkReport(subject: String, expected: Any?, actual: Any?) {
if (expected != actual) {
report(
"$subject differs:\n" +
"expected $expected\n" +
"actual: $actual"
)
}
}
fun externalSystemTestTask(taskName: String, projectId: String, targetName: String) {
expectedExternalSystemTestTasks.add(ExternalSystemTestRunTask(taskName, projectId, targetName))
}
fun languageVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.languageVersion.versionString
checkReport("Language version", expectedVersion, actualVersion)
}
fun isHMPP(expectedValue: Boolean) {
checkReport("isHMPP", expectedValue, module.isHMPPEnabled)
}
fun targetPlatform(vararg platforms: TargetPlatform) {
val expected = platforms.flatMap { it.componentPlatforms }.toSet()
val actual = runReadAction { module.platform?.componentPlatforms }
if (actual == null) {
report("Actual target platform is null")
return
}
val notFound = expected.subtract(actual)
if (notFound.isNotEmpty()) {
report("These target platforms were not found: " + notFound.joinToString())
}
val unexpected = actual.subtract(expected)
if (unexpected.isNotEmpty()) {
report("Unexpected target platforms found: " + unexpected.joinToString())
}
}
fun apiVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.apiVersion.versionString
checkReport("API version", expectedVersion, actualVersion)
}
fun platform(expectedPlatform: TargetPlatform) {
val actualPlatform = module.platform
checkReport("Platform", expectedPlatform, actualPlatform)
}
fun additionalArguments(arguments: String?) {
val actualArguments = KotlinFacet.get(module)?.configuration?.settings?.compilerSettings?.additionalArguments
checkReport("Additional arguments", arguments, actualArguments)
}
fun kotlinFacetSettingCreated() {
val facet = KotlinFacet.get(module)?.configuration?.settings
if (facet == null) report("KotlinFacetSettings does not exist")
}
fun noLibraryDependency(libraryNameRegex: Regex) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName?.matches(libraryNameRegex) == true }
if (libraryEntries.isNotEmpty()) {
report(
"Expected no dependencies for $libraryNameRegex, but found:\n" +
libraryEntries.joinToString(prefix = "[", postfix = "]", separator = ",") { it.presentableName }
)
}
}
fun noLibraryDependency(@Language("regex") libraryNameRegex: String) {
noLibraryDependency(Regex(libraryNameRegex))
}
fun libraryDependency(libraryName: String, scope: DependencyScope, isOptional: Boolean = false) {
libraryDependency(Regex.fromLiteral(libraryName), scope, allowMultiple = false, isOptional)
}
fun libraryDependency(libraryName: Regex, scope: DependencyScope, allowMultiple: Boolean = false, isOptional: Boolean = false) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName?.matches(libraryName) == true }
if (!allowMultiple && libraryEntries.size > 1) {
report("Multiple root entries for library $libraryName")
}
if (!isOptional && libraryEntries.isEmpty()) {
val candidate = rootModel.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.sortedWith(Comparator { o1, o2 ->
val o1len = o1?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
val o2len = o2?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
o2len - o1len
}).firstOrNull()
val candidateName = candidate?.libraryName
report("Expected library dependency $libraryName, found nothing. Most probably candidate: $candidateName")
}
libraryEntries.forEach { library ->
checkLibrary(library, scope)
}
}
fun libraryDependencyByUrl(classesUrl: String, scope: DependencyScope) {
libraryDependencyByUrl(Regex.fromLiteral(classesUrl), scope)
}
fun libraryDependencyByUrl(classesUrl: Regex, scope: DependencyScope) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>().filter { entry ->
entry.library?.getUrls(OrderRootType.CLASSES)?.any { it.matches(classesUrl) } ?: false
}
if (libraryEntries.size > 1) {
report("Multiple entries for library $classesUrl")
}
if (libraryEntries.isEmpty()) {
report("No library dependency found for $classesUrl")
}
checkLibrary(libraryEntries.firstOrNull() ?: return, scope)
}
private fun checkLibrary(libraryEntry: LibraryOrderEntry, scope: DependencyScope) {
checkDependencyScope(libraryEntry, scope)
expectedDependencies += libraryEntry
expectedDependencyNames += libraryEntry.debugText
}
fun moduleDependency(
moduleName: String, scope: DependencyScope,
productionOnTest: Boolean? = null, allowMultiple: Boolean = false, isOptional: Boolean = false
) {
val moduleEntries = rootModel.orderEntries.asList()
.filterIsInstanceWithChecker<ModuleOrderEntry> { it.moduleName == moduleName && it.scope == scope }
// In normal conditions, 'allowMultiple' should always be 'false'. In reality, however, a lot of tests fails because of it.
if (!allowMultiple && moduleEntries.size > 1) {
val allEntries = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Multiple order entries found for module $moduleName: $allEntries")
return
}
if (moduleEntries.isEmpty() && !isOptional) {
val allModules = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Module dependency ${moduleName} (${scope.displayName}) not found. All module dependencies: $allModules")
}
moduleEntries.forEach { moduleEntry ->
checkDependencyScope(moduleEntry, scope)
checkProductionOnTest(moduleEntry, productionOnTest)
expectedDependencies += moduleEntry
expectedDependencyNames += moduleEntry.debugText
}
}
private val ANY_PACKAGE_PREFIX = "any_package_prefix"
fun sourceFolder(pathInProject: String, rootType: JpsModuleSourceRootType<*>, packagePrefix: String? = ANY_PACKAGE_PREFIX) {
val sourceFolder = sourceFolderByPath[pathInProject]
if (sourceFolder == null) {
report("No source root found: '$pathInProject' among $sourceFolderByPath")
return
}
if (packagePrefix != ANY_PACKAGE_PREFIX && sourceFolder.packagePrefix != packagePrefix) {
report("Source root '$pathInProject': Expected package prefix $packagePrefix, got: ${sourceFolder.packagePrefix}")
}
expectedSourceRoots += pathInProject
val actualRootType = sourceFolder.rootType
if (actualRootType != rootType) {
report("Source root '$pathInProject': Expected root type $rootType, got: $actualRootType")
return
}
}
fun inheritProjectOutput() {
val isInherited = CompilerModuleExtension.getInstance(module)?.isCompilerOutputPathInherited ?: true
if (!isInherited) {
report("Project output is not inherited")
}
}
fun outputPath(pathInProject: String, isProduction: Boolean) {
val compilerModuleExtension = CompilerModuleExtension.getInstance(module)
val url = if (isProduction) compilerModuleExtension?.compilerOutputUrl else compilerModuleExtension?.compilerOutputUrlForTests
val actualPathInProject = url?.let {
FileUtil.getRelativePath(
projectInfo.projectPath,
JpsPathUtil.urlToPath(
it
),
'/'
)
}
checkReport("Output path", pathInProject, actualPathInProject)
}
fun noSdk() {
mustHaveSdk = false
}
inline fun <reified T : KotlinImportingDiagnostic> assertDiagnosticsCount(count: Int) {
val moduleNode = GradleUtil.findGradleModuleData(module)
val diagnostics = moduleNode!!.kotlinGradleProjectDataOrFail.kotlinImportingDiagnosticsContainer!!
val typedDiagnostics = diagnostics.filterIsInstance<T>()
if (typedDiagnostics.size != count) {
projectInfo.messageCollector.report(
"Expected number of ${T::class.java.simpleName} diagnostics $count doesn't match the actual one: ${typedDiagnostics.size}"
)
}
}
fun assertExhaustiveDependencyList() {
assertions += {
val expectedDependencyNames = expectedDependencyNames.sorted()
val actualDependencyNames = rootModel
.orderEntries.asList()
.filterIsInstanceWithChecker<ExportableOrderEntry> { it is ModuleOrderEntry || it is LibraryOrderEntry }
.map { it.debugText }
.sorted()
.distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedDependencyNames) 0 else 1 }
checkReport("Dependency list", expectedDependencyNames, actualDependencyNames)
}
}
fun assertExhaustiveModuleDependencyList() {
assertions += {
val expectedModuleDependencies = expectedDependencies.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
val actualModuleDependencies = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedModuleDependencies) 0 else 1 }
if (actualModuleDependencies != expectedModuleDependencies) {
report(
"Bad Module dependency list for ${module.name}\n" +
"Expected: $expectedModuleDependencies\n" +
"Actual: $actualModuleDependencies"
)
}
}
}
fun assertExhaustiveLibraryDependencyList() {
assertions += {
val expectedLibraryDependencies = expectedDependencies.filterIsInstance<LibraryOrderEntry>()
.map { it.debugText }.sorted().distinct()
val actualLibraryDependencies = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.map { it.debugText }.sorted().distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedLibraryDependencies) 0 else 1 }
if (actualLibraryDependencies != expectedLibraryDependencies) {
report(
"Bad Library dependency list for ${module.name}\n" +
"Expected: $expectedLibraryDependencies\n" +
"Actual: $actualLibraryDependencies"
)
}
}
}
fun assertExhaustiveTestsList() {
assertions += {
val actualTasks = module.externalSystemTestRunTasks()
val containsAllTasks = actualTasks.containsAll(expectedExternalSystemTestTasks)
val containsSameTasks = actualTasks == expectedExternalSystemTestTasks
if (!containsAllTasks || !containsSameTasks) {
report("Expected tests list $expectedExternalSystemTestTasks, got: $actualTasks")
}
}
}
fun assertExhaustiveSourceRootList() {
assertions += {
val actualSourceRoots = sourceFolderByPath.keys.sorted()
val expectedSourceRoots = expectedSourceRoots.sorted()
if (actualSourceRoots != expectedSourceRoots) {
report("Expected source root list $expectedSourceRoots, got: $actualSourceRoots")
}
}
}
fun assertNoDependencyInBuildClasses() {
val librariesOnly = OrderEnumerator.orderEntries(module).recursively().librariesOnly()
val rootUrls = librariesOnly.classes().urls + librariesOnly.sources().urls
val dependenciesInBuildDirectory = rootUrls
.map { url -> PathUtil.getLocalPath(VfsUtilCore.urlToPath(url)) }
.filter { path -> "/build/classes/" in path }
if (dependenciesInBuildDirectory.isNotEmpty()) {
report("References dependency in build directory:\n${dependenciesInBuildDirectory.joinToString("\n")}")
}
}
fun run(body: ModuleInfo.() -> Unit = {}) {
body()
assertions.forEach { it.invoke(this) }
assertions.clear()
if (mustHaveSdk && rootModel.sdk == null) {
report("No SDK defined")
}
}
private fun checkDependencyScope(library: ExportableOrderEntry, expectedScope: DependencyScope) {
checkReport("Dependency scope", expectedScope, library.scope)
}
private fun checkProductionOnTest(library: ExportableOrderEntry, productionOnTest: Boolean?) {
if (productionOnTest == null) return
val actualFlag = (library as? ModuleOrderEntry)?.isProductionOnTestDependency
if (actualFlag == null) {
report("Dependency '${library.presentableName}' has no 'productionOnTest' property")
} else {
if (actualFlag != productionOnTest) {
report("Dependency '${library.presentableName}': expected productionOnTest '$productionOnTest', got '$actualFlag'")
}
}
}
init {
if (projectInfo.exhaustiveDependencyList) {
assertExhaustiveDependencyList()
}
if (projectInfo.exhaustiveTestsList) {
assertExhaustiveTestsList()
}
if (projectInfo.exhaustiveSourceSourceRootList) {
assertExhaustiveSourceRootList()
}
}
}
fun checkProjectStructure(
project: Project,
projectPath: String,
exhaustiveModuleList: Boolean = false,
exhaustiveSourceSourceRootList: Boolean = false,
exhaustiveDependencyList: Boolean = false,
exhaustiveTestsList: Boolean = false,
body: ProjectInfo.() -> Unit = {}
) {
ProjectInfo(
project,
projectPath,
exhaustiveModuleList,
exhaustiveSourceSourceRootList,
exhaustiveDependencyList,
exhaustiveTestsList
).run(body)
}
private val ExportableOrderEntry.debugText: String
get() = "$presentableName (${scope.displayName})"
private fun VirtualFile.toIoFile(): File = VfsUtil.virtualToIoFile(this)
| plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/projectStructureDSL.kt | 2508983158 |
package test
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.cache.normalized.api.CacheHeaders
import com.apollographql.apollo3.cache.normalized.api.MemoryCache
import com.apollographql.apollo3.cache.normalized.api.Record
import com.apollographql.apollo3.testing.runTest
import kotlinx.coroutines.delay
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
@OptIn(ApolloExperimental::class)
class MemoryCacheTest {
@Test
fun testDoesNotExpireBeforeMillis() = runTest {
val record = Record(
key = "key",
fields = mapOf(
"field" to "value"
)
)
val memoryCache = MemoryCache(expireAfterMillis = 200)
memoryCache.merge(record, CacheHeaders.NONE)
val cacheRecord = checkNotNull(memoryCache.loadRecord(record.key, CacheHeaders.NONE))
assertEquals(record.key, cacheRecord.key)
assertEquals(record.fields, cacheRecord.fields)
delay(250)
assertNull(memoryCache.loadRecord(record.key, CacheHeaders.NONE))
}
} | tests/integration-tests/src/commonTest/kotlin/test/MemoryCacheTest.kt | 1288904199 |
package com.apollographql.apollo3.adapter
import com.apollographql.apollo3.api.Adapter
import com.apollographql.apollo3.api.CustomScalarAdapters
import com.apollographql.apollo3.api.json.JsonReader
import com.apollographql.apollo3.api.json.JsonWriter
import kotlinx.datetime.Instant
import java.util.Date
/**
* An [Adapter] that converts an ISO 8601 String like "2010-06-01T22:19:44.475Z" to/from
* a java [Date]
*
* It requires Android Gradle plugin 4.0 or newer and [core library desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring).
*/
object DateAdapter : Adapter<Date> {
override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): Date {
return Date(Instant.parse(reader.nextString()!!).toEpochMilliseconds())
}
override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: Date) {
writer.value(Instant.fromEpochMilliseconds(value.time).toString())
}
} | apollo-adapters/src/jvmMain/kotlin/com/apollographql/apollo3/adapter/DateAdapter.kt | 3091406076 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.ColorUtil
import com.intellij.util.ui.HTMLEditorKitBuilder
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JEditorPane
import javax.swing.JLabel
import javax.swing.JPanel
@Deprecated("Use Kotlin UI DSL 2, or com.intellij.diagnostic.PrivacyNotice from Java code")
class PrivacyNoticeComponent(@NlsContexts.Label private val label: String, @NlsContexts.Label private val expandedLabel: String) : JPanel(
GridBagLayout()) {
private val iconLabel: JLabel = JLabel()
private val titleLabel = JLabel()
private val privacyPolicyPane: JEditorPane = JEditorPane()
var expanded: Boolean = true
set(expanded) {
field = expanded
if (expanded) {
titleLabel.text = expandedLabel
iconLabel.icon = AllIcons.General.ArrowDown
privacyPolicyPane.isVisible = true
}
else {
titleLabel.text = label
iconLabel.icon = AllIcons.General.ArrowRight
privacyPolicyPane.isVisible = false
}
}
var privacyPolicy: String
get() = privacyPolicyPane.text
set(@Nls(capitalization = Nls.Capitalization.Sentence) text) {
privacyPolicyPane.text = text
}
init {
background = backgroundColor()
val iconLabelPanel = JPanel(BorderLayout())
useInHeader(iconLabelPanel)
iconLabelPanel.add(iconLabel, BorderLayout.WEST)
val mySeparatorPanel = JPanel()
useInHeader(mySeparatorPanel)
mySeparatorPanel.preferredSize = Dimension(6, 1)
useInHeader(titleLabel)
titleLabel.foreground = titleColor()
titleLabel.font = titleLabel.font.deriveFont((titleLabel.font.size - 1).toFloat())
privacyPolicyPane.isEditable = false
privacyPolicyPane.isFocusable = false
privacyPolicyPane.background = backgroundColor()
privacyPolicyPane.foreground = noticeColor()
privacyPolicyPane.font = privacyPolicyPane.font.deriveFont((privacyPolicyPane.font.size - if (SystemInfo.isWindows) 2 else 1).toFloat())
privacyPolicyPane.editorKit = HTMLEditorKitBuilder.simple()
privacyPolicyPane.border = JBUI.Borders.empty(0, 0, 6, 6)
privacyPolicyPane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
add(mySeparatorPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL,
JBInsets.emptyInsets(),
0, 0))
add(iconLabelPanel,
GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, JBInsets.emptyInsets(), 0, 0))
add(titleLabel, GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBInsets.emptyInsets(), 0,
0))
add(privacyPolicyPane, GridBagConstraints(2, 1, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBInsets.emptyInsets(), 0, 0))
expanded = true
}
private fun useInHeader(component: JComponent) {
component.border = JBUI.Borders.empty(6, 0)
component.background = backgroundColor()
component.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
component.addMouseListener(object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent?) {
expanded = !expanded
}
})
}
companion object {
private fun titleColor() = UIUtil.getLabelForeground()
private fun noticeColor() = UIUtil.getContextHelpForeground()
private fun backgroundColor() = ColorUtil.hackBrightness(JBUI.CurrentTheme.CustomFrameDecorations.paneBackground(), 1, 1 / 1.05f)
}
} | platform/platform-impl/src/com/intellij/diagnostic/PrivacyNoticeComponent.kt | 172110202 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import com.intellij.util.text.CharSequenceSubSequence
import junit.framework.ComparisonFailure
import java.util.*
import java.util.concurrent.atomic.AtomicLong
abstract class DiffTestCase : UsefulTestCase() {
companion object {
private val DEFAULT_CHAR_COUNT = 12
private val DEFAULT_CHAR_TABLE: Map<Int, Char> = {
val map = HashMap<Int, Char>()
listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) }
map
}()
}
val RNG: Random = Random()
private var gotSeedException = false
val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE
val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl()
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
}
override fun tearDown() {
DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable"))
super.tearDown()
}
//
// Assertions
//
fun assertTrue(actual: Boolean, message: String = "") {
assertTrue(message, actual)
}
fun assertFalse(actual: Boolean, message: String = "") {
assertFalse(message, actual)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
assertEquals(message, expected, actual)
}
fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") {
if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString())
}
fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(StringUtil.equals(chunk1, chunk2) ||
StringUtil.equals(stripNewline(chunk1), chunk2) ||
StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(!StringUtil.equals(chunk1, chunk2) ||
!StringUtil.equals(stripNewline(chunk1), chunk2) ||
!StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean {
if (ignoreSpaces) {
return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2)
}
else {
return StringUtil.equals(chunk1, chunk2)
}
}
//
// Parsing
//
fun textToReadableFormat(text: CharSequence?): String {
if (text == null) return "null"
return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'"
}
fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n')
fun parseMatching(matching: String): BitSet {
val set = BitSet()
matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) }
return set
}
//
// Misc
//
fun getLineCount(document: Document): Int {
return Math.max(1, document.lineCount)
}
infix fun Int.until(a: Int): IntRange = this..a - 1
//
// AutoTests
//
fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) {
RNG.setSeed(seed)
var lastSeed: Long = -1
val debugData = DebugData()
for (i in 1..runs) {
if (i % 1000 == 0) println(i)
try {
lastSeed = getCurrentSeed()
test(debugData)
debugData.reset()
}
catch (e: Throwable) {
println("Seed: " + seed)
println("Runs: " + runs)
println("I: " + i)
println("Current seed: " + lastSeed)
debugData.dump()
throw e
}
}
}
fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String {
val length = RNG.nextInt(maxLength + 1)
val builder = StringBuilder(length)
for (i in 1..length) {
val rnd = RNG.nextInt(charCount)
val char = predefinedChars[rnd] ?: (rnd + 97).toChar()
builder.append(char)
}
return builder.toString()
}
fun generateText(maxLength: Int): String {
return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE)
}
fun getCurrentSeed(): Long {
if (gotSeedException) return -1
try {
val seedField = RNG.javaClass.getDeclaredField("seed")
seedField.isAccessible = true
val seedFieldValue = seedField.get(RNG) as AtomicLong
return seedFieldValue.get() xor 0x5DEECE66DL
}
catch (e: Exception) {
gotSeedException = true
System.err.println("Can't get random seed: " + e.message)
return -1
}
}
private fun stripNewline(text: CharSequence): CharSequence? {
return when (StringUtil.endsWithChar(text, '\n')) {
true -> CharSequenceSubSequence(text, 0, text.length - 1)
false -> null
}
}
class DebugData() {
private val data: MutableList<Pair<String, Any>> = ArrayList()
fun put(key: String, value: Any) {
data.add(Pair(key, value))
}
fun reset() {
data.clear()
}
fun dump() {
data.forEach { println(it.first + ": " + it.second) }
}
}
//
// Helpers
//
open class Trio<out T>(val data1: T, val data2: T, val data3: T) {
companion object {
fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT))
}
fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3))
fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT))
fun forEach(f: (T, ThreeSide) -> Unit): Unit {
f(data1, ThreeSide.LEFT)
f(data2, ThreeSide.BASE)
f(data3, ThreeSide.RIGHT)
}
operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T
override fun toString(): String {
return "($data1, $data2, $data3)"
}
override fun equals(other: Any?): Boolean {
return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3
}
override fun hashCode(): Int {
var h = 0
if (data1 != null) h = h * 31 + data1.hashCode()
if (data2 != null) h = h * 31 + data2.hashCode()
if (data3 != null) h = h * 31 + data3.hashCode()
return h
}
}
} | platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt | 709217312 |
/*
* 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.samples.apps.iosched.shared.data.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
/**
* The Data Access Object for the [SpeakerFtsEntity] class.
*/
@Dao
interface SpeakerFtsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(speakers: List<SpeakerFtsEntity>)
@Query("SELECT speakerId FROM speakersFts WHERE speakersFts MATCH :query")
fun searchAllSpeakers(query: String): List<String>
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/data/db/SpeakerFtsDao.kt | 1414843154 |
package com.simplemobiletools.gallery.pro.extensions
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
fun View.sendFakeClick(x: Float, y: Float) {
val uptime = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(uptime, uptime, MotionEvent.ACTION_DOWN, x, y, 0)
dispatchTouchEvent(event)
event.action = MotionEvent.ACTION_UP
dispatchTouchEvent(event)
}
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/extensions/View.kt | 1565273958 |
package org.stepik.android.view.injection.course_list.user
import dagger.Subcomponent
import org.stepik.android.view.course_list.ui.fragment.CourseListUserFragment
import org.stepik.android.view.course_list.ui.fragment.CourseListUserHorizontalFragment
import org.stepik.android.view.injection.course.CourseDataModule
import org.stepik.android.view.injection.course_payments.CoursePaymentsDataModule
import org.stepik.android.view.injection.last_step.LastStepDataModule
import org.stepik.android.view.injection.wishlist.WishlistDataModule
@CourseListUserScope
@Subcomponent(modules = [
CourseListUserModule::class,
CourseDataModule::class,
CoursePaymentsDataModule::class,
LastStepDataModule::class,
WishlistDataModule::class
])
interface CourseListUserComponent {
@Subcomponent.Builder
interface Builder {
fun build(): CourseListUserComponent
}
fun inject(courseListUserFragment: CourseListUserFragment)
fun inject(courseListUserHorizontalFragment: CourseListUserHorizontalFragment)
} | app/src/main/java/org/stepik/android/view/injection/course_list/user/CourseListUserComponent.kt | 3410507901 |
package io.github.chrislo27.rhre3.entity.model.special
import com.badlogic.gdx.graphics.Color
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.entity.model.IStretchable
import io.github.chrislo27.rhre3.entity.model.ModelEntity
import io.github.chrislo27.rhre3.playalong.InputAction
import io.github.chrislo27.rhre3.playalong.PlayalongInput
import io.github.chrislo27.rhre3.playalong.PlayalongMethod
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.special.PlayalongModel
import io.github.chrislo27.rhre3.theme.Theme
import io.github.chrislo27.rhre3.track.Remix
class PlayalongEntity(remix: Remix, datamodel: PlayalongModel)
: ModelEntity<PlayalongModel>(remix, datamodel), IStretchable {
override val isStretchable: Boolean = datamodel.stretchable
val playalongInput: PlayalongInput get() = datamodel.playalongInput
val playalongMethod: PlayalongMethod get() = datamodel.playalongMethod
override var needsNameTooltip: Boolean
get() = false
set(_) {}
init {
this.bounds.width = datamodel.duration
this.bounds.height = 1f
}
override fun getHoverText(inSelection: Boolean): String? {
return datamodel.pickerName.main
}
override fun getRenderColor(editor: Editor, theme: Theme): Color {
return theme.entities.cue
}
override fun getTextForSemitone(semitone: Int): String {
return playalongInput.displayText
}
override fun copy(remix: Remix): PlayalongEntity {
return PlayalongEntity(remix, datamodel).also {
it.updateBounds {
it.bounds.set([email protected])
}
}
}
override fun onStart() {
}
override fun whilePlaying() {
}
override fun onEnd() {
}
fun getInputAction(): InputAction {
return InputAction(bounds.x, bounds.width, playalongInput, playalongMethod)
}
} | core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/special/PlayalongEntity.kt | 4176117890 |
package com.hazelcast.idea.plugins.tools
import javax.swing.Icon
import com.intellij.openapi.util.IconLoader
interface IconConstants {
companion object {
val HZ_ACTION = IconLoader.getIcon("/icons/hazelcast.png")
}
}
| src/main/kotlin/com/hazelcast/idea/plugins/tools/IconConstants.kt | 3217637108 |
package com.nononsenseapps.feeder.model
import androidx.room.ColumnInfo
import androidx.room.Ignore
import com.nononsenseapps.feeder.db.COL_BOOKMARKED
import com.nononsenseapps.feeder.db.COL_PINNED
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.util.sloppyLinkToStrictURLNoThrows
import java.net.URI
import java.net.URL
import org.threeten.bp.ZonedDateTime
const val previewColumns = """
feed_items.id AS id, guid, plain_title, plain_snippet, feed_items.image_url, enclosure_link,
author, pub_date, link, unread, feeds.tag AS tag, feeds.id AS feed_id, feeds.title AS feed_title,
feeds.custom_title as feed_customtitle, feeds.url AS feed_url,
feeds.open_articles_with AS feed_open_articles_with, pinned, bookmarked,
feeds.image_url as feed_image_url
"""
data class PreviewItem @Ignore constructor(
var id: Long = ID_UNSET,
var guid: String = "",
@ColumnInfo(name = "plain_title") var plainTitle: String = "",
@ColumnInfo(name = "plain_snippet") var plainSnippet: String = "",
@ColumnInfo(name = "image_url") var imageUrl: String? = null,
@ColumnInfo(name = "enclosure_link") var enclosureLink: String? = null,
var author: String? = null,
@ColumnInfo(name = "pub_date") var pubDate: ZonedDateTime? = null,
var link: String? = null,
var tag: String = "",
var unread: Boolean = true,
@ColumnInfo(name = "feed_id") var feedId: Long? = null,
@ColumnInfo(name = "feed_title") var feedTitle: String = "",
@ColumnInfo(name = "feed_customtitle") var feedCustomTitle: String = "",
@ColumnInfo(name = "feed_url") var feedUrl: URL = sloppyLinkToStrictURLNoThrows(""),
@ColumnInfo(name = "feed_open_articles_with") var feedOpenArticlesWith: String = "",
@ColumnInfo(name = COL_PINNED) var pinned: Boolean = false,
@ColumnInfo(name = COL_BOOKMARKED) var bookmarked: Boolean = false,
@ColumnInfo(name = "feed_image_url") var feedImageUrl: URL? = null,
) {
constructor() : this(id = ID_UNSET)
val feedDisplayTitle: String
get() = if (feedCustomTitle.isBlank()) feedTitle else feedCustomTitle
val enclosureFilename: String?
get() {
if (enclosureLink != null) {
var fname: String? = null
try {
fname = URI(enclosureLink).path.split("/").last()
} catch (e: Exception) {
}
if (fname == null || fname.isEmpty()) {
return null
} else {
return fname
}
}
return null
}
val pubDateString: String?
get() = pubDate?.toString()
val domain: String?
get() {
val l: String? = enclosureLink ?: link
if (l != null) {
try {
return URL(l).host.replace("www.", "")
} catch (e: Throwable) {
}
}
return null
}
}
| app/src/main/java/com/nononsenseapps/feeder/model/PreviewItem.kt | 3450872345 |
package org.stepik.android.cache.personal_deadlines.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepik.android.cache.personal_deadlines.structure.DbStructureDeadlinesBanner
import javax.inject.Inject
class DeadlinesBannerDaoImpl
@Inject
constructor(
databaseOperations: DatabaseOperations
) : DaoBase<Long>(databaseOperations), DeadlinesBannerDao {
override fun getDbName(): String =
DbStructureDeadlinesBanner.DEADLINES_BANNER
override fun getDefaultPrimaryColumn(): String =
DbStructureDeadlinesBanner.Columns.COURSE_ID
override fun getDefaultPrimaryValue(persistentObject: Long): String =
persistentObject.toString()
override fun getContentValues(persistentObject: Long): ContentValues =
ContentValues().apply {
put(DbStructureDeadlinesBanner.Columns.COURSE_ID, persistentObject)
}
override fun parsePersistentObject(cursor: Cursor): Long =
cursor.getLong(cursor.getColumnIndex(DbStructureDeadlinesBanner.Columns.COURSE_ID))
} | app/src/main/java/org/stepik/android/cache/personal_deadlines/dao/DeadlinesBannerDaoImpl.kt | 172553014 |
package gdl.dreamteam.skynet.Models
/**
* Created by christopher on 28/08/17.
*/
open class AbstractDeviceData {
var status: Boolean = false
} | SkyNet/app/src/main/java/gdl/dreamteam/skynet/Models/AbstractDeviceData.kt | 762874796 |
package test.kotlin.integration
import io.envoyproxy.envoymobile.EngineBuilder
import io.envoyproxy.envoymobile.engine.JniLibrary
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class EnvoyEngineSimpleIntegrationTest {
init {
JniLibrary.loadTestLibrary()
}
@Test
fun `ensure engine build and termination succeeds with no errors`() {
val engine = EngineBuilder().build()
Thread.sleep(5000)
engine.terminate()
assertThat(true).isTrue()
}
}
| test/kotlin/integration/EnvoyEngineSimpleIntegrationTest.kt | 4142377176 |
package com.tazachoncha.wildcards
import java.util.ArrayList
object Main {
@JvmStatic fun main(args: Array<String>) {
// write your code here
val base = ClaseBase("BASE")
val hijo1 = ClaseHijo1("HIJO 1")
val hijo2 = ClaseHijo2("HIJO 2")
val elementos = ArrayList<Any>()
elementos.add(hijo1)
elementos.add(base)
elementos.add(hijo2)
// manda a imprimir
imprimeTodo(elementos)
}
fun imprime(base: ClaseBase) {
println(base.toString())
}
fun <T : ClaseBase> imprimeTodo(elementos: List<T>) {
//imprime
for (elemento in elementos) {
imprime(elemento)
}
}
}
| programas/wildcards/src/com/tazachoncha/wildcards/Main.kt | 3239714822 |
// 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 training.dsl.impl
import com.intellij.openapi.project.Project
import training.dsl.LearningBalloonConfig
import training.dsl.LessonContext
import training.dsl.TaskContext
import training.learn.lesson.LessonManager
class OpenPassedContext(private val project: Project) : LessonContext() {
override fun task(taskContent: TaskContext.() -> Unit) {
OpenPassedTaskContext(project).apply(taskContent)
}
}
private class OpenPassedTaskContext(override val project: Project) : TaskContext() {
override fun text(text: String, useBalloon: LearningBalloonConfig?) {
LessonManager.instance.addMessage(text)
LessonManager.instance.passExercise()
}
}
| plugins/ide-features-trainer/src/training/dsl/impl/OpenPassedContext.kt | 1769916997 |
/*
* 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 okio
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.junit.rules.Timeout as JUnitTimeout
class TimeoutTest {
@JvmField @Rule val timeout = JUnitTimeout(5, TimeUnit.SECONDS)
private val executorService = Executors.newScheduledThreadPool(1)
@After @Throws(Exception::class)
fun tearDown() {
executorService.shutdown()
}
@Test fun intersectWithReturnsAValue() {
val timeoutA = Timeout()
val timeoutB = Timeout()
val s = timeoutA.intersectWith(timeoutB) { "hello" }
assertEquals("hello", s)
}
@Test fun intersectWithPrefersSmallerTimeout() {
val timeoutA = Timeout()
timeoutA.timeout(smallerTimeoutNanos, TimeUnit.NANOSECONDS)
val timeoutB = Timeout()
timeoutB.timeout(biggerTimeoutNanos, TimeUnit.NANOSECONDS)
timeoutA.intersectWith(timeoutB) {
assertEquals(smallerTimeoutNanos, timeoutA.timeoutNanos())
assertEquals(biggerTimeoutNanos, timeoutB.timeoutNanos())
}
timeoutB.intersectWith(timeoutA) {
assertEquals(smallerTimeoutNanos, timeoutA.timeoutNanos())
assertEquals(smallerTimeoutNanos, timeoutB.timeoutNanos())
}
assertEquals(smallerTimeoutNanos, timeoutA.timeoutNanos())
assertEquals(biggerTimeoutNanos, timeoutB.timeoutNanos())
}
@Test fun intersectWithPrefersNonZeroTimeout() {
val timeoutA = Timeout()
val timeoutB = Timeout()
timeoutB.timeout(biggerTimeoutNanos, TimeUnit.NANOSECONDS)
timeoutA.intersectWith(timeoutB) {
assertEquals(biggerTimeoutNanos, timeoutA.timeoutNanos())
assertEquals(biggerTimeoutNanos, timeoutB.timeoutNanos())
}
timeoutB.intersectWith(timeoutA) {
assertEquals(0L, timeoutA.timeoutNanos())
assertEquals(biggerTimeoutNanos, timeoutB.timeoutNanos())
}
assertEquals(0L, timeoutA.timeoutNanos())
assertEquals(biggerTimeoutNanos, timeoutB.timeoutNanos())
}
@Test fun intersectWithPrefersSmallerDeadline() {
val timeoutA = Timeout()
timeoutA.deadlineNanoTime(smallerDeadlineNanos)
val timeoutB = Timeout()
timeoutB.deadlineNanoTime(biggerDeadlineNanos)
timeoutA.intersectWith(timeoutB) {
assertEquals(smallerDeadlineNanos, timeoutA.deadlineNanoTime())
assertEquals(biggerDeadlineNanos, timeoutB.deadlineNanoTime())
}
timeoutB.intersectWith(timeoutA) {
assertEquals(smallerDeadlineNanos, timeoutA.deadlineNanoTime())
assertEquals(smallerDeadlineNanos, timeoutB.deadlineNanoTime())
}
assertEquals(smallerDeadlineNanos, timeoutA.deadlineNanoTime())
assertEquals(biggerDeadlineNanos, timeoutB.deadlineNanoTime())
}
@Test fun intersectWithPrefersNonZeroDeadline() {
val timeoutA = Timeout()
val timeoutB = Timeout()
timeoutB.deadlineNanoTime(biggerDeadlineNanos)
timeoutA.intersectWith(timeoutB) {
assertEquals(biggerDeadlineNanos, timeoutA.deadlineNanoTime())
assertEquals(biggerDeadlineNanos, timeoutB.deadlineNanoTime())
}
timeoutB.intersectWith(timeoutA) {
assertFalse(timeoutA.hasDeadline())
assertEquals(biggerDeadlineNanos, timeoutB.deadlineNanoTime())
}
assertFalse(timeoutA.hasDeadline())
assertEquals(biggerDeadlineNanos, timeoutB.deadlineNanoTime())
}
companion object {
val smallerTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(500L)
val biggerTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(1500L)
val smallerDeadlineNanos = TimeUnit.MILLISECONDS.toNanos(500L)
val biggerDeadlineNanos = TimeUnit.MILLISECONDS.toNanos(1500L)
}
}
| okio/src/jvmTest/kotlin/okio/TimeoutTest.kt | 2044954222 |
package com.rightfromleftsw.weather.remote.model
import com.rightfromleftsw.weather.domain.model.Location
/**
* Representation for a [WeatherModel] fetched from the API
*/
class WeatherModel(val temperature: String, val location: Location, val time: Long) | remote/src/main/java/com/rightfromleftsw/weather/remote/model/WeatherModel.kt | 2457694533 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.accounts
import com.intellij.openapi.components.service
// Helper to hide account ID which is used to store account selection
object GHAccountSerializer {
fun serialize(account: GithubAccount): String = account.id
fun deserialize(string: String): GithubAccount? {
return service<GithubAccountManager>().accounts.find { it.id == string }
}
} | plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GHAccountSerializer.kt | 2376192501 |
// 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.codeInsight.hints
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
internal class ParameterHintsSettingsMigration : StartupActivity {
init {
if (ApplicationManager.getApplication().isUnitTestMode) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun runActivity(project: Project) {
val editorSettingsExternalizable = EditorSettingsExternalizable.getInstance()
if (!editorSettingsExternalizable.isShowParameterNameHints) {
editorSettingsExternalizable.isShowParameterNameHints = true
for (language in getBaseLanguagesWithProviders()) {
ParameterNameHintsSettings.getInstance().setIsEnabledForLanguage(false, language)
}
}
}
} | platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsSettingsMigration.kt | 2449882625 |
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.notifications.email
import slatekit.utils.templates.Templates
import slatekit.common.values.Vars
import slatekit.http.HttpRPC
import slatekit.notifications.common.TemplateSender
import slatekit.results.*
abstract class EmailService(
override val templates: Templates? = null,
override val client: HttpRPC = HttpRPC()
) : TemplateSender<EmailMessage> {
/**
* Sends the email message
* @param to : The destination email address
* @param subject : The subject of email
* @param body : The body of the email
* @param html : Whether or not the email is html formatted
* @return
*/
suspend fun send(to: String, subject: String, body: String, html: Boolean): Outcome<String> {
return send(EmailMessage(to, subject, body, html))
}
/**
* sends a message using the template and variables supplied
* @param template : The name of the template
* @param to : The destination email address
* @param subject : The subject of email
* @param html : Whether or not the email is html formatted
* @param variables : values to replace the variables in template
*/
suspend fun sendTemplate(template: String, to: String, subject: String, html: Boolean, variables: Vars): Outcome<String> {
return sendTemplate(template, variables) { EmailMessage(to, subject, it, html) }
}
}
| src/lib/kotlin/slatekit-notifications/src/main/kotlin/slatekit/notifications/email/EmailService.kt | 2493318014 |
// 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.vcs.log.history
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.VcsLogStructureFilter
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.graph.GraphCommit
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.StopWatch
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
internal class FileHistoryFilterer(logData: VcsLogData) : VcsLogFilterer {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val indexDataGetter = index.dataGetter!!
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache,
logData.commitDetailsGetter, index)
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters) ?: return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
LOG.assertTrue(!filePath.isDirectory)
val root = VcsLogUtil.getActualRoot(project, filePath)!!
return MyWorker(root, filePath, getHash(filters)).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val start = System.currentTimeMillis()
if (index.isIndexed(root) && dataPack.isFull) {
val visiblePack = filterWithIndex(dataPack, oldVisiblePack, sortType, filters,
commitCount == CommitCountStage.INITIAL)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
return@filter try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for computing history for $filePath with history provider")
checkNotEmpty(dataPack, visiblePack, false)
Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection): VisiblePack {
val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
val revisions = VcsCachingHistory.collect(vcs, filePath, revisionNumber)
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull) {
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val revisionEx = revision as VcsFileRevisionEx
pathsMap[getIndex(revision)] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
}
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
val commits = ArrayList<GraphCommit<Int>>(revisions.size)
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val index = getIndex(revision)
val revisionEx = revision as VcsFileRevisionEx
pathsMap[index] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
commits.add(GraphCommitImpl.createCommit(index, emptyList(), revision.getRevisionDate().time))
}
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = vcsLogFilterer.createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun getIndex(revision: VcsFileRevision): Int {
return storage.getCommitIndex(HashImpl.build(revision.revisionNumber.asString()), root)
}
private fun filterWithIndex(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(dataPack, filters, sortType, oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(data.buildPathsMap()))
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters, fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
val start = System.currentTimeMillis()
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull {
val parentHash = storage.getCommitId(it.parent)!!.hash
val childHash = storage.getCommitId(it.child)!!.hash
if (it.isAddition) handler.getRename(root, it.filePath, parentHash, childHash)
else handler.getRename(root, it.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
LOG.debug("Found ${renames.size} renames for ${fileHistory.unmatchedAdditionsDeletions.size} addition-deletions in " +
StopWatch.formatTime(System.currentTimeMillis() - start))
val result = MultiMap<UnorderedPair<Int>, Rename>()
renames.forEach { result.putValue(it.commits, it) }
return result
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = logger<FileHistoryFilterer>()
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) {
return map
}
if (map.isEmpty) {
return this
}
val result = MultiMap<K, V>()
result.putAllValues(this)
result.putAllValues(map)
return result
}
| platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt | 2724975632 |
package gr.tsagi.jekyllforandroid.app.data
import android.annotation.SuppressLint
import android.content.ContentUris
import android.net.Uri
import android.provider.BaseColumns
import android.util.Log
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
\* Created with IntelliJ IDEA.
\* User: jchanghong
\* Date: 8/8/14
\* Time: 19:47
\*/
object PostsContract {
private val LOG_TAG = PostsContract::class.java.simpleName
// The "Content authority" is a name for the entire content provider, similar to the
// relationship between a domain name and its website. A convenient string to use for the
// content authority is the package name for the app, which is guaranteed to be unique on the
// device.
val CONTENT_AUTHORITY = "gr.tsagi.jekyllforandroid"
// Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact
// the content provider.
val BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY)!!
// Possible paths (appended to base content URI for possible URI's)
// For instance, content://com.example.android.sunshine.app/weather/ is a valid path for
// looking at weather data. content://gr.tsagi.jekyllforandroid/givemeroot/ will fail,
// as the ContentProvider hasn't been given any information on what to do with "givemeroot".
// At least, let's hope not. Don't be that dev, reader. Don't be that dev.
val PATH_POSTS = "posts"
val PATH_TAGS = "tags"
val PATH_CATEGORIES = "categories"
// Format used for storing dates in the database. ALso used for converting those strings
// back into date objects for comparison/processing.
val DATE_FORMAT = "yyyyMMdd"
/**
* Converts Date class to a string representation, used for easy comparison and database lookup.
* @param date The input date
* *
* @return a DB-friendly representation of the date, using the format defined in DATE_FORMAT.
*/
fun getDbDateString(date: Date): String {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
@SuppressLint("SimpleDateFormat")
val sdf = SimpleDateFormat(DATE_FORMAT)
return sdf.format(date)
}
/**
* Converts a dateText to a long Unix time representation
* @param dateText the input date string
* *
* @return the Date object
*/
fun getDateFromDb(dateText: String): Date {
@SuppressLint("SimpleDateFormat")
val dbDateFormat = SimpleDateFormat(DATE_FORMAT)
try {
return dbDateFormat.parse(dateText)
} catch (e: ParseException) {
// e.printStackTrace();
return Date()
}
}
/* Inner class that defines the table contents of the location table */
class PostEntry : BaseColumns {
companion object {
val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_POSTS).build()
val CONTENT_TYPE =
"vnd.android.cursor.dir/$CONTENT_AUTHORITY/$PATH_POSTS"
// Table name
val TABLE_NAME = "posts"
val COLUMN_POST_ID = "id"
val COLUMN_TITLE = "title"
val COLUMN_DRAFT = "draft"
val COLUMN_DATETEXT = "date"
val COLUMN_CONTENT = "content"
fun buildPostUri(id: Long): Uri {
return ContentUris.withAppendedId(CONTENT_URI, id)
}
fun buildPublishedPosts(): Uri {
return CONTENT_URI.buildUpon().appendPath("published").build()
}
fun buildDraftPosts(): Uri {
return CONTENT_URI.buildUpon().appendPath("drafts").build()
}
fun buildPostFromId(status: String, postId: String): Uri {
Log.d(LOG_TAG, "postId: " + postId)
return CONTENT_URI.buildUpon().appendPath(status).appendPath(postId)
.build()
}
fun getStatusFromUri(uri: Uri): String {
return uri.pathSegments[1]
}
fun getIdFromUri(uri: Uri): String {
return uri.pathSegments[2]
}
}
}
// public static final class TagEntry implements BaseColumns {
//
// public static final Uri CONTENT_URI =
// BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build();
//
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_TAGS;
// public static final String CONTENT_ITEM_TYPE =
// "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_TAGS;
//
// // Table name
// public static final String TABLE_NAME = "tags";
//
// public static final String COLUMN_TAG = "tag";
// public static final String COLUMN_POST_ID = "post_id";
//
// public static Uri buildTagUri(long id) {
// return ContentUris.withAppendedId(CONTENT_URI, id);
// }
// }
// public static final class CategoryEntry implements BaseColumns {
//
// public static final Uri CONTENT_URI =
// BASE_CONTENT_URI.buildUpon().appendPath(PATH_CATEGORIES).build();
//
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/" + CONTENT_AUTHORITY + "/" + PATH_CATEGORIES;
// public static final String CONTENT_ITEM_TYPE =
// "vnd.android.cursor.item/" + CONTENT_AUTHORITY + "/" + PATH_CATEGORIES;
//
// // Table name
// public static final String TABLE_NAME = "categories";
//
// public static final String COLUMN_CATEGORY = "category";
// public static final String COLUMN_POST_ID = "post_id";
//
// public static Uri buildCategoryUri(long id) {
// return ContentUris.withAppendedId(CONTENT_URI, id);
// }
// }
}
| app/src/main/java/gr/tsagi/jekyllforandroid/app/data/PostsContract.kt | 3426526816 |
class A {
val p : Int = try{
1
} catch(e: Exception) {
throw RuntimeException()
}
}
fun box() : String {
if (A().p != 1) return "fail 1"
return "OK"
} | backend.native/tests/external/codegen/box/lazyCodegen/tryCatchExpression.kt | 2232515132 |
package com.trello.rxlifecycle.sample
import android.os.Bundle
import android.util.Log
import com.trello.rxlifecycle.android.ActivityEvent
import com.trello.rxlifecycle.components.support.RxAppCompatActivity
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import com.trello.rxlifecycle.kotlin.bindUntilEvent
import rx.Observable
import java.util.concurrent.TimeUnit
class KotlinActivity : RxAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate()")
setContentView(R.layout.activity_main)
// Specifically bind this until onPause()
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe { Log.i(TAG, "Unsubscribing subscription from onCreate()") }
.bindUntilEvent(this, ActivityEvent.PAUSE)
.subscribe { num -> Log.i(TAG, "Started in onCreate(), running until onPause(): " + num!!) }
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart()")
// Using automatic unsubscription, this should determine that the correct time to
// unsubscribe is onStop (the opposite of onStart).
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe { Log.i(TAG, "Unsubscribing subscription from onStart()") }
.bindToLifecycle(this)
.subscribe { num -> Log.i(TAG, "Started in onStart(), running until in onStop(): " + num!!) }
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume()")
Observable.interval(1, TimeUnit.SECONDS)
.doOnUnsubscribe { Log.i(TAG, "Unsubscribing subscription from onResume()") }
.bindUntilEvent(this, ActivityEvent.DESTROY)
.subscribe { num -> Log.i(TAG, "Started in onResume(), running until in onDestroy(): " + num!!) }
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause()")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop()")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy()")
}
companion object {
private val TAG = "RxLifecycleAndroid-Kotlin"
}
}
| rxlifecycle-sample/src/main/kotlin/com/trello/rxlifecycle/sample/KotlinActivity.kt | 962896214 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
var result = "fail 2"
object Foo {
@JvmStatic
private val a = "OK"
val b = { a }
val c = Runnable { result = a }
}
fun box(): String {
if (Foo.b() != "OK") return "fail 1"
Foo.c.run()
return result
}
| backend.native/tests/external/codegen/box/jvmStatic/propertyAccessorsObject.kt | 2558189067 |
// 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.core
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Cap
import android.graphics.Paint.Join
import android.graphics.Xfermode
import org.monksanctum.xand11.errors.ValueError
import org.monksanctum.xand11.fonts.FontManager
actual class GraphicsContext actual constructor(private val mId: Int) {
actual var drawable: Int = 0
actual var function: Byte = 0
actual var planeMask: Int = 0
actual var foreground = -0x1000000
actual var background = -0x1
actual var lineWidth: Int = 0 // Card16
actual var lineStyle: Byte = 0
actual var capStyle: Byte = 0
actual var joinStyle: Byte = 0
actual var fillStyle: Byte = 0
actual var fillRule: Byte = 0
actual var tile: Int = 0 // PIXMAP
actual var stipple: Int = 0 // PIXMAP
actual var tileStippleX: Int = 0 // Card16
actual var tileStippleY: Int = 0 // Card16
actual var font: Int = 0 // Font
actual var subwindowMode: Byte = 0
actual var graphicsExposures: Boolean = false
actual var clipX: Int = 0 // Card16
actual var clipY: Int = 0 // Card16
actual var clipMask: Int = 0 // PIXMAP
actual var dashOffset: Int = 0 // Card16
actual var dashes: Byte = 0
actual var arcMode: Byte = 0
var paint: Paint? = null
private set
private var p: Path? = null
fun applyToPaint(p: Paint): Paint {
p.color = foreground or -0x1000000
p.strokeWidth = lineWidth.toFloat()
when (function) {
FUNCTION_XOR -> {
}
else -> p.xfermode = null
}// TODO: Support this.
when (capStyle) {
CAP_STYLE_NOT_LAST, CAP_STYLE_BUTT -> p.strokeCap = Cap.BUTT
CAP_STYLE_ROUND -> p.strokeCap = Cap.ROUND
CAP_STYLE_PROJECTING -> p.strokeCap = Cap.SQUARE
}
when (joinStyle) {
JOIN_STYLE_MITER -> p.strokeJoin = Join.MITER
JOIN_STYLE_ROUND -> p.strokeJoin = Join.ROUND
JOIN_STYLE_BEVEL -> p.strokeJoin = Join.BEVEL
}
return p
}
@Throws(ValueError::class)
actual fun createPaint(fontManager: FontManager) {
val f = fontManager.getFont(font)
paint = applyToPaint(if (f != null) f.paint else Paint())
}
actual fun setClipPath(p: Path) {
this.p = p
}
actual fun init(c: Canvas) {
if (p != null) {
c.clipPath(p!!)
}
}
actual fun drawRect(canvas: Canvas, rect: Rect, stroke: Boolean) {
val p = Paint(paint)
p!!.style = if (stroke) Paint.Style.STROKE else Paint.Style.FILL
canvas.drawRect(rect, p)
}
actual fun drawText(canvas: Canvas, f: Font?, v: String, x: Int, y: Int, bounds: Rect) {
var paint = f?.paint?.let { applyToPaint(it) } ?: this.paint;
Font.getTextBounds(v, paint!!, x, y, bounds)
paint.color = foreground
if (DEBUG) Platform.logd("GraphicsContext", "Draw text $v $x $y")
canvas.drawText(v, x.toFloat(), y.toFloat(), paint)
}
actual fun drawPath(canvas: Canvas, p: Path, fill: Boolean) {
val paint = Paint(this.paint)
paint!!.style = if (fill) Paint.Style.FILL else Paint.Style.STROKE
canvas.drawPath(p, paint)
}
actual fun drawLine(canvas: Canvas, fx: Float, fy: Float, sx: Float, sy: Float) {
canvas.drawLine(fx, fy, sx, sy, paint!!)
}
actual fun drawBitmap(canvas: Canvas, bitmap: Bitmap, x: Float, y: Float) {
canvas.drawBitmap(bitmap, x, y, paint)
}
companion object {
val FUNCTION_CLEAR: Byte = 0
val FUNCTION_AND: Byte = 1
val FUNCTION_AND_REVERSE: Byte = 2
val FUNCTION_COPY: Byte = 3
val FUNCTION_AND_INVERTED: Byte = 4
val FUNCTION_NOOP: Byte = 5
val FUNCTION_XOR: Byte = 6
val FUNCTION_OR: Byte = 7
val FUNCTION_NOR: Byte = 8
val FUNCTION_EQUIV: Byte = 9
val FUNCTION_INVERT: Byte = 10
val FUNCTION_OR_REVERSE: Byte = 11
val FUNCTION_COPY_INVERTED: Byte = 12
val FUNCTION_OR_INVERTED: Byte = 13
val FUNCTION_NAND: Byte = 14
val FUNCTION_SET: Byte = 15
val STYLE_SOLID: Byte = 0
val STYLE_ON_OFF_DASH: Byte = 1
val STYLE_DOUBLE_DASH: Byte = 2
val CAP_STYLE_NOT_LAST: Byte = 0
val CAP_STYLE_BUTT: Byte = 1
val CAP_STYLE_ROUND: Byte = 2
val CAP_STYLE_PROJECTING: Byte = 3
val JOIN_STYLE_MITER: Byte = 0
val JOIN_STYLE_ROUND: Byte = 1
val JOIN_STYLE_BEVEL: Byte = 2
val FILL_STYLE_SOLID: Byte = 0
val FILL_STYLE_TILED: Byte = 1
val FILL_STYLE_STIPPLED: Byte = 2
val FILL_STYLE_OPAQUE_STIPPLED: Byte = 3
val FILL_RULE_EVEN_ODD: Byte = 0
val FILL_RULE_WINDING: Byte = 1
val SUBWINDOW_MODE_CLIP_BY_CHILDREN: Byte = 0
val SUBWINDOW_MODE_INCLUDE_INFERIORS: Byte = 1
val ARC_MODE_CHORD: Byte = 0
val ARC_MODE_PIE_SLICE: Byte = 1
}
}
actual fun Canvas.drawBitmap(context: GraphicsContext?, bitmap: Bitmap, src: Rect, bounds: Rect) {
drawBitmap(bitmap, src, bounds, context?.paint ?: Paint())
}
actual fun Canvas.drawBitmap(context: GraphicsContext?, bitmap: Bitmap, x: Float, y: Float) {
drawBitmap(bitmap, x, y, context?.paint ?: Paint())
}
| core/src/android/java/org/monksanctum/xand11/core/GraphicsContext.kt | 348279790 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.hilt.integration.viewmodelapp
import android.os.Build
import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
// TODO: Find out why random ClassNotFoundException is thrown in APIs lower than 21.
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
class BaseActivityInjectionTest {
@get:Rule
val rule = HiltAndroidRule(this)
@Test
fun verifyInjection() {
ActivityScenario.launch(TestActivity::class.java).use {
it.onActivity { activity ->
assertThat(activity.myAndroidViewModel).isNotNull()
assertThat(activity.myViewModel).isNotNull()
assertThat(activity.myInjectedViewModel).isNotNull()
}
}
}
@AndroidEntryPoint
class TestActivity : BaseActivity()
abstract class BaseActivity : FragmentActivity() {
val myAndroidViewModel by viewModels<MyAndroidViewModel>()
val myViewModel by viewModels<MyViewModel>()
val myInjectedViewModel by viewModels<MyInjectedViewModel>()
}
} | hilt/integration-tests/viewmodelapp/src/androidTest/java/androidx/hilt/integration/viewmodelapp/BaseActivityInjectionTest.kt | 4094210085 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("CreateFieldFromUsage")
package com.intellij.lang.java.request
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFieldFromUsageFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.java.actions.toJavaClassOrNull
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.EP_NAME
import com.intellij.lang.jvm.actions.groupActionsByType
import com.intellij.psi.*
import com.intellij.psi.impl.PsiImplUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.resolveClassInClassTypeOnly
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.parentOfType
fun generateActions(ref: PsiReferenceExpression): List<IntentionAction> {
if (!checkReference(ref)) return emptyList()
val fieldRequests = CreateFieldRequests(ref).collectRequests()
val extensions = EP_NAME.extensions
return fieldRequests.flatMap { (clazz, request) ->
extensions.flatMap { ext ->
ext.createAddFieldActions(clazz, request)
}
}.groupActionsByType(JavaLanguage.INSTANCE)
}
private fun checkReference(ref: PsiReferenceExpression): Boolean {
if (ref.referenceName == null) return false
if (ref.parent is PsiMethodCallExpression) return false
return true
}
private class CreateFieldRequests(val myRef: PsiReferenceExpression) {
private val requests = LinkedHashMap<JvmClass, CreateFieldRequest>()
fun collectRequests(): Map<JvmClass, CreateFieldRequest> {
doCollectRequests()
return requests
}
private fun addRequest(target: JvmClass, request: CreateFieldRequest) {
if (target is PsiElement) {
PsiUtilCore.ensureValid(target)
}
requests[target] = request
}
private fun doCollectRequests() {
val qualifier = myRef.qualifierExpression
if (qualifier != null) {
val instanceClass = resolveClassInClassTypeOnly(qualifier.type)
if (instanceClass != null) {
processHierarchy(instanceClass)
}
else {
val staticClass = (qualifier as? PsiJavaCodeReferenceElement)?.resolve() as? PsiClass
if (staticClass != null) {
processClass(staticClass, true)
}
}
}
else {
val baseClass = resolveClassInClassTypeOnly(PsiImplUtil.getSwitchLabel(myRef)?.enclosingSwitchStatement?.expression?.type)
if (baseClass != null) {
processHierarchy(baseClass)
}
else {
processOuterAndImported()
}
}
}
private fun processHierarchy(baseClass: PsiClass) {
for (clazz in hierarchy(baseClass)) {
processClass(clazz, false)
}
}
private fun processOuterAndImported() {
val inStaticContext = myRef.isInStaticContext()
for (outerClass in collectOuterClasses(myRef)) {
processClass(outerClass, inStaticContext)
}
for (imported in collectOnDemandImported(myRef)) {
processClass(imported, true)
}
}
private fun processClass(target: JvmClass, staticContext: Boolean) {
if (!staticContext && target.classKind in STATIC_ONLY) return
val modifiers = mutableSetOf<JvmModifier>()
if (staticContext) {
modifiers += JvmModifier.STATIC
}
if (shouldCreateFinalField(myRef, target)) {
modifiers += JvmModifier.FINAL
}
val ownerClass = myRef.parentOfType<PsiClass>()
val visibility = computeVisibility(myRef.project, ownerClass, target)
if (visibility != null) {
modifiers += visibility
}
val request = CreateFieldFromJavaUsageRequest(
modifiers = modifiers,
reference = myRef,
useAnchor = ownerClass != null && PsiTreeUtil.isAncestor(target.toJavaClassOrNull(), ownerClass, false),
isConstant = false
)
addRequest(target, request)
}
}
private val STATIC_ONLY = arrayOf(JvmClassKind.INTERFACE, JvmClassKind.ANNOTATION)
/**
* Given unresolved unqualified reference,
* this reference could be resolved into static member if some class which has it's members imported.
*
* @return list of classes from static on demand imports.
*/
private fun collectOnDemandImported(place: PsiElement): List<JvmClass> {
val containingFile = place.containingFile as? PsiJavaFile ?: return emptyList()
val importList = containingFile.importList ?: return emptyList()
val onDemandImports = importList.importStaticStatements.filter { it.isOnDemand }
if (onDemandImports.isEmpty()) return emptyList()
return onDemandImports.mapNotNull { it.resolveTargetClass() }
}
private fun shouldCreateFinalField(ref: PsiReferenceExpression, targetClass: JvmClass): Boolean {
val javaClass = targetClass.toJavaClassOrNull() ?: return false
return CreateFieldFromUsageFix.shouldCreateFinalMember(ref, javaClass)
}
| java/java-impl/src/com/intellij/lang/java/request/createFieldFromUsage.kt | 1057561296 |
// "Surround with null check" "true"
fun foo(exec: (() -> Unit)?) {
<caret>exec()
} | plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/invokeFuncUnsafe.kt | 3015947053 |
// 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.quickfix
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class SpecifySuperTypeFix(
superExpression: KtSuperExpression,
private val superTypes: List<String>
) : KotlinQuickFixAction<KtSuperExpression>(superExpression) {
override fun getText() = KotlinIdeaCompletionBundle.message("intention.name.specify.supertype")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val superExpression = element ?: return
CommandProcessor.getInstance().runUndoTransparentAction {
if (superTypes.size == 1) {
superExpression.specifySuperType(superTypes.first())
} else {
JBPopupFactory
.getInstance()
.createListPopup(createListPopupStep(superExpression, superTypes))
.showInBestPositionFor(editor)
}
}
}
private fun KtSuperExpression.specifySuperType(superType: String) {
project.executeWriteCommand(KotlinIdeaCompletionBundle.message("intention.name.specify.supertype")) {
val label = this.labelQualifier?.text ?: ""
replace(KtPsiFactory(this).createExpression("super<$superType>$label"))
}
}
private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<String>): ListPopupStep<*> {
return object : BaseListPopupStep<String>(KotlinIdeaCompletionBundle.message("popup.title.choose.supertype"), superTypes) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
superExpression.specifySuperType(selectedValue)
}
return PopupStep.FINAL_CHOICE
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtSuperExpression>? {
val superExpression = diagnostic.psiElement as? KtSuperExpression ?: return null
val qualifiedExpression = superExpression.getQualifiedExpressionForReceiver() ?: return null
val selectorExpression = qualifiedExpression.selectorExpression ?: return null
val containingClassOrObject = superExpression.getStrictParentOfType<KtClassOrObject>() ?: return null
val superTypeListEntries = containingClassOrObject.superTypeListEntries
if (superTypeListEntries.isEmpty()) return null
val context = superExpression.analyze(BodyResolveMode.PARTIAL)
val superTypes = superTypeListEntries.mapNotNull {
val typeReference = it.typeReference ?: return@mapNotNull null
val typeElement = it.typeReference?.typeElement ?: return@mapNotNull null
val kotlinType = context[BindingContext.TYPE, typeReference] ?: return@mapNotNull null
typeElement to kotlinType
}
if (superTypes.size != superTypeListEntries.size) return null
val psiFactory = KtPsiFactory(superExpression)
val superTypesForSuperExpression = superTypes.mapNotNull { (typeElement, kotlinType) ->
if (superTypes.any { it.second != kotlinType && it.second.isSubtypeOf(kotlinType) }) return@mapNotNull null
val fqName = kotlinType.fqName ?: return@mapNotNull null
val fqNameAsString = fqName.asString()
val name = if (typeElement.text.startsWith(fqNameAsString)) fqNameAsString else fqName.shortName().asString()
val newQualifiedExpression = psiFactory.createExpressionByPattern("super<$name>.$0", selectorExpression, reformat = false)
val newContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context)
if (newQualifiedExpression.getResolvedCall(newContext)?.resultingDescriptor == null) return@mapNotNull null
if (newContext.diagnostics.noSuppression().forElement(newQualifiedExpression).isNotEmpty()) return@mapNotNull null
name
}
if (superTypesForSuperExpression.isEmpty()) return null
return SpecifySuperTypeFix(superExpression, superTypesForSuperExpression)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifySuperTypeFix.kt | 4141577084 |
package jettesting
class ClassFromJet {
} | plugins/kotlin/completion/tests/testData/handlers/injava/ClassAutoImport.kt | 3109958635 |
@file:Suppress("unused")
class MyLanguage : com.intellij.lang.Language {
companion object {
const val PREFIX = "My"
const val ID = "LanguageID"
const val ANONYMOUS_ID = "AnonymousLanguageID"
val ANONYMOUS_LANGUAGE: com.intellij.lang.Language = object : MySubLanguage(PREFIX + ANONYMOUS_ID, "MyDisplayName") {}
}
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor() : super(PREFIX + ID)
private open class MySubLanguage(id: String?, private val myName: String) : com.intellij.lang.Language(id!!) {
override fun getDisplayName(): String = myName
}
abstract class AbstractLanguage protected constructor() : com.intellij.lang.Language("AbstractLanguageIDMustNotBeVisible")
} | plugins/devkit/devkit-kotlin-tests/testData/codeInsight/MyLanguage.kt | 3095177713 |
// 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.codeMetaInfo.renderConfigurations
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.checkers.diagnostics.factories.DebugInfoDiagnosticFactory1
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.rendering.*
import org.jetbrains.kotlin.idea.codeMetaInfo.models.DiagnosticCodeMetaInfo
import org.jetbrains.kotlin.idea.codeMetaInfo.models.HighlightingCodeMetaInfo
import org.jetbrains.kotlin.idea.codeMetaInfo.models.CodeMetaInfo
import org.jetbrains.kotlin.idea.codeMetaInfo.models.LineMarkerCodeMetaInfo
abstract class AbstractCodeMetaInfoRenderConfiguration(var renderParams: Boolean = true) {
private val clickOrPressRegex = "(Click or press|Press).*(to navigate)".toRegex() // We have different hotkeys on different platforms
open fun asString(codeMetaInfo: CodeMetaInfo) = codeMetaInfo.tag + getPlatformsString(codeMetaInfo)
open fun getAdditionalParams(codeMetaInfo: CodeMetaInfo) = ""
protected fun sanitizeLineMarkerTooltip(originalText: String?): String {
if (originalText == null) return "null"
val noHtmlTags = StringUtil.removeHtmlTags(originalText)
.replace(" ", "")
.replace(clickOrPressRegex, "$1 ... $2")
.trim()
return sanitizeLineBreaks(noHtmlTags)
}
protected fun sanitizeLineBreaks(originalText: String): String {
var sanitizedText = originalText
sanitizedText = StringUtil.replace(sanitizedText, "\r\n", " ")
sanitizedText = StringUtil.replace(sanitizedText, "\n", " ")
sanitizedText = StringUtil.replace(sanitizedText, "\r", " ")
return sanitizedText
}
protected fun getPlatformsString(codeMetaInfo: CodeMetaInfo): String {
if (codeMetaInfo.attributes.isEmpty()) return ""
return "{${codeMetaInfo.attributes.joinToString(";")}}"
}
}
open class DiagnosticCodeMetaInfoConfiguration(
val withNewInference: Boolean = true,
val renderSeverity: Boolean = false
) : AbstractCodeMetaInfoRenderConfiguration() {
private val crossPlatformLineBreak = """\r?\n""".toRegex()
override fun asString(codeMetaInfo: CodeMetaInfo): String {
if (codeMetaInfo !is DiagnosticCodeMetaInfo) return ""
return (getTag(codeMetaInfo)
+ getPlatformsString(codeMetaInfo)
+ getParamsString(codeMetaInfo))
.replace(crossPlatformLineBreak, "")
}
private fun getParamsString(codeMetaInfo: DiagnosticCodeMetaInfo): String {
if (!renderParams) return ""
val params = mutableListOf<String>()
@Suppress("UNCHECKED_CAST")
val renderer = when (codeMetaInfo.diagnostic.factory) {
is DebugInfoDiagnosticFactory1 -> DiagnosticWithParameters1Renderer(
"{0}",
Renderers.TO_STRING
) as DiagnosticRenderer<Diagnostic>
else -> DefaultErrorMessages.getRendererForDiagnostic(codeMetaInfo.diagnostic)
}
if (renderer is AbstractDiagnosticWithParametersRenderer) {
val renderParameters = renderer.renderParameters(codeMetaInfo.diagnostic)
params.addAll(ContainerUtil.map(renderParameters) { it.toString() })
}
if (renderSeverity)
params.add("severity='${codeMetaInfo.diagnostic.severity}'")
params.add(getAdditionalParams(codeMetaInfo))
return "(\"${params.filter { it.isNotEmpty() }.joinToString("; ")}\")"
}
fun getTag(codeMetaInfo: DiagnosticCodeMetaInfo): String {
return codeMetaInfo.diagnostic.factory.name!!
}
}
open class LineMarkerConfiguration(var renderDescription: Boolean = true) : AbstractCodeMetaInfoRenderConfiguration() {
override fun asString(codeMetaInfo: CodeMetaInfo): String {
if (codeMetaInfo !is LineMarkerCodeMetaInfo) return ""
return getTag() + getPlatformsString(codeMetaInfo) + getParamsString(codeMetaInfo)
}
fun getTag() = "LINE_MARKER"
private fun getParamsString(lineMarkerCodeMetaInfo: LineMarkerCodeMetaInfo): String {
if (!renderParams) return ""
val params = mutableListOf<String>()
if (renderDescription) {
lineMarkerCodeMetaInfo.lineMarker.lineMarkerTooltip?.apply {
params.add("descr='${sanitizeLineMarkerTooltip(this)}'")
}
}
params.add(getAdditionalParams(lineMarkerCodeMetaInfo))
val paramsString = params.filter { it.isNotEmpty() }.joinToString("; ")
return if (paramsString.isEmpty()) "" else "(\"$paramsString\")"
}
}
open class HighlightingConfiguration(
val renderDescription: Boolean = true,
val renderTextAttributesKey: Boolean = true,
val renderSeverity: Boolean = true,
val severityLevel: HighlightSeverity = HighlightSeverity.INFORMATION,
val checkNoError: Boolean = false
) : AbstractCodeMetaInfoRenderConfiguration() {
override fun asString(codeMetaInfo: CodeMetaInfo): String {
if (codeMetaInfo !is HighlightingCodeMetaInfo) return ""
return getTag() + getPlatformsString(codeMetaInfo) + getParamsString(codeMetaInfo)
}
fun getTag() = "HIGHLIGHTING"
private fun getParamsString(highlightingCodeMetaInfo: HighlightingCodeMetaInfo): String {
if (!renderParams) return ""
val params = mutableListOf<String>()
if (renderSeverity)
params.add("severity='${highlightingCodeMetaInfo.highlightingInfo.severity}'")
if (renderDescription)
params.add("descr='${sanitizeLineBreaks(highlightingCodeMetaInfo.highlightingInfo.description)}'")
if (renderTextAttributesKey)
highlightingCodeMetaInfo.highlightingInfo.forcedTextAttributesKey?.apply {
params.add("textAttributesKey='${this}'")
}
params.add(getAdditionalParams(highlightingCodeMetaInfo))
val paramsString = params.filter { it.isNotEmpty() }.joinToString("; ")
return if (paramsString.isEmpty()) "" else "(\"$paramsString\")"
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeMetaInfo/renderConfigurations/AbstractCodeMetaInfoRenderConfiguration.kt | 774217106 |
// "Suppress 'REDUNDANT_NULLABLE' for parameter p" "true"
fun foo(p: String?<caret>?) = null | plugins/kotlin/idea/tests/testData/quickfix/suppress/declarationKinds/param.kt | 719787072 |
// SET_TRUE: USE_TAB_CHARACTER
// SET_INT: TAB_SIZE=2
// SET_INT: INDENT_SIZE=2
val a = """blah blah
|<caret>
""".trimMargin().replace("\r", "")
// IGNORE_FORMATTER | plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs2/EnterInMethodCallMargin.after.kt | 2156778600 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.esotericsoftware.kryo.DefaultSerializer
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.Serializer
import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.io.Output
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.project.isDirectoryBased
import com.intellij.project.stateStore
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.atomic.AtomicInteger
/**
* Represents a file/directory where IntelliJ project is stored.
*/
sealed class JpsProjectConfigLocation {
val baseDirectoryUrlString: String
get() = baseDirectoryUrl.url
abstract val baseDirectoryUrl: VirtualFileUrl
data class DirectoryBased(val projectDir: VirtualFileUrl, val ideaFolder: VirtualFileUrl) : JpsProjectConfigLocation() {
override val baseDirectoryUrl: VirtualFileUrl
get() = projectDir
}
data class FileBased(val iprFile: VirtualFileUrl, val iprFileParent: VirtualFileUrl) : JpsProjectConfigLocation() {
override val baseDirectoryUrl: VirtualFileUrl
get() = iprFileParent
}
}
/**
* Represents an xml file containing configuration of IntelliJ IDEA project in JPS format (*.ipr file or *.xml file under .idea directory)
*/
sealed class JpsFileEntitySource : EntitySource {
abstract val projectLocation: JpsProjectConfigLocation
/**
* Represents a specific xml file containing configuration of some entities of IntelliJ IDEA project.
*/
data class ExactFile(val file: VirtualFileUrl, override val projectLocation: JpsProjectConfigLocation) : JpsFileEntitySource() {
override val virtualFileUrl: VirtualFileUrl
get() = file
}
/**
* Represents an xml file located in the specified [directory] which contains configuration of some entities of IntelliJ IDEA project.
* The file name is automatically derived from the entity name.
*/
@DefaultSerializer(FileInDirectorySerializer::class)
data class FileInDirectory(val directory: VirtualFileUrl,
override val projectLocation: JpsProjectConfigLocation) : JpsFileEntitySource() {
/**
* Automatically generated value which is used to distinguish different files in [directory]. The actual name is stored in serialization
* structures and may change if name of the corresponding entity has changed.
*/
val fileNameId: Int = nextId.getAndIncrement()
companion object {
private val nextId = AtomicInteger()
/**
* This method is temporary added for tests only
*/
@ApiStatus.Internal
@TestOnly
fun resetId() {
nextId.set(0)
}
}
override val virtualFileUrl: VirtualFileUrl
get() = directory
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is FileInDirectory && directory == other.directory && projectLocation == other.projectLocation && fileNameId == other.fileNameId
}
override fun hashCode(): Int {
return directory.hashCode() * 31 * 31 + projectLocation.hashCode() * 31 + fileNameId
}
override fun toString(): String {
return "FileInDirectory(directory=$directory, fileNameId=$fileNameId, projectLocation=$projectLocation)"
}
}
}
/**
* Represents entities which configuration is loaded from an JPS format configuration file (e.g. *.iml, stored in [originalSource]) and some additional configuration
* files (e.g. '.classpath' and *.eml files for Eclipse projects).
*/
interface JpsFileDependentEntitySource {
val originalSource: JpsFileEntitySource
}
/**
* Represents entities imported from external project system.
*/
data class ExternalEntitySource(val displayName: String, val id: String) : EntitySource
/**
* Represents entities imported from external project system and stored in JPS format. They may be stored either in a regular project
* configuration [internalFile] if [storedExternally] is `false` or in an external file under IDE caches directory if [storedExternally] is `true`.
*/
data class JpsImportedEntitySource(val internalFile: JpsFileEntitySource,
val externalSystemId: String,
val storedExternally: Boolean) : EntitySource, JpsFileDependentEntitySource {
override val originalSource: JpsFileEntitySource
get() = internalFile
override val virtualFileUrl: VirtualFileUrl?
get() = internalFile.virtualFileUrl
}
fun JpsImportedEntitySource.toExternalSource(): ProjectModelExternalSource = ExternalProjectSystemRegistry.getInstance().getSourceById(externalSystemId)
/**
* Represents entities which are added to the model automatically and shouldn't be persisted
*/
object NonPersistentEntitySource : EntitySource
/**
* Represents entities which are imported from some external model, but still have some *.iml file associated with them. That iml file
* will be used to save configuration of facets added to the module. This is a temporary solution, later we should invent a way to store
* such settings in their own files.
*/
interface CustomModuleEntitySource : EntitySource {
val internalSource: JpsFileEntitySource
}
/**
* Returns `null` for the default project
*/
fun getJpsProjectConfigLocation(project: Project): JpsProjectConfigLocation? {
return if (project.isDirectoryBased) {
project.basePath?.let {
val virtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
val ideaFolder = project.stateStore.directoryStorePath!!.toVirtualFileUrl(virtualFileUrlManager)
JpsProjectConfigLocation.DirectoryBased(virtualFileUrlManager.fromPath(it), ideaFolder)
}
}
else {
project.projectFilePath?.let {
val virtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
val iprFile = virtualFileUrlManager.fromPath(it)
JpsProjectConfigLocation.FileBased(iprFile, virtualFileUrlManager.getParentVirtualUrl(iprFile)!!)
}
}
}
internal class FileInDirectorySerializer : Serializer<JpsFileEntitySource.FileInDirectory>(false, true) {
override fun write(kryo: Kryo, output: Output, o: JpsFileEntitySource.FileInDirectory) {
kryo.writeClassAndObject(output, o.directory)
kryo.writeClassAndObject(output, o.projectLocation)
}
override fun read(kryo: Kryo, input: Input, type: Class<JpsFileEntitySource.FileInDirectory>): JpsFileEntitySource.FileInDirectory {
val fileUrl = kryo.readClassAndObject(input) as VirtualFileUrl
val location = kryo.readClassAndObject(input) as JpsProjectConfigLocation
return JpsFileEntitySource.FileInDirectory(fileUrl, location)
}
} | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/jpsEntitySources.kt | 1784444826 |
/*
* 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
*
* 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 androidx.compose.samples.crane.calendar
import androidx.compose.foundation.layout.Row
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.clearAndSetSemantics
@Composable
internal fun MonthHeader(modifier: Modifier = Modifier, month: String, year: String) {
Row(modifier = modifier.clearAndSetSemantics { }) {
Text(
modifier = Modifier.weight(1f),
text = month,
style = MaterialTheme.typography.h6
)
Text(
modifier = Modifier.align(Alignment.CenterVertically),
text = year,
style = MaterialTheme.typography.caption
)
}
}
| Crane/app/src/main/java/androidx/compose/samples/crane/calendar/Month.kt | 131391370 |
package com.habitrpg.android.habitica.ui.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.forEachIndexed
import androidx.core.widget.NestedScrollView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.TagRepository
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.OnChangeTextWatcher
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.helpers.TaskAlarmManager
import com.habitrpg.android.habitica.models.Tag
import com.habitrpg.android.habitica.models.tasks.HabitResetOption
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.tasks.form.*
import io.reactivex.functions.Consumer
import io.realm.RealmList
import java.util.*
import javax.inject.Inject
class TaskFormActivity : BaseActivity() {
private var userScrolled: Boolean = false
private var isSaving: Boolean = false
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var taskRepository: TaskRepository
@Inject
lateinit var tagRepository: TagRepository
@Inject
lateinit var taskAlarmManager: TaskAlarmManager
private val toolbar: Toolbar by bindView(R.id.toolbar)
private val scrollView: NestedScrollView by bindView(R.id.scroll_view)
private val upperTextWrapper: LinearLayout by bindView(R.id.upper_text_wrapper)
private val textEditText: EditText by bindView(R.id.text_edit_text)
private val notesEditText: EditText by bindView(R.id.notes_edit_text)
private val habitScoringButtons: HabitScoringButtonsView by bindView(R.id.habit_scoring_buttons)
private val checklistTitleView: TextView by bindView(R.id.checklist_title)
private val checklistContainer: ChecklistContainer by bindView(R.id.checklist_container)
private val habitResetStreakTitleView: TextView by bindView(R.id.habit_reset_streak_title)
private val habitResetStreakButtons: HabitResetStreakButtons by bindView(R.id.habit_reset_streak_buttons)
private val taskSchedulingTitleView: TextView by bindView(R.id.scheduling_title)
private val taskSchedulingControls: TaskSchedulingControls by bindView(R.id.scheduling_controls)
private val adjustStreakWrapper: ViewGroup by bindView(R.id.adjust_streak_wrapper)
private val adjustStreakTitleView: TextView by bindView(R.id.adjust_streak_title)
private val habitAdjustPositiveStreakView: EditText by bindView(R.id.habit_adjust_positive_streak)
private val habitAdjustNegativeStreakView: EditText by bindView(R.id.habit_adjust_negative_streak)
private val remindersTitleView: TextView by bindView(R.id.reminders_title)
private val remindersContainer: ReminderContainer by bindView(R.id.reminders_container)
private val taskDifficultyTitleView: TextView by bindView(R.id.task_difficulty_title)
private val taskDifficultyButtons: TaskDifficultyButtons by bindView(R.id.task_difficulty_buttons)
private val statWrapper: ViewGroup by bindView(R.id.stat_wrapper)
private val statStrengthButton: TextView by bindView(R.id.stat_strength_button)
private val statIntelligenceButton: TextView by bindView(R.id.stat_intelligence_button)
private val statConstitutionButton: TextView by bindView(R.id.stat_constitution_button)
private val statPerceptionButton: TextView by bindView(R.id.stat_perception_button)
private val rewardValueTitleView: TextView by bindView(R.id.reward_value_title)
private val stepperValueFormView: StepperValueFormView by bindView(R.id.reward_value)
private val tagsTitleView: TextView by bindView(R.id.tags_title)
private val tagsWrapper: LinearLayout by bindView(R.id.tags_wrapper)
private var isCreating = true
private var isChallengeTask = false
private var usesTaskAttributeStats = false
private var task: Task? = null
private var taskType: String = ""
private var tags = listOf<Tag>()
private var preselectedTags: ArrayList<String>? = null
private var hasPreselectedTags = false
private var selectedStat = Stats.STRENGTH
set(value) {
field = value
setSelectedAttribute(value)
}
private var canSave: Boolean = false
private var tintColor: Int = 0
set(value) {
field = value
upperTextWrapper.setBackgroundColor(value)
taskDifficultyButtons.tintColor = value
habitScoringButtons.tintColor = value
habitResetStreakButtons.tintColor = value
taskSchedulingControls.tintColor = value
supportActionBar?.setBackgroundDrawable(ColorDrawable(value))
updateTagViewsColors()
}
override fun getLayoutResId(): Int {
return R.layout.activity_task_form
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
val bundle = intent.extras ?: return
val taskId = bundle.getString(TASK_ID_KEY)
forcedTheme = if (taskId != null) {
val taskValue = bundle.getDouble(TASK_VALUE_KEY)
when {
taskValue < -20 -> "maroon"
taskValue < -10 -> "red"
taskValue < -1 -> "orange"
taskValue < 1 -> "yellow"
taskValue < 5 -> "green"
taskValue < 10 -> "teal"
else -> "blue"
}
} else {
"purple"
}
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
tintColor = getThemeColor(R.attr.taskFormTint)
isChallengeTask = bundle.getBoolean(IS_CHALLENGE_TASK, false)
taskType = bundle.getString(TASK_TYPE_KEY) ?: Task.TYPE_HABIT
preselectedTags = bundle.getStringArrayList(SELECTED_TAGS_KEY)
compositeSubscription.add(tagRepository.getTags()
.map { tagRepository.getUnmanagedCopy(it) }
.subscribe(Consumer {
tags = it
setTagViews()
}, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(userRepository.getUser().subscribe(Consumer {
usesTaskAttributeStats = it.preferences?.allocationMode == "taskbased"
configureForm()
}, RxErrorHandler.handleEmptyError()))
textEditText.addTextChangedListener(OnChangeTextWatcher { _, _, _, _ ->
checkCanSave()
})
statStrengthButton.setOnClickListener { selectedStat = Stats.STRENGTH }
statIntelligenceButton.setOnClickListener { selectedStat = Stats.INTELLIGENCE }
statConstitutionButton.setOnClickListener { selectedStat = Stats.CONSTITUTION }
statPerceptionButton.setOnClickListener { selectedStat = Stats.PERCEPTION }
scrollView.setOnTouchListener { view, event ->
userScrolled = view == scrollView && (event.action == MotionEvent.ACTION_SCROLL || event.action == MotionEvent.ACTION_MOVE)
return@setOnTouchListener false
}
scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, _: Int, _: Int, _: Int ->
if (userScrolled) {
dismissKeyboard()
}
}
title = ""
when {
taskId != null -> {
isCreating = false
compositeSubscription.add(taskRepository.getUnmanagedTask(taskId).firstElement().subscribe(Consumer {
task = it
//tintColor = ContextCompat.getColor(this, it.mediumTaskColor)
fillForm(it)
}, RxErrorHandler.handleEmptyError()))
}
bundle.containsKey(PARCELABLE_TASK) -> {
isCreating = false
task = bundle.getParcelable(PARCELABLE_TASK)
task?.let { fillForm(it) }
}
else -> title = getString(R.string.create_task, getString(when (taskType) {
Task.TYPE_DAILY -> R.string.daily
Task.TYPE_TODO -> R.string.todo
Task.TYPE_REWARD -> R.string.reward
else -> R.string.habit
}))
}
configureForm()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (isCreating) {
menuInflater.inflate(R.menu.menu_task_create, menu)
} else {
menuInflater.inflate(R.menu.menu_task_edit, menu)
}
menu.findItem(R.id.action_save).isEnabled = canSave
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_save -> saveTask()
R.id.action_delete -> deleteTask()
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun checkCanSave() {
val newCanSave = textEditText.text.isNotBlank()
if (newCanSave != canSave) {
invalidateOptionsMenu()
}
canSave = newCanSave
}
private fun configureForm() {
val habitViewsVisibility = if (taskType == Task.TYPE_HABIT) View.VISIBLE else View.GONE
habitScoringButtons.visibility = habitViewsVisibility
habitResetStreakTitleView.visibility = habitViewsVisibility
habitResetStreakButtons.visibility = habitViewsVisibility
habitAdjustNegativeStreakView.visibility = habitViewsVisibility
val habitDailyVisibility = if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_HABIT) View.VISIBLE else View.GONE
adjustStreakTitleView.visibility = habitDailyVisibility
adjustStreakWrapper.visibility = habitDailyVisibility
if (taskType == Task.TYPE_HABIT) {
habitAdjustPositiveStreakView.hint = getString(R.string.positive_habit_form)
} else {
habitAdjustPositiveStreakView.hint = getString(R.string.streak)
}
val todoDailyViewsVisibility = if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) View.VISIBLE else View.GONE
checklistTitleView.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
checklistContainer.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersTitleView.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersContainer.visibility = if (isChallengeTask) View.GONE else todoDailyViewsVisibility
remindersContainer.taskType = taskType
taskSchedulingTitleView.visibility = todoDailyViewsVisibility
taskSchedulingControls.visibility = todoDailyViewsVisibility
taskSchedulingControls.taskType = taskType
val rewardHideViews = if (taskType == Task.TYPE_REWARD) View.GONE else View.VISIBLE
taskDifficultyTitleView.visibility = rewardHideViews
taskDifficultyButtons.visibility = rewardHideViews
val rewardViewsVisibility = if (taskType == Task.TYPE_REWARD) View.VISIBLE else View.GONE
rewardValueTitleView.visibility = rewardViewsVisibility
stepperValueFormView.visibility = rewardViewsVisibility
tagsTitleView.visibility = if (isChallengeTask) View.GONE else View.VISIBLE
tagsWrapper.visibility = if (isChallengeTask) View.GONE else View.VISIBLE
statWrapper.visibility = if (usesTaskAttributeStats) View.VISIBLE else View.GONE
if (isCreating) {
adjustStreakTitleView.visibility = View.GONE
adjustStreakWrapper.visibility = View.GONE
}
}
private fun setTagViews() {
tagsWrapper.removeAllViews()
val padding = 20.dpToPx(this)
for (tag in tags) {
val view = CheckBox(this)
view.setPadding(padding, view.paddingTop, view.paddingRight, view.paddingBottom)
view.text = tag.name
if (preselectedTags?.contains(tag.id) == true) {
view.isChecked = true
}
tagsWrapper.addView(view)
}
setAllTagSelections()
updateTagViewsColors()
}
private fun setAllTagSelections() {
if (hasPreselectedTags) {
tags.forEachIndexed { index, tag ->
val view = tagsWrapper.getChildAt(index) as? CheckBox
view?.isChecked = task?.tags?.find { it.id == tag.id } != null
}
} else {
hasPreselectedTags = true
}
}
private fun fillForm(task: Task) {
if (!task.isValid) {
return
}
canSave = true
textEditText.setText(task.text)
notesEditText.setText(task.notes)
taskDifficultyButtons.selectedDifficulty = task.priority
when (taskType) {
Task.TYPE_HABIT -> {
habitScoringButtons.isPositive = task.up ?: false
habitScoringButtons.isNegative = task.down ?: false
task.frequency?.let {
if (it.isNotBlank()) {
habitResetStreakButtons.selectedResetOption = HabitResetOption.valueOf(it.toUpperCase(Locale.US))
}
}
habitAdjustPositiveStreakView.setText((task.counterUp ?: 0).toString())
habitAdjustNegativeStreakView.setText((task.counterDown ?: 0).toString())
habitAdjustPositiveStreakView.visibility = if (task.up == true) View.VISIBLE else View.GONE
habitAdjustNegativeStreakView.visibility = if (task.down == true) View.VISIBLE else View.GONE
if (task.up != true && task.down != true) {
adjustStreakTitleView.visibility = View.GONE
adjustStreakWrapper.visibility = View.GONE
}
}
Task.TYPE_DAILY -> {
taskSchedulingControls.startDate = task.startDate ?: Date()
taskSchedulingControls.everyX = task.everyX ?: 1
task.repeat?.let { taskSchedulingControls.weeklyRepeat = it }
taskSchedulingControls.daysOfMonth = task.getDaysOfMonth()
taskSchedulingControls.weeksOfMonth = task.getWeeksOfMonth()
habitAdjustPositiveStreakView.setText((task.streak ?: 0).toString())
taskSchedulingControls.frequency = task.frequency ?: Task.FREQUENCY_DAILY
}
Task.TYPE_TODO -> taskSchedulingControls.dueDate = task.dueDate
Task.TYPE_REWARD -> stepperValueFormView.value = task.value
}
if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) {
task.checklist?.let { checklistContainer.checklistItems = it }
remindersContainer.taskType = taskType
task.reminders?.let { remindersContainer.reminders = it }
}
task.attribute?.let { selectedStat = it }
setAllTagSelections()
}
private fun setSelectedAttribute(attributeName: String) {
if (!usesTaskAttributeStats) return
configureStatsButton(statStrengthButton, attributeName == Stats.STRENGTH )
configureStatsButton(statIntelligenceButton, attributeName == Stats.INTELLIGENCE )
configureStatsButton(statConstitutionButton, attributeName == Stats.CONSTITUTION )
configureStatsButton(statPerceptionButton, attributeName == Stats.PERCEPTION )
}
private fun configureStatsButton(button: TextView, isSelected: Boolean) {
button.background.setTint(if (isSelected) tintColor else ContextCompat.getColor(this, R.color.taskform_gray))
val textColorID = if (isSelected) R.color.white else R.color.gray_100
button.setTextColor(ContextCompat.getColor(this, textColorID))
}
private fun updateTagViewsColors() {
tagsWrapper.children.forEach { view ->
val tagView = view as? AppCompatCheckBox
val colorStateList = ColorStateList(
arrayOf(intArrayOf(-android.R.attr.state_checked), // unchecked
intArrayOf(android.R.attr.state_checked) // checked
),
intArrayOf(ContextCompat.getColor(this, R.color.gray_400), tintColor)
)
tagView?.buttonTintList = colorStateList
}
}
private fun saveTask() {
if (isSaving) {
return
}
isSaving = true
var thisTask = task
if (thisTask == null) {
thisTask = Task()
thisTask.type = taskType
thisTask.dateCreated = Date()
} else {
if (!thisTask.isValid) return
}
thisTask.text = textEditText.text.toString()
thisTask.notes = notesEditText.text.toString()
thisTask.priority = taskDifficultyButtons.selectedDifficulty
if (usesTaskAttributeStats) {
thisTask.attribute = selectedStat
}
if (taskType == Task.TYPE_HABIT) {
thisTask.up = habitScoringButtons.isPositive
thisTask.down = habitScoringButtons.isNegative
thisTask.frequency = habitResetStreakButtons.selectedResetOption.value
if (habitAdjustPositiveStreakView.text.isNotEmpty()) thisTask.counterUp = habitAdjustPositiveStreakView.text.toString().toIntCatchOverflow()
if (habitAdjustNegativeStreakView.text.isNotEmpty()) thisTask.counterDown = habitAdjustNegativeStreakView.text.toString().toIntCatchOverflow()
} else if (taskType == Task.TYPE_DAILY) {
thisTask.startDate = taskSchedulingControls.startDate
thisTask.everyX = taskSchedulingControls.everyX
thisTask.frequency = taskSchedulingControls.frequency
thisTask.repeat = taskSchedulingControls.weeklyRepeat
thisTask.setDaysOfMonth(taskSchedulingControls.daysOfMonth)
thisTask.setWeeksOfMonth(taskSchedulingControls.weeksOfMonth)
if (habitAdjustPositiveStreakView.text.isNotEmpty()) thisTask.streak = habitAdjustPositiveStreakView.text.toString().toIntCatchOverflow()
} else if (taskType == Task.TYPE_TODO) {
thisTask.dueDate = taskSchedulingControls.dueDate
} else if (taskType == Task.TYPE_REWARD) {
thisTask.value = stepperValueFormView.value
}
val resultIntent = Intent()
resultIntent.putExtra(TASK_TYPE_KEY, taskType)
if (!isChallengeTask) {
if (taskType == Task.TYPE_DAILY || taskType == Task.TYPE_TODO) {
thisTask.checklist = checklistContainer.checklistItems
thisTask.reminders = remindersContainer.reminders
}
thisTask.tags = RealmList()
tagsWrapper.forEachIndexed { index, view ->
val tagView = view as? CheckBox
if (tagView?.isChecked == true) {
thisTask.tags?.add(tags[index])
}
}
if (isCreating) {
taskRepository.createTaskInBackground(thisTask)
} else {
taskRepository.updateTaskInBackground(thisTask)
}
if (thisTask.type == Task.TYPE_DAILY || thisTask.type == Task.TYPE_TODO) {
taskAlarmManager.scheduleAlarmsForTask(thisTask)
}
} else {
resultIntent.putExtra(PARCELABLE_TASK, thisTask)
}
val mainHandler = Handler(this.mainLooper)
mainHandler.postDelayed({
setResult(Activity.RESULT_OK, resultIntent)
dismissKeyboard()
finish()
}, 500)
}
private fun deleteTask() {
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.are_you_sure)
alert.addButton(R.string.delete_task, true) { _, _ ->
if (task?.isValid != true) return@addButton
task?.id?.let { taskRepository.deleteTask(it).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) }
dismissKeyboard()
finish()
}
alert.addCancelButton()
alert.show()
}
private fun dismissKeyboard() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
val currentFocus = currentFocus
if (currentFocus != null && !habitAdjustPositiveStreakView.isFocused && !habitAdjustNegativeStreakView.isFocused) {
imm?.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
companion object {
val SELECTED_TAGS_KEY = "selectedTags"
const val TASK_ID_KEY = "taskId"
const val TASK_VALUE_KEY = "taskValue"
const val USER_ID_KEY = "userId"
const val TASK_TYPE_KEY = "type"
const val IS_CHALLENGE_TASK = "isChallengeTask"
const val PARCELABLE_TASK = "parcelable_task"
// in order to disable the event handler in MainActivity
const val SET_IGNORE_FLAG = "ignoreFlag"
}
}
private fun String.toIntCatchOverflow(): Int? {
return try {
toInt()
} catch (e: NumberFormatException) {
0
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/TaskFormActivity.kt | 1586506067 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.dvcs.repo.VcsRepositoryMappingListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryChangeListener
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.authentication.accounts.AccountRemovedListener
import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.util.CollectionDelta
import org.jetbrains.plugins.github.util.GitRemoteUrlCoordinates
import org.jetbrains.plugins.github.util.GithubGitHelper
import kotlin.properties.Delegates.observable
@Service
internal class GHPRToolWindowTabsManager(private val project: Project) {
private val gitHelper = GithubGitHelper.getInstance()
private val settings = GithubPullRequestsProjectUISettings.getInstance(project)
private val contentManager by lazy(LazyThreadSafetyMode.NONE) {
GHPRToolWindowsTabsContentManager(project, ChangesViewContentManager.getInstance(project))
}
private var remoteUrls by observable(setOf<GitRemoteUrlCoordinates>()) { _, oldValue, newValue ->
val delta = CollectionDelta(oldValue, newValue)
for (item in delta.removedItems) {
contentManager.removeTab(item)
}
for (item in delta.newItems) {
contentManager.addTab(item, Disposable {
//means that tab closed by user
if (gitHelper.getPossibleRemoteUrlCoordinates(project).contains(item)) settings.addHiddenUrl(item.url)
ApplicationManager.getApplication().invokeLater(::updateRemoteUrls) { project.isDisposed }
})
}
}
@CalledInAwt
fun showTab(remoteUrl: GitRemoteUrlCoordinates) {
settings.removeHiddenUrl(remoteUrl.url)
updateRemoteUrls()
contentManager.focusTab(remoteUrl)
}
private fun updateRemoteUrls() {
remoteUrls = gitHelper.getPossibleRemoteUrlCoordinates(project).filter {
!settings.getHiddenUrls().contains(it.url)
}.toSet()
}
class RemoteUrlsListener(private val project: Project)
: VcsRepositoryMappingListener, GitRepositoryChangeListener {
override fun mappingChanged() = runInEdt(project) { updateRemotes(project) }
override fun repositoryChanged(repository: GitRepository) = runInEdt(project) { updateRemotes(project) }
}
class AccountsListener : AccountRemovedListener, AccountTokenChangedListener {
override fun accountRemoved(removedAccount: GithubAccount) = updateRemotes()
override fun tokenChanged(account: GithubAccount) = updateRemotes()
private fun updateRemotes() = runInEdt {
for (project in ProjectManager.getInstance().openProjects) {
updateRemotes(project)
}
}
}
companion object {
private inline fun runInEdt(project: Project, crossinline runnable: () -> Unit) {
val application = ApplicationManager.getApplication()
if (application.isDispatchThread) runnable()
else application.invokeLater({ runnable() }) { project.isDisposed }
}
private fun updateRemotes(project: Project) = project.service<GHPRToolWindowTabsManager>().updateRemoteUrls()
}
}
| plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRToolWindowTabsManager.kt | 85214579 |
fun test() {
/*
comment1
comment2
*/<caret>
val foo = 1
} | plugins/kotlin/idea/tests/testData/intentions/convertBlockCommentToLineComment/simple.kt | 1573751049 |
// IGNORE_FIR
val <error descr="Destructuring declarations are only allowed for local variables/values">(a, b)</error> by <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">lazy</error> { <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">Pair</error>(1, 2) }
val <error descr="Destructuring declarations are only allowed for local variables/values">(c, d)</error> = <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">run</error> { <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">Pair</error>(3, 4) }
class Foo {
val <error descr="Destructuring declarations are only allowed for local variables/values">(a, b)</error> by <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">lazy</error> { <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">Pair</error>(1, 2) }
val <error descr="Destructuring declarations are only allowed for local variables/values">(c, d)</error> = <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">run</error> { <error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">Pair</error>(3, 4) }
}
// NO_CHECK_INFOS
// WITH_RUNTIME
| plugins/kotlin/idea/tests/testData/highlighter/TopLevelDestructuring.kt | 2164809922 |
fun a() {
val a = "${
<caret>
}"
}
// IGNORE_FORMATTER | plugins/kotlin/idea/tests/testData/indentationOnNewline/templates/TemplateEntryOpenWithoutContent2.after.kt | 271536972 |
package com.dev.moviedb.mvvm.repository
import com.dev.moviedb.mvvm.repository.remote.TmdbApiService
import com.dev.moviedb.mvvm.repository.remote.dto.MovieCollectionDTO
import io.reactivex.Observable
/**
*
* Yamda 1.0.0.
*/
class TopRatedMovieRepository(private val api: TmdbApiService){
fun findAll(): Observable<MovieCollectionDTO> {
return api.findTopRatedmovies()
}
} | app/src/main/java/com/dev/moviedb/mvvm/repository/TopRatedMovieRepository.kt | 3501642915 |
package com.lucas.mycontacts.di
import android.arch.persistence.room.Room
import android.content.Context
import com.lucas.mycontacts.db.AppDatabase
import com.lucas.mycontacts.db.dao.ContactDao
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Created by lucas on 13/11/2017.
*/
@Module
class DatabaseModule(private val context: Context) {
@Provides
@Singleton
fun providesDatabase() = Room
.databaseBuilder(context, AppDatabase::class.java, "mycontacts.db")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build()
@Provides
@Singleton
fun providesContactDao(db: AppDatabase): ContactDao = db.contactDao()
} | MyContacts/app/src/main/java/com/lucas/mycontacts/di/DatabaseModule.kt | 3932650043 |
internal class C(val arg1: Int) {
var arg2 = 0
var arg3 = 0
constructor(arg1: Int, arg2: Int, arg3: Int) : this(arg1) {
this.arg2 = arg2
this.arg3 = arg3
}
constructor(arg1: Int, arg2: Int) : this(arg1) {
this.arg2 = arg2
arg3 = 0
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/FieldUsagesInFactoryMethods.kt | 2202739861 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.profile
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.profile.ProfileApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigator
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandler
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi
@Module
class ProfileModule {
@Provides
fun providePresenter(schedulers: Schedulers, profilesApi: ProfileApi) = ProfilePresenter(schedulers, profilesApi)
@Provides
fun provideNavigator(activity: ProfileActivity): NewNavigatorApi = NewNavigator(activity)
@Provides
fun provideLinkHandler(activity: ProfileActivity, navigator: NewNavigatorApi): WykopLinkHandlerApi = WykopLinkHandler(activity, navigator)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/ProfileModule.kt | 3694131045 |
package taiwan.no1.app.ssfm.features.playlist
import android.os.Bundle
import android.support.v7.widget.helper.ItemTouchHelper
import android.transition.TransitionInflater
import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import org.jetbrains.anko.bundleOf
import taiwan.no1.app.ssfm.App
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.databinding.FragmentPlaylistDetailBinding
import taiwan.no1.app.ssfm.features.base.AdvancedFragment
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.HELPER_ADD_TO_PLAYLIST
import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo
import taiwan.no1.app.ssfm.misc.extension.recyclerview.PlaylistItemAdapter
import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch
import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.ItemTouchViewmodelCallback
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.SimpleItemTouchHelperCallback
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter
import taiwan.no1.app.ssfm.models.entities.PlaylistEntity
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import javax.inject.Inject
/**
* @author jieyi
* @since 11/14/17
*/
class PlaylistDetailFragment : AdvancedFragment<PlaylistDetailFragmentViewModel, FragmentPlaylistDetailBinding>() {
//region Static initialization
companion object Factory {
// The key name of the fragment initialization parameters.
private const val ARG_PARAM_PLAYLIST_OBJECT: String = "param_playlist_object"
private const val ARG_PARAM_PLAYLIST_TRANSITION: String = "param_playlist_transition_params"
/**
* Use this factory method to create a new instance of this fragment using the provided parameters.
*
* @return A new instance of [android.app.Fragment] PlaylistDetailFragment.
*/
fun newInstance(playlist: PlaylistEntity, transition: List<String>) =
PlaylistDetailFragment().apply {
arguments = bundleOf(ARG_PARAM_PLAYLIST_OBJECT to playlist,
ARG_PARAM_PLAYLIST_TRANSITION to ArrayList(transition))
if (transition.isNotEmpty()) {
sharedElementEnterTransition = TransitionInflater.from(App.appComponent.context()).inflateTransition(
R.transition.change_bound_and_fade)
sharedElementReturnTransition = TransitionInflater.from(App.appComponent.context()).inflateTransition(
R.transition.change_bound_and_fade)
}
}
}
//endregion
@Inject override lateinit var viewModel: PlaylistDetailFragmentViewModel
@Inject lateinit var addPlaylistItemCase: AddPlaylistItemCase
private val playlistItemInfo by lazy { DataInfo() }
private var playlistItemRes = mutableListOf<PlaylistItemEntity>()
// Get the arguments from the bundle here.
private val playlist by lazy { arguments.getParcelable<PlaylistEntity>(ARG_PARAM_PLAYLIST_OBJECT) }
private val transition by lazy { arguments.getStringArrayList(ARG_PARAM_PLAYLIST_TRANSITION) }
//region Fragment lifecycle
override fun onDestroyView() {
(binding?.itemAdapter as BaseDataBindingAdapter<*, *>).detachAll()
super.onDestroyView()
}
//endregion
//region Base fragment implement
override fun rendered(savedInstanceState: Bundle?) {
binding?.apply {
// TODO(jieyi): 11/19/17 Create a map for each elements.
if (transition.isNotEmpty()) {
ivAlbumImage.transitionName = transition[0]
tvName.transitionName = transition[1]
}
itemLayoutManager = WrapContentLinearLayoutManager(activity)
itemAdapter = PlaylistItemAdapter(this@PlaylistDetailFragment,
R.layout.item_music_type_5,
playlistItemRes) { holder, item, index ->
if (null == holder.binding.avm)
holder.binding.avm = RecyclerViewPlaylistDetailViewModel(addPlaylistItemCase,
item,
index + 1)
else
holder.binding.avm?.setPlaylistItem(item, index + 1)
}
val callback = SimpleItemTouchHelperCallback(itemAdapter as PlaylistItemAdapter, vmItemTouchCallback)
ItemTouchHelper(callback).attachToRecyclerView(recyclerView)
}
viewModel.attachPlaylistInfo(playlist)
playlistItemInfo.firstFetch { info ->
viewModel.fetchPlaylistItems(playlist.id) {
playlistItemRes.refreshAndChangeList(it, 0, binding?.itemAdapter as PlaylistItemAdapter, info)
}
}
}
override fun provideInflateView(): Int = R.layout.fragment_playlist_detail
//endregion
/**
* @param playlistItem
*
* @event_from [taiwan.no1.app.ssfm.features.playlist.RecyclerViewPlaylistDetailViewModel.trackOnClick]
*/
@Subscribe(tags = [(Tag(HELPER_ADD_TO_PLAYLIST))])
fun addToPlaylist(playlistItem: PlaylistItemEntity) {
playerHelper.addToPlaylist(playlistItem, playlistItemRes, this.javaClass.name)
}
private val vmItemTouchCallback = object : ItemTouchViewmodelCallback {
override fun onItemDismiss(position: Int, direction: Int) {
playlistItemRes[position].let { deletedItem ->
viewModel.deleteItem(deletedItem) { if (it) playlistItemRes.remove(deletedItem) }
}
}
}
} | app/src/main/kotlin/taiwan/no1/app/ssfm/features/playlist/PlaylistDetailFragment.kt | 1576256703 |
package views
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import android.util.AttributeSet
import android.view.View
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
import org.stoyicker.dinger.views.R
class RoundCornerImageView(context: Context, attributeSet: AttributeSet? = null)
: View(context, attributeSet), Target {
private val cornerRadiusPx: Float
private val picasso = Picasso.get()
private val clipPath = Path()
private var drawable: Drawable? = null
set(value) {
field = value
postInvalidate()
}
private var queuedUrl: String? = null
private var queuedErrorRes: Int = 0
init {
context.theme.obtainStyledAttributes(
attributeSet,
R.styleable.RoundCornerImageView,
0,
0).apply {
try {
cornerRadiusPx = getDimension(R.styleable.RoundCornerImageView_cornerRadius, DEFAULT_RADIUS_PX)
} finally {
recycle()
}
}
}
fun loadImage(url: String, @DrawableRes errorRes: Int = 0) {
queuedUrl = url
queuedErrorRes = errorRes
loadImageInternal()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
queuedUrl?.let { picasso.invalidate(it) }
picasso.cancelRequest(this)
clipPath.reset()
RectF().apply {
set(0f, 0f, w.toFloat(), h.toFloat())
clipPath.addRoundRect(this, DEFAULT_RADIUS_PX, DEFAULT_RADIUS_PX, Path.Direction.CW)
}
clipPath.close()
loadImageInternal(w, h)
}
override fun onDraw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(clipPath)
drawable?.apply {
setBounds(0, 0, width, height)
draw(canvas)
}
canvas.restoreToCount(save)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
drawable = placeHolderDrawable
}
override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
val roundedDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
layoutParams.apply {
width = Math.min((parent as View).width, bitmap.width)
height = bitmap.height
}
roundedDrawable.cornerRadius = cornerRadiusPx
drawable = roundedDrawable
layoutParams = layoutParams
}
override fun onBitmapFailed(e: Exception, errorDrawable: Drawable?) {
layoutParams.apply {
width = Math.min(width, height)
height = width
}
drawable = errorDrawable
layoutParams = layoutParams
}
private fun loadImageInternal(w: Int = Math.min((parent as View).width, width), h: Int = height) {
if (w < 1 && h < 1) {
return
}
queuedUrl?.let {
picasso.load(it)
.noPlaceholder()
.centerCrop()
.resize(w, h)
.stableKey(it)
.apply {
if (queuedErrorRes != 0) {
error(queuedErrorRes)
}
}
.into(this)
}
}
private companion object {
const val DEFAULT_RADIUS_PX = 25f
}
}
| views/src/main/kotlin/views/RoundCornerImageView.kt | 3327979348 |
package com.kamer.orny.interaction.common
import com.kamer.orny.interaction.model.AuthorsWithDefault
import io.reactivex.Single
interface GetAuthorsWithDefaultSingleUseCase {
fun get(): Single<AuthorsWithDefault>
} | app/src/main/kotlin/com/kamer/orny/interaction/common/GetAuthorsWithDefaultSingleUseCase.kt | 497055126 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATED_JAVA_ANNOTATION")
package androidx.annotation
import java.lang.annotation.ElementType
import kotlin.annotation.Retention
import kotlin.annotation.Target
import kotlin.reflect.KClass
/**
* Allows use of an opt-in API denoted by the given markers in the annotated file, declaration,
* or expression. If a declaration is annotated with [OptIn], its usages are **not** required to
* opt-in to that API.
*/
@Retention(AnnotationRetention.BINARY)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.PROPERTY,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.FILE,
AnnotationTarget.TYPEALIAS
)
@java.lang.annotation.Target(
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.TYPE,
)
public annotation class OptIn(
/**
* Defines the opt-in API(s) whose usage this annotation allows.
*/
@get:Suppress("ArrayReturn") // Kotlin generates a raw array for annotation vararg
vararg val markerClass: KClass<out Annotation>
)
| annotation/annotation-experimental/src/main/java/androidx/annotation/OptIn.kt | 1482712064 |
/*
* 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.animation.internal
internal expect annotation class JvmDefaultWithCompatibility() | compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/internal/JvmDefaultWithCompatibility.kt | 2614707729 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
import androidx.paging.LoadState.Loading
import androidx.paging.LoadState.NotLoading
import androidx.paging.LoadType.APPEND
import androidx.paging.LoadType.PREPEND
import androidx.paging.LoadType.REFRESH
import androidx.paging.PagingSource.LoadResult.Page
import androidx.paging.PagingSource.LoadResult.Page.Companion.COUNT_UNDEFINED
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.test.assertEquals
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(JUnit4::class)
class PageFetcherSnapshotStateTest {
val testScope = TestScope()
@Test
fun placeholders_uncounted() = testScope.runTest {
val pagerState = PageFetcherSnapshotState.Holder<Int, Int>(
config = PagingConfig(2, enablePlaceholders = false)
).withLock { it }
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
pagerState.insert(
loadId = 0, loadType = REFRESH,
page = Page(
data = listOf(),
prevKey = -1,
nextKey = 1,
itemsBefore = 50,
itemsAfter = 50
)
)
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
pagerState.insert(
loadId = 0, loadType = PREPEND,
page = Page(
data = listOf(),
prevKey = -2,
nextKey = 0,
itemsBefore = 25
)
)
pagerState.insert(
loadId = 0, loadType = APPEND,
page = Page(
data = listOf(),
prevKey = 0,
nextKey = 2,
itemsBefore = 25
)
)
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
// Should automatically decrement remaining placeholders when counted.
pagerState.insert(
loadId = 0,
loadType = PREPEND,
page = Page(
data = listOf(0),
prevKey = -3,
nextKey = 0,
itemsBefore = COUNT_UNDEFINED,
itemsAfter = COUNT_UNDEFINED
)
)
pagerState.insert(
loadId = 0,
loadType = APPEND,
page = Page(
data = listOf(0),
prevKey = 0,
nextKey = 3,
itemsBefore = COUNT_UNDEFINED,
itemsAfter = COUNT_UNDEFINED
)
)
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
pagerState.drop(
event = PageEvent.Drop(
loadType = PREPEND,
minPageOffset = -2,
maxPageOffset = -2,
placeholdersRemaining = 100
)
)
pagerState.drop(
event = PageEvent.Drop(
loadType = APPEND,
minPageOffset = 2,
maxPageOffset = 2,
placeholdersRemaining = 100
)
)
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
}
@Test
fun placeholders_counted() = testScope.runTest {
val pagerState = PageFetcherSnapshotState.Holder<Int, Int>(
config = PagingConfig(2, enablePlaceholders = true)
).withLock { it }
assertEquals(0, pagerState.placeholdersBefore)
assertEquals(0, pagerState.placeholdersAfter)
pagerState.insert(
loadId = 0,
loadType = REFRESH,
page = Page(
data = listOf(),
prevKey = -1,
nextKey = 1,
itemsBefore = 50,
itemsAfter = 50
)
)
assertEquals(50, pagerState.placeholdersBefore)
assertEquals(50, pagerState.placeholdersAfter)
pagerState.insert(
loadId = 0,
loadType = PREPEND,
page = Page(
data = listOf(),
prevKey = -2,
nextKey = 0,
itemsBefore = 25,
itemsAfter = COUNT_UNDEFINED
)
)
pagerState.insert(
loadId = 0,
loadType = APPEND,
page = Page(
data = listOf(),
prevKey = 0,
nextKey = 2,
itemsBefore = COUNT_UNDEFINED,
itemsAfter = 25
)
)
assertEquals(25, pagerState.placeholdersBefore)
assertEquals(25, pagerState.placeholdersAfter)
// Should automatically decrement remaining placeholders when counted.
pagerState.insert(
loadId = 0,
loadType = PREPEND,
page = Page(
data = listOf(0),
prevKey = -3,
nextKey = 0,
itemsBefore = COUNT_UNDEFINED,
itemsAfter = COUNT_UNDEFINED
)
)
pagerState.insert(
loadId = 0,
loadType = APPEND,
page = Page(
data = listOf(0),
prevKey = 0,
nextKey = 3,
itemsBefore = COUNT_UNDEFINED,
itemsAfter = COUNT_UNDEFINED
)
)
assertEquals(24, pagerState.placeholdersBefore)
assertEquals(24, pagerState.placeholdersAfter)
pagerState.drop(
event = PageEvent.Drop(
loadType = PREPEND,
minPageOffset = -2,
maxPageOffset = -2,
placeholdersRemaining = 100
)
)
pagerState.drop(
event = PageEvent.Drop(
loadType = APPEND,
minPageOffset = 2,
maxPageOffset = 2,
placeholdersRemaining = 100
)
)
assertEquals(100, pagerState.placeholdersBefore)
assertEquals(100, pagerState.placeholdersAfter)
}
@Test
fun currentPagingState() = testScope.runTest {
val config = PagingConfig(pageSize = 2)
val state = PageFetcherSnapshotState.Holder<Int, Int>(config = config).withLock { it }
val pages = listOf(
Page(
data = listOf(2, 3),
prevKey = 1,
nextKey = 4
),
Page(
data = listOf(4, 5),
prevKey = 3,
nextKey = 6,
itemsBefore = 4,
itemsAfter = 4
),
Page(
data = listOf(6, 7),
prevKey = 5,
nextKey = 8
)
)
state.insert(0, REFRESH, pages[1])
state.insert(0, PREPEND, pages[0])
state.insert(0, APPEND, pages[2])
val presenter = pages.toPresenter(1)
val presenterMissingPrepend = pages.drop(1).toPresenter(0)
val presenterMissingAppend = pages.dropLast(1).toPresenter(1)
val presenterExtraPrepend = pages.toMutableList().apply {
add(
0,
Page(
data = listOf(0, 1),
prevKey = null,
nextKey = 2
)
)
}.toPresenter(2)
val presenterExtraAppend = pages.toMutableList().apply {
add(
Page(
data = listOf(8, 9),
prevKey = 7,
nextKey = null
)
)
}.toPresenter(1)
// Hint in loaded items, fetcher state == presenter state.
assertThat(state.currentPagingState(presenter.accessHintForPresenterIndex(4)))
.isEqualTo(
PagingState(
pages = pages,
anchorPosition = 4,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders before, fetcher state == presenter state.
assertThat(state.currentPagingState(presenter.accessHintForPresenterIndex(0)))
.isEqualTo(
PagingState(
pages = pages,
anchorPosition = 0,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders after, fetcher state == presenter state.
assertThat(state.currentPagingState(presenter.accessHintForPresenterIndex(9)))
.isEqualTo(
PagingState(
pages = pages,
anchorPosition = 9,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in loaded items, fetcher state has an extra prepended page.
assertThat(
state.currentPagingState(presenterMissingPrepend.accessHintForPresenterIndex(4))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 4,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders before, fetcher state has an extra prepended page.
assertThat(
state.currentPagingState(presenterMissingPrepend.accessHintForPresenterIndex(0))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 0,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders after, fetcher state has an extra prepended page.
assertThat(
state.currentPagingState(presenterMissingPrepend.accessHintForPresenterIndex(9))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 9,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in loaded items, fetcher state has an extra appended page.
assertThat(
state.currentPagingState(presenterMissingAppend.accessHintForPresenterIndex(4))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 4,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders before, fetcher state has an extra appended page.
assertThat(
state.currentPagingState(presenterMissingAppend.accessHintForPresenterIndex(0))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 0,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders after, fetcher state has an extra prepended page.
assertThat(
state.currentPagingState(presenterMissingAppend.accessHintForPresenterIndex(9))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 9,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in loaded items, presenter state has an extra prepended page.
assertThat(
state.currentPagingState(presenterExtraPrepend.accessHintForPresenterIndex(4))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 4,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders before, presenter state has an extra prepended page.
assertThat(
state.currentPagingState(presenterExtraPrepend.accessHintForPresenterIndex(0))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 0,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders after, presenter state has an extra prepended page.
assertThat(
state.currentPagingState(presenterExtraPrepend.accessHintForPresenterIndex(9))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 9,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in loaded items, presenter state has an extra appended page.
assertThat(
state.currentPagingState(presenterExtraAppend.accessHintForPresenterIndex(4))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 4,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders before, presenter state has an extra appended page.
assertThat(
state.currentPagingState(presenterExtraAppend.accessHintForPresenterIndex(0))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 0,
config = config,
leadingPlaceholderCount = 2
)
)
// Hint in placeholders after, fetcher state has an extra appended page.
assertThat(
state.currentPagingState(presenterExtraAppend.accessHintForPresenterIndex(9))
).isEqualTo(
PagingState(
pages = pages,
anchorPosition = 9,
config = config,
leadingPlaceholderCount = 2
)
)
}
@Test
fun loadStates() = testScope.runTest {
val config = PagingConfig(pageSize = 2)
val state = PageFetcherSnapshotState.Holder<Int, Int>(config = config).withLock { it }
// assert initial state
assertThat(state.sourceLoadStates.snapshot()).isEqualTo(loadStates(refresh = Loading))
// assert APPEND state is updated
state.sourceLoadStates.set(APPEND, NotLoading.Complete)
assertThat(state.sourceLoadStates.snapshot()).isEqualTo(
loadStates(
refresh = Loading,
append = NotLoading.Complete
)
)
// assert REFRESH state is incrementally updated
state.sourceLoadStates.set(REFRESH, NotLoading.Incomplete)
assertThat(state.sourceLoadStates.snapshot()).isEqualTo(
loadStates(
refresh = NotLoading.Incomplete,
append = NotLoading.Complete,
)
)
assertThat(state.sourceLoadStates.get(APPEND)).isEqualTo(NotLoading.Complete)
}
private fun List<Page<Int, Int>>.toPresenter(initialPageIndex: Int): PagePresenter<Int> {
val pageSize = 2
val initialPage = get(initialPageIndex)
val presenter = PagePresenter(
insertEvent = localRefresh(
pages = listOf(TransformablePage(initialPage.data)),
placeholdersBefore = initialPage.itemsBefore,
placeholdersAfter = initialPage.itemsAfter,
)
)
for (i in 0 until initialPageIndex) {
val offset = i + 1
presenter.processEvent(
localPrepend(
pages = listOf(
TransformablePage(originalPageOffset = -offset, data = get(i).data)
),
placeholdersBefore = initialPage.itemsBefore - (offset * pageSize),
),
ProcessPageEventCallbackCapture()
)
}
for (i in (initialPageIndex + 1)..lastIndex) {
val offset = i - initialPageIndex
presenter.processEvent(
localAppend(
pages = listOf(
TransformablePage(originalPageOffset = offset, data = get(i).data)
),
placeholdersAfter = initialPage.itemsAfter - (offset * pageSize),
),
ProcessPageEventCallbackCapture()
)
}
return presenter
}
}
| paging/paging-common/src/test/kotlin/androidx/paging/PageFetcherSnapshotStateTest.kt | 1838243418 |
// 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.projectModel
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinNativeLibraryKind
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.utils.Printer
import java.io.File
open class ProjectResolveModel(val modules: List<ResolveModule>) {
open class Builder {
val modules: MutableList<ResolveModule.Builder> = mutableListOf()
open fun build(): ProjectResolveModel = ProjectResolveModel(modules.map { it.build() })
}
}
open class ResolveModule(
val name: String,
val root: File,
val platform: TargetPlatform,
val dependencies: List<ResolveDependency>,
val testRoot: File? = null,
val additionalCompilerArgs: String? = null
) {
final override fun toString(): String {
return buildString { renderDescription(Printer(this)) }
}
open fun renderDescription(printer: Printer) {
printer.println("Module $name")
printer.pushIndent()
printer.println("platform=$platform")
printer.println("root=${root.absolutePath}")
if (testRoot != null) printer.println("testRoot=${testRoot.absolutePath}")
printer.println("dependencies=${dependencies.joinToString { it.to.name }}")
if (additionalCompilerArgs != null) printer.println("additionalCompilerArgs=$additionalCompilerArgs")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ResolveModule
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
open class Builder {
private var state: State = State.NOT_BUILT
private var cachedResult: ResolveModule? = null
var name: String? = null
var root: File? = null
var platform: TargetPlatform? = null
val dependencies: MutableList<ResolveDependency.Builder> = mutableListOf()
var testRoot: File? = null
var additionalCompilerArgs: String? = null
open fun build(): ResolveModule {
if (state == State.BUILT) return cachedResult!!
require(state == State.NOT_BUILT) { "Re-building module $this with name $name (root at $root)" }
state = State.BUILDING
val builtDependencies = dependencies.map { it.build() }
cachedResult = ResolveModule(name!!, root!!, platform!!, builtDependencies, testRoot, additionalCompilerArgs= additionalCompilerArgs)
state = State.BUILT
return cachedResult!!
}
enum class State {
NOT_BUILT,
BUILDING,
BUILT
}
}
}
sealed class ResolveLibrary(
name: String,
root: File,
platform: TargetPlatform,
val kind: PersistentLibraryKind<*>?
) : ResolveModule(name, root, platform, emptyList()) {
class Builder(val target: ResolveLibrary) : ResolveModule.Builder() {
override fun build(): ResolveModule = target
}
}
sealed class Stdlib(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object CommonStdlib : Stdlib(
"stdlib-common",
TestKotlinArtifacts.kotlinStdlibCommon,
CommonPlatforms.defaultCommonPlatform,
KotlinCommonLibraryKind
)
object NativeStdlib : Stdlib(
"stdlib-native-by-host",
TestKotlinArtifacts.kotlinStdlibNative,
NativePlatforms.nativePlatformBySingleTarget(HostManager.host),
KotlinNativeLibraryKind
)
object JvmStdlib : Stdlib(
"stdlib-jvm",
TestKotlinArtifacts.kotlinStdlib,
JvmPlatforms.defaultJvmPlatform,
null
)
object JsStdlib : Stdlib(
"stdlib-js",
TestKotlinArtifacts.kotlinStdlibJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
}
sealed class KotlinTest(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object JsKotlinTest : KotlinTest(
"kotlin-test-js",
TestKotlinArtifacts.kotlinTestJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
object JvmKotlinTest : KotlinTest(
"kotlin-test-jvm",
TestKotlinArtifacts.kotlinTestJunit,
JvmPlatforms.defaultJvmPlatform,
null
)
object JustKotlinTest : KotlinTest(
"kotlin-test",
TestKotlinArtifacts.kotlinTest,
JvmPlatforms.defaultJvmPlatform,
null
)
object Junit : KotlinTest(
"junit",
File("$IDEA_TEST_DATA_DIR/lib/junit-4.12.jar"),
JvmPlatforms.defaultJvmPlatform,
null
)
}
interface ResolveSdk
object FullJdk : ResolveLibrary(
"full-jdk",
File("fake file for full jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object MockJdk : ResolveLibrary(
"mock-jdk",
File("fake file for mock jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object KotlinSdk : ResolveLibrary(
"kotlin-sdk",
File("fake file for kotlin sdk"),
CommonPlatforms.defaultCommonPlatform,
null,
), ResolveSdk
open class ResolveDependency(val to: ResolveModule, val kind: Kind) {
open class Builder {
var to: ResolveModule.Builder = ResolveModule.Builder()
var kind: Kind? = null
open fun build(): ResolveDependency = ResolveDependency(to.build(), kind!!)
}
enum class Kind {
DEPENDS_ON,
DEPENDENCY,
}
} | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/projectModel/Model.kt | 2083867083 |
// 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.script.configuration
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.options.UnnamedConfigurable
import org.jetbrains.annotations.Nls
abstract class ScriptingSupportSpecificSettingsProvider {
@get:Nls
abstract val title: String
abstract fun createConfigurable(): UnnamedConfigurable
companion object {
@JvmField
val SETTINGS_PROVIDERS: ExtensionPointName<ScriptingSupportSpecificSettingsProvider> =
ExtensionPointName.create("org.jetbrains.kotlin.scripting.idea.settings.provider")
}
}
| plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/script/configuration/ScriptingSupportSpecificSettingsProvider.kt | 789076598 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.extensions
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.orNull
import com.intellij.util.lang.UrlClassLoader
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity
import org.jetbrains.kotlin.analysis.project.structure.KtCompilerPluginsProvider
import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.plugins.processCompilerPluginsOptions
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor
import org.jetbrains.kotlin.idea.base.projectStructure.ideaModule
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettingsListener
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.util.ServiceLoaderLite
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentMap
@OptIn(ExperimentalCompilerApi::class)
internal class KtCompilerPluginsProviderIdeImpl(private val project: Project) : KtCompilerPluginsProvider(), Disposable {
private val pluginsCacheCachedValue: SynchronizedClearableLazy<PluginsCache?> = SynchronizedClearableLazy { createNewCache() }
private val pluginsCache: PluginsCache?
get() = pluginsCacheCachedValue.value
init {
val messageBusConnection = project.messageBus.connect(this)
messageBusConnection.subscribe(WorkspaceModelTopics.CHANGED,
object : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
val hasChanges = event.getChanges(FacetEntity::class.java).any { change ->
change.facetTypes.any { it == KotlinFacetType.ID }
}
if (hasChanges) {
pluginsCacheCachedValue.drop()
}
}
}
)
messageBusConnection.subscribe(KotlinCompilerSettingsListener.TOPIC,
object : KotlinCompilerSettingsListener {
override fun <T> settingsChanged(oldSettings: T?, newSettings: T?) {
pluginsCacheCachedValue.drop()
}
}
)
}
private val EntityChange<FacetEntity>.facetTypes: List<String>
get() = when (this) {
is EntityChange.Added -> listOf(entity.facetType)
is EntityChange.Removed -> listOf(entity.facetType)
is EntityChange.Replaced -> listOf(oldEntity.facetType, newEntity.facetType)
}
private fun createNewCache(): PluginsCache? {
if (!project.isTrusted()) return null
val pluginsClassLoader: UrlClassLoader = UrlClassLoader.build().apply {
parent(KtSourceModule::class.java.classLoader)
val pluginsClasspath = ModuleManager.getInstance(project).modules
.flatMap { it.getCompilerArguments().getPluginClassPaths() }
.distinct()
files(pluginsClasspath)
}.get()
return PluginsCache(
pluginsClassLoader,
ContainerUtil.createConcurrentWeakMap<KtSourceModule, Optional<CompilerPluginRegistrar.ExtensionStorage>>()
)
}
private class PluginsCache(
val pluginsClassLoader: UrlClassLoader,
val registrarForModule: ConcurrentMap<KtSourceModule, Optional<CompilerPluginRegistrar.ExtensionStorage>>
)
override fun <T : Any> getRegisteredExtensions(module: KtSourceModule, extensionType: ProjectExtensionDescriptor<T>): List<T> {
val registrarForModule = pluginsCache?.registrarForModule ?: return emptyList()
val extensionStorage = registrarForModule.computeIfAbsent(module) {
Optional.ofNullable(computeExtensionStorage(module))
}.orNull() ?: return emptyList()
val registrars = extensionStorage.registeredExtensions[extensionType] ?: return emptyList()
@Suppress("UNCHECKED_CAST")
return registrars as List<T>
}
private fun computeExtensionStorage(module: KtSourceModule): CompilerPluginRegistrar.ExtensionStorage? {
val classLoader = pluginsCache?.pluginsClassLoader ?: return null
val compilerArguments = module.ideaModule.getCompilerArguments()
val classPaths = compilerArguments.getPluginClassPaths().map { it.toFile() }.takeIf { it.isNotEmpty() } ?: return null
val logger = logger<KtCompilerPluginsProviderIdeImpl>()
val pluginRegistrars =
logger.runAndLogException { ServiceLoaderLite.loadImplementations<CompilerPluginRegistrar>(classPaths, classLoader) }
?.takeIf { it.isNotEmpty() }
?: return null
val commandLineProcessors = logger.runAndLogException {
ServiceLoaderLite.loadImplementations<CommandLineProcessor>(classPaths, classLoader)
} ?: return null
val compilerConfiguration = CompilerConfiguration()
processCompilerPluginsOptions(compilerConfiguration, compilerArguments.pluginOptions?.toList(), commandLineProcessors)
val storage = CompilerPluginRegistrar.ExtensionStorage()
for (pluginRegistrar in pluginRegistrars) {
with(pluginRegistrar) {
storage.registerExtensions(compilerConfiguration)
}
}
return storage
}
private fun CommonCompilerArguments.getPluginClassPaths(): List<Path> {
return this
.pluginClasspaths
?.map { Path.of(it).toAbsolutePath() }
?.toList()
.orEmpty()
}
private fun Module.getCompilerArguments(): CommonCompilerArguments {
return KotlinFacet.get(this)?.configuration?.settings?.mergedCompilerArguments
?: KotlinCommonCompilerArgumentsHolder.getInstance(project).settings
}
override fun dispose() {
pluginsCacheCachedValue.drop()
}
companion object {
fun getInstance(project: Project): KtCompilerPluginsProviderIdeImpl {
return project.getService(KtCompilerPluginsProvider::class.java) as KtCompilerPluginsProviderIdeImpl
}
}
}
| plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/extensions/KtCompilerPluginsProviderIdeImpl.kt | 2681958297 |
// 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.uiTests.e2e.steps
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import com.intellij.uiTests.e2e.fixtures.dialog
import com.intellij.uiTests.e2e.fixtures.idea
import com.intellij.uiTests.e2e.fixtures.welcomeFrame
import com.intellij.uiTests.robot.optional
import java.time.Duration
class CreateNewProjectSteps(private val robot: RemoteRobot) {
fun createCommandLineProject() = step("Create CommandLine Project") {
robot.welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
robot.idea {
waitFor(Duration.ofMinutes(5)) { isDumbMode().not() }
}
tryCloseTipOfTheDay()
}
private fun tryCloseTipOfTheDay(): Unit = step("Try to close 'Tip of The Day'") {
robot.idea {
optional {
dialog("Tip of the Day", Duration.ofSeconds(5)) {
button("Close").click()
}
}
}
}
} | platform/testFramework/ui/src/com/intellij/uiTests/e2e/steps/CreateNewProjectSteps.kt | 4278159270 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
@Deprecated(
"Use 'moduleInfoOrNull' instead",
ReplaceWith("this.moduleInfoOrNull", "org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull")
)
fun PsiElement.getNullableModuleInfo(): IdeaModuleInfo? = this.moduleInfoOrNull | plugins/kotlin/base/obsolete-compat/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt | 1130592326 |
// PROBLEM: none
// WITH_STDLIB
object O {
@JvmStatic val <caret>a = 1
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/mayBeConstant/jvmStatic.kt | 3136075681 |
// TYPE: '4'
// OUT_OF_CODE_BLOCK: FALSE
fun bar() {
class InnerBoo(val someValue: Int) {
constructor() : this(<caret>) {
}
}
val b = InnerBoo()
} | plugins/kotlin/idea/tests/testData/codeInsight/outOfBlock/InDelegateCallOfSecondaryConstructorInLocalClass.kt | 291094928 |
// 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.idea.devkit.actions.updateFromSources
import com.intellij.CommonBundle
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.ide.plugins.PluginInstaller
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.task.ProjectTaskManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.Restarter
import com.intellij.util.TimeoutUtil
import com.intellij.util.io.inputStream
import com.intellij.util.io.isFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import java.nio.file.Paths
import java.util.*
private val LOG = logger<UpdateIdeFromSourcesAction>()
private val notificationGroup by lazy {
NotificationGroup(displayId = "Update from Sources", displayType = NotificationDisplayType.STICKY_BALLOON)
}
internal open class UpdateIdeFromSourcesAction
@JvmOverloads constructor(private val forceShowSettings: Boolean = false)
: AnAction(if (forceShowSettings) DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.show.settings.text")
else DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.text"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.description"), null), DumbAware, UpdateInBackground {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (forceShowSettings || UpdateFromSourcesSettings.getState().showSettings) {
val oldWorkIdePath = UpdateFromSourcesSettings.getState().actualIdePath
val ok = UpdateFromSourcesDialog(project, forceShowSettings).showAndGet()
if (!ok) return
val updatedState = UpdateFromSourcesSettings.getState()
if (oldWorkIdePath != updatedState.actualIdePath) {
updatedState.workIdePathsHistory.remove(oldWorkIdePath)
updatedState.workIdePathsHistory.remove(updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, oldWorkIdePath)
}
}
fun error(@NlsContexts.DialogMessage message : String) {
Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle())
}
val state = UpdateFromSourcesSettings.getState()
val devIdeaHome = project.basePath ?: return
val workIdeHome = state.actualIdePath
val restartAutomatically = state.restartAutomatically
if (!ApplicationManager.getApplication().isRestartCapable && FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.ide.cannot.restart"))
}
val notIdeHomeMessage = checkIdeHome(workIdeHome)
if (notIdeHomeMessage != null) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home",
workIdeHome, notIdeHomeMessage))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getConfigPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_CONFIG_PATH))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getSystemPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_SYSTEM_PATH))
}
val scriptFile = File(devIdeaHome, "build/scripts/idea_ultimate.gant")
if (!scriptFile.exists()) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.not.exists", scriptFile))
}
if (!scriptFile.readText().contains(includeBinAndRuntimeProperty)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.out.of.date"))
}
val bundledPluginDirsToSkip: List<String>
val nonBundledPluginDirsToInclude: List<String>
val buildEnabledPluginsOnly = !state.buildDisabledPlugins
if (buildEnabledPluginsOnly) {
val pluginDirectoriesToSkip = LinkedHashSet(state.pluginDirectoriesForDisabledPlugins)
pluginDirectoriesToSkip.removeAll(PluginManagerCore.getLoadedPlugins().asSequence().filter { it.isBundled }.map { it.path }.filter { it.isDirectory }.map { it.name })
PluginManagerCore.getPlugins().filter { it.isBundled && !it.isEnabled }.map { it.path }.filter { it.isDirectory }.mapTo(pluginDirectoriesToSkip) { it.name }
val list = pluginDirectoriesToSkip.toMutableList()
state.pluginDirectoriesForDisabledPlugins = list
bundledPluginDirsToSkip = list
nonBundledPluginDirsToInclude = PluginManagerCore.getPlugins().filter {
!it.isBundled && it.isEnabled && it.version != null && it.version.contains("SNAPSHOT")
}.map { it.path }.filter { it.isDirectory }.map { it.name }
}
else {
bundledPluginDirsToSkip = emptyList()
nonBundledPluginDirsToInclude = emptyList()
}
val deployDir = "$devIdeaHome/out/deploy" // NON-NLS
val distRelativePath = "dist" // NON-NLS
val backupDir = "$devIdeaHome/out/backup-before-update-from-sources" // NON-NLS
val params = createScriptJavaParameters(devIdeaHome, project, deployDir, distRelativePath, scriptFile,
buildEnabledPluginsOnly, bundledPluginDirsToSkip, nonBundledPluginDirsToInclude) ?: return
ProjectTaskManager.getInstance(project)
.buildAllModules()
.onSuccess {
if (!it.isAborted && !it.hasErrors()) {
runUpdateScript(params, project, workIdeHome, deployDir, distRelativePath, backupDir, restartAutomatically)
}
}
}
private fun checkIdeHome(workIdeHome: String): String? {
val homeDir = File(workIdeHome)
if (!homeDir.exists()) return null
if (homeDir.isFile) return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.directory")
val buildTxt = if (SystemInfo.isMac) "Resources/build.txt" else "build.txt" // NON-NLS
for (name in listOf("bin", buildTxt)) {
if (!File(homeDir, name).exists()) {
return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.exists", name)
}
}
return null
}
private fun runUpdateScript(params: JavaParameters,
project: Project,
workIdeHome: String,
deployDirPath: String,
distRelativePath: String,
backupDir: String,
restartAutomatically: Boolean) {
val builtDistPath = "$deployDirPath/$distRelativePath"
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.text")
backupImportantFilesIfNeeded(workIdeHome, backupDir, indicator)
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.delete", builtDistPath)
FileUtil.delete(File(builtDistPath))
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.start.gant.script")
val commandLine = params.toCommandLine()
commandLine.isRedirectErrorStream = true
val scriptHandler = OSProcessHandler(commandLine)
val output = Collections.synchronizedList(ArrayList<@NlsSafe String>())
scriptHandler.addProcessListener(object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
output.add(event.text)
if (outputType == ProcessOutputTypes.STDOUT) {
indicator.text2 = event.text
}
}
override fun processTerminated(event: ProcessEvent) {
if (indicator.isCanceled) {
return
}
if (event.exitCode != 0) {
notificationGroup.createNotification(title = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.title"),
content = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.content",
event.exitCode),
type = NotificationType.ERROR)
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.output")) {
FileEditorManager.getInstance(project).openFile(LightVirtualFile("output.txt", output.joinToString("")), true)
})
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.debug.log")) {
val logFile = LocalFileSystem.getInstance().refreshAndFindFileByPath("$deployDirPath/log/debug.log") ?: return@createSimple // NON-NLS
logFile.refresh(true, false)
FileEditorManager.getInstance(project).openFile(logFile, true)
})
.notify(project)
return
}
if (!FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
startCopyingFiles(builtDistPath, workIdeHome, project)
return
}
val command = generateUpdateCommand(builtDistPath, workIdeHome)
if (restartAutomatically) {
ApplicationManager.getApplication().invokeLater { scheduleRestart(command, deployDirPath, project) }
}
else {
showRestartNotification(command, deployDirPath, project)
}
}
})
scriptHandler.startNotify()
while (!scriptHandler.isProcessTerminated) {
scriptHandler.waitFor(300)
indicator.checkCanceled()
}
}
}.queue()
}
private fun showRestartNotification(command: Array<String>, deployDirPath: String, project: Project) {
notificationGroup
.createNotification(DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.content"), NotificationType.INFORMATION)
.setListener(NotificationListener { _, _ -> restartWithCommand(command, deployDirPath) })
.notify(project)
}
private fun scheduleRestart(command: Array<String>, deployDirPath: String, project: Project) {
object : Task.Modal(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
var progress = 0
for (i in 10 downTo 1) {
indicator.text = DevKitBundle.message(
"action.UpdateIdeFromSourcesAction.progress.text.new.installation.prepared.ide.will.restart", i)
repeat(10) {
indicator.fraction = 0.01 * progress++
indicator.checkCanceled()
TimeoutUtil.sleep(100)
}
}
restartWithCommand(command, deployDirPath)
}
override fun onCancel() {
showRestartNotification(command, deployDirPath, project)
}
}.setCancelText(DevKitBundle.message("action.UpdateIdeFromSourcesAction.button.postpone")).queue()
}
private fun backupImportantFilesIfNeeded(workIdeHome: String,
backupDirPath: String,
indicator: ProgressIndicator) {
val backupDir = File(backupDirPath)
if (backupDir.exists()) {
LOG.debug("$backupDir already exists, skipping backup")
return
}
LOG.debug("Backing up files from $workIdeHome to $backupDir")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.backup.progress.text")
FileUtil.createDirectory(backupDir)
File(workIdeHome, "bin").listFiles()
?.filter { it.name !in safeToDeleteFilesInBin && it.extension !in safeToDeleteExtensions }
?.forEach { FileUtil.copy(it, File(backupDir, "bin/${it.name}")) }
File(workIdeHome).listFiles()
?.filter { it.name !in safeToDeleteFilesInHome }
?.forEach { FileUtil.copyFileOrDir(it, File(backupDir, it.name)) }
}
private fun startCopyingFiles(builtDistPath: String, workIdeHome: String, project: Project) {
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.progress.text")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.delete.old.files.text")
FileUtil.delete(File(workIdeHome))
indicator.checkCanceled()
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.copy.new.files.text")
FileUtil.copyDir(File(builtDistPath), File(workIdeHome))
indicator.checkCanceled()
Notification("Update from Sources", DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.title"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.content", workIdeHome),
NotificationType.INFORMATION).notify(project)
}
}.queue()
}
@Suppress("HardCodedStringLiteral")
private fun generateUpdateCommand(builtDistPath: String, workIdeHome: String): Array<String> {
if (SystemInfo.isWindows) {
val restartLogFile = File(PathManager.getLogPath(), "update-from-sources.log")
val updateScript = FileUtil.createTempFile("update", ".cmd", false)
val workHomePath = File(workIdeHome).absolutePath
/* deletion of the IDE files may fail to delete some executable files because they are still used by the IDE process,
so the script wait for some time and try to delete again;
'ping' command is used instead of 'timeout' because the latter doesn't work from batch files;
removal of the script file is performed in separate process to avoid errors while executing the script */
FileUtil.writeToFile(updateScript, """
@echo off
SET count=20
SET time_to_wait=1
:DELETE_DIR
RMDIR /Q /S "$workHomePath"
IF EXIST "$workHomePath" (
IF %count% GEQ 0 (
ECHO "$workHomePath" still exists, wait %time_to_wait%s and try delete again
SET /A time_to_wait=%time_to_wait%+1
PING 127.0.0.1 -n %time_to_wait% >NUL
SET /A count=%count%-1
ECHO %count% attempts remain
GOTO DELETE_DIR
)
ECHO Failed to delete "$workHomePath", IDE wasn't updated. You may delete it manually and copy files from "${File(builtDistPath).absolutePath}" by hand
GOTO CLEANUP_AND_EXIT
)
XCOPY "${File(builtDistPath).absolutePath}" "$workHomePath"\ /Q /E /Y
:CLEANUP_AND_EXIT
START /b "" cmd /c DEL /Q /F "${updateScript.absolutePath}" & EXIT /b
""".trimIndent())
return arrayOf("cmd", "/c", updateScript.absolutePath, ">${restartLogFile.absolutePath}", "2>&1")
}
val command = arrayOf(
"rm -rf \"$workIdeHome\"/*",
"cp -R \"$builtDistPath\"/* \"$workIdeHome\""
)
return arrayOf("/bin/sh", "-c", command.joinToString(" && "))
}
private fun restartWithCommand(command: Array<String>, deployDirPath: String) {
updatePlugins(deployDirPath)
Restarter.doNotLockInstallFolderOnRestart()
(ApplicationManager.getApplication() as ApplicationImpl).restart(ApplicationEx.FORCE_EXIT or ApplicationEx.EXIT_CONFIRMED or ApplicationEx.SAVE, command)
}
private fun updatePlugins(deployDirPath: String) {
val pluginsDir = Paths.get(deployDirPath).resolve("artifacts/${ApplicationInfo.getInstance().build.productCode}-plugins")
val pluginsXml = pluginsDir.resolve("plugins.xml")
if (!pluginsXml.isFile()) {
LOG.warn("Cannot read non-bundled plugins from $pluginsXml, they won't be updated")
return
}
val plugins = try {
pluginsXml.inputStream().reader().use {
MarketplaceRequests.parsePluginList(it)
}
}
catch (e: Exception) {
LOG.error("Failed to parse $pluginsXml", e)
return
}
val existingCustomPlugins =
PluginManagerCore.getLoadedPlugins().asSequence().filter { !it.isBundled }.associateBy { it.pluginId.idString }
LOG.debug("Existing custom plugins: $existingCustomPlugins")
val pluginsToUpdate =
plugins.mapNotNull { node -> existingCustomPlugins[node.pluginId.idString]?.let { it to node } }
for ((existing, update) in pluginsToUpdate) {
val pluginFile = pluginsDir.resolve(update.downloadUrl)
LOG.debug("Adding update command: ${existing.pluginPath} to $pluginFile")
PluginInstaller.installAfterRestart(pluginFile, false, existing.pluginPath, update)
}
}
private fun createScriptJavaParameters(devIdeaHome: String,
project: Project,
deployDir: String,
@Suppress("SameParameterValue") distRelativePath: String,
scriptFile: File,
buildEnabledPluginsOnly: Boolean,
bundledPluginDirsToSkip: List<String>,
nonBundledPluginDirsToInclude: List<String>): JavaParameters? {
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) {
LOG.warn("Project SDK is not defined")
return null
}
val params = JavaParameters()
params.isUseClasspathJar = true
params.setDefaultCharset(project)
params.jdk = sdk
params.mainClass = "org.codehaus.groovy.tools.GroovyStarter"
params.programParametersList.add("--classpath")
val buildScriptsModuleName = "intellij.idea.ultimate.build"
val buildScriptsModule = ModuleManager.getInstance(project).findModuleByName(buildScriptsModuleName)
if (buildScriptsModule == null) {
LOG.warn("Build scripts module $buildScriptsModuleName is not found in the project")
return null
}
val classpath = OrderEnumerator.orderEntries(buildScriptsModule)
.recursively().withoutSdk().runtimeOnly().productionOnly().classes().pathsList
val classesFromCoreJars = listOf(
params.mainClass,
"org.apache.tools.ant.BuildException", //ant
"org.apache.tools.ant.launch.AntMain", //ant-launcher
"org.apache.commons.cli.ParseException", //commons-cli
"groovy.util.CliBuilder", //groovy-cli-commons
"org.codehaus.groovy.runtime.NioGroovyMethods", //groovy-nio
)
val coreClassPath = classpath.rootDirs.filter { root ->
classesFromCoreJars.any { LibraryUtil.isClassAvailableInLibrary(listOf(root), it) }
}.mapNotNull { PathUtil.getLocalPath(it) }
params.classPath.addAll(coreClassPath)
coreClassPath.forEach { classpath.remove(FileUtil.toSystemDependentName(it)) }
params.programParametersList.add(classpath.pathsString)
params.programParametersList.add("--main")
params.programParametersList.add("gant.Gant")
params.programParametersList.add("--debug")
params.programParametersList.add("-Dsome_unique_string_42_239")
params.programParametersList.add("--file")
params.programParametersList.add(scriptFile.absolutePath)
params.programParametersList.add("update-from-sources")
params.vmParametersList.add("-D$includeBinAndRuntimeProperty=true")
params.vmParametersList.add("-Dintellij.build.bundled.jre.prefix=jbrsdk-")
if (buildEnabledPluginsOnly) {
if (bundledPluginDirsToSkip.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.bundled.plugin.dirs.to.skip=${bundledPluginDirsToSkip.joinToString(",")}")
}
val nonBundled = if (nonBundledPluginDirsToInclude.isNotEmpty()) nonBundledPluginDirsToInclude.joinToString(",") else "none"
params.vmParametersList.add("-Dintellij.build.non.bundled.plugin.dirs.to.include=$nonBundled")
}
if (!buildEnabledPluginsOnly || nonBundledPluginDirsToInclude.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.local.plugins.repository=true")
}
params.vmParametersList.add("-Dintellij.build.output.root=$deployDir")
params.vmParametersList.add("-DdistOutputRelativePath=$distRelativePath")
return params
}
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabledAndVisible = project != null && isIdeaProject(project)
}
private fun isIdeaProject(project: Project) = try {
DumbService.getInstance(project).computeWithAlternativeResolveEnabled<Boolean, RuntimeException> { PsiUtil.isIdeaProject(project) }
}
catch (e: IndexNotReadyException) {
false
}
}
private const val includeBinAndRuntimeProperty = "intellij.build.generate.bin.and.runtime.for.unpacked.dist"
internal class UpdateIdeFromSourcesSettingsAction : UpdateIdeFromSourcesAction(true)
@NonNls
private val safeToDeleteFilesInHome = setOf(
"bin", "help", "jre", "jre64", "jbr", "lib", "license", "plugins", "redist", "MacOS", "Resources",
"build.txt", "product-info.json", "Install-Linux-tar.txt", "Install-Windows-zip.txt", "ipr.reg"
)
@NonNls
private val safeToDeleteFilesInBin = setOf(
"append.bat", "appletviewer.policy", "format.sh", "format.bat",
"fsnotifier", "fsnotifier64",
"inspect.bat", "inspect.sh",
"restarter"
/*
"idea.properties",
"idea.sh",
"idea.bat",
"idea.exe.vmoptions",
"idea64.exe.vmoptions",
"idea.vmoptions",
"idea64.vmoptions",
"log.xml",
*/
)
@NonNls
private val safeToDeleteExtensions = setOf("exe", "dll", "dylib", "so", "ico", "svg", "png", "py")
| plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateIdeFromSourcesAction.kt | 1752945373 |
package test
class ClassWithAddedCompanionObject {
public fun unchangedFun() {}
companion object {}
}
class ClassWithRemovedCompanionObject {
public fun unchangedFun() {}
}
class ClassWithChangedCompanionObject {
public fun unchangedFun() {}
companion object SecondName {}
}
class ClassWithChangedVisibilityForCompanionObject {
public fun unchangedFun() {}
private companion object {}
}
| plugins/kotlin/jps/jps-plugin/tests/testData/comparison/classMembersOnlyChanged/classWithCompanionObjectChanged/new.kt | 618050536 |
package com.zeroami.commonlib.utils
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.media.RingtoneManager
import android.os.*
import android.view.View
import com.zeroami.commonlib.CommonLib
import java.io.Serializable
/**
* 不好分类的工具方法
*
* @author Zeroami
*/
object LUtils {
private val vibrator by lazy { CommonLib.ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator }
/**
* 复制文本到剪贴板
*/
fun copyToClipboard(text: String) {
if (Build.VERSION.SDK_INT >= 11) {
val cbm = CommonLib.ctx.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cbm.primaryClip = ClipData.newPlainText(CommonLib.ctx.packageName, text)
} else {
val cbm = CommonLib.ctx.getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
cbm.text = text
}
}
/**
* 判断事件点是否在控件内
*/
fun isTouchPointInView(view: View, x: Float, y: Float): Boolean {
val location = IntArray(2)
view.getLocationOnScreen(location)
val left = location[0]
val top = location[1]
val right = left + view.measuredWidth
val bottom = top + view.measuredHeight
if (y in top..bottom && x in left..right) {
return true
}
return false
}
/**
* 生成Extras
*/
fun generateExtras(vararg params: Pair<String, Any>): Bundle {
val extras = Bundle()
if (params.isNotEmpty()) {
params.forEach {
val value = it.second
when (value) {
is Int -> extras.putInt(it.first, value)
is Long -> extras.putLong(it.first, value)
is CharSequence -> extras.putCharSequence(it.first, value)
is String -> extras.putString(it.first, value)
is Float -> extras.putFloat(it.first, value)
is Double -> extras.putDouble(it.first, value)
is Char -> extras.putChar(it.first, value)
is Short -> extras.putShort(it.first, value)
is Boolean -> extras.putBoolean(it.first, value)
is Serializable -> extras.putSerializable(it.first, value)
is Bundle -> extras.putBundle(it.first, value)
is Parcelable -> extras.putParcelable(it.first, value)
is Array<*> -> when {
value.isArrayOf<CharSequence>() -> extras.putCharSequenceArray(it.first, value as Array<out CharSequence>?)
value.isArrayOf<String>() -> extras.putStringArray(it.first, value as Array<out String>?)
value.isArrayOf<Parcelable>() -> extras.putParcelableArray(it.first, value as Array<out Parcelable>?)
else -> throw RuntimeException("extras ${it.first} has wrong type ${value.javaClass.name}")
}
is IntArray -> extras.putIntArray(it.first, value)
is LongArray -> extras.putLongArray(it.first, value)
is FloatArray -> extras.putFloatArray(it.first, value)
is DoubleArray -> extras.putDoubleArray(it.first, value)
is CharArray -> extras.putCharArray(it.first, value)
is ShortArray -> extras.putShortArray(it.first, value)
is BooleanArray -> extras.putBooleanArray(it.first, value)
else -> throw RuntimeException("extra ${it.first} has wrong type ${value.javaClass.name}")
}
}
}
return extras
}
@SuppressLint("MissingPermission")
fun vibrate() {
if (isAndroidO()) {
vibrator.vibrate(VibrationEffect.createWaveform(longArrayOf(300, 300, 300), intArrayOf(VibrationEffect.DEFAULT_AMPLITUDE, 0, VibrationEffect.DEFAULT_AMPLITUDE), -1))
} else {
vibrator.vibrate(longArrayOf(0, 300, 300, 300), -1) // OFF/ON/OFF/ON
}
}
fun playRing() {
try {
val ringtone = RingtoneManager.getRingtone(CommonLib.ctx, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
ringtone.play()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun isAndroidO(): Boolean = Build.VERSION.SDK_INT >= 26
}
| commonlib/src/main/java/com/zeroami/commonlib/utils/LUtils.kt | 4054101188 |
/*
* Copyright 2010-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.ring
import org.jetbrains.benchmarksLauncher.Blackhole
open class ClassStreamBenchmark {
private var _data: Iterable<Value>? = null
val data: Iterable<Value>
get() = _data!!
init {
_data = classValues(BENCHMARK_SIZE)
}
//Benchmark
fun copy(): List<Value> {
return data.asSequence().toList()
}
//Benchmark
fun copyManual(): List<Value> {
val list = ArrayList<Value>()
for (item in data.asSequence()) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.asSequence().filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndMap() {
for (item in data.asSequence().filter { filterLoad(it) }.map { mapLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterAndMapManual() {
for (it in data.asSequence()) {
if (filterLoad(it)) {
val item = mapLoad(it)
Blackhole.consume(item)
}
}
}
//Benchmark
fun filter() {
for (item in data.asSequence().filter { filterLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterManual(){
for (it in data.asSequence()) {
if (filterLoad(it))
Blackhole.consume(it)
}
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data.asSequence()) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.asSequence().count { filterLoad(it) }
}
//Benchmark
// fun countFilteredLocal(): Int {
// return data.asSequence().cnt { filterLoad(it) }
// }
//Benchmark
fun reduce(): Int {
return data.asSequence().fold(0) {acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
} | performance/ring/src/main/kotlin/org/jetbrains/ring/ClassStreamBenchmark.kt | 1455386898 |
package com.github.kerubistan.kerub.utils
fun Boolean.flag(trueStr: String, falseStr: String = ""): String =
if (this) {
trueStr
} else {
falseStr
}
| src/main/kotlin/com/github/kerubistan/kerub/utils/Flags.kt | 475742802 |
// FIR_IDENTICAL
// FIR_COMPARISON
class A {
fun foo() {
bar()
}
}
class B {
fun bar() {
foo()
}
}
<caret>
// EXIST: abstract
// EXIST: class
// EXIST: class AfterClasses_LangLevel11
// EXIST: enum class
// EXIST: enum class AfterClasses_LangLevel11
// EXIST: final
// EXIST: fun
// EXIST: internal
// EXIST: object
// EXIST: object AfterClasses_LangLevel11
// EXIST: open
// EXIST: private
// EXIST: public
// EXIST: interface
// EXIST: interface AfterClasses_LangLevel11
// EXIST: val
// EXIST: var
// EXIST: operator
// EXIST: infix
// EXIST: sealed class
// EXIST: sealed class AfterClasses_LangLevel11
// EXIST: data class
// EXIST: { "lookupString":"data class", "itemText":"data class", "tailText":" AfterClasses_LangLevel11(...)", "attributes":"bold" }
// EXIST: inline
// EXIST: value
// EXIST: tailrec
// EXIST: external
// EXIST: annotation class
// EXIST: annotation class AfterClasses_LangLevel11
// EXIST: const val
// EXIST: suspend fun
// EXIST: typealias
// NOTHING_ELSE
| plugins/kotlin/completion/tests/testData/keywords/AfterClasses_LangLevel11.kt | 2849511966 |
// 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.configurationStore.schemeManager
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.configurationStore.*
import com.intellij.ide.ui.UITheme
import com.intellij.ide.ui.laf.TempUIThemeBasedLookAndFeelInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeProcessor
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.SafeWriteRequestor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.util.*
import com.intellij.util.containers.catch
import com.intellij.util.containers.mapSmart
import com.intellij.util.io.*
import com.intellij.util.text.UniqueNameGenerator
import org.jdom.Document
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Function
import java.util.function.Predicate
class SchemeManagerImpl<T: Scheme, MUTABLE_SCHEME : T>(val fileSpec: String,
processor: SchemeProcessor<T, MUTABLE_SCHEME>,
private val provider: StreamProvider?,
internal val ioDirectory: Path,
val roamingType: RoamingType = RoamingType.DEFAULT,
val presentableName: String? = null,
private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER,
private val fileChangeSubscriber: FileChangeSubscriber? = null,
private val virtualFileResolver: VirtualFileResolver? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor, StorageManagerFileWriteRequestor {
private val isUseVfs: Boolean
get() = fileChangeSubscriber != null || virtualFileResolver != null
internal val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER
private val isLoadingSchemes = AtomicBoolean()
internal val schemeListManager = SchemeListManager(this)
internal val schemes: MutableList<T>
get() = schemeListManager.schemes
internal var cachedVirtualDirectory: VirtualFile? = null
internal val schemeExtension: String
private val updateExtension: Boolean
internal val filesToDelete: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
internal val schemeToInfo = ConcurrentCollectionFactory.createConcurrentIdentityMap<T, ExternalInfo>()
init {
if (processor is SchemeExtensionProvider) {
schemeExtension = processor.schemeExtension
updateExtension = true
}
else {
schemeExtension = FileStorageCoreUtil.DEFAULT_EXT
updateExtension = false
}
if (isUseVfs) {
LOG.runAndLogException { refreshVirtualDirectory() }
}
}
override val rootDirectory: File
get() = ioDirectory.toFile()
override val allSchemeNames: Collection<String>
get() = schemes.mapSmart { processor.getSchemeKey(it) }
override val allSchemes: List<T>
get() = Collections.unmodifiableList(schemes)
override val isEmpty: Boolean
get() = schemes.isEmpty()
private fun refreshVirtualDirectory() {
// store refreshes root directory, so, we don't need to use refreshAndFindFile
val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return
cachedVirtualDirectory = directory
directory.children
if (directory is NewVirtualFile) {
directory.markDirty()
}
directory.refresh(true, false)
}
override fun loadBundledScheme(resourceName: String, requestor: Any?, pluginDescriptor: PluginDescriptor?) {
try {
val bytes: ByteArray
if (pluginDescriptor == null) {
when (requestor) {
is TempUIThemeBasedLookAndFeelInfo -> {
bytes = Files.readAllBytes(Path.of(resourceName))
}
is UITheme -> {
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"), requestor.providerClassLoader)
if (bytes == null) {
LOG.error("Cannot find $resourceName in ${requestor.providerClassLoader}")
return
}
}
else -> {
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"),
(if (requestor is ClassLoader) requestor else requestor!!.javaClass.classLoader))
if (bytes == null) {
LOG.error("Cannot read scheme from $resourceName")
return
}
}
}
}
else {
val classLoader = pluginDescriptor.classLoader
bytes = ResourceUtil.getResourceAsBytes(resourceName.removePrefix("/"), classLoader, true)
if (bytes == null) {
LOG.error("Cannot found scheme $resourceName in $classLoader")
return
}
}
lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val fileName = PathUtilRt.getFileName(resourceName)
val extension = getFileExtension(fileName, true)
val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension)
val schemeKey = name
?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension)
?: throw nameIsMissed(bytes)
externalInfo.schemeKey = schemeKey
val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(processor, bytes, externalInfo), schemeKey, attributeProvider, true)
val oldInfo = schemeToInfo.put(scheme, externalInfo)
LOG.assertTrue(oldInfo == null)
val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme)
if (oldScheme != null) {
LOG.warn("Duplicated scheme $schemeKey - old: $oldScheme, new $scheme")
}
schemes.add(scheme)
if (requestor is UITheme) {
requestor.editorSchemeName = schemeKey
}
if (requestor is TempUIThemeBasedLookAndFeelInfo) {
requestor.theme.editorSchemeName = schemeKey
}
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot read scheme from $resourceName", e)
}
}
internal fun createSchemeLoader(isDuringLoad: Boolean = false): SchemeLoader<T, MUTABLE_SCHEME> {
val filesToDelete = HashSet(filesToDelete)
// caller must call SchemeLoader.apply to bring back scheduled for delete files
this.filesToDelete.removeAll(filesToDelete)
// SchemeLoader can use retain list to bring back previously scheduled for delete file,
// but what if someone will call save() during load and file will be deleted, although should be loaded by a new load session
// (because modified on disk)
return SchemeLoader(this, schemes, filesToDelete, isDuringLoad)
}
internal fun getFileExtension(fileName: CharSequence, isAllowAny: Boolean): String {
return when {
StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension
StringUtilRt.endsWithIgnoreCase(fileName, FileStorageCoreUtil.DEFAULT_EXT) -> FileStorageCoreUtil.DEFAULT_EXT
isAllowAny -> PathUtil.getFileExtension(fileName.toString())!!
else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out")
}
}
override fun loadSchemes(): Collection<T> {
if (!isLoadingSchemes.compareAndSet(false, true)) {
throw IllegalStateException("loadSchemes is already called")
}
try {
// isDuringLoad is true even if loadSchemes called not first time, but on reload,
// because scheme processor should use cumulative event `reloaded` to update runtime state/caches
val schemeLoader = createSchemeLoader(isDuringLoad = true)
val isLoadOnlyFromProvider = provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly ->
catchAndLog({ "${provider.javaClass.name}: $name" }) {
val scheme = schemeLoader.loadScheme(name, input, null)
if (readOnly && scheme != null) {
schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme)
}
}
true
}
if (!isLoadOnlyFromProvider) {
if (virtualFileResolver == null) {
ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { directoryStream ->
for (file in directoryStream) {
catchAndLog({ file.toString() }) {
val bytes = try {
Files.readAllBytes(file)
}
catch (e: FileSystemException) {
when {
file.isDirectory() -> return@catchAndLog
else -> throw e
}
}
schemeLoader.loadScheme(file.fileName.toString(), null, bytes)
}
}
}
}
else {
for (file in getVirtualDirectory(StateStorageOperation.READ)?.children ?: VirtualFile.EMPTY_ARRAY) {
catchAndLog({ file.path }) {
if (canRead(file.nameSequence)) {
schemeLoader.loadScheme(file.name, null, file.contentsToByteArray())
}
}
}
}
}
val newSchemes = schemeLoader.apply()
for (newScheme in newSchemes) {
if (processPendingCurrentSchemeName(newScheme)) {
break
}
}
fileChangeSubscriber?.invoke(this)
return newSchemes
}
finally {
isLoadingSchemes.set(false)
}
}
override fun reload() {
processor.beforeReloaded(this)
// we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously)
// do not schedule scheme file removing because we just need to update our runtime state, not state on disk
removeExternalizableSchemesFromRuntimeState()
processor.reloaded(this, loadSchemes())
}
// method is used to reflect already performed changes on disk, so, `isScheduleToDelete = false` is passed to `retainExternalInfo`
internal fun removeExternalizableSchemesFromRuntimeState() {
// todo check is bundled/read-only schemes correctly handled
val iterator = schemes.iterator()
for (scheme in iterator) {
if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) {
continue
}
activeScheme?.let {
if (scheme === it) {
currentPendingSchemeName = processor.getSchemeKey(it)
activeScheme = null
}
}
iterator.remove()
@Suppress("UNCHECKED_CAST")
processor.onSchemeDeleted(scheme as MUTABLE_SCHEME)
}
retainExternalInfo(isScheduleToDelete = false)
}
internal fun getFileName(scheme: T) = schemeToInfo.get(scheme)?.fileNameWithoutExtension
fun canRead(name: CharSequence) = (updateExtension && name.endsWith(FileStorageCoreUtil.DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name))
override fun save(errors: MutableList<Throwable>) {
if (isLoadingSchemes.get()) {
LOG.warn("Skip save - schemes are loading")
}
var hasSchemes = false
val nameGenerator = UniqueNameGenerator()
val changedSchemes = SmartList<MUTABLE_SCHEME>()
for (scheme in schemes) {
val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme)
if (state == SchemeState.NON_PERSISTENT) {
continue
}
hasSchemes = true
if (state != SchemeState.UNCHANGED) {
@Suppress("UNCHECKED_CAST")
changedSchemes.add(scheme as MUTABLE_SCHEME)
}
val fileName = getFileName(scheme)
if (fileName != null && !isRenamed(scheme)) {
nameGenerator.addExistingName(fileName)
}
}
val filesToDelete = HashSet(filesToDelete)
for (scheme in changedSchemes) {
try {
saveScheme(scheme, nameGenerator, filesToDelete)
}
catch (e: Throwable) {
errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e))
}
}
if (filesToDelete.isNotEmpty()) {
val iterator = schemeToInfo.values.iterator()
for (info in iterator) {
if (filesToDelete.contains(info.fileName)) {
iterator.remove()
}
}
this.filesToDelete.removeAll(filesToDelete)
deleteFiles(errors, filesToDelete)
// remove empty directory only if some file was deleted - avoid check on each save
if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) {
removeDirectoryIfEmpty(errors)
}
}
}
private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) {
ioDirectory.directoryStreamIfExists {
for (file in it) {
if (!file.isHidden()) {
LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists")
return@removeDirectoryIfEmpty
}
}
}
LOG.info("Remove scheme directory ${ioDirectory.fileName}")
if (isUseVfs) {
val dir = getVirtualDirectory(StateStorageOperation.WRITE)
cachedVirtualDirectory = null
if (dir != null) {
runWriteAction {
try {
dir.delete(this)
}
catch (e: IOException) {
errors.add(e)
}
}
}
}
else {
errors.catch {
ioDirectory.delete()
}
}
}
private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator, filesToDelete: MutableSet<String>) {
var externalInfo: ExternalInfo? = schemeToInfo.get(scheme)
val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension
val element = processor.writeScheme(scheme)?.let { it as? Element ?: (it as Document).detachRootElement() }
if (JDOMUtil.isEmpty(element)) {
externalInfo?.scheduleDelete(filesToDelete, "empty")
return
}
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName(processor.getSchemeKey(scheme)))
}
val fileName = fileNameWithoutExtension + schemeExtension
// file will be overwritten, so, we don't need to delete it
filesToDelete.remove(fileName)
val newDigest = element!!.digest()
when {
externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return
isEqualToBundledScheme(externalInfo, newDigest, scheme, filesToDelete) -> return
// we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open)
processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> {
externalInfo?.scheduleDelete(filesToDelete, "equals to default")
return
}
}
// stream provider always use LF separator
val byteOut = element.toBufferExposingByteArray()
var providerPath: String?
if (provider != null && provider.enabled) {
providerPath = "$fileSpec/$fileName"
if (!provider.isApplicable(providerPath, roamingType)) {
providerPath = null
}
}
else {
providerPath = null
}
// if another new scheme uses old name of this scheme, we must not delete it (as part of rename operation)
@Suppress("SuspiciousEqualsCombination")
val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension)
if (providerPath == null) {
if (isUseVfs) {
var file: VirtualFile? = null
var dir = getVirtualDirectory(StateStorageOperation.WRITE)
if (dir == null || !dir.isValid) {
dir = createDir(ioDirectory, this)
cachedVirtualDirectory = dir
}
if (renamed) {
val oldFile = dir.findChild(externalInfo!!.fileName)
if (oldFile != null) {
// VFS doesn't allow to rename to existing file, so, check it
if (dir.findChild(fileName) == null) {
runWriteAction {
oldFile.rename(this, fileName)
}
file = oldFile
}
else {
externalInfo.scheduleDelete(filesToDelete, "renamed")
}
}
}
if (file == null) {
file = dir.getOrCreateChild(fileName, this)
}
runWriteAction {
file.getOutputStream(this).use { byteOut.writeTo(it) }
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size())
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType)
}
if (externalInfo == null) {
externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension)
schemeToInfo.put(scheme, externalInfo)
}
else {
externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension)
}
externalInfo.digest = newDigest
externalInfo.schemeKey = processor.getSchemeKey(scheme)
}
private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME, filesToDelete: MutableSet<String>): Boolean {
fun serializeIfPossible(scheme: T): Element? {
LOG.runAndLogException {
@Suppress("UNCHECKED_CAST")
val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null
return processor.writeScheme(bundledAsMutable) as Element
}
return null
}
val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme))
if (bundledScheme == null) {
if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false
if (bundledExternalInfo.digest == null) {
serializeIfPossible(bundledScheme)?.let {
bundledExternalInfo.digest = it.digest()
} ?: return false
}
if (bundledExternalInfo.isDigestEquals(newDigest)) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
private fun isRenamed(scheme: T): Boolean {
val info = schemeToInfo.get(scheme)
return info != null && processor.getSchemeKey(scheme) != info.schemeKey
}
private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) {
if (provider != null) {
val iterator = filesToDelete.iterator()
for (name in iterator) {
errors.catch {
val spec = "$fileSpec/$name"
if (provider.delete(spec, roamingType)) {
LOG.debug { "$spec deleted from provider $provider" }
iterator.remove()
}
}
}
}
if (filesToDelete.isEmpty()) {
return
}
LOG.debug { "Delete scheme files: ${filesToDelete.joinToString()}" }
if (isUseVfs) {
getVirtualDirectory(StateStorageOperation.WRITE)?.let { virtualDir ->
val childrenToDelete = virtualDir.children.filter { filesToDelete.contains(it.name) }
if (childrenToDelete.isNotEmpty()) {
runWriteAction {
for (file in childrenToDelete) {
errors.catch { file.delete(this) }
}
}
}
return
}
}
for (name in filesToDelete) {
errors.catch { ioDirectory.resolve(name).delete() }
}
}
internal fun getVirtualDirectory(reasonOperation: StateStorageOperation): VirtualFile? {
var result = cachedVirtualDirectory
if (result == null) {
val path = ioDirectory.systemIndependentPath
result = when (virtualFileResolver) {
null -> LocalFileSystem.getInstance().findFileByPath(path)
else -> virtualFileResolver.resolveVirtualFile(path, reasonOperation)
}
cachedVirtualDirectory = result
}
return result
}
override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Predicate<T>?) {
schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition)
}
internal fun retainExternalInfo(isScheduleToDelete: Boolean) {
if (schemeToInfo.isEmpty()) {
return
}
val iterator = schemeToInfo.entries.iterator()
l@ for ((scheme, info) in iterator) {
if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) === scheme) {
continue
}
for (s in schemes) {
if (s === scheme) {
filesToDelete.remove(info.fileName)
continue@l
}
}
iterator.remove()
if (isScheduleToDelete) {
info.scheduleDelete(filesToDelete, "requested to delete")
}
}
}
override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting)
override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName }
override fun removeScheme(name: String) = removeFirstScheme(true) { processor.getSchemeKey(it) == name }
override fun removeScheme(scheme: T) = removeScheme(scheme, isScheduleToDelete = true)
fun removeScheme(scheme: T, isScheduleToDelete: Boolean) = removeFirstScheme(isScheduleToDelete) { it === scheme } != null
override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme))
override fun toString() = fileSpec
internal fun removeFirstScheme(isScheduleToDelete: Boolean, condition: (T) -> Boolean): T? {
val iterator = schemes.iterator()
for (scheme in iterator) {
if (!condition(scheme)) {
continue
}
if (activeScheme === scheme) {
activeScheme = null
}
iterator.remove()
if (isScheduleToDelete && processor.isExternalizable(scheme)) {
schemeToInfo.remove(scheme)?.scheduleDelete(filesToDelete, "requested to delete (removeFirstScheme)")
}
return scheme
}
return null
}
} | platform/configuration-store-impl/src/schemeManager/SchemeManagerImpl.kt | 1540207862 |
// 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.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.explicateReceiverOf
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.util.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.parameter.to.receiver")
) {
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val parameterToMove = functionTypeParameterList.parameters.getOrNull(data.typeParameterIndex) ?: return
val typeReferenceToMove = parameterToMove.typeReference ?: return
functionType.setReceiverTypeReference(typeReferenceToMove)
functionTypeParameterList.removeParameter(parameterToMove)
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val argumentList = callExpression.valueArgumentList ?: return
val expressionToMove = argumentList.arguments.getOrNull(data.typeParameterIndex)?.getArgumentExpression() ?: return
val callWithReceiver =
KtPsiFactory(callExpression).createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression
(callWithReceiver.selectorExpression as KtCallExpression).valueArgumentList!!.removeArgument(data.typeParameterIndex)
callExpression.replace(callWithReceiver)
}
}
class InternalReferencePassInfo(element: KtSimpleNameExpression) :
AbstractProcessableUsageInfo<KtSimpleNameExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val lambdaType = data.lambdaType
val validator = CollectingNameValidator()
val parameterNames = lambdaType.arguments
.dropLast(1)
.map { KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() }
val receiver = parameterNames.getOrNull(data.typeParameterIndex) ?: return
val arguments = parameterNames.filter { it != receiver }
val adapterLambda = KtPsiFactory(expression).createLambdaExpression(
parameterNames.joinToString(),
"$receiver.${expression.text}(${arguments.joinToString()})"
)
expression.replaced(adapterLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
}
class LambdaInfo(element: KtExpression) : AbstractProcessableUsageInfo<KtExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(expression)
if (expression is KtLambdaExpression || (expression !is KtSimpleNameExpression && expression !is KtCallableReferenceExpression)) {
expression.forEachDescendantOfType<KtThisExpression> {
if (it.getLabelName() != null) return@forEachDescendantOfType
val descriptor = context[BindingContext.REFERENCE_TARGET, it.instanceReference] ?: return@forEachDescendantOfType
it.replace(psiFactory.createExpression(explicateReceiverOf(descriptor)))
}
}
if (expression is KtLambdaExpression) {
expression.valueParameters.getOrNull(data.typeParameterIndex)?.let { parameterToConvert ->
val thisRefExpr = psiFactory.createThisExpression()
for (ref in ReferencesSearch.search(parameterToConvert, LocalSearchScope(expression))) {
(ref.element as? KtSimpleNameExpression)?.replace(thisRefExpr)
}
val lambda = expression.functionLiteral
lambda.valueParameterList!!.removeParameter(parameterToConvert)
if (lambda.valueParameters.isEmpty()) {
lambda.arrow?.delete()
}
}
return
}
val originalLambdaTypes = data.lambdaType
val originalParameterTypes = originalLambdaTypes.arguments.dropLast(1).map { it.type }
val calleeText = when (expression) {
is KtSimpleNameExpression -> expression.text
is KtCallableReferenceExpression -> "(${expression.text})"
else -> generateVariable(expression)
}
val parameterNameValidator = CollectingNameValidator(
if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList()
)
val parameterNamesWithReceiver = originalParameterTypes.mapIndexed { i, type ->
if (i != data.typeParameterIndex) KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p")
.first() else "this"
}
val parameterNames = parameterNamesWithReceiver.filter { it != "this" }
val body = psiFactory.createExpression(parameterNamesWithReceiver.joinToString(prefix = "$calleeText(", postfix = ")"))
val replacingLambda = psiFactory.buildExpression {
appendFixedText("{ ")
appendFixedText(parameterNames.joinToString())
appendFixedText(" -> ")
appendExpression(body)
appendFixedText(" }")
} as KtLambdaExpression
expression.replaced(replacingLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
private fun generateVariable(expression: KtExpression): String {
var baseCallee = ""
KotlinIntroduceVariableHandler.doRefactoring(project, null, expression, false, emptyList()) {
baseCallee = it.name!!
}
return baseCallee
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?
) : CallableRefactoring<CallableDescriptor>(data.function.project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
usageLoop@ for (ref in callable.searchReferencesOrMethodReferences()) {
val refElement = ref.element
when (ref) {
is KtSimpleReference<*> -> processExternalUsage(conflicts, refElement, usages)
is KtReference -> continue@usageLoop
else -> {
if (data.isFirstParameter) continue@usageLoop
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.non.kotlin.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
if (callable is KtFunction) {
usages += FunctionDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
conflicts: MultiMap<PsiElement, String>,
refElement: PsiElement,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val callElement = refElement.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = getArgumentExpressionToProcess(callElement, context) ?: return
if (!data.isFirstParameter
&& callElement is KtConstructorDelegationCall
&& expressionToProcess !is KtLambdaExpression
&& expressionToProcess !is KtSimpleNameExpression
&& expressionToProcess !is KtCallableReferenceExpression
) {
conflicts.putValue(
expressionToProcess,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
expressionToProcess.text
)
)
return
}
if (!checkThisExpressionsAreExplicatable(conflicts, context, expressionToProcess)) return
if (data.isFirstParameter && expressionToProcess !is KtLambdaExpression) return
usages += LambdaInfo(expressionToProcess)
return
}
if (data.isFirstParameter) return
val callableReference = refElement.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }
if (callableReference != null) {
conflicts.putValue(
refElement,
KotlinBundle.message(
"callable.reference.transformation.is.not.supported.0",
StringUtil.htmlEmphasize(callableReference.text)
)
)
return
}
}
private fun getArgumentExpressionToProcess(callElement: KtCallElement, context: BindingContext): KtExpression? {
return callElement
.getArgumentByParameterIndex(data.functionParameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
}
private fun checkThisExpressionsAreExplicatable(
conflicts: MultiMap<PsiElement, String>,
context: BindingContext,
expressionToProcess: KtExpression
): Boolean {
for (thisExpr in expressionToProcess.collectDescendantsOfType<KtThisExpression>()) {
if (thisExpr.getLabelName() != null) continue
val descriptor = context[BindingContext.REFERENCE_TARGET, thisExpr.instanceReference] ?: continue
if (explicateReceiverOf(descriptor) == "this") {
conflicts.putValue(
thisExpr,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
thisExpr.text
)
)
return false
}
}
return true
}
private fun processInternalUsages(callable: KtFunction, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>) {
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
else -> callable.bodyExpression
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(data.functionParameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }
if (callExpression != null) {
usages += ParameterCallInfo(callExpression)
} else if (!data.isFirstParameter) {
usages += InternalReferencePassInfo(element)
}
}
}
}
}
class ConversionData(
val typeParameterIndex: Int,
val functionParameterIndex: Int,
val lambdaType: KotlinType,
val function: KtFunction
) {
val isFirstParameter: Boolean get() = typeParameterIndex == 0
val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor }
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val parameter = parent as? KtParameter ?: return null
val functionType = parameter.getParentOfTypeAndBranch<KtFunctionType> { parameterList } ?: return null
if (functionType.receiverTypeReference != null) return null
val lambdaType = functionType.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) ?: return null
val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null
val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null
val typeParameterIndex = functionType.parameters.indexOf(parameter)
val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter)
return ConversionData(typeParameterIndex, functionParameterIndex, lambdaType, ownerFunction)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType
val elementAfter = elementBefore.copied().apply {
setReceiverTypeReference(element)
parameterList!!.removeParameter(data.typeParameterIndex)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor).run() }
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt | 2477485334 |
fun check() {
1.0.toString()<caret>.toString()
}
// SET_FALSE: CONTINUATION_INDENT_FOR_CHAINED_CALLS | plugins/kotlin/idea/tests/testData/editor/enterHandler/beforeDot/FloatLiteralInFirstPosition2.kt | 968822253 |
package com.github.pockethub.android.ui.helpers
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.pockethub.android.R
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.xwray.groupie.Item
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
class ListFetcher<E>(
private val swipeRefreshLayout: SwipeRefreshLayout?,
private val lifecycle: Lifecycle,
private val itemListHandler: ItemListHandler,
private val showError: (Throwable) -> Unit,
private val loadData: (force: Boolean) -> Single<List<E>>,
private val createItem: (item: E) -> Item<*>
): LifecycleObserver {
/**
* Disposable for data load request.
*/
private var dataLoadDisposable: Disposable = Disposables.disposed()
private var isLoading = false
var onDataLoaded: (MutableList<Item<*>>) -> MutableList<Item<*>> = { items -> items }
init {
lifecycle.addObserver(this)
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setOnRefreshListener(this::forceRefresh)
swipeRefreshLayout.setColorSchemeResources(
R.color.pager_title_background_top_start,
R.color.pager_title_background_end,
R.color.text_link,
R.color.pager_title_background_end)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onStart() {
refresh()
}
private fun refresh(force: Boolean) {
if (isLoading) {
return
}
if (!dataLoadDisposable.isDisposed) {
dataLoadDisposable.dispose()
}
isLoading = true
dataLoadDisposable = loadData(force)
.flatMap { items ->
Observable.fromIterable<E>(items)
.map<Item<*>> { this.createItem(it) }
.toList()
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle<MutableList<Item<*>>>(lifecycle))
.subscribe(
{ this.onLoadFinished(it) },
{ this.onDataLoadError(it) }
)
}
fun refresh() {
refresh(false)
}
fun forceRefresh() {
swipeRefreshLayout!!.isRefreshing = true
refresh(true)
}
/**
* Called when the data has loaded.
*
* @param newItems The items added to the list.
*/
private fun onLoadFinished(newItems: MutableList<Item<*>>) {
isLoading = false
swipeRefreshLayout!!.isRefreshing = false
val items = onDataLoaded(newItems)
itemListHandler.update(items)
}
private fun onDataLoadError(throwable: Throwable) {
isLoading = false
swipeRefreshLayout!!.isRefreshing = false
showError(throwable)
}
} | app/src/main/java/com/github/pockethub/android/ui/helpers/ListFetcher.kt | 3875222248 |
// 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.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.wizard.core.YamlParsingError
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.parser.ParserException
import java.nio.file.Path
@Suppress("HardCodedStringLiteral")
class YamlSettingsParser(settings: List<PluginSetting<Any, *>>, private val parsingState: ParsingState) {
private val settingByName = settings.associateBy { it.path }
fun parseYamlText(yaml: String): TaskResult<Map<SettingReference<*, *>, Any>> {
val yamlObject = try {
Success(Yaml().load<Any>(yaml) ?: emptyMap<String, Any>())
} catch (e: ParserException) {
Failure(YamlParsingError(e))
} catch (e: Exception) {
Failure(ExceptionErrorImpl(e))
}
return yamlObject.flatMap { map ->
if (map is Map<*, *>) {
val result = ComputeContext.runInComputeContextWithState(parsingState) {
parseSettingValues(map, "")
}
result.map { (pluginSettings, newState) ->
pluginSettings + newState.settingValues
}
} else Failure(
BadSettingValueError("Settings file should be a map of settings")
)
}
}
fun parseYamlFile(file: Path) = computeM {
val (yaml) = safe { file.toFile().readText() }
parseYamlText(yaml)
}
private fun ParsingContext.parseSettingValues(
data: Any,
settingPath: String
): TaskResult<Map<PluginSettingReference<*, *>, Any>> =
if (settingPath in settingByName) compute {
val setting = settingByName.getValue(settingPath)
val (parsed) = setting.type.parse(this, data, settingPath)
listOf(PluginSettingReference(setting) to parsed)
} else {
when (data) {
is Map<*, *> -> {
data.entries.mapCompute { (name, value) ->
if (value == null) fail(BadSettingValueError("No value was found for a key `$settingPath`"))
val prefix = if (settingPath.isEmpty()) "" else "$settingPath."
val (children) = parseSettingValues(value, "$prefix$name")
children.entries.map { (key, value) -> key to value }
}.sequence().map { it.flatten() }
}
else -> Failure(
BadSettingValueError("No value was found for a key `$settingPath`")
)
}
}.map { it.toMap() }
} | plugins/kotlin/project-wizard/cli/src/org/jetbrains/kotlin/tools/projectWizard/YamlSettingsParser.kt | 2031008226 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// FIR_IDENTICAL
// FIR_COMPARISON
interface Base {
fun inBase()
}
interface I1 : Base {
fun inI1()
}
interface I2 : I1 {
fun inI2()
}
fun foo(i1: I1, i2: I2) {
with(i1) {
with(i2) {
<caret>
}
}
}
// EXIST: { lookupString: "inI1", attributes: "bold", icon: "nodes/abstractMethod.svg"}
// EXIST: { lookupString: "inI2", attributes: "bold", icon: "nodes/abstractMethod.svg"}
// EXIST: { lookupString: "inBase", attributes: "", icon: "nodes/abstractMethod.svg"}
// EXIST: { lookupString: "equals", attributes: "", icon: "Method"}
| plugins/kotlin/completion/testData/basic/common/boldOrGrayed/TwoReceivers.kt | 2887262499 |
package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.codeInsight.hints.presentation.MouseButton
import com.intellij.codeInsight.hints.presentation.mouseButton
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl
import com.intellij.util.asSafely
import org.jetbrains.plugins.notebooks.visualization.NotebookCellInlayManager
import org.jetbrains.plugins.notebooks.ui.visualization.notebookAppearance
import org.jetbrains.plugins.notebooks.visualization.outputs.hoveredCollapsingComponentRect
import java.awt.BorderLayout
import java.awt.Cursor
import java.awt.Point
import javax.swing.JComponent
import javax.swing.SwingUtilities
private class OutputCollapsingGutterMouseListener : EditorMouseListener, EditorMouseMotionListener {
private val EditorMouseEvent.notebookEditor: EditorEx?
get() = editor.takeIf { NotebookCellInlayManager.get(it) != null } as? EditorEx
override fun mousePressed(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
val gutterComponentEx = editor.gutterComponentEx
val point = e.mouseEvent.takeIf { it.component === gutterComponentEx }?.point ?: return
if (!isAtCollapseVerticalStripe(editor, point)) return
val component = gutterComponentEx.hoveredCollapsingComponentRect ?: return
val actionManager = ActionManager.getInstance()
when (e.mouseEvent.mouseButton) {
MouseButton.Left -> {
e.consume()
val action = actionManager.getAction(NotebookOutputCollapseSingleInCellAction::class.java.simpleName)!!
actionManager.tryToExecute(action, e.mouseEvent, component, ActionPlaces.EDITOR_GUTTER_POPUP, true)
SwingUtilities.invokeLater { // Being invoked without postponing, it would access old states of layouts and get the same results.
if (!editor.isDisposed) {
updateState(editor, point)
}
}
}
MouseButton.Right -> {
e.consume()
val group = actionManager.getAction("NotebookOutputCollapseActions")
if (group is ActionGroup) {
val menu = actionManager.createActionPopupMenu(ActionPlaces.EDITOR_GUTTER_POPUP, group)
menu.setTargetComponent(component)
menu.component.show(gutterComponentEx, e.mouseEvent.x, e.mouseEvent.y)
}
}
else -> Unit
}
}
override fun mouseExited(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
updateState(editor, null)
}
override fun mouseMoved(e: EditorMouseEvent) {
val editor = e.notebookEditor ?: return
updateState(editor, e.mouseEvent.point)
}
private fun updateState(editor: EditorEx, point: Point?) {
val gutterComponentEx = editor.gutterComponentEx
if (point == null || !isAtCollapseVerticalStripe(editor, point)) {
IdeGlassPaneImpl.forgetPreProcessedCursor(gutterComponentEx)
gutterComponentEx.cursor = @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") null // Huh? It's a valid operation!
updateHoveredComponent(gutterComponentEx, null)
}
else {
val collapsingComponent = getCollapsingComponent(editor, point)
updateHoveredComponent(gutterComponentEx, collapsingComponent)
if (collapsingComponent != null) {
val cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
IdeGlassPaneImpl.savePreProcessedCursor(gutterComponentEx, cursor)
gutterComponentEx.cursor = cursor
}
else {
IdeGlassPaneImpl.forgetPreProcessedCursor(gutterComponentEx)
}
}
}
private fun isAtCollapseVerticalStripe(editor: EditorEx, point: Point): Boolean =
if ((editor as EditorImpl).isMirrored) {
val margin = editor.notebookAppearance.LINE_NUMBERS_MARGIN / 2
CollapsingComponent.collapseRectHorizontalLeft(editor).let {
point.x in it - margin until it + CollapsingComponent.COLLAPSING_RECT_WIDTH - margin
}
}
else {
CollapsingComponent.collapseRectHorizontalLeft(editor).let {
point.x in it until it + CollapsingComponent.COLLAPSING_RECT_WIDTH
}
}
private fun getCollapsingComponent(editor: EditorEx, point: Point): CollapsingComponent? {
val surroundingX = if ((editor as EditorImpl).isMirrored) 80 else 0
val surroundingComponent =
editor.contentComponent.getComponentAt(surroundingX, point.y)
.asSafely<JComponent>()
?.takeIf { it.componentCount > 0 }
?.getComponent(0)
?.asSafely<SurroundingComponent>()
?: return null
val innerComponent =
(surroundingComponent.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER).asSafely<InnerComponent>()
?: return null
val y = point.y - SwingUtilities.convertPoint(innerComponent, 0, 0, editor.contentComponent).y
val collapsingComponent =
innerComponent.getComponentAt(0, y).asSafely<CollapsingComponent>()
?: return null
if (!collapsingComponent.isWorthCollapsing) return null
return collapsingComponent
}
private fun updateHoveredComponent(gutterComponentEx: EditorGutterComponentEx, collapsingComponent: CollapsingComponent?) {
val old = gutterComponentEx.hoveredCollapsingComponentRect
if (old !== collapsingComponent) {
gutterComponentEx.hoveredCollapsingComponentRect = collapsingComponent
gutterComponentEx.repaint()
}
}
} | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/OutputCollapsingGutterMouseListener.kt | 668707229 |
package org.jetbrains.spek.tooling.runner
/**
* @author Ranie Jade Ramiso
*/
data class TestExecutionResult(val status: Status, val duration: Long, val throwable: Throwable? = null) {
enum class Status {
Success,
Failure,
Aborted
}
}
| tooling/src/main/kotlin/org/jetbrains/spek/tooling/runner/TestExecutionResult.kt | 1304280150 |
package com.github.psxpaul.util
import org.gradle.api.GradleException
import java.net.*
import java.util.concurrent.TimeUnit
/**
* Find a random port that is available to listen on
* @return a port number that is available
*/
fun findOpenPort(): Int {
ServerSocket(0).use { return it.localPort }
}
/**
* Check if a given port is in use
* @param port the port number to check
* @return true if the port is open, false otherwise
*/
private fun isPortOpen(port: Int): Boolean {
Socket().use {
val inetAddress: InetAddress = InetAddress.getByName("127.0.0.1")
val socketAddress: InetSocketAddress = InetSocketAddress(inetAddress, port)
return try {
it.connect(socketAddress)
true
} catch (e: ConnectException) {
false
}
}
}
/**
* Wait for a given amount of time for a port to be opened locally, by a given
* process. This method will poll every 100 ms and try to connect to the port. If
* the amount of time is reached and the port is not yet open, a GradleException
* is thrown. If the given process terminates before the port is open, a
* GradleException is thrown.
*
* @param port the port number to check
* @param timeout the maximum number of TimeUnits to wait
* @param unit the unit of time to wait
* @param process the process to monitor for early termination
*
* @throws GradleException when the timeout has elapsed and the port is still
* not open, OR the given process has terminated before the port is
* opened (whichever occurs first)
*/
fun waitForPortOpen(port: Int, timeout: Long, unit: TimeUnit, process: Process) {
val millisToWait: Long = unit.toMillis(timeout)
val waitUntil: Long = System.currentTimeMillis() + millisToWait
while (System.currentTimeMillis() < waitUntil) {
Thread.sleep(100)
if (!process.isAlive) throw GradleException("Process died before port $port was opened")
if (isPortOpen(port)) return
}
throw GradleException("Timed out waiting for port $port to be opened")
}
| src/main/kotlin/com/github/psxpaul/util/PortUtils.kt | 1222252487 |
// "Create member function 'A.foo'" "true"
// ERROR: Unresolved reference: foo
fun test(): Int? {
return A().foo(1, "2")
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/funOnJavaType.after.kt | 2532070921 |
fun foo(
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Boolean
): Int {
when {
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -> {<caret>
return 1
}
else -> return 2
}
} | plugins/kotlin/idea/tests/testData/intentions/removeBraces/whenLong.kt | 3617564381 |
fun some() {
while(true) {
}
do {
} while(true)
}
// SET_FALSE: SPACE_BEFORE_WHILE_PARENTHESES | plugins/kotlin/idea/tests/testData/formatter/SpaceBeforeWhileParentheses.after.kt | 2823752718 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.navigationToolbar.experimental
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.lang.Integer.min
import javax.swing.JComponent
class NewToolbarBorderLayout : BorderLayout() {
private var lastTarget: Container? = null
private val componentListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
layoutContainer(lastTarget)
}
override fun componentMoved(e: ComponentEvent?) {
layoutContainer(lastTarget)
}
}
override fun addLayoutComponent(comp: Component?, constraints: Any?) {
super.addLayoutComponent(comp, constraints)
if (comp is JComponent) {
comp.components.forEach { it.addComponentListener(componentListener) }
}
comp?.addComponentListener(componentListener)
}
override fun layoutContainer(target: Container?) {
synchronized(target!!.treeLock) {
lastTarget = target
val insets = target.insets
var top = insets.top
var bottom = target.height - insets.bottom
var left = insets.left
var right = target.width - insets.right
var c: Component?
if (getLayoutComponent(EAST).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setSize(c!!.width, bottom - top)
c!!.setBounds(right - d.width, top + hdiff, d.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(CENTER).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setBounds(right - c!!.preferredSize.width, top + hdiff, c!!.preferredSize.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(WEST).also { c = it } != null) {
val d = c!!.preferredSize
var hdiff = 0
if (target.height > 0 && d.height > 0) {
hdiff = (target.height - d.height) / 2
}
c!!.setBounds(left, top + hdiff, min(d.width, right), bottom - top)
left += d.width + hgap
}
}
}
} | platform/lang-impl/src/com/intellij/ide/navigationToolbar/experimental/NewToolbarBorderLayout.kt | 2233638978 |
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.di.module
import com.zwq65.unity.di.ActivityScoped
import com.zwq65.unity.ui.activity.*
import com.zwq65.unity.ui.module.*
import com.zwq65.unity.ui.provider.*
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* We want Dagger.Android to create a Subcomponent which has a parent Component of whichever module ActivityBindingModule is on,
* in our case that will be AppComponent. The beautiful part about this setup is that you never need to tell AppComponent
* that it is going to have all these subcomponents
* nor do you need to tell these subcomponents that AppComponent exists.
* We are also telling Dagger.Android that this generated SubComponent needs to include the specified modules
* and be aware of a scope annotation @ActivityScoped
* When Dagger.Android annotation processor runs it will create 4 subcomponents for us.
*/
@Module
abstract class ActivityModule {
@ActivityScoped
@ContributesAndroidInjector(modules = [(MainModule::class), (AlbumProvider::class), (RestVideoProvider::class), (TestProvider::class), (ArticleProvider::class), (TabArticleProvider::class)])
internal abstract fun mainActivity(): MainActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(AccountModule::class)])
internal abstract fun accountActivity(): AccountActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(ImageModule::class)])
internal abstract fun imageActivity(): ImageActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(LoginModule::class)])
internal abstract fun loginActivity(): LoginActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(WebArticleModule::class)])
internal abstract fun webArticleActivity(): WebArticleActivity
@ActivityScoped
@ContributesAndroidInjector(modules = [(WatchModule::class)])
internal abstract fun watchActivity(): WatchActivity
}
| app/src/main/java/com/zwq65/unity/di/module/ActivityModule.kt | 2507330556 |
/*
* Copyright 2017, 2018 Nikola Trubitsyn
*
* 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.trubitsyn.visiblefortesting
import org.trubitsyn.visiblefortesting.intention.AnnotateKtClassOrObjectMethodsIntention
import org.junit.Test
class AnnotateKtClassOrObjectMethodsIntentionTest : AbstractIntentionTest(AnnotateKtClassOrObjectMethodsIntention()) {
@Test
fun testAndroid() {
runTest("AndroidVisibleForTesting.java",
"android/before.template.kt",
"android/before.template.after.kt")
}
@Test
fun testGuava() {
runTest("GuavaVisibleForTesting.java",
"guava/before.template.kt",
"guava/before.template.after.kt")
}
@Test
fun testObjectGuava() {
runTest("GuavaVisibleForTesting.java",
"guava/before.object.template.kt",
"guava/before.object.template.after.kt")
}
fun testObjectAndroid() {
runTest("AndroidVisibleForTesting.java",
"android/before.object.template.kt",
"android/before.object.template.after.kt")
}
}
| src/test/kotlin/org/trubitsyn/visiblefortesting/AnnotateKtClassOrObjectMethodsIntentionTest.kt | 1186158415 |
package com.gallery.ui.material.activity
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bumptech.glide.Glide
import com.gallery.compat.activity.PrevCompatActivity
import com.gallery.compat.extensions.requirePrevFragment
import com.gallery.compat.widget.GalleryImageView
import com.gallery.core.GalleryBundle
import com.gallery.core.delegate.IPrevDelegate
import com.gallery.core.entity.ScanEntity
import com.gallery.core.extensions.drawableExpand
import com.gallery.core.extensions.safeToastExpand
import com.gallery.ui.material.R
import com.gallery.ui.material.args.MaterialGalleryBundle
import com.gallery.ui.material.databinding.MaterialGalleryActivityPreviewBinding
import com.gallery.ui.material.materialGalleryArgOrDefault
open class MaterialPreActivity : PrevCompatActivity() {
companion object {
private const val format = "%s / %s"
}
private val viewBinding: MaterialGalleryActivityPreviewBinding by lazy {
MaterialGalleryActivityPreviewBinding.inflate(layoutInflater)
}
private val materialGalleryBundle: MaterialGalleryBundle by lazy {
gapConfig.materialGalleryArgOrDefault
}
override val galleryFragmentId: Int
get() = R.id.preFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
window.statusBarColor = materialGalleryBundle.statusBarColor
viewBinding.toolbar.setTitleTextColor(materialGalleryBundle.toolbarTextColor)
val drawable = drawableExpand(materialGalleryBundle.toolbarIcon)
drawable?.colorFilter =
PorterDuffColorFilter(materialGalleryBundle.toolbarIconColor, PorterDuff.Mode.SRC_ATOP)
viewBinding.toolbar.navigationIcon = drawable
viewBinding.toolbar.setBackgroundColor(materialGalleryBundle.toolbarBackground)
viewBinding.toolbar.elevation = materialGalleryBundle.toolbarElevation
viewBinding.count.textSize = materialGalleryBundle.preBottomCountTextSize
viewBinding.count.setTextColor(materialGalleryBundle.preBottomCountTextColor)
viewBinding.bottomView.setBackgroundColor(materialGalleryBundle.preBottomViewBackground)
viewBinding.bottomViewSelect.text = materialGalleryBundle.preBottomOkText
viewBinding.bottomViewSelect.textSize = materialGalleryBundle.preBottomOkTextSize
viewBinding.bottomViewSelect.setTextColor(materialGalleryBundle.preBottomOkTextColor)
viewBinding.bottomViewSelect.setOnClickListener {
if (requirePrevFragment.isSelectEmpty) {
onGallerySelectEmpty()
} else {
onGallerySelectEntities()
}
}
viewBinding.toolbar.setNavigationOnClickListener { onGalleryFinish() }
}
override fun onDisplayGalleryPrev(scanEntity: ScanEntity, container: FrameLayout) {
container.removeAllViews()
val imageView = GalleryImageView(container.context).apply {
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
).apply {
gravity = Gravity.CENTER
}
}
Glide.with(container.context)
.load(scanEntity.uri)
.into(imageView)
container.addView(imageView)
}
override fun onPrevCreated(
delegate: IPrevDelegate,
bundle: GalleryBundle,
savedInstanceState: Bundle?
) {
delegate.rootView.setBackgroundColor(materialGalleryBundle.prevRootBackground)
viewBinding.count.text =
format.format(delegate.selectCount, galleryConfig.multipleMaxCount)
viewBinding.toolbar.title =
materialGalleryBundle.preTitle + "(" + (delegate.currentPosition + 1) + "/" + delegate.itemCount + ")"
}
override fun onClickItemFileNotExist(
context: Context,
bundle: GalleryBundle,
scanEntity: ScanEntity
) {
super.onClickItemFileNotExist(context, bundle, scanEntity)
viewBinding.count.text =
format.format(requirePrevFragment.selectCount, bundle.multipleMaxCount)
}
override fun onPageSelected(position: Int) {
viewBinding.toolbar.title =
materialGalleryBundle.preTitle + "(" + (position + 1) + "/" + requirePrevFragment.itemCount + ")"
}
override fun onChangedCheckBox() {
viewBinding.count.text =
format.format(requirePrevFragment.selectCount, galleryConfig.multipleMaxCount)
}
open fun onGallerySelectEmpty() {
getString(R.string.material_gallery_prev_select_empty_pre).safeToastExpand(this)
}
} | material/src/main/java/com/gallery/ui/material/activity/MaterialPreActivity.kt | 1570140953 |
package ch.rmy.android.http_shortcuts.activities.main.usecases
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.main.ShortcutListViewModel
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.extensions.createDialogState
import javax.inject.Inject
class GetShortcutDeletionDialogUseCase
@Inject
constructor() {
operator fun invoke(shortcutId: ShortcutId, title: Localizable, viewModel: ShortcutListViewModel) =
createDialogState {
title(title)
.message(R.string.confirm_delete_shortcut_message)
.positive(R.string.dialog_delete) {
viewModel.onDeletionConfirmed(shortcutId)
}
.negative(R.string.dialog_cancel)
.build()
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/main/usecases/GetShortcutDeletionDialogUseCase.kt | 129028240 |
/*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.testFramework.utils.inlays
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.util.TextRange
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.testFramework.VfsTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import junit.framework.ComparisonFailure
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import java.util.regex.Pattern
class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) {
private var isParamHintsEnabledBefore = false
companion object {
val pattern: Pattern = Pattern.compile("(<caret>)|(<selection>)|(</selection>)|<(hint|HINT|Hint|hINT)\\s+text=\"([^\"\n\r]+)\"\\s*/>")
private val default = ParameterNameHintsSettings()
}
fun setUp() {
val settings = EditorSettingsExternalizable.getInstance()
isParamHintsEnabledBefore = settings.isShowParameterNameHints
settings.isShowParameterNameHints = true
}
fun tearDown() {
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore
val hintSettings = ParameterNameHintsSettings.getInstance()
hintSettings.loadState(default.state)
}
fun checkInlays() {
val file = myFixture.file
val document = myFixture.getDocument(file)
val originalText = document.text
val expectedInlaysAndCaret = extractInlaysAndCaretInfo(document)
myFixture.doHighlighting()
verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText)
}
fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo, originalText: String) {
val file = myFixture.file
val document = myFixture.getDocument(file)
val actual: List<ParamHintInfo> = getActualInlays()
val expected = expectedInlaysAndCaret.inlays
if (expectedInlaysAndCaret.inlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) {
val entries: MutableList<Pair<Int, String>> = mutableListOf()
actual.forEach { entries.add(Pair(it.offset, buildString {
append("<")
append((if (it.highlighted) "H" else "h"))
append((if (it.current) "INT" else "int"))
append(" text=\"")
append(it.text)
append("\"/>")
}))}
if (expectedInlaysAndCaret.caretOffset != null) {
val actualCaretOffset = myFixture.editor.caretModel.offset
val actualInlaysBeforeCaret = myFixture.editor.caretModel.visualPosition.column -
myFixture.editor.offsetToVisualPosition(actualCaretOffset).column
val first = entries.indexOfFirst { it.first == actualCaretOffset }
val insertIndex = if (first == -1) -entries.binarySearch { it.first - actualCaretOffset } - 1
else first + actualInlaysBeforeCaret
entries.add(insertIndex, Pair(actualCaretOffset, "<caret>"))
}
val proposedText = StringBuilder(document.text)
entries.asReversed().forEach { proposedText.insert(it.first, it.second) }
VfsTestUtil.TEST_DATA_FILE_PATH.get(file.virtualFile)?.let { originalPath ->
throw FileComparisonFailure("Hints differ", originalText, proposedText.toString(), originalPath)
} ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString())
}
if (expectedInlaysAndCaret.caretOffset != null) {
assertEquals("Unexpected caret offset", expectedInlaysAndCaret.caretOffset, myFixture.editor.caretModel.offset)
val position = myFixture.editor.offsetToVisualPosition(expectedInlaysAndCaret.caretOffset)
assertEquals("Unexpected caret visual position",
VisualPosition(position.line, position.column + expectedInlaysAndCaret.inlaysBeforeCaret),
myFixture.editor.caretModel.visualPosition)
val selectionModel = myFixture.editor.selectionModel
if (expectedInlaysAndCaret.selection == null) assertFalse(selectionModel.hasSelection())
else assertEquals("Unexpected selection",
expectedInlaysAndCaret.selection,
TextRange(selectionModel.selectionStart, selectionModel.selectionEnd))
}
}
private fun getActualInlays(): List<ParamHintInfo> {
val editor = myFixture.editor
val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength)
val hintManager = ParameterHintsPresentationManager.getInstance()
return allInlays
.filter { hintManager.isParameterHint(it) }
.map { ParamHintInfo(it.offset, hintManager.getHintText(it), hintManager.isHighlighted(it), hintManager.isCurrent(it))}
.sortedBy { it.offset }
}
fun extractInlaysAndCaretInfo(document: Document): CaretAndInlaysInfo {
val text = document.text
val matcher = pattern.matcher(text)
val inlays = mutableListOf<ParamHintInfo>()
var extractedLength = 0
var caretOffset : Int? = null
var inlaysBeforeCaret = 0
var selectionStart : Int? = null
var selectionEnd : Int? = null
while (matcher.find()) {
val start = matcher.start()
val matchedLength = matcher.end() - start
val realStartOffset = start - extractedLength
if (matcher.group(1) != null) {
caretOffset = realStartOffset
inlays.asReversed()
.takeWhile { it.offset == caretOffset }
.forEach { inlaysBeforeCaret++ }
}
else if (matcher.group(2) != null) {
selectionStart = realStartOffset
}
else if (matcher.group(3) != null) {
selectionEnd = realStartOffset
}
else {
inlays += ParamHintInfo(realStartOffset, matcher.group(5), matcher.group(4).startsWith("H"), matcher.group(4).endsWith("INT"))
}
removeText(document, realStartOffset, matchedLength)
extractedLength += (matcher.end() - start)
}
return CaretAndInlaysInfo(caretOffset, inlaysBeforeCaret,
if (selectionStart == null || selectionEnd == null) null else TextRange(selectionStart, selectionEnd),
inlays)
}
private fun removeText(document: Document, realStartOffset: Int, matchedLength: Int) {
WriteCommandAction.runWriteCommandAction(myFixture.project, {
document.replaceString(realStartOffset, realStartOffset + matchedLength, "")
})
}
}
class CaretAndInlaysInfo (val caretOffset: Int?, val inlaysBeforeCaret: Int, val selection: TextRange?,
val inlays: List<ParamHintInfo>)
data class ParamHintInfo (val offset: Int, val text: String, val highlighted: Boolean, val current: Boolean) | platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt | 974994234 |
package xyz.nulldev.ts.api.java.model.downloads
enum class DownloadStatus {
NOT_DOWNLOADED,
QUEUE,
DOWNLOADING,
DOWNLOADED,
ERROR
} | TachiServer/src/main/java/xyz/nulldev/ts/api/java/model/downloads/DownloadStatus.kt | 904025599 |
package com.vicpin.kpa.annotation.processor
import com.vicpin.kpa.annotation.processor.model.Model
import java.io.File
import java.io.IOException
import javax.annotation.processing.ProcessingEnvironment
/**
* Created by victor on 10/12/17.
*/
class AdapterWritter(private val entity: Model.EntityModel) {
private var text: String = ""
private val className: String
val KAPT_KOTLIN_GENERATED_OPTION = "kapt.kotlin.generated"
init {
this.className = entity.name + ADAPTER_SUFIX
}
private fun generateClass(): String {
appendPackpage()
appendImports()
appendClassName()
appendGetViewInfomethod()
appendClassEnding()
return text
}
private fun appendPackpage() {
newLine("package ${entity.pkg}", newLine = true)
}
private fun appendImports() {
newLine("import ${entity.modelClass}")
newLine("import com.vicpin.kpresenteradapter.PresenterAdapter")
newLine("import com.vicpin.kpresenteradapter.model.ViewInfo", newLine = true)
}
private fun appendClassName() {
newLine("class TownPresenterAdapter(val layoutRes: Int) : PresenterAdapter<${entity.name}>() {")
}
private fun appendGetViewInfomethod() {
newLine("override fun getViewInfo(position: Int) = ViewInfo(${entity.name}ViewHolderParent::class, layoutRes)", level = 1)
}
private fun appendClassEnding() {
newLine("}")
}
fun generateFile(env: ProcessingEnvironment) {
try { // write the env
val options = env.options
val kotlinGenerated = options[KAPT_KOTLIN_GENERATED_OPTION] ?: ""
File(kotlinGenerated.replace("kaptKotlin","kapt"), "$className.kt").writer().buffered().use {
it.appendln(generateClass())
}
} catch (e: IOException) {
// Note: calling e.printStackTrace() will print IO errors
// that occur from the file already existing after its first run, this is normal
}
}
fun newLine(line: String = "", level: Int = 0, newLine: Boolean = false) {
var indentation = ""
var semicolon = if (!line.isEmpty() && !line.endsWith("}") && !line.endsWith("{")) ";" else ""
(1..level).forEach { indentation += "\t" }
text += if (newLine) {
"$indentation$line$semicolon\n\n"
} else {
"$indentation$line$semicolon\n"
}
}
companion object {
public val ADAPTER_SUFIX = "PresenterAdapter"
}
} | kpa-processor/src/main/java/com/vicpin/kpa/annotation/processor/AdapterWritter.kt | 705371612 |
package io.kotest.property.arbitrary
import io.kotest.property.Arb
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.Period
import kotlin.reflect.full.isSubclassOf
@Suppress("UNCHECKED_CAST")
actual inline fun <reified A> targetDefaultForClass(): Arb<A>? {
return when {
A::class.isSubclassOf(List::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
Arb.list(defaultForClass<Any>(upper.kotlin) as Arb<Any>) as Arb<A>
}
A::class.isSubclassOf(Set::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
Arb.set(defaultForClass<Any>(upper.kotlin) as Arb<Any>) as Arb<A>
}
A::class.isSubclassOf(Pair::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
val first = (type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
Arb.pair(defaultForClass<Any>(first.kotlin)!!, defaultForClass<Any>(second.kotlin)!!) as Arb<A>
}
A::class.isSubclassOf(Map::class) -> {
val type = object : TypeReference<A>() {}.type as ParameterizedType
// map key type can have or have not variance
val first = if (type.actualTypeArguments[0] is Class<*>) {
type.actualTypeArguments[0] as Class<*>
} else {
(type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
}
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
Arb.map(defaultForClass<Any>(first.kotlin)!!, defaultForClass<Any>(second.kotlin)!!) as Arb<A>
}
A::class == LocalDate::class -> Arb.localDate() as Arb<A>
A::class == LocalDateTime::class -> Arb.localDateTime() as Arb<A>
A::class == LocalTime::class -> Arb.localTime() as Arb<A>
A::class == Period::class -> Arb.period() as Arb<A>
A::class == BigDecimal::class -> Arb.bigDecimal() as Arb<A>
else -> null
}
}
// need some supertype that types a type param so it gets baked into the class file
abstract class TypeReference<T> : Comparable<TypeReference<T>> {
// this is the type of T
val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
override fun compareTo(other: TypeReference<T>) = 0
}
| kotest-property/src/jvmMain/kotlin/io/kotest/property/arbitrary/targetDefaultForClassName.kt | 3038240464 |
package de.husterknupp.todoapp
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
fun main(args: Array<String>) {
SpringApplication.run(JubilantTodoTribble::class.java, *args)
}
@SpringBootApplication
@EnableScheduling
@EnableWebSecurity
open class JubilantTodoTribble
| src/main/kotlin/de/husterknupp/todoapp/JubilantTodoTribble.kt | 1015576756 |
package org.fossasia.openevent.general.paypal
import retrofit2.http.Body
import retrofit2.http.POST
import retrofit2.http.Path
interface PaypalApi {
@POST("orders/{orderIdentifier}/create-paypal-payment")
fun createPaypalPayment(@Path("orderIdentifier") orderIdentifier: String, @Body paypal: Paypal)
}
| app/src/main/java/org/fossasia/openevent/general/paypal/PaypalApi.kt | 3412038349 |
package zak0.github.calendarcountdown.storage
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import zak0.github.calendarcountdown.data.CountdownSettings
import zak0.github.calendarcountdown.data.ExcludedDays
import zak0.github.calendarcountdown.data.GeneralSettings
import java.util.*
/**
* Handler for all SQLite activity.
* Reads and writes into the database.
*
* Created by jaakko on 24.6.2018.
*/
class DatabaseHelper(context: Context,
name: String,
version: Int)
: SQLiteOpenHelper(context, name, null, version) {
// Member variables
private var db: SQLiteDatabase? = null
fun openDb() {
Log.d(TAG, "openDb() - called")
db = this.writableDatabase
}
fun closeDb() {
Log.d(TAG, "closeDb() - called")
db?.close()
}
override fun onCreate(db: SQLiteDatabase) {
initSchema(db)
Log.d(TAG, "onCreate() - done")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Add general settings table
if (oldVersion == 1 && newVersion > 1) {
// create generalsettings table
val sql = "CREATE TABLE '" + TBLGENERALSETTINGS + "' (" +
"'" + COLGSSORTBY + "' INTEGER)"
db.execSQL(sql)
// init general settings table with "default" values
// note: this table only has one row
this.db = db
saveGeneralSettings()
}
}
/**
* Constructs empty tables. This is called when DB is first created.
*/
private fun initSchema(db: SQLiteDatabase) {
// create countdown table
var sql = "CREATE TABLE '" + TBLCOUNTDOWN + "' (" +
"`" + COLCOUNTDOWNID + "` INTEGER," +
"`" + COLCDENDDATE + "` TEXT," +
"`" + COLCDEXCLUDEWEEKENDS + "` INTEGER," +
"`" + COLCDLABEL + "` TEXT," +
"`" + COLCDWIDGET + "` INTEGER," +
"PRIMARY KEY(" + COLCOUNTDOWNID + ")" +
")"
db.execSQL(sql)
// create excludeddays table
sql = "CREATE TABLE `" + TBLEXCLUDEDDAYS + "` (" +
"`" + COLEXCLUDEDDAYSID + "` INTEGER," +
"`" + COLCOUNTDOWNID + "` INTEGER," +
"`" + COLEDFROMDATE + "` TEXT," +
"`" + COLEDTODATE + "` TEXT," +
"PRIMARY KEY(" + COLEXCLUDEDDAYSID + ")" +
")"
db.execSQL(sql)
// create generalsettings table
sql = "CREATE TABLE '" + TBLGENERALSETTINGS + "' (" +
"'" + COLGSSORTBY + "' INTEGER)"
db.execSQL(sql)
// init general settings table with "default" values
// note: this table only has one row
this.db = db
saveGeneralSettings()
Log.d(TAG, "initSchema() - done")
}
/**
* Loads the Countdowns that are set to be used on a widget.
*/
fun loadSettingsForWidget(): List<CountdownSettings> {
val ret = ArrayList<CountdownSettings>()
val sql = "select * from $TBLCOUNTDOWN where $COLCDWIDGET=1"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var countdown: CountdownSettings
while (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
ret.add(countdown)
// Load excluded date ranges for countdown
loadExcludedDaysForCountdown(countdown)
cur.moveToNext()
}
}
return ret
}
fun saveGeneralSettings() {
val gs = GeneralSettings
// GeneralSettings table only has one row.
// Empty the table before saving to ensure there stays only one...
var sql = "delete from $TBLGENERALSETTINGS"
db?.execSQL(sql)
// ...Then insert the settings into the table.
sql = "insert into " + TBLGENERALSETTINGS + " (" +
COLGSSORTBY + ") values (" +
gs.sortOrder + ")"
db?.execSQL(sql)
}
fun loadGeneralSettings() {
val gs = GeneralSettings
// GeneralSettings table only has a one row
val sql = "select * from $TBLGENERALSETTINGS"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
if (!cur.isAfterLast) {
gs.sortOrder = cur.getInt(0)
}
cur.close()
}
}
/**
* Loads countdown with specific ID from the database.
* Returns null if nothing is found.
*/
fun loadSetting(id: Int): CountdownSettings? {
val sql = "select * from $TBLCOUNTDOWN where $COLCOUNTDOWNID = $id"
var countdown: CountdownSettings? = null
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
if (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
// Load excluded date ranges for countdown
countdown?.also {
loadExcludedDaysForCountdown(it)
}
cur.moveToNext()
}
}
Log.d(TAG, "loadSetting() - loaded countdown with title '${countdown?.label ?: "null"}' from DB")
return countdown
}
/**
* Reads and returns settings from database.
*/
fun loadSettings(): List<CountdownSettings> {
val ret = ArrayList<CountdownSettings>()
val sql = "select * from $TBLCOUNTDOWN"
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var countdown: CountdownSettings
while (!cur.isAfterLast) {
countdown = cursorToCountdown(cur)
ret.add(countdown)
// Load excluded date ranges for countdown
loadExcludedDaysForCountdown(countdown)
cur.moveToNext()
}
}
Log.d(TAG, "loadSettings() - loaded " + Integer.toString(ret.size) + " countdowns from DB")
return ret
}
/**
* Loads and sets excluded date ranges for given countdown.
*/
private fun loadExcludedDaysForCountdown(countdown: CountdownSettings) {
val sql = "select * from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(countdown.dbId)
db?.also { db ->
val cur = db.rawQuery(sql, null)
cur.moveToFirst()
var exclDays: ExcludedDays
while (!cur.isAfterLast) {
exclDays = cursorToExcludedDays(cur)
exclDays.setSettings(countdown) // this is null before setting
countdown.addExcludedDays(exclDays)
cur.moveToNext()
}
}
}
/**
* Saves a given countdown into the database.
*/
fun saveCountdownToDB(settings: CountdownSettings) {
val list = ArrayList<CountdownSettings>()
list.add(settings)
saveToDB(list)
}
/**
* Saves all settings given as parameter into DB.
*/
private fun saveToDB(list: List<CountdownSettings>) {
var sql: String
// Iterate through all the settings.
for (settings in list) {
db?.also { db ->
// Check if entry for current CountDownSettings already exists in DB
sql = "select * from " + TBLCOUNTDOWN + " where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
val cur = db.rawQuery(sql, null)
if (cur.count > 0) {
// It id already exist --> update existing
Log.d(TAG, "saveToDB() - updating countdownid " + Integer.toString(settings.dbId))
sql = "update " + TBLCOUNTDOWN + " set " + COLCDENDDATE + "='" + settings.endDate + "'," +
COLCDEXCLUDEWEEKENDS + "=" + (if (settings.isExcludeWeekends) "1" else "0") + "," +
COLCDLABEL + "='" + settings.label + "'," +
COLCDWIDGET + "=" + (if (settings.isUseOnWidget) "1" else "0") + " where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db.execSQL(sql)
} else {
// It did not exist --> insert a new entry
Log.d(TAG, "saveToDB() - inserting a new countdown entry")
sql = "insert into " + TBLCOUNTDOWN + "(" + COLCDENDDATE + "," + COLCDEXCLUDEWEEKENDS + "," + COLCDLABEL + "," + COLCDWIDGET + ") " +
"values('" + settings.endDate + "'," + (if (settings.isExcludeWeekends) "1" else "0") + "," +
"'" + settings.label + "'," + (if (settings.isUseOnWidget) "1" else "0") + ")"
db.execSQL(sql)
// Update settings with corresponding rowID.
// (Used when inserting excluded ranges)
val rowIdCur = db.rawQuery("select last_insert_rowid();", null)
rowIdCur.moveToFirst()
settings.dbId = rowIdCur.getInt(0)
rowIdCur.close()
}
cur.close()
// Save excluded date ranges.
saveExcludedDaysOfCountdown(settings)
}
}
}
private fun saveExcludedDaysOfCountdown(countdown: CountdownSettings) {
// First clear all the existing excluded ranges for the countdown.
var sql = "delete from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(countdown.dbId)
db?.execSQL(sql)
db?.also { db ->
for (excludedDays in countdown.excludedDays) {
// Check if entry already exists.
sql = "select * from " + TBLEXCLUDEDDAYS + " where " + COLEXCLUDEDDAYSID + "=" + Integer.toString(excludedDays.dbId)
val cur = db.rawQuery(sql, null)
if (cur.count > 0) {
// Entry did already exist --> update it.
Log.d(TAG, "saveExcludedDaysOfCountdown() - updating an excludeddays entry")
sql = "update " + TBLEXCLUDEDDAYS + " set " +
COLEDFROMDATE + "='" + excludedDays.fromDate + "'," +
COLEDTODATE + "='" + excludedDays.toDate + "'" +
" where " + COLEXCLUDEDDAYSID + "=" + Integer.toString(excludedDays.dbId)
db.execSQL(sql)
} else {
// Did not already exist in the database.
// --> insert a new one.
Log.d(TAG, "saveExcludedDaysOfCountdown() - inserting a new excludeddays entry")
sql = ("insert into " + TBLEXCLUDEDDAYS + "(" +
COLCOUNTDOWNID + "," +
COLEDFROMDATE + "," +
COLEDTODATE + ") values ("
+ Integer.toString(countdown.dbId) + ",'" +
excludedDays.fromDate + "','" +
excludedDays.toDate + "')")
db.execSQL(sql)
// Update excludedDays with corresponding rowID.
val exclRowIdCur = db.rawQuery("select last_insert_rowid();", null)
exclRowIdCur.moveToFirst()
excludedDays.dbId = exclRowIdCur.getInt(0)
exclRowIdCur.close()
}
cur.close()
}
}
}
private fun cursorToCountdown(cur: Cursor): CountdownSettings {
val ret = CountdownSettings()
ret.dbId = cur.getInt(0)
ret.endDate = cur.getString(1)
ret.isExcludeWeekends = cur.getInt(2) == 1
ret.label = cur.getString(3)
ret.isUseOnWidget = cur.getInt(4) == 1
return ret
}
private fun cursorToExcludedDays(cur: Cursor): ExcludedDays {
val ret = ExcludedDays()
ret.dbId = cur.getInt(0)
ret.fromDate = cur.getString(2)
ret.toDate = cur.getString(3)
return ret
}
/**
* Daletes given countdown from the database.
*/
fun deleteCountdown(settings: CountdownSettings) {
// First delete excluded date ranges.
var sql = "delete from " + TBLEXCLUDEDDAYS +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db?.execSQL(sql)
// Then delete the countdown itself.
sql = "delete from " + TBLCOUNTDOWN +
" where " + COLCOUNTDOWNID + "=" + Integer.toString(settings.dbId)
db?.execSQL(sql)
}
companion object {
private val TAG = DatabaseHelper::class.java.simpleName
const val DB_NAME = "calendarcountdown.db"
const val DB_VERSION = 2
private const val TBLCOUNTDOWN = "countdown"
private const val TBLEXCLUDEDDAYS = "excludeddays"
private const val TBLGENERALSETTINGS = "generalsettings"
private const val COLCOUNTDOWNID = "countdownid"
private const val COLCDENDDATE = "cdenddate"
private const val COLCDEXCLUDEWEEKENDS = "cdexcludeweekends"
private const val COLCDLABEL = "cdlabel"
private const val COLCDWIDGET = "cdwidget"
private const val COLEXCLUDEDDAYSID = "excludeddaysid"
private const val COLEDFROMDATE = "edfromdate"
private const val COLEDTODATE = "edtodate"
private const val COLGSSORTBY = "gssortby"
}
}
| app/src/main/java/zak0/github/calendarcountdown/storage/DatabaseHelper.kt | 1027821985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.