repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
msebire/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 3 | 2810 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic
import com.intellij.CommonBundle
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.RememberCheckBoxState
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import com.intellij.util.text.nullize
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun showJetBrainsAccountDialog(parent: Component, project: Project? = null): DialogWrapper {
val credentials = ErrorReportConfigurable.getCredentials()
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.password?.toString())
val passwordSafe = PasswordSafe.instance
val isSelected = if (credentials?.userName == null) {
// if no user name - never stored and so, defaults
passwordSafe.isRememberPasswordByDefault
}
else {
// if user name set, but no password, so, previously was stored without password
!credentials.password.isNullOrEmpty()
}
val rememberCheckBox = CheckBox(CommonBundle.message("checkbox.remember.password"), isSelected)
val panel = panel {
noteRow("Login to JetBrains Account to get notified\nwhen the submitted exceptions are fixed.")
row("Username:") { userField(growPolicy = GrowPolicy.SHORT_TEXT) }
row("Password:") { passwordField() }
row {
rememberCheckBox()
right {
link("Forgot password?") {
val userName = userField.text.trim().encodeUrlQueryParameter()
BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=$userName")
}
}
}
noteRow("""Do not have an account? <a href="https://account.jetbrains.com/login?signup">Sign Up</a>""")
}
return dialog(
title = DiagnosticBundle.message("error.report.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null) {
val userName = userField.text.nullize(true)
val password = if (rememberCheckBox.isSelected) passwordField.password else null
RememberCheckBoxState.update(rememberCheckBox)
passwordSafe.set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, password))
return@dialog null
}
} | apache-2.0 | 4ec39bbb503f6c613079d5d57b0721d6 | 41.590909 | 140 | 0.758007 | 4.488818 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/Whiteboard.kt | 1 | 21497 | /*
* Copyright (c) 2009 Andrew <[email protected]>
* Copyright (c) 2009 Nicolas Raoul <[email protected]>
* Copyright (c) 2009 Edu Zamora <[email protected]>
* Copyright (c) 2021 Nicolai Weitkemper <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki
import android.annotation.SuppressLint
import android.graphics.*
import android.graphics.drawable.VectorDrawable
import android.net.Uri
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.annotation.CheckResult
import androidx.annotation.VisibleForTesting
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import com.ichi2.anki.dialogs.WhiteBoardWidthDialog
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.utils.Time
import com.ichi2.libanki.utils.TimeUtils
import com.ichi2.themes.Themes.currentTheme
import com.ichi2.utils.DisplayUtils.getDisplayDimensions
import com.ichi2.utils.KotlinCleanup
import com.mrudultora.colorpicker.ColorPickerPopUp
import timber.log.Timber
import java.io.FileNotFoundException
import kotlin.math.abs
import kotlin.math.max
/**
* Whiteboard allowing the user to draw the card's answer on the touchscreen.
*/
@SuppressLint("ViewConstructor")
class Whiteboard(activity: AnkiActivity, handleMultiTouch: Boolean, inverted: Boolean) : View(activity, null) {
private val mPaint: Paint
private val mUndo = UndoList()
private lateinit var mBitmap: Bitmap
private lateinit var mCanvas: Canvas
private val mPath: Path
private val mBitmapPaint: Paint
private val mAnkiActivity: AnkiActivity = activity
private var mX = 0f
private var mY = 0f
private var mSecondFingerX0 = 0f
private var mSecondFingerY0 = 0f
private var mSecondFingerX = 0f
private var mSecondFingerY = 0f
private var mSecondFingerPointerId = 0
private var mSecondFingerWithinTapTolerance = false
var isCurrentlyDrawing = false
private set
/**
* @return true if the undo queue has had any strokes added to it since the last clear
*/
var isUndoModeActive = false
private set
@get:CheckResult
@get:VisibleForTesting
var foregroundColor = 0
private val mColorPalette: LinearLayout
private val mHandleMultiTouch: Boolean = handleMultiTouch
private var mOnPaintColorChangeListener: OnPaintColorChangeListener? = null
val currentStrokeWidth: Int
get() = AnkiDroidApp.getSharedPrefs(mAnkiActivity).getInt("whiteBoardStrokeWidth", 6)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.apply {
drawColor(0)
drawBitmap(mBitmap, 0f, 0f, mBitmapPaint)
drawPath(mPath, mPaint)
}
}
/** Handle motion events to draw using the touch screen or to interact with the flashcard behind
* the whiteboard by using a second finger.
*
* @param event The motion event.
* @return True if the event was handled, false otherwise
*/
fun handleTouchEvent(event: MotionEvent): Boolean {
return handleDrawEvent(event) || handleMultiTouchEvent(event)
}
/**
* Handle motion events to draw using the touch screen. Only simple touch events are processed,
* a multitouch event aborts to current stroke.
*
* @param event The motion event.
* @return True if the event was handled, false otherwise or when drawing was aborted due to
* detection of a multitouch event.
*/
private fun handleDrawEvent(event: MotionEvent): Boolean {
val x = event.x
val y = event.y
return when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
drawStart(x, y)
invalidate()
true
}
MotionEvent.ACTION_MOVE -> {
if (isCurrentlyDrawing) {
for (i in 0 until event.historySize) {
drawAlong(event.getHistoricalX(i), event.getHistoricalY(i))
}
drawAlong(x, y)
invalidate()
return true
}
false
}
MotionEvent.ACTION_UP -> {
if (isCurrentlyDrawing) {
drawFinish()
invalidate()
return true
}
false
}
MotionEvent.ACTION_POINTER_DOWN -> {
if (isCurrentlyDrawing) {
drawAbort()
}
false
}
211, 213 -> {
if (event.buttonState == MotionEvent.BUTTON_STYLUS_PRIMARY && !undoEmpty()) {
val didErase = mUndo.erase(event.x.toInt(), event.y.toInt())
if (didErase) {
mUndo.apply()
if (undoEmpty()) {
mAnkiActivity.invalidateOptionsMenu()
}
}
}
true
}
else -> false
}
}
// Parse multitouch input to scroll the card behind the whiteboard or click on elements
private fun handleMultiTouchEvent(event: MotionEvent): Boolean {
return if (mHandleMultiTouch && event.pointerCount == 2) {
when (event.actionMasked) {
MotionEvent.ACTION_POINTER_DOWN -> {
reinitializeSecondFinger(event)
true
}
MotionEvent.ACTION_MOVE -> trySecondFingerScroll(event)
MotionEvent.ACTION_POINTER_UP -> trySecondFingerClick(event)
else -> false
}
} else false
}
/**
* Clear the whiteboard.
*/
fun clear() {
isUndoModeActive = false
mBitmap.eraseColor(0)
mUndo.clear()
invalidate()
mAnkiActivity.invalidateOptionsMenu()
}
/**
* Undo the last stroke
*/
fun undo() {
mUndo.pop()
mUndo.apply()
if (undoEmpty()) {
mAnkiActivity.invalidateOptionsMenu()
}
}
/** @return Whether there are strokes to undo
*/
fun undoEmpty(): Boolean {
return mUndo.empty()
}
private fun createBitmap(w: Int, h: Int) {
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
mBitmap = bitmap
mCanvas = Canvas(bitmap)
clear()
}
private fun createBitmap() {
// To fix issue #1336, just make the whiteboard big and square.
val p = displayDimensions
val bitmapSize = max(p.x, p.y)
createBitmap(bitmapSize, bitmapSize)
}
/**
* On rotating the device onSizeChanged() helps to stretch the previously created Bitmap rather
* than creating a new Bitmap which makes sure bitmap doesn't go out of screen.
*/
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val scaledBitmap: Bitmap = Bitmap.createScaledBitmap(mBitmap, w, h, true)
mBitmap = scaledBitmap
mCanvas = Canvas(mBitmap)
}
private fun drawStart(x: Float, y: Float) {
isCurrentlyDrawing = true
mPath.reset()
mPath.moveTo(x, y)
mX = x
mY = y
}
private fun drawAlong(x: Float, y: Float) {
val dx = abs(x - mX)
val dy = abs(y - mY)
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2)
mX = x
mY = y
}
}
private fun drawFinish() {
isCurrentlyDrawing = false
val pm = PathMeasure(mPath, false)
mPath.lineTo(mX, mY)
val paint = Paint(mPaint)
val action = if (pm.length > 0) DrawPath(Path(mPath), paint) else DrawPoint(mX, mY, paint)
action.apply(mCanvas)
mUndo.add(action)
isUndoModeActive = true
// kill the path so we don't double draw
mPath.reset()
if (mUndo.size() == 1) {
mAnkiActivity.invalidateOptionsMenu()
}
}
private fun drawAbort() {
drawFinish()
undo()
}
// call this with an ACTION_POINTER_DOWN event to start a new round of detecting drag or tap with
// a second finger
private fun reinitializeSecondFinger(event: MotionEvent) {
mSecondFingerWithinTapTolerance = true
mSecondFingerPointerId = event.getPointerId(event.actionIndex)
mSecondFingerX0 = event.getX(event.findPointerIndex(mSecondFingerPointerId))
mSecondFingerY0 = event.getY(event.findPointerIndex(mSecondFingerPointerId))
}
private fun updateSecondFinger(event: MotionEvent): Boolean {
val pointerIndex = event.findPointerIndex(mSecondFingerPointerId)
if (pointerIndex > -1) {
mSecondFingerX = event.getX(pointerIndex)
mSecondFingerY = event.getY(pointerIndex)
val dx = abs(mSecondFingerX0 - mSecondFingerX)
val dy = abs(mSecondFingerY0 - mSecondFingerY)
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mSecondFingerWithinTapTolerance = false
}
return true
}
return false
}
// call this with an ACTION_POINTER_UP event to check whether it matches a tap of the second finger
// if so, forward a click action and return true
private fun trySecondFingerClick(event: MotionEvent): Boolean {
if (mSecondFingerPointerId == event.getPointerId(event.actionIndex)) {
updateSecondFinger(event)
if (mSecondFingerWithinTapTolerance && mWhiteboardMultiTouchMethods != null) {
mWhiteboardMultiTouchMethods!!.tapOnCurrentCard(mSecondFingerX.toInt(), mSecondFingerY.toInt())
return true
}
}
return false
}
// call this with an ACTION_MOVE event to check whether it is within the threshold for a tap of the second finger
// in this case perform a scroll action
private fun trySecondFingerScroll(event: MotionEvent): Boolean {
if (updateSecondFinger(event) && !mSecondFingerWithinTapTolerance) {
val dy = (mSecondFingerY0 - mSecondFingerY).toInt()
if (dy != 0 && mWhiteboardMultiTouchMethods != null) {
mWhiteboardMultiTouchMethods!!.scrollCurrentCardBy(dy)
mSecondFingerX0 = mSecondFingerX
mSecondFingerY0 = mSecondFingerY
}
return true
}
return false
}
fun onClick(view: View) {
when (view.id) {
R.id.pen_color_white -> {
penColor = Color.WHITE
}
R.id.pen_color_black -> {
penColor = Color.BLACK
}
R.id.pen_color_red -> {
val redPenColor = ContextCompat.getColor(context, R.color.material_red_500)
penColor = redPenColor
}
R.id.pen_color_green -> {
val greenPenColor = ContextCompat.getColor(context, R.color.material_green_500)
penColor = greenPenColor
}
R.id.pen_color_blue -> {
val bluePenColor = ContextCompat.getColor(context, R.color.material_blue_500)
penColor = bluePenColor
}
R.id.pen_color_yellow -> {
val yellowPenColor = ContextCompat.getColor(context, R.color.material_yellow_500)
penColor = yellowPenColor
}
R.id.pen_color_custom -> {
ColorPickerPopUp(context).run {
setShowAlpha(true)
setDefaultColor(penColor)
setOnPickColorListener(object : ColorPickerPopUp.OnPickColorListener {
override fun onColorPicked(color: Int) {
penColor = color
}
override fun onCancel() {
// unused
}
})
show()
}
}
R.id.stroke_width -> {
handleWidthChangeDialog()
}
}
}
private fun handleWidthChangeDialog() {
val whiteBoardWidthDialog = WhiteBoardWidthDialog(mAnkiActivity, currentStrokeWidth)
whiteBoardWidthDialog.onStrokeWidthChanged { wbStrokeWidth: Int -> saveStrokeWidth(wbStrokeWidth) }
whiteBoardWidthDialog.showStrokeWidthDialog()
}
private fun saveStrokeWidth(wbStrokeWidth: Int) {
mPaint.strokeWidth = wbStrokeWidth.toFloat()
AnkiDroidApp.getSharedPrefs(mAnkiActivity).edit {
putInt("whiteBoardStrokeWidth", wbStrokeWidth)
}
}
@get:VisibleForTesting
var penColor: Int
get() = mPaint.color
set(color) {
Timber.d("Setting pen color to %d", color)
mPaint.color = color
mColorPalette.visibility = GONE
if (mOnPaintColorChangeListener != null) {
mOnPaintColorChangeListener!!.onPaintColorChange(color)
}
}
fun setOnPaintColorChangeListener(onPaintColorChangeListener: OnPaintColorChangeListener?) {
mOnPaintColorChangeListener = onPaintColorChangeListener
}
/**
* Keep a list of all points and paths so that the last stroke can be undone
* pop() removes the last stroke from the list, and apply() redraws it to whiteboard.
*/
private inner class UndoList {
private val mList: MutableList<WhiteboardAction> = ArrayList()
fun add(action: WhiteboardAction) {
mList.add(action)
}
fun clear() {
mList.clear()
}
fun size(): Int {
return mList.size
}
fun pop() {
mList.removeAt(mList.size - 1)
}
fun apply() {
mBitmap.eraseColor(0)
for (action in mList) {
action.apply(mCanvas)
}
invalidate()
}
fun erase(x: Int, y: Int): Boolean {
var didErase = false
val clip = Region(0, 0, displayDimensions.x, displayDimensions.y)
val eraserPath = Path()
eraserPath.addRect((x - 10).toFloat(), (y - 10).toFloat(), (x + 10).toFloat(), (y + 10).toFloat(), Path.Direction.CW)
val eraserRegion = Region()
eraserRegion.setPath(eraserPath, clip)
// used inside the loop – created here to make things a little more efficient
val bounds = RectF()
var lineRegion = Region()
// we delete elements while iterating, so we need to use an iterator in order to avoid java.util.ConcurrentModificationException
val iterator = mList.iterator()
while (iterator.hasNext()) {
val action = iterator.next()
val path = action.path
if (path != null) { // → line
val lineRegionSuccess = lineRegion.setPath(path, clip)
if (!lineRegionSuccess) {
// Small lines can be perfectly vertical/horizontal,
// thus giving us an empty region, which would make them undeletable.
// For this edge case, we create a Region ourselves.
path.computeBounds(bounds, true)
lineRegion = Region(Rect(bounds.left.toInt(), bounds.top.toInt(), bounds.right.toInt() + 1, bounds.bottom.toInt() + 1))
}
} else { // → point
val p = action.point
lineRegion = Region(p!!.x, p.y, p.x + 1, p.y + 1)
}
if (!lineRegion.quickReject(eraserRegion) && lineRegion.op(eraserRegion, Region.Op.INTERSECT)) {
iterator.remove()
didErase = true
}
}
return didErase
}
fun empty(): Boolean {
return mList.isEmpty()
}
}
private interface WhiteboardAction {
fun apply(canvas: Canvas)
val path: Path?
val point: Point?
}
private class DrawPoint(private val x: Float, private val y: Float, private val paint: Paint) : WhiteboardAction {
override fun apply(canvas: Canvas) {
canvas.drawPoint(x, y, paint)
}
override val path: Path?
get() = null
override val point: Point
get() = Point(x.toInt(), y.toInt())
}
private class DrawPath(override val path: Path, private val paint: Paint) : WhiteboardAction {
override fun apply(canvas: Canvas) {
canvas.drawPath(path, paint)
}
override val point: Point?
get() = null
}
@Throws(FileNotFoundException::class)
fun saveWhiteboard(time: Time?): Uri {
val bitmap = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
if (foregroundColor != Color.BLACK) {
canvas.drawColor(Color.BLACK)
} else {
canvas.drawColor(Color.WHITE)
}
draw(canvas)
val baseFileName = "Whiteboard" + TimeUtils.getTimestamp(time!!)
// TODO: Fix inconsistent CompressFormat 'JPEG' and file extension 'png'
return CompatHelper.compat.saveImage(context, bitmap, baseFileName, "png", Bitmap.CompressFormat.JPEG, 95)
}
@KotlinCleanup("fun interface & use SAM on callers")
interface OnPaintColorChangeListener {
fun onPaintColorChange(color: Int?)
}
companion object {
private const val TOUCH_TOLERANCE = 4f
private var mWhiteboardMultiTouchMethods: WhiteboardMultiTouchMethods? = null
fun createInstance(context: AnkiActivity, handleMultiTouch: Boolean, whiteboardMultiTouchMethods: WhiteboardMultiTouchMethods?): Whiteboard {
val whiteboard = Whiteboard(context, handleMultiTouch, currentTheme.isNightMode)
mWhiteboardMultiTouchMethods = whiteboardMultiTouchMethods
val lp2 = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
whiteboard.layoutParams = lp2
val fl = context.findViewById<FrameLayout>(R.id.whiteboard)
fl.addView(whiteboard)
whiteboard.isEnabled = true
return whiteboard
}
private val displayDimensions: Point
get() = getDisplayDimensions(AnkiDroidApp.instance.applicationContext)
}
init {
val whitePenColorButton = activity.findViewById<Button>(R.id.pen_color_white)
val blackPenColorButton = activity.findViewById<Button>(R.id.pen_color_black)
if (!inverted) {
whitePenColorButton.visibility = GONE
blackPenColorButton.setOnClickListener { view: View -> onClick(view) }
foregroundColor = Color.BLACK
} else {
blackPenColorButton.visibility = GONE
whitePenColorButton.setOnClickListener { view: View -> onClick(view) }
foregroundColor = Color.WHITE
}
mPaint = Paint().apply {
isAntiAlias = true
isDither = true
color = foregroundColor
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
strokeWidth = currentStrokeWidth.toFloat()
}
createBitmap()
mPath = Path()
mBitmapPaint = Paint(Paint.DITHER_FLAG)
// selecting pen color to draw
mColorPalette = activity.findViewById(R.id.whiteboard_editor)
activity.findViewById<View>(R.id.pen_color_red).setOnClickListener { view: View -> onClick(view) }
activity.findViewById<View>(R.id.pen_color_green).setOnClickListener { view: View -> onClick(view) }
activity.findViewById<View>(R.id.pen_color_blue).setOnClickListener { view: View -> onClick(view) }
activity.findViewById<View>(R.id.pen_color_yellow).setOnClickListener { view: View -> onClick(view) }
activity.findViewById<View>(R.id.pen_color_custom).apply {
setOnClickListener { view: View -> onClick(view) }
(background as? VectorDrawable)?.setTint(foregroundColor)
}
activity.findViewById<View>(R.id.stroke_width).apply {
setOnClickListener { view: View -> onClick(view) }
(background as? VectorDrawable)?.setTint(foregroundColor)
}
}
}
| gpl-3.0 | 2d8a4b977f75ac6e472df7ce9f0fb953 | 36.181661 | 149 | 0.599693 | 4.647708 | false | false | false | false |
NooAn/bytheway | app/src/main/java/ru/a1024bits/bytheway/repository/UserRepository.kt | 1 | 8898 | package ru.a1024bits.bytheway.repository
import android.net.Uri
import android.util.Log
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.crash.FirebaseCrash
import com.google.firebase.firestore.*
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageException
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import ru.a1024bits.bytheway.MapWebService
import ru.a1024bits.bytheway.model.FireBaseNotification
import ru.a1024bits.bytheway.model.User
import ru.a1024bits.bytheway.model.map_directions.RoutesList
import ru.a1024bits.bytheway.util.Constants
import ru.a1024bits.bytheway.util.toJsonString
import ru.a1024bits.bytheway.viewmodel.FilterAndInstallListener
import javax.inject.Inject
const val COLLECTION_USERS = "users"
/**
* Created by andrey.gusenkov on 19/09/2017
*/
class UserRepository @Inject constructor(val store: FirebaseFirestore, var mapService: MapWebService) : IUsersRepository {
override fun getUser(id: String): Single<User> =
Single.create<User> { stream ->
try {
store.collection(COLLECTION_USERS).document(id).get().addOnSuccessListener({ document ->
if (document.exists()) {
val user = document.toObject(User::class.java)
stream.onSuccess(user)
}
}).addOnFailureListener({ t ->
stream.tryOnError(t)
})
} catch (e: Exception) {
stream.tryOnError(e)
}
}
override fun uploadPhotoLink(path: Uri, id: String): Single<String> = Single.create { stream ->
try {
val storageRef = FirebaseStorage.getInstance().reference
val riversRef = storageRef.child("images/" + id)
val uploadTask = riversRef.putFile(path)
uploadTask.addOnFailureListener {
stream.tryOnError(it)
}.addOnSuccessListener { taskSnapshot ->
stream.onSuccess(taskSnapshot.downloadUrl.toString())
}
} catch (e: Exception) {
stream.tryOnError(e)
}
}
override fun installAllUsers(listener: FilterAndInstallListener) {
try {
var lastTime = listener.filter.endDate
if (listener.filter.endDate == 0L) {
lastTime = System.currentTimeMillis()
}
var query = store.collection(COLLECTION_USERS).orderBy("dates.end_date")
if (listener.filter.endDate == 0L) {
query = query.whereGreaterThanOrEqualTo("dates.end_date", lastTime)
} else {
query = query.whereLessThanOrEqualTo("dates.end_date", lastTime)
}
query.addSnapshotListener(EventListener { snapshot, error ->
if (error != null) {
listener.onFailure(error)
return@EventListener
}
if (listener.filter.endDate != 0L) {
listener.filterAndInstallUsers(snapshot)
return@EventListener
}
store.collection(COLLECTION_USERS)
.whereEqualTo("dates.end_date", 0)
.whereGreaterThan("cities.first_city", "")
.get()
.addOnCompleteListener({ task ->
listener.filterAndInstallUsers(snapshot, task.result)
})
.addOnFailureListener({ e -> listener.onFailure(e) })
})
} catch (e: Exception) {
FirebaseCrash.report(e)
}
}
override fun getRealUsers(): Observable<User> = Observable.create<User> { stream ->
try {
store.collection(COLLECTION_USERS).whereGreaterThanOrEqualTo("dates.start_date", System.currentTimeMillis())
.get().addOnCompleteListener({ task ->
if (task.isSuccessful) {
for (document in task.result) {
var user: User
try {
user = document.toObject(User::class.java)
stream.onNext(user)
} catch (ex2: Exception) {
FirebaseCrash.report(ex2)
}
}
} else {
stream.tryOnError(Exception("Not Successful load users"))
}
stream.onComplete()
})
} catch (exp: Exception) {
stream.tryOnError(exp) // for fix bugs FirebaseFirestoreException: DEADLINE_EXCEEDED
stream.onComplete()
}
}
override fun getUserById(userID: String): Task<DocumentSnapshot> {
return store.collection(COLLECTION_USERS).document(userID).get()
}
override fun addUser(user: User): Task<Void> {
if (user.id == "1") throw FirebaseFirestoreException("User id is not set", FirebaseFirestoreException.Code.ABORTED)
return store.collection(COLLECTION_USERS).document(user.id).set(user)
}
override fun changeUserProfile(map: HashMap<String, Any>, id: String): Completable =
Completable.create { stream ->
try {
val documentRef = store.collection(COLLECTION_USERS).document(id)
store.runTransaction(object : Transaction.Function<Void> {
override fun apply(transaction: Transaction): Void? {
map["timestamp"] = FieldValue.serverTimestamp()
documentRef.update(map)
return null
}
}).addOnFailureListener { stream.tryOnError(it) }
.addOnSuccessListener { _ -> stream.onComplete() }
} catch (e: Exception) {
stream.tryOnError(e)
}
}
override fun getRoute(cityFromLatLng: GeoPoint, cityToLatLng: GeoPoint, waypoints: GeoPoint?): Single<RoutesList> {
val latLngPoint = if (waypoints?.latitude == 0.0 || waypoints?.longitude == 0.0 || waypoints == null) "" else LatLng(waypoints.latitude, waypoints.longitude).toJsonString()
return mapService.getDirection(hashMapOf(
"origin" to LatLng(cityFromLatLng.latitude, cityFromLatLng.longitude).toJsonString(),
"destination" to LatLng(cityToLatLng.latitude, cityToLatLng.longitude).toJsonString(),
"waypoints" to latLngPoint,
"sensor" to "false"))
}
override fun sendTime(id: String): Completable = Completable.create { stream ->
try {
val documentRef = store.collection(COLLECTION_USERS).document(id)
store.runTransaction {
val map = hashMapOf<String, Any>()
map["timestamp"] = FieldValue.serverTimestamp()
documentRef.update(map)
null
}.addOnSuccessListener { _ ->
stream.onComplete()
}.addOnFailureListener {
stream.tryOnError(it)
}
} catch (e: Exception) {
stream.onComplete()
}
}
override fun updateFcmToken(token: String?): Completable = Completable.create { stream ->
try {
store.runTransaction({
val currentUid = FirebaseAuth.getInstance().currentUser?.uid.orEmpty()
if (currentUid.isNotEmpty() && token != null && token.isNotEmpty()) {
val docRef = FirebaseFirestore.getInstance().collection(COLLECTION_USERS)
.document(currentUid)
docRef.update(Constants.FCM_TOKEN, token)
}
}).addOnFailureListener {
stream.tryOnError(it)
}.addOnSuccessListener { stream.onComplete() }
} catch (e: Exception) {
stream.tryOnError(e)
}
}
override fun sendNotifications(ids: String, notification: FireBaseNotification): Completable {
return mapService.sendNotifications(hashMapOf(
"ids" to ids,
"title" to notification.title,
"body" to notification.body,
"cmd" to notification.cmd,
"value" to notification.value.toString()
))
}
} | mit | 3a217cba89fc951ced9d1852528e1c39 | 41.990338 | 180 | 0.56361 | 5.179278 | false | false | false | false |
gmillz/SlimFileManager | manager/src/main/java/com/slim/util/SDCardUtils.kt | 1 | 3967 | /* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.slim.util
import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.storage.StorageManager
import android.os.storage.StorageVolume
import android.util.Log
import java.io.File
import java.lang.reflect.Method
class SDCardUtils private constructor(context: Context) {
private var mStorageManager: StorageManager? = null
private var mVolume: StorageVolume? = null
private var path: String? = null
val isWriteable: Boolean
get() = mVolume != null && sdCardStorageState == Environment.MEDIA_MOUNTED
val directory: String?
get() {
if (mVolume == null) {
return null
}
if (path == null) {
path = pathInternal
}
return path
}
private val pathInternal: String?
get() {
try {
val m = mVolume!!.javaClass.getDeclaredMethod("getPath")
return m.invoke(mVolume) as String
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
private val sdCardStorageState: String
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mVolume!!.state
} else {
Environment.MEDIA_MOUNTED
}
init {
try {
mStorageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
val volumeList = mStorageManager!!.javaClass.getDeclaredMethod("getVolumeList")
val volumes = volumeList.invoke(mStorageManager) as Array<StorageVolume>
if (volumes.size > VOLUME_SDCARD_INDEX) {
mVolume = volumes[VOLUME_SDCARD_INDEX]
}
} catch (e: Exception) {
Log.e(TAG, "couldn't talk to MountService", e)
}
}
fun exists(): Boolean {
return mVolume != null && File(directory!!).exists()
}
companion object {
private val TAG = "SDCard"
private val VOLUME_SDCARD_INDEX = 1
private var sSDCard: SDCardUtils? = null
fun initialize(context: Context) {
if (sSDCard == null) {
sSDCard = SDCardUtils(context)
}
}
@Synchronized fun instance(): SDCardUtils? {
return sSDCard
}
}
} | gpl-3.0 | 02c385bb73e822925ef67b9efd560dec | 33.807018 | 97 | 0.645828 | 4.683589 | false | false | false | false |
googlecodelabs/maps-platform-101-android | starter/app/src/main/java/com/google/codelabs/buildyourfirstmap/place/PlacesResponse.kt | 3 | 1156 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.codelabs.buildyourfirstmap.place
import com.google.android.gms.maps.model.LatLng
data class PlaceResponse(
val geometry: Geometry,
val name: String,
val vicinity: String,
val rating: Float
) {
data class Geometry(
val location: GeometryLocation
)
data class GeometryLocation(
val lat: Double,
val lng: Double
)
}
fun PlaceResponse.toPlace(): Place = Place(
name = name,
latLng = LatLng(geometry.location.lat, geometry.location.lng),
address = vicinity,
rating = rating
)
| apache-2.0 | 04df370387c8d23cf67886aa27628199 | 27.195122 | 75 | 0.709343 | 4.084806 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/bootimg/v2/BootV2.kt | 1 | 20174 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.bootimg.v2
import avb.AVBInfo
import cfig.Avb
import cfig.EnvironmentVerifier
import cfig.bootimg.Common
import cfig.bootimg.Common.Companion.deleleIfExists
import cfig.bootimg.Signer
import cfig.helper.Helper
import cfig.packable.VBMetaParser
import com.fasterxml.jackson.databind.ObjectMapper
import de.vandermeer.asciitable.AsciiTable
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
data class BootV2(
var info: MiscInfo = MiscInfo(),
var kernel: CommArgs = CommArgs(),
var ramdisk: CommArgs = CommArgs(),
var secondBootloader: CommArgs? = null,
var recoveryDtbo: CommArgsLong? = null,
var dtb: CommArgsLong? = null,
) {
data class MiscInfo(
var output: String = "",
var json: String = "",
var headerVersion: Int = 0,
var headerSize: Int = 0,
var loadBase: Long = 0,
var tagsOffset: Long = 0,
var board: String? = null,
var pageSize: Int = 0,
var cmdline: String = "",
var osVersion: String? = null,
var osPatchLevel: String? = null,
var hash: ByteArray? = byteArrayOf(),
var verify: String = "",
var imageSize: Long = 0,
)
data class CommArgs(
var file: String? = null,
var position: Long = 0,
var size: Int = 0,
var loadOffset: Long = 0,
)
data class CommArgsLong(
var file: String? = null,
var position: Long = 0,
var size: Int = 0,
var loadOffset: Long = 0,
)
companion object {
private val log = LoggerFactory.getLogger(BootV2::class.java)
private val workDir = Helper.prop("workDir")
fun parse(fileName: String): BootV2 {
val ret = BootV2()
FileInputStream(fileName).use { fis ->
val bh2 = BootHeaderV2(fis)
ret.info.let { theInfo ->
theInfo.output = File(fileName).name
theInfo.json = File(fileName).name.removeSuffix(".img") + ".json"
theInfo.pageSize = bh2.pageSize
theInfo.headerSize = bh2.headerSize
theInfo.headerVersion = bh2.headerVersion
theInfo.board = bh2.board
theInfo.cmdline = bh2.cmdline
theInfo.imageSize = File(fileName).length()
theInfo.tagsOffset = bh2.tagsOffset
theInfo.hash = bh2.hash
theInfo.osVersion = bh2.osVersion
theInfo.osPatchLevel = bh2.osPatchLevel
if (Avb.hasAvbFooter(fileName)) {
theInfo.verify = "VB2.0"
if (Avb.verifyAVBIntegrity(fileName, String.format(Helper.prop("avbtool"), "v1.2"))) {
theInfo.verify += " PASS"
} else {
theInfo.verify += " FAIL"
}
} else {
theInfo.verify = "VB1.0"
}
}
ret.kernel.let { theKernel ->
theKernel.file = "${workDir}kernel"
theKernel.size = bh2.kernelLength
theKernel.loadOffset = bh2.kernelOffset
theKernel.position = ret.getKernelPosition()
}
ret.ramdisk.let { theRamdisk ->
theRamdisk.size = bh2.ramdiskLength
theRamdisk.loadOffset = bh2.ramdiskOffset
theRamdisk.position = ret.getRamdiskPosition()
if (bh2.ramdiskLength > 0) {
theRamdisk.file = "${workDir}ramdisk.img"
}
}
if (bh2.secondBootloaderLength > 0) {
ret.secondBootloader = CommArgs()
ret.secondBootloader!!.size = bh2.secondBootloaderLength
ret.secondBootloader!!.loadOffset = bh2.secondBootloaderOffset
ret.secondBootloader!!.file = "${workDir}second"
ret.secondBootloader!!.position = ret.getSecondBootloaderPosition()
}
if (bh2.recoveryDtboLength > 0) {
ret.recoveryDtbo = CommArgsLong()
ret.recoveryDtbo!!.size = bh2.recoveryDtboLength
ret.recoveryDtbo!!.loadOffset = bh2.recoveryDtboOffset //Q
ret.recoveryDtbo!!.file = "${workDir}recoveryDtbo"
ret.recoveryDtbo!!.position = ret.getRecoveryDtboPosition()
}
if (bh2.dtbLength > 0) {
ret.dtb = CommArgsLong()
ret.dtb!!.size = bh2.dtbLength
ret.dtb!!.loadOffset = bh2.dtbOffset //Q
ret.dtb!!.file = "${workDir}dtb"
ret.dtb!!.position = ret.getDtbPosition()
}
}
return ret
}
}
private fun getHeaderSize(pageSize: Int): Int {
val pad = (pageSize - (1648 and (pageSize - 1))) and (pageSize - 1)
return pad + 1648
}
private fun getKernelPosition(): Long {
return getHeaderSize(info.pageSize).toLong()
}
private fun getRamdiskPosition(): Long {
return (getKernelPosition() + kernel.size +
Common.getPaddingSize(kernel.size, info.pageSize))
}
private fun getSecondBootloaderPosition(): Long {
return getRamdiskPosition() + ramdisk.size +
Common.getPaddingSize(ramdisk.size, info.pageSize)
}
private fun getRecoveryDtboPosition(): Long {
return if (this.secondBootloader == null) {
getSecondBootloaderPosition()
} else {
getSecondBootloaderPosition() + secondBootloader!!.size +
Common.getPaddingSize(secondBootloader!!.size, info.pageSize)
}
}
private fun getDtbPosition(): Long {
return if (this.recoveryDtbo == null) {
getRecoveryDtboPosition()
} else {
getRecoveryDtboPosition() + recoveryDtbo!!.size +
Common.getPaddingSize(recoveryDtbo!!.size, info.pageSize)
}
}
fun extractImages(): BootV2 {
val workDir = Helper.prop("workDir")
//info
ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(File(workDir + info.json), this)
//kernel
Common.dumpKernel(Helper.Slice(info.output, kernel.position.toInt(), kernel.size, kernel.file!!))
//ramdisk
if (this.ramdisk.size > 0) {
val fmt = Common.dumpRamdisk(
Helper.Slice(info.output, ramdisk.position.toInt(), ramdisk.size, ramdisk.file!!), "${workDir}root"
)
this.ramdisk.file = this.ramdisk.file!! + ".$fmt"
//dump info again
ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this)
}
//second bootloader
secondBootloader?.let {
Helper.extractFile(
info.output,
secondBootloader!!.file!!,
secondBootloader!!.position,
secondBootloader!!.size
)
}
//recovery dtbo
recoveryDtbo?.let {
Helper.extractFile(
info.output,
recoveryDtbo!!.file!!,
recoveryDtbo!!.position,
recoveryDtbo!!.size
)
}
//dtb
this.dtb?.let { _ ->
Common.dumpDtb(Helper.Slice(info.output, dtb!!.position.toInt(), dtb!!.size, dtb!!.file!!))
}
return this
}
fun extractVBMeta(): BootV2 {
if (this.info.verify.startsWith("VB2.0")) {
AVBInfo.parseFrom(info.output).dumpDefault(info.output)
if (File("vbmeta.img").exists()) {
log.warn("Found vbmeta.img, parsing ...")
VBMetaParser().unpack("vbmeta.img")
}
} else {
log.info("verify type is ${this.info.verify}, skip AVB parsing")
}
return this
}
fun printSummary(): BootV2 {
val workDir = Helper.prop("workDir")
val tableHeader = AsciiTable().apply {
addRule()
addRow("What", "Where")
addRule()
}
val tab = AsciiTable().let {
it.addRule()
it.addRow("image info", workDir + info.output.removeSuffix(".img") + ".json")
if (this.info.verify.startsWith("VB2.0")) {
it.addRule()
val verifyStatus = if (this.info.verify.contains("PASS")) {
"verified"
} else {
"verify fail"
}
it.addRow("AVB info [$verifyStatus]", Avb.getJsonFileName(info.output))
}
//kernel
it.addRule()
it.addRow("kernel", this.kernel.file)
File(Helper.prop("kernelVersionFile")).let { kernelVersionFile ->
if (kernelVersionFile.exists()) {
it.addRow("\\-- version " + kernelVersionFile.readLines().toString(), kernelVersionFile.path)
}
}
File(Helper.prop("kernelConfigFile")).let { kernelConfigFile ->
if (kernelConfigFile.exists()) {
it.addRow("\\-- config", kernelConfigFile.path)
}
}
//ramdisk
if (this.ramdisk.size > 0) {
it.addRule()
it.addRow("ramdisk", this.ramdisk.file)
it.addRow("\\-- extracted ramdisk rootfs", "${workDir}root")
}
//second
this.secondBootloader?.let { theSecondBootloader ->
if (theSecondBootloader.size > 0) {
it.addRule()
it.addRow("second bootloader", theSecondBootloader.file)
}
}
//dtbo
this.recoveryDtbo?.let { theDtbo ->
if (theDtbo.size > 0) {
it.addRule()
it.addRow("recovery dtbo", theDtbo.file)
}
}
//dtb
this.dtb?.let { theDtb ->
if (theDtb.size > 0) {
it.addRule()
it.addRow("dtb", theDtb.file)
if (File(theDtb.file + ".src").exists()) {
it.addRow("\\-- decompiled dts", theDtb.file + ".src")
}
}
}
//END
it.addRule()
it
}
val tabVBMeta = AsciiTable().let {
if (File("vbmeta.img").exists()) {
it.addRule()
it.addRow("vbmeta.img", Avb.getJsonFileName("vbmeta.img"))
it.addRule()
"\n" + it.render()
} else {
""
}
}
log.info(
"\n\t\t\tUnpack Summary of ${info.output}\n{}\n{}{}",
tableHeader.render(), tab.render(), tabVBMeta
)
return this
}
private fun toHeader(): BootHeaderV2 {
return BootHeaderV2(
kernelLength = kernel.size,
kernelOffset = kernel.loadOffset,
ramdiskLength = ramdisk.size,
ramdiskOffset = ramdisk.loadOffset,
secondBootloaderLength = if (secondBootloader != null) secondBootloader!!.size else 0,
secondBootloaderOffset = if (secondBootloader != null) secondBootloader!!.loadOffset else 0,
recoveryDtboLength = if (recoveryDtbo != null) recoveryDtbo!!.size else 0,
recoveryDtboOffset = if (recoveryDtbo != null) recoveryDtbo!!.loadOffset else 0,
dtbLength = if (dtb != null) dtb!!.size else 0,
dtbOffset = if (dtb != null) dtb!!.loadOffset else 0,
tagsOffset = info.tagsOffset,
pageSize = info.pageSize,
headerSize = info.headerSize,
headerVersion = info.headerVersion,
board = info.board.toString(),
cmdline = info.cmdline,
hash = info.hash,
osVersion = info.osVersion,
osPatchLevel = info.osPatchLevel
)
}
fun pack(): BootV2 {
//refresh kernel size
this.kernel.size = File(this.kernel.file!!).length().toInt()
//refresh ramdisk size
if (this.ramdisk.file.isNullOrBlank()) {
ramdisk.file = null
ramdisk.loadOffset = 0
} else {
if (File(this.ramdisk.file!!).exists() && !File(workDir + "root").exists()) {
//do nothing if we have ramdisk.img.gz but no /root
log.warn("Use prebuilt ramdisk file: ${this.ramdisk.file}")
} else {
File(this.ramdisk.file!!).deleleIfExists()
File(this.ramdisk.file!!.removeSuffix(".gz")).deleleIfExists()
//Common.packRootfs("${workDir}/root", this.ramdisk.file!!, Common.parseOsMajor(info.osVersion.toString()))
Common.packRootfs("${workDir}/root", this.ramdisk.file!!)
}
this.ramdisk.size = File(this.ramdisk.file!!).length().toInt()
}
//refresh second bootloader size
secondBootloader?.let { theSecond ->
theSecond.size = File(theSecond.file!!).length().toInt()
}
//refresh recovery dtbo size
recoveryDtbo?.let { theDtbo ->
theDtbo.size = File(theDtbo.file!!).length().toInt()
theDtbo.loadOffset = getRecoveryDtboPosition()
log.warn("using fake recoveryDtboOffset ${theDtbo.loadOffset} (as is in AOSP avbtool)")
}
//refresh dtb size
dtb?.let { theDtb ->
theDtb.size = File(theDtb.file!!).length().toInt()
}
//refresh image hash
info.hash = when (info.headerVersion) {
0 -> {
Common.hashFileAndSize(kernel.file, ramdisk.file, secondBootloader?.file)
}
1 -> {
Common.hashFileAndSize(
kernel.file, ramdisk.file,
secondBootloader?.file, recoveryDtbo?.file
)
}
2 -> {
Common.hashFileAndSize(
kernel.file, ramdisk.file,
secondBootloader?.file, recoveryDtbo?.file, dtb?.file
)
}
else -> {
throw IllegalArgumentException("headerVersion ${info.headerVersion} illegal")
}
}
val encodedHeader = this.toHeader().encode()
//write
FileOutputStream("${info.output}.clear", false).use { fos ->
fos.write(encodedHeader)
fos.write(ByteArray((Helper.round_to_multiple(encodedHeader.size, info.pageSize) - encodedHeader.size)))
}
log.info("Writing data ...")
//boot image size may > 64MB. Fix issue #57
val bytesV2 = ByteBuffer.allocate(maxOf(1024 * 1024 * 64, info.imageSize.toInt()))
.let { bf ->
bf.order(ByteOrder.LITTLE_ENDIAN)
Common.writePaddedFile(bf, kernel.file!!, info.pageSize)
if (ramdisk.size > 0) {
Common.writePaddedFile(bf, ramdisk.file!!, info.pageSize)
}
secondBootloader?.let {
Common.writePaddedFile(bf, secondBootloader!!.file!!, info.pageSize)
}
recoveryDtbo?.let {
Common.writePaddedFile(bf, recoveryDtbo!!.file!!, info.pageSize)
}
dtb?.let {
Common.writePaddedFile(bf, dtb!!.file!!, info.pageSize)
}
bf
}
//write
FileOutputStream("${info.output}.clear", true).use { fos ->
fos.write(bytesV2.array(), 0, bytesV2.position())
}
this.toCommandLine().apply {
addArgument("${info.output}.google")
log.info(this.toString())
DefaultExecutor().execute(this)
}
Common.assertFileEquals("${info.output}.clear", "${info.output}.google")
return this
}
private fun toCommandLine(): CommandLine {
val cmdPrefix = if (EnvironmentVerifier().isWindows) "python " else ""
val ret = CommandLine.parse(cmdPrefix + Helper.prop("mkbootimg"))
ret.addArgument(" --header_version ")
ret.addArgument(info.headerVersion.toString())
ret.addArgument(" --base ")
ret.addArgument("0x" + java.lang.Long.toHexString(0))
ret.addArgument(" --kernel ")
ret.addArgument(kernel.file!!)
ret.addArgument(" --kernel_offset ")
ret.addArgument("0x" + Integer.toHexString(kernel.loadOffset.toInt()))
if (this.ramdisk.size > 0) {
ret.addArgument(" --ramdisk ")
ret.addArgument(ramdisk.file)
}
ret.addArgument(" --ramdisk_offset ")
ret.addArgument("0x" + Integer.toHexString(ramdisk.loadOffset.toInt()))
if (secondBootloader != null) {
ret.addArgument(" --second ")
ret.addArgument(secondBootloader!!.file!!)
ret.addArgument(" --second_offset ")
ret.addArgument("0x" + Integer.toHexString(secondBootloader!!.loadOffset.toInt()))
}
if (!info.board.isNullOrBlank()) {
ret.addArgument(" --board ")
ret.addArgument(info.board)
}
if (info.headerVersion > 0) {
if (recoveryDtbo != null) {
ret.addArgument(" --recovery_dtbo ")
ret.addArgument(recoveryDtbo!!.file!!)
}
}
if (info.headerVersion > 1) {
if (dtb != null) {
ret.addArgument("--dtb ")
ret.addArgument(dtb!!.file!!)
ret.addArgument("--dtb_offset ")
ret.addArgument("0x" + java.lang.Long.toHexString(dtb!!.loadOffset))
}
}
ret.addArgument(" --pagesize ")
ret.addArgument(info.pageSize.toString())
ret.addArgument(" --cmdline ")
ret.addArgument(info.cmdline, false)
if (!info.osVersion.isNullOrBlank()) {
ret.addArgument(" --os_version ")
ret.addArgument(info.osVersion)
}
if (!info.osPatchLevel.isNullOrBlank()) {
ret.addArgument(" --os_patch_level ")
ret.addArgument(info.osPatchLevel)
}
ret.addArgument(" --tags_offset ")
ret.addArgument("0x" + Integer.toHexString(info.tagsOffset.toInt()))
ret.addArgument(" --id ")
ret.addArgument(" --output ")
//ret.addArgument("boot.img" + ".google")
log.debug("To Commandline: $ret")
return ret
}
fun sign(): BootV2 {
//unify with v1.1/v1.2 avbtool
val avbtool = String.format(Helper.prop("avbtool"), "v1.2")
if (info.verify.startsWith("VB2.0")) {
Signer.signAVB(info.output, this.info.imageSize, avbtool)
log.info("Adding hash_footer with verified-boot 2.0 style")
} else {
Signer.signVB1(info.output + ".clear", info.output + ".signed")
}
return this
}
}
| apache-2.0 | 700280f14a670338e5deb3360b16c7e6 | 37.870906 | 123 | 0.534698 | 4.601734 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/cause/entity/damage/source/DamageSource.kt | 1 | 3755 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("FunctionName", "NOTHING_TO_INLINE")
package org.lanternpowered.api.cause.entity.damage.source
import org.lanternpowered.api.cause.entity.damage.DamageType
import org.lanternpowered.api.entity.Entity
import org.lanternpowered.api.registry.builderOf
import org.lanternpowered.api.world.Location
import org.spongepowered.api.block.BlockSnapshot
import org.spongepowered.api.entity.FallingBlock
typealias DamageSource = org.spongepowered.api.event.cause.entity.damage.source.DamageSource
typealias BlockDamageSource = org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource
typealias EntityDamageSource = org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource
typealias FallingBlockDamageSource = org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource
typealias IndirectEntityDamageSource = org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource
private typealias DamageSourceBuilder = org.spongepowered.api.event.cause.entity.damage.source.DamageSource.Builder
private typealias BlockDamageSourceBuilder = org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource.Builder
private typealias EntityDamageSourceBuilder = org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource.Builder
private typealias IndirectEntityDamageSourceBuilder = org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource.Builder
private typealias FallingBlockDamageSourceBuilder = org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource.Builder
/**
* Constructs a new [DamageSource] with the given [DamageType].
*/
inline fun damageSourceOf(type: DamageType): DamageSource =
builderOf<DamageSourceBuilder>().type(type).build()
/**
* Constructs a new [BlockDamageSource] with the given [DamageType] and [Location].
*/
inline fun blockDamageSourceOf(type: DamageType, location: Location): BlockDamageSource =
builderOf<BlockDamageSourceBuilder>().type(type).block(location).build()
/**
* Constructs a new [BlockDamageSource] with the given [DamageType] and [BlockSnapshot].
*/
inline fun blockDamageSourceOf(type: DamageType, snapshot: BlockSnapshot): BlockDamageSource =
builderOf<BlockDamageSourceBuilder>().type(type).block(snapshot).build()
/**
* Constructs a new [EntityDamageSource] with the given [DamageType] and [Entity].
*/
inline fun entityDamageSourceOf(type: DamageType, entity: Entity): EntityDamageSource =
builderOf<EntityDamageSourceBuilder>().type(type).entity(entity).build()
/**
* Constructs a new [FallingBlockDamageSource] with the given [DamageType], [FallingBlock] and builder function.
*/
inline fun entityDamageSourceOf(type: DamageType, fallingBlock: FallingBlock): FallingBlockDamageSource =
builderOf<FallingBlockDamageSourceBuilder>().type(type).entity(fallingBlock).build()
fun EntityDamageSource.indirectBy(entity: Entity): IndirectEntityDamageSource =
builderOf<IndirectEntityDamageSourceBuilder>().apply {
val source = this@indirectBy
if (source.isAbsolute)
absolute()
if (source.isBypassingArmor)
bypassesArmor()
if (source.isExplosive)
explosion()
if (source.isFire)
fire()
if (source.isMagic)
magical()
}.build()
| mit | dd27a33fa4f5e5b46c7458d95224a3b9 | 47.766234 | 143 | 0.770439 | 4.326037 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/completion/handlers/LatexCommandArgumentInsertHandler.kt | 1 | 2925 | package nl.hannahsten.texifyidea.completion.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.TemplateImpl
import com.intellij.codeInsight.template.impl.TextExpression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import nl.hannahsten.texifyidea.lang.commands.Argument
import nl.hannahsten.texifyidea.lang.commands.RequiredArgument
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.util.endOffset
import nl.hannahsten.texifyidea.util.files.psiFile
import nl.hannahsten.texifyidea.util.parentOfType
/**
* @author Hannah Schellekens
*/
class LatexCommandArgumentInsertHandler(val arguments: List<Argument>? = null) : InsertHandler<LookupElement> {
override fun handleInsert(insertionContext: InsertionContext, lookupElement: LookupElement) {
insert(insertionContext, lookupElement)
}
private fun insert(context: InsertionContext, lookupElement: LookupElement) {
val editor = context.editor
val document = editor.document
val caret = editor.caretModel
val offset = caret.offset
// When not followed by { or [ (whichever the first parameter starts with) insert the parameters.
if (arguments != null && (
offset >= document.textLength - 1 || document.getText(TextRange.from(offset, 1)) !in setOf("{", "[")
)
) {
insertParametersLiveTemplate(editor)
}
else {
skipParameters(editor, lookupElement)
}
}
private fun insertParametersLiveTemplate(editor: Editor) {
// arguments is not null, we checked when calling this function.
val template = TemplateImpl(
"",
arguments!!.mapIndexed { index: Int, argument: Argument ->
if (argument is RequiredArgument) "{\$__Variable$index\$}" else "[\$__Variable$index\$]"
}.joinToString(""),
""
)
repeat(arguments.size) { template.addVariable(TextExpression(""), true) }
TemplateManager.getInstance(editor.project).startTemplate(editor, template)
}
private fun skipParameters(editor: Editor, lookupElement: LookupElement) {
val document = editor.document
val file = document.psiFile(editor.project ?: return)
val caret = editor.caretModel
val extraSpaces = lookupElement.lookupString.takeLastWhile { it == ' ' }.length
val psiElement = file?.findElementAt(caret.offset + extraSpaces) ?: return
if (psiElement.text in setOf("{", "[")) {
caret.moveToOffset((psiElement.parentOfType(LatexCommands::class)?.endOffset() ?: return) - extraSpaces)
}
}
} | mit | 01ca4dc1de46988f52729bdef0801686 | 42.671642 | 116 | 0.702222 | 4.899497 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/settings/conventions/TexifyConventionsScheme.kt | 1 | 3899 | package nl.hannahsten.texifyidea.settings.conventions
import nl.hannahsten.texifyidea.lang.DefaultEnvironment.*
import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand.*
import nl.hannahsten.texifyidea.lang.commands.LatexListingCommand.LSTINPUTLISTING
import nl.hannahsten.texifyidea.util.magic.env
/**
* A scheme instance for storing settings regarding Texify conventions. Default values of this class represent the
* default settings
*
* Scheme instances generally store settings for a specific scope. Concrete scheme implementations decide on which
* scopes make sense. For example, a scheme could represent different color settings for code or different inspection
* rules. In the context of Texify conventions, a scheme stores either project or IDE level conventions.
*
* Instances must be serializable since they are persisted as part of [TexifyConventionsGlobalState] or
* [TexifyConventionsProjectState]. Changing the properties to "val" silently fails serialization.
*/
data class TexifyConventionsScheme(
/**
* The name of the scheme
*/
var myName: String = DEFAULT_SCHEME_NAME,
/**
* The maximum section size before the corresponding inspection issues a warning.
*/
var maxSectionSize: Int = 4000,
/**
* List of configured conventions.
* The default conventions mirror the settings currently read from *Magic classes and the existing settings UI.
* For example, which label conventions are enabled by default corresponds to the minimum section level which
* should receive a label, but provides more fine-grained control.
*/
var labelConventions: MutableList<LabelConvention> = mutableListOf(
LabelConvention(true, LabelConventionType.COMMAND, PART.command, "part"),
LabelConvention(true, LabelConventionType.COMMAND, CHAPTER.command, "ch"),
LabelConvention(true, LabelConventionType.COMMAND, SECTION.command, "sec"),
LabelConvention(true, LabelConventionType.COMMAND, SUBSECTION.command, "subsec"),
LabelConvention(false, LabelConventionType.COMMAND, SUBSUBSECTION.command, "subsubsec"),
LabelConvention(false, LabelConventionType.COMMAND, PARAGRAPH.command, "par"),
LabelConvention(false, LabelConventionType.COMMAND, SUBPARAGRAPH.command, "subpar"),
LabelConvention(false, LabelConventionType.COMMAND, ITEM.command, "itm"),
LabelConvention(true, LabelConventionType.COMMAND, LSTINPUTLISTING.command, "lst"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, FIGURE.env, "fig"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, TABLE.env, "tab"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, EQUATION.env, "eq"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, ALGORITHM.env, "alg"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, LISTINGS.env, "lst"),
LabelConvention(true, LabelConventionType.ENVIRONMENT, VERBATIM_CAPITAL.env, "verb"),
)
) : com.intellij.openapi.options.Scheme {
val isProjectScheme: Boolean
get() = name == PROJECT_SCHEME_NAME
companion object {
const val DEFAULT_SCHEME_NAME = "Default"
const val PROJECT_SCHEME_NAME = "Project"
}
fun deepCopy(): TexifyConventionsScheme =
copy(labelConventions = labelConventions.map { it.copy() }.toMutableList())
/**
* Same as [myName].
*/
override fun getName() = myName
/**
* Copy all settings except the name from the given scheme. This method is useful when you want to transfer settings
* from one instance to another.
*/
fun copyFrom(scheme: TexifyConventionsScheme) {
if (scheme != this) {
maxSectionSize = scheme.maxSectionSize
labelConventions.clear()
labelConventions.addAll(scheme.labelConventions)
}
}
}
| mit | 53aa27ede633a23f49632b05b24a432e | 45.416667 | 120 | 0.7307 | 4.658303 | false | false | false | false |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/repo/internals/migrations/Migration28to29.kt | 1 | 1635 | package voice.data.repo.internals.migrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.squareup.anvil.annotations.ContributesMultibinding
import org.json.JSONObject
import voice.common.AppScope
import voice.logging.core.Logger
import java.io.File
import javax.inject.Inject
@ContributesMultibinding(
scope = AppScope::class,
boundType = Migration::class,
)
class Migration28to29
@Inject constructor() : IncrementalMigration(28) {
override fun migrate(db: SupportSQLiteDatabase) {
db.query("TABLE_BOOK", arrayOf("BOOK_JSON", "BOOK_ID"))
.use { cursor ->
while (cursor.moveToNext()) {
val book = JSONObject(cursor.getString(0))
val chapters = book.getJSONArray("chapters")
for (i in 0 until chapters.length()) {
val chapter = chapters.getJSONObject(i)
val fileName = File(chapter.getString("path")).name
val dotIndex = fileName.lastIndexOf(".")
val chapterName = if (dotIndex > 0) {
fileName.substring(0, dotIndex)
} else {
fileName
}
chapter.put("name", chapterName)
}
val cv = ContentValues()
Logger.d("so saving book=$book")
cv.put("BOOK_JSON", book.toString())
db.update(
"TABLE_BOOK",
SQLiteDatabase.CONFLICT_FAIL,
cv,
"BOOK_ID" + "=?",
arrayOf(cursor.getLong(1).toString()),
)
}
}
}
}
| gpl-3.0 | 0d35bfb8ef4098b84d4408c9b7fa1c1b | 31.058824 | 63 | 0.625688 | 4.529086 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/logistics/SessionManager.kt | 1 | 12340 | @file:Suppress("unused", "MemberVisibilityCanBePrivate")
package com.duopoints.android.logistics
import com.duopoints.android.Calls
import com.duopoints.android.rest.RestUtils
import com.duopoints.android.rest.RestUtils.isNotFoundException
import com.duopoints.android.rest.models.composites.*
import com.duopoints.android.rest.models.dbviews.UserData
import com.duopoints.android.utils.ReactiveUtils
import com.google.common.base.Optional
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import io.reactivex.subjects.BehaviorSubject
import java.util.*
object SessionManager {
private const val KEY = "USER_DATA"
private val signedInUser = BehaviorSubject.create<Optional<UserData>>()
private val signedInUserJwt = BehaviorSubject.createDefault<Optional<String>>(Optional.absent())
private val userFriendshipRequests = BehaviorSubject.createDefault(Optional.absent<List<CompositeFriendshipRequest>>())
private val userFriendships = BehaviorSubject.createDefault(Optional.absent<List<CompositeFriendship>>())
private val userRelationshipRequests = BehaviorSubject.createDefault(Optional.absent<List<CompositeRelationshipRequest>>())
private val userRelationship = BehaviorSubject.createDefault(Optional.absent<CompositeRelationship>())
private val userRelationshipBreakupRequest = BehaviorSubject.createDefault(Optional.absent<CompositeRelationshipBreakupRequest>())
private val userLikedPointEvents = BehaviorSubject.createDefault<List<UUID>>(ArrayList())
private val userLikedLevelUps = BehaviorSubject.createDefault<List<UUID>>(ArrayList())
// Creates empty observable to listen to when points are given.
private val pointsGivenEvent = BehaviorSubject.createDefault(false)
/**
* Only the User is stored as persisted because everything is reloaded
* if app is killed and reloaded.
*/
init {
signedInUser.onNext(Optional.fromNullable(Pers.get<UserData>(KEY)))
}
/*********************
* USER ACTIONS
*********************/
/**
* This will clear the User stored in the Session and also any data related to the user.
*
*
* Basically used for Logging out the user or clearing app data.
*/
fun clearUser() {
Pers.delete(KEY)
signedInUser.onNext(Optional.absent())
signedInUserJwt.onNext(Optional.absent())
userFriendshipRequests.onNext(Optional.absent())
userFriendships.onNext(Optional.absent())
userRelationshipRequests.onNext(Optional.absent())
userRelationship.onNext(Optional.absent())
userRelationshipBreakupRequest.onNext(Optional.absent())
userLikedPointEvents.onNext(ArrayList())
userLikedLevelUps.onNext(ArrayList())
}
/***********
* GETTERS
***********/
fun getUser(): UserData {
if (!signedInUser.value.isPresent) {
throw RuntimeException("UserData Null! Error!")
}
return signedInUser.value.get()
}
fun getNullableUser(): UserData? {
return if (signedInUser.value.isPresent) signedInUser.value.get() else null
}
fun getUserJwt(): String? {
return if (signedInUserJwt.value.isPresent) signedInUserJwt.value.get() else null
}
fun getUserFriendshipRequests(): List<CompositeFriendshipRequest>? {
return if (userFriendshipRequests.value.isPresent) userFriendshipRequests.value.get() else null
}
fun getUserFriendships(): List<CompositeFriendship>? {
return if (userFriendships.value.isPresent) userFriendships.value.get() else null
}
fun getUserRelationshipRequests(): List<CompositeRelationshipRequest>? {
return if (userRelationshipRequests.value.isPresent) userRelationshipRequests.value.get() else null
}
fun getUserRelationshipBreakupRequests(): CompositeRelationshipBreakupRequest? {
return if (userRelationshipBreakupRequest.value.isPresent) userRelationshipBreakupRequest.value.get() else null
}
fun getUserRelationship(): CompositeRelationship? {
return if (userRelationship.value.isPresent) userRelationship.value.get() else null
}
fun getUserLikedPointEvents(): List<UUID> {
return userLikedPointEvents.value
}
fun getUserLikedLevelUps(): List<UUID> {
return userLikedLevelUps.value
}
/***********
* SETTERS
***********/
// Nullable because they can be reset this way
fun setUser(user: UserData) {
Pers.put(KEY, user)
signedInUser.onNext(Optional.of(user))
}
fun setUserJwt(jwt: String) {
this.signedInUserJwt.onNext(Optional.of(jwt))
}
fun setUserFriendshipRequests(userFriendshipRequests: List<CompositeFriendshipRequest>?) {
this.userFriendshipRequests.onNext(Optional.fromNullable(userFriendshipRequests))
}
fun setUserFriendships(userFriendships: List<CompositeFriendship>?) {
this.userFriendships.onNext(Optional.fromNullable(userFriendships))
}
fun setUserRelationshipRequests(userRelationshipRequests: List<CompositeRelationshipRequest>?) {
this.userRelationshipRequests.onNext(Optional.fromNullable(userRelationshipRequests))
}
fun setUserRelationshipBreakupRequests(userRelationshipBreakupRequests: CompositeRelationshipBreakupRequest?) {
this.userRelationshipBreakupRequest.onNext(Optional.fromNullable(userRelationshipBreakupRequests))
}
fun setUserRelationship(userRelationship: CompositeRelationship?) {
this.userRelationship.onNext(Optional.fromNullable(userRelationship))
}
fun setUserLikedPointEvents(userLikedPointEvents: List<UUID>) {
this.userLikedPointEvents.onNext(userLikedPointEvents)
}
fun setUserLikedLevelUps(userLikedLevelUps: List<UUID>) {
this.userLikedLevelUps.onNext(userLikedLevelUps)
}
fun newPointGiven() {
this.pointsGivenEvent.onNext(true)
}
/**************
* OBSERVERS
**************/
/**
* NOTE: Because BehaviourSubjects always emit their current value when subscribed to, first
* items being emitted is being skipped to only get items emitted after subscription.
*/
fun observeUser(): Observable<Optional<UserData>> {
return signedInUser.skip(1)
}
fun observeUserFriendRequests(): Observable<Optional<List<CompositeFriendshipRequest>>> {
return userFriendshipRequests.skip(1)
}
fun observeUserFriendships(): Observable<Optional<List<CompositeFriendship>>> {
return userFriendships.skip(1)
}
fun observeUserRelationshipRequests(): Observable<Optional<List<CompositeRelationshipRequest>>> {
return userRelationshipRequests.skip(1)
}
fun observeUserRelationship(): Observable<Optional<CompositeRelationship>> {
return userRelationship.skip(1)
}
fun observeUserRelationshipBreakupRequest(): Observable<Optional<CompositeRelationshipBreakupRequest>> {
return userRelationshipBreakupRequest.skip(1)
}
fun observeUserLikedEvents(): Observable<List<UUID>> {
return userLikedPointEvents.skip(1)
}
fun observeUserLevelUps(): Observable<List<UUID>> {
return userLikedLevelUps.skip(1)
}
fun observePointsGiven(): Observable<Boolean> {
return pointsGivenEvent.skip(1)
}
fun observeUserWithDefault(): Observable<Optional<UserData>> {
return signedInUser
}
fun observeUserFriendRequestsWithDefault(): Observable<Optional<List<CompositeFriendshipRequest>>> {
return userFriendshipRequests
}
fun observeUserFriendshipsWithDefault(): Observable<Optional<List<CompositeFriendship>>> {
return userFriendships
}
fun observeUserRelationshipRequestsWithDefault(): Observable<Optional<List<CompositeRelationshipRequest>>> {
return userRelationshipRequests
}
fun observeUserRelationshipWithDefault(): Observable<Optional<CompositeRelationship>> {
return userRelationship
}
fun observeUserRelationshipBreakupRequestWithDefault(): Observable<Optional<CompositeRelationshipBreakupRequest>> {
return userRelationshipBreakupRequest
}
fun observeUserLikedEventsWithDefault(): Observable<List<UUID>> {
return userLikedPointEvents
}
fun observeUserLevelUpsWithDefault(): Observable<List<UUID>> {
return userLikedLevelUps
}
fun observePointsGivenWithDefault(): Observable<Boolean> {
return pointsGivenEvent
}
/***********
* SYNC
***********/
fun syncUser() {
syncUserObservable().subscribe({ setUser(it) }, { it.printStackTrace() })
}
fun syncUserObservable(): Maybe<UserData> {
return Calls.userService.getUser(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncFriendRequests() {
syncFriendRequestsObservable().subscribe({ setUserFriendshipRequests(it) }, { it.printStackTrace() })
}
fun syncFriendRequestsObservable(): Maybe<List<CompositeFriendshipRequest>> {
return Calls.friendService.getAllActiveCompositeFriendRequests(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncFriendships() {
syncFriendshipsObservable().subscribe({ setUserFriendships(it) }, { it.printStackTrace() })
}
fun syncFriendshipsObservable(): Maybe<List<CompositeFriendship>> {
return Calls.friendService.getAllActiveCompositeFriendships(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncRelationshipRequests() {
syncRelationshipRequestsObservable().subscribe({ setUserRelationshipRequests(it) }, { it.printStackTrace() })
}
fun syncRelationshipRequestsObservable(): Maybe<List<CompositeRelationshipRequest>> {
return Calls.relationshipService.getAllActiveCompositeRelationshipRequests(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncRelationship() {
syncRelationshipObservable().subscribe({ setUserRelationship(it) }, {
if (isNotFoundException(it)) {
setUserRelationship(null)
} else {
it.printStackTrace()
}
})
}
fun syncRelationshipObservable(): Maybe<CompositeRelationship> {
return Calls.relationshipService.getUserActiveCompositeRelationship(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncRelationshipBreakup() {
val relationship = getUserRelationship()
if (relationship != null) {
syncRelationshipBreakupObservable(relationship.relationshipUuid)
.subscribe({ setUserRelationshipBreakupRequests(it) }, { throwable ->
if (isNotFoundException(throwable)) {
setUserRelationshipBreakupRequests(null)
} else {
throwable.printStackTrace()
}
})
}
}
fun syncRelationshipBreakupObservable(relationshipUuid: UUID): Maybe<CompositeRelationshipBreakupRequest> {
return Calls.relationshipService
.getActiveCompositeRelationshipBreakupRequest(relationshipUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncAllPointEventsLikes() {
syncAllPointEventsLikesObservable().subscribe(Consumer { setUserLikedPointEvents(it) }, RestUtils.notNotFound({ it.printStackTrace() }))
}
fun syncAllPointEventsLikesObservable(): Maybe<List<UUID>> {
return Calls.pointService.getAllPointEventLikes(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
fun syncAllLevelUpsLikes() {
syncAllLevelUpsLikesObservable().subscribe({ setUserLikedLevelUps(it) }, { it.printStackTrace() })
}
fun syncAllLevelUpsLikesObservable(): Maybe<List<UUID>> {
return Calls.userService.getAllLevelUpLikes(getUser().userUuid)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
}
}
| gpl-3.0 | c0288b9b8fd5b1dc4ae2633dea34dafc | 34.976676 | 144 | 0.70624 | 5.063603 | false | false | false | false |
Gekkot/SnowboardSpeed | app/src/main/java/gekkot/com/snowspeed/data/DistanceHelper.kt | 1 | 908 | package gekkot.com.snowspeed.data
import android.location.Location
/**
* Created by Konstantin Sorokin on 09.03.2017.
*/
object DistanceHelper {
fun distFrom(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Double {
val earthRadius = 6371000.0 //meters
val dLat = Math.toRadians((lat2 - lat1).toDouble())
val dLng = Math.toRadians((lng2 - lng1).toDouble())
val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1.toDouble())) * Math.cos(Math.toRadians(lat2.toDouble())) *
Math.sin(dLng / 2) * Math.sin(dLng / 2)
val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
val dist = (earthRadius * c)
return dist
}
fun distFrom(location1:Location,location2: Location ): Double {
return distFrom(location1.latitude, location1.longitude, location2.latitude, location2.longitude)
}
} | apache-2.0 | 13c2f17d4e16f7ec1a9b40367858b60c | 36.875 | 145 | 0.643172 | 3.313869 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/sync/GivenSynchronizingLibraries/AndAStoredFileWriteErrorOccurs/WhenSynchronizing.kt | 1 | 5183 | package com.lasthopesoftware.bluewater.client.stored.sync.GivenSynchronizingLibraries.AndAStoredFileWriteErrorOccurs
import androidx.test.core.app.ApplicationProvider
import com.lasthopesoftware.AndroidContext
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.stored.library.items.files.PruneStoredFiles
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobState
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobStatus
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.exceptions.StoredFileWriteException
import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile
import com.lasthopesoftware.bluewater.client.stored.library.sync.CheckForSync
import com.lasthopesoftware.bluewater.client.stored.library.sync.ControlLibrarySyncs
import com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.lasthopesoftware.resources.FakeMessageBus
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import io.reactivex.Observable
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.*
class WhenSynchronizing : AndroidContext() {
companion object {
private val random = Random()
private val storedFiles = arrayOf(
StoredFile().setId(random.nextInt()).setServiceId(1).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(2).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(4).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(5).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(7).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(114).setLibraryId(4),
StoredFile().setId(random.nextInt()).setServiceId(92).setLibraryId(4)
)
private val expectedStoredFileJobs = storedFiles.filter { f: StoredFile -> f.serviceId != 7 }
private val fakeMessageSender = FakeMessageBus(ApplicationProvider.getApplicationContext())
private val filePruner by lazy {
mockk<PruneStoredFiles>()
.apply {
every { pruneDanglingFiles() } returns Unit.toPromise()
}
}
}
override fun before() {
val libraryProvider = mockk<ILibraryProvider>()
every { libraryProvider.allLibraries } returns Promise(listOf(Library().setId(4)))
val librarySyncHandler = mockk<ControlLibrarySyncs>()
every { librarySyncHandler.observeLibrarySync(any()) } returns Observable.concat(
Observable
.fromArray(*storedFiles)
.filter { f -> f.serviceId != 7 }
.flatMap { f ->
Observable.just(
StoredFileJobStatus(mockk(), f, StoredFileJobState.Queued),
StoredFileJobStatus(mockk(), f, StoredFileJobState.Downloading),
StoredFileJobStatus(mockk(), f, StoredFileJobState.Downloaded)
)
},
Observable
.fromArray(*storedFiles)
.filter { f -> f.serviceId == 7 }
.flatMap({ f ->
Observable.concat(
Observable.just(
StoredFileJobStatus(mockk(), f, StoredFileJobState.Queued),
StoredFileJobStatus(mockk(), f, StoredFileJobState.Downloading),
),
Observable.error(
StoredFileWriteException(mockk(), f)
)
)
}, true)
)
val checkSync = mockk<CheckForSync>()
with (checkSync) {
every { promiseIsSyncNeeded() } returns Promise(true)
}
val synchronization = StoredFileSynchronization(
libraryProvider,
fakeMessageSender,
filePruner,
checkSync,
librarySyncHandler
)
synchronization.streamFileSynchronization().blockingAwait()
}
@Test
fun thenTheStoredFilesAreBroadcastAsQueued() {
assertThat(
fakeMessageSender.recordedIntents
.filter { i -> StoredFileSynchronization.onFileQueuedEvent == i.action }
.map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) })
.isSubsetOf(storedFiles.map { obj -> obj.id })
}
@Test
fun thenTheStoredFilesAreBroadcastAsDownloading() {
assertThat(
fakeMessageSender.recordedIntents
.filter { i -> StoredFileSynchronization.onFileDownloadingEvent == i.action }
.map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) })
.isSubsetOf(storedFiles.map { obj -> obj.id })
}
@Test
fun thenTheWriteErrorsIsBroadcast() {
assertThat(
fakeMessageSender.recordedIntents
.filter { i -> StoredFileSynchronization.onFileWriteErrorEvent == i.action }
.map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) })
.containsExactlyElementsOf(storedFiles.filter { f -> f.serviceId == 7 }.map { obj -> obj.id })
}
@Test
fun thenTheStoredFilesAreBroadcastAsDownloaded() {
assertThat(
fakeMessageSender.recordedIntents
.filter { i -> StoredFileSynchronization.onFileDownloadedEvent == i.action }
.map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) })
.isSubsetOf(expectedStoredFileJobs.map { obj -> obj.id })
}
}
| lgpl-3.0 | 79ff82d38f7cbaf834faf554265c602b | 38.869231 | 116 | 0.764615 | 4.234477 | false | false | false | false |
FHannes/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/ui/Notifier.kt | 7 | 1467 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.ui
import com.intellij.testGuiFramework.recorder.components.GuiRecorderComponent
import javax.swing.SwingUtilities
/**
* @author Sergey Karashevich
*/
object Notifier {
val LONG_OPERATION_PREFIX = "<long>"
fun updateStatus(statusMessage: String) {
if (GuiRecorderComponent.getFrame() == null) return
val guiScriptEditorPanel = GuiRecorderComponent.getFrame()!!.getGuiScriptEditorPanel()
val statusHandler: (String) -> Unit = { status ->
if (status.startsWith(LONG_OPERATION_PREFIX)) {
guiScriptEditorPanel.updateStatusWithProgress(status.removePrefix(LONG_OPERATION_PREFIX))
}
else {
guiScriptEditorPanel.stopProgress()
guiScriptEditorPanel.updateStatus(status)
}
}
SwingUtilities.invokeLater { statusHandler.invoke(statusMessage) }
}
} | apache-2.0 | 5d46c90d8f62a4706ff94d58346bf957 | 31.622222 | 97 | 0.73756 | 4.418675 | false | true | false | false |
alphafoobar/intellij-community | platform/configuration-store-impl/src/FileBasedStorage.kt | 2 | 10756 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.FileStorage
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.store.ReadOnlyModificationException
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import org.jdom.Element
import org.jdom.JDOMException
import org.jdom.Parent
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.ByteBuffer
open class FileBasedStorage(file: File,
fileSpec: String,
rootElementName: String,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider), FileStorage {
private volatile var cachedVirtualFile: VirtualFile? = null
private var lineSeparator: LineSeparator? = null
private var blockSavingTheContent = false
volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode() && file.getPath().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog: Boolean = false
// we never set io file to null
override fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (!storage.blockSavingTheContent) {
super.save()
}
}
override fun saveLocally(element: Element?) {
if (storage.lineSeparator == null) {
storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
}
val virtualFile = storage.getVirtualFile()
if (element == null) {
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog)
}
}
}
override fun getVirtualFile(): VirtualFile? {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByIoFile(file)
cachedVirtualFile = result
}
return cachedVirtualFile
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
try {
val file = getVirtualFile()
if (file == null || file.isDirectory() || !file.isValid()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}")
}
}
else if (file.getLength() == 0L) {
processReadException(null)
}
else {
val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray()))
lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.loadDocument(charBuffer).detachRootElement()
}
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
private fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated && (isProjectOrModuleFile(fileSpec) || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (!ApplicationManager.getApplication().isUnitTestMode() && !ApplicationManager.getApplication().isHeadlessEnvironment()) {
if (e != null) {
LOG.info(e)
}
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.getMessage()}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING).notify(null)
}
}
override fun toString() = file.systemIndependentPath
}
fun writeFile(file: File?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile {
val result = if (file != null && (virtualFile == null || !virtualFile.isValid())) {
StorageUtil.getOrCreateVirtualFile(requestor, file)
}
else {
virtualFile!!
}
if (LOG.isDebugEnabled() || ApplicationManager.getApplication().isUnitTestMode()) {
val content = element.toBufferExposingByteArray(lineSeparator.getSeparatorString())
if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) {
throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.getName()}")
}
else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode()) {
StorageUtil.DEBUG_LOG = "${result.getPath()}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------"
}
}
doWrite(requestor, result, element, lineSeparator, prependXmlProlog)
return result
}
private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray()
private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size() + lineSeparator.getSeparatorBytes().size()
if (result.getLength().toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size(), lineSeparator.getSeparatorBytes()))) {
return false
}
for (i in headerLength..oldContent.size() - 1) {
if (oldContent[i] != content.getInternalBuffer()[i - headerLength]) {
return false
}
}
return true
}
private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
if (LOG.isDebugEnabled()) {
LOG.debug("Save ${file.getPresentableUrl()}")
}
val token = WriteAction.start()
try {
val out = file.getOutputStream(requestor)
try {
if (prependXmlProlog) {
out.write(XML_PROLOG)
out.write(lineSeparator.getSeparatorBytes())
}
if (content is Element) {
JDOMUtil.writeParent(content, out, lineSeparator.getSeparatorString())
}
else {
(content as BufferExposingByteArrayOutputStream).writeTo(out)
}
}
finally {
out.close()
}
}
catch (e: FileNotFoundException) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = if (content is Element) content.toBufferExposingByteArray(lineSeparator.getSeparatorString()) else (content as BufferExposingByteArrayOutputStream)
throw ReadOnlyModificationException(file, e, object : StateStorage.SaveSession {
override fun save() {
doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog)
}
})
}
finally {
token.finish()
}
}
fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.writeParent(this, out, lineSeparator)
return out
}
public fun isProjectOrModuleFile(fileSpec: String): Boolean = StoragePathMacros.PROJECT_FILE == fileSpec || fileSpec.startsWith(StoragePathMacros.PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE
fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: File, requestor: Any, virtualFile: VirtualFile?) {
if (virtualFile == null) {
LOG.warn("Cannot find virtual file ${file.getAbsolutePath()}")
}
if (virtualFile == null) {
if (file.exists()) {
FileUtil.delete(file)
}
}
else if (virtualFile.exists()) {
try {
deleteFile(requestor, virtualFile)
}
catch (e: FileNotFoundException) {
throw ReadOnlyModificationException(virtualFile, e, object : StateStorage.SaveSession {
override fun save() {
deleteFile(requestor, virtualFile)
}
})
}
}
}
fun deleteFile(requestor: Any, virtualFile: VirtualFile) {
runWriteAction { virtualFile.delete(requestor) }
} | apache-2.0 | 7cc98a9fe2f9aeacc10cd64ac32c84b5 | 37.14539 | 327 | 0.71653 | 4.80393 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/providers/medialibrary/ArtistsProvider.kt | 1 | 2155 | /*****************************************************************************
* ArtistsProvider.kt
*****************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.providers.medialibrary
import android.content.Context
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import org.videolan.medialibrary.interfaces.media.Artist
import org.videolan.vlc.viewmodels.SortableModel
@ExperimentalCoroutinesApi
class ArtistsProvider(context: Context, model: SortableModel, var showAll: Boolean) : MedialibraryProvider<Artist>(context, model) {
override fun getAll() : Array<Artist> = medialibrary.getArtists(showAll, sort, desc)
override fun getPage(loadSize: Int, startposition: Int): Array<Artist> {
val list = if (model.filterQuery == null) medialibrary.getPagedArtists(showAll, sort, desc, loadSize, startposition)
else medialibrary.searchArtist(model.filterQuery, sort, desc, loadSize, startposition)
model.viewModelScope.launch { completeHeaders(list, startposition) }
return list
}
override fun getTotalCount() = if (model.filterQuery == null) medialibrary.getArtistsCount(showAll)
else medialibrary.getArtistsCount(model.filterQuery)
} | gpl-2.0 | ee9ceac06bb803ecdcf6bfd2ea690b97 | 46.888889 | 132 | 0.688022 | 4.929062 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/DuplicateCaseInWhenExpression.kt | 1 | 2023 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import org.jetbrains.kotlin.psi.KtWhenExpression
/**
* Flags duplicate case statements in when expressions.
*
* If a when expression contains the same case statement multiple times they should be merged. Otherwise it might be
* easy to miss one of the cases when reading the code, leading to unwanted side effects.
*
* <noncompliant>
* when (i) {
* 1 -> println("one")
* 1 -> println("one")
* else -> println("else")
* }
* </noncompliant>
*
* <compliant>
* when (i) {
* 1 -> println("one")
* else -> println("else")
* }
* </compliant>
*/
@ActiveByDefault(since = "1.0.0")
class DuplicateCaseInWhenExpression(config: Config) : Rule(config) {
override val issue = Issue(
"DuplicateCaseInWhenExpression",
Severity.Warning,
"Duplicated case statements in when expression. Both cases should be merged.",
Debt.TEN_MINS
)
override fun visitWhenExpression(expression: KtWhenExpression) {
val distinctEntries = expression.entries.distinctBy { entry -> entry.conditions.joinToString { it.text } }
if (distinctEntries != expression.entries) {
val duplicateEntries = expression.entries
.subtract(distinctEntries)
.map { entry -> entry.conditions.joinToString { it.text } }
report(
CodeSmell(
issue,
Entity.from(expression),
"When expression has multiple case statements for ${duplicateEntries.joinToString("; ")}."
)
)
}
}
}
| apache-2.0 | 8ad1dc1bcadb766abd0fa245445a0fb1 | 32.716667 | 116 | 0.660405 | 4.295117 | false | true | false | false |
nemerosa/ontrack | ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/connector/graphql/GraphQLConnectorUtils.kt | 1 | 802 | package net.nemerosa.ontrack.kdsl.connector.graphql
import net.nemerosa.ontrack.kdsl.connector.graphql.schema.fragment.PageInfoContent
import net.nemerosa.ontrack.kdsl.connector.support.PaginatedList
import net.nemerosa.ontrack.kdsl.connector.support.emptyPaginatedList
fun <T : Any, R> T?.checkData(
code: (T) -> R,
) = if (this != null) {
val r = code(this)
r ?: throw GraphQLClientException("No data node was returned")
} else {
throw GraphQLClientException("No data was returned")
}
fun <T : Any, R> T.paginate(
pageInfo: (T) -> PageInfoContent?,
pageItems: (T) -> List<R>?,
): PaginatedList<R> {
val items = pageItems(this)
return if (items == null) {
emptyPaginatedList()
} else {
PaginatedList(
items = items,
)
}
}
| mit | 1cd4f9c5e3277116543ac53a31ecc82d | 27.642857 | 82 | 0.664589 | 3.645455 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/commands/music/NowPlaying.kt | 1 | 3000 | package gg.octave.bot.commands.music
import gg.octave.bot.entities.framework.MusicCog
import gg.octave.bot.music.TrackContext
import gg.octave.bot.utils.Utils
import gg.octave.bot.utils.extensions.config
import gg.octave.bot.utils.extensions.manager
import me.devoxin.flight.api.Context
import me.devoxin.flight.api.annotations.Command
class NowPlaying : MusicCog {
override fun requirePlayingTrack() = true
override fun requirePlayer() = true
private val totalBlocks = 20
@Command(aliases = ["nowplaying", "np", "playing"], description = "Shows what's currently playing.")
fun nowPlaying(ctx: Context) {
val manager = ctx.manager
val track = manager.player.playingTrack
//Reset expire time if np has been called.
manager.scheduler.queue.clearExpireAsync()
ctx.send {
setTitle("Now Playing")
setDescription("**[${track.info.embedTitle}](${track.info.embedUri})**")
manager.discordFMTrack?.let {
val member = ctx.guild?.getMemberById(it.requester)
val r = buildString {
append("Currently streaming music from radio station `${it.station.capitalize()}`")
append(", requested by ${it.requesterMention}.")
}
addField("Radio", r, false)
}
addField(
"Requester",
track.getUserData(TrackContext::class.java)?.requesterMention ?: "Unknown.",
true
)
addField(
"Request Channel",
track.getUserData(TrackContext::class.java)?.channelMention ?: "Unknown.",
true
)
addBlankField(true)
addField("Repeating", manager.scheduler.repeatOption.name.toLowerCase().capitalize(), true)
addField("Volume", "${manager.player.volume}%", true)
addField("Bass Boost", manager.dspFilter.bassBoost.name.toLowerCase().capitalize(), true)
val timeString = if (track.duration == Long.MAX_VALUE) {
"`Streaming`"
} else {
val position = Utils.getTimestamp(track.position)
val duration = Utils.getTimestamp(track.duration)
"`[$position / $duration]`"
}
addField("Time", timeString, true)
val percent = track.position.toDouble() / track.duration
val progress = buildString {
for (i in 0 until totalBlocks) {
if ((percent * (totalBlocks - 1)).toInt() == i) {
append("__**\u25AC**__")
} else {
append("\u2015")
}
}
append(" **%.1f**%%".format(percent * 100))
}
addField("Progress", progress, false)
setFooter("Use ${ctx.config.prefix}lyrics current to see the lyrics of the song!")
}
}
}
| mit | 241695b59be9f7668cf672b75850786a | 40.09589 | 104 | 0.559667 | 4.830918 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/nbt/lang/NbttParserDefinition.kt | 1 | 2143 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang
import com.demonwav.mcdev.nbt.lang.gen.parser.NbttParser
import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
class NbttParserDefinition : ParserDefinition {
override fun createParser(project: Project) = NbttParser()
override fun createLexer(project: Project) = NbttLexerAdapter()
override fun createFile(viewProvider: FileViewProvider) = NbttFile(viewProvider)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode) =
LanguageUtil.canStickTokensTogetherByLexer(left, right, NbttLexerAdapter())
override fun getStringLiteralElements() = STRING_LITERALS
override fun getWhitespaceTokens() = WHITE_SPACES
override fun getFileNodeType() = FILE
override fun createElement(node: ASTNode) = NbttTypes.Factory.createElement(node)!!
override fun getCommentTokens() = TokenSet.EMPTY!!
companion object {
val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE)
val STRING_LITERALS = TokenSet.create(NbttTypes.STRING_LITERAL)
val FILE = IFileElementType(NbttLanguage)
val NBTT_CONTAINERS = TokenSet.create(
NbttTypes.BYTE_ARRAY,
NbttTypes.INT_ARRAY,
NbttTypes.LONG_ARRAY,
NbttTypes.COMPOUND,
NbttTypes.LIST
)
val NBTT_OPEN_BRACES = TokenSet.create(
NbttTypes.LPAREN,
NbttTypes.LBRACE,
NbttTypes.LBRACKET
)
val NBTT_CLOSE_BRACES = TokenSet.create(
NbttTypes.RPAREN,
NbttTypes.RBRACE,
NbttTypes.RBRACKET
)
val NBTT_BRACES = TokenSet.orSet(NBTT_OPEN_BRACES, NBTT_CLOSE_BRACES)
}
}
| mit | afc18c56b27fd9180da31add52588770 | 30.985075 | 87 | 0.708353 | 4.598712 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/download/DownloadStatus.kt | 1 | 658 | package de.xikolo.download
class DownloadStatus(
var totalBytes: Long,
var downloadedBytes: Long,
var state: State
) {
enum class State {
PENDING, RUNNING, SUCCESSFUL, CANCELLED, FAILED;
// Determines what two states result in together.
fun and(other: State): State {
return when {
this == FAILED || other == FAILED -> FAILED
this == CANCELLED || other == CANCELLED -> CANCELLED
this == RUNNING || other == RUNNING -> RUNNING
this == PENDING || other == PENDING -> PENDING
else -> SUCCESSFUL
}
}
}
}
| bsd-3-clause | 5bfdc09f605cd485d1de5c4118133c14 | 28.909091 | 68 | 0.537994 | 5.264 | false | false | false | false |
AleksanderMielczarek/text2emoji | text2emoji-console/src/main/kotlin/com/github/aleksandermielczarek/text2emoji/Text2EmojiApplication.kt | 1 | 1543 | package com.github.aleksandermielczarek.text2emoji
import com.beust.jcommander.JCommander
import com.google.inject.Guice
import javax.inject.Inject
/**
* Created by Aleksander Mielczarek on 08.07.2017.
*/
class Text2EmojiApplication @Inject constructor(val text2Emoji: Text2Emoji) {
fun run(args: Array<String>) {
val arguments = parseArguments(args)
val emojis = text2Emoji.text2emoji(arguments.text,
arguments.textEmoji,
arguments.emptyEmoji,
arguments.separator(),
arguments.widthLimit)
println(emojis)
}
private fun parseArguments(args: Array<String>): Arguments {
val arguments = Arguments()
val jCommander = JCommander.newBuilder()
.addObject(arguments)
.programName("Text2Emoji")
.build()
parse(jCommander, args)
showHelp(arguments, jCommander)
return arguments
}
private fun showHelp(arguments: Arguments, jCommander: JCommander) {
if (arguments.help) {
jCommander.usage()
System.exit(0)
}
}
private fun parse(jCommander: JCommander, args: Array<String>) {
try {
jCommander.parse(*args)
} catch(e: Exception) {
jCommander.usage()
System.exit(1)
}
}
}
fun main(args: Array<String>) {
val injector = Guice.createInjector()
val app = injector.getInstance(Text2EmojiApplication::class.java)
app.run(args)
}
| apache-2.0 | f3d7347f040426a71607e66a5970bb95 | 26.070175 | 77 | 0.614388 | 4.227397 | false | false | false | false |
akinaru/bbox-api-client | bboxapi-router/src/main/kotlin/fr/bmartel/bboxapi/router/model/BboxException.kt | 2 | 346 | package fr.bmartel.bboxapi.router.model
data class BboxException(
val exception: ApiException? = null
)
data class ApiException(
val domain: String? = null,
val code: String? = null,
val errors: List<ApiError>? = null
)
data class ApiError(
val name: String? = null,
val reason: String? = null
) | mit | d125d13691b8804509cadbb71b800540 | 20.6875 | 43 | 0.632948 | 3.931818 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/premium/DummyExtraFeaturesService.kt | 1 | 1625 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.premium
import android.content.Context
import android.content.Intent
import de.vanita5.twittnuker.view.ContainerView
class DummyExtraFeaturesService : ExtraFeaturesService() {
override fun getDashboardControllers() = emptyList<Class<ContainerView.ViewController>>()
override fun isSupported(feature: String?): Boolean = false
override fun isEnabled(feature: String): Boolean = false
override fun isPurchased(feature: String): Boolean = false
override fun destroyPurchase(): Boolean = false
override fun createPurchaseIntent(context: Context, feature: String): Intent? = null
override fun createRestorePurchaseIntent(context: Context, feature: String): Intent? = null
} | gpl-3.0 | f819631a47d5a0fc807d2657df7f6398 | 35.133333 | 95 | 0.756923 | 4.391892 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/BsbConfig.kt | 1 | 3404 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.annotation.StringRes
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import com.stripe.android.ui.core.R
import com.stripe.android.view.BecsDebitBanks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* A text field configuration for a BSB number, or Bank State Branch Number,
* a six-digit number used to identify the individual branch of an Australian financial institution
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class BsbConfig(private val banks: List<BecsDebitBanks.Bank>) : TextFieldConfig {
override val capitalization: KeyboardCapitalization = KeyboardCapitalization.None
override val debugLabel = "bsb"
override val trailingIcon: StateFlow<TextFieldIcon?> = MutableStateFlow(null)
override val loading: StateFlow<Boolean> = MutableStateFlow(false)
@StringRes
override val label = R.string.becs_widget_bsb
override val keyboard = KeyboardType.Number
// Displays the BSB number in 2 groups of 3 characters with a dash added between them
override val visualTransformation: VisualTransformation = VisualTransformation { text ->
val output = StringBuilder()
val separator = " - "
text.text.forEachIndexed { i, char ->
output.append(char)
if (i == 2) output.append(separator)
}
TransformedText(
AnnotatedString(output.toString()),
object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
return if (offset <= 2) {
offset
} else {
offset + separator.length
}
}
override fun transformedToOriginal(offset: Int): Int {
return if (offset <= 3) {
offset
} else {
offset - separator.length
}
}
}
)
}
override fun filter(userTyped: String) =
userTyped.filter { VALID_INPUT_RANGES.contains(it) }.take(LENGTH)
override fun convertToRaw(displayName: String) = displayName
override fun convertFromRaw(rawValue: String) = rawValue
override fun determineState(input: String): TextFieldState {
input.ifBlank {
return TextFieldStateConstants.Error.Blank
}
if (input.length < LENGTH) {
return TextFieldStateConstants.Error.Incomplete(
R.string.becs_widget_bsb_incomplete
)
}
val bank = banks.firstOrNull {
input.startsWith(it.prefix)
}
if (bank == null || input.length > LENGTH) {
return TextFieldStateConstants.Error.Invalid(
R.string.becs_widget_bsb_invalid
)
}
return TextFieldStateConstants.Valid.Full
}
private companion object {
const val LENGTH = 6
val VALID_INPUT_RANGES = ('0'..'9')
}
}
| mit | 0a739845c9d44afadd3473a8b7884cbc | 34.092784 | 99 | 0.639835 | 4.85592 | false | false | false | false |
slartus/4pdaClient-plus | hosthelper/src/main/java/org/softeg/slartus/hosthelper/HostHelper.kt | 1 | 434 | package org.softeg.slartus.hosthelper
fun String?.is4pdaHost() =
this?.matches(Regex(HostHelper.hostPattern + ".*", RegexOption.IGNORE_CASE)) == true
class HostHelper {
companion object {
@JvmStatic
val host = "4pda.to"
val schemedHost = "https://$host"
val endPoint = "$schemedHost/forum/index.php"
@JvmStatic
val hostPattern = "(?:^|.*[^a-zA-Z0-9])4pda\\.(?:to|ru)"
}
} | apache-2.0 | 51184a7a97968985fe933165fd2ce412 | 26.1875 | 88 | 0.601382 | 3.444444 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/data/local/model/CrewMovie.kt | 1 | 1295 | package tech.salroid.filmy.data.local.model
import com.google.gson.annotations.SerializedName
data class CrewMovie(
@SerializedName("adult")
var adult: Boolean? = null,
@SerializedName("backdrop_path")
var backdropPath: String? = null,
@SerializedName("genre_ids")
var genreIds: ArrayList<Int> = arrayListOf(),
@SerializedName("id")
var id: Int? = null,
@SerializedName("original_language")
var originalLanguage: String? = null,
@SerializedName("original_title")
var originalTitle: String? = null,
@SerializedName("overview")
var overview: String? = null,
@SerializedName("poster_path")
var posterPath: String? = null,
@SerializedName("release_date")
var releaseDate: String? = null,
@SerializedName("title")
var title: String? = null,
@SerializedName("video")
var video: Boolean? = null,
@SerializedName("vote_average")
var voteAverage: Int? = null,
@SerializedName("vote_count")
var voteCount: Int? = null,
@SerializedName("popularity")
var popularity: Double? = null,
@SerializedName("credit_id")
var creditId: String? = null,
@SerializedName("department")
var department: String? = null,
@SerializedName("job")
var job: String? = null
) | apache-2.0 | 117df56a00616526a9793855f8b43f0e | 21.736842 | 49 | 0.661004 | 4.13738 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/AnnotationBasedGeneratorIntention.kt | 1 | 2729 | package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.elm.lang.core.imports.ImportAdder
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.endOffset
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.startOffset
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.typeExpressionInference
import org.elm.openapiext.runWriteCommandAction
import org.elm.utils.getIndent
abstract class AnnotationBasedGeneratorIntention : ElmAtCaretIntentionActionBase<AnnotationBasedGeneratorIntention.Context>() {
data class Context(val file: ElmFile, val ty: Ty, val name: String, val startOffset: Int, val endOffset: Int)
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val file = element.containingFile as? ElmFile ?: return null
val typeAnnotation = element.parentOfType<ElmTypeAnnotation>()
?: return null
if (typeAnnotation.reference.resolve() != null) {
// the target declaration already exists; nothing to do
return null
}
val ty = typeAnnotation.typeExpressionInference()?.ty ?: return null
val root = getRootIfApplicable(ty) ?: return null
return Context(file, root, typeAnnotation.referenceName, typeAnnotation.startOffset, typeAnnotation.endOffset)
}
/** If the intention applies to the type of this annotation, return the [Ty] to use as [Context.ty]. */
abstract fun getRootIfApplicable(annotationTy: Ty): Ty?
/** The code generator for this intention*/
abstract fun generator(context: Context): TyFunctionGenerator
override fun invoke(project: Project, editor: Editor, context: Context) {
val generator = generator(context)
val indent = editor.getIndent(context.startOffset)
val (generatedCode, imports) = generator.run()
val code = generatedCode.replace(Regex("\n(?![\r\n])"), "\n$indent")
project.runWriteCommandAction {
editor.document.insertString(context.endOffset, "$indent$code")
if (imports.isNotEmpty()) {
// Commit the string changes so we can work with the new PSI
PsiDocumentManager.getInstance(context.file.project).commitDocument(editor.document)
for (import in imports) {
ImportAdder.addImport(import, context.file, import.nameToBeExposed.isEmpty())
}
}
}
}
}
| mit | 46616ba4b0b282076ca8d0f198d1edaf | 44.483333 | 127 | 0.709051 | 4.548333 | false | false | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/MockK.kt | 1 | 19951 | @file:Suppress("NOTHING_TO_INLINE")
package io.mockk
import kotlin.reflect.KClass
/**
* Builds a new mock for specified class
*
* @param name mock name
* @param relaxed allows creation with no specific behaviour
* @param moreInterfaces additional interfaces for this mockk to implement
* @param relaxUnitFun allows creation with no specific behaviour for Unit function
* @param block block to execute after mock is created with mock as a receiver
*
* @sample [io.mockk.MockKSamples.basicMockkCreation]
* @sample [io.mockk.MockKSamples.mockkWithCreationBlock]
*/
inline fun <reified T : Any> mockk(
name: String? = null,
relaxed: Boolean = false,
vararg moreInterfaces: KClass<*>,
relaxUnitFun: Boolean = false,
block: T.() -> Unit = {}
): T = MockK.useImpl {
MockKDsl.internalMockk(
name,
relaxed,
*moreInterfaces,
relaxUnitFun = relaxUnitFun,
block = block
)
}
/**
* Builds a new spy for specified class. Initializes object via default constructor.
*
* A spy is a special kind of mockk that enables a mix of mocked behaviour and real behaviour.
* A part of the behaviour may be mocked, but any non-mocked behaviour will call the original method.
*
* @param name spyk name
* @param moreInterfaces additional interfaces for this spyk to implement
* @param recordPrivateCalls allows this spyk to record any private calls, enabling a verification
* @param block block to execute after spyk is created with spyk as a receiver
*
* @sample [io.mockk.SpykSamples.spyOriginalBehaviourDefaultConstructor]
*/
inline fun <reified T : Any> spyk(
name: String? = null,
vararg moreInterfaces: KClass<*>,
recordPrivateCalls: Boolean = false,
block: T.() -> Unit = {}
): T = MockK.useImpl {
MockKDsl.internalSpyk(
name,
*moreInterfaces,
recordPrivateCalls = recordPrivateCalls,
block = block
)
}
/**
* Builds a new spy for specified class, copying fields from [objToCopy].
*
* A spy is a special kind of mockk that enables a mix of mocked behaviour and real behaviour.
* A part of the behaviour may be mocked, but any non-mocked behaviour will call the original method.
*
* @sample [io.mockk.SpykSamples.spyOriginalBehaviourCopyingFields]
* @sample [io.mockk.SpykSamples.spyOriginalBehaviourWithPrivateCalls]
*/
inline fun <reified T : Any> spyk(
objToCopy: T,
name: String? = null,
vararg moreInterfaces: KClass<*>,
recordPrivateCalls: Boolean = false,
block: T.() -> Unit = {}
): T = MockK.useImpl {
MockKDsl.internalSpyk(
objToCopy,
name,
*moreInterfaces,
recordPrivateCalls = recordPrivateCalls,
block = block
)
}
/**
* Creates new capturing slot
*
* @sample [io.mockk.SlotSample.captureSlot]
*/
inline fun <reified T : Any> slot() = MockK.useImpl {
MockKDsl.internalSlot<T>()
}
/**
* Starts a block of stubbing. Part of DSL.
*
* Used to define what behaviour is going to be mocked.
*
* @sample [io.mockk.EverySample.simpleEvery]
*/
fun <T> every(stubBlock: MockKMatcherScope.() -> T): MockKStubScope<T, T> = MockK.useImpl {
MockKDsl.internalEvery(stubBlock)
}
/**
* Starts a block of stubbing for coroutines. Part of DSL.
* Similar to [every]
*
* Used to define what behaviour is going to be mocked.
* @see [every]
*/
fun <T> coEvery(stubBlock: suspend MockKMatcherScope.() -> T): MockKStubScope<T, T> = MockK.useImpl {
MockKDsl.internalCoEvery(stubBlock)
}
/**
* Verifies that calls were made in the past. Part of DSL
*
* @param ordering how the verification should be ordered
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
* @param atLeast verifies that the behaviour happened at least [atLeast] times
* @param atMost verifies that the behaviour happened at most [atMost] times
* @param exactly verifies that the behaviour happened exactly [exactly] times. Use -1 to disable
*
* @sample [io.mockk.VerifySample.verifyAmount]
* @sample [io.mockk.VerifySample.verifyRange]
*/
fun verify(
ordering: Ordering = Ordering.UNORDERED,
inverse: Boolean = false,
atLeast: Int = 1,
atMost: Int = Int.MAX_VALUE,
exactly: Int = -1,
timeout: Long = 0,
verifyBlock: MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalVerify(ordering, inverse, atLeast, atMost, exactly, timeout, verifyBlock)
}
/**
* Verifies that calls were made inside a coroutine.
*
* @param ordering how the verification should be ordered
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
* @param atLeast verifies that the behaviour happened at least [atLeast] times
* @param atMost verifies that the behaviour happened at most [atMost] times
* @param exactly verifies that the behaviour happened exactly [exactly] times. Use -1 to disable
*
* @see [verify]
*/
fun coVerify(
ordering: Ordering = Ordering.UNORDERED,
inverse: Boolean = false,
atLeast: Int = 1,
atMost: Int = Int.MAX_VALUE,
exactly: Int = -1,
timeout: Long = 0,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalCoVerify(
ordering,
inverse,
atLeast,
atMost,
exactly,
timeout,
verifyBlock
)
}
/**
* Verifies that all calls inside [verifyBlock] happened. **Does not** verify any order.
*
* If ordering is important, use [verifyOrder]
*
* @see verify
* @see verifyOrder
* @see verifySequence
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*/
fun verifyAll(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalVerifyAll(inverse, verifyBlock)
}
/**
* Verifies that all calls inside [verifyBlock] happened, checking that they happened in the order declared.
*
* @see verify
* @see verifyAll
* @see verifySequence
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*
* @sample [io.mockk.VerifySample.verifyOrder]
* @sample [io.mockk.VerifySample.failingVerifyOrder]
*/
fun verifyOrder(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalVerifyOrder(inverse, verifyBlock)
}
/**
* Verifies that all calls inside [verifyBlock] happened, and no other call was made to those mocks
*
* @see verify
* @see verifyOrder
* @see verifyAll
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*
* @sample [io.mockk.VerifySample.verifySequence]
* @sample [io.mockk.VerifySample.failingVerifySequence]
*/
fun verifySequence(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalVerifySequence(inverse, verifyBlock)
}
/**
* Verifies that all calls inside [verifyBlock] happened. **Does not** verify any order. Coroutine version
*
* If ordering is important, use [verifyOrder]
*
* @see coVerify
* @see coVerifyOrder
* @see coVerifySequence
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*/
fun coVerifyAll(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalCoVerifyAll(inverse, verifyBlock)
}
/**
* Verifies that all calls inside [verifyBlock] happened, checking that they happened in the order declared.
* Coroutine version.
*
* @see coVerify
* @see coVerifyAll
* @see coVerifySequence
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*
* @sample [io.mockk.VerifySample.verifyOrder]
* @sample [io.mockk.VerifySample.failingVerifyOrder]
*/
fun coVerifyOrder(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalCoVerifyOrder(inverse, verifyBlock)
}
/**
* Verifies that all calls inside [verifyBlock] happened, and no other call was made to those mocks
*
* @see coVerify
* @see coVerifyOrder
* @see coVerifyAll
*
* @param inverse when true, the verification will check that the behaviour specified did **not** happen
*
* @sample [io.mockk.VerifySample.verifySequence]
* @sample [io.mockk.VerifySample.failingVerifySequence]
*/
fun coVerifySequence(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalCoVerifySequence(inverse, verifyBlock)
}
/**
* Exclude calls from recording
*
* @param current if current recorded calls should be filtered out
*/
fun excludeRecords(
current: Boolean = true,
excludeBlock: MockKMatcherScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalExcludeRecords(current, excludeBlock)
}
/**
* Exclude calls from recording for a suspend block
*
* @param current if current recorded calls should be filtered out
*/
fun coExcludeRecords(
current: Boolean = true,
excludeBlock: suspend MockKMatcherScope.() -> Unit
) = MockK.useImpl {
MockKDsl.internalCoExcludeRecords(current, excludeBlock)
}
/**
* Checks if all recorded calls were verified.
*/
fun confirmVerified(vararg mocks: Any) = MockK.useImpl {
MockKDsl.internalConfirmVerified(*mocks)
}
/**
* Resets information associated with specified mocks.
* To clear all mocks use clearAllMocks.
*/
fun clearMocks(
firstMock: Any,
vararg mocks: Any,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) =
MockK.useImpl {
MockKDsl.internalClearMocks(
firstMock = firstMock,
mocks = *mocks,
answers = answers,
recordedCalls = recordedCalls,
childMocks = childMocks,
verificationMarks = verificationMarks,
exclusionRules = exclusionRules
)
}
/**
* Registers instance factory and returns object able to do deregistration.
*/
inline fun <reified T : Any> registerInstanceFactory(noinline instanceFactory: () -> T): Deregisterable =
MockK.useImpl {
MockKDsl.internalRegisterInstanceFactory(instanceFactory)
}
/**
* Executes block of code with registering and unregistering instance factory.
*/
inline fun <reified T : Any, R> withInstanceFactory(noinline instanceFactory: () -> T, block: () -> R): R =
MockK.useImpl {
MockKDsl.internalWithInstanceFactory(instanceFactory, block)
}
/**
* Builds a static mock via static mock scope.
* To actually use it you need to call use or mock/unmock.
*/
@Deprecated(
message = "Scopes for mocking tend to be error prone. Use new 'mockkStatic' function",
replaceWith = ReplaceWith(
expression = "mockkStatic(T::class)",
imports = ["io.mockk.mockkStatic"]
)
)
inline fun <reified T : Any> staticMockk(): MockKStaticScope = MockK.useImpl {
MockKDsl.internalStaticMockk<T>()
}
/**
* Builds a static mock via static mock scope.
* To actually use it you need to call use or mock/unmock/use.
*/
@Deprecated(
message = "Scopes for mocking tend to be error prone. Use new 'mockkStatic' function",
replaceWith = ReplaceWith(
expression = "mockkStatic(cls)",
imports = ["io.mockk.mockkStatic"]
)
)
inline fun staticMockk(vararg cls: String): MockKStaticScope = MockK.useImpl {
MockKDsl.internalStaticMockk(*cls.map { InternalPlatformDsl.classForName(it) as KClass<*> }.toTypedArray())
}
/**
* Builds a mock for object.
* To actually use it you need to call use or mock/unmock.
*/
@Deprecated(
message = "Scopes for mocking tend to be error prone. Use new 'mockkObject' function",
replaceWith = ReplaceWith(
expression = "mockkObject(objs, recordPrivateCalls = recordPrivateCalls)",
imports = ["io.mockk.mockkObject"]
)
)
inline fun objectMockk(vararg objs: Any, recordPrivateCalls: Boolean = false): MockKObjectScope = MockK.useImpl {
MockKDsl.internalObjectMockk(objs, recordPrivateCalls = recordPrivateCalls)
}
/**
* Builds a mock using particular constructor.
* To actually use it you need to call use or mock/unmock.
*/
@Deprecated(
message = "Scopes for mocking tend to be error prone. Use new 'mockkConstructor' function",
replaceWith = ReplaceWith(
expression = "mockkConstructor(T::class, recordPrivateCalls = recordPrivateCalls, localToThread = localToThread)",
imports = ["io.mockk.mockkConstructor"]
)
)
inline fun <reified T : Any> constructorMockk(
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false
): MockKConstructorScope<T> = MockK.useImpl {
MockKDsl.internalConstructorMockk(recordPrivateCalls, localToThread)
}
/**
* Builds a mock for a class.
*/
@Deprecated(
message = "Every mocking function now starts with 'mockk...'. " +
"Scoped functions alike objectMockk and staticMockk were error prone. " +
"Use new 'mockkClass' function",
replaceWith = ReplaceWith(
expression = "mockkClass(type, name, relaxed, moreInterfaces, block)",
imports = ["io.mockk.mockkClass"]
)
)
inline fun <T : Any> classMockk(
type: KClass<T>,
name: String? = null,
relaxed: Boolean = false,
vararg moreInterfaces: KClass<*>,
block: T.() -> Unit = {}
): T = MockK.useImpl {
MockKDsl.internalMockkClass(type, name, relaxed, *moreInterfaces, block = block)
}
/**
* Builds a mock for an arbitrary class
*/
inline fun <T : Any> mockkClass(
type: KClass<T>,
name: String? = null,
relaxed: Boolean = false,
vararg moreInterfaces: KClass<*>,
relaxUnitFun: Boolean = false,
block: T.() -> Unit = {}
): T = MockK.useImpl {
MockKDsl.internalMockkClass(
type,
name,
relaxed,
*moreInterfaces,
relaxUnitFun = relaxUnitFun,
block = block
)
}
/**
* Builds an Object mock. Any mocks of this exact object are cancelled before it's mocked.
*
* @sample io.mockk.ObjectMockkSample.mockSimpleObject
* @sample io.mockk.ObjectMockkSample.mockEnumeration
*/
inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false) = MockK.useImpl {
MockKDsl.internalMockkObject(*objects, recordPrivateCalls = recordPrivateCalls)
}
/**
* Cancel object mocks.
*/
inline fun unmockkObject(vararg objects: Any) = MockK.useImpl {
MockKDsl.internalUnmockkObject(*objects)
}
/**
* Builds a static mock and unmocks it after the block has been executed.
*/
inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false, block: () -> Unit) {
mockkObject(*objects, recordPrivateCalls = recordPrivateCalls)
try {
block()
} finally {
unmockkObject(*objects)
}
}
/**
* Builds a static mock. Any mocks of this exact class are cancelled before it's mocked
*
* @sample io.mockk.StaticMockkSample.mockJavaStatic
*/
inline fun mockkStatic(vararg classes: KClass<*>) = MockK.useImpl {
MockKDsl.internalMockkStatic(*classes)
}
/**
* Builds a static mock. Old static mocks of same classes are cancelled before.
*
* @sample io.mockk.StaticMockkSample.mockJavaStaticString
*/
inline fun mockkStatic(vararg classes: String) = MockK.useImpl {
MockKDsl.internalMockkStatic(*classes.map { InternalPlatformDsl.classForName(it) as KClass<*> }.toTypedArray())
}
/**
* Cancel static mocks.
*/
inline fun clearStaticMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true
) = MockK.useImpl {
MockKDsl.internalClearStaticMockk(
*classes,
answers = answers,
recordedCalls = recordedCalls,
childMocks = childMocks
)
}
/**
* Cancel static mocks.
*/
inline fun unmockkStatic(vararg classes: KClass<*>) = MockK.useImpl {
MockKDsl.internalUnmockkStatic(*classes)
}
/**
* Cancel static mocks.
*/
inline fun unmockkStatic(vararg classes: String) = MockK.useImpl {
MockKDsl.internalUnmockkStatic(*classes.map { InternalPlatformDsl.classForName(it) as KClass<*> }.toTypedArray())
}
/**
* Builds a static mock and unmocks it after the block has been executed.
*/
inline fun mockkStatic(vararg classes: KClass<*>, block: () -> Unit) {
mockkStatic(*classes)
try {
block()
} finally {
unmockkStatic(*classes)
}
}
/**
* Builds a static mock and unmocks it after the block has been executed.
*/
inline fun mockkStatic(vararg classes: String, block: () -> Unit) {
mockkStatic(*classes)
try {
block()
} finally {
unmockkStatic(*classes)
}
}
/**
* Builds a constructor mock. Old constructor mocks of same classes are cancelled before.
*/
inline fun mockkConstructor(
vararg classes: KClass<*>,
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false
) = MockK.useImpl {
MockKDsl.internalMockkConstructor(
*classes,
recordPrivateCalls = recordPrivateCalls,
localToThread = localToThread
)
}
/**
* Cancel constructor mocks.
*/
inline fun unmockkConstructor(vararg classes: KClass<*>) = MockK.useImpl {
MockKDsl.internalUnmockkConstructor(*classes)
}
/**
* Builds a constructor mock and unmocks it after the block has been executed.
*/
inline fun mockkConstructor(
vararg classes: KClass<*>,
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false,
block: () -> Unit
) {
mockkConstructor(*classes, recordPrivateCalls = recordPrivateCalls, localToThread = localToThread)
try {
block()
} finally {
unmockkConstructor(*classes)
}
}
/**
* Clears constructor mock.
*/
inline fun clearConstructorMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true
) = MockK.useImpl {
MockKDsl.internalClearConstructorMockk(
*classes,
answers = answers,
recordedCalls = recordedCalls,
childMocks = childMocks
)
}
/**
* Cancels object, static and constructor mocks.
*/
inline fun unmockkAll() = MockK.useImpl {
MockKDsl.internalUnmockkAll()
}
/**
* Clears all regular, object, static and constructor mocks.
*/
inline fun clearAllMocks(
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
regularMocks: Boolean = true,
objectMocks: Boolean = true,
staticMocks: Boolean = true,
constructorMocks: Boolean = true
) = MockK.useImpl {
MockKDsl.internalClearAllMocks(
answers,
recordedCalls,
childMocks,
regularMocks,
objectMocks,
staticMocks,
constructorMocks
)
}
/**
* Checks if provided mock is mock of certain type
*/
fun isMockKMock(
mock: Any,
regular: Boolean = true,
spy: Boolean = false,
objectMock: Boolean = false,
staticMock: Boolean = false,
constructorMock: Boolean = false
) = MockK.useImpl {
MockKDsl.internalIsMockKMock(
mock,
regular,
spy,
objectMock,
staticMock,
constructorMock
)
}
object MockKAnnotations {
/**
* Initializes properties annotated with @MockK, @RelaxedMockK, @Slot and @SpyK in provided object.
*/
inline fun init(
vararg obj: Any,
overrideRecordPrivateCalls: Boolean = false,
relaxUnitFun: Boolean = false,
relaxed: Boolean = false
) = MockK.useImpl {
MockKDsl.internalInitAnnotatedMocks(
obj.toList(),
overrideRecordPrivateCalls,
relaxUnitFun,
relaxed
)
}
}
expect object MockK {
inline fun <T> useImpl(block: () -> T): T
}
| apache-2.0 | f0df6ca6a92300961aa5046bb81a1927 | 27.66523 | 122 | 0.688236 | 4.105989 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/glfw/templates/GLFWNativeCocoa.kt | 1 | 1241 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.glfw.templates
import org.lwjgl.generator.*
import org.lwjgl.glfw.*
import org.lwjgl.system.macosx.*
val GLFWNativeCocoa = "GLFWNativeCocoa".nativeClass(packageName = GLFW_PACKAGE, nativeSubPath = "macosx", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) {
documentation = "Native bindings to the GLFW library's Cocoa native access functions."
CGDirectDisplayID(
"GetCocoaMonitor",
"""
Returns the ${code("CGDirectDisplayID")} of the specified monitor.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.IN("monitor", "the GLFW monitor"),
returnDoc = "The ${code("CGDirectDisplayID")} of the specified monitor, or {@code kCGNullDirectDisplay} if an error occurred.",
since = "version 3.1"
)
id(
"GetCocoaWindow",
"""
Returns the ${code("NSWindow")} of the specified GLFW window.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.IN("window", "the GLFW window"),
returnDoc = "The ${code("NSWindow")} of the specified window, or nil if an error occurred.",
since = "version 3.0"
)
} | bsd-3-clause | 059097083f865631ea84adfd95c84c5b | 30.05 | 157 | 0.709106 | 3.726727 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/task/TodoList.kt | 1 | 12059 | package nl.mpcjanssen.simpletask.task
import android.app.Activity
import android.content.Intent
import android.os.SystemClock
import android.util.Log
import nl.mpcjanssen.simpletask.*
import nl.mpcjanssen.simpletask.remote.FileStore
import nl.mpcjanssen.simpletask.remote.IFileStore
import nl.mpcjanssen.simpletask.util.*
import java.util.*
import kotlin.collections.ArrayList
/**
* Implementation of the in memory representation of the Todo list
* uses an ActionQueue to ensure modifications and access of the underlying todo list are
* sequential. If this is not done properly the result is a likely ConcurrentModificationException.
* @author Mark Janssen
*/
object TodoList {
private var mLists: MutableList<String>? = null
private var mTags: MutableList<String>? = null
private val todoItems = ArrayList<Task>()
val pendingEdits = ArrayList<Int>()
internal val TAG = TodoList::class.java.simpleName
init {
Config.todoList?.let { todoItems.addAll(it) }
}
fun add(items: List<Task>, atEnd: Boolean) {
Log.d(TAG, "Add task ${items.size} atEnd: $atEnd")
val updatedItems = items.map { item ->
Interpreter.onAddCallback(item) ?: item
}
if (atEnd) {
todoItems.addAll(updatedItems)
} else {
todoItems.addAll(0, updatedItems)
}
}
fun add(t: Task, atEnd: Boolean) {
add(listOf(t), atEnd)
}
fun removeAll(tasks: List<Task>) {
Log.d(TAG, "Remove")
tasks.forEach {
val idx = todoItems.indexOf(it)
pendingEdits.remove(idx)
}
todoItems.removeAll(tasks)
}
fun size(): Int {
return todoItems.size
}
val priorities: ArrayList<Priority>
get() {
val res = HashSet<Priority>()
todoItems.iterator().forEach {
res.add(it.priority)
}
val ret = ArrayList(res)
ret.sort()
return ret
}
val contexts: List<String>
get() {
val lists = mLists
if (lists != null) {
return lists
}
val res = HashSet<String>()
todoItems.forEach { t ->
t.lists?.let {res.addAll(it)}
}
val newLists = res.toMutableList()
mLists = newLists
return newLists
}
val projects: List<String>
get() {
val tags = mTags
if (tags != null) {
return tags
}
val res = HashSet<String>()
todoItems.forEach { t ->
t.tags?.let {res.addAll(it)}
}
val newTags = res.toMutableList()
mTags = newTags
return newTags
}
fun uncomplete(items: List<Task>) {
Log.d(TAG, "Uncomplete")
items.forEach {
it.markIncomplete()
}
}
fun complete(tasks: List<Task>, keepPrio: Boolean, extraAtEnd: Boolean) {
Log.d(TAG, "Complete")
for (task in tasks) {
val extra = task.markComplete(todayAsString)
if (extra != null) {
if (extraAtEnd) {
todoItems.add(extra)
} else {
todoItems.add(0, extra)
}
}
if (!keepPrio) {
task.priority = Priority.NONE
}
}
}
fun prioritize(tasks: List<Task>, prio: Priority) {
Log.d(TAG, "Complete")
tasks.map { it.priority = prio }
}
fun defer(deferString: String, tasks: List<Task>, dateType: DateType) {
Log.d(TAG, "Defer")
tasks.forEach {
when (dateType) {
DateType.DUE -> it.deferDueDate(deferString, todayAsString)
DateType.THRESHOLD -> it.deferThresholdDate(deferString, todayAsString)
}
}
}
var selectedTasks: List<Task> = ArrayList()
get() {
return todoItemsCopy.filter { it.selected }
}
var completedTasks: List<Task> = ArrayList()
get() {
return todoItemsCopy.filter { it.isCompleted() }
}
fun notifyTasklistChanged(todoName: String, save: Boolean) {
Log.d(TAG, "Notified changed")
if (save) {
save(FileStore, todoName, true, Config.eol)
}
if (!Config.hasKeepSelection) {
clearSelection()
}
mLists = null
mTags = null
broadcastTasklistChanged(TodoApplication.app.localBroadCastManager)
}
fun startAddTaskActivity(act: Activity, prefill: String) {
Log.d(TAG, "Start add/edit task activity")
val intent = Intent(act, AddTask::class.java)
intent.putExtra(Constants.EXTRA_PREFILL_TEXT, prefill)
act.startActivity(intent)
}
val todoItemsCopy
get() = todoItems.toList()
fun getSortedTasks(filter: Query, sorts: ArrayList<String>, caseSensitive: Boolean): Pair<List<Task>, Int> {
Log.d(TAG, "Getting sorted and filtered tasks")
val start = SystemClock.elapsedRealtime()
val comp = MultiComparator(sorts, TodoApplication.app.today, caseSensitive, filter.createIsThreshold, filter.luaModule)
val listCopy = todoItemsCopy
val taskCount = listCopy.size
val itemsToSort = if (comp.fileOrder) {
listCopy
} else {
listCopy.reversed()
}
val sortedItems = comp.comparator?.let { itemsToSort.sortedWith(it) } ?: itemsToSort
val result = filter.applyFilter(sortedItems, showSelected = true)
val end = SystemClock.elapsedRealtime()
Log.d(TAG, "Sorting and filtering tasks took ${end - start} ms")
return Pair(result, taskCount)
}
fun reload(reason: String = "") {
Log.d(TAG, "Reload: $reason")
broadcastFileSyncStart(TodoApplication.app.localBroadCastManager)
if (!FileStore.isAuthenticated) {
broadcastFileSyncDone(TodoApplication.app.localBroadCastManager)
return
}
val filename = Config.todoFileName
if (Config.changesPending && FileStore.isOnline) {
Log.i(TAG, "Not loading, changes pending")
Log.i(TAG, "Saving instead of loading")
save(FileStore, filename, true, Config.eol)
} else {
FileStoreActionQueue.add("Reload") {
val needSync = try {
val newerVersion = FileStore.getRemoteVersion(Config.todoFileName)
newerVersion != Config.lastSeenRemoteId
} catch (e: Throwable) {
Log.e(TAG, "Can't determine remote file version", e)
false
}
if (needSync) {
Log.i(TAG, "Remote version is different, sync")
} else {
Log.i(TAG, "Remote version is same, load from cache")
}
val cachedList = Config.todoList
if (cachedList == null || needSync) {
try {
val remoteContents = FileStore.loadTasksFromFile(filename)
val items = ArrayList<Task>(
remoteContents.contents.map { text ->
Task(text)
})
Log.d(TAG, "Fill todolist")
todoItems.clear()
todoItems.addAll(items)
// Update cache
Config.cachedContents = remoteContents.contents.joinToString("\n")
Config.lastSeenRemoteId = remoteContents.remoteId
// Backup
Backupper.backup(filename, items.map { it.inFileFormat() })
notifyTasklistChanged(filename, false)
} catch (e: Exception) {
Log.e(TAG, "TodoList load failed: {}" + filename, e)
showToastShort(TodoApplication.app, "Loading of todo file failed")
}
Log.i(TAG, "TodoList loaded from dropbox")
}
}
broadcastFileSyncDone(TodoApplication.app.localBroadCastManager)
}
}
private fun save(fileStore: IFileStore, todoFileName: String, backup: Boolean, eol: String) {
broadcastFileSyncStart(TodoApplication.app.localBroadCastManager)
val lines = todoItemsCopy.map {
it.inFileFormat()
}
// Update cache
Config.cachedContents = lines.joinToString("\n")
if (backup) {
Backupper.backup(todoFileName, lines)
}
FileStoreActionQueue.add("Save") {
try {
Log.i(TAG, "Saving todo list, size ${lines.size}")
val rev = fileStore.saveTasksToFile(todoFileName, lines, eol = eol)
Config.lastSeenRemoteId = rev
val changesWerePending = Config.changesPending
Config.changesPending = false
if (changesWerePending) {
// Remove the red bar
broadcastUpdateStateIndicator(TodoApplication.app.localBroadCastManager)
}
} catch (e: Exception) {
Log.e(TAG, "TodoList save to $todoFileName failed", e)
Config.changesPending = true
if (FileStore.isOnline) {
showToastShort(TodoApplication.app, "Saving of todo file failed")
}
}
broadcastFileSyncDone(TodoApplication.app.localBroadCastManager)
}
}
fun archive(todoFilename: String, doneFileName: String, tasks: List<Task>, eol: String) {
Log.d(TAG, "Archive ${tasks.size} tasks")
FileStoreActionQueue.add("Append to file") {
broadcastFileSyncStart(TodoApplication.app.localBroadCastManager)
try {
FileStore.appendTaskToFile(doneFileName, tasks.map { it.text }, eol)
removeAll(tasks)
notifyTasklistChanged(todoFilename, true)
} catch (e: Exception) {
Log.e(TAG, "Task archiving failed", e)
showToastShort(TodoApplication.app, "Task archiving failed")
}
broadcastFileSyncDone(TodoApplication.app.localBroadCastManager)
}
}
fun isSelected(item: Task): Boolean = item.selected
fun numSelected(): Int {
return todoItemsCopy.count { it.selected }
}
fun selectTasks(items: List<Task>) {
Log.d(TAG, "Select")
items.forEach { selectTask(it) }
broadcastRefreshSelection(TodoApplication.app.localBroadCastManager)
}
private fun selectTask(item: Task?) {
item?.selected = true
}
private fun unSelectTask(item: Task) {
item.selected = false
}
fun unSelectTasks(items: List<Task>) {
Log.d(TAG, "Unselect")
items.forEach { unSelectTask(it) }
broadcastRefreshSelection(TodoApplication.app.localBroadCastManager)
}
fun clearSelection() {
Log.d(TAG, "Clear selection")
todoItems.iterator().forEach { it.selected = false }
broadcastRefreshSelection(TodoApplication.app.localBroadCastManager)
}
fun getTaskIndex(t: Task): Int {
return todoItems.indexOf(t)
}
fun getTaskAt(idx: Int): Task? {
return todoItems.getOrNull(idx)
}
fun editTasks(from: Activity, tasks: List<Task>, prefill: String) {
Log.d(TAG, "Edit tasks")
for (task in tasks) {
val i = todoItems.indexOf(task)
if (i >= 0) {
pendingEdits.add(Integer.valueOf(i))
}
}
startAddTaskActivity(from, prefill)
}
fun clearPendingEdits() {
Log.d(TAG, "Clear selection")
pendingEdits.clear()
}
}
| gpl-3.0 | 98be057490b39eeb7966dcb684653f40 | 31.769022 | 127 | 0.558338 | 4.76452 | false | false | false | false |
pyamsoft/power-manager | powermanager/src/main/java/com/pyamsoft/powermanager/manage/DelayItem.kt | 1 | 3064 | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.manage
import android.view.View
import com.pyamsoft.powermanager.Injector
import com.pyamsoft.powermanager.R
import com.pyamsoft.powermanager.databinding.AdapterItemSimpleBinding
import timber.log.Timber
import javax.inject.Inject
class DelayItem : TimeItem<TimePresenter, DelayItem.ViewHolder>(TAG) {
override fun getType(): Int {
return R.id.adapter_delay_card_item
}
override fun getTimeRadioOne(): Long {
return 5L
}
override fun getTimeRadioTwo(): Long {
return 10L
}
override fun getTimeRadioThree(): Long {
return 15L
}
override fun getTimeRadioFour(): Long {
return 30L
}
override fun getTimeRadioFive(): Long {
return 45L
}
override fun getTimeRadioSix(): Long {
return 60L
}
override fun getTimeRadioSeven(): Long {
return 90L
}
override fun getTimeRadioEight(): Long {
return 120L
}
override fun getViewHolder(view: View): ViewHolder {
return ViewHolder(view)
}
override fun bindView(holder: ViewHolder, payloads: List<Any>?) {
super.bindView(holder, payloads)
Timber.d("Bind Delay item")
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
Timber.d("Unbind Delay item")
}
class ViewHolder internal constructor(itemView: View) : TimeItem.ViewHolder<TimePresenter>(
itemView) {
@field:Inject override lateinit var presenter: TimePresenter
internal val binding = AdapterItemSimpleBinding.bind(itemView)
init {
Injector.with(itemView.context) {
it.plusManageComponent().injectDelay(this)
}
binding.simpleExpander.setTitle("Active Delay")
binding.simpleExpander.setDescription(
"Power Manager will wait for the specified amount of time before automatically managing certain device functions")
binding.simpleExpander.setExpandingContent(containerBinding.root)
containerBinding.delayRadioOne.text = "5 Seconds"
containerBinding.delayRadioTwo.text = "10 Seconds"
containerBinding.delayRadioThree.text = "15 Seconds"
containerBinding.delayRadioFour.text = "30 Seconds"
containerBinding.delayRadioFive.text = "45 Seconds"
containerBinding.delayRadioSix.text = "1 Minute"
containerBinding.delayRadioSeven.text = "1 Minute 30 Seconds"
containerBinding.delayRadioEight.text = "2 Minutes"
}
}
companion object {
const internal val TAG = "DelayItem"
}
}
| apache-2.0 | fb949d5e630d107b2f1a1512ce9c692f | 27.635514 | 124 | 0.725849 | 4.249653 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/kotlin/builder/tasks/js/Kotlin2JsTaskExecutor.kt | 1 | 3225 | package io.bazel.kotlin.builder.tasks.js
import io.bazel.kotlin.builder.toolchain.CompilationException
import io.bazel.kotlin.builder.toolchain.CompilationTaskContext
import io.bazel.kotlin.builder.toolchain.KotlinToolchain
import io.bazel.kotlin.builder.utils.addAll
import io.bazel.kotlin.builder.utils.jars.JarCreator
import io.bazel.kotlin.builder.utils.jars.SourceJarCreator
import io.bazel.kotlin.builder.utils.resolveTwinVerified
import io.bazel.kotlin.model.JsCompilationTask
import java.io.FileOutputStream
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Kotlin2JsTaskExecutor @Inject constructor(
private val invoker: KotlinToolchain.K2JSCompilerInvoker,
) {
private val fileSystem: FileSystem = FileSystems.getDefault()
fun execute(
context: CompilationTaskContext,
task: JsCompilationTask,
) {
task.compile(context)
val jsPath = fileSystem.getPath(task.outputs.js)
val jsMetaFile = jsPath.resolveTwinVerified(".meta.js")
val jsDirectory = Files.createDirectories(
fileSystem.getPath(task.directories.temp)
.resolve(jsPath.toFile().nameWithoutExtension),
)
task.createJar(
jsDirectory,
listOf(jsPath, jsPath.resolveTwinVerified(".js.map"), jsMetaFile),
)
// this mutates the jsPath file , so do it after creating the jar.
appendMetaToPrimary(jsPath, jsMetaFile)
task.createSourceJar()
}
private fun JsCompilationTask.compile(context: CompilationTaskContext) {
val args = mutableListOf<String>().also {
it.addAll(passThroughFlagsList)
it.addAll("-libraries", inputs.librariesList.joinToString(":"))
it.addAll("-output", outputs.js)
it.addAll(inputs.kotlinSourcesList)
}
context.whenTracing { printLines("js compile args", args) }
context.executeCompilerTask(args, invoker::compile)
}
private fun JsCompilationTask.createSourceJar() {
try {
SourceJarCreator(Paths.get(outputs.srcjar), false).also { creator ->
creator.addSources(inputs.kotlinSourcesList.map { Paths.get(it) }.stream())
}.execute()
} catch (ex: Throwable) {
throw CompilationException("could not create source jar", ex)
}
}
/**
* Append the meta file to the JS file. This is an accepted pattern, and it allows us to not have to export the
* meta.js file with the js.
*/
private fun appendMetaToPrimary(jsPath: Path, jsMetaFile: Path) {
try {
FileOutputStream(jsPath.toFile(), true).use { Files.copy(jsMetaFile, it) }
} catch (ex: Throwable) {
throw CompilationException("could not normalize js file", ex)
}
}
private fun JsCompilationTask.createJar(jsDirectoryPath: Path, rootEntries: List<Path>) {
try {
val outputJarPath = Paths.get(outputs.jar)
JarCreator(outputJarPath).also { creator ->
creator.addDirectory(jsDirectoryPath)
creator.addRootEntries(rootEntries.map { it.toString() })
creator.execute()
}
} catch (ex: Throwable) {
throw CompilationException("error creating js jar", ex)
}
}
}
| apache-2.0 | c68ea4b919441ed22d96b84ae8ecef59 | 33.308511 | 113 | 0.726822 | 4.066835 | false | false | false | false |
cliffroot/awareness | app/src/main/java/hive/com/paradiseoctopus/awareness/utils/PermissionUtility.kt | 1 | 1595 | package hive.com.paradiseoctopus.awareness.utils
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import rx.Observable
import rx.subjects.ReplaySubject
/**
* Created by cliffroot on 14.09.16.
*/
object PermissionUtility {
val REQUEST_LOCATION_CODE = 17
val REQUEST_WIFI_CODE = 19
var permissionSubject : ReplaySubject<Pair<Int, Boolean>> = ReplaySubject.create()
fun requestPermission (host : AppCompatActivity, permissions : List<String>,
requestCode : Int) : Observable<Pair<Int, Boolean>> {
Log.e("Request:", "r: " + permissions)
val toRequest = permissions.filter {
permission -> !checkPermission(host, permission)
}
Log.e("Request:", "r: " + toRequest)
permissionSubject = ReplaySubject.create()
if (!toRequest.isEmpty()) {
ActivityCompat.requestPermissions(host,
permissions.filter {
permission ->
!checkPermission(host, permission)
}.toTypedArray(), requestCode)
} else {
permissionSubject.onNext(Pair(requestCode, true))
permissionSubject.onCompleted()
}
return permissionSubject
}
fun checkPermission (host : AppCompatActivity, permission : String) : Boolean =
ContextCompat.checkSelfPermission(host, permission) == PackageManager.PERMISSION_GRANTED
} | apache-2.0 | 91b596c5ae2ca79c79a6523f69bd9daf | 32.957447 | 96 | 0.655172 | 4.892638 | false | false | false | false |
garmax1/material-flashlight | app/src/main/java/co/garmax/materialflashlight/ui/BaseFragment.kt | 1 | 967 | package co.garmax.materialflashlight.ui
import android.os.Build
import android.view.View
import androidx.fragment.app.Fragment
abstract class BaseFragment : Fragment() {
open val isInImmersiveMode = false
override fun onResume() {
super.onResume()
if (isInImmersiveMode) setFullscreen() else exitFullscreen()
}
private fun setFullscreen() {
var flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_FULLSCREEN
if (Build.VERSION.SDK_INT >= 19) {
flags =
flags or (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
}
requireActivity().window.decorView.systemUiVisibility = flags
}
private fun exitFullscreen() {
requireActivity().window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
}
} | apache-2.0 | 9ab523a21ecdbd0bf2d783ae44292094 | 29.25 | 108 | 0.679421 | 4.375566 | false | false | false | false |
DevJake/SaltBot-2.0 | src/test/kotlin/me/salt/entities/config/entities/PermissionMapBuilderTest.kt | 1 | 4026 | /*
* Copyright 2017 DevJake
*
* 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 me.salt.entities.config.entities
import com.winterbe.expekt.should
import me.salt.entities.permissions.GroupPermission
import me.salt.utilities.exception.ExceptionHandler
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
class PermissionMapBuilderTest : Spek({
ExceptionHandler.isTesting = true
var subject = PermissionMapBuilder()
val g0 = GroupPermission("group1", mutableListOf(), mutableListOf(), mutableListOf(), true, mutableListOf())
val g1 = GroupPermission("group2", mutableListOf(), mutableListOf(), mutableListOf(), false, mutableListOf())
val g2 = GroupPermission("group3", mutableListOf(), mutableListOf(), mutableListOf(), true, mutableListOf())
beforeEachTest { subject = PermissionMapBuilder() }
context("Group permissions") {
on("adding a single group permission") {
subject.addGroups(g0)
it("should add our group permission to the list of group permissions") {
(subject.build() as PermissionMap).groups.should.contain(g0)
}
it("should contain only one group permission") {
(subject.build() as PermissionMap).groups?.size.should.equal(1)
}
}
on("adding multiple group permission") {
subject.addGroups(g0, g1)
it("should add our group permission to the list of group permissions") {
(subject.build() as PermissionMap).groups.should.contain(g0)
(subject.build() as PermissionMap).groups.should.contain(g1)
}
it("should contain two group permissions") {
(subject.build() as PermissionMap).groups?.size.should.equal(2)
}
}
on("removing one existing group permission") {
subject.addGroups(g0)
it("should remove our specified group permission") {
subject.removeGroups(g0)
(subject.build() as PermissionMap).groups.should.not.contain(g0)
}
it("should contain zero group permissions") {
(subject.build() as PermissionMap).groups?.size.should.equal(0)
}
}
on("removing multiple existing group permissions where both are present") {
subject.addGroups(g0, g1)
it("should remove both of our specified group permissions") {
subject.removeGroups(g0, g1)
(subject.build() as PermissionMap).groups.should.not.contain(g0)
(subject.build() as PermissionMap).groups.should.not.contain(g1)
}
it("should contain zero group permissions") {
(subject.build() as PermissionMap).groups?.size.should.equal(0)
}
}
on("removing multiple group permissions where only one is present") {
subject.addGroups(g0, g2)
it("should remove only the existing specified group permissions") {
subject.removeGroups(g0, g1)
(subject.build() as PermissionMap).groups.should.not.contain(g0)
(subject.build() as PermissionMap).groups.should.contain(g2)
}
it("should contain zero group permissions") {
(subject.build() as PermissionMap).groups?.size.should.equal(1)
}
}
}
}) | apache-2.0 | da52c3baf0833f8ec37fb761475494ba | 40.515464 | 113 | 0.637606 | 4.498324 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDEKotlinAsJavaSupport.kt | 2 | 12026 | // 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.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory.getLightClassForDecompiledClassOrObject
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.caches.lightClasses.platformMutabilityWrapper
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.scopes.MemberScope
open class IDEKotlinAsJavaSupport(private val project: Project) : KotlinAsJavaSupport() {
private val psiManager: PsiManager = PsiManager.getInstance(project)
private val languageVersionSettings = project.languageVersionSettings
override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> {
val facadeFilesInPackage = project.runReadActionInSmartMode {
KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope)
}
return facadeFilesInPackage.map { it.javaFileFacadeFqName.shortName().asString() }.toSet()
}
override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val facadeFilesInPackage = runReadAction {
KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope).platformSourcesFirst()
}
val groupedByFqNameAndModuleInfo = facadeFilesInPackage.groupBy {
Pair(it.javaFileFacadeFqName, it.getModuleInfoPreferringJvmPlatform())
}
return groupedByFqNameAndModuleInfo.flatMap {
val (key, files) = it
val (fqName, moduleInfo) = key
createLightClassForFileFacade(fqName, files, moduleInfo)
}
}
override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> {
return project.runReadActionInSmartMode {
KotlinFullClassNameIndex.get(
fqName.asString(),
project,
KotlinSourceFilterScope.projectSourcesAndLibraryClasses(searchScope, project)
)
}
}
override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> {
return project.runReadActionInSmartMode {
KotlinPackageIndexUtils.findFilesWithExactPackage(
fqName,
KotlinSourceFilterScope.projectSourcesAndLibraryClasses(
searchScope,
project
),
project
)
}
}
override fun findClassOrObjectDeclarationsInPackage(
packageFqName: FqName,
searchScope: GlobalSearchScope
): Collection<KtClassOrObject> {
return KotlinTopLevelClassByPackageIndex.get(
packageFqName.asString(), project,
KotlinSourceFilterScope.projectSourcesAndLibraryClasses(searchScope, project)
)
}
override fun packageExists(fqName: FqName, scope: GlobalSearchScope): Boolean {
return KotlinPackageIndexUtils.packageExists(
fqName,
KotlinSourceFilterScope.projectSourcesAndLibraryClasses(
scope,
project
)
)
}
override fun getSubPackages(fqn: FqName, scope: GlobalSearchScope): Collection<FqName> {
return KotlinPackageIndexUtils.getSubPackageFqNames(
fqn,
KotlinSourceFilterScope.projectSourcesAndLibraryClasses(
scope,
project
),
MemberScope.ALL_NAME_FILTER
)
}
private val recursiveGuard = ThreadLocal<Boolean>()
private inline fun <T> guardedRun(body: () -> T): T? {
if (recursiveGuard.get() == true) return null
return try {
recursiveGuard.set(true)
body()
} finally {
recursiveGuard.set(false)
}
}
override fun getLightClass(classOrObject: KtClassOrObject): KtLightClass? {
if (!classOrObject.isValid) {
return null
}
val virtualFile = classOrObject.containingFile.virtualFile
if (virtualFile != null) {
when {
RootKindFilter.projectSources.matches(project, virtualFile) -> {
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
return KtLightClassForSourceDeclaration.create(classOrObject, jvmDefaultMode)
}
RootKindFilter.libraryClasses.matches(project, virtualFile) -> {
return getLightClassForDecompiledClassOrObject(classOrObject, project)
}
RootKindFilter.librarySources.matches(project, virtualFile) -> {
return guardedRun {
SourceNavigationHelper.getOriginalClass(classOrObject) as? KtLightClass
}
}
}
}
if ((classOrObject.containingFile as? KtFile)?.analysisContext != null ||
classOrObject.containingFile.originalFile.virtualFile != null
) {
// explicit request to create light class from dummy.kt
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
return KtLightClassForSourceDeclaration.create(classOrObject, jvmDefaultMode)
}
return null
}
override fun getLightClassForScript(script: KtScript): KtLightClass? {
if (!script.isValid) {
return null
}
return KtLightClassForScript.create(script)
}
override fun getFacadeClasses(facadeFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy { it.getModuleInfoPreferringJvmPlatform() }
return filesByModule.flatMap {
createLightClassForFileFacade(facadeFqName, it.value, it.key)
}
}
override fun getScriptClasses(scriptFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
return KotlinScriptFqnIndex.get(scriptFqName.asString(), project, scope).mapNotNull {
getLightClassForScript(it)
}
}
override fun getKotlinInternalClasses(fqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
if (fqName.isRoot) return emptyList()
val packageParts = findPackageParts(fqName, scope)
val platformWrapper = findPlatformWrapper(fqName, scope)
return if (platformWrapper != null) packageParts + platformWrapper else packageParts
}
private fun findPackageParts(fqName: FqName, scope: GlobalSearchScope): List<KtLightClassForDecompiledDeclaration> {
val facadeKtFiles = StaticFacadeIndexUtil.getMultifileClassForPart(fqName, scope, project)
val partShortName = fqName.shortName().asString()
val partClassFileShortName = "$partShortName.class"
return facadeKtFiles.mapNotNull { facadeKtFile ->
if (facadeKtFile is KtClsFile) {
val partClassFile = facadeKtFile.virtualFile.parent.findChild(partClassFileShortName) ?: return@mapNotNull null
val javaClsClass = DecompiledLightClassesFactory.createClsJavaClassFromVirtualFile(facadeKtFile, partClassFile, null, project) ?: return@mapNotNull null
KtLightClassForDecompiledDeclaration(javaClsClass, javaClsClass.parent, facadeKtFile, null)
} else {
// TODO should we build light classes for parts from source?
null
}
}
}
private fun findPlatformWrapper(fqName: FqName, scope: GlobalSearchScope): PsiClass? {
return platformMutabilityWrapper(fqName) {
JavaPsiFacade.getInstance(
project
).findClass(it, scope)
}
}
private fun createLightClassForFileFacade(
facadeFqName: FqName,
facadeFiles: List<KtFile>,
moduleInfo: IdeaModuleInfo
): List<PsiClass> = SmartList<PsiClass>().apply {
tryCreateFacadesForSourceFiles(moduleInfo, facadeFqName)?.let { sourcesFacade ->
add(sourcesFacade)
}
facadeFiles.filterIsInstance<KtClsFile>().mapNotNullTo(this) {
DecompiledLightClassesFactory.createLightClassForDecompiledKotlinFile(it, project)
}
}
private fun tryCreateFacadesForSourceFiles(moduleInfo: IdeaModuleInfo, facadeFqName: FqName): PsiClass? {
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is PlatformModuleInfo) return null
return KtLightClassForFacadeImpl.createForFacade(psiManager, facadeFqName, moduleInfo.contentScope)
}
override fun findFilesForFacade(facadeFqName: FqName, scope: GlobalSearchScope): Collection<KtFile> {
return runReadAction {
KotlinFileFacadeFqNameIndex.get(facadeFqName.asString(), project, scope).platformSourcesFirst()
}
}
override fun getFakeLightClass(classOrObject: KtClassOrObject): KtFakeLightClass =
KtDescriptorBasedFakeLightClass(classOrObject)
override fun createFacadeForSyntheticFile(facadeClassFqName: FqName, file: KtFile): PsiClass =
KtLightClassForFacadeImpl.createForSyntheticFile(facadeClassFqName, file)
// NOTE: this is a hacky solution to the following problem:
// when building this light class resolver will be built by the first file in the list
// (we could assume that files are in the same module before)
// thus we need to ensure that resolver will be built by the file from platform part of the module
// (resolver built by a file from the common part will have no knowledge of the platform part)
// the actual of order of files that resolver receives is controlled by *findFilesForFacade* method
private fun Collection<KtFile>.platformSourcesFirst() =
sortedByDescending { it.platform.isJvm() }
private fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo =
getPlatformModuleInfo(JvmPlatforms.unspecifiedJvmPlatform) ?: this.moduleInfo
}
| apache-2.0 | 9068ad27f4cb2fcffa27dd57b233b074 | 44.900763 | 168 | 0.714119 | 5.549608 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/provider/KotlinScriptClassPathProviderTest.kt | 1 | 2912 | package org.gradle.kotlin.dsl.provider
import org.gradle.kotlin.dsl.support.ProgressMonitor
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Generated
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactory.ClassPathNotation.GRADLE_API
import org.gradle.api.internal.classpath.Module
import org.gradle.api.internal.file.TestFiles
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.kotlin.dsl.accessors.TestWithClassPath
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@LeaksFileHandles("embedded Kotlin compiler environment keepalive")
class KotlinScriptClassPathProviderTest : TestWithClassPath() {
@Test
fun `should report progress based on the number of entries in gradle-api jar`() {
val gradleApiJar = jarClassPathWith("gradle-api-3.1.jar", Generated::class).asFiles
val generatedKotlinExtensions = file("kotlin-dsl-extensions.jar")
val apiMetadataModule = mockGradleApiMetadataModule()
val kotlinExtensionsMonitor = mock<ProgressMonitor>(name = "kotlinExtensionsMonitor")
val progressMonitorProvider = mock<JarGenerationProgressMonitorProvider> {
on { progressMonitorFor(generatedKotlinExtensions, 3) } doReturn kotlinExtensionsMonitor
}
val subject = KotlinScriptClassPathProvider(
moduleRegistry = mock { on { getExternalModule(any()) } doReturn apiMetadataModule },
classPathRegistry = mock { on { getClassPath(GRADLE_API.name) } doReturn DefaultClassPath.of(gradleApiJar) },
coreAndPluginsScope = mock(),
gradleApiJarsProvider = { gradleApiJar },
jarCache = { id, generator -> file("$id.jar").apply(generator) },
progressMonitorProvider = progressMonitorProvider,
temporaryFileProvider = TestFiles.tmpDirTemporaryFileProvider(tempFolder.root)
)
assertThat(
subject.gradleKotlinDsl.asFiles.toList(),
equalTo(gradleApiJar + generatedKotlinExtensions)
)
verifyProgressMonitor(kotlinExtensionsMonitor)
}
private
fun verifyProgressMonitor(monitor: ProgressMonitor) {
verify(monitor, times(3)).onProgress()
verify(monitor, times(1)).close()
}
private
fun mockGradleApiMetadataModule() =
withZip(
"gradle-api-metadata-0.jar",
sequenceOf(
"gradle-api-declaration.properties" to "includes=\nexcludes=\n".toByteArray()
)
).let { jar ->
mock<Module> { on { classpath } doReturn DefaultClassPath.of(listOf(jar)) }
}
}
| apache-2.0 | 9ae0658175b80c71d3d358fa32c4f39e | 36.818182 | 121 | 0.720124 | 4.674157 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/widgets/MySiteTitleAndSubtitleLabelView.kt | 1 | 2073 | package org.wordpress.android.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import com.google.android.material.button.MaterialButton
import com.google.android.material.textview.MaterialTextView
import org.wordpress.android.R
/**
* Text View used for a site name and url label on My Site fragment.
* This view works in tandem with autosizing behavior of title textiview so
* when the title is long, and wraps to the next line text size is reduced and title and subtitle stop being centered.
*/
class MySiteTitleAndSubtitleLabelView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
var title: MaterialTextView
var subtitle: MaterialButton
init {
inflate(context, R.layout.my_site_title_subtitle_view, this)
title = findViewById(R.id.my_site_title_label)
subtitle = findViewById(R.id.my_site_subtitle_label)
val guideline = findViewById<View>(R.id.guideline)
title.viewTreeObserver.addOnGlobalLayoutListener {
if (title.lineCount == 1 && (title.layoutParams as LayoutParams).bottomToTop == View.NO_ID) {
val constraintSet = ConstraintSet()
constraintSet.clone(this@MySiteTitleAndSubtitleLabelView)
constraintSet.connect(title.id, ConstraintSet.BOTTOM, guideline.id, ConstraintSet.TOP, 0)
constraintSet.applyTo(this@MySiteTitleAndSubtitleLabelView)
} else if (title.lineCount > 1 && (title.layoutParams as LayoutParams).bottomToTop == guideline.id) {
val constraintSet = ConstraintSet()
constraintSet.clone(this@MySiteTitleAndSubtitleLabelView)
constraintSet.clear(title.id, ConstraintSet.BOTTOM)
constraintSet.applyTo(this@MySiteTitleAndSubtitleLabelView)
}
}
}
}
| gpl-2.0 | 5d6f3e1f2d21e61dceab2f4daf113557 | 43.106383 | 118 | 0.720212 | 4.668919 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/TabRouter.kt | 1 | 2171 | package forpdateam.ru.forpda.presentation
import ru.terrakok.cicerone.Router
class TabRouter : Router() {
companion object {
private const val errorMessage = "Use methods with class Screen instead screenKey"
}
fun newScreenChain(screen: Screen) {
super.newScreenChain(screen.getKey(), screen)
}
fun navigateTo(screen: Screen) {
super.navigateTo(screen.getKey(), screen)
}
fun backTo(screen: Screen) {
super.backTo(screen.getKey())
}
fun replaceScreen(screen: Screen) {
super.replaceScreen(screen.getKey(), screen)
}
fun newRootScreen(screen: Screen) {
super.newRootScreen(screen.getKey(), screen)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun newScreenChain(screenKey: String) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun newScreenChain(screenKey: String, data: Any?) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun navigateTo(screenKey: String) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun navigateTo(screenKey: String, data: Any?) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun backTo(screenKey: String) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun replaceScreen(screenKey: String) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun replaceScreen(screenKey: String, data: Any?) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun newRootScreen(screenKey: String) {
throw Exception(errorMessage)
}
@Deprecated(errorMessage, level = DeprecationLevel.ERROR)
override fun newRootScreen(screenKey: String, data: Any?) {
throw Exception(errorMessage)
}
} | gpl-3.0 | 6e58a0fa3c31cb2d28f7879352efd8ad | 28.351351 | 90 | 0.690926 | 4.589852 | false | false | false | false |
DiUS/pact-jvm | core/support/src/main/kotlin/au/com/dius/pact/core/support/HttpClient.kt | 1 | 3926 | package au.com.dius.pact.core.support
import au.com.dius.pact.core.support.expressions.DataType
import au.com.dius.pact.core.support.expressions.ExpressionParser.parseExpression
import au.com.dius.pact.core.support.expressions.ValueResolver
import mu.KLogging
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.impl.client.HttpClients
import org.apache.http.impl.client.SystemDefaultCredentialsProvider
import org.apache.http.message.BasicHeader
import java.net.URI
sealed class Auth {
data class BasicAuthentication(val username: String, val password: String) : Auth()
data class BearerAuthentication(val token: String) : Auth()
fun resolveProperties(resolver: ValueResolver): Auth {
return when (this) {
is BasicAuthentication -> BasicAuthentication(parseExpression(this.username, DataType.RAW, resolver).toString(),
parseExpression(this.password, DataType.RAW, resolver).toString())
is BearerAuthentication -> BearerAuthentication(parseExpression(this.token, DataType.RAW, resolver).toString())
}
}
}
/**
* HTTP client support functions
*/
object HttpClient : KLogging() {
/**
* Creates a new HTTP client
*/
fun newHttpClient(
authentication: Any?,
uri: URI,
defaultHeaderStore: MutableMap<String, String>,
maxPublishRetries: Int = 5,
publishRetryInterval: Int = 3000
): Pair<CloseableHttpClient, CredentialsProvider?> {
val retryStrategy = CustomServiceUnavailableRetryStrategy(maxPublishRetries, publishRetryInterval)
val builder = HttpClients.custom().useSystemProperties().setServiceUnavailableRetryStrategy(retryStrategy)
val credsProvider = when (authentication) {
is Auth -> {
when (authentication) {
is Auth.BasicAuthentication -> basicAuth(uri, authentication.username, authentication.password, builder)
is Auth.BearerAuthentication -> {
defaultHeaderStore["Authorization"] = "Bearer " + authentication.token
SystemDefaultCredentialsProvider()
}
}
}
is List<*> -> {
when (val scheme = authentication.first().toString().toLowerCase()) {
"basic" -> {
if (authentication.size > 2) {
basicAuth(uri, authentication[1].toString(), authentication[2].toString(), builder)
} else {
logger.warn { "Basic authentication requires a username and password, ignoring." }
SystemDefaultCredentialsProvider()
}
}
"bearer" -> {
if (authentication.size > 1) {
defaultHeaderStore["Authorization"] = "Bearer " + authentication[1].toString()
} else {
logger.warn { "Bearer token authentication requires a token, ignoring." }
}
SystemDefaultCredentialsProvider()
}
else -> {
logger.warn { "HTTP client Only supports basic and bearer token authentication, got '$scheme', ignoring." }
SystemDefaultCredentialsProvider()
}
}
}
else -> SystemDefaultCredentialsProvider()
}
builder.setDefaultHeaders(defaultHeaderStore.map { BasicHeader(it.key, it.value) })
return builder.build() to credsProvider
}
private fun basicAuth(
uri: URI,
username: String,
password: String,
builder: HttpClientBuilder
): CredentialsProvider {
val credsProvider = BasicCredentialsProvider()
credsProvider.setCredentials(AuthScope(uri.host, uri.port),
UsernamePasswordCredentials(username, password))
builder.setDefaultCredentialsProvider(credsProvider)
return credsProvider
}
}
| apache-2.0 | 1e12d2e49ad7d30a24e46cd5b7b40279 | 37.490196 | 119 | 0.698166 | 4.747279 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/CodeWriter.kt | 2 | 4590 | // 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.codegen
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresWriteLock
import com.intellij.workspaceModel.codegen.deft.model.DefType
import com.intellij.workspaceModel.codegen.deft.model.KtObjModule
import com.intellij.workspaceModel.codegen.patcher.rewrite
import com.intellij.workspaceModel.codegen.utils.fileContents
import com.intellij.workspaceModel.storage.*
import java.io.File
val SKIPPED_TYPES = setOf(WorkspaceEntity::class.simpleName,
ReferableWorkspaceEntity::class.simpleName,
ModifiableWorkspaceEntity::class.simpleName,
ModifiableReferableWorkspaceEntity::class.simpleName,
WorkspaceEntityWithPersistentId::class.simpleName)
fun DefType.implIjWsFileContents(simpleTypes: List<DefType>): String {
return fileContents(def.file!!.pkg.fqn, """
${implWsCode(simpleTypes)}
""".trim(), def.file?.imports?.list)
}
private val LOG = logger<CodeWriter>()
object CodeWriter {
@RequiresWriteLock
fun generate(project: Project, sourceFolder: VirtualFile, keepUnknownFields: Boolean, targetFolderGenerator: () -> VirtualFile?) {
val documentManager = FileDocumentManager.getInstance()
val ktSrcs = mutableListOf<Pair<VirtualFile, Document>>()
val fileMapping = mutableMapOf<String, VirtualFile>()
VfsUtilCore.processFilesRecursively(sourceFolder) {
if (it.extension == "kt") {
val document = documentManager.getDocument(it) ?: return@processFilesRecursively true
ktSrcs.add(it to document)
fileMapping[it.name] = it
}
return@processFilesRecursively true
}
val module = KtObjModule(project, keepUnknownFields = keepUnknownFields)
ktSrcs.forEach { (vfu, document) ->
module.addPsiFile(vfu.name, vfu) { document.text }
}
val result = module.build()
val entitiesForGeneration = result.typeDefs.filterNot { it.utilityType || it.abstract }
if (!entitiesForGeneration.isEmpty()) {
val genFolder = targetFolderGenerator.invoke()
if (genFolder == null) {
LOG.info("Generated source folder doesn't exist. Skip processing source folder with path: ${sourceFolder}")
return
}
module.files.forEach {
val virtualFile = fileMapping[it.name] ?: return@forEach
val fileContent = it.rewrite() ?: return@forEach
documentManager.getDocument(virtualFile)?.setText(fileContent)
}
entitiesForGeneration.forEach {
val sourceFile = it.def.file?.virtualFile ?: error("Source file for ${it.def.name} doesn't exist")
val packageFolder = createPackageFolderIfMissing(sourceFolder, sourceFile, genFolder)
val virtualFile = packageFolder.createChildData(this, it.javaImplName + ".kt")
documentManager.getDocument(virtualFile)?.setText(it.implIjWsFileContents(result.simpleTypes))
}
} else {
LOG.info("Not found types for generation")
}
}
fun generate(dir: File, fromDirectory: String, generatedDestDir: File, keepUnknownFields: Boolean) {
generatedDestDir.mkdirs()
val ktSrcs = dir.resolve(fromDirectory).listFiles()!!
.toList()
.filter { it.name.endsWith(".kt") }
val module = KtObjModule(null, keepUnknownFields)
ktSrcs.forEach {
module.addFile(it.relativeTo(dir).path, null) { it.readText() }
}
val result = module.build()
module.files.forEach {
val fileContent = it.rewrite() ?: return@forEach
dir.resolve(it.name).writeText(fileContent)
}
result.typeDefs.filterNot { it.name == "WorkspaceEntity" || it.name == "WorkspaceEntityWithPersistentId" || it.abstract }.forEach {
generatedDestDir
.resolve(it.javaImplName + ".kt")
.writeText(it.implIjWsFileContents(result.simpleTypes))
}
}
private fun createPackageFolderIfMissing(sourceRoot: VirtualFile, sourceFile: VirtualFile, genFolder: VirtualFile): VirtualFile {
val relativePath = VfsUtil.getRelativePath(sourceFile.parent, sourceRoot, '/')
return VfsUtil.createDirectoryIfMissing(genFolder, "$relativePath")
}
} | apache-2.0 | 3da33dac24b5d94bf11b2c603a94d530 | 43.572816 | 135 | 0.719826 | 4.531096 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LetImplementInterfaceFix.kt | 2 | 3967 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isInterface
class LetImplementInterfaceFix(
element: KtClassOrObject,
expectedType: KotlinType,
expressionType: KotlinType
) : KotlinQuickFixAction<KtClassOrObject>(element), LowPriorityAction {
private fun KotlinType.renderShort() = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(this)
private val expectedTypeName: String
private val expectedTypeNameSourceCode: String
private val prefix: String
private val validExpectedType = with(expectedType) {
isInterface() &&
!containsStarProjections() &&
constructor !in TypeUtils.getAllSupertypes(expressionType).map(KotlinType::constructor)
}
init {
val expectedTypeNotNullable = TypeUtils.makeNotNullable(expectedType)
expectedTypeName = expectedTypeNotNullable.renderShort()
expectedTypeNameSourceCode = IdeDescriptorRenderers.SOURCE_CODE.renderType(expectedTypeNotNullable)
val verb = if (expressionType.isInterface()) KotlinBundle.message("text.extend") else KotlinBundle.message("text.implement")
val typeDescription = if (element.isObjectLiteral())
KotlinBundle.message("the.anonymous.object")
else
"'${expressionType.renderShort()}'"
prefix = KotlinBundle.message("let.0.1", typeDescription, verb)
}
override fun getFamilyName() = KotlinBundle.message("let.type.implement.interface")
override fun getText() = KotlinBundle.message("0.interface.1", prefix, expectedTypeName)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = validExpectedType
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val point = element.createSmartPointer()
val superTypeEntry = KtPsiFactory(element).createSuperTypeEntry(expectedTypeNameSourceCode)
runWriteAction {
val entryElement = element.addSuperTypeListEntry(superTypeEntry)
ShortenReferences.DEFAULT.process(entryElement)
}
val newElement = point.element ?: return
val implementMembersHandler = ImplementMembersHandler()
if (implementMembersHandler.collectMembersToGenerate(newElement).isEmpty()) return
if (editor != null) {
editor.caretModel.moveToOffset(element.textRange.startOffset)
val containingFile = element.containingFile
FileEditorManager.getInstance(project).openFile(containingFile.virtualFile, true)
implementMembersHandler.invoke(project, editor, containingFile)
}
}
}
| apache-2.0 | df7faeb44e6f620c10d9ca8d21987761 | 44.597701 | 158 | 0.765566 | 5.151948 | false | false | false | false |
SimpleMobileTools/Simple-Music-Player | app/src/main/kotlin/com/simplemobiletools/musicplayer/databases/SongsDatabase.kt | 1 | 8314 | package com.simplemobiletools.musicplayer.databases
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.simplemobiletools.musicplayer.interfaces.*
import com.simplemobiletools.musicplayer.models.*
import com.simplemobiletools.musicplayer.objects.MyExecutor
@Database(entities = [Track::class, Playlist::class, QueueItem::class, Artist::class, Album::class], version = 11)
abstract class SongsDatabase : RoomDatabase() {
abstract fun SongsDao(): SongsDao
abstract fun PlaylistsDao(): PlaylistsDao
abstract fun QueueItemsDao(): QueueItemsDao
abstract fun ArtistsDao(): ArtistsDao
abstract fun AlbumsDao(): AlbumsDao
companion object {
private var db: SongsDatabase? = null
fun getInstance(context: Context): SongsDatabase {
if (db == null) {
synchronized(SongsDatabase::class) {
if (db == null) {
db = Room.databaseBuilder(context.applicationContext, SongsDatabase::class.java, "songs.db")
.setQueryExecutor(MyExecutor.myExecutor)
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.addMigrations(MIGRATION_3_4)
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.addMigrations(MIGRATION_6_7)
.addMigrations(MIGRATION_7_8)
.addMigrations(MIGRATION_8_9)
.addMigrations(MIGRATION_9_10)
.addMigrations(MIGRATION_10_11)
.build()
}
}
}
return db!!
}
fun destroyInstance() {
db = null
}
// removing the "type" value of Song
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"CREATE TABLE songs_new (media_store_id INTEGER NOT NULL, title TEXT NOT NULL, artist TEXT NOT NULL, path TEXT NOT NULL, duration INTEGER NOT NULL, " +
"album TEXT NOT NULL, playlist_id INTEGER NOT NULL, PRIMARY KEY(path, playlist_id))"
)
execSQL(
"INSERT INTO songs_new (media_store_id, title, artist, path, duration, album, playlist_id) " +
"SELECT media_store_id, title, artist, path, duration, album, playlist_id FROM songs"
)
execSQL("DROP TABLE songs")
execSQL("ALTER TABLE songs_new RENAME TO songs")
execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_playlists_id` ON `playlists` (`id`)")
}
}
}
private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE songs ADD COLUMN track_id INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE songs ADD COLUMN cover_art TEXT default '' NOT NULL")
}
}
private val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE `queue_items` (`track_id` INTEGER NOT NULL PRIMARY KEY, `track_order` INTEGER NOT NULL, `is_current` INTEGER NOT NULL, `last_position` INTEGER NOT NULL)")
}
}
// change the primary keys from path + playlist_id to media_store_id + playlist_id
private val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"CREATE TABLE songs_new (media_store_id INTEGER NOT NULL, title TEXT NOT NULL, artist TEXT NOT NULL, path TEXT NOT NULL, duration INTEGER NOT NULL, " +
"album TEXT NOT NULL, cover_art TEXT default '' NOT NULL, playlist_id INTEGER NOT NULL, track_id INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(media_store_id, playlist_id))"
)
execSQL(
"INSERT OR IGNORE INTO songs_new (media_store_id, title, artist, path, duration, album, cover_art, playlist_id, track_id) " +
"SELECT media_store_id, title, artist, path, duration, album, cover_art, playlist_id, track_id FROM songs"
)
execSQL("DROP TABLE songs")
execSQL("ALTER TABLE songs_new RENAME TO tracks")
}
}
}
// adding an autoincrementing "id" field, replace primary keys with indices
private val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL(
"CREATE TABLE tracks_new (`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `media_store_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `artist` TEXT NOT NULL, `path` TEXT NOT NULL, `duration` INTEGER NOT NULL, " +
"`album` TEXT NOT NULL, `cover_art` TEXT default '' NOT NULL, `playlist_id` INTEGER NOT NULL, `track_id` INTEGER NOT NULL DEFAULT 0)"
)
execSQL(
"INSERT OR IGNORE INTO tracks_new (media_store_id, title, artist, path, duration, album, cover_art, playlist_id, track_id) " +
"SELECT media_store_id, title, artist, path, duration, album, cover_art, playlist_id, track_id FROM tracks"
)
execSQL("DROP TABLE tracks")
execSQL("ALTER TABLE tracks_new RENAME TO tracks")
execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_tracks_id` ON `tracks` (`media_store_id`, `playlist_id`)")
}
}
}
private val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(database: SupportSQLiteDatabase) {
database.apply {
execSQL("CREATE TABLE `artists` (`id` INTEGER NOT NULL PRIMARY KEY, `title` TEXT NOT NULL, `album_cnt` INTEGER NOT NULL, `track_cnt` INTEGER NOT NULL, `album_art_id` INTEGER NOT NULL)")
execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_artists_id` ON `artists` (`id`)")
execSQL("CREATE TABLE `albums` (`id` INTEGER NOT NULL PRIMARY KEY, `artist` TEXT NOT NULL, `title` TEXT NOT NULL, `cover_art` TEXT NOT NULL, `year` INTEGER NOT NULL)")
execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_albums_id` ON `albums` (`id`)")
}
}
}
private val MIGRATION_7_8 = object : Migration(7, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE tracks ADD COLUMN folder_name TEXT default '' NOT NULL")
}
}
private val MIGRATION_8_9 = object : Migration(8, 9) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE albums ADD COLUMN track_cnt INTEGER NOT NULL DEFAULT 0")
}
}
private val MIGRATION_9_10 = object : Migration(9, 10) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE albums ADD COLUMN artist_id INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE tracks ADD COLUMN album_id INTEGER NOT NULL DEFAULT 0")
}
}
private val MIGRATION_10_11 = object : Migration(10, 11) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE tracks ADD COLUMN order_in_playlist INTEGER NOT NULL DEFAULT 0")
}
}
}
}
| gpl-3.0 | 877478379dd40556f1b0fe6ade7b226d | 47.905882 | 235 | 0.570844 | 4.861988 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/teams/SingleTeamViewModel.kt | 1 | 1903 | package dev.mfazio.abl.teams
import android.content.Intent
import android.view.View
import androidx.lifecycle.*
import dev.mfazio.abl.standings.TeamStanding
import dev.mfazio.abl.standings.UITeamStanding
import java.net.URLEncoder
class SingleTeamViewModel : ViewModel() {
val team = MutableLiveData<UITeam>()
private val standings: LiveData<List<TeamStanding>>
val teamStanding = MediatorLiveData<UITeamStanding>()
init {
standings = MutableLiveData<List<TeamStanding>>().apply {
value = TeamStanding.mockTeamStandings
}
teamStanding.addSource(this.team) { uiTeam ->
updateUIStanding(uiTeam, standings.value)
}
teamStanding.addSource(this.standings) { standings ->
updateUIStanding(team.value, standings)
}
}
fun setTeam(teamId: String) {
UITeam.allTeams.firstOrNull { it.teamId == teamId }?.let { team ->
this.team.value = team
}
}
fun shareTeam(view: View) {
team.value?.let { team ->
val encodedTeamName = URLEncoder.encode(team.teamName, "UTF-8")
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(
Intent.EXTRA_TEXT,
"https://link.mfazio.dev/teams/${team.teamId}" +
"?teamName=$encodedTeamName"
)
type = "text/plain"
}
val shareIntent =
Intent.createChooser(sendIntent, "Share ${team.teamName}")
view.context.startActivity(shareIntent)
}
}
private fun updateUIStanding(uiTeam: UITeam?, teamStandings: List<TeamStanding>?) {
if(uiTeam != null && teamStandings != null) {
this.teamStanding.value = UITeamStanding.fromTeamAndStandings(uiTeam, teamStandings)
}
}
} | apache-2.0 | acaa5b2e596b8f2f618f6a4ca50d5d4e | 29.222222 | 96 | 0.604834 | 4.509479 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransitName.kt | 1 | 3102 | /*
* TransitName.kt
*
* Copyright (C) 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.util.Preferences
class TransitName(
val englishFull: String?,
val englishShort: String?,
val localFull: String?,
val localShort: String?,
val localLanguagesList: List<String>,
val ttsHintLanguage: String
) {
private fun useEnglishName(): Boolean {
val locale = Preferences.language
return !localLanguagesList.contains(locale)
}
fun selectBestName(isShort: Boolean): FormattedString? {
val hasEnglishFull = englishFull != null && !englishFull.isEmpty()
val hasEnglishShort = englishShort != null && !englishShort.isEmpty()
val english: String? = when {
hasEnglishFull && !hasEnglishShort -> englishFull
!hasEnglishFull && hasEnglishShort -> englishShort
isShort -> englishShort
else -> englishFull
}
val hasLocalFull = localFull != null && !localFull.isEmpty()
val hasLocalShort = localShort != null && !localShort.isEmpty()
val local: String? = when {
hasLocalFull && !hasLocalShort -> localFull
!hasLocalFull && hasLocalShort -> localShort
isShort -> localShort
else -> localFull
}
if (showBoth() && english != null && !english.isEmpty()
&& local != null && !local.isEmpty()) {
if (english == local)
return FormattedString.language(local, ttsHintLanguage)
return if (useEnglishName()) FormattedString.english(english) + " (" + FormattedString.language(local, ttsHintLanguage) + ")" else FormattedString.language(local, ttsHintLanguage) + " (" + FormattedString.english(english) + ")"
}
if (useEnglishName() && english != null && !english.isEmpty()) {
return FormattedString.english(english)
}
return if (local != null && !local.isEmpty()) {
// Local preferred, or English not available
FormattedString.language(local, ttsHintLanguage)
} else if (english != null) {
// Local unavailable, use English
FormattedString.english(english)
} else
null
}
companion object {
private fun showBoth(): Boolean = Preferences.showBothLocalAndEnglish
}
}
| gpl-3.0 | 591f99c90304462d101f394319a5fad9 | 36.829268 | 239 | 0.647969 | 4.528467 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddLoopLabelFix.kt | 4 | 3859 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
class AddLoopLabelFix(
loop: KtLoopExpression,
private val jumpExpression: KtExpressionWithLabel
) : KotlinQuickFixAction<KtLoopExpression>(loop) {
private val existingLabelName = (loop.parent as? KtLabeledExpression)?.getLabelName()
@Nls
private val description = run {
when {
existingLabelName != null -> {
val labelName = "@$existingLabelName"
KotlinBundle.message("fix.add.loop.label.text", labelName, jumpExpression.text)
}
else -> {
KotlinBundle.message("fix.add.loop.label.text.generic")
}
}
}
override fun getText() = description
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val labelName = existingLabelName ?: getUniqueLabelName(element)
val jumpWithLabel = KtPsiFactory(project).createExpression(jumpExpression.text + "@" + labelName)
jumpExpression.replace(jumpWithLabel)
// TODO(yole) use createExpressionByPattern() once it's available
if (existingLabelName == null) {
val labeledLoopExpression = KtPsiFactory(project).createLabeledExpression(labelName)
labeledLoopExpression.baseExpression!!.replace(element)
element.replace(labeledLoopExpression)
}
// TODO(yole) We should initiate in-place rename for the label here, but in-place rename for labels is not yet implemented
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtExpressionWithLabel
assert(element is KtBreakExpression || element is KtContinueExpression)
assert((element as? KtLabeledExpression)?.getLabelName() == null)
val loop = element?.getStrictParentOfType<KtLoopExpression>() ?: return null
return AddLoopLabelFix(loop, element)
}
private fun collectUsedLabels(element: KtElement): Set<String> {
val usedLabels = hashSetOf<String>()
element.acceptChildren(object : KtTreeVisitorVoid() {
override fun visitLabeledExpression(expression: KtLabeledExpression) {
super.visitLabeledExpression(expression)
usedLabels.add(expression.getLabelName()!!)
}
})
element.parents.forEach {
if (it is KtLabeledExpression) {
usedLabels.add(it.getLabelName()!!)
}
}
return usedLabels
}
private fun getUniqueLabelName(existingNames: Collection<String>): String {
var index = 0
var result = "loop"
while (result in existingNames) {
result = "loop${++index}"
}
return result
}
fun getUniqueLabelName(loop: KtLoopExpression): String =
getUniqueLabelName(collectUsedLabels(loop))
}
} | apache-2.0 | 8a20a6fd5deaa1317aed40d7a54c3c85 | 40.505376 | 158 | 0.666494 | 5.315427 | false | false | false | false |
kherembourg/MetaAPI | app/src/main/java/net/apigator/metaapi/CinemaActivity.kt | 1 | 2593 | package net.apigator.metaapi
import android.content.Intent
import android.location.Geocoder
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
class CinemaActivity : AppCompatActivity(), OnMapReadyCallback {
private var mMap: GoogleMap? = null
private var mResponseNode: ResponseNode? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cinema)
title = "Cinemas around you"
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
mResponseNode = intent.extras.getParcelable<ResponseNode>("response")
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mResponseNode?.children?.forEach {
val geocoder = Geocoder(applicationContext)
val locations = geocoder.getFromLocationName(it.node.address, 1)
if(locations != null) {
val position = LatLng(locations[0].latitude, locations[0].longitude)
mMap!!.addMarker(MarkerOptions().position(position).title(it.node.name).snippet(it.node.address))
}
}
val myPosition = LatLng(48.855800, 2.358570)
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 13f))
mMap!!.setOnInfoWindowClickListener {
val intent = Intent(applicationContext, MovieListActivity::class.java)
intent.putExtra("cinema", mResponseNode?.children!![it.id.substring(1).toInt()])
startActivity(intent)
}
}
}
| apache-2.0 | 334a57f8fddc3c1384a8b0e398fa494b | 40.822581 | 113 | 0.71076 | 4.581272 | false | false | false | false |
cfieber/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteExecutionHandlerTest.kt | 1 | 9917 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.StartWaitingExecutions
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
import java.time.Duration
import java.util.*
import kotlin.collections.set
object CompleteExecutionHandlerTest : SubjectSpek<CompleteExecutionHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val retryDelay = Duration.ofSeconds(5)
subject(GROUP) {
CompleteExecutionHandler(queue, repository, publisher, retryDelayMs = retryDelay.toMillis())
}
fun resetMocks() = reset(queue, repository, publisher)
setOf(SUCCEEDED, TERMINAL, CANCELED).forEach { stageStatus ->
describe("when an execution completes and has a single stage with $stageStatus status") {
val pipeline = pipeline {
stage {
refId = "1"
status = stageStatus
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("updates the execution") {
verify(repository).updateStatus(message.executionType, message.executionId, stageStatus)
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.status).isEqualTo(stageStatus)
})
}
it("does not queue any other commands") {
verifyZeroInteractions(queue)
}
}
describe("when an execution with a pipelineConfigId completes with $stageStatus") {
val configId = UUID.randomUUID().toString()
val pipeline = pipeline {
pipelineConfigId = configId
stage {
refId = "1"
status = stageStatus
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("triggers any waiting pipelines") {
verify(queue).push(StartWaitingExecutions(configId, !pipeline.isKeepWaitingPipelines))
}
it("does not queue any other commands") {
verifyNoMoreInteractions(queue)
}
}
}
setOf(SUCCEEDED, STOPPED, FAILED_CONTINUE, SKIPPED).forEach { stageStatus ->
describe("an execution appears to complete with one branch $stageStatus but other branches are still running") {
val pipeline = pipeline {
stage {
refId = "1"
status = stageStatus
}
stage {
refId = "2"
status = RUNNING
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("waits for the other branch(es)") {
verify(repository, never()).updateStatus(eq(PIPELINE), eq(pipeline.id), any())
}
it("does not publish any events") {
verifyZeroInteractions(publisher)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
verifyNoMoreInteractions(queue)
}
}
}
setOf(TERMINAL, CANCELED).forEach { stageStatus ->
describe("a stage signals branch completion with $stageStatus but other branches are still running") {
val pipeline = pipeline {
stage {
refId = "1"
status = stageStatus
}
stage {
refId = "2"
status = RUNNING
}
stage {
refId = "3"
status = RUNNING
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("updates the pipeline status") {
verify(repository).updateStatus(PIPELINE, pipeline.id, stageStatus)
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.status).isEqualTo(stageStatus)
})
}
it("cancels other stages") {
verify(queue).push(CancelStage(pipeline.stageByRef("2")))
verify(queue).push(CancelStage(pipeline.stageByRef("3")))
verifyNoMoreInteractions(queue)
}
}
}
describe("when a stage status was STOPPED but should fail the pipeline at the end") {
val pipeline = pipeline {
stage {
refId = "1a"
status = STOPPED
context["completeOtherBranchesThenFail"] = true
}
stage {
refId = "1b"
requisiteStageRefIds = setOf("1a")
status = NOT_STARTED
}
stage {
refId = "2"
status = SUCCEEDED
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("updates the execution") {
verify(repository).updateStatus(PIPELINE, message.executionId, TERMINAL)
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.status).isEqualTo(TERMINAL)
})
}
it("does not queue any other commands") {
verifyZeroInteractions(queue)
}
}
describe("when a stage status was STOPPED and should not fail the pipeline at the end") {
val pipeline = pipeline {
stage {
refId = "1a"
status = STOPPED
context["completeOtherBranchesThenFail"] = false
}
stage {
refId = "1b"
requisiteStageRefIds = setOf("1a")
status = NOT_STARTED
}
stage {
refId = "2"
status = SUCCEEDED
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("updates the execution") {
verify(repository).updateStatus(PIPELINE, message.executionId, SUCCEEDED)
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.status).isEqualTo(SUCCEEDED)
})
}
it("does not queue any other commands") {
verifyZeroInteractions(queue)
}
}
describe("when a branch is stopped and nothing downstream has started yet") {
val pipeline = pipeline {
stage {
refId = "1a"
status = STOPPED
context["completeOtherBranchesThenFail"] = false
}
stage {
refId = "2a"
status = SUCCEEDED
context["completeOtherBranchesThenFail"] = false
}
stage {
refId = "1b"
requisiteStageRefIds = setOf("1a")
status = NOT_STARTED
}
stage {
refId = "2b"
requisiteStageRefIds = setOf("2a")
status = NOT_STARTED
}
}
val message = CompleteExecution(pipeline)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("does not complete the execution") {
verify(repository, never()).updateStatus(eq(PIPELINE), any(), any())
}
it("publishes no events") {
verifyZeroInteractions(publisher)
}
it("re-queues the message") {
verify(queue).push(message, retryDelay)
}
}
})
| apache-2.0 | 6717edf4f3614c3a28c1899fffa81e07 | 27.497126 | 116 | 0.650297 | 4.675625 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/i18n/inspections/MissingFormatInspection.kt | 1 | 1846 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.inspections
import com.demonwav.mcdev.i18n.translations.Translation
import com.demonwav.mcdev.i18n.translations.Translation.Companion.FormattingError
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiReferenceExpression
class MissingFormatInspection : TranslationInspection() {
override fun getStaticDescription() = "Detects missing format arguments for translations"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitReferenceExpression(expression: PsiReferenceExpression) {
visit(expression)
}
override fun visitLiteralExpression(expression: PsiLiteralExpression) {
visit(expression, ChangeTranslationQuickFix("Use a different translation"))
}
private fun visit(expression: PsiExpression, vararg quickFixes: LocalQuickFix) {
val result = Translation.find(expression)
if (result != null && result.formattingError == FormattingError.MISSING) {
holder.registerProblem(
expression,
"There are missing formatting arguments to satisfy '${result.text}'",
ProblemHighlightType.GENERIC_ERROR,
*quickFixes
)
}
}
}
}
| mit | 2b6ce35b69e8341943973491887aaf0a | 35.92 | 93 | 0.717226 | 5.41349 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/BungeeCordModuleType.kt | 1 | 1499 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bungeecord.generation.BungeeCordEventGenerationPanel
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object BungeeCordModuleType : AbstractModuleType<BungeeCordModule<BungeeCordModuleType>>("net.md-5", "bungeecord-api") {
private const val ID = "BUNGEECORD_MODULE_TYPE"
val IGNORED_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION)
val LISTENER_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION)
init {
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.BUNGEECORD
override val icon = PlatformAssets.BUNGEECORD_ICON
override val id = ID
override val ignoredAnnotations = IGNORED_ANNOTATIONS
override val listenerAnnotations = LISTENER_ANNOTATIONS
override fun generateModule(facet: MinecraftFacet) = BungeeCordModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BungeeCordEventGenerationPanel(chosenClass)
}
| mit | 491de5525dcb5ee8298937bf49120504 | 35.560976 | 120 | 0.801868 | 4.584098 | false | false | false | false |
android/project-replicator | buildSrc/src/main/kotlin/Versions.kt | 1 | 1086 | /*
* Copyright (C) 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.
*
*/
class Versions {
companion object {
val gradleVersion: String
get() =
_gradleVersion ?: throw RuntimeException("Access to gradleVersion without applying a buildSrc plugin")
internal var _gradleVersion: String? = null
const val agpVersion = "4.2.0-alpha13"
const val kotlinVersion = "1.3.72"
const val pluginVersion = "0.2"
const val pluginArtifactId = "project-replicator"
}
} | apache-2.0 | 5832d1834bc465860c597c62b100ea70 | 34.064516 | 118 | 0.686924 | 4.45082 | false | false | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/appearance/AppearanceSettingsViewModel.kt | 2 | 1176 | package org.thoughtcrime.securesms.components.settings.app.appearance
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import org.thoughtcrime.securesms.jobs.EmojiSearchIndexDownloadJob
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.livedata.Store
class AppearanceSettingsViewModel : ViewModel() {
private val store: Store<AppearanceSettingsState>
init {
val initialState = AppearanceSettingsState(
SignalStore.settings().theme,
SignalStore.settings().messageFontSize,
SignalStore.settings().language
)
store = Store(initialState)
}
val state: LiveData<AppearanceSettingsState> = store.stateLiveData
fun setTheme(theme: String) {
store.update { it.copy(theme = theme) }
SignalStore.settings().theme = theme
}
fun setLanguage(language: String) {
store.update { it.copy(language = language) }
SignalStore.settings().language = language
EmojiSearchIndexDownloadJob.scheduleImmediately()
}
fun setMessageFontSize(size: Int) {
store.update { it.copy(messageFontSize = size) }
SignalStore.settings().messageFontSize = size
}
}
| gpl-3.0 | c0783965635ea89087f5ba6bae15bf51 | 29.153846 | 69 | 0.760204 | 4.575875 | false | false | false | false |
tateisu/SubwayTooter | apng/src/main/java/jp/juggler/apng/util/StreamTokenizer.kt | 1 | 1619 | package jp.juggler.apng.util
import jp.juggler.apng.ApngParseError
import java.io.InputStream
import java.util.zip.CRC32
internal class StreamTokenizer(val inStream : InputStream) {
fun skipBytes(size : Long) {
var nRead = 0L
while(true) {
val remain = size - nRead
if(remain <= 0) break
val delta = inStream.skip(size - nRead)
if(delta <= 0) throw ApngParseError("skipBytes: unexpected EoS")
nRead += delta
}
}
fun readBytes(size : Int) : ByteArray {
val dst = ByteArray(size)
var nRead = 0
while(true) {
val remain = size - nRead
if(remain <= 0) break
val delta = inStream.read(dst, nRead, size - nRead)
if(delta < 0) throw ApngParseError("readBytes: unexpected EoS")
nRead += delta
}
return dst
}
private fun readByte() : Int {
val b = inStream.read()
if(b == - 1) throw ApngParseError("readByte: unexpected EoS")
return b and 0xff
}
fun readInt32() : Int {
val b0 = readByte()
val b1 = readByte()
val b2 = readByte()
val b3 = readByte()
return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3
}
fun readInt32(crc32 : CRC32) : Int {
val ba = readBytes(4)
crc32.update(ba)
val b0 = ba[0].toInt() and 255
val b1 = ba[1].toInt() and 255
val b2 = ba[2].toInt() and 255
val b3 = ba[3].toInt() and 255
return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3
}
fun readUInt32() : Long {
val b0 = readByte()
val b1 = readByte()
val b2 = readByte()
val b3 = readByte()
return (b0.toLong() shl 24) or ((b1 shl 16) or (b2 shl 8) or b3).toLong()
}
} | apache-2.0 | 887dcf748e5aae6f84d19020ba9e68cc | 22.560606 | 75 | 0.609636 | 2.573927 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/actions/Approach.kt | 1 | 1648 | package simyukkuri.gameobject.yukkuri.event.action.actions
import simyukkuri.Time
import simyukkuri.gameobject.yukkuri.event.IndividualEvent
import simyukkuri.gameobject.yukkuri.event.action.Action
import simyukkuri.gameobject.yukkuri.event.action.Posture
import simyukkuri.gameobject.yukkuri.event.action.postureByPosition
import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats
import simyukkuri.geometry.HasPosition3
import simyukkuri.geometry.MutableVectorXZ
/** 近づくアクション */
class Approach(val self: YukkuriStats, val dst: HasPosition3) : Action {
override var hasEnded: Boolean = false
override val currentAction: Action = this
override fun execute() {
val maxMovement = self.speed * Time.UNIT
if (self.distance2(dst) <= maxMovement + self.radius) {
val moveVec = MutableVectorXZ(dst.x - self.x, dst.z - self.z)
.normalize()
.multiply(self.distance2(dst) - self.radius)
self.x += moveVec.x
self.z += moveVec.z
hasEnded = true
return
} else {
val moveVec = MutableVectorXZ(dst.x - self.x, dst.z - self.z)
.normalize()
.multiply(maxMovement)
self.x += moveVec.x
self.z += moveVec.z
return
}
}
override fun interrupt() = Unit
override fun isTheSameAs(other: IndividualEvent): Boolean {
if (other !is Move) return false
return dst == other.dst
}
override val posture: Posture
get() = postureByPosition(self, dst)
} | apache-2.0 | d87e96b6adb555bac7797ff9d4f5db1c | 32.765957 | 73 | 0.634804 | 4.173913 | false | false | false | false |
ssseasonnn/RxDownload | rxdownload4/src/main/java/zlc/season/rxdownload4/watcher/WatcherImpl.kt | 1 | 816 | package zlc.season.rxdownload4.watcher
import zlc.season.rxdownload4.task.Task
import zlc.season.rxdownload4.utils.getFile
object WatcherImpl : Watcher {
private val taskMap = mutableMapOf<String, String>()
private val fileMap = mutableMapOf<String, String>()
@Synchronized
override fun watch(task: Task) {
//check task
check(taskMap[task.tag()] == null) { "Task [${task.tag()} is exists!" }
val filePath = task.getFile().canonicalPath
//check file
check(fileMap[filePath] == null) { "File [$filePath] is occupied!" }
taskMap[task.tag()] = task.tag()
fileMap[filePath] = filePath
}
@Synchronized
override fun unwatch(task: Task) {
taskMap.remove(task.tag())
fileMap.remove(task.getFile().canonicalPath)
}
} | apache-2.0 | b0b909910ef33a06fc936150002b7229 | 28.178571 | 79 | 0.647059 | 4.019704 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/features/bookmarks/list/BookMarkHolder.kt | 1 | 1480 | package de.ph1b.audiobook.features.bookmarks.list
import android.view.ViewGroup
import de.ph1b.audiobook.R
import de.ph1b.audiobook.data.Bookmark
import de.ph1b.audiobook.data.Chapter
import de.ph1b.audiobook.misc.formatTime
import de.ph1b.audiobook.uitools.ExtensionsHolder
import kotlinx.android.synthetic.main.bookmark_row_layout.*
/**
* ViewHolder for displaying a Bookmark
*/
class BookMarkHolder(
parent: ViewGroup,
private val listener: BookmarkClickListener
) : ExtensionsHolder(parent, R.layout.bookmark_row_layout) {
var boundBookmark: Bookmark? = null
private set
init {
edit.setOnClickListener { view ->
boundBookmark?.let {
listener.onOptionsMenuClicked(it, view)
}
}
itemView.setOnClickListener {
boundBookmark?.let { bookmark ->
listener.onBookmarkClicked(bookmark)
}
}
}
fun bind(bookmark: Bookmark, chapters: List<Chapter>) {
boundBookmark = bookmark
title.text = bookmark.title
val size = chapters.size
val currentChapter = chapters.single { it.file == bookmark.mediaFile }
val index = chapters.indexOf(currentChapter)
summary.text = itemView.context.getString(
de.ph1b.audiobook.R.string.format_bookmarks_n_of,
index + 1,
size
)
time.text = itemView.context.getString(
de.ph1b.audiobook.R.string.format_bookmarks_time,
formatTime(bookmark.time.toLong()),
formatTime(currentChapter.duration.toLong())
)
}
}
| lgpl-3.0 | 2175da9feef63d835f1521862d693c65 | 26.407407 | 74 | 0.713514 | 3.905013 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/VFUWithTwoPropertiesEntityImpl.kt | 1 | 8835 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class VFUWithTwoPropertiesEntityImpl(val dataSource: VFUWithTwoPropertiesEntityData) : VFUWithTwoPropertiesEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: String
get() = dataSource.data
override val fileProperty: VirtualFileUrl
get() = dataSource.fileProperty
override val secondFileProperty: VirtualFileUrl
get() = dataSource.secondFileProperty
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: VFUWithTwoPropertiesEntityData?) : ModifiableWorkspaceEntityBase<VFUWithTwoPropertiesEntity>(), VFUWithTwoPropertiesEntity.Builder {
constructor() : this(VFUWithTwoPropertiesEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity VFUWithTwoPropertiesEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "fileProperty", this.fileProperty)
index(this, "secondFileProperty", this.secondFileProperty)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field VFUWithTwoPropertiesEntity#data should be initialized")
}
if (!getEntityData().isFilePropertyInitialized()) {
error("Field VFUWithTwoPropertiesEntity#fileProperty should be initialized")
}
if (!getEntityData().isSecondFilePropertyInitialized()) {
error("Field VFUWithTwoPropertiesEntity#secondFileProperty should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as VFUWithTwoPropertiesEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
this.fileProperty = dataSource.fileProperty
this.secondFileProperty = dataSource.secondFileProperty
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var fileProperty: VirtualFileUrl
get() = getEntityData().fileProperty
set(value) {
checkModificationAllowed()
getEntityData().fileProperty = value
changedProperty.add("fileProperty")
val _diff = diff
if (_diff != null) index(this, "fileProperty", value)
}
override var secondFileProperty: VirtualFileUrl
get() = getEntityData().secondFileProperty
set(value) {
checkModificationAllowed()
getEntityData().secondFileProperty = value
changedProperty.add("secondFileProperty")
val _diff = diff
if (_diff != null) index(this, "secondFileProperty", value)
}
override fun getEntityData(): VFUWithTwoPropertiesEntityData = result ?: super.getEntityData() as VFUWithTwoPropertiesEntityData
override fun getEntityClass(): Class<VFUWithTwoPropertiesEntity> = VFUWithTwoPropertiesEntity::class.java
}
}
class VFUWithTwoPropertiesEntityData : WorkspaceEntityData<VFUWithTwoPropertiesEntity>() {
lateinit var data: String
lateinit var fileProperty: VirtualFileUrl
lateinit var secondFileProperty: VirtualFileUrl
fun isDataInitialized(): Boolean = ::data.isInitialized
fun isFilePropertyInitialized(): Boolean = ::fileProperty.isInitialized
fun isSecondFilePropertyInitialized(): Boolean = ::secondFileProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<VFUWithTwoPropertiesEntity> {
val modifiable = VFUWithTwoPropertiesEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): VFUWithTwoPropertiesEntity {
return getCached(snapshot) {
val entity = VFUWithTwoPropertiesEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return VFUWithTwoPropertiesEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return VFUWithTwoPropertiesEntity(data, fileProperty, secondFileProperty, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as VFUWithTwoPropertiesEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
if (this.secondFileProperty != other.secondFileProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as VFUWithTwoPropertiesEntityData
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
if (this.secondFileProperty != other.secondFileProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + secondFileProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + secondFileProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.fileProperty?.let { collector.add(it::class.java) }
this.secondFileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 87fd6bad6f221c0784cce803420efc80 | 34.914634 | 160 | 0.738766 | 5.470588 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/WorldMapManager.kt | 1 | 4584 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.PUTFIELD
import org.objectweb.asm.Type.BOOLEAN_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.UniqueMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.withDimensions
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
@DependsOn(IndexedSprite::class)
class WorldMapManager : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.constructors.isNotEmpty() }
.and { it.constructors.first().arguments.startsWith(listOf(type<IndexedSprite>().withDimensions(1), HashMap::class.type)) }
@DependsOn(IndexedSprite::class)
class mapSceneSprites : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<IndexedSprite>().withDimensions(1) }
}
@DependsOn(WorldMapRegion::class)
class regions : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<WorldMapRegion>().withDimensions(2) }
}
class fonts : OrderMapper.InConstructor.Field(WorldMapManager::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == HashMap::class.type }
}
@MethodParameters()
class buildIcons : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == HashMap::class.type }
}
@MethodParameters()
@DependsOn(buildIcons::class)
class buildIcons0 : UniqueMapper.InMethod.Method(buildIcons::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@DependsOn(buildIcons::class)
class icons : UniqueMapper.InMethod.Field(buildIcons::class) {
override val predicate = predicateOf<Instruction2> { it.isField }
}
class drawOverview : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size == 7 }
}
@MethodParameters("indexCache", "cacheName", "isMembersWorld")
@DependsOn(AbstractArchive::class)
class load : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<AbstractArchive>()) }
}
@MethodParameters()
class clearIcons : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.none { it.isLabel } }
}
@DependsOn(Sprite::class)
class overviewSprite : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<Sprite>() }
}
@DependsOn(WorldMapAreaData::class)
class mapAreaData : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<WorldMapAreaData>() }
}
class isLoaded0 : OrderMapper.InConstructor.Field(WorldMapManager::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters()
class isLoaded : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
}
class loadStarted : OrderMapper.InConstructor.Field(WorldMapManager::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == BOOLEAN_TYPE }
}
// @MethodParameters("x", "y", "dst")
// @DependsOn(WorldMapRegion::class)
// class getNeighboringRegions : IdentityMapper.InstanceMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments == listOf(INT_TYPE, INT_TYPE, type<WorldMapRegion>().withDimensions(1)) }
// }
} | mit | 6e1c6398d70f439eee14797fea041802 | 42.666667 | 135 | 0.712696 | 4.252319 | false | false | false | false |
raybritton/json-query | lib/src/main/kotlin/com/raybritton/jsonquery/parsing/tokens/Operator.kt | 1 | 3591 | package com.raybritton.jsonquery.parsing.tokens
import com.raybritton.jsonquery.ext.compareWith
import com.raybritton.jsonquery.ext.isSameValueAs
import com.raybritton.jsonquery.models.JsonArray
import com.raybritton.jsonquery.models.JsonObject
import com.raybritton.jsonquery.models.Value
/**
* Used to compare two fields/values
*/
internal sealed class Operator(val symbol: String) {
abstract fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean
object Equal : Operator("==") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean) = lhs.isSameValueAs(rhs, caseSensitive)
}
object NotEqual : Operator("!=") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean) = !Equal.op(lhs, rhs, caseSensitive)
}
object Contains : Operator("#") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return when {
(lhs is String && rhs is Value.ValueString) -> lhs.contains(rhs.value, !caseSensitive)
lhs is JsonArray -> lhs.any { it.isSameValueAs(rhs, caseSensitive) }
lhs is JsonObject -> lhs.keys.any { it.isSameValueAs(rhs, caseSensitive) }
else -> false //TODO throw?
}
}
}
object NotContains : Operator("!#") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean) = !Contains.op(lhs, rhs, caseSensitive)
}
object LessThan : Operator("<") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return lhs.compareWith(false, caseSensitive, rhs.value) < 0
}
}
object GreaterThan : Operator(">") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return lhs.compareWith(false, caseSensitive, rhs.value) > 0
}
}
object LessThanOrEqual : Operator("<=") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return lhs.compareWith(false, caseSensitive, rhs.value) < 1
}
}
object GreaterThanOrEqual : Operator(">=") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return lhs.compareWith(false, caseSensitive, rhs.value) > -1
}
}
object TypeEqual : Operator("IS") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return when {
lhs is Number && rhs.value == Keyword.NUMBER -> true
lhs is String && rhs.value == Keyword.STRING -> true
lhs is Boolean && rhs.value == Keyword.BOOLEAN -> true
lhs is JsonObject && rhs.value == Keyword.OBJECT -> true
lhs is JsonArray && rhs.value == Keyword.ARRAY -> true
lhs == null && rhs.value == Keyword.NULL -> true
else -> false
}
}
}
object TypeNotEqual : Operator("IS NOT") {
override fun op(lhs: Any?, rhs: Value<*>, caseSensitive: Boolean): Boolean {
return when {
lhs is Number && rhs.value != Keyword.NUMBER -> true
lhs is String && rhs.value != Keyword.STRING -> true
lhs is Boolean && rhs.value != Keyword.BOOLEAN -> true
lhs is JsonObject && rhs.value != Keyword.OBJECT -> true
lhs is JsonArray && rhs.value != Keyword.ARRAY -> true
lhs == null && rhs.value != Keyword.NULL -> true
else -> false
}
}
}
}
| apache-2.0 | c0314826e3cce552be8dcc1c4d92ccc5 | 38.461538 | 113 | 0.58396 | 4.54557 | false | false | false | false |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/bot/objects/TelegramBotChat.kt | 1 | 4557 | package io.github.ranolp.kubo.telegram.bot.objects
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.salomonbrys.kotson.*
import com.google.gson.JsonObject
import io.github.ranolp.kubo.general.error.CannotDeleteError
import io.github.ranolp.kubo.general.objects.History
import io.github.ranolp.kubo.general.objects.User
import io.github.ranolp.kubo.general.side.Side
import io.github.ranolp.kubo.telegram.Telegram
import io.github.ranolp.kubo.telegram.bot.functions.TelegramFunction
import io.github.ranolp.kubo.telegram.errors.NotOkError
import io.github.ranolp.kubo.telegram.general.MessageParseMode
import io.github.ranolp.kubo.telegram.general.objects.TelegramChat
import io.github.ranolp.kubo.telegram.util.byNullable
import io.github.ranolp.kubo.telegram.util.notNull
class TelegramBotChat(json: JsonObject) : TelegramChat {
internal class sendMessage : TelegramFunction<TelegramBotMessage>("sendMessage") {
companion object {
operator fun invoke(chatId: String, text: String, parseMode: MessageParseMode? = null,
webPreview: Boolean? = null, notify: Boolean? = null, replyTo: Int? = null,
replyMarkup: ReplyMarkup? = null): TelegramBotMessage {
return sendMessage().apply {
this.chatId = chatId
this.text = text
this.parseMode = parseMode
this.webPreview = webPreview
this.notify = notify
this.replyTo = replyTo
this.replyMarkup = replyMarkup
}.request()
}
}
lateinit var chatId: String
lateinit var text: String
var parseMode: MessageParseMode? = null
var webPreview: Boolean? = null
// only available on channel
var notify: Boolean? = null
// reply message id
var replyTo: Int? = null
var replyMarkup: ReplyMarkup? = null
override fun parse(request: Request, response: Response, result: String): TelegramBotMessage {
return workObject(result, ::TelegramBotMessage) ?: throw NotOkError
}
override fun generateArguments(): Map<String, Any?> {
return hashMapOf("chat_id" to chatId, "text" to text).apply {
parseMode.notNull { put("parse_mode", toString()) }
webPreview.notNull { put("disable_web_page_preview", not().toString()) }
notify.notNull { put("disable_notification", not().toString()) }
replyTo.notNull { put("reply_to_message_id", toString()) }
replyMarkup.notNull { put("reply_markup", toString()) }
}
}
}
private object leaveChat : TelegramFunction<TelegramBotChat>("leaveChat") {
private lateinit var chatId: String
operator fun invoke(chat: TelegramBotChat): TelegramBotChat {
chatId = chat.id.toString()
return request()
}
override fun parse(request: Request, response: Response, result: String): TelegramBotChat {
return workObject(result, ::TelegramBotChat) ?: throw NotOkError
}
override fun generateArguments(): Map<String, Any?> {
return mapOf("chat_id" to chatId)
}
}
override val side: Side = Telegram.BOT_SIDE
val id by json.byLong
val type by json.byString
override val title by json.byNullableString
val username by json.byNullableString
val firstName by json.byNullableString("first_name")
val lastName by json.byNullableString("last_name")
val allMembersAreAdmin by json.byBool("all_members_are_administrators", { false })
// It will replace by ChatPhoto
val photo by json.byNullableObject
val description by json.byNullableString
val inviteLink by json.byNullableString("invite_link")
val pinnedMessage by json.byNullable("pinned_message", ::TelegramBotMessage)
override val users: List<User> = emptyList() // Can't get ;(
override fun sendMessage(message: String) {
sendMessage().apply {
chatId = id.toString()
text = message
}.request()
}
override fun history(): History {
TODO("not implemented")
}
override fun leave(): Boolean {
return try {
leaveChat(this)
true
} catch(e: Throwable) {
false
}
}
override fun delete() {
throw CannotDeleteError
}
} | mit | 1de1699065c6b58d7ff056a0b1a00933 | 37.957265 | 102 | 0.643625 | 4.534328 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/LongExt.kt | 1 | 767 | package jp.cordea.mackerelclient
import android.content.Context
fun Long.toRelativeTime(context: Context, current: Long): String {
val currentSec = current / 1000f
var diff = currentSec - this
if (diff <= 59) {
return context.getString(R.string.relative_time_format_seconds, diff.toInt())
}
diff /= 60
if (diff <= 59) {
return context.getString(R.string.relative_time_format_minutes, diff.toInt())
}
diff /= 60
if (diff <= 23) {
return context.getString(R.string.relative_time_format_hours, diff.toInt())
}
diff /= 24
if (diff <= 9) {
return context.getString(R.string.relative_time_format_days, diff.toInt())
}
return context.getString(R.string.relative_time_format_others)
}
| apache-2.0 | 705f6bdccc5081c068cb274249fb9af2 | 30.958333 | 85 | 0.655802 | 3.652381 | false | false | false | false |
xranby/modern-jogl-examples | src/main/kotlin/main/tut05/overlapNoDepth.kt | 1 | 11100 | package main.tut05
import buffer.BufferUtils
import buffer.destroy
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import extensions.floatBufferBig
import extensions.intBufferBig
import extensions.toFloatBuffer
import extensions.toShortBuffer
import glsl.programOf
import main.*
import main.framework.Framework
import main.framework.Semantic
import vec._3.Vec3
import vec._4.Vec4
/**
* Created by GBarbieri on 23.02.2017.
*/
fun main(args: Array<String>) {
OverlapNoDepth_()
}
class OverlapNoDepth_ : Framework("Tutorial 05 - Overlap No Depth") {
object Buffer {
val VERTEX = 0
val INDEX = 1
val MAX = 2
}
object Vao {
val A = 0
val B = 1
val MAX = 2
}
var theProgram = 0
var offsetUniform = 0
var perspectiveMatrixUnif = 0
val numberOfVertices = 36
val perspectiveMatrix = floatBufferBig(16)
val frustumScale = 1.0f
val bufferObject = intBufferBig(Buffer.MAX)
val vao = intBufferBig(Vao.MAX)
val RIGHT_EXTENT = 0.8f
val LEFT_EXTENT = -RIGHT_EXTENT
val TOP_EXTENT = 0.20f
val MIDDLE_EXTENT = 0.0f
val BOTTOM_EXTENT = -TOP_EXTENT
val FRONT_EXTENT = -1.25f
val REAR_EXTENT = -1.75f
val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f)
val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f)
val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f)
val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f)
val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f)
val vertexData = floatArrayOf(
//Object 1 positions
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
//Object 2 positions
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
//Object 1 colors
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
//Object 2 colors
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3],
GREY_COLOR[0], GREY_COLOR[1], GREY_COLOR[2], GREY_COLOR[3])
val indexData = shortArrayOf(
0, 2, 1,
3, 2, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
11, 13, 12,
14, 16, 15,
17, 16, 14)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeBuffers(gl)
initializeVertexArrays(gl)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, this::class.java, "tut05", "standard.vert", "standard.frag")
offsetUniform = glGetUniformLocation(theProgram, "offset")
perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix")
val zNear = 1.0f
val zFar = 3.0f
perspectiveMatrix[0] = frustumScale
perspectiveMatrix[5] = frustumScale
perspectiveMatrix[10]= (zFar + zNear) / (zNear - zFar)
perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar)
perspectiveMatrix[11] = -1.0f
glUseProgram(theProgram)
glUniformMatrix4fv(perspectiveMatrixUnif, 1, false, perspectiveMatrix)
glUseProgram(0)
}
fun initializeBuffers(gl: GL3) = with(gl){
val vertexBuffer = vertexData.toFloatBuffer()
val indexBuffer = indexData.toShortBuffer()
glGenBuffers(Buffer.MAX, bufferObject)
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX])
glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBufferData(GL_ARRAY_BUFFER, indexBuffer.SIZE.L, indexBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
vertexBuffer.destroy()
indexBuffer.destroy()
}
fun initializeVertexArrays(gl: GL3) = with(gl){
glGenVertexArrays(Vao.MAX, vao)
glBindVertexArray(vao.get(Vao.A))
var colorDataOffset = Float.BYTES * 3 * numberOfVertices
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX])
glEnableVertexAttribArray(Semantic.Attr.POSITION)
glEnableVertexAttribArray(Semantic.Attr.COLOR)
glVertexAttribPointer(Semantic.Attr.POSITION, 3, GL_FLOAT, false, Vec3.SIZE, 0)
glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, colorDataOffset.L)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBindVertexArray(vao[Vao.B])
val positionDataOffset = Float.BYTES * 3 * (numberOfVertices / 2)
colorDataOffset += Float.BYTES * 4 * (numberOfVertices / 2)
//Use the same buffer object previously bound to GL_ARRAY_BUFFER.
glEnableVertexAttribArray(Semantic.Attr.POSITION)
glEnableVertexAttribArray(Semantic.Attr.COLOR)
glVertexAttribPointer(Semantic.Attr.POSITION, 3, GL_FLOAT, false, Vec3.SIZE, positionDataOffset.L)
glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, colorDataOffset.L)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBindVertexArray(0)
}
override fun display(gl: GL3) = with(gl){
glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f))
glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1.0f))
glUseProgram(theProgram)
glBindVertexArray(vao[Vao.A])
glUniform3f(offsetUniform, 0.0f, 0.0f, 0.0f)
glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT, 0)
glBindVertexArray(vao[Vao.B])
glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f)
glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT, 0)
glBindVertexArray(0)
glUseProgram(0)
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
perspectiveMatrix[0] = frustumScale * (h / w.f)
perspectiveMatrix[5] = frustumScale
glUseProgram(theProgram)
glUniformMatrix4fv(perspectiveMatrixUnif, 1, false, perspectiveMatrix)
glUseProgram(0)
glViewport(0, 0, w, h)
}
override fun end(gl: GL3) = with(gl){
glDeleteProgram(theProgram)
glDeleteBuffers(Buffer.MAX, bufferObject)
glDeleteVertexArrays(Vao.MAX, vao)
vao.destroy()
bufferObject.destroy()
perspectiveMatrix.destroy()
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> {
animator.remove(window)
window.destroy()
}
}
}
} | mit | 3d0ed11910b4bd1437cdbbf55da02bfe | 34.466454 | 106 | 0.615676 | 3.584114 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/viewmodel/HostListItemViewModel.kt | 1 | 2454 | package jp.cordea.mackerelclient.viewmodel
import android.content.Context
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.TextAppearanceSpan
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.api.response.Tsdb
import jp.cordea.mackerelclient.model.DisplayableHost
class HostListItemViewModel(
private val context: Context,
private val item: DisplayableHost,
private val metric: Map<String, Tsdb>?
) {
val roleText: String
get() = item.numberOfRoles.let {
if (it <= 1) {
context.resources.getString(R.string.format_role).format(it)
} else {
if (it > 99) {
context.resources.getString(R.string.format_roles_ex)
} else {
context.resources.getString(R.string.format_roles).format(it)
}
}
}
val loadavgText: String
get() {
metric?.get(HostViewModel.loadavgMetricsKey)?.let { met ->
return "%.2f".format(met.metricValue)
}
return ""
}
val cpuText: SpannableStringBuilder
get() {
val sp = SpannableStringBuilder()
metric?.get(HostViewModel.cpuMetricsKey)?.let { met ->
sp.append("%.1f %%".format(met.metricValue))
sp.setSpan(
TextAppearanceSpan(context, R.style.HostMetricUnit),
sp.length - 1, sp.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return sp
}
val memoryText: SpannableStringBuilder
get() {
val sp = SpannableStringBuilder()
metric?.get(HostViewModel.memoryMetricsKey)?.let { met ->
var unit = "MB"
var mem = (met.metricValue ?: 0.0f) / 1024.0f / 1024.0f
if (mem > 999) {
unit = "GB"
mem /= 1024.0f
}
if (mem > 999) {
sp.append("999+ %s".format(unit))
} else {
sp.append("%.0f %s".format(mem, unit))
}
sp.setSpan(
TextAppearanceSpan(context, R.style.HostMetricUnit),
sp.length - 2, sp.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return sp
}
}
| apache-2.0 | 573f2045f1be502812624c7c24b5bf3c | 33.083333 | 81 | 0.526487 | 4.612782 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/refactoring/suggested/SignatureChangePresentation.kt | 1 | 20463 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.suggested
import com.intellij.ide.ui.AntialiasingType
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.diff.DiffColors
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.refactoring.suggested.SignatureChangePresentationModel.Effect
import com.intellij.refactoring.suggested.SignatureChangePresentationModel.TextFragment
import com.intellij.ui.JBColor
import java.awt.*
import java.awt.font.FontRenderContext
import java.awt.geom.AffineTransform
import java.awt.geom.Arc2D
import java.awt.geom.GeneralPath
import java.awt.geom.Point2D
import kotlin.math.*
class SignatureChangePresentation(
private val model: SignatureChangePresentationModel,
private val font: Font,
colorsScheme: EditorColorsScheme,
private val verticalMode: Boolean
) {
private val defaultForegroundColor = JBColor.namedColor("Label.foreground", Color.black)
private val modifiedAttributes = colorsScheme.getAttributes(DiffColors.DIFF_MODIFIED)
private val addedAttributes = colorsScheme.getAttributes(DiffColors.DIFF_INSERTED)
private val crossStroke = BasicStroke(1f)
private val connectionStroke = BasicStroke(connectionLineThickness.toFloat())
private val connectionColor = modifiedAttributes.backgroundColor ?: defaultForegroundColor
private val dummyFontRenderContext = FontRenderContext(
AffineTransform(),
AntialiasingType.getKeyForCurrentScope(false),
if (UISettings.FORCE_USE_FRACTIONAL_METRICS) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF
)
val requiredSize by lazy {
val oldSignatureSize = signatureDimensions(model.oldSignature, dummyFontRenderContext)
val newSignatureSize = signatureDimensions(model.newSignature, dummyFontRenderContext)
if (verticalMode) {
Dimension(
oldSignatureSize.width + newSignatureSize.width + betweenSignaturesHSpace + leftSpace + rightSpace,
max(oldSignatureSize.height, newSignatureSize.height) + topSpace + bottomSpace
)
}
else {
val size = Dimension(
max(oldSignatureSize.width, newSignatureSize.width) + leftSpace + rightSpace,
oldSignatureSize.height + newSignatureSize.height + betweenSignaturesVSpace + topSpace + bottomSpace
)
if (model.oldSignature.any { it.connectionId != null }) {
val router = renderAll(null, dummyFontRenderContext, Rectangle(Point(), size)) as HorizontalModeConnectionRouter
if (router.hSegmentLevelsRequired > 0) {
size.height += betweenSignaturesVSpaceWithOneHSegment - betweenSignaturesVSpace +
betweenHSegmentsVSpace * (router.hSegmentLevelsRequired - 1)
}
}
size
}
}
private fun signatureDimensions(fragments: List<TextFragment>, context: FontRenderContext): Dimension {
if (verticalMode) {
var maxWidth = 0
var currentLineWidth = 0
var lines = 1
fragments.forAllFragments { fragment ->
when (fragment) {
is TextFragment.Group -> { } // children processed by forAllFragments()
is TextFragment.Leaf -> {
currentLineWidth += font.getStringBounds(fragment.text, context).width.ceilToInt()
}
is TextFragment.LineBreak -> {
maxWidth = max(maxWidth, currentLineWidth)
currentLineWidth = 0
if (fragment.indentAfter) {
currentLineWidth += (font.getStringBounds(" ", context).width * indentInVerticalMode).roundToInt()
}
lines++
}
}
}
return Dimension(maxWidth, lines * lineHeight(context))
}
else {
var width = 0
fragments.forAllFragments { fragment ->
when (fragment) {
is TextFragment.Group -> { } // children processed by forAllFragments()
is TextFragment.Leaf -> width += font.getStringBounds(fragment.text, context).width.ceilToInt()
is TextFragment.LineBreak -> width += font.getStringBounds(fragment.spaceInHorizontalMode, context).width.ceilToInt()
}
}
return Dimension(width, lineHeight(context))
}
}
fun paint(g: Graphics2D, bounds: Rectangle) {
renderAll(g, g.fontRenderContext, bounds)
}
private fun renderAll(g: Graphics2D?, fontRenderContext: FontRenderContext, bounds: Rectangle): ConnectionRouter {
if (g != null) {
UISettings.setupAntialiasing(g)
}
val lineHeight = lineHeight(fontRenderContext)
val oldSignatureSize = signatureDimensions(model.oldSignature, fontRenderContext)
val newSignatureSize = signatureDimensions(model.newSignature, fontRenderContext)
val oldSignatureTop: Int
val newSignatureTop: Int
val oldSignatureLeft: Int
val newSignatureLeft: Int
if (verticalMode) {
oldSignatureTop = bounds.y + topSpace
newSignatureTop = oldSignatureTop
oldSignatureLeft = bounds.left + leftSpace
newSignatureLeft = bounds.right - newSignatureSize.width
}
else {
oldSignatureTop = bounds.y + topSpace
newSignatureTop = bounds.y + bounds.height - lineHeight - bottomSpace
val width = max(oldSignatureSize.width, newSignatureSize.width)
val left = bounds.x + (bounds.width - width) / 2 + leftSpace
oldSignatureLeft = left
newSignatureLeft = left
}
val oldFragmentBounds = SignatureRenderer(g, fontRenderContext, oldSignatureLeft, oldSignatureTop).render(model.oldSignature)
val newFragmentBounds = SignatureRenderer(g, fontRenderContext, newSignatureLeft, newSignatureTop).render(model.newSignature)
val newFragmentBoundsById = mutableMapOf<Any, Rectangle>()
for ((fragment, fragmentBounds) in newFragmentBounds.entries) {
fragment.connectionId?.let {
newFragmentBoundsById[it] = fragmentBounds
}
}
val connectedBounds = mutableListOf<Pair<Rectangle, Rectangle>>()
for ((oldFragment, oldBounds) in oldFragmentBounds.entries) {
oldFragment.connectionId?.let {
val newBounds = newFragmentBoundsById[it]!!
connectedBounds.add(oldBounds to newBounds)
}
}
g?.stroke = connectionStroke
g?.color = connectionColor
val connectionRouter = if (verticalMode)
VerticalModeConnectionRouter(g, newSignatureLeft, oldSignatureLeft + oldSignatureSize.width)
else
HorizontalModeConnectionRouter(g, oldSignatureTop + lineHeight, newSignatureTop)
connectionRouter.drawConnections(connectedBounds)
return connectionRouter
}
private inner class SignatureRenderer(
private val g: Graphics2D?,
private val fontRenderContext: FontRenderContext,
private val left: Int,
private val top: Int
) {
private val lineHeight = lineHeight(fontRenderContext)
private var currentX = left
private var currentY = top
private val fragmentBounds = mutableMapOf<TextFragment, Rectangle>()
fun render(fragments: List<TextFragment>): Map<TextFragment, Rectangle> {
currentX = left
currentY = top
drawFragments(fragments, Effect.None, null)
return fragmentBounds
}
private fun drawFragments(fragments: List<TextFragment>, inheritedEffect: Effect, inheritedFontStyle: Int?) {
for (fragment in fragments) {
val fragmentStartX = currentX
val fragmentStartY = currentY
val effect = inheritedEffect.takeIf { it != Effect.None } ?: fragment.effect
val fontStyle = inheritedFontStyle ?: when (fragment.effect) {
Effect.Modified -> Font.BOLD
Effect.Added, Effect.Removed -> if (inheritedEffect != Effect.None) Font.BOLD else null
else -> null
}
when (fragment) {
is TextFragment.Leaf -> {
val font = if (fontStyle != null) font.deriveFont(fontStyle) else font
currentX = drawText(fragment.text, currentX, currentY, effect, font)
}
is TextFragment.LineBreak -> {
if (verticalMode) {
currentY += lineHeight
currentX = left
if (fragment.indentAfter) {
currentX += (font.getStringBounds(" ", fontRenderContext).width * indentInVerticalMode).roundToInt()
}
}
else {
currentX = drawText(fragment.spaceInHorizontalMode, currentX, currentY, effect, font)
}
}
is TextFragment.Group -> {
drawFragments(fragment.children, effect, fontStyle)
}
}
fragmentBounds[fragment] = Rectangle(
fragmentStartX - backgroundGap,
fragmentStartY - backgroundGap,
currentX - fragmentStartX + backgroundGap * 2,
currentY - fragmentStartY + lineHeight + backgroundGap * 2
)
}
}
private fun drawText(
text: String,
x: Int,
y: Int,
effect: Effect,
font: Font
): Int {
val backgroundColor = backgroundColor(effect)
val foregroundColor = foregroundColor(effect) ?: defaultForegroundColor
val metrics = font.getLineMetrics(text, fontRenderContext)
val newX = x + font.getStringBounds(text, fontRenderContext).width.ceilToInt()
if (g != null) {
if (backgroundColor != null) {
g.color = backgroundColor
g.fillRect(x - backgroundGap, y - backgroundGap, newX - x + backgroundGap * 2, lineHeight + backgroundGap * 2)
}
g.color = foregroundColor
g.font = font
g.drawString(text, x.toFloat(), y.toFloat() + metrics.ascent)
if (effect == Effect.Removed) {
g.stroke = crossStroke
g.color = foregroundColor
val lineY = y + lineHeight / 2
g.drawLine(x, lineY, newX, lineY)
}
}
return newX
}
private fun backgroundColor(effect: Effect): Color? {
return when (effect) {
Effect.Modified, Effect.Moved -> modifiedAttributes.backgroundColor
Effect.Added -> addedAttributes.backgroundColor
else -> null
}
}
private fun foregroundColor(effect: Effect): Color? {
return when (effect) {
Effect.Modified, Effect.Moved -> modifiedAttributes.foregroundColor
Effect.Added -> addedAttributes.foregroundColor
else -> null
}
}
}
private interface ConnectionRouter {
fun drawConnections(connectedBounds: List<Pair<Rectangle, Rectangle>>)
}
private class HorizontalModeConnectionRouter(
private val g: Graphics2D?,
private val oldSignatureBottom: Int,
private val newSignatureTop: Int
) : ConnectionRouter {
private val connectionsByHSegmentLevel = mutableListOf<MutableList<ConnectionData>>()
val hSegmentLevelsRequired: Int
get() = connectionsByHSegmentLevel.size
override fun drawConnections(connectedBounds: List<Pair<Rectangle, Rectangle>>) {
val connections = prepareConnectionData(connectedBounds)
val connectors = mutableListOf<VerticalConnectorData>()
for (connection in connections) {
if (connection.oldX == connection.newX) {
connectors.add(VerticalConnectorData(connection.oldX, oldSignatureBottom, newSignatureTop))
drawVerticalConnection(connection.oldX)
}
else {
val level = connectionsByHSegmentLevel.firstOrNull { connectionsInLevel ->
connectionsInLevel.none { it.overlapsHorizontally(connection) }
}
if (level != null) {
level += connection
}
else {
connectionsByHSegmentLevel += mutableListOf(connection)
}
}
}
if (connectionsByHSegmentLevel.isEmpty()) return
val firstLevelY = oldSignatureBottom +
(newSignatureTop - oldSignatureBottom - (connectionsByHSegmentLevel.size - 1) * betweenHSegmentsVSpace) / 2
fun levelY(level: Int) = firstLevelY + level * betweenHSegmentsVSpace
for ((level, connectionsInLevel) in connectionsByHSegmentLevel.withIndex()) {
for ((oldX, newX) in connectionsInLevel) {
val levelY = levelY(level)
connectors.add(VerticalConnectorData(oldX, oldSignatureBottom, levelY))
connectors.add(VerticalConnectorData(newX, levelY, newSignatureTop))
}
}
for ((level, connectionsInLevel) in connectionsByHSegmentLevel.withIndex()) {
for ((oldX, newX) in connectionsInLevel) {
drawConnection(oldX, newX, levelY(level), connectors)
}
}
}
private fun prepareConnectionData(connectedBounds: List<Pair<Rectangle, Rectangle>>): List<ConnectionData> {
val occupiedConnectorX = mutableListOf<Int>()
fun chooseConnectorX(x: Int, step: Int): Int {
if (occupiedConnectorX.none { abs(it - x) < betweenConnectorsHSpace }) {
occupiedConnectorX.add(x)
return x
}
return chooseConnectorX(x + step, step)
}
val data = mutableListOf<ConnectionData>()
for ((oldBounds, newBounds) in connectedBounds) {
var oldX: Int
var newX: Int
val oldXStep: Int
val newXStep: Int
when {
oldBounds.right <= newBounds.left -> {
oldX = oldBounds.right - connectionLineThickness / 2
newX = newBounds.left + connectionLineThickness / 2
oldXStep = -betweenConnectorsHSpace
newXStep = +betweenConnectorsHSpace
}
oldBounds.left >= newBounds.right -> {
oldX = oldBounds.left + connectionLineThickness / 2
newX = newBounds.right - connectionLineThickness / 2
oldXStep = +betweenConnectorsHSpace
newXStep = -betweenConnectorsHSpace
}
else -> {
val left = max(oldBounds.left, newBounds.left)
val right = min(oldBounds.right, newBounds.right)
oldX = (left + right) / 2
newX = oldX
oldXStep = 0
newXStep = 0
}
}
if (oldX != newX) {
if (abs(oldX - newX) < minHSegmentLength) {
oldX = oldBounds.centerX.roundToInt()
newX = newBounds.centerX.roundToInt()
}
oldX = chooseConnectorX(oldX, oldXStep)
newX = chooseConnectorX(newX, newXStep)
}
data += ConnectionData(oldX, newX)
}
return data
}
private fun drawConnection(oldX: Int, newX: Int, levelY: Int, connectors: List<VerticalConnectorData>) {
val oldXD = oldX.toDouble()
val newXD = newX.toDouble()
val levelYD = levelY.toDouble()
val d = rectangularConnectionArcR * 2
g?.draw(GeneralPath().apply {
moveTo(oldXD, oldSignatureBottom.toDouble())
lineTo(oldXD, levelYD - d / 2)
if (oldXD < newXD) {
append(Arc2D.Double(oldXD, levelYD - d, d, d, 180.0, 90.0, Arc2D.OPEN), false)
moveTo(oldXD + d / 2, levelYD)
horizontalSegmentWithInterruptions(levelYD, oldXD + d / 2, newXD - d / 2, connectors)
append(Arc2D.Double(newXD - d, levelYD, d, d, 0.0, 90.0, Arc2D.OPEN), false)
}
else {
append(Arc2D.Double(oldXD - d, levelYD - d, d, d, 270.0, 90.0, Arc2D.OPEN), false)
moveTo(oldXD - d / 2, levelYD)
horizontalSegmentWithInterruptions(levelYD, newXD + d / 2, oldXD - d / 2, connectors)
append(Arc2D.Double(newXD, levelYD, d, d, 90.0, 90.0, Arc2D.OPEN), false)
}
moveTo(newXD, levelYD + d / 2)
lineTo(newXD, newSignatureTop.toDouble())
})
}
private fun drawVerticalConnection(x: Int) {
g?.draw(GeneralPath().apply {
moveTo(x.toDouble(), oldSignatureBottom.toDouble())
lineTo(x.toDouble(), newSignatureTop.toDouble())
})
}
private fun GeneralPath.horizontalSegmentWithInterruptions(
y: Double,
minX: Double,
maxX: Double,
connectors: List<VerticalConnectorData>
) {
if (minX >= maxX) return
val interruptions = connectors
.filter { minX < it.x && it.x < maxX && it.minY < y && y < it.maxY }
.map { it.x }
.sorted()
var x = minX
moveTo(x, y)
for (interruption in interruptions) {
lineTo((interruption - hLineInterruptionGap - connectionLineThickness).toDouble(), y)
x = (interruption + hLineInterruptionGap + connectionLineThickness).toDouble()
moveTo(x, y)
}
lineTo(maxX, y)
}
private data class ConnectionData(val oldX: Int, val newX: Int)
private val ConnectionData.minX get() = min(oldX, newX)
private val ConnectionData.maxX get() = max(oldX, newX)
private fun ConnectionData.overlapsHorizontally(other: ConnectionData): Boolean {
if (minX > other.maxX) return false
if (maxX < other.minX) return false
return true
}
private data class VerticalConnectorData(val x: Int, val minY: Int, val maxY: Int)
}
private class VerticalModeConnectionRouter(
private val g: Graphics2D?,
private val newSignatureLeft: Int,
private val oldSignatureRight: Int
) : ConnectionRouter {
override fun drawConnections(connectedBounds: List<Pair<Rectangle, Rectangle>>) {
for ((oldBounds, newBounds) in connectedBounds) {
drawConnection(oldBounds, newBounds)
}
}
private fun drawConnection(oldBounds: Rectangle, newBounds: Rectangle) {
val oldY = oldBounds.top + oldBounds.height.toDouble() / 2
val newY = newBounds.top + newBounds.height.toDouble() / 2
val p1 = Point2D.Double((oldSignatureRight + betweenSignaturesConnectionStraightPart).toDouble(), oldY)
val p2 = Point2D.Double((newSignatureLeft - betweenSignaturesConnectionStraightPart).toDouble(), newY)
val angle = atan((p1.y - p2.y) / (p2.x - p1.x))
val angleInDegrees = angle * 180 / PI
val radius = verticalModeArcW / sin(angle.absoluteValue / 2)
g?.draw(GeneralPath().apply {
moveTo(oldBounds.right.toDouble(), oldY)
if (angle >= 0) {
connectedArc(p1.x - verticalModeArcW, p1.y - radius, 270.0, angleInDegrees, radius)
connectedArc(p2.x + verticalModeArcW, p2.y + radius, 90.0 + angleInDegrees, -angleInDegrees, radius)
}
else {
connectedArc(p1.x - verticalModeArcW, p1.y + radius, 90.0, angleInDegrees, radius)
connectedArc(p2.x + verticalModeArcW, p2.y - radius, 270.0 + angleInDegrees, -angleInDegrees, radius)
}
lineTo(newBounds.left.toDouble(), newY)
})
}
private fun GeneralPath.connectedArc(centerX: Double, centerY: Double, start: Double, extentWithSign: Double, radius: Double) {
val arc = Arc2D.Double(
centerX - radius,
centerY - radius,
radius * 2,
radius * 2,
if (extentWithSign > 0) start else start + extentWithSign,
extentWithSign.absoluteValue,
Arc2D.OPEN
)
val startPoint = if (extentWithSign > 0) arc.startPoint else arc.endPoint
val endPoint = if (extentWithSign > 0) arc.endPoint else arc.startPoint
lineTo(startPoint.x, startPoint.y)
append(arc, false)
moveTo(endPoint.x, endPoint.y)
}
}
private fun lineHeight(context: FontRenderContext): Int {
return font.getMaxCharBounds(context).height.ceilToInt()
}
private companion object Constants {
const val indentInVerticalMode = 4
// horizontal mode
const val betweenSignaturesVSpace = 10
const val betweenSignaturesVSpaceWithOneHSegment = 16
const val betweenHSegmentsVSpace = 6
const val betweenConnectorsHSpace = 10
const val rectangularConnectionArcR = 4.0
const val hLineInterruptionGap = 1
const val minHSegmentLength = 25
// vertical mode
const val betweenSignaturesHSpace = 50
const val betweenSignaturesConnectionStraightPart = 10
const val verticalModeArcW = 4.0
// both modes
const val topSpace = 14
const val bottomSpace = 18
const val leftSpace = 0
const val rightSpace = 6
const val connectionLineThickness = 2
const val backgroundGap = 1
}
}
private inline val Rectangle.left: Int
get() = x
private inline val Rectangle.top: Int
get() = y
private val Rectangle.right: Int
get() = x + width
private fun Double.ceilToInt(): Int = ceil(this).toInt()
| apache-2.0 | b08c28b2d34c494688f664e88805445a | 35.541071 | 140 | 0.66305 | 4.414887 | false | false | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/database/AndroidMigrationFileHelper.kt | 1 | 1795 | package com.dbflow5.database
import android.content.Context
import com.dbflow5.config.FlowLog
import java.io.IOException
import java.io.InputStream
/**
* Description: Implements [MigrationFileHelper] for Android targets.
*/
class AndroidMigrationFileHelper(private val context: Context) : MigrationFileHelper {
override fun getListFiles(dbMigrationPath: String): List<String> =
context.assets.list(dbMigrationPath)?.toList() ?: listOf()
override fun executeMigration(fileName: String, dbFunction: (queryString: String) -> Unit) {
try {
val input: InputStream = context.assets.open(fileName)
// ends line with SQL
val querySuffix = ";"
// standard java comments
val queryCommentPrefix = "--"
var query = StringBuffer()
input.reader().buffered().forEachLine { fileLine ->
var line = fileLine.trim { it <= ' ' }
val isEndOfQuery = line.endsWith(querySuffix)
if (line.startsWith(queryCommentPrefix)) {
return@forEachLine
}
if (isEndOfQuery) {
line = line.substring(0, line.length - querySuffix.length)
}
query.append(" ").append(line)
if (isEndOfQuery) {
dbFunction(query.toString())
query = StringBuffer()
}
}
val queryString = query.toString()
if (queryString.trim { it <= ' ' }.isNotEmpty()) {
dbFunction(queryString)
}
} catch (e: IOException) {
FlowLog.log(FlowLog.Level.E, "Failed to execute $fileName. App might be in an inconsistent state!", e)
}
}
} | mit | ba7b25b26ab39fc3a9b1d19d7cafafed | 34.92 | 114 | 0.567688 | 4.891008 | false | false | false | false |
zdary/intellij-community | platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/legacyBridge/watcher/FileContainerDescription.kt | 2 | 4960 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.watcher
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.util.ArrayUtilRt.EMPTY_STRING_ARRAY
import com.intellij.util.containers.ConcurrentList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.toArray
import com.intellij.util.io.URLUtil
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
class FileContainerDescription(val urls: List<VirtualFileUrl>, val jarDirectories: List<JarDirectoryDescription>) {
private val virtualFilePointersList: ConcurrentList<VirtualFilePointer> = ContainerUtil.createConcurrentList()
private val virtualFilePointerManager = VirtualFilePointerManager.getInstance()
@Volatile
private var timestampOfCachedFiles = -1L
@Volatile
private var cachedFilesList = arrayOf<VirtualFile>()
@Volatile
private var cachedUrlsList: Array<String>? = null
init {
urls.forEach { virtualFilePointersList.addIfAbsent(it as VirtualFilePointer) }
jarDirectories.forEach { virtualFilePointersList.addIfAbsent(it.directoryUrl as VirtualFilePointer) }
}
fun isJarDirectory(url: String): Boolean = jarDirectories.any { it.directoryUrl.url == url }
fun findByUrl(url: String): VirtualFilePointer? = virtualFilePointersList.find { it.url == url }
fun getList(): List<VirtualFilePointer> = Collections.unmodifiableList(virtualFilePointersList)
fun getUrls(): Array<String> {
if (cachedUrlsList == null) {
cachedUrlsList = virtualFilePointersList.map { it.url }.toArray(EMPTY_STRING_ARRAY)
}
return cachedUrlsList!!
}
fun getFiles(): Array<VirtualFile> {
val timestamp = timestampOfCachedFiles
val cachedResults = cachedFilesList
return if (timestamp == virtualFilePointerManager.modificationCount) cachedResults else cacheVirtualFilePointersData()
}
private fun cacheVirtualFilePointersData(): Array<VirtualFile> {
val cachedFiles: MutableList<VirtualFile> = ArrayList(virtualFilePointersList.size)
val cachedDirectories: MutableList<VirtualFile> = ArrayList(virtualFilePointersList.size / 3)
var allFilesAreDirs = true
for (pointer in virtualFilePointersList) {
if (!pointer.isValid) continue
val file = pointer.file
if (file != null) {
cachedFiles.add(file)
if (file.isDirectory) {
cachedDirectories.add(file)
}
else {
allFilesAreDirs = false
}
}
}
for (jarDirectory in jarDirectories) {
val virtualFilePointer = jarDirectory.directoryUrl as VirtualFilePointer
if (!virtualFilePointer.isValid) continue
val directoryFile = virtualFilePointer.file
if (directoryFile != null) {
cachedDirectories.remove(directoryFile)
if (jarDirectory.recursive) {
VfsUtilCore.visitChildrenRecursively(directoryFile, object : VirtualFileVisitor<Void?>() {
override fun visitFile(file: VirtualFile): Boolean {
if (!file.isDirectory && FileTypeRegistry.getInstance().getFileTypeByFileName(
file.nameSequence) === ArchiveFileType.INSTANCE) {
val jarRoot = StandardFileSystems.jar().findFileByPath(file.path + URLUtil.JAR_SEPARATOR)
if (jarRoot != null) {
cachedFiles.add(jarRoot)
cachedDirectories.add(jarRoot)
return false
}
}
return true
}
})
} else {
if (!directoryFile.isValid) continue
val children = directoryFile.children
for (file in children) {
if (!file.isDirectory && FileTypeRegistry.getInstance().getFileTypeByFileName(file.nameSequence) === ArchiveFileType.INSTANCE) {
val jarRoot = StandardFileSystems.jar().findFileByPath(file.path + URLUtil.JAR_SEPARATOR)
if (jarRoot != null) {
cachedFiles.add(jarRoot)
cachedDirectories.add(jarRoot)
}
}
}
}
}
}
val files = if (allFilesAreDirs) VfsUtilCore.toVirtualFileArray(cachedDirectories) else VfsUtilCore.toVirtualFileArray(cachedFiles)
cachedFilesList = files
timestampOfCachedFiles = virtualFilePointerManager.modificationCount
return files
}
}
data class JarDirectoryDescription(val directoryUrl: VirtualFileUrl, val recursive: Boolean) | apache-2.0 | 7a1740a415a14f29218cc1bc59c69e47 | 43.294643 | 140 | 0.71875 | 4.930417 | false | false | false | false |
prangbi/LottoPop-Android | LottoPop/app/src/main/java/com/prangbi/android/lottopop/helper/database/PLottoDB.kt | 1 | 4320 | package com.prangbi.android.lottopop.helper.database
import android.content.ContentValues
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
/**
* Created by Prangbi on 2017. 8. 19..
* 연금복권520 DB
*/
interface IPLottoDB {
fun insertWinResult(round: Int, jsonString: String): Long
fun insertMyLotto(round: Int, jsonString: String): Long
fun selectWinResults(round: Int, count: Int): List<Map<String, Any>>
fun selectLatestWinResult(): Map<String, Any>?
fun selectMyLottos(round: Int, count: Int): List<Map<String, Any>>
fun deleteMyLotto(round: Int): Int
}
class PLottoDB constructor(val readableDB: SQLiteDatabase, val writableDB: SQLiteDatabase): IPLottoDB {
companion object {
val TABLE_PLOTTO = "pLotto"
val TABLE_MY_PLOTTO = "myPLotto"
}
override fun insertWinResult(round: Int, jsonString: String): Long {
var count = 0L
val contentValues = ContentValues()
contentValues.put("round", round)
contentValues.put("jsonString", jsonString)
try {
count = writableDB.insertOrThrow(TABLE_PLOTTO, null, contentValues)
} catch (e: SQLException) {
}
return count
}
override fun insertMyLotto(round: Int, jsonString: String): Long {
var count = 0L
val contentValues = ContentValues()
contentValues.put("round", round)
contentValues.put("jsonString", jsonString)
try {
count = writableDB.insertOrThrow(TABLE_MY_PLOTTO, null, contentValues)
} catch (e: SQLException) {
}
return count
}
override fun selectWinResults(round: Int, count: Int): List<Map<String, Any>> {
val list = mutableListOf<Map<String, Any>>()
val last = round
var first = last - if (0 < count - 1) count - 1 else 0
if (0 > first) {
first = 0
}
val query = "SELECT * FROM " + TABLE_PLOTTO +
" WHERE round BETWEEN " + first + " AND " + last +
" ORDER BY round DESC;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val resRound = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("round", resRound)
map.put("jsonString", resJsonString)
list.add(map)
} while (result.moveToNext())
}
result.close()
return list
}
override fun selectLatestWinResult(): Map<String, Any>? {
var winResultMap: Map<String, Any>? = null
val query = "SELECT * FROM " + TABLE_PLOTTO +
" ORDER BY round DESC LIMIT 1;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
val resRound = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("round", resRound)
map.put("jsonString", resJsonString)
winResultMap = map
}
result.close()
return winResultMap
}
override fun selectMyLottos(round: Int, count: Int): List<Map<String, Any>> {
val list = mutableListOf<Map<String, Any>>()
val last = round
var first = last - if (0 < count - 1) count - 1 else 0
if (0 > first) {
first = 0
}
val query = "SELECT * FROM " + TABLE_PLOTTO +
" WHERE round BETWEEN " + first + " AND " + last +
" ORDER BY round DESC;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val resRound = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("round", resRound)
map.put("jsonString", resJsonString)
list.add(map)
} while (result.moveToNext())
}
result.close()
return list
}
override fun deleteMyLotto(round: Int): Int {
val count = writableDB.delete(TABLE_MY_PLOTTO, "round=" + round, null)
return count
}
}
| mit | 5670294434027149e1883d312fb28320 | 31.179104 | 103 | 0.572124 | 4.146154 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reified/arraysReification/instanceOfArrays.kt | 1 | 1237 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
inline fun <reified T> foo(x: Any?) = Pair(x is T, x is T?)
inline fun <reified F> bar(y: Any?) = foo<Array<F>>(y)
inline fun <reified F> barNullable(y: Any?) = foo<Array<F>?>(y)
fun box(): String {
val x1 = bar<String>(arrayOf(""))
if (x1.toString() != "(true, true)") return "fail 1"
val x3 = bar<String>(null)
if (x3.toString() != "(false, true)") return "fail 3"
val x4 = bar<String?>(null)
if (x4.toString() != "(false, true)") return "fail 4"
val x5 = bar<Double?>(arrayOf(""))
if (x5.toString() != "(false, false)") return "fail 5"
val x6 = bar<Double?>(null)
if (x6.toString() != "(false, true)") return "fail 6"
// barNullable
val x7 = barNullable<String>(arrayOf(""))
if (x7.toString() != "(true, true)") return "fail 7"
val x9 = barNullable<String>(null)
if (x9.toString() != "(true, true)") return "fail 9"
val x10 = barNullable<Double?>(arrayOf(""))
if (x10.toString() != "(false, false)") return "fail 11"
val x12 = barNullable<Double?>(null)
if (x12.toString() != "(true, true)") return "fail 12"
return "OK"
}
| apache-2.0 | 50dfe943d0c8992574c84b9338594420 | 29.925 | 72 | 0.589329 | 3.147583 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/MoveDeclarationsOutHelper.kt | 5 | 6528 | // 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.codeInsight.surroundWith
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
fun move(container: PsiElement, statements: Array<PsiElement>, generateDefaultInitializers: Boolean): Array<PsiElement> {
if (statements.isEmpty()) {
return statements
}
val project = container.project
val resultStatements = ArrayList<PsiElement>()
val propertiesDeclarations = ArrayList<KtProperty>()
// Dummy element to add new declarations at the beginning
val psiFactory = KtPsiFactory(project)
val dummyFirstStatement = container.addBefore(psiFactory.createExpression("dummyStatement"), statements[0])
try {
val scope = LocalSearchScope(container)
val lastStatementOffset = statements[statements.size - 1].textRange.endOffset
statements.forEachIndexed { i, statement ->
if (needToDeclareOut(statement, lastStatementOffset, scope)) {
val property = statement as? KtProperty
if (property?.initializer != null) {
if (i == statements.size - 1) {
kotlinStyleDeclareOut(container, dummyFirstStatement, resultStatements, propertiesDeclarations, property)
} else {
declareOut(
container,
dummyFirstStatement,
generateDefaultInitializers,
resultStatements,
propertiesDeclarations,
property
)
}
} else {
val newStatement = container.addBefore(statement, dummyFirstStatement)
container.addAfter(psiFactory.createNewLine(), newStatement)
container.deleteChildRange(statement, statement)
}
} else {
resultStatements.add(statement)
}
}
} finally {
dummyFirstStatement.delete()
}
ShortenReferences.DEFAULT.process(propertiesDeclarations)
return PsiUtilCore.toPsiElementArray(resultStatements)
}
private fun kotlinStyleDeclareOut(
container: PsiElement,
dummyFirstStatement: PsiElement,
resultStatements: ArrayList<PsiElement>,
propertiesDeclarations: ArrayList<KtProperty>,
property: KtProperty
) {
val name = property.name ?: return
var declaration = KtPsiFactory(property).createProperty(name, property.typeReference?.text, property.isVar, null)
declaration = container.addBefore(declaration, dummyFirstStatement) as KtProperty
container.addAfter(KtPsiFactory(declaration).createEQ(), declaration)
propertiesDeclarations.add(declaration)
property.initializer?.let {
resultStatements.add(property.replace(it))
}
}
private fun declareOut(
container: PsiElement,
dummyFirstStatement: PsiElement,
generateDefaultInitializers: Boolean,
resultStatements: ArrayList<PsiElement>,
propertiesDeclarations: ArrayList<KtProperty>,
property: KtProperty
) {
var declaration = createVariableDeclaration(property, generateDefaultInitializers)
declaration = container.addBefore(declaration, dummyFirstStatement) as KtProperty
propertiesDeclarations.add(declaration)
val assignment = createVariableAssignment(property)
resultStatements.add(property.replace(assignment))
}
private fun createVariableAssignment(property: KtProperty): KtBinaryExpression {
val propertyName = property.name ?: error("Property should have a name " + property.text)
val assignment = KtPsiFactory(property).createExpression("$propertyName = x") as KtBinaryExpression
val right = assignment.right ?: error("Created binary expression should have a right part " + assignment.text)
val initializer = property.initializer ?: error("Initializer should exist for property " + property.text)
right.replace(initializer)
return assignment
}
private fun createVariableDeclaration(property: KtProperty, generateDefaultInitializers: Boolean): KtProperty {
val propertyType = getPropertyType(property)
var defaultInitializer: String? = null
if (generateDefaultInitializers && property.isVar) {
defaultInitializer = CodeInsightUtils.defaultInitializer(propertyType)
}
return createProperty(property, propertyType, defaultInitializer)
}
private fun getPropertyType(property: KtProperty): KotlinType {
val variableDescriptor = property.resolveToDescriptorIfAny(BodyResolveMode.PARTIAL)
?: error("Couldn't resolve property to property descriptor " + property.text)
return variableDescriptor.type
}
private fun createProperty(property: KtProperty, propertyType: KotlinType, initializer: String?): KtProperty {
val typeRef = property.typeReference
val typeString = when {
typeRef != null -> typeRef.text
!propertyType.isError -> IdeDescriptorRenderers.SOURCE_CODE.renderType(propertyType)
else -> null
}
return KtPsiFactory(property).createProperty(property.name!!, typeString, property.isVar, initializer)
}
private fun needToDeclareOut(element: PsiElement, lastStatementOffset: Int, scope: SearchScope): Boolean {
if (element is KtProperty ||
element is KtClassOrObject ||
element is KtFunction
) {
val refs = ReferencesSearch.search(element, scope, false).toArray(PsiReference.EMPTY_ARRAY)
if (refs.isNotEmpty()) {
val lastRef = refs.maxByOrNull { it.element.textOffset } ?: return false
if (lastRef.element.textOffset > lastStatementOffset) {
return true
}
}
}
return false
}
| apache-2.0 | b76283da69876bac0b695677007165e7 | 41.38961 | 158 | 0.708946 | 5.290113 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/idepreview/UiPreView.kt | 1 | 8311 | /*
* Copyright 2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.idepreview
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import splitties.dimensions.dip
import splitties.exceptions.illegalArg
import splitties.exceptions.unsupported
import splitties.init.injectAsAppCtx
import splitties.resources.str
import splitties.resources.strArray
import splitties.resources.styledColor
import splitties.views.backgroundColor
import splitties.views.dsl.core.*
import splitties.views.gravityCenterVertical
import splitties.views.padding
import splitties.views.setCompoundDrawables
import java.lang.reflect.Constructor
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import splitties.views.dsl.core.R
/**
* This class is dedicated to previewing `Ui` subclasses in the IDE.
*
* You can enable the preview with code or a dedicated xml file.
*
* Here's an example in Kotlin:
*
* ```kotlin
* //region IDE preview
* @Deprecated("For IDE preview only", level = DeprecationLevel.HIDDEN)
* private class MainUiImplPreview(
* context: Context,
* attrs: AttributeSet? = null,
* defStyleAttr: Int = 0
* ) : UiPreView(
* context = context.withTheme(R.style.AppTheme),
* attrs = attrs,
* defStyleAttr = defStyleAttr,
* createUi = { MainUiImpl(it) }
* )
* //endregion
* ```
*
* And here is an example xml layout file that would preview a `MainUi` class in the `main` package:
*
* ```xml
* <splitties.views.dsl.idepreview.UiPreView
* xmlns:android="http://schemas.android.com/apk/res/android"
* xmlns:app="http://schemas.android.com/apk/res-auto"
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* android:theme="@style/AppTheme.NoActionBar"
* app:class_package_name_relative="main.MainUi"/>
* ```
*
* Note that only the Kotlin version is safe from refactorings (such as renames, package moving…).
*
* If you use the xml approach, it's recommended to add it to your debug sources straightaway.
* For the Kotlin approach, R8 or proguard will see the class is unused and will strip it so long as you
* have `minifyEnabled = true`.
*
* See the sample for complete examples.
*/
open class UiPreView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
createUi: ((Context) -> Ui)? = null
) : FrameLayout(context, attrs, defStyleAttr) {
init {
backgroundColor = styledColor(android.R.attr.colorBackground)
require(isInEditMode) { "Only intended for use in IDE!" }
this.context.injectAsAppCtx()
try {
if (createUi == null) {
init(this.context, attrs, defStyleAttr)
} else {
add(createUi(this.context).root, lParams(matchParent, matchParent))
}
} catch (t: IllegalArgumentException) {
backgroundColor = Color.WHITE
addView(textView {
text = t.message ?: t.toString()
setCompoundDrawables(top = R.drawable.ic_warning_red_96dp)
gravity = gravityCenterVertical
setTextColor(Color.BLUE)
padding = dip(16)
textSize = 24f
}, lParams(matchParent, matchParent))
}
}
private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
val uiClass: Class<out Ui> = withStyledAttributes(
attrs = attrs,
attrsRes = R.styleable.UiPreView,
defStyleAttr = defStyleAttr,
defStyleRes = 0
) { ta ->
ta.getString(R.styleable.UiPreView_splitties_class_fully_qualified_name)?.let {
try {
@Suppress("UNCHECKED_CAST")
Class.forName(it) as Class<out Ui>
} catch (e: ClassNotFoundException) {
illegalArg("Did not find the specified class: $it")
}
} ?: ta.getString(R.styleable.UiPreView_splitties_class_package_name_relative)?.let {
val packageName = context.packageName.removeSuffix(
suffix = str(R.string.splitties_views_dsl_ide_preview_package_name_suffix)
)
try {
@Suppress("UNCHECKED_CAST")
Class.forName("$packageName.$it") as Class<out Ui>
} catch (e: ClassNotFoundException) {
val otherPackages =
context.strArray(R.array.splitties_ui_preview_base_package_names)
otherPackages.fold<String, Class<out Ui>?>(null) { foundOrNull, packageNameHierarchy ->
foundOrNull ?: try {
@Suppress("UNCHECKED_CAST")
Class.forName("$packageNameHierarchy.$it") as Class<out Ui>
} catch (e: ClassNotFoundException) {
null
}
} ?: illegalArg(
"Package-name relative class \"$it\" not found!\nDid you make a typo?\n\n" +
"Searched in the following root packages:\n" +
"- $packageName\n" +
otherPackages.joinToString(separator = "\n", prefix = "- ")
)
}
} ?: illegalArg("No class name attribute provided")
}
require(!uiClass.isInterface) { "$uiClass is not instantiable because it's an interface!" }
require(Ui::class.java.isAssignableFrom(uiClass)) { "$uiClass is not a subclass of Ui!" }
val ui = try {
val uiConstructor: Constructor<out Ui> = uiClass.getConstructor(Context::class.java)
uiConstructor.newInstance(context)
} catch (e: NoSuchMethodException) {
val uiConstructor = uiClass.constructors.firstOrNull {
it.parameterTypes.withIndex().all { (i, parameterType) ->
(i == 0 && parameterType == Context::class.java) || parameterType.isInterface
}
} ?: illegalArg(
"No suitable constructor found. Need one with Context as " +
"first parameter, and only interface types for other parameters, if any."
)
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
val parameters = mutableListOf<Any>(context).also { params ->
uiConstructor.parameterTypes.forEachIndexed { index, parameterType ->
if (index != 0) params += when (parameterType) {
CoroutineContext::class.java -> EmptyCoroutineContext
else -> Proxy.newProxyInstance(
parameterType.classLoader,
arrayOf(parameterType)
) { proxy: Any?, method: Method, args: Array<out Any>? ->
when (method.declaringClass.name) {
"kotlinx.coroutines.CoroutineScope" -> EmptyCoroutineContext
else -> unsupported("Edit mode: stub implementation.")
}
}
}
}
}.toTypedArray()
uiConstructor.newInstance(*parameters) as Ui
}
addView(ui.root, lParams(matchParent, matchParent))
}
}
@OptIn(ExperimentalContracts::class)
private inline fun <R> View.withStyledAttributes(
attrs: AttributeSet?,
attrsRes: IntArray,
defStyleAttr: Int,
defStyleRes: Int = 0,
func: (styledAttrs: TypedArray) -> R
): R {
contract { callsInPlace(func, InvocationKind.EXACTLY_ONCE) }
val styledAttrs = context.obtainStyledAttributes(attrs, attrsRes, defStyleAttr, defStyleRes)
return func(styledAttrs).also { styledAttrs.recycle() }
}
| apache-2.0 | 5c9cb8ae6f552fe7c510ecdc06e2ed7a | 41.177665 | 109 | 0.607775 | 4.704983 | false | false | false | false |
headissue/cache2k | test-android-gradle/buildSrc/src/main/java/org/cache2k/android/Cache2kAndroidPlugin.kt | 2 | 3733 | package org.cache2k.android
/*
* #%L
* cache2k Android integration
* %%
* Copyright (C) 2000 - 2021 headissue GmbH, Munich
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.ConfigurableFileTree
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.kotlin.dsl.fileTree
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import java.io.File
/**
* Custom build logic for hooking the Maven-based Cache2k core modules
* to the Gradle-based Android infrastructure.
*
* This plugin has multiple responsibilities, e.g. declaring dependencies on
* local Cache2k modules from a Gradle context, as well as ensuring
* that Maven tasks are up-to-date before the instrumentation tests are executed.
*
* @author Marcel Schnelle
*/
class Cache2kAndroidPlugin : Plugin<Project> {
override fun apply(target: Project) {
// Connect directly to the Android Gradle plugin
target.plugins.withId("com.android.library") {
applyInternal(target)
}
}
/* Private */
private fun applyInternal(project: Project) {
// Register Cache2k dependencies for Android instrumentation tests
registerCache2kDependencies(project)
// Connect Maven packaging task to Android instrumentation tests
registerMavenPackagingTask(project)
}
private fun registerCache2kDependencies(project: Project) =
with(project) {
// Depend on Cache2k test suite and its transitive dependencies
dependencies.add("androidTestImplementation", cache2kDependency("api"))
dependencies.add("androidTestImplementation", cache2kDependency("core"))
dependencies.add("androidTestImplementation", cache2kDependency("pinpoint"))
dependencies.add("androidTestImplementation", cache2kDependency("testing"))
dependencies.add("androidTestImplementation", cache2kDependency("testsuite"))
}
private val Project.repositoryRoot: File
get() = rootDir.parentFile
private fun Project.cache2kDependency(moduleName: String): ConfigurableFileTree {
val moduleFolder = repositoryRoot.resolve("cache2k-$moduleName")
return project.fileTree(
"dir" to moduleFolder.resolve("target"),
"include" to "*.jar",
"exclude" to listOf("*sources*", "*javadoc*")
)
}
private fun registerMavenPackagingTask(project: Project) {
// Create a Gradle task that in turn invokes Maven's compilation task
// then make that task a precondition of Android's instrumentation test compilation
val mavenTask = project.tasks.register<Exec>("packageCache2kTestsuiteWithMaven") {
workingDir = project.repositoryRoot
commandLine("mvn -DskipTests clean package -pl :cache2k-testsuite -am -T1C".split(" "))
}
project.tasks.withType<JavaCompile> {
if (name == "compileDebugAndroidTestJavaWithJavac") {
dependsOn(mavenTask)
}
}
}
}
| gpl-3.0 | 10bfb783ea015478e90885adc691211b | 36.707071 | 99 | 0.691133 | 4.541363 | false | true | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/WrongConstraintLayoutUsageDetector.kt | 1 | 2029 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LayoutDetector
import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE
import com.android.tools.lint.detector.api.Severity.ERROR
import com.android.tools.lint.detector.api.XmlContext
import org.w3c.dom.Element
val ISSUE_WRONG_CONSTRAINT_LAYOUT_USAGE = Issue.create(
"WrongConstraintLayoutUsage", "Marks a wrong usage of the Constraint Layout.",
"Instead of using left & right constraints start & end should be used.",
CORRECTNESS, PRIORITY, ERROR,
Implementation(WrongConstraintLayoutUsageDetector::class.java, RESOURCE_FILE_SCOPE),
)
class WrongConstraintLayoutUsageDetector : LayoutDetector() {
override fun getApplicableElements() = ALL
override fun visitElement(context: XmlContext, element: Element) {
val attributes = element.attributes
for (i in 0 until attributes.length) {
val item = attributes.item(i)
val localName = item.localName
if (localName != null) {
val properLocalName = localName.replace("Left", "Start")
.replace("Right", "End")
val isConstraint = localName.contains("layout_constraint")
val hasLeft = localName.contains("Left")
val hasRight = localName.contains("Right")
val isAnIssue = isConstraint && (hasLeft || hasRight)
if (isAnIssue) {
val fix = fix()
.name("Fix it")
.replace()
.text(localName)
.with(properLocalName)
.autoFix()
.build()
context.report(ISSUE_WRONG_CONSTRAINT_LAYOUT_USAGE, item, context.getNameLocation(item), "This attribute won't work with RTL. Please use $properLocalName instead.", fix)
}
}
}
}
}
| apache-2.0 | b91c3aafe8b45f8d8395c936a2088b3b | 35.890909 | 179 | 0.703795 | 4.157787 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt | 1 | 9609 | package info.nightscout.androidaps.plugins.treatments.fragments
import android.content.DialogInterface
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.events.EventTempBasalChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment.RecyclerViewAdapter.TempBasalsViewHolder
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.treatments_tempbasals_fragment.*
import javax.inject.Inject
class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
private val disposable = CompositeDisposable()
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.treatments_tempbasals_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tempbasals_recyclerview.setHasFixedSize(true)
tempbasals_recyclerview.layoutManager = LinearLayoutManager(view.context)
tempbasals_recyclerview.adapter = RecyclerViewAdapter(activePlugin.activeTreatments.temporaryBasalsFromHistory)
}
@Synchronized override fun onResume() {
super.onResume()
disposable.add(rxBus
.toObservable(EventTempBasalChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }) { fabricPrivacy.logException(it) }
)
disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }) { fabricPrivacy.logException(it) }
)
updateGui()
}
@Synchronized override fun onPause() {
super.onPause()
disposable.clear()
}
inner class RecyclerViewAdapter internal constructor(private var tempBasalList: Intervals<TemporaryBasal>) : RecyclerView.Adapter<TempBasalsViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempBasalsViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_tempbasals_item, viewGroup, false)
return TempBasalsViewHolder(v)
}
override fun onBindViewHolder(holder: TempBasalsViewHolder, position: Int) {
val tempBasal = tempBasalList.getReversed(position)
holder.ph.visibility = if (tempBasal.source == Source.PUMP) View.VISIBLE else View.GONE
holder.ns.visibility = if (NSUpload.isIdValid(tempBasal._id)) View.VISIBLE else View.GONE
if (tempBasal.isEndingEvent) {
holder.date.text = dateUtil.dateAndTimeString(tempBasal.date)
holder.duration.text = resourceHelper.gs(R.string.cancel)
holder.absolute.text = ""
holder.percent.text = ""
holder.realDuration.text = ""
holder.iob.text = ""
holder.netInsulin.text = ""
holder.netRatio.text = ""
holder.extendedFlag.visibility = View.GONE
holder.iob.setTextColor(holder.netRatio.currentTextColor)
} else {
if (tempBasal.isInProgress) {
holder.date.text = dateUtil.dateAndTimeString(tempBasal.date)
holder.date.setTextColor(resourceHelper.gc(R.color.colorActive))
} else {
holder.date.text = dateUtil.dateAndTimeRangeString(tempBasal.date, tempBasal.end())
holder.date.setTextColor(holder.netRatio.currentTextColor)
}
holder.duration.text = resourceHelper.gs(R.string.format_mins, tempBasal.durationInMinutes)
if (tempBasal.isAbsolute) {
val profile = profileFunction.getProfile(tempBasal.date)
if (profile != null) {
holder.absolute.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile))
holder.percent.text = ""
} else {
holder.absolute.text = resourceHelper.gs(R.string.noprofile)
holder.percent.text = ""
}
} else {
holder.absolute.text = ""
holder.percent.text = resourceHelper.gs(R.string.format_percent, tempBasal.percentRate)
}
holder.realDuration.text = resourceHelper.gs(R.string.format_mins, tempBasal.realDuration)
val now = DateUtil.now()
var iob = IobTotal(now)
val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile)
holder.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.basaliob)
holder.netInsulin.text = resourceHelper.gs(R.string.formatinsulinunits, iob.netInsulin)
holder.netRatio.text = resourceHelper.gs(R.string.pump_basebasalrate, iob.netRatio)
holder.extendedFlag.visibility = View.GONE
if (iob.basaliob != 0.0) holder.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.iob.setTextColor(holder.netRatio.currentTextColor)
}
holder.remove.tag = tempBasal
}
override fun getItemCount(): Int {
return tempBasalList.size()
}
inner class TempBasalsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var cv: CardView = itemView.findViewById(R.id.tempbasals_cardview)
var date: TextView = itemView.findViewById(R.id.tempbasals_date)
var duration: TextView = itemView.findViewById(R.id.tempbasals_duration)
var absolute: TextView = itemView.findViewById(R.id.tempbasals_absolute)
var percent: TextView = itemView.findViewById(R.id.tempbasals_percent)
var realDuration: TextView = itemView.findViewById(R.id.tempbasals_realduration)
var netRatio: TextView = itemView.findViewById(R.id.tempbasals_netratio)
var netInsulin: TextView = itemView.findViewById(R.id.tempbasals_netinsulin)
var iob: TextView = itemView.findViewById(R.id.tempbasals_iob)
var extendedFlag: TextView = itemView.findViewById(R.id.tempbasals_extendedflag)
var remove: TextView = itemView.findViewById(R.id.tempbasals_remove)
var ph: TextView = itemView.findViewById(R.id.pump_sign)
var ns: TextView = itemView.findViewById(R.id.ns_sign)
init {
remove.setOnClickListener { v: View ->
val tempBasal = v.tag as TemporaryBasal
context?.let {
showConfirmation(it, resourceHelper.gs(R.string.removerecord),
"""
${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull()}
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)}
""".trimIndent(),
DialogInterface.OnClickListener { _: DialogInterface?, _: Int ->
activePlugin.activeTreatments.removeTempBasal(tempBasal)
}, null)
}
}
remove.paintFlags = remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
}
}
private fun updateGui() {
tempbasals_recyclerview?.swapAdapter(RecyclerViewAdapter(activePlugin.activeTreatments.temporaryBasalsFromHistory), false)
val tempBasalsCalculation = activePlugin.activeTreatments.lastCalculationTempBasals
if (tempBasalsCalculation != null) tempbasals_totaltempiob?.text = resourceHelper.gs(R.string.formatinsulinunits, tempBasalsCalculation.basaliob)
}
} | agpl-3.0 | 159f4d757011d5d2616c5ab4f05fcd9c | 52.093923 | 167 | 0.679571 | 4.955647 | false | false | false | false |
fabmax/kool | kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/joints/RevoluteJoint.kt | 1 | 1926 | package de.fabmax.kool.physics.joints
import de.fabmax.kool.math.Mat4f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.physics.Physics
import de.fabmax.kool.physics.RigidActor
import de.fabmax.kool.physics.createPxTransform
import de.fabmax.kool.physics.joints.RevoluteJointHelper.computeFrame
import de.fabmax.kool.physics.toPxTransform
import org.lwjgl.system.MemoryStack
import physx.PxTopLevelFunctions
import physx.extensions.PxRevoluteJoint
import physx.extensions.PxRevoluteJointFlagEnum
actual class RevoluteJoint actual constructor(actual val bodyA: RigidActor, actual val bodyB: RigidActor,
frameA: Mat4f, frameB: Mat4f) : Joint() {
actual val frameA = Mat4f().set(frameA)
actual val frameB = Mat4f().set(frameB)
actual constructor(bodyA: RigidActor, bodyB: RigidActor,
pivotA: Vec3f, pivotB: Vec3f,
axisA: Vec3f, axisB: Vec3f)
: this(bodyA, bodyB, computeFrame(pivotA, axisA), computeFrame(pivotB, axisB))
override val pxJoint: PxRevoluteJoint
init {
Physics.checkIsLoaded()
MemoryStack.stackPush().use { mem ->
val frmA = frameA.toPxTransform(mem.createPxTransform())
val frmB = frameB.toPxTransform(mem.createPxTransform())
pxJoint = PxTopLevelFunctions.RevoluteJointCreate(Physics.physics, bodyA.pxRigidActor, frmA, bodyB.pxRigidActor, frmB)
}
}
actual fun disableAngularMotor() {
pxJoint.driveVelocity = 0f
pxJoint.driveForceLimit = 0f
pxJoint.setRevoluteJointFlag(PxRevoluteJointFlagEnum.eDRIVE_ENABLED, false)
}
actual fun enableAngularMotor(angularVelocity: Float, forceLimit: Float) {
pxJoint.driveVelocity = angularVelocity
pxJoint.driveForceLimit = forceLimit
pxJoint.setRevoluteJointFlag(PxRevoluteJointFlagEnum.eDRIVE_ENABLED, true)
}
} | apache-2.0 | 1ad9238a4d6289f8b5a9f612402de9dc | 39.145833 | 130 | 0.712876 | 3.890909 | false | false | false | false |
leafclick/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsState.kt | 1 | 8286 | // 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.ide.ui
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.ReportValue
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.PlatformUtils
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
import javax.swing.SwingConstants
import kotlin.math.roundToInt
class UISettingsState : BaseState() {
companion object {
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Int
get() = (JBUIScale.DEF_SYSTEM_FONT_SIZE * UISettings.defFontScale).roundToInt()
}
@get:OptionTag("FONT_FACE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontFace"))
var fontFace by string()
@get:OptionTag("FONT_SIZE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontSize"))
var fontSize by property(0)
@get:OptionTag("FONT_SCALE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontScale"))
var fontScale by property(0f)
@get:ReportValue
@get:OptionTag("RECENT_FILES_LIMIT")
var recentFilesLimit by property(50)
@get:ReportValue
@get:OptionTag("RECENT_LOCATIONS_LIMIT")
var recentLocationsLimit by property(25)
@get:OptionTag("CONSOLE_COMMAND_HISTORY_LIMIT")
var consoleCommandHistoryLimit by property(300)
@get:OptionTag("OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE")
var overrideConsoleCycleBufferSize by property(false)
@get:OptionTag("CONSOLE_CYCLE_BUFFER_SIZE_KB")
var consoleCycleBufferSizeKb by property(1024)
@get:ReportValue
@get:OptionTag("EDITOR_TAB_LIMIT")
var editorTabLimit by property(10)
@get:OptionTag("REUSE_NOT_MODIFIED_TABS")
var reuseNotModifiedTabs by property(false)
@get:OptionTag("ANIMATE_WINDOWS")
var animateWindows by property(true)
@get:OptionTag("SHOW_TOOL_WINDOW_NUMBERS")
var showToolWindowsNumbers by property(true)
@get:OptionTag("HIDE_TOOL_STRIPES")
var hideToolStripes by property(false)
@get:OptionTag("WIDESCREEN_SUPPORT")
var wideScreenSupport by property(false)
@get:OptionTag("LEFT_HORIZONTAL_SPLIT")
var leftHorizontalSplit by property(false)
@get:OptionTag("RIGHT_HORIZONTAL_SPLIT")
var rightHorizontalSplit by property(false)
@get:OptionTag("SHOW_EDITOR_TOOLTIP")
var showEditorToolTip by property(true)
@get:OptionTag("SHOW_MEMORY_INDICATOR")
var showMemoryIndicator by property(false)
@get:OptionTag("SHOW_WRITE_THREAD_INDICATOR")
var showWriteThreadIndicator by property(false)
@get:OptionTag("ALLOW_MERGE_BUTTONS")
var allowMergeButtons by property(true)
@get:OptionTag("SHOW_MAIN_TOOLBAR")
var showMainToolbar by property(false)
@get:OptionTag("SHOW_STATUS_BAR")
var showStatusBar by property(true)
@get:OptionTag("SHOW_MAIN_MENU")
var showMainMenu by property(true)
@get:OptionTag("SHOW_NAVIGATION_BAR")
var showNavigationBar by property(true)
@get:OptionTag("SHOW_NAVIGATION_BAR_MEMBERS")
var showMembersInNavigationBar by property(true)
@get:OptionTag("ALWAYS_SHOW_WINDOW_BUTTONS")
var alwaysShowWindowsButton by property(false)
@get:OptionTag("CYCLE_SCROLLING")
var cycleScrolling by property(true)
@get:OptionTag("SELECTED_TABS_LAYOUT_INFO_ID")
var selectedTabsLayoutInfoId by string(null)
@get:OptionTag("SCROLL_TAB_LAYOUT_IN_EDITOR")
var scrollTabLayoutInEditor by property(true)
@get:OptionTag("HIDE_TABS_IF_NEED")
var hideTabsIfNeeded by property(true)
@get:OptionTag("SHOW_CLOSE_BUTTON")
var showCloseButton by property(true)
@get:OptionTag("CLOSE_TAB_BUTTON_ON_THE_RIGHT")
var closeTabButtonOnTheRight by property(true)
@get:OptionTag("EDITOR_TAB_PLACEMENT")
var editorTabPlacement: Int by property(SwingConstants.TOP)
@get:OptionTag("SHOW_FILE_ICONS_IN_TABS")
var showFileIconInTabs by property(true)
@get:OptionTag("HIDE_KNOWN_EXTENSION_IN_TABS")
var hideKnownExtensionInTabs by property(false)
@get:OptionTag("SHOW_ICONS_IN_QUICK_NAVIGATION")
var showIconInQuickNavigation by property(true)
var showTreeIndentGuides by property(false)
var compactTreeIndents by property(false)
@get:OptionTag("SORT_TABS_ALPHABETICALLY")
var sortTabsAlphabetically by property(false)
@get:OptionTag("OPEN_TABS_AT_THE_END")
var openTabsAtTheEnd by property(false)
@get:OptionTag("CLOSE_NON_MODIFIED_FILES_FIRST")
var closeNonModifiedFilesFirst by property(false)
@get:OptionTag("ACTIVATE_MRU_EDITOR_ON_CLOSE")
var activeMruEditorOnClose by property(false)
// TODO[anton] consider making all IDEs use the same settings
@get:OptionTag("ACTIVATE_RIGHT_EDITOR_ON_CLOSE")
var activeRightEditorOnClose by property(PlatformUtils.isAppCode())
@get:OptionTag("IDE_AA_TYPE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.ideAAType"))
internal var ideAAType by enum(AntialiasingType.SUBPIXEL)
@get:OptionTag("EDITOR_AA_TYPE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.editorAAType"))
internal var editorAAType by enum(AntialiasingType.SUBPIXEL)
@get:OptionTag("COLOR_BLINDNESS")
var colorBlindness by enum<ColorBlindness>()
@get:OptionTag("CONTRAST_SCROLLBARS")
var useContrastScrollBars by property(false)
@get:OptionTag("MOVE_MOUSE_ON_DEFAULT_BUTTON")
var moveMouseOnDefaultButton by property(false)
@get:OptionTag("ENABLE_ALPHA_MODE")
var enableAlphaMode by property(false)
@get:OptionTag("ALPHA_MODE_DELAY")
var alphaModeDelay by property(1500)
@get:OptionTag("ALPHA_MODE_RATIO")
var alphaModeRatio by property(0.5f)
@get:OptionTag("OVERRIDE_NONIDEA_LAF_FONTS")
var overrideLafFonts by property(false)
@get:OptionTag("SHOW_ICONS_IN_MENUS")
var showIconsInMenus by property(true)
// IDEADEV-33409, should be disabled by default on MacOS
@get:OptionTag("DISABLE_MNEMONICS")
var disableMnemonics by property(SystemInfo.isMac)
@get:OptionTag("DISABLE_MNEMONICS_IN_CONTROLS")
var disableMnemonicsInControls by property(false)
@get:OptionTag("USE_SMALL_LABELS_ON_TABS")
var useSmallLabelsOnTabs by property(SystemInfo.isMac)
@get:OptionTag("MAX_LOOKUP_WIDTH2")
var maxLookupWidth by property(500)
@get:OptionTag("MAX_LOOKUP_LIST_HEIGHT")
var maxLookupListHeight by property(11)
@get:OptionTag("HIDE_NAVIGATION_ON_FOCUS_LOSS")
var hideNavigationOnFocusLoss by property(true)
@get:OptionTag("DND_WITH_PRESSED_ALT_ONLY")
var dndWithPressedAltOnly by property(false)
@get:OptionTag("DEFAULT_AUTOSCROLL_TO_SOURCE")
var defaultAutoScrollToSource by property(false)
@get:Transient
var presentationMode: Boolean = false
@get:OptionTag("PRESENTATION_MODE_FONT_SIZE")
var presentationModeFontSize by property(24)
@get:OptionTag("MARK_MODIFIED_TABS_WITH_ASTERISK")
var markModifiedTabsWithAsterisk by property(false)
@get:OptionTag("SHOW_TABS_TOOLTIPS")
var showTabsTooltips by property(true)
@get:OptionTag("SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES")
var showDirectoryForNonUniqueFilenames by property(true)
var smoothScrolling by property(true)
@get:OptionTag("NAVIGATE_TO_PREVIEW")
var navigateToPreview by property(false)
var animatedScrolling by property(!SystemInfo.isMac || !SystemInfo.isJetBrainsJvm)
var animatedScrollingDuration by property(
when {
SystemInfo.isWindows -> 200
SystemInfo.isMac -> 50
else -> 150
}
)
var animatedScrollingCurvePoints by property(
when {
SystemInfo.isWindows -> 1684366536
SystemInfo.isMac -> 845374563
else -> 729434056
}
)
@get:OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY")
var sortLookupElementsLexicographically by property(false)
@get:OptionTag("MERGE_EQUAL_STACKTRACES")
var mergeEqualStackTraces by property(true)
@get:OptionTag("SORT_BOOKMARKS")
var sortBookmarks by property(false)
@get:OptionTag("PIN_FIND_IN_PATH_POPUP")
var pinFindInPath by property(false)
@get:OptionTag("SHOW_INPLACE_COMMENTS")
var showInplaceComments by property(false)
@Suppress("FunctionName")
fun _incrementModificationCount() = incrementModificationCount()
} | apache-2.0 | 59effea5f8d9265f19f60919b515d3a7 | 37.724299 | 140 | 0.768284 | 3.997106 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateNotificationReceiver.kt | 2 | 2558 | package eu.kanade.tachiyomi.data.updater
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import eu.kanade.tachiyomi.Constants.NOTIFICATION_UPDATER_ID
import eu.kanade.tachiyomi.util.notificationManager
import java.io.File
class UpdateNotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
ACTION_INSTALL_APK -> {
UpdateDownloaderService.installAPK(context,
File(intent.getStringExtra(EXTRA_FILE_LOCATION)))
cancelNotification(context)
}
ACTION_DOWNLOAD_UPDATE -> UpdateDownloaderService.downloadUpdate(context,
intent.getStringExtra(UpdateDownloaderService.EXTRA_DOWNLOAD_URL))
ACTION_CANCEL_NOTIFICATION -> cancelNotification(context)
}
}
fun cancelNotification(context: Context) {
context.notificationManager.cancel(NOTIFICATION_UPDATER_ID)
}
companion object {
// Install apk action
const val ACTION_INSTALL_APK = "eu.kanade.INSTALL_APK"
// Download apk action
const val ACTION_DOWNLOAD_UPDATE = "eu.kanade.RETRY_DOWNLOAD"
// Cancel notification action
const val ACTION_CANCEL_NOTIFICATION = "eu.kanade.CANCEL_NOTIFICATION"
// Absolute path of apk file
const val EXTRA_FILE_LOCATION = "file_location"
fun cancelNotificationIntent(context: Context): PendingIntent {
val intent = Intent(context, UpdateNotificationReceiver::class.java).apply {
action = ACTION_CANCEL_NOTIFICATION
}
return PendingIntent.getBroadcast(context, 0, intent, 0)
}
fun installApkIntent(context: Context, path: String): PendingIntent {
val intent = Intent(context, UpdateNotificationReceiver::class.java).apply {
action = ACTION_INSTALL_APK
putExtra(EXTRA_FILE_LOCATION, path)
}
return PendingIntent.getBroadcast(context, 0, intent, 0)
}
fun downloadApkIntent(context: Context, url: String): PendingIntent {
val intent = Intent(context, UpdateNotificationReceiver::class.java).apply {
action = ACTION_DOWNLOAD_UPDATE
putExtra(UpdateDownloaderService.EXTRA_DOWNLOAD_URL, url)
}
return PendingIntent.getBroadcast(context, 0, intent, 0)
}
}
} | gpl-3.0 | 47723cbe1fdafdbe392b88aab8a6fadf | 37.19403 | 88 | 0.6595 | 5.055336 | false | false | false | false |
alexames/flatbuffers | kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/JSON.kt | 6 | 26349 | /*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.google.flatbuffers.kotlin
import com.google.flatbuffers.kotlin.FlexBuffersBuilder.Companion.SHARE_KEYS_AND_STRINGS
import kotlin.experimental.and
import kotlin.math.pow
/**
* Returns a minified version of this FlexBuffer as a JSON.
*/
public fun Reference.toJson(): String = ArrayReadWriteBuffer(1024).let {
toJson(it)
val data = it.data() // it.getString(0, it.writePosition)
return data.decodeToString(0, it.writePosition)
}
/**
* Returns a minified version of this FlexBuffer as a JSON.
* @param out [ReadWriteBuffer] the JSON will be written.
*/
public fun Reference.toJson(out: ReadWriteBuffer) {
when (type) {
T_STRING -> {
val start = buffer.indirect(end, parentWidth)
val size = buffer.readULong(start - byteWidth, byteWidth).toInt()
out.jsonEscape(buffer, start, size)
}
T_KEY -> {
val start = buffer.indirect(end, parentWidth)
val end = buffer.findFirst(0.toByte(), start)
out.jsonEscape(buffer, start, end - start)
}
T_BLOB -> {
val blob = toBlob()
out.jsonEscape(out, blob.end, blob.size)
}
T_INT -> out.put(toLong().toString())
T_UINT -> out.put(toULong().toString())
T_FLOAT -> out.put(toDouble().toString())
T_NULL -> out.put("null")
T_BOOL -> out.put(toBoolean().toString())
T_MAP -> toMap().toJson(out)
T_VECTOR, T_VECTOR_BOOL, T_VECTOR_FLOAT, T_VECTOR_INT,
T_VECTOR_UINT, T_VECTOR_KEY, T_VECTOR_STRING_DEPRECATED -> toVector().toJson(out)
else -> error("Unable to convert type ${type.typeToString()} to JSON")
}
}
/**
* Returns a minified version of this FlexBuffer as a JSON.
*/
public fun Map.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() }
/**
* Returns a minified version of this FlexBuffer as a JSON.
* @param out [ReadWriteBuffer] the JSON will be written.
*/
public fun Map.toJson(out: ReadWriteBuffer) {
out.put('{'.toByte())
// key values pairs
for (i in 0 until size) {
val key = keyAt(i)
out.jsonEscape(buffer, key.start, key.sizeInBytes)
out.put(':'.toByte())
get(i).toJson(out)
if (i != size - 1) {
out.put(','.toByte())
}
}
// close bracket
out.put('}'.toByte())
}
/**
* Returns a minified version of this FlexBuffer as a JSON.
*/
public fun Vector.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() }
/**
* Returns a minified version of this FlexBuffer as a JSON.
* @param out that the JSON is being concatenated.
*/
public fun Vector.toJson(out: ReadWriteBuffer) {
out.put('['.toByte())
for (i in 0 until size) {
get(i).toJson(out)
if (i != size - 1) {
out.put(','.toByte())
}
}
out.put(']'.toByte())
}
/**
* JSONParser class is used to parse a JSON as FlexBuffers. Calling [JSONParser.parse] fiils [output]
* and returns a [Reference] ready to be used.
*/
public class JSONParser(public var output: FlexBuffersBuilder = FlexBuffersBuilder(1024, SHARE_KEYS_AND_STRINGS)) {
private var readPos = 0
private var scopes = ScopeStack()
/**
* Parse a json as [String] and returns a [Reference] to a FlexBuffer.
*/
public fun parse(data: String): Reference = parse(ArrayReadBuffer(data.encodeToByteArray()))
/**
* Parse a json as [ByteArray] and returns a [Reference] to a FlexBuffer.
*/
public fun parse(data: ByteArray): Reference = parse(ArrayReadBuffer(data))
/**
* Parse a json as [ReadBuffer] and returns a [Reference] to a FlexBuffer.
*/
public fun parse(data: ReadBuffer): Reference {
reset()
parseValue(data, nextToken(data), null)
if (readPos < data.limit) {
val tok = skipWhitespace(data)
if (tok != CHAR_EOF) {
makeError(data, "Extraneous charaters after parse has finished", tok)
}
}
output.finish()
return getRoot(output.buffer)
}
private fun parseValue(data: ReadBuffer, token: Token, key: String? = null): FlexBufferType {
return when (token) {
TOK_BEGIN_OBJECT -> parseObject(data, key)
TOK_BEGIN_ARRAY -> parseArray(data, key)
TOK_TRUE -> T_BOOL.also { output[key] = true }
TOK_FALSE -> T_BOOL.also { output[key] = false }
TOK_NULL -> T_NULL.also { output.putNull(key) }
TOK_BEGIN_QUOTE -> parseString(data, key)
TOK_NUMBER -> parseNumber(data, data.data(), key)
else -> makeError(data, "Unexpected Character while parsing", 'x'.toByte())
}
}
private fun parseObject(data: ReadBuffer, key: String? = null): FlexBufferType {
this.scopes.push(SCOPE_OBJ_EMPTY)
val fPos = output.startMap()
val limit = data.limit
while (readPos <= limit) {
when (val tok = nextToken(data)) {
TOK_END_OBJECT -> {
this.scopes.pop()
output.endMap(fPos, key); return T_MAP
}
TOK_BEGIN_QUOTE -> {
val childKey = readString(data)
parseValue(data, nextToken(data), childKey)
}
else -> makeError(data, "Expecting start of object key", tok)
}
}
makeError(data, "Unable to parse the object", "x".toByte())
}
private fun parseArray(data: ReadBuffer, key: String? = null): FlexBufferType {
this.scopes.push(SCOPE_ARRAY_EMPTY)
val fPos = output.startVector()
var elementType = T_INVALID
var multiType = false
val limit = data.limit
while (readPos <= limit) {
when (val tok = nextToken(data)) {
TOK_END_ARRAY -> {
this.scopes.pop()
return if (!multiType && elementType.isScalar()) {
output.endTypedVector(fPos, key)
elementType.toElementTypedVector()
} else {
output.endVector(key, fPos)
T_VECTOR
}
}
else -> {
val newType = parseValue(data, tok, null)
if (elementType == T_INVALID) {
elementType = newType
} else if (newType != elementType) {
multiType = true
}
}
}
}
makeError(data, "Unable to parse the array")
}
private fun parseNumber(data: ReadBuffer, array: ByteArray, key: String?): FlexBufferType {
val ary = array
var cursor = readPos
var c = data[readPos++]
var useDouble = false
val limit = ary.size
var sign = 1
var double: Double
var long = 0L
var digits = 0
if (c == CHAR_MINUS) {
cursor++
checkEOF(data, cursor)
c = ary[cursor]
sign = -1
}
// peek first byte
when (c) {
CHAR_0 -> {
cursor++
if (cursor != limit) {
c = ary[cursor]
}
}
!in CHAR_0..CHAR_9 -> makeError(data, "Invalid Number", c)
else -> {
do {
val digit = c - CHAR_0
// double = 10.0 * double + digit
long = 10 * long + digit
digits++
cursor++
if (cursor == limit) break
c = ary[cursor]
} while (c in CHAR_0..CHAR_9)
}
}
var exponent = 0
// If we find '.' we need to convert to double
if (c == CHAR_DOT) {
useDouble = true
checkEOF(data, cursor)
c = ary[++cursor]
if (c < CHAR_0 || c > CHAR_9) {
makeError(data, "Invalid Number", c)
}
do {
// double = double * 10 + (tok - CHAR_0)
long = 10 * long + (c - CHAR_0)
digits++
--exponent
cursor++
if (cursor == limit) break
c = ary[cursor]
} while (c in CHAR_0..CHAR_9)
}
// If we find 'e' we need to convert to double
if (c == CHAR_e || c == CHAR_E) {
useDouble = true
++cursor
checkEOF(data, cursor)
c = ary[cursor]
var negativeExponent = false
if (c == CHAR_MINUS) {
++cursor
checkEOF(data, cursor)
negativeExponent = true
c = ary[cursor]
} else if (c == CHAR_PLUS) {
++cursor
checkEOF(data, cursor)
c = ary[cursor]
}
if (c < CHAR_0 || c > CHAR_9) {
makeError(data, "Missing exponent", c)
}
var exp = 0
do {
val digit = c - CHAR_0
exp = 10 * exp + digit
++cursor
if (cursor == limit) break
c = ary[cursor]
} while (c in CHAR_0..CHAR_9)
exponent += if (negativeExponent) -exp else exp
}
if (digits > 17 || exponent < -19 || exponent > 19) {
// if the float number is not simple enough
// we use language's Double parsing, which is slower but
// produce more expected results for extreme numbers.
val firstPos = readPos - 1
val str = data.getString(firstPos, cursor - firstPos)
if (useDouble) {
double = str.toDouble()
output[key] = double
} else {
long = str.toLong()
output[key] = long
}
} else {
// this happens on single numbers outside any object
// or array
if (useDouble || exponent != 0) {
double = if (long == 0L) 0.0 else long.toDouble() * 10.0.pow(exponent)
double *= sign
output[key] = double
} else {
long *= sign
output[key] = long
}
}
readPos = cursor
return if (useDouble) T_FLOAT else T_INT
}
private fun parseString(data: ReadBuffer, key: String?): FlexBufferType {
output[key] = readString(data)
return T_STRING
}
private fun readString(data: ReadBuffer): String {
val limit = data.limit
if (data is ArrayReadBuffer) {
val ary = data.data()
// enables range check elimination
return readString(data, limit) { ary[it] }
}
return readString(data, limit) { data[it] }
}
private inline fun readString(data: ReadBuffer, limit: Int, crossinline fetch: (Int) -> Byte): String {
var cursorPos = readPos
var foundEscape = false
var currentChar: Byte = 0
// we loop over every 4 bytes until find any non-plain char
while (limit - cursorPos >= 4) {
currentChar = fetch(cursorPos)
if (!isPlainStringChar(currentChar)) {
foundEscape = true
break
}
currentChar = fetch(cursorPos + 1)
if (!isPlainStringChar(currentChar)) {
cursorPos += 1
foundEscape = true
break
}
currentChar = fetch(cursorPos + 2)
if (!isPlainStringChar(currentChar)) {
cursorPos += 2
foundEscape = true
break
}
currentChar = fetch(cursorPos + 3)
if (!isPlainStringChar(currentChar)) {
cursorPos += 3
foundEscape = true
break
}
cursorPos += 4
}
if (!foundEscape) {
// if non-plain string char is not found we loop over
// the remaining bytes
while (true) {
if (cursorPos >= limit) {
error("Unexpected end of string")
}
currentChar = fetch(cursorPos)
if (!isPlainStringChar(currentChar)) {
break
}
++cursorPos
}
}
if (currentChar == CHAR_DOUBLE_QUOTE) {
val str = data.getString(readPos, cursorPos - readPos)
readPos = cursorPos + 1
return str
}
if (currentChar in 0..0x1f) {
error("Illegal Codepoint")
} else {
// backslash or >0x7f
return readStringSlow(data, currentChar, cursorPos)
}
}
private fun readStringSlow(data: ReadBuffer, first: Byte, lastPos: Int): String {
var cursorPos = lastPos
var endOfString = lastPos
while (true) {
val pos = data.findFirst(CHAR_DOUBLE_QUOTE, endOfString)
when {
pos == -1 -> makeError(data, "Unexpected EOF, missing end of string '\"'", first)
data[pos - 1] == CHAR_BACKSLASH && data[pos - 2] != CHAR_BACKSLASH -> {
// here we are checking for double quotes preceded by backslash. eg \"
// we have to look past pos -2 to make sure that the backlash is not
// part of a previous escape, eg "\\"
endOfString = pos + 1
}
else -> {
endOfString = pos; break
}
}
}
// copy everything before the escape
val builder = StringBuilder(data.getString(readPos, lastPos - readPos))
while (true) {
when (val pos = data.findFirst(CHAR_BACKSLASH, cursorPos, endOfString)) {
-1 -> {
val doubleQuotePos = data.findFirst(CHAR_DOUBLE_QUOTE, cursorPos)
if (doubleQuotePos == -1) makeError(data, "Reached EOF before enclosing string", first)
val rest = data.getString(cursorPos, doubleQuotePos - cursorPos)
builder.append(rest)
readPos = doubleQuotePos + 1
return builder.toString()
}
else -> {
// we write everything up to \
builder.append(data.getString(cursorPos, pos - cursorPos))
val c = data[pos + 1]
builder.append(readEscapedChar(data, c, pos))
cursorPos = pos + if (c == CHAR_u) 6 else 2
}
}
}
}
private inline fun isPlainStringChar(c: Byte): Boolean {
val flags = parseFlags
// return c in 0x20..0x7f && c != 0x22.toByte() && c != 0x5c.toByte()
return (flags[c.toInt() and 0xFF] and 1) != 0.toByte()
}
private inline fun isWhitespace(c: Byte): Boolean {
val flags = parseFlags
// return c == '\r'.toByte() || c == '\n'.toByte() || c == '\t'.toByte() || c == ' '.toByte()
return (flags[c.toInt() and 0xFF] and 2) != 0.toByte()
}
private fun reset() {
readPos = 0
output.clear()
scopes.reset()
}
private fun nextToken(data: ReadBuffer): Token {
val scope = this.scopes.last
when (scope) {
SCOPE_ARRAY_EMPTY -> this.scopes.last = SCOPE_ARRAY_FILLED
SCOPE_ARRAY_FILLED -> {
when (val c = skipWhitespace(data)) {
CHAR_CLOSE_ARRAY -> return TOK_END_ARRAY
CHAR_COMMA -> Unit
else -> makeError(data, "Unfinished Array", c)
}
}
SCOPE_OBJ_EMPTY, SCOPE_OBJ_FILLED -> {
this.scopes.last = SCOPE_OBJ_KEY
// Look for a comma before the next element.
if (scope == SCOPE_OBJ_FILLED) {
when (val c = skipWhitespace(data)) {
CHAR_CLOSE_OBJECT -> return TOK_END_OBJECT
CHAR_COMMA -> Unit
else -> makeError(data, "Unfinished Object", c)
}
}
return when (val c = skipWhitespace(data)) {
CHAR_DOUBLE_QUOTE -> TOK_BEGIN_QUOTE
CHAR_CLOSE_OBJECT -> if (scope != SCOPE_OBJ_FILLED) {
TOK_END_OBJECT
} else {
makeError(data, "Expected Key", c)
}
else -> {
makeError(data, "Expected Key/Value", c)
}
}
}
SCOPE_OBJ_KEY -> {
this.scopes.last = SCOPE_OBJ_FILLED
when (val c = skipWhitespace(data)) {
CHAR_COLON -> Unit
else -> makeError(data, "Expect ${CHAR_COLON.print()}", c)
}
}
SCOPE_DOC_EMPTY -> this.scopes.last = SCOPE_DOC_FILLED
SCOPE_DOC_FILLED -> {
val c = skipWhitespace(data)
if (c != CHAR_EOF)
makeError(data, "Root object already finished", c)
return TOK_EOF
}
}
val c = skipWhitespace(data)
when (c) {
CHAR_CLOSE_ARRAY -> if (scope == SCOPE_ARRAY_EMPTY) return TOK_END_ARRAY
CHAR_COLON -> makeError(data, "Unexpected character", c)
CHAR_DOUBLE_QUOTE -> return TOK_BEGIN_QUOTE
CHAR_OPEN_ARRAY -> return TOK_BEGIN_ARRAY
CHAR_OPEN_OBJECT -> return TOK_BEGIN_OBJECT
CHAR_t -> {
checkEOF(data, readPos + 2)
// 0x65757274 is equivalent to ['t', 'r', 'u', 'e' ] as a 4 byte Int
if (data.getInt(readPos - 1) != 0x65757274) {
makeError(data, "Expecting keyword \"true\"", c)
}
readPos += 3
return TOK_TRUE
}
CHAR_n -> {
checkEOF(data, readPos + 2)
// 0x6c6c756e is equivalent to ['n', 'u', 'l', 'l' ] as a 4 byte Int
if (data.getInt(readPos - 1) != 0x6c6c756e) {
makeError(data, "Expecting keyword \"null\"", c)
}
readPos += 3
return TOK_NULL
}
CHAR_f -> {
checkEOF(data, readPos + 3)
// 0x65736c61 is equivalent to ['a', 'l', 's', 'e' ] as a 4 byte Int
if (data.getInt(readPos) != 0x65736c61) {
makeError(data, "Expecting keyword \"false\"", c)
}
readPos += 4
return TOK_FALSE
}
CHAR_0, CHAR_1, CHAR_2, CHAR_3, CHAR_4, CHAR_5,
CHAR_6, CHAR_7, CHAR_8, CHAR_9, CHAR_MINUS -> return TOK_NUMBER.also {
readPos-- // rewind one position so we don't lose first digit
}
}
makeError(data, "Expecting element", c)
}
// keeps increasing [readPos] until finds a non-whitespace byte
private inline fun skipWhitespace(data: ReadBuffer): Byte {
val limit = data.limit
if (data is ArrayReadBuffer) {
// enables range check elimination
val ary = data.data()
return skipWhitespace(limit) { ary[it] }
}
return skipWhitespace(limit) { data[it] }
}
private inline fun skipWhitespace(limit: Int, crossinline fetch: (Int) -> Byte): Byte {
var pos = readPos
while (pos < limit) {
val d = fetch(pos++)
if (!isWhitespace(d)) {
readPos = pos
return d
}
}
readPos = limit
return CHAR_EOF
}
// byte1 is expected to be first char before `\`
private fun readEscapedChar(data: ReadBuffer, byte1: Byte, cursorPos: Int): Char {
return when (byte1) {
CHAR_u -> {
checkEOF(data, cursorPos + 1 + 4)
var result: Char = 0.toChar()
var i = cursorPos + 2 // cursorPos is on '\\', cursorPos + 1 is 'u'
val end = i + 4
while (i < end) {
val part: Byte = data[i]
result = (result.toInt() shl 4).toChar()
result += when (part) {
in CHAR_0..CHAR_9 -> part - CHAR_0
in CHAR_a..CHAR_f -> part - CHAR_a + 10
in CHAR_A..CHAR_F -> part - CHAR_A + 10
else -> makeError(data, "Invalid utf8 escaped character", -1)
}
i++
}
result
}
CHAR_b -> '\b'
CHAR_t -> '\t'
CHAR_r -> '\r'
CHAR_n -> '\n'
CHAR_f -> 12.toChar() // '\f'
CHAR_DOUBLE_QUOTE, CHAR_BACKSLASH, CHAR_FORWARDSLASH -> byte1.toChar()
else -> makeError(data, "Invalid escape sequence.", byte1)
}
}
private fun Byte.print(): String = when (this) {
in 0x21..0x7E -> "'${this.toChar()}'" // visible ascii chars
CHAR_EOF -> "EOF"
else -> "'0x${this.toString(16)}'"
}
private inline fun makeError(data: ReadBuffer, msg: String, tok: Byte? = null): Nothing {
val (line, column) = calculateErrorPosition(data, readPos)
if (tok != null) {
error("Error At ($line, $column): $msg, got ${tok.print()}")
} else {
error("Error At ($line, $column): $msg")
}
}
private inline fun makeError(data: ReadBuffer, msg: String, tok: Token): Nothing {
val (line, column) = calculateErrorPosition(data, readPos)
error("Error At ($line, $column): $msg, got ${tok.print()}")
}
private inline fun checkEOF(data: ReadBuffer, pos: Int) {
if (pos >= data.limit)
makeError(data, "Unexpected end of file", -1)
}
private fun calculateErrorPosition(data: ReadBuffer, endPos: Int): Pair<Int, Int> {
var line = 1
var column = 1
var current = 0
while (current < endPos - 1) {
if (data[current++] == CHAR_NEWLINE) {
++line
column = 1
} else {
++column
}
}
return Pair(line, column)
}
}
internal inline fun Int.toPaddedHex(): String = "\\u${this.toString(16).padStart(4, '0')}"
private inline fun ReadWriteBuffer.jsonEscape(data: ReadBuffer, start: Int, size: Int) {
val replacements = JSON_ESCAPE_CHARS
put(CHAR_DOUBLE_QUOTE)
var last = start
val length: Int = size
val ary = data.data()
for (i in start until start + length) {
val c = ary[i].toUByte()
var replacement: ByteArray?
if (c.toInt() < 128) {
replacement = replacements[c.toInt()]
if (replacement == null) {
continue
}
} else {
continue
}
if (last < i) {
put(ary, last, i - last)
}
put(replacement, 0, replacement.size)
last = i + 1
}
if (last < (last + length)) {
put(ary, last, (start + length) - last)
}
put(CHAR_DOUBLE_QUOTE)
}
// Following escape strategy defined in RFC7159.
private val JSON_ESCAPE_CHARS: Array<ByteArray?> = arrayOfNulls<ByteArray>(128).apply {
this['\n'.toInt()] = "\\n".encodeToByteArray()
this['\t'.toInt()] = "\\t".encodeToByteArray()
this['\r'.toInt()] = "\\r".encodeToByteArray()
this['\b'.toInt()] = "\\b".encodeToByteArray()
this[0x0c] = "\\f".encodeToByteArray()
this['"'.toInt()] = "\\\"".encodeToByteArray()
this['\\'.toInt()] = "\\\\".encodeToByteArray()
for (i in 0..0x1f) {
this[i] = "\\u${i.toPaddedHex()}".encodeToByteArray()
}
}
// Scope is used to the define current space that the scanner is operating.
private inline class Scope(val id: Int)
private val SCOPE_DOC_EMPTY = Scope(0)
private val SCOPE_DOC_FILLED = Scope(1)
private val SCOPE_OBJ_EMPTY = Scope(2)
private val SCOPE_OBJ_KEY = Scope(3)
private val SCOPE_OBJ_FILLED = Scope(4)
private val SCOPE_ARRAY_EMPTY = Scope(5)
private val SCOPE_ARRAY_FILLED = Scope(6)
// Keeps the stack state of the scopes being scanned. Currently defined to have a
// max stack size of 22, as per tests cases defined in http://json.org/JSON_checker/
private class ScopeStack(
private val ary: IntArray = IntArray(22) { SCOPE_DOC_EMPTY.id },
var lastPos: Int = 0
) {
var last: Scope
get() = Scope(ary[lastPos])
set(x) {
ary[lastPos] = x.id
}
fun reset() {
lastPos = 0
ary[0] = SCOPE_DOC_EMPTY.id
}
fun pop(): Scope {
// println("Popping: ${last.print()}")
return Scope(ary[lastPos--])
}
fun push(scope: Scope): Scope {
if (lastPos == ary.size - 1)
error("Too much nesting reached. Max nesting is ${ary.size} levels")
// println("PUSHING : ${scope.print()}")
ary[++lastPos] = scope.id
return scope
}
}
private inline class Token(val id: Int) {
fun print(): String = when (this) {
TOK_EOF -> "TOK_EOF"
TOK_NONE -> "TOK_NONE"
TOK_BEGIN_OBJECT -> "TOK_BEGIN_OBJECT"
TOK_END_OBJECT -> "TOK_END_OBJECT"
TOK_BEGIN_ARRAY -> "TOK_BEGIN_ARRAY"
TOK_END_ARRAY -> "TOK_END_ARRAY"
TOK_NUMBER -> "TOK_NUMBER"
TOK_TRUE -> "TOK_TRUE"
TOK_FALSE -> "TOK_FALSE"
TOK_NULL -> "TOK_NULL"
TOK_BEGIN_QUOTE -> "TOK_BEGIN_QUOTE"
else -> this.toString()
}
}
private val TOK_EOF = Token(-1)
private val TOK_NONE = Token(0)
private val TOK_BEGIN_OBJECT = Token(1)
private val TOK_END_OBJECT = Token(2)
private val TOK_BEGIN_ARRAY = Token(3)
private val TOK_END_ARRAY = Token(4)
private val TOK_NUMBER = Token(5)
private val TOK_TRUE = Token(6)
private val TOK_FALSE = Token(7)
private val TOK_NULL = Token(8)
private val TOK_BEGIN_QUOTE = Token(9)
private const val CHAR_NEWLINE = '\n'.toByte()
private const val CHAR_OPEN_OBJECT = '{'.toByte()
private const val CHAR_COLON = ':'.toByte()
private const val CHAR_CLOSE_OBJECT = '}'.toByte()
private const val CHAR_OPEN_ARRAY = '['.toByte()
private const val CHAR_CLOSE_ARRAY = ']'.toByte()
private const val CHAR_DOUBLE_QUOTE = '"'.toByte()
private const val CHAR_BACKSLASH = '\\'.toByte()
private const val CHAR_FORWARDSLASH = '/'.toByte()
private const val CHAR_f = 'f'.toByte()
private const val CHAR_a = 'a'.toByte()
private const val CHAR_r = 'r'.toByte()
private const val CHAR_t = 't'.toByte()
private const val CHAR_n = 'n'.toByte()
private const val CHAR_b = 'b'.toByte()
private const val CHAR_e = 'e'.toByte()
private const val CHAR_E = 'E'.toByte()
private const val CHAR_u = 'u'.toByte()
private const val CHAR_A = 'A'.toByte()
private const val CHAR_F = 'F'.toByte()
private const val CHAR_EOF = (-1).toByte()
private const val CHAR_COMMA = ','.toByte()
private const val CHAR_0 = '0'.toByte()
private const val CHAR_1 = '1'.toByte()
private const val CHAR_2 = '2'.toByte()
private const val CHAR_3 = '3'.toByte()
private const val CHAR_4 = '4'.toByte()
private const val CHAR_5 = '5'.toByte()
private const val CHAR_6 = '6'.toByte()
private const val CHAR_7 = '7'.toByte()
private const val CHAR_8 = '8'.toByte()
private const val CHAR_9 = '9'.toByte()
private const val CHAR_MINUS = '-'.toByte()
private const val CHAR_PLUS = '+'.toByte()
private const val CHAR_DOT = '.'.toByte()
// This template utilizes the One Definition Rule to create global arrays in a
// header. As seen in:
// https://github.com/chadaustin/sajson/blob/master/include/sajson.h
// bit 0 (1) - set if: plain ASCII string character
// bit 1 (2) - set if: whitespace
// bit 4 (0x10) - set if: 0-9 e E .
private val parseFlags = byteArrayOf(
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
3, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0x11, 1, // 2
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 1, 1, 1, 1, 1, 1, // 3
1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 5
1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7
// 128-255
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
)
| apache-2.0 | 25210a44eef28c084221af99d030c11a | 30.822464 | 115 | 0.584311 | 3.41884 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/util/shortenUtils.kt | 1 | 2741 | // 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.util
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.analysis.api.analyse
import org.jetbrains.kotlin.analysis.api.components.ShortenOption
import org.jetbrains.kotlin.analysis.api.components.ShortenOption.Companion.defaultCallableShortenOption
import org.jetbrains.kotlin.analysis.api.components.ShortenOption.Companion.defaultClassShortenOption
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassLikeSymbol
import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT
import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
/**
* Shorten references in the given [element]. See [shortenReferencesInRange] for more details.
*/
fun shortenReferences(
element: KtElement,
classShortenOption: (KtClassLikeSymbol) -> ShortenOption = defaultClassShortenOption,
callableShortenOption: (KtCallableSymbol) -> ShortenOption = defaultCallableShortenOption
): Unit = shortenReferencesInRange(
element.containingKtFile,
element.textRange,
classShortenOption,
callableShortenOption
)
/**
* Shorten references in the given [file] and [range]. The function must be invoked on EDT thread because it modifies the underlying
* PSI. This method analyse Kotlin code and hence could block the EDT thread for longer period of time. Hence, this method should be
* called only to shorten references in *newly generated code* by IDE actions. In other cases, please consider using
* [org.jetbrains.kotlin.analysis.api.components.KtReferenceShortenerMixIn] in a background thread to perform the analysis and then
* modify PSI on the EDt thread by invoking [org.jetbrains.kotlin.analysis.api.components.ShortenCommand.invokeShortening]. */
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
fun shortenReferencesInRange(
file: KtFile,
range: TextRange = file.textRange,
classShortenOption: (KtClassLikeSymbol) -> ShortenOption = defaultClassShortenOption,
callableShortenOption: (KtCallableSymbol) -> ShortenOption = defaultCallableShortenOption
) {
ApplicationManager.getApplication().assertIsDispatchThread()
val shortenCommand = hackyAllowRunningOnEdt {
analyse(file) {
collectPossibleReferenceShortenings(file, range, classShortenOption, callableShortenOption)
}
}
shortenCommand.invokeShortening()
}
| apache-2.0 | ec56cce2b835c1db4fe3cd4c3bd070bc | 51.711538 | 158 | 0.808099 | 4.464169 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt | 2 | 10878 | // 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.roots
import com.intellij.conversion.*
import com.intellij.conversion.impl.ConversionContextImpl
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.ApplicationLibraryTable
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryKindRegistry
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jdom.Element
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.*
import org.jetbrains.kotlin.config.getFacetPlatformByConfigurationElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil
import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil
import org.jetbrains.kotlin.idea.framework.getLibraryJar
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.utils.PathUtil
import java.util.*
private val rootTypesToMigrate: List<JpsModuleSourceRootType<*>> = listOf(
JavaSourceRootType.SOURCE,
JavaSourceRootType.TEST_SOURCE,
JavaResourceRootType.RESOURCE,
JavaResourceRootType.TEST_RESOURCE
)
// TODO(dsavvinov): review how it behaves in HMPP environment
private val PLATFORM_TO_STDLIB_DETECTORS: Map<TargetPlatform, (Array<VirtualFile>) -> Boolean> = mapOf(
JvmPlatforms.unspecifiedJvmPlatform to { roots: Array<VirtualFile> ->
JavaRuntimeDetectionUtil.getRuntimeJar(roots.toList()) != null
},
JsPlatforms.defaultJsPlatform to { roots: Array<VirtualFile> ->
JsLibraryStdDetectionUtil.getJsStdLibJar(roots.toList()) != null
},
CommonPlatforms.defaultCommonPlatform to { roots: Array<VirtualFile> ->
getLibraryJar(roots, PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN) != null
}
)
internal class KotlinNonJvmSourceRootConverterProvider : ConverterProvider() {
sealed class LibInfo {
class ByXml(
private val element: Element,
private val conversionContext: ConversionContext,
private val moduleSettings: ModuleSettings
) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = LibraryKindRegistry.getInstance().findKindById(element.getAttributeValue("type")) as? PersistentLibraryKind<*>
override fun getRoots(): Array<VirtualFile> {
val contextImpl = conversionContext as? ConversionContextImpl ?: return VirtualFile.EMPTY_ARRAY
val classRoots = contextImpl.getClassRootUrls(element, moduleSettings)
val jarFileSystem = JarFileSystem.getInstance()
return classRoots
.map {
if (it.startsWith(JarFileSystem.PROTOCOL_PREFIX)) {
jarFileSystem.findFileByPath(it.substring(JarFileSystem.PROTOCOL_PREFIX.length))
} else {
null
}
}
.filter(Objects::nonNull)
.toArray{ arrayOfNulls<VirtualFile>(it) }
}
}
class ByLibrary(private val library: Library) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = (library as? LibraryEx)?.kind
override fun getRoots(): Array<VirtualFile> = library.getFiles(OrderRootType.CLASSES)
}
abstract val explicitKind: PersistentLibraryKind<*>?
abstract fun getRoots(): Array<VirtualFile>
val stdlibPlatform: TargetPlatform? by lazy {
val roots = getRoots()
for ((platform, detector) in PLATFORM_TO_STDLIB_DETECTORS) {
if (detector.invoke(roots)) {
return@lazy platform
}
}
return@lazy null
}
}
class ConverterImpl(private val context: ConversionContext) : ProjectConverter() {
private val projectLibrariesByName by lazy {
context.projectLibrariesSettings.projectLibraries.groupBy { it.getAttributeValue(NAME_ATTRIBUTE) }
}
private fun findGlobalLibrary(name: String) = ApplicationLibraryTable.getApplicationTable().getLibraryByName(name)
private fun findProjectLibrary(name: String) = projectLibrariesByName[name]?.firstOrNull()
private fun createLibInfo(orderEntryElement: Element, moduleSettings: ModuleSettings): LibInfo? {
return when (orderEntryElement.getAttributeValue("type")) {
MODULE_LIBRARY_TYPE -> {
orderEntryElement.getChild(LIBRARY_TAG)?.let { LibInfo.ByXml(it, context, moduleSettings) }
}
LIBRARY_TYPE -> {
val libraryName = orderEntryElement.getAttributeValue(NAME_ATTRIBUTE) ?: return null
when (orderEntryElement.getAttributeValue(LEVEL_ATTRIBUTE)) {
LibraryTablesRegistrar.PROJECT_LEVEL ->
findProjectLibrary(libraryName)?.let { LibInfo.ByXml(it, context, moduleSettings) }
LibraryTablesRegistrar.APPLICATION_LEVEL ->
findGlobalLibrary(libraryName)?.let { LibInfo.ByLibrary(it) }
else ->
null
}
}
else -> null
}
}
override fun createModuleFileConverter(): ConversionProcessor<ModuleSettings> {
return object : ConversionProcessor<ModuleSettings>() {
private fun ModuleSettings.detectPlatformByFacet(): TargetPlatform? {
return getFacetElement(KotlinFacetType.ID)
?.getChild(JpsFacetSerializer.CONFIGURATION_TAG)
?.getFacetPlatformByConfigurationElement()
}
private fun detectPlatformByDependencies(moduleSettings: ModuleSettings): TargetPlatform? {
var hasCommonStdlib = false
moduleSettings.orderEntries
.asSequence()
.mapNotNull { createLibInfo(it, moduleSettings) }
.forEach {
val stdlibPlatform = it.stdlibPlatform
if (stdlibPlatform != null) {
if (stdlibPlatform.isCommon()) {
hasCommonStdlib = true
} else {
return stdlibPlatform
}
}
}
return if (hasCommonStdlib) CommonPlatforms.defaultCommonPlatform else null
}
private fun ModuleSettings.detectPlatform(): TargetPlatform {
return detectPlatformByFacet()
?: detectPlatformByDependencies(this)
?: JvmPlatforms.unspecifiedJvmPlatform
}
private fun ModuleSettings.getSourceFolderElements(): List<Element> {
val rootManagerElement = getComponentElement(ModuleSettings.MODULE_ROOT_MANAGER_COMPONENT) ?: return emptyList()
return rootManagerElement
.getChildren(CONTENT_TAG)
.flatMap { it.getChildren(SOURCE_FOLDER_TAG) }
}
@Suppress("UnstableApiUsage")
private fun ModuleSettings.isExternalModule(): Boolean {
return when {
rootElement.getAttributeValue(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) != null -> true
rootElement.getAttributeValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY)?.toBoolean() ?: false -> true
else -> false
}
}
override fun isConversionNeeded(settings: ModuleSettings): Boolean {
if (settings.isExternalModule()) return false
val hasMigrationRoots = settings.getSourceFolderElements().any {
loadSourceRoot(it).rootType in rootTypesToMigrate
}
if (!hasMigrationRoots) {
return false
}
val targetPlatform = settings.detectPlatform()
return (!targetPlatform.isJvm())
}
override fun process(settings: ModuleSettings) {
for (sourceFolder in settings.getSourceFolderElements()) {
val contentRoot = sourceFolder.parent as? Element ?: continue
val oldSourceRoot = loadSourceRoot(sourceFolder)
val (newRootType, data) = oldSourceRoot.getMigratedSourceRootTypeWithProperties() ?: continue
val url = sourceFolder.getAttributeValue(URL_ATTRIBUTE)!!
@Suppress("UNCHECKED_CAST")
val newSourceRoot = JpsElementFactory.getInstance().createModuleSourceRoot(url, newRootType, data)
as? JpsTypedModuleSourceRoot<JpsElement> ?: continue
contentRoot.removeContent(sourceFolder)
saveSourceRoot(contentRoot, url, newSourceRoot)
}
}
}
}
}
override fun getConversionDescription() =
KotlinBundle.message("roots.description.text.update.source.roots.for.non.jvm.modules.in.kotlin.project")
override fun createConverter(context: ConversionContext) = ConverterImpl(context)
} | apache-2.0 | 6569e609862042c76a17078646f79e98 | 46.92511 | 134 | 0.629987 | 5.854682 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2018/Day10.kt | 1 | 2170 | package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.Rectangle
import com.nibado.projects.advent.resourceLines
import kotlin.math.max
import kotlin.math.min
object Day10 : Day {
private val input = resourceLines(2018, 10).map(::parse)
private val solution: Pair<String, Int> by lazy { solve() }
private fun parse(line: String) = line.split("[^0-9-]+".toRegex())
.filterNot { it.trim().isEmpty() }.map { it.toInt() }
.let { (x, y, dx, dy) -> Star(Point(x, y), Point(dx, dy)) }
private fun toString(stars: List<Star>): String {
val points = stars.map { it.loc }.toSet()
val rect = Rectangle.containing(points)
val builder = StringBuilder()
for (y in rect.left.y..rect.right.y) {
for (x in rect.left.x..rect.right.x) {
builder.append(if (points.contains(Point(x, y))) {
'#'
} else {
'.'
})
}
builder.append('\n')
}
return builder.toString()
}
private fun area(stars: List<Star>) = stars
.fold(listOf(Int.MAX_VALUE, Int.MAX_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)) { (minX, minY, maxX, maxY), s ->
listOf(min(minX, s.loc.x), min(minY, s.loc.y), max(maxX, s.loc.x), max(maxY, s.loc.y))
}
.let { (minX, minY, maxX, maxY) -> (maxX - minX).toLong() * (maxY - minY).toLong() }
private fun solve(): Pair<String, Int> {
var stars = input
var second = 0
var area = Long.MAX_VALUE
while (true) {
val next = stars.map { it.copy(loc = it.loc + it.velocity) }
val nextArea = area(next)
if (area < nextArea) {
break
}
second++
stars = next
area = nextArea
}
return toString(stars) to second
}
override fun part1() = Day10Ocr.ocr(solution.first)
override fun part2() = solution.second
data class Star(val loc: Point, val velocity: Point)
} | mit | f5e78c6a2b404d201201040f851ceb5e | 31.893939 | 118 | 0.547926 | 3.703072 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/ESUploader.kt | 4 | 2193 | // 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.perf.util
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.kotlin.idea.performance.tests.utils.logMessage
object ESUploader {
var host: String? = null
var username: String? = null
var password: String? = null
var indexName = "kotlin_ide_benchmarks"
private val JSON: MediaType = "application/json; charset=utf-8".toMediaType()
private val client = OkHttpClient()
init {
host = System.getenv("ES_HOSTNAME") ?: System.getenv("es.hostname")
username = System.getenv("ES_USERNAME") ?: System.getenv("es.username")
password = System.getenv("ES_PASSWORD") ?: System.getenv("es.password")
logMessage { "initialized es details $username @ $host" }
}
fun upload(benchmark: Benchmark) {
if (host == null) {
logMessage { "ES host is not specified, ${benchmark.id()} would not be uploaded" }
return
}
val url = "$host/$indexName/_doc/${benchmark.id()}"
val auth = if (username != null && password != null) {
Credentials.basic(username!!, password!!)
} else {
null
}
val json = kotlinJsonMapper.writeValueAsString(benchmark)
val body: RequestBody = json.toRequestBody(JSON)
val request: Request = Request.Builder()
.url(url)
.post(body)
.header("Content-Type", "application/json")
.also { builder ->
auth?.let {
builder.header("Authorization", it)
}
}
.build()
client.newCall(request).execute().use { response ->
val code = response.code
val string = response.body?.string()
logMessage { "$code -> $string" }
if (code != 200 && code != 201) {
throw IllegalStateException("Error code $code -> $string")
}
}
}
} | apache-2.0 | bf17e14af69e4acd831b091b1e802cf3 | 34.967213 | 158 | 0.593707 | 4.484663 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/FirstWizardStepComponent.kt | 2 | 9975 | // 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.tools.projectWizard.wizard.ui.firstStep
import com.intellij.icons.AllIcons
import com.intellij.ide.util.projectWizard.JavaModuleBuilder
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.roots.ui.configuration.JdkComboBox
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.TitledSeparator
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.kotlin.idea.statistics.WizardStatsService
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.wizard.IdeWizard
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.*
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.PathSettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.StringSettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.TitledComponentsList
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.createSettingComponent
import java.awt.Cursor
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
class FirstWizardStepComponent(ideWizard: IdeWizard) : WizardStepComponent(ideWizard.context) {
private val projectSettingsComponent = ProjectSettingsComponent(ideWizard).asSubComponent()
override val component: JComponent = projectSettingsComponent.component
}
class ProjectSettingsComponent(ideWizard: IdeWizard) : DynamicComponent(ideWizard.context) {
private val context = ideWizard.context
private val projectTemplateComponent = ProjectTemplateSettingComponent(context).asSubComponent()
private val buildSystemSetting = BuildSystemTypeSettingComponent(context).asSubComponent().apply {
component.addBorder(JBUI.Borders.empty(0, /*left&right*/4))
}
private var locationWasUpdatedByHand: Boolean = false
private var artifactIdWasUpdatedByHand: Boolean = false
private val buildSystemAdditionalSettingsComponent =
BuildSystemAdditionalSettingsComponent(
ideWizard,
onUserTypeInArtifactId = { artifactIdWasUpdatedByHand = true },
).asSubComponent()
private val jdkComponent = JdkComponent(ideWizard).asSubComponent()
private val nameAndLocationComponent = TitledComponentsList(
listOf(
StructurePlugin.name.reference.createSettingComponent(context),
StructurePlugin.projectPath.reference.createSettingComponent(context).also {
(it as? PathSettingComponent)?.onUserType { locationWasUpdatedByHand = true }
},
projectTemplateComponent,
buildSystemSetting,
jdkComponent
),
context,
stretchY = true,
useBigYGap = true,
xPadding = 0,
yPadding = 0
).asSubComponent()
override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) {
panel {
row {
cell(nameAndLocationComponent.component)
.align(AlignX.FILL)
.resizableColumn()
bottomGap(BottomGap.SMALL)
}
row {
cell(buildSystemAdditionalSettingsComponent.component)
.align(AlignX.FILL)
.resizableColumn()
bottomGap(BottomGap.SMALL)
}
}.addBorder(IdeBorderFactory.createEmptyBorder(JBInsets(20, 20, 20, 20)))
}
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
when (reference?.path) {
StructurePlugin.name.path -> {
val isNameValid = read { StructurePlugin.name.reference.validate().isOk }
if (isNameValid) {
tryUpdateLocationByProjectName()
tryArtifactIdByProjectName()
}
}
}
}
private fun tryUpdateLocationByProjectName() {
if (!locationWasUpdatedByHand) {
val location = read { StructurePlugin.projectPath.settingValue }
if (location.parent != null) modify {
StructurePlugin.projectPath.reference.setValue(location.resolveSibling(StructurePlugin.name.settingValue))
locationWasUpdatedByHand = false
}
}
}
private fun tryArtifactIdByProjectName() {
if (!artifactIdWasUpdatedByHand) modify {
StructurePlugin.artifactId.reference.setValue(StructurePlugin.name.settingValue)
artifactIdWasUpdatedByHand = false
}
}
}
class BuildSystemAdditionalSettingsComponent(
ideWizard: IdeWizard,
onUserTypeInArtifactId: () -> Unit,
) : DynamicComponent(ideWizard.context) {
private val pomSettingsList = PomSettingsComponent(ideWizard.context, onUserTypeInArtifactId).asSubComponent()
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
if (reference == BuildSystemPlugin.type.reference) {
updateBuildSystemComponent()
}
}
override fun onInit() {
super.onInit()
updateBuildSystemComponent()
}
private fun updateBuildSystemComponent() {
val buildSystemType = read { BuildSystemPlugin.type.settingValue }
section.isVisible = buildSystemType != BuildSystemType.Jps
}
private val section = HideableSection(
KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.artifact.coordinates"),
pomSettingsList.component
)
override val component: JComponent = section
}
private class PomSettingsComponent(context: Context, onUserTypeInArtifactId: () -> Unit) : TitledComponentsList(
listOf(
StructurePlugin.groupId.reference.createSettingComponent(context),
StructurePlugin.artifactId.reference.createSettingComponent(context).also {
(it as? StringSettingComponent)?.onUserType(onUserTypeInArtifactId)
},
StructurePlugin.version.reference.createSettingComponent(context)
),
context,
stretchY = true
)
private class JdkComponent(ideWizard: IdeWizard) : TitledComponent(ideWizard.context) {
private val javaModuleBuilder = JavaModuleBuilder()
private val jdkComboBox: JdkComboBox
private val sdksModel: ProjectSdksModel
init {
val project = ProjectManager.getInstance().defaultProject
sdksModel = ProjectSdksModel()
sdksModel.reset(project)
jdkComboBox = JdkComboBox(
project,
sdksModel,
Condition(javaModuleBuilder::isSuitableSdkType),
null,
null,
null
).apply {
reloadModel()
getDefaultJdk()?.let { jdk -> selectedJdk = jdk }
ideWizard.jdk = selectedJdk
addActionListener {
ideWizard.jdk = selectedJdk
WizardStatsService.logDataOnJdkChanged(ideWizard.context.contextComponents.get())
}
}
}
private fun getDefaultJdk(): Sdk? {
val defaultProject = ProjectManagerEx.getInstanceEx().defaultProject
return ProjectRootManagerEx.getInstanceEx(defaultProject).projectSdk ?: run {
val sdks = ProjectJdkTable.getInstance().allJdks
.filter { it.homeDirectory?.isValid == true && javaModuleBuilder.isSuitableSdkType(it.sdkType) }
.groupBy(Sdk::getSdkType)
.entries.firstOrNull()
?.value?.filterNotNull() ?: return@run null
sdks.maxWithOrNull(sdks.firstOrNull()?.sdkType?.versionComparator() ?: return@run null)
}
}
override val title: String = KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.project.jdk")
override val component: JComponent = jdkComboBox
}
private class HideableSection(@NlsContexts.Separator text: String, component: JComponent) : BorderLayoutPanel() {
private val titledSeparator = TitledSeparator(text)
private val contentPanel = borderPanel {
addBorder(JBUI.Borders.emptyLeft(20))
addToCenter(component)
}
private var isExpanded = false
init {
titledSeparator.label.cursor = Cursor(Cursor.HAND_CURSOR)
addToTop(titledSeparator)
addToCenter(contentPanel)
update(isExpanded)
titledSeparator.addMouseListener(object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) = update(!isExpanded)
})
}
private fun update(isExpanded: Boolean) {
this.isExpanded = isExpanded
contentPanel.isVisible = isExpanded
titledSeparator.label.icon = if (isExpanded) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight
}
} | apache-2.0 | afe305b391eeff97644edff268b1d4b5 | 39.718367 | 122 | 0.712682 | 5.027722 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PlaybackCommandCoroutineAdapter.kt | 4 | 1399 | // 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.ui.playback.commands
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.playback.PlaybackCommand
import com.intellij.openapi.ui.playback.PlaybackContext
import kotlinx.coroutines.launch
import org.jetbrains.annotations.NonNls
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
abstract class PlaybackCommandCoroutineAdapter(protected val text: @NonNls String, protected val line: Int) : PlaybackCommand {
companion object {
const val CMD_PREFIX: @NonNls String = "%"
}
protected abstract suspend fun doExecute(context: PlaybackContext)
fun extractCommandArgument(prefix: String): String {
return if (text.startsWith(prefix)) text.substring(prefix.length).trim { it <= ' ' } else text
}
override fun canGoFurther() = true
override fun execute(context: PlaybackContext): Promise<Any> {
context.code(text, line)
val promise = AsyncPromise<Any>()
ApplicationManager.getApplication().coroutineScope.launch {
doExecute(context)
}.invokeOnCompletion {
if (it == null) {
promise.setResult(null)
}
else {
context.error(text, line)
promise.setError(it)
}
}
return promise
}
} | apache-2.0 | 3727195aeb966e2293dbe08dab1ed1b6 | 32.333333 | 127 | 0.739814 | 4.358255 | false | false | false | false |
zillachan/actor-platform | actor-apps/app-android/src/main/java/im/actor/messenger/app/fragment/dialogs/DialogHolder.kt | 39 | 13388 | package im.actor.messenger.app.fragment.dialogs
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import im.actor.android.view.RootViewType
import im.actor.messenger.R
import im.actor.messenger.app.core.Core.messenger
import im.actor.messenger.app.core.Core.myUid
import im.actor.messenger.app.util.Screen
import im.actor.messenger.app.view.*
import im.actor.messenger.app.view.anko.*
import im.actor.messenger.app.view.emoji.SmileProcessor
import im.actor.messenger.app.view.emoji.SmileProcessor.emoji
import im.actor.messenger.app.view.keyboard.emoji.smiles.SmilesListener
import im.actor.model.entity.Dialog
import im.actor.model.entity.MessageState
import im.actor.model.entity.PeerType
import im.actor.model.mvvm.ValueChangedListener
import im.actor.model.mvvm.ValueModel
import org.jetbrains.anko.*
public class DialogHolder(private val _context: Context, onClickListener: OnItemClickedListener<Dialog>) : AnkoViewHolder(_context) {
private var avatar: AvatarView? = null
private var title: TextView? = null
private var text: TextView? = null
private var time: TextView? = null
private var state: TintImageView? = null
private var counter: TextView? = null
private var separator: View? = null
private var bindedText: CharSequence? = null
private var bindedUid: Int = 0
private var bindedGid: Int = 0
private var privateTypingListener: ValueChangedListener<Boolean>? = null
private var groupTypingListener: ValueChangedListener<IntArray>? = null
private var bindedItem: Dialog? = null
private val pendingColor: Int
private val sentColor: Int
private val receivedColor: Int
private val readColor: Int
private val errorColor: Int
private var binded: Long = 0
init {
val paddingH = Screen.dp(11f)
val paddingV = Screen.dp(9f)
pendingColor = context.getResources().getColor(R.color.chats_state_pending)
sentColor = context.getResources().getColor(R.color.chats_state_sent)
receivedColor = context.getResources().getColor(R.color.chats_state_delivered)
readColor = context.getResources().getColor(R.color.chats_state_read)
errorColor = context.getResources().getColor(R.color.chats_state_error)
with(itemView as FrameLayout) {
layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Screen.dp(73f))
backgroundResource = R.drawable.selector_fill
avatar = avatarView {
init(dip(52), 24f)
val viewLayoutParams = FrameLayout.LayoutParams(Screen.dp(52f), Screen.dp(52f))
viewLayoutParams.gravity = Gravity.CENTER_VERTICAL or Gravity.LEFT
viewLayoutParams.leftMargin = paddingH
layoutParams = viewLayoutParams
}
verticalLayout {
gravity = Gravity.TOP
linearLayout {
title = textView {
textColor = color(R.color.chats_title)
typeface = Fonts.medium()
textSize = 17f
paddingTop = dip(1)
singleLine = true
compoundDrawablePadding = dip(4)
ellipsize = TextUtils.TruncateAt.END
}.layoutParams {
height = wrapContent
width = 0
weight = 1f
}
time = textView {
textColor = color(R.color.chats_time)
typeface = Fonts.regular()
textSize = 13f
paddingLeft = dip(6)
singleLine = true
}
}.layoutParams {
width = matchParent
height = wrapContent
}
text = textView {
typeface = Fonts.regular()
textColor = color(R.color.chats_text)
textSize = 15f
paddingTop = dip(5)
paddingRight = dip(28)
singleLine = true
ellipsize = TextUtils.TruncateAt.END
}.layoutParams {
}
val viewLayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
viewLayoutParams.rightMargin = paddingH
viewLayoutParams.leftMargin = Screen.dp(79f)
viewLayoutParams.topMargin = paddingV
viewLayoutParams.bottomMargin = paddingV
layoutParams = viewLayoutParams
}
separator = view {
backgroundColor = color(R.color.chats_divider)
val viewLayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, context.getResources().getDimensionPixelSize(R.dimen.div_size))
viewLayoutParams.leftMargin = Screen.dp(76f)
viewLayoutParams.gravity = Gravity.BOTTOM
layoutParams = viewLayoutParams
}
state = tintImageView {
val viewLayoutParams = FrameLayout.LayoutParams(Screen.dp(28f), Screen.dp(12f), Gravity.BOTTOM or Gravity.RIGHT)
viewLayoutParams.bottomMargin = dip(16)
viewLayoutParams.rightMargin = dip(9)
layoutParams = viewLayoutParams
}
counter = textView {
textColor = color(R.color.chats_counter)
backgroundColor = color(R.color.chats_counter_bg)
typeface = Fonts.regular()
gravity = Gravity.CENTER
paddingLeft = dip(4)
paddingRight = dip(4)
textSize = 10f
setIncludeFontPadding(false)
minimumWidth = dip(14)
val viewLayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Screen.dp(14f), Gravity.BOTTOM or Gravity.RIGHT)
viewLayoutParams.bottomMargin = dip(12)
viewLayoutParams.rightMargin = dip(10)
layoutParams = viewLayoutParams
}
}
itemView.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
if (bindedItem != null) {
onClickListener.onClicked(bindedItem)
}
}
})
itemView.setOnLongClickListener(object : View.OnLongClickListener {
override fun onLongClick(v: View): Boolean {
if (bindedItem != null) {
return onClickListener.onLongClicked(bindedItem)
}
return false
}
})
}
public fun bind(data: Dialog, isLast: Boolean) {
this.binded = data.getPeer().getUnuqueId()
this.bindedItem = data
avatar!!.bind(data)
if (data.getUnreadCount() > 0) {
counter!!.setText(Integer.toString(data.getUnreadCount()))
counter!!.setVisibility(View.VISIBLE)
} else {
counter!!.setVisibility(View.GONE)
}
title!!.setText(data.getDialogTitle())
var left: Drawable? = null
if (data.getPeer().getPeerType() === PeerType.GROUP) {
left = TintDrawable(R.drawable.dialogs_group, R.color.chats_title, context)
}
title!!.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null)
if (data.getDate() > 0) {
time!!.setVisibility(View.VISIBLE)
time!!.setText(messenger().getFormatter().formatShortDate(data.getDate()))
} else {
time!!.setVisibility(View.GONE)
}
// Bypass bypass = new Bypass(context);
// bindedText = bypass.markdownToSpannable(messenger().getFormatter().formatDialogText(data), true);
bindedText = messenger().getFormatter().formatDialogText(data)
if (SmileProcessor.containsEmoji(bindedText)) {
if (emoji().isLoaded()) {
bindedText = emoji().processEmojiCompatMutable(bindedText, SmileProcessor.CONFIGURATION_BUBBLES)
} else {
emoji().registerListener(object : SmilesListener {
override fun onSmilesUpdated(completed: Boolean) {
val emojiProcessed = emoji().processEmojiCompatMutable(bindedText, SmileProcessor.CONFIGURATION_DIALOGS)
if (text!!.getText() == bindedText) {
text!!.setText(emojiProcessed)
}
bindedText = emojiProcessed
}
})
}
}
if (privateTypingListener != null) {
messenger().getTyping(bindedUid)!!.unsubscribe(privateTypingListener)
privateTypingListener = null
}
if (groupTypingListener != null) {
messenger().getGroupTyping(bindedGid)!!.unsubscribe(groupTypingListener)
groupTypingListener = null
}
if (data.getPeer().getPeerType() === PeerType.PRIVATE) {
bindedUid = data.getPeer().getPeerId()
privateTypingListener = object : ValueChangedListener<Boolean> {
override fun onChanged(`val`: Boolean?, valueModel: ValueModel<Boolean>) {
if (`val`!!) {
text!!.setText(messenger().getFormatter().formatTyping())
text!!.setTextColor(context.getResources().getColor(R.color.chats_typing))
} else {
text!!.setText(bindedText)
text!!.setTextColor(context.getResources().getColor(R.color.chats_text))
}
}
}
messenger().getTyping(bindedUid)!!.subscribe(privateTypingListener)
} else if (data.getPeer().getPeerType() === PeerType.GROUP) {
bindedGid = data.getPeer().getPeerId()
groupTypingListener = object : ValueChangedListener<IntArray> {
override fun onChanged(`val`: IntArray, valueModel: ValueModel<IntArray>) {
if (`val`.size() != 0) {
if (`val`.size() == 1) {
text!!.setText(messenger().getFormatter().formatTyping(messenger().getUsers()!!.get(`val`[0].toLong()).getName().get()))
} else {
text!!.setText(messenger().getFormatter().formatTyping(`val`.size()))
}
text!!.setTextColor(context.getResources().getColor(R.color.chats_typing))
} else {
text!!.setText(bindedText)
text!!.setTextColor(context.getResources().getColor(R.color.chats_text))
}
}
}
messenger().getGroupTyping(bindedGid)!!.subscribe(groupTypingListener)
} else {
text!!.setText(bindedText)
text!!.setTextColor(context.getResources().getColor(R.color.chats_text))
}
if (data.getSenderId() != myUid()) {
state!!.setVisibility(View.GONE)
} else {
when (data.getStatus()) {
MessageState.SENT -> {
state!!.setResource(R.drawable.msg_check_1)
state!!.setTint(sentColor)
}
MessageState.RECEIVED -> {
state!!.setResource(R.drawable.msg_check_2)
state!!.setTint(receivedColor)
}
MessageState.READ -> {
state!!.setResource(R.drawable.msg_check_2)
state!!.setTint(readColor)
}
MessageState.ERROR -> {
state!!.setResource(R.drawable.msg_error)
state!!.setTint(errorColor)
}
MessageState.PENDING -> {
state!!.setResource(R.drawable.msg_clock)
state!!.setTint(pendingColor)
}
else -> {
state!!.setResource(R.drawable.msg_clock)
state!!.setTint(pendingColor)
}
}
state!!.setVisibility(View.VISIBLE)
}
if (isLast) {
separator!!.setVisibility(View.GONE)
} else {
separator!!.setVisibility(View.VISIBLE)
}
}
public fun unbind() {
this.bindedItem = null
this.avatar!!.unbind()
if (privateTypingListener != null) {
messenger().getTyping(bindedUid)!!.unsubscribe(privateTypingListener)
privateTypingListener = null
}
if (groupTypingListener != null) {
messenger().getGroupTyping(bindedGid)!!.unsubscribe(groupTypingListener)
groupTypingListener = null
}
}
}
| mit | 0f997ecdb0e839e32ee369087ae05eca | 38.964179 | 164 | 0.565805 | 5.053983 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/CoroutineSelectedNodeListener.kt | 3 | 3851 | // 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.debugger.coroutine.view
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.JavaExecutionStack
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.ui.DoubleClickListener
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl
import org.jetbrains.kotlin.analysis.decompiler.stub.file.ClsClassFinder.isKotlinInternalCompiledFile
import org.jetbrains.kotlin.idea.debugger.coroutine.data.RunningCoroutineStackFrameItem
import org.jetbrains.kotlin.idea.debugger.invokeInManagerThread
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
class CoroutineSelectedNodeListener(
private val debugProcess: DebugProcessImpl,
private val tree: XDebuggerTree
) {
fun install() {
object : DoubleClickListener() {
override fun onDoubleClick(e: MouseEvent): Boolean =
processSelectedNode()
}.installOn(tree)
tree.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
val key = e.keyCode
if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_SPACE || key == KeyEvent.VK_RIGHT) {
processSelectedNode()
}
}
})
}
private fun processSelectedNode(): Boolean {
val selectedNodes = tree.getSelectedNodes(XValueNodeImpl::class.java, null)
val valueContainer = selectedNodes.getSingleCoroutineFrameValueContainer() ?: return false
val frameItem = valueContainer.frameItem
val frame = frameItem.createFrame(debugProcess) ?: return false
val executionStack =
if (frameItem is RunningCoroutineStackFrameItem)
createExecutionStack(frameItem.frame.threadProxy(), debugProcess)
else
debugProcess.suspendContext.thread?.let {
createExecutionStack(it, debugProcess)
}
if (executionStack != null) {
setCurrentStackFrame(executionStack, frame)
}
return true
}
private fun setCurrentStackFrame(executionStack: XExecutionStack, stackFrame: XStackFrame) {
val fileToNavigate = stackFrame.sourcePosition?.file ?: return
val session = debugProcess.session.xDebugSession ?: return
if (!isKotlinInternalCompiledFile(fileToNavigate)) {
ApplicationManager.getApplication().invokeLater({
session.setCurrentStackFrame(executionStack, stackFrame, false)
}, ModalityState.stateForComponent(tree))
}
}
}
private fun createExecutionStack(threadReference: ThreadReferenceProxyImpl, debugProcess: DebugProcessImpl): JavaExecutionStack? =
debugProcess.invokeInManagerThread {
val executionStack = JavaExecutionStack(
threadReference,
debugProcess,
debugProcess.suspendContext.thread == threadReference
)
executionStack.initTopFrame()
executionStack
}
private fun Array<XValueNodeImpl>.getSingleCoroutineFrameValueContainer(): CoroutineView.CoroutineFrameValue? =
singleOrNull()?.valueContainer as? CoroutineView.CoroutineFrameValue
private val DebugProcessImpl.suspendContext: SuspendContextImpl
get() = suspendManager.pausedContext
| apache-2.0 | 2281582634f1d6dcde23a2787bbe90cf | 42.761364 | 158 | 0.725266 | 5.121011 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/host/distros/Centos6.kt | 2 | 1163 | package com.github.kerubistan.kerub.host.distros
import com.github.kerubistan.kerub.host.PackageManager
import com.github.kerubistan.kerub.host.checkFileExists
import com.github.kerubistan.kerub.host.getFileContents
import com.github.kerubistan.kerub.host.packman.YumPackageManager
import com.github.kerubistan.kerub.model.Version
import org.apache.sshd.client.session.ClientSession
class Centos6 : AbstractLinux() {
companion object {
private const val redHatReleaseFile = "/etc/redhat-release"
}
override fun getPackageManager(session: ClientSession): PackageManager = YumPackageManager(session)
override fun getVersion(session: ClientSession): Version {
return Version.fromVersionString(
session.getFileContents(redHatReleaseFile).substringAfter("CentOS release").replace(
"(Final)".toRegex(),
"")
)
}
override fun name(): String = "CentOS Linux"
override fun handlesVersion(version: Version): Boolean {
return version.major == "6"
}
override fun detect(session: ClientSession): Boolean =
session.checkFileExists(redHatReleaseFile) &&
session.getFileContents(redHatReleaseFile).startsWith("CentOS release 6")
} | apache-2.0 | c610a3aaeb739a3e54edd555b1bd2383 | 31.333333 | 100 | 0.785039 | 3.996564 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/editor/ComplexPathVirtualFileSystem.kt | 2 | 2929 | // 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.editor
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.vfs.DeprecatedVirtualFileSystem
import com.intellij.openapi.vfs.NonPhysicalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
abstract class ComplexPathVirtualFileSystem<P : ComplexPathVirtualFileSystem.ComplexPath>(
private val pathSerializer: ComplexPathSerializer<P>
) : DeprecatedVirtualFileSystem(), NonPhysicalFileSystem {
protected abstract fun findOrCreateFile(project: Project, path: P): VirtualFile?
fun getPath(path: P): String = pathSerializer.serialize(path)
private fun getComplexPath(path: String): P = pathSerializer.deserialize(path)
private fun getComplexPathSafe(path: String): P? {
return try {
getComplexPath(path)
}
catch (e: Exception) {
LOG.warn("Cannot deserialize $path", e)
return null
}
}
override fun findFileByPath(path: String): VirtualFile? {
val parsedPath = getComplexPathSafe(path) ?: return null
val project = ProjectManagerEx.getInstanceEx().findOpenProjectByHash(parsedPath.projectHash) ?: return null
return findOrCreateFile(project, parsedPath)
}
override fun refreshAndFindFileByPath(path: String) = findFileByPath(path)
override fun extractPresentableUrl(path: String) = (refreshAndFindFileByPath(path) as? VirtualFilePathWrapper)?.presentablePath ?: path
override fun refresh(asynchronous: Boolean) {}
interface ComplexPath {
/**
* [sessionId] is required to differentiate files between launches.
* This is necessary to make the files appear in "Recent Files" correctly.
* Without this field files are saved in [com.intellij.openapi.fileEditor.impl.EditorHistoryManager] via pointers and urls are saved to disk
* After reopening the project manager will try to restore the files and will not find them since necessary components are not ready yet
* and despite this history entry will still be created using a url-only [com.intellij.openapi.vfs.impl.IdentityVirtualFilePointer] via
* [com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl.getOrCreateIdentity] where pointers are cached.
* As a result all previously opened files will be seen by history manager as non-existent.
* Including this [sessionId] helps distinguish files between launches.
*/
val sessionId: String
val projectHash: String
}
interface ComplexPathSerializer<P : ComplexPath> {
fun serialize(path: P): String
fun deserialize(rawPath: String): P
}
companion object {
private val LOG = logger<ComplexPathVirtualFileSystem<ComplexPath>>()
}
}
| apache-2.0 | 99d8b854468fd043c406ce09b261b5be | 43.378788 | 144 | 0.769887 | 4.55521 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithOperatorAssignmentInspection.kt | 4 | 6832 | // 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.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.doNotAnalyze
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceWithOperatorAssignmentInspection : AbstractApplicabilityBasedInspection<KtBinaryExpression>(
KtBinaryExpression::class.java
) {
override fun isApplicable(element: KtBinaryExpression): Boolean {
if (element.operationToken != KtTokens.EQ) return false
val left = element.left as? KtNameReferenceExpression ?: return false
val right = element.right as? KtBinaryExpression ?: return false
if (right.left == null || right.right == null) return false
val bindingContext = right.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (!checkExpressionRepeat(left, right, bindingContext)) return false
// now check that the resulting operator assignment will be resolved
val opAssign = buildOperatorAssignment(element) ?: return false
opAssign.containingKtFile.doNotAnalyze = null //TODO: strange hack
val newBindingContext = opAssign.analyzeAsReplacement(element, bindingContext)
return newBindingContext.diagnostics.forElement(opAssign.operationReference).isEmpty()
}
override fun inspectionText(element: KtBinaryExpression) = KotlinBundle.message("replaceable.with.operator.assignment")
override val defaultFixText get() = KotlinBundle.message("replace.with.operator.assignment")
override fun fixText(element: KtBinaryExpression) =
KotlinBundle.message(
"replace.with.0",
(element.right as? KtBinaryExpression)?.operationReference?.operationSignTokenType?.value.toString() + '='
)
override fun inspectionHighlightType(element: KtBinaryExpression): ProblemHighlightType {
val left = element.left as? KtNameReferenceExpression
if (left != null) {
val context = left.analyze(BodyResolveMode.PARTIAL)
val leftType = left.getType(context)
if (leftType?.isReadOnlyCollectionOrMap(element.builtIns) == true) return ProblemHighlightType.INFORMATION
}
return ProblemHighlightType.GENERIC_ERROR_OR_WARNING
}
private fun checkExpressionRepeat(
variableExpression: KtNameReferenceExpression,
expression: KtBinaryExpression,
bindingContext: BindingContext
): Boolean {
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expression.operationReference]?.containingDeclaration
val isPrimitiveOperation = descriptor is ClassDescriptor && KotlinBuiltIns.isPrimitiveType(descriptor.defaultType)
val operationToken = expression.operationToken
val expressionLeft = expression.left
val expressionRight = expression.right
return when {
variableExpression.matches(expressionLeft) -> {
isArithmeticOperation(operationToken)
}
variableExpression.matches(expressionRight) -> {
isPrimitiveOperation && isCommutative(operationToken)
}
expressionLeft is KtBinaryExpression -> {
val sameCommutativeOperation = expressionLeft.operationToken == operationToken && isCommutative(operationToken)
isPrimitiveOperation && sameCommutativeOperation && checkExpressionRepeat(
variableExpression,
expressionLeft,
bindingContext
)
}
else -> {
false
}
}
}
private fun isCommutative(operationToken: IElementType) = operationToken == KtTokens.PLUS || operationToken == KtTokens.MUL
private fun isArithmeticOperation(operationToken: IElementType) = operationToken == KtTokens.PLUS ||
operationToken == KtTokens.MINUS ||
operationToken == KtTokens.MUL ||
operationToken == KtTokens.DIV ||
operationToken == KtTokens.PERC
override fun applyTo(element: KtBinaryExpression, project: Project, editor: Editor?) {
val operatorAssignment = buildOperatorAssignment(element) ?: return
element.replace(operatorAssignment)
}
private fun buildOperatorAssignment(element: KtBinaryExpression): KtBinaryExpression? {
val variableExpression = element.left as? KtNameReferenceExpression ?: return null
val assignedExpression = element.right as? KtBinaryExpression ?: return null
val replacement = buildOperatorAssignmentText(variableExpression, assignedExpression, "")
return KtPsiFactory(element).createExpression(replacement) as KtBinaryExpression
}
private tailrec fun buildOperatorAssignmentText(
variableExpression: KtNameReferenceExpression,
expression: KtBinaryExpression,
tail: String
): String {
val operationText = expression.operationReference.text
val variableName = variableExpression.text
fun String.appendTail() = if (tail.isEmpty()) this else "$this $tail"
return when {
variableExpression.matches(expression.left) ->
"$variableName $operationText= ${expression.right!!.text}".appendTail()
variableExpression.matches(expression.right) ->
"$variableName $operationText= ${expression.left!!.text}".appendTail()
expression.left is KtBinaryExpression ->
buildOperatorAssignmentText(
variableExpression,
expression.left as KtBinaryExpression,
"$operationText ${expression.right!!.text}".appendTail()
)
else ->
tail
}
}
}
| apache-2.0 | 2a0d07e8884242912c80e3c7df1fdbed | 44.852349 | 127 | 0.712822 | 5.904927 | false | false | false | false |
mglukhikh/intellij-community | platform/script-debugger/backend/src/debugger/SuspendContext.kt | 6 | 2652 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.util.Consumer
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.values.ValueManager
/**
* An object that matches the execution state of the VM while suspended
*/
interface SuspendContext<CALL_FRAME : CallFrame> {
val state: SuspendState
val script: Script?
get() = topFrame?.let { vm.scriptManager.getScript(it) }
/**
* @return the current exception state, or `null` if current state is
* * not `EXCEPTION`
* *
* @see .getState
*/
val exceptionData: ExceptionData?
get() = null
val topFrame: CALL_FRAME?
/**
* Call frames for the current suspended state (from the innermost (top) frame to the main (bottom) frame)
*/
val frames: Promise<Array<CallFrame>>
/**
* list of the breakpoints hit on VM suspension with which this
* context is associated. An empty collection if the suspension was
* not related to hitting breakpoints (e.g. a step end)
*/
val breakpointsHit: List<Breakpoint>
val hasUnresolvedBreakpointsHit: Boolean
get() = false
val valueManager: ValueManager
val vm: Vm
get() = throw UnsupportedOperationException()
}
abstract class ContextDependentAsyncResultConsumer<T>(private val context: SuspendContext<*>) : Consumer<T> {
override final fun consume(result: T) {
val vm = context.vm
if (vm.attachStateManager.isAttached && !vm.suspendContextManager.isContextObsolete(context)) {
consume(result, vm)
}
}
protected abstract fun consume(result: T, vm: Vm)
}
inline fun <T> Promise<T>.done(context: SuspendContext<*>, crossinline handler: (result: T) -> Unit) = done(object : ContextDependentAsyncResultConsumer<T>(context) {
override fun consume(result: T, vm: Vm) = handler(result)
})
inline fun Promise<*>.rejected(context: SuspendContext<*>, crossinline handler: (error: Throwable) -> Unit) = rejected(object : ContextDependentAsyncResultConsumer<Throwable>(context) {
override fun consume(result: Throwable, vm: Vm) = handler(result)
}) | apache-2.0 | e0167152f2b091c7476addea8218a166 | 31.753086 | 185 | 0.722097 | 4.130841 | false | false | false | false |
smmribeiro/intellij-community | platform/markdown-utils/src/com/intellij/markdown/utils/lang/HtmlSyntaxHighlighter.kt | 9 | 2015 | // 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.markdown.utils.lang
import com.intellij.lang.Language
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.ColorUtil
import java.awt.Color
interface HtmlSyntaxHighlighter {
fun color(language: String?, rawContent: String): HtmlChunk
companion object {
fun parseContent(project: Project?,
language: Language,
text: String,
collector: (String, IntRange, Color?) -> Unit) {
val file = LightVirtualFile("markdown_temp", text)
val highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, file)
val colorScheme = EditorColorsManager.getInstance().globalScheme
val lexer = highlighter.highlightingLexer
lexer.start(text)
while (lexer.tokenType != null) {
val type = lexer.tokenType
val highlights = highlighter.getTokenHighlights(type).lastOrNull()
val color = highlights?.let {
colorScheme.getAttributes(it)?.foregroundColor
} ?: highlights?.defaultAttributes?.foregroundColor
collector(lexer.tokenText, lexer.tokenStart..lexer.tokenEnd, color)
lexer.advance()
}
}
fun colorHtmlChunk(project: Project?, language: Language, rawContent: String): HtmlChunk {
val html = HtmlBuilder()
parseContent(project, language, rawContent) { content, _, color ->
html.append(
if (color != null) HtmlChunk.span("color:${ColorUtil.toHtmlColor(color)}").addText(content)
else HtmlChunk.text(content)
)
}
return html.toFragment()
}
}
} | apache-2.0 | 94b0204c27907e7896878f12492ce1e1 | 37.037736 | 120 | 0.703226 | 4.786223 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/experiment/ExperimentConfig.kt | 5 | 1213 | // 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.completion.ml.experiment
import kotlinx.serialization.Serializable
@Serializable
data class ExperimentConfig(val version: Int,
val seed: Long?,
val groups: List<ExperimentGroupConfig>,
val languages: List<ExperimentLanguageConfig>) {
companion object {
private val DISABLED_EXPERIMENT = ExperimentConfig(version = 2, seed = null, groups = emptyList(), languages = emptyList())
fun disabledExperiment(): ExperimentConfig = DISABLED_EXPERIMENT
}
}
@Serializable
data class ExperimentGroupConfig(val number: Int,
val description: String,
val useMLRanking: Boolean,
val showArrows: Boolean,
val calculateFeatures: Boolean)
@Serializable
data class ExperimentLanguageConfig(val id: String,
val experimentBucketsCount: Int,
val includeGroups: List<Int>) | apache-2.0 | 2221c96f31df4eccd390cc056eb231f9 | 43.962963 | 140 | 0.605111 | 5.589862 | false | true | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/sealed.kt | 1 | 2978 | // 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.
@file:JvmName("SealedUtil")
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.util.SmartList
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil
import org.jetbrains.plugins.groovy.lang.psi.util.SealedHelper.inferReferencedClass
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.type
internal fun getAllSealedElements(typeDef : GrTypeDefinition) : List<PsiElement> {
val modifier = typeDef.modifierList?.getModifier(GrModifier.SEALED)
val annotation = typeDef.modifierList?.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_SEALED)
return listOf(modifier, annotation).filterNotNullTo(SmartList())
}
fun GrTypeDefinition.getSealedElement() : PsiElement? = getAllSealedElements(this).firstOrNull()
fun getAllPermittedClassElements(typeDef : GrTypeDefinition) : List<PsiElement> {
var isTypeDefSealed = false
if (typeDef.hasModifierProperty(GrModifier.SEALED)) {
isTypeDefSealed = true
if (typeDef.permitsClause?.keyword != null) {
return typeDef.permitsClause?.referenceElementsGroovy?.toList() ?: emptyList()
}
}
else {
val annotation = typeDef.modifierList?.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_SEALED) as? GrAnnotation
val declaredAttribute = annotation?.findDeclaredAttributeValue("permittedSubclasses")
if (annotation != null) {
isTypeDefSealed = true
if (declaredAttribute != null) {
return AnnotationUtil.arrayAttributeValues(declaredAttribute)
}
}
}
if (isTypeDefSealed) {
val ownerType = typeDef.type()
return (typeDef.containingFile as? GroovyFile)?.classes?.filter { ownerType in it.extendsListTypes || ownerType in it.implementsListTypes }
?: emptyList()
}
return emptyList()
}
// reduce visibility of this function to avoid misuse
object SealedHelper {
fun inferReferencedClass(element : PsiElement) : PsiClass? = when (element) {
is GrCodeReferenceElement -> element.resolve() as? PsiClass
is PsiAnnotationMemberValue -> GrAnnotationUtil.getPsiClass(element)
is PsiClass -> element
else -> null
}
}
fun getAllPermittedClasses(typeDef: GrTypeDefinition): List<PsiClass> =
getAllPermittedClassElements(typeDef).mapNotNull(::inferReferencedClass) | apache-2.0 | 415937bc39a6942e0c5ba1736845baba | 45.546875 | 158 | 0.788784 | 4.532725 | false | false | false | false |
paul58914080/ff4j-spring-boot-starter-parent | ff4j-spring-services/src/main/kotlin/org/ff4j/services/domain/FeatureStoreApiBean.kt | 1 | 1785 | /*-
* #%L
* ff4j-spring-services
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.ff4j.services.domain
import org.ff4j.cache.FF4jCacheProxy
import org.ff4j.core.FeatureStore
import java.io.Serializable
/**
* Created by Paul
*
* @author <a href="mailto:[email protected]">Paul Williams</a>
*/
class FeatureStoreApiBean : Serializable {
companion object {
private const val serialVersionUID = 1868920596870427435L
}
var type: String? = null
var numberOfFeatures: Int = 0
var numberOfGroups: Int = 0
var features: MutableList<String> = ArrayList()
var groups: MutableList<String> = ArrayList()
var cache: CacheApiBean? = null
constructor() : super()
constructor(featureStore: FeatureStore) {
type = featureStore.javaClass.canonicalName
if (isInstanceOfCache(featureStore)) {
cache = CacheApiBean(featureStore)
}
features = ArrayList(featureStore.readAll().keys)
groups = ArrayList(featureStore.readAllGroups())
numberOfFeatures = features.size
numberOfGroups = groups.size
}
private fun isInstanceOfCache(featureStore: FeatureStore) = featureStore is FF4jCacheProxy
}
| apache-2.0 | 60e23a48ee6a38b925fcde5a63496a9a | 29.775862 | 94 | 0.701961 | 4.038462 | false | false | false | false |
AlexKrupa/kotlin-koans | src/v_builders/_39_HtmlBuilders.kt | 1 | 1401 | package v_builders
import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*
fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) % 2 == 0) "#dce4ff" else "#eff2ff"
fun todoTask39(): Nothing = TODO(
"""
Task 39.
1) Fill the table with the proper values from products.
2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
Pass a color as an argument tail functions 'tr', 'td'.
You can run the 'Html Demo' configuration in IntelliJ IDEA tail see the rendered table.
""",
documentation = doc39()
)
fun renderProductTable(): String {
return html {
table {
tr {
td {
text("Product")
}
td {
text("Price")
}
td {
text("Popularity")
}
}
val products = getProducts()
products.forEachIndexed { i, product ->
tr {
td(getCellColor(i, 0)) { text(product.description) }
td(getCellColor(i, 1)) { text(product.price) }
td(getCellColor(i, 2)) { text(product.popularity) }
}
}
}
}.toString()
}
| mit | a808d3f297bfa79e278c2e8a2f4695b8 | 29.456522 | 105 | 0.508208 | 4.433544 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/HTMLUtil.kt | 1 | 1144 | package ch.rmy.android.http_shortcuts.utils
import android.content.Context
import android.os.Build
import android.text.Html
import android.text.Spanned
import kotlinx.coroutines.CoroutineScope
object HTMLUtil {
fun format(string: String): Spanned =
fromHTML(string.convertNewlines().normalize())
fun formatWithImageSupport(
string: String,
context: Context,
onImageLoaded: () -> Unit,
coroutineScope: CoroutineScope,
): Spanned =
fromHTML(string.convertNewlines().normalize(), ImageGetter(context, onImageLoaded, coroutineScope))
private fun String.normalize(): String =
replace("<pre>", "<tt>")
.replace("</pre>", "</tt>")
private fun String.convertNewlines() =
removeSuffix("\n").replace("\n", "<br>")
@Suppress("DEPRECATION")
private fun fromHTML(
string: String,
imageGetter: ImageGetter? = null,
): Spanned =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(string, 0, imageGetter, null)
} else {
Html.fromHtml(string, imageGetter, null)
}
}
| mit | b1a6d887270b879ea8c70684c4b0d11d | 29.105263 | 107 | 0.63986 | 4.34981 | false | false | false | false |
sg26565/hott-transmitter-config | VDFEditor/src/main/kotlin/de/treichels/hott/vdfeditor/actions/Actions.kt | 1 | 3208 | package de.treichels.hott.vdfeditor.actions
import de.treichels.hott.voice.VoiceData
/**
* Abstract base class for undoable actions for mutable lists of type <T>.
*/
abstract class UndoableAction<T> {
abstract fun apply(list: MutableList<T>): MutableList<T>
abstract fun undo(list: MutableList<T>): MutableList<T>
}
/**
* Insert a new item into the list.
*/
class InsertAction<T>(private val index: Int, private val item: T) : UndoableAction<T>() {
override fun apply(list: MutableList<T>): MutableList<T> {
list.add(index, item)
return list
}
override fun undo(list: MutableList<T>): MutableList<T> {
list.removeAt(index)
return list
}
}
/**
* Add a new item to the end of the list.
*/
class AddAction<T>(private val item: T) : UndoableAction<T>() {
private var index: Int = -1
override fun apply(list: MutableList<T>): MutableList<T> {
index = list.size
list.add(index, item)
return list
}
override fun undo(list: MutableList<T>): MutableList<T> {
list.removeAt(index)
return list
}
}
/**
* Remove an item from the list.
*/
class RemoveAction<T>(private val index: Int) : UndoableAction<T>() {
private var item: T? = null
override fun apply(list: MutableList<T>): MutableList<T> {
item = list.removeAt(index)
return list
}
override fun undo(list: MutableList<T>): MutableList<T> {
list.add(index, item!!)
return list
}
}
/**
* Replace an existing item with a new one.
*/
class ReplaceAction<T>(private val index: Int, private val item: T) : UndoableAction<T>() {
private var oldItem: T? = null
override fun apply(list: MutableList<T>): MutableList<T> {
oldItem = list[index]
list[index] = item
return list
}
override fun undo(list: MutableList<T>): MutableList<T> {
list[index] = oldItem!!
return list
}
}
/**
* Move an item in the list.
*/
open class MoveAction<T>(private val fromIndex: Int, private val toIndex: Int) : UndoableAction<T>() {
override fun apply(list: MutableList<T>): MutableList<T> {
val item = list.removeAt(fromIndex)
list.add(toIndex, item)
return list
}
override fun undo(list: MutableList<T>): MutableList<T> {
val item = list.removeAt(toIndex)
list.add(fromIndex, item)
return list
}
}
class MoveDownAction<T>(index: Int) : MoveAction<T>(fromIndex = index, toIndex = index + 1)
class MoveUpAction<T>(index: Int) : MoveAction<T>(fromIndex = index, toIndex = index - 1)
class RenameAction(private val index: Int, private val newName: String) : UndoableAction<VoiceData>() {
private lateinit var oldName: String
override fun apply(list: MutableList<VoiceData>): MutableList<VoiceData> {
val voiceData = list[index]
oldName = voiceData.name
voiceData.name = newName
list[index] = voiceData
return list
}
override fun undo(list: MutableList<VoiceData>): MutableList<VoiceData> {
val voiceData = list[index]
voiceData.name = oldName
list[index] = voiceData
return list
}
} | lgpl-3.0 | 09ad601fd2c1de5c24f76c0d8fc78e98 | 26.194915 | 103 | 0.637469 | 3.832736 | false | false | false | false |
amasciul/Drinks | app/src/main/java/fr/masciulli/drinks/drink/DrinkViewModel.kt | 1 | 1416 | package fr.masciulli.drinks.drink
import fr.masciulli.drinks.BaseViewModel
import fr.masciulli.drinks.core.drinks.Drink
import fr.masciulli.drinks.core.drinks.DrinksSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
class DrinkViewModel(
private val drinksSource: DrinksSource,
private val drinkId: String
) : BaseViewModel {
private var drinkDisposable: Disposable? = null
val drink: BehaviorSubject<Drink> = BehaviorSubject.create()
val error: BehaviorSubject<Throwable> = BehaviorSubject.create()
val shareDrink: BehaviorSubject<Drink> = BehaviorSubject.create()
override fun start() {
drinkDisposable = drinksSource.getDrink(drinkId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ drinkLoaded(it) },
{ errorLoadingDrink(it) }
)
}
private fun drinkLoaded(drink: Drink) {
this.drink.onNext(drink)
}
private fun errorLoadingDrink(throwable: Throwable) {
error.onNext(throwable)
}
fun openShareDrink() {
drink.value?.let { shareDrink.onNext(it) }
}
override fun stop() {
drinkDisposable?.dispose()
}
} | apache-2.0 | a1ad6b1ad119da9c251d1befc3938311 | 29.804348 | 69 | 0.675847 | 4.45283 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/util/PaymentProtocolUtils.kt | 1 | 3689 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 1/15/20.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.util
import com.breadwallet.crypto.PaymentProtocolPayment
import com.breadwallet.crypto.PaymentProtocolRequest
import com.breadwallet.crypto.PaymentProtocolRequestType
import com.breadwallet.crypto.Wallet
import com.breadwallet.tools.util.BRConstants
import com.platform.APIClient
private const val HEADER_PAYMENT_REQUEST_BIP70 =
"application/bitcoin-paymentrequest"
private const val HEADER_PAYMENT_REQUEST_BITPAY_V1 = "application/payment-request"
private const val HEADER_PAYMENT_BIP70 = "application/bitcoin-payment"
private const val HEADER_PAYMENT_BITPAY_V1 = "application/payment"
private const val HEADER_PAYMENT_ACK_BIP70 = "application/bitcoin-paymentack"
private const val HEADER_PAYMENT_ACK_BITPAY_V1 = "application/payment-ack"
const val HEADER_BITPAY_PARTNER_KEY = "BP_PARTNER"
const val HEADER_BITPAY_PARTNER = "brd"
/** Return the header required to fetch a [PaymentProtocolRequest] */
fun CurrencyCode.getPaymentRequestHeader(): String =
when {
isBitcoin() -> HEADER_PAYMENT_REQUEST_BIP70
else -> HEADER_PAYMENT_REQUEST_BITPAY_V1
}
/** Return the content type header required to post a [PaymentProtocolPayment] */
fun PaymentProtocolRequest.getContentTypeHeader(): String =
when (type) {
PaymentProtocolRequestType.BIP70 -> HEADER_PAYMENT_BIP70
PaymentProtocolRequestType.BITPAY -> HEADER_PAYMENT_BITPAY_V1
else -> ""
}
/** Return the content type header required to post a [PaymentProtocolPayment] */
fun PaymentProtocolRequest.getAcceptHeader(): String =
when (type) {
PaymentProtocolRequestType.BIP70 -> HEADER_PAYMENT_ACK_BIP70
PaymentProtocolRequestType.BITPAY -> HEADER_PAYMENT_ACK_BITPAY_V1
else -> ""
}
/** Build a [PaymentProtocolRequest] from an [APIClient.BRResponse] */
fun buildPaymentProtocolRequest(
wallet: Wallet,
response: APIClient.BRResponse
): PaymentProtocolRequest? {
val header = response.headers[BRConstants.HEADER_CONTENT_TYPE.toLowerCase()].orEmpty()
return when {
header.startsWith(HEADER_PAYMENT_BIP70, true) -> {
PaymentProtocolRequest.createForBip70(
wallet,
response.body
).orNull()
}
header.startsWith(HEADER_PAYMENT_BITPAY_V1, true) -> {
PaymentProtocolRequest.createForBitPay(
wallet,
response.bodyText
).orNull()
}
else -> null
}
} | mit | 697b04850a79d72c601a804828fa6718 | 40.931818 | 90 | 0.73055 | 4.279582 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/flavors/MayaSdkFlavor.kt | 1 | 2327 | package flavors
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonFlavorProvider
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import icons.PythonIcons
import java.io.File
import javax.swing.Icon
class MayaSdkFlavor private constructor() : PythonSdkFlavor() {
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getVersionOption(): String {
return "--version"
}
override fun getLanguageLevelFromVersionString(version: String?): LanguageLevel {
if (version != null && version.startsWith(verStringPrefix)) {
return LanguageLevel.fromPythonVersion(version.substring(verStringPrefix.length))
?: LanguageLevel.getDefault()
}
return LanguageLevel.getDefault()
}
override fun getLanguageLevel(sdk: Sdk): LanguageLevel {
return getLanguageLevelFromVersionString(sdk.versionString)
}
override fun getLanguageLevel(sdkHome: String): LanguageLevel {
val version = getVersionString(sdkHome)
return getLanguageLevelFromVersionString(version)
}
override fun getName(): String {
return "Maya Python"
}
override fun getIcon(): Icon {
return PythonIcons.Python.Python
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
const val verStringPrefix = "Python "
val INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider : PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): PythonSdkFlavor = MayaSdkFlavor.INSTANCE
}
| mit | 5350d0c0d81dbe4101be9946f57ee69e | 30.876712 | 98 | 0.699613 | 4.888655 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.