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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/script/definition/highlighting/doNotSpeakAboutJava/template/template.kt | 5 | 2071 | package custom.scriptDefinition
import kotlin.script.dependencies.*
import kotlin.script.experimental.dependencies.*
import kotlin.script.templates.*
import java.io.File
import kotlin.script.experimental.location.*
class TestDependenciesResolver : DependenciesResolver {
override fun resolve(scriptContents: ScriptContents, environment: Environment): DependenciesResolver.ResolveResult {
val reports = ArrayList<ScriptReport>()
scriptContents.text?.let { text ->
text.lines().forEachIndexed { lineIndex, line ->
val adjustedLine = line.replace(Regex("(<error descr=\"Can't use\">)|(</error>)|(<warning descr=\"Shouldn't use\">)|(</warning>)"), "")
Regex("java").findAll(adjustedLine).forEach {
reports.add(
ScriptReport(
"Can't use",
ScriptReport.Severity.ERROR,
ScriptReport.Position(lineIndex, it.range.first, lineIndex, it.range.last + 1)
)
)
}
Regex("scala").findAll(adjustedLine).forEach {
reports.add(
ScriptReport(
"Shouldn't use",
ScriptReport.Severity.WARNING,
ScriptReport.Position(lineIndex, it.range.first, lineIndex, it.range.last + 1)
)
)
}
}
}
return DependenciesResolver.ResolveResult.Success(
ScriptDependencies(
classpath = environment["template-classes"] as List<File>
),
reports
)
}
}
@ScriptExpectedLocations([ScriptExpectedLocation.Everywhere])
@ScriptTemplateDefinition(TestDependenciesResolver::class, scriptFilePattern = "script.kts")
class Template : Base()
open class Base {
val i = 3
val str = ""
} | apache-2.0 | fe1e77c1fd7cb39363e556a0a47ab675 | 38.846154 | 151 | 0.534524 | 5.673973 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinListVariable.kt | 4 | 1201 | // 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.debugger.sequence.trace.dsl
import com.intellij.debugger.streams.trace.dsl.Expression
import com.intellij.debugger.streams.trace.dsl.ListVariable
import com.intellij.debugger.streams.trace.dsl.VariableDeclaration
import com.intellij.debugger.streams.trace.dsl.impl.VariableImpl
import com.intellij.debugger.streams.trace.impl.handler.type.ListType
class KotlinListVariable(override val type: ListType, name: String) : VariableImpl(type, name), ListVariable {
override operator fun get(index: Expression): Expression = call("get", index)
override operator fun set(index: Expression, newValue: Expression): Expression = call("set", index, newValue)
override fun add(element: Expression): Expression = call("add", element)
override fun contains(element: Expression): Expression = call("contains", element)
override fun size(): Expression = property("size")
override fun defaultDeclaration(): VariableDeclaration =
KotlinVariableDeclaration(this, false, type.defaultValue)
} | apache-2.0 | c263f2b2e82ac4db7bff5f10ca195e3a | 53.636364 | 158 | 0.782681 | 4.33574 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/action/GHPRDiffReviewThreadsToggleAction.kt | 4 | 1274 | // 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 org.jetbrains.plugins.github.pullrequest.comment.action
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport
class GHPRDiffReviewThreadsToggleAction
: ToggleAction({ GithubBundle.message("pull.request.review.show.comments.action") },
{ GithubBundle.message("pull.request.review.show.comments.action.description") },
null) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = e.getData(GHPRDiffReviewSupport.DATA_KEY) != null
}
override fun isSelected(e: AnActionEvent): Boolean =
e.getData(GHPRDiffReviewSupport.DATA_KEY)?.showReviewThreads ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
e.getData(GHPRDiffReviewSupport.DATA_KEY)?.showReviewThreads = state
}
} | apache-2.0 | 8eb873a1c9c6ee16607ac7155f01b8eb | 44.535714 | 140 | 0.782575 | 4.533808 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/popup/list/InlineActionsUtil.kt | 2 | 1772 | // 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.ui.popup.list
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import java.awt.Point
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JList
private const val INLINE_BUTTON_WIDTH = 16
const val INLINE_BUTTON_MARKER = "inlineButtonMarker"
fun createExtraButton(icon: Icon, active: Boolean): JComponent {
val label = JLabel(icon)
label.putClientProperty(INLINE_BUTTON_MARKER, true)
val leftRightInsets = JBUI.CurrentTheme.List.buttonLeftRightInsets()
label.border = JBUI.Borders.empty(0, leftRightInsets)
val panel = SelectablePanel.wrap(label)
val size = panel.preferredSize
size.width = buttonWidth(leftRightInsets)
panel.preferredSize = size
panel.minimumSize = size
panel.selectionColor = if (active) JBUI.CurrentTheme.List.buttonHoverBackground() else null
panel.selectionArc = JBUI.CurrentTheme.Popup.Selection.ARC.get()
panel.isOpaque = false
return panel
}
fun calcButtonIndex(list: JList<*>, buttonsCount: Int, point: Point): Int? {
val index = list.selectedIndex
val bounds = list.getCellBounds(index, index) ?: return null
JBInsets.removeFrom(bounds, PopupListElementRenderer.getListCellPadding())
val distanceToRight = bounds.x + bounds.width - point.x
val buttonsToRight = distanceToRight / buttonWidth()
if (buttonsToRight >= buttonsCount) return null
return buttonsCount - buttonsToRight - 1
}
@JvmOverloads
fun buttonWidth(leftRightInsets: Int = JBUI.CurrentTheme.List.buttonLeftRightInsets()) : Int = JBUIScale.scale(INLINE_BUTTON_WIDTH + leftRightInsets * 2) | apache-2.0 | 1201cdd47e9fbda463dd5f3ecfcbeebb | 38.4 | 153 | 0.783296 | 3.964206 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/ExtensionFunctions.fir.kt | 10 | 1666 | fun Int?.optint() : Unit {}
val Int?.optval : Unit get() = Unit
fun <T: Any, E> T.foo(x : E, y : A) : T {
y.plus(1)
y plus 1
y + 1.0
this?.minus<T>(this)
return this
}
class A
infix operator fun A.plus(a : Any) {
1.foo()
true.foo(<error descr="[NO_VALUE_FOR_PARAMETER] No value passed for parameter 'x'"><error descr="[NO_VALUE_FOR_PARAMETER] No value passed for parameter 'y'">)</error></error>
1
}
infix operator fun A.plus(a : Int) {
1
}
fun <T> T.minus(t : T) : Int = 1
fun test() {
val y = 1.abs
}
val Int.abs : Int
get() = if (this > 0) this else -this;
<error descr="[EXTENSION_PROPERTY_MUST_HAVE_ACCESSORS_OR_BE_ABSTRACT] Extension property must have accessors or be abstract">val <T> T.foo : T</error>
fun Int.foo() = this
// FILE: b.kt
//package null_safety
fun parse(cmd: String): Command? { return null }
class Command() {
// fun equals(other : Any?) : Boolean
val foo : Int = 0
}
operator fun Any.equals(other : Any?) : Boolean = true
fun Any?.equals1(other : Any?) : Boolean = true
fun Any.equals2(other : Any?) : Boolean = true
fun main(args: Array<String>) {
System.out.print(1)
val command = parse("")
command.foo
command<error descr="[UNSAFE_CALL] Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Command?">.</error>equals(null)
command?.equals(null)
command.equals1(null)
command?.equals1(null)
val c = Command()
c?.equals2(null)
if (command == null) 1
}
| apache-2.0 | 57681f4fc469996f716304ca4d19d96d | 22.8 | 176 | 0.570828 | 3.358871 | false | false | false | false |
walleth/kethereum | extensions/src/main/kotlin/org/kethereum/extensions/BitArray.kt | 1 | 692 | package org.kethereum.extensions
import kotlin.experimental.or
fun ByteArray.toBitArray(): BooleanArray {
val bits = BooleanArray(this.size * 8)
for (byteIndex in this.indices)
for (bitIndex in 0..7) {
bits[byteIndex * 8 + bitIndex] = (1 shl (7 - bitIndex)) and this[byteIndex].toInt() != 0
}
return bits
}
fun BooleanArray.toByteArray(len : Int = this.size / 8): ByteArray {
val result = ByteArray(len)
for (byteIndex in result.indices)
for (bitIndex in 0..7)
if (this[byteIndex * 8 + bitIndex]) {
result[byteIndex] = result[byteIndex] or (1 shl (7 - bitIndex)).toByte()
}
return result
} | mit | c3afa9c0f4447b585371598bba315216 | 30.5 | 100 | 0.612717 | 3.680851 | false | false | false | false |
bgogetap/KotlinWeather | app/src/main/kotlin/com/cultureoftech/kotlinweather/details/ForecastItemView.kt | 1 | 1273 | package com.cultureoftech.kotlinweather.details
import android.content.Context
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import com.cultureoftech.kotlinweather.R
import com.cultureoftech.kotlinweather.utils.bindView
import com.cultureoftech.kotlinweather.weather.CityForecastResponse
import java.text.SimpleDateFormat
/**
* Created by bgogetap on 2/22/16.
*/
class ForecastItemView(context: Context, screen: DetailsScreen): LinearLayout(context) {
lateinit var formatter: SimpleDateFormat
val dateText by bindView<TextView>(R.id.tv_date)
val minTempText by bindView<TextView>(R.id.tv_temp_min)
val maxTempTxt by bindView<TextView>(R.id.tv_temp_max)
init {
LayoutInflater.from(context).inflate(R.layout.forecast_item, this, true)
orientation = LinearLayout.VERTICAL
screen.component()?.inject(this)
formatter = screen.component()?.simpleDateFormat()!!
}
fun setData(day: CityForecastResponse.Day) {
dateText.text = formatter.format(day.getDate())
minTempText.text = context.getString(R.string.temp_min_format, day.temp.min.toInt())
maxTempTxt.text = context.getString(R.string.temp_max_format, day.temp.max.toInt())
}
} | apache-2.0 | 1e7f66620859585ce1e4b9a78080868c | 35.4 | 92 | 0.750982 | 3.916923 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/HomeActivity.kt | 1 | 14979 | /*
* Copyright (C) 2012 dvbviewer-controller Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.dvbviewer.controller.ui
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.appcompat.widget.AppCompatSpinner
import androidx.fragment.app.FragmentManager
import org.dvbviewer.controller.R
import org.dvbviewer.controller.activitiy.base.GroupDrawerActivity
import org.dvbviewer.controller.data.entities.DVBTarget
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.data.entities.IEPG
import org.dvbviewer.controller.data.media.MediaFile
import org.dvbviewer.controller.ui.adapter.MediaAdapter
import org.dvbviewer.controller.ui.fragments.*
import org.dvbviewer.controller.ui.fragments.ChannelList.OnChannelSelectedListener
import org.dvbviewer.controller.ui.fragments.Dashboard.OnDashboardButtonClickListener
import org.dvbviewer.controller.ui.phone.*
import org.dvbviewer.controller.utils.*
import java.util.*
/**
* The Class HomeActivity.
*
* @author RayBa
*/
class HomeActivity : GroupDrawerActivity(), OnClickListener, OnChannelSelectedListener, OnDashboardButtonClickListener, Remote.OnTargetsChangedListener, IEpgDetailsActivity.OnIEPGClickListener, MediaAdapter.OnMediaClickListener {
private var multiContainer: View? = null
private var mSpinnerAdapter: ArrayAdapter<*>? = null
private var mClientSpinner: AppCompatSpinner? = null
private var chans: ChannelPager? = null
private var enableDrawer: Boolean = false
override var selectedTarget: DVBTarget? = null
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.base.BaseActivity#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_home)
super.onCreate(savedInstanceState)
multiContainer = findViewById(R.id.right_content)
if (savedInstanceState == null) {
val dashboard = Dashboard()
var tran = supportFragmentManager.beginTransaction()
tran.add(R.id.left_content, dashboard)
tran.commit()
if (multiContainer != null) {
enableDrawer = true
tran = supportFragmentManager.beginTransaction()
chans = ChannelPager()
chans!!.setHasOptionsMenu(true)
val bundle = Bundle()
bundle.putInt(ChannelPager.KEY_GROUP_INDEX, groupIndex)
chans!!.arguments = bundle
tran.add(multiContainer!!.id, chans!!, GroupDrawerActivity.Companion.CHANNEL_PAGER_TAG)
tran.commit()
setTitle(R.string.channelList)
}
if (Config.IS_FIRST_START) {
Config.IS_FIRST_START = false
val builder = AlertDialog.Builder(this)
builder.setMessage(resources.getString(R.string.firstStartMessage)).setPositiveButton(R.string.yes, this).setTitle(resources.getString(R.string.firstStartMessageTitle))
.setNegativeButton(R.string.no, this).show()
prefs = DVBViewerPreferences(this)
prefs.prefs.edit()
.putBoolean(DVBViewerPreferences.KEY_IS_FIRST_START, false)
.apply()
}
} else {
val frag = supportFragmentManager.findFragmentByTag(GroupDrawerActivity.Companion.CHANNEL_PAGER_TAG)
if (frag != null && frag is ChannelPager) {
chans = frag
}
enableDrawer = savedInstanceState.getBoolean(ENABLE_DRAWER, false)
title = savedInstanceState.getString(TITLE)!!
}
initRemoteSpinner()
setDrawerEnabled(enableDrawer)
}
private fun initRemoteSpinner() {
mClientSpinner = findViewById(R.id.clientSpinner)
if (mClientSpinner != null) {
mClientSpinner!!.visibility = View.GONE
mClientSpinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val selectedClient = mSpinnerAdapter!!.getItem(position) as String?
prefs.prefs.edit()
.putString(DVBViewerPreferences.KEY_SELECTED_CLIENT, selectedClient)
.apply()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
}
}
/* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
val settings = Intent(this@HomeActivity, PreferencesActivity::class.java)
startActivity(settings)
}
else -> finish()
}
}
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.fragments.Dashboard.OnDashboardButtonClickListener#onDashboarButtonClick(android.view.View)
*/
override fun onDashboarButtonClick(v: View) {
val fm = supportFragmentManager
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
when (v.id) {
R.id.home_btn_remote -> if (multiContainer != null) {
enableDrawer = false
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, Remote())
tran.commit()
setTitle(R.string.remote)
} else {
startActivity(Intent(this, RemoteActivity::class.java))
}
R.id.home_btn_channels -> if (multiContainer != null) {
enableDrawer = true
val tran = fm.beginTransaction()
chans = ChannelPager()
chans!!.setHasOptionsMenu(true)
val bundle = Bundle()
bundle.putInt(ChannelPager.KEY_GROUP_INDEX, groupIndex)
chans!!.arguments = bundle
tran.replace(multiContainer!!.id, chans!!, GroupDrawerActivity.Companion.CHANNEL_PAGER_TAG)
tran.commit()
setTitle(R.string.channelList)
} else {
startActivity(Intent(this, ChannelListActivity::class.java))
}
R.id.home_btn_timers -> if (multiContainer != null) {
enableDrawer = false
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, TimerList())
tran.commit()
} else {
startActivity(Intent(this, TimerlistActivity::class.java))
}
R.id.home_btn_recordings -> if (multiContainer != null) {
enableDrawer = false
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, RecordingList())
tran.commit()
setTitle(R.string.recordings)
} else {
startActivity(Intent(this, RecordinglistActivity::class.java))
}
R.id.home_btn_settings -> startActivity(Intent(this, PreferencesActivity::class.java))
R.id.home_btn_tasks -> if (multiContainer != null) {
enableDrawer = false
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, TaskListFragment())
tran.commit()
setTitle(R.string.tasks)
} else {
startActivity(Intent(this, TaskActivity::class.java))
}
R.id.home_btn_status -> if (multiContainer != null) {
enableDrawer = false
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, StatusList())
tran.commit()
setTitle(R.string.status)
} else {
startActivity(Intent(this, StatusActivity::class.java))
}
R.id.home_btn_medias -> if (multiContainer != null) {
enableDrawer = false
val b = Bundle()
b.putLong(MediaList.KEY_PARENT_ID, 1)
val mediaList = MediaList()
mediaList.arguments = b
val tran = fm.beginTransaction()
tran.replace(multiContainer!!.id, mediaList)
tran.commit()
} else {
startActivity(Intent(this, MedialistActivity::class.java))
}
else -> {
}
}
if (mClientSpinner != null) {
mClientSpinner!!.visibility = View.GONE
}
setDrawerEnabled(enableDrawer)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.home, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuAbout -> {
startActivity(Intent(this, AboutActivity::class.java))
return true
}
R.id.menuWOL -> {
val wakeOnLanRunnabel = Runnable { NetUtils.sendWakeOnLan(prefs!!, ServerConsts.REC_SERVICE_WOL_PORT) }
val wakeOnLanThread = Thread(wakeOnLanRunnabel)
wakeOnLanThread.start()
return true
}
else -> {
}
}
return super.onOptionsItemSelected(item)
}
override fun channelSelected(groupId: Long, groupIndex: Int, channelIndex: Int) {
val channelListIntent = Intent(this, ChannelListActivity::class.java)
channelListIntent.putExtra(ChannelPager.KEY_GROUP_ID, groupId)
channelListIntent.putExtra(ChannelPager.KEY_GROUP_INDEX, groupIndex)
channelListIntent.putExtra(ChannelList.KEY_CHANNEL_INDEX, channelIndex)
channelListIntent.putExtra(ChannelPager.KEY_HIDE_FAV_SWITCH, true)
startActivity(channelListIntent)
}
override fun targetsChanged(title: String, spinnerData: List<DVBTarget>?) {
setTitle(title)
if (mClientSpinner != null) {
val clients = LinkedList<String>()
spinnerData?.map { it.name }?.let { clients.addAll(it) }
mSpinnerAdapter = ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, clients.toTypedArray())
mSpinnerAdapter!!.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
mClientSpinner!!.adapter = mSpinnerAdapter
val activeClient = prefs!!.getString(DVBViewerPreferences.KEY_SELECTED_CLIENT)
val index = clients.indexOf(activeClient)
val spinnerPosition = if (index > Spinner.INVALID_POSITION) index else Spinner.INVALID_POSITION
mClientSpinner!!.setSelection(spinnerPosition)
mClientSpinner!!.visibility = View.VISIBLE
}
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
super.onItemClick(parent, view, position, id)
if (chans != null) {
chans!!.setPosition(position)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(ENABLE_DRAWER, enableDrawer)
outState.putString(TITLE, title.toString())
}
override fun onIEPGClick(iepg: IEPG) {
val details = EPGDetails()
val bundle = Bundle()
bundle.putParcelable(IEPG::class.java.simpleName, iepg)
details.arguments = bundle
details.show(supportFragmentManager, IEPG::class.java.name)
}
override fun onMediaClick(mediaFile: MediaFile) {
if (mediaFile.dirId > 0) {
val mediaList = MediaList()
val b = Bundle()
b.putLong(MediaList.KEY_PARENT_ID, mediaFile.dirId)
mediaList.arguments = b
val tran = supportFragmentManager.beginTransaction()
tran.replace(multiContainer!!.id, mediaList)
tran.addToBackStack(MediaList::class.java.name + mediaFile.dirId!!)
tran.commit()
} else {
val arguments = Bundle()
arguments.putLong(StreamConfig.EXTRA_FILE_ID, mediaFile.id!!)
arguments.putParcelable(StreamConfig.EXTRA_FILE_TYPE, FileType.VIDEO)
arguments.putInt(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig)
arguments.putString(StreamConfig.EXTRA_TITLE, mediaFile.name)
val cfg = StreamConfig.newInstance()
cfg.arguments = arguments
cfg.show(supportFragmentManager, StreamConfig::class.java.name)
}
}
override fun onMediaStreamClick(mediaFile: MediaFile) {
val videoIntent = StreamUtils.buildQuickUrl(this, mediaFile.id!!, mediaFile.name, FileType.VIDEO)
startActivity(videoIntent)
val prefs = DVBViewerPreferences(this).streamPrefs
val direct = prefs.getBoolean(DVBViewerPreferences.KEY_STREAM_DIRECT, true)
val bundle = Bundle()
bundle.putString(PARAM_START, START_QUICK)
bundle.putString(PARAM_TYPE, if (direct) TYPE_DIRECT else TYPE_TRANSCODED)
bundle.putString(PARAM_NAME, mediaFile.name)
mFirebaseAnalytics?.logEvent(EVENT_STREAM_MEDIA, bundle)
}
override fun onMediaContextClick(mediaFile: MediaFile) {
val arguments = Bundle()
arguments.putLong(StreamConfig.EXTRA_FILE_ID, mediaFile.id!!)
arguments.putParcelable(StreamConfig.EXTRA_FILE_TYPE, FileType.VIDEO)
arguments.putInt(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig)
arguments.putString(StreamConfig.EXTRA_TITLE, mediaFile.name)
val cfg = StreamConfig.newInstance()
cfg.arguments = arguments
cfg.show(supportFragmentManager, StreamConfig::class.java.name)
}
companion object {
const val ENABLE_DRAWER = "ENABLE_DRAWER"
const val TITLE = "title"
}
}
| apache-2.0 | 3699e5102cf643013a79df2a788ac24e | 41.553977 | 229 | 0.630616 | 4.761284 | false | false | false | false |
e16din/LightUtils | LightUtils/src/main/java/com/e16din/lightutils/utils/DisplayUtils.kt | 1 | 4268 | package com.e16din.lightutils.utils
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Build
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Display
import android.view.View
import com.e16din.lightutils.model.Size
import java.lang.reflect.InvocationTargetException
val displayMetrics
get() = resources!!.displayMetrics
val Number.toPx: Float
get() = (this.toFloat() * displayMetrics.density)
val Number.toDp: Float
get() = (this.toFloat() / displayMetrics.density)
open class DisplayUtils : ColorUtils() {
companion object {
@JvmStatic
fun dpToPx(dp: Number) = dp.toPx
@JvmStatic
fun pxToDp(px: Number) = px.toDp
@JvmStatic
fun pxToSp(px: Float) = px / displayMetrics.scaledDensity
@JvmStatic
fun pxToMm(px: Float) =
px / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1f, displayMetrics)
@JvmStatic
fun spToPx(sp: Int) =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), displayMetrics).toInt()
@JvmStatic
fun setElevation(view: View, levelPx: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.elevation = levelPx.toFloat()
}
}
@JvmStatic
fun getScreenSize(activity: Activity) = getScreenSize(activity.windowManager.defaultDisplay)
@JvmStatic
fun getScreenSize(display: Display): Size {
var realWidth: Int
var realHeight: Int
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 -> {
//new pleasant way to get real metrics
val realMetrics = DisplayMetrics()
display.getRealMetrics(realMetrics)
realWidth = realMetrics.widthPixels
realHeight = realMetrics.heightPixels
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH -> //reflection for this weird in-between time
try {
val mGetRawH = Display::class.java.getMethod("getRawHeight")
val mGetRawW = Display::class.java.getMethod("getRawWidth")
realWidth = mGetRawW.invoke(display) as Int
realHeight = mGetRawH.invoke(display) as Int
} catch (e: NoSuchMethodException) {
//this may not be 100% accurate, but it's all we've got
realWidth = display.width
realHeight = display.height
} catch (e: SecurityException) {
realWidth = display.width
realHeight = display.height
} catch (e: IllegalAccessException) {
realWidth = display.width
realHeight = display.height
} catch (e: IllegalArgumentException) {
realWidth = display.width
realHeight = display.height
} catch (e: InvocationTargetException) {
realWidth = display.width
realHeight = display.height
}
else -> {
//This should be close, as lower API devices should not have window navigation bars
realWidth = display.width
realHeight = display.height
}
}
return Size(realWidth, realHeight)
}
@JvmStatic
fun takeScreenshot(view: View): Bitmap {
val bitmap = Bitmap.createBitmap(view.width, view.height,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val backgroundDrawable = view.background
if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas)
} else {
canvas.drawColor(Color.WHITE)
}
view.draw(canvas)
return bitmap
}
}
}
| mit | 1821e646ca6c5866e295d7cc4d898f16 | 34.865546 | 126 | 0.559278 | 5.062871 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/test/java/com/doctoror/particleswallpaper/userprefs/ConfigFragmentTest.kt | 1 | 5623 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.userprefs
import android.content.Context
import androidx.annotation.StringRes
import androidx.test.core.app.ApplicationProvider
import com.doctoror.particleswallpaper.R
import com.doctoror.particleswallpaper.userprefs.bgimage.BackgroundImagePreference
import com.doctoror.particleswallpaper.userprefs.bgimage.BackgroundImagePreferencePresenter
import com.doctoror.particleswallpaper.userprefs.howtoapply.HowToApplyPreference
import com.doctoror.particleswallpaper.userprefs.preview.OpenChangeWallpaperIntentProvider
import com.doctoror.particleswallpaper.userprefs.preview.PreviewPreference
import com.doctoror.particleswallpaper.userprefs.preview.PreviewPreferencePresenter
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.standalone.StandAloneContext
import org.koin.standalone.inject
import org.koin.test.KoinTest
import org.koin.test.declareMock
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
import org.robolectric.android.controller.FragmentController
import org.robolectric.annotation.Config
@Config(sdk = intArrayOf(19))
@RunWith(RobolectricTestRunner::class)
class ConfigFragmentTest : KoinTest {
private val intentProvider: OpenChangeWallpaperIntentProvider by inject()
private val underTestController = FragmentController.of(ConfigFragment())
@Before
fun setup() {
declareMock<BackgroundImagePreferencePresenter>()
declareMock<PreviewPreferencePresenter>()
declareMock<OpenChangeWallpaperIntentProvider>()
}
@After
fun tearDown() {
StandAloneContext.stopKoin()
}
@Test
fun backgroundImagePreferenceHostSetOnCreate() {
val underTest = underTestController.create().start().get()
val backgroundImagePreference = underTest.findPreference(
getString(R.string.pref_key_background_image)
) as BackgroundImagePreference
assertEquals(underTest, backgroundImagePreference.fragment)
}
@Test
fun backgroundImagePreferenceHostResetOnDestroy() {
val underTest = underTestController
.create()
.start()
.stop()
.destroy()
.get()
val backgroundImagePreference = underTest.findPreference(
getString(R.string.pref_key_background_image)
) as BackgroundImagePreference
assertNull(backgroundImagePreference.fragment)
}
@Test
fun howToApplyPreferenceHostSetOnCreate() {
val underTest = underTestController.create().start().get()
val howToApplyPreference = underTest.findPreference(
getString(R.string.pref_key_how_to_apply)
) as HowToApplyPreference
assertEquals(underTest, howToApplyPreference.fragment)
}
@Test
fun howToApplyPreferenceHostResetOnDestroy() {
val underTest = underTestController
.create()
.start()
.stop()
.destroy()
.get()
val howToApplyPreference = underTest.findPreference(
getString(R.string.pref_key_how_to_apply)
) as HowToApplyPreference
assertNull(howToApplyPreference.fragment)
}
@Test
fun previewPreferenceHostSetOnCreate() {
whenever(intentProvider.provideActionIntent()).thenReturn(mock())
val underTest = underTestController
.create()
.start()
.get()
val previewPreference = underTest.findPreference(
getString(R.string.pref_key_apply)
) as PreviewPreference
assertEquals(underTest, previewPreference.fragment)
}
@Test
fun previewPreferenceHostResetOnDestroy() {
whenever(intentProvider.provideActionIntent()).thenReturn(mock())
val underTest = underTestController
.create()
.start()
.stop()
.destroy()
.get()
val previewPreference = underTest.findPreference(
getString(R.string.pref_key_apply)
) as PreviewPreference
assertNull(previewPreference.fragment)
}
@Test
fun previewPreferenceRemovedWhenIntentIsNull() {
val underTest = underTestController
.create()
.start()
.stop()
.destroy()
.get()
val previewPreference = underTest.findPreference(
getString(R.string.pref_key_apply)
)
assertNull(previewPreference)
}
@Test
fun lifecycleObserversUnregisteredOnDestroy() {
val underTest = underTestController
.create()
.destroy()
.get()
assertEquals(0, underTest.lifecycle.observerCount)
}
private fun getString(@StringRes key: Int) =
ApplicationProvider.getApplicationContext<Context>().getString(key)
}
| apache-2.0 | 26339fd30a9af32232f80afd6d6fa147 | 30.413408 | 91 | 0.699449 | 5.029517 | false | true | false | false |
Apolline-Lille/apolline-android | app/src/main/java/science/apolline/view/fragment/IOIOFragment.kt | 1 | 11181 | package science.apolline.view.fragment
import android.Manifest
import android.annotation.SuppressLint
import android.arch.lifecycle.ViewModelProviders
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import at.grabner.circleprogress.TextMode
import com.fondesa.kpermissions.extension.listeners
import com.fondesa.kpermissions.extension.permissionsBuilder
import com.fondesa.kpermissions.request.PermissionRequest
import com.github.salomonbrys.kodein.android.appKodein
import com.github.salomonbrys.kodein.instance
import com.google.gson.GsonBuilder
import es.dmoral.toasty.Toasty
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_ioio.*
import kotlinx.android.synthetic.main.fragment_ioio_content.*
import org.jetbrains.anko.*
import science.apolline.R
import science.apolline.models.Device
import science.apolline.models.IOIOData
import science.apolline.root.FragmentLifecycle
import science.apolline.utils.DataDeserializer
import science.apolline.utils.DataExport.exportShareCsv
import science.apolline.utils.DataExport.exportToCsv
import science.apolline.utils.DataExport.exportToJson
import science.apolline.root.RootFragment
import science.apolline.service.database.SensorDao
import science.apolline.utils.CheckUtility
import science.apolline.viewModel.SensorViewModel
import kotlin.math.roundToLong
import android.content.Context
import android.preference.PreferenceManager
import android.widget.TextView
import science.apolline.view.activity.MainActivity
class IOIOFragment : RootFragment(), FragmentLifecycle, AnkoLogger {
private val mSensorDao by instance<SensorDao>()
private lateinit var mDisposable: CompositeDisposable
private lateinit var mViewModel: SensorViewModel
private var mIsWriteToExternalStoragePermissionGranted = false
private lateinit var mPrefs: SharedPreferences
private lateinit var deviceAddress : String
private lateinit var deviceName : String
private val mRequestWriteToExternalStoragePermission by lazy {
permissionsBuilder(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewModel = ViewModelProviders.of(this).get(SensorViewModel::class.java).init(appKodein())
this.retainInstance = true
MainActivity.mFragment = this
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_ioio, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mDisposable = CompositeDisposable()
mPrefs = PreferenceManager.getDefaultSharedPreferences(activity)
deviceAddress = mPrefs.getString("sensor_mac_address","sensor_mac_address does not exist")
deviceName = mPrefs.getString("sensor_name", "sensor_name does not exist")
mIsWriteToExternalStoragePermissionGranted = CheckUtility.checkWriteToExternalStoragePermissionPermission (activity!!.applicationContext)
floating_action_menu_json.setOnClickListener {
if (!mIsWriteToExternalStoragePermissionGranted) {
checkWriteToExternalStoragePermission(mRequestWriteToExternalStoragePermission)
} else {
exportToJson(activity!!.application, mSensorDao)
}
}
floating_action_menu_csv_multi.setOnClickListener {
if (!mIsWriteToExternalStoragePermissionGranted) {
checkWriteToExternalStoragePermission(mRequestWriteToExternalStoragePermission)
} else {
exportToCsv(activity!!.application, mSensorDao, true)
}
}
floating_action_menu_csv.setOnClickListener {
if (!mIsWriteToExternalStoragePermissionGranted) {
checkWriteToExternalStoragePermission(mRequestWriteToExternalStoragePermission)
} else {
exportToCsv(activity!!.application, mSensorDao, false)
}
}
floating_action_menu_share.setOnClickListener {
if (!mIsWriteToExternalStoragePermissionGranted) {
checkWriteToExternalStoragePermission(mRequestWriteToExternalStoragePermission)
} else {
exportShareCsv(activity!!.application, mSensorDao, false)
}
}
fragment_ioio_progress_pm1.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
fragment_ioio_progress_pm2_5.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
fragment_ioio_progress_pm10.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
fragment_ioio_progress_rht.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
fragment_ioio_progress_tmpk.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
fragment_ioio_progress_tmpc.apply {
setTextMode(TextMode.VALUE)
setValue(0F)
}
}
override fun onStart() {
super.onStart()
if(this.deviceName.toLowerCase().contains(regex = "^ioio.".toRegex())) {
mDisposable.add(mViewModel.getDeviceList(MAX_DEVICE)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onExceptionResumeNext {
Flowable.empty<Device>()
}
.onErrorReturn {
error("Error device list not found $it")
emptyList()
}
.subscribe {
if (it.isNotEmpty()) {
val device = it.first()
val gsonBuilder = GsonBuilder().registerTypeAdapter(IOIOData::class.java, DataDeserializer()).create()
val data = gsonBuilder.fromJson(device.data, IOIOData::class.java)
sensorName.text = "sensor name : " + this.deviceName
val pm01 = data!!.pm01Value
val pm25 = data.pm2_5Value
val pm10 = data.pm10Value
val tempC = data.tempCelcius.roundToLong()
val tempK = data.tempKelvin.roundToLong()
val humidComp = data.rht.roundToLong()
fragment_ioio_progress_pm1.setValueAnimated(pm01.toFloat())
fragment_ioio_progress_pm2_5.setValueAnimated(pm25.toFloat())
fragment_ioio_progress_pm10.setValueAnimated(pm10.toFloat())
fragment_ioio_progress_rht.setValueAnimated(humidComp.toFloat())
fragment_ioio_progress_tmpk.setValueAnimated(tempK.toFloat())
fragment_ioio_progress_tmpc.setValueAnimated(tempC.toFloat())
} else {
fragment_ioio_progress_pm1.setValue(0.0f)
fragment_ioio_progress_pm2_5.setValue(0.0f)
fragment_ioio_progress_pm10.setValue(0.0f)
fragment_ioio_progress_rht.setValue(0.0f)
fragment_ioio_progress_tmpk.setValue(0.0f)
fragment_ioio_progress_tmpc.setValue(0.0f)
}
})
}
else {
sensorName.text = "sensor name : " + this.deviceName
fragment_ioio_progress_pm1.spin()
fragment_ioio_progress_pm1.setText("Loading...")
fragment_ioio_progress_pm2_5.spin()
fragment_ioio_progress_pm2_5.setText("Loading...")
fragment_ioio_progress_pm10.spin()
fragment_ioio_progress_pm10.setText("Loading...")
fragment_ioio_progress_rht.spin()
fragment_ioio_progress_rht.setText("Loading...")
fragment_ioio_progress_tmpk.spin()
fragment_ioio_progress_tmpk.setText("Loading...")
fragment_ioio_progress_tmpc.spin()
fragment_ioio_progress_tmpc.setText("Loading...")
}
info("onStart")
}
override fun onResume() {
super.onResume()
info("onResume")
}
override fun onPause() {
super.onPause()
info("onPause")
}
override fun onStop() {
super.onStop()
info("onStop")
}
override fun onDestroyView() {
if (!mDisposable.isDisposed)
mDisposable.dispose()
super.onDestroyView()
info("onDestroyView")
}
@SuppressLint("MissingSuperCall")
override fun onDestroy() {
if (!mDisposable.isDisposed)
mDisposable.dispose()
super.onDestroy()
info("onDestroy")
}
override fun onPauseFragment() {
info("IOIO onPauseFragment")
}
override fun onResumeFragment() {
info("IOIO onResumeFragment")
}
private fun checkWriteToExternalStoragePermission(request: PermissionRequest) {
info("check permission")
request.detachAllListeners()
request.send()
request.listeners {
onAccepted {
mIsWriteToExternalStoragePermissionGranted = true
Toasty.success(activity!!.applicationContext, "WRITE_EXTERNAL_STORAGE permission granted.", Toast.LENGTH_SHORT, true).show()
}
onDenied {
mIsWriteToExternalStoragePermissionGranted = false
Toasty.error(activity!!.applicationContext, "WRITE_EXTERNAL_STORAGE permission denied.", Toast.LENGTH_SHORT, true).show()
}
onPermanentlyDenied {
mIsWriteToExternalStoragePermissionGranted = false
Toasty.error(activity!!.applicationContext, "Fatal error, WRITE_EXTERNAL_STORAGE permission permanently denied, please grant it manually", Toast.LENGTH_LONG, true).show()
}
onShouldShowRationale { _, _ ->
mIsWriteToExternalStoragePermissionGranted = false
activity!!.alert("Apolline couldn't export any file, please grant WRITE_EXTERNAL_STORAGE permission.", "Request write permission") {
yesButton {
checkWriteToExternalStoragePermission(mRequestWriteToExternalStoragePermission)
}
noButton {}
}.show()
}
}
}
companion object {
val TAG = "IOIOFragment"
private const val MAX_DEVICE: Long = 10
}
}
| gpl-3.0 | 10328d5c721aa20c5decf83363560aee | 36.394649 | 186 | 0.632233 | 5.025169 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/theme/ThemeFittingRoomActivity.kt | 1 | 1637 | package org.wikipedia.theme
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import org.wikipedia.Constants
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.page.ExclusiveBottomSheetPresenter
class ThemeFittingRoomActivity : SingleFragmentActivity<ThemeFittingRoomFragment>(), ThemeChooserDialog.Callback {
private var themeChooserDialog: ThemeChooserDialog? = null
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
themeChooserDialog = ThemeChooserDialog.newInstance(Constants.InvokeSource.SETTINGS)
bottomSheetPresenter.show(supportFragmentManager, themeChooserDialog!!)
}
// Don't let changed theme affects the status bar color and navigation bar color
setStatusBarColor(ContextCompat.getColor(this, android.R.color.black))
setNavigationBarColor(ContextCompat.getColor(this, android.R.color.black))
}
override fun createFragment(): ThemeFittingRoomFragment {
return ThemeFittingRoomFragment.newInstance()
}
override fun onToggleDimImages() {
ActivityCompat.recreate(this)
}
override fun onCancelThemeChooser() {
finish()
}
companion object {
@JvmStatic
fun newIntent(context: Context): Intent {
return Intent(context, ThemeFittingRoomActivity::class.java)
}
}
}
| apache-2.0 | 0e3b3d43d921f450b13f0a631f9bdf15 | 34.586957 | 114 | 0.746487 | 5.263666 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateAnnotationAction.kt | 5 | 5083 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.AddAnnotationPsiFix
import com.intellij.lang.jvm.actions.AnnotationAttributeValueRequest
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.util.PsiTreeUtil
internal class CreateAnnotationAction(target: PsiModifierListOwner, override val request: AnnotationRequest) :
CreateTargetAction<PsiModifierListOwner>(target, request) {
override fun getText(): String =
AddAnnotationPsiFix.calcText(target, StringUtilRt.getShortName(request.qualifiedName))
override fun getFamilyName(): String = QuickFixBundle.message("create.annotation.family")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val modifierList = target.modifierList ?: return
addAnnotationToModifierList(modifierList, request)
}
override fun getFileModifierForPreview(targetFile: PsiFile): FileModifier {
val copy = PsiTreeUtil.findSameElementInCopy(target, targetFile)
return CreateAnnotationAction(copy, request)
}
companion object {
private val LOG = logger<CreateAnnotationAction>()
internal fun addAnnotationToModifierList(modifierList: PsiModifierList, annotationRequest: AnnotationRequest) {
val list = AddAnnotationPsiFix.expandParameterIfNecessary(modifierList)
addAnnotationToAnnotationOwner(modifierList, list, annotationRequest)
}
internal fun addAnnotationToAnnotationOwner(context: PsiElement,
list: PsiAnnotationOwner,
annotationRequest: AnnotationRequest) {
val project = context.project
val annotation = list.addAnnotation(annotationRequest.qualifiedName)
val psiElementFactory = PsiElementFactory.getInstance(project)
fillAnnotationAttributes(annotation, annotationRequest, psiElementFactory, context)
val formatter = CodeStyleManager.getInstance(project)
val codeStyleManager = JavaCodeStyleManager.getInstance(project)
codeStyleManager.shortenClassReferences(formatter.reformat(annotation))
}
private fun fillAnnotationAttributes(annotation: PsiAnnotation,
annotationRequest: AnnotationRequest,
psiElementFactory: PsiElementFactory,
context: PsiElement?) {
for ((name, value) in annotationRequest.attributes) {
val memberValue = attributeRequestToValue(value, psiElementFactory, context, annotationRequest)
annotation.setDeclaredAttributeValue(name.takeIf { name != "value" }, memberValue)
}
}
private fun attributeRequestToValue(value: AnnotationAttributeValueRequest,
psiElementFactory: PsiElementFactory,
context: PsiElement?,
annotationRequest: AnnotationRequest): PsiAnnotationMemberValue? = when (value) {
is AnnotationAttributeValueRequest.PrimitiveValue -> psiElementFactory
.createExpressionFromText(value.value.toString(), null)
is AnnotationAttributeValueRequest.StringValue -> psiElementFactory
.createExpressionFromText("\"" + StringUtil.escapeStringCharacters(value.value) + "\"", null)
is AnnotationAttributeValueRequest.ClassValue -> psiElementFactory
.createExpressionFromText(value.classFqn + ".class", context)
is AnnotationAttributeValueRequest.ConstantValue -> psiElementFactory
.createExpressionFromText(value.text, context)
is AnnotationAttributeValueRequest.NestedAnnotation -> psiElementFactory
.createAnnotationFromText("@" + value.annotationRequest.qualifiedName, context).also { nested ->
fillAnnotationAttributes(nested, value.annotationRequest, psiElementFactory, context)
}
is AnnotationAttributeValueRequest.ArrayValue -> {
val arrayExpressionText = value.members.joinToString {
attributeRequestToValue(it, psiElementFactory, context, annotationRequest)?.text ?: ""
}
val dummyAnnotation = psiElementFactory.createAnnotationFromText("@dummy({$arrayExpressionText})", context)
dummyAnnotation.findAttributeValue(null)
}
else -> {
LOG.error("adding annotation members of ${value.javaClass} type is not implemented")
null
}
}
}
}
| apache-2.0 | 6f8fb68ae0c01c87fc369695eab97c6b | 50.343434 | 158 | 0.730868 | 5.598018 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/projectTemplates/ProjectTemplatesPlugin.kt | 5 | 2247 | // 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.tools.projectWizard.plugins.projectTemplates
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.withAllSubModules
import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.ProjectTemplate
class ProjectTemplatesPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "projectTemplates"
val template by dropDownSetting<ProjectTemplate>(
KotlinNewProjectWizardBundle.message("plugin.templates.setting.template"),
GenerationPhase.INIT_TEMPLATE,
parser = valueParserM { _, _ ->
Failure(ParseError(KotlinNewProjectWizardBundle.message("error.text.project.templates.is.not.supported.in.yaml.for.now")))
},
) {
values = ProjectTemplate.ALL
isRequired = false
tooltipText = KotlinNewProjectWizardBundle.message("plugin.templates.setting.template.tooltip")
}
}
override val settings: List<PluginSetting<*, *>> = listOf(template)
override val pipelineTasks: List<PipelineTask> = listOf()
override val properties: List<Property<*>> = listOf()
}
fun SettingsWriter.applyProjectTemplate(projectTemplate: ProjectTemplate) {
projectTemplate.setsValues.forEach { (setting, value) ->
setting.setValue(value)
}
KotlinPlugin.modules.settingValue.withAllSubModules(includeSourcesets = true).forEach { module ->
module.apply { initDefaultValuesForSettings() }
}
} | apache-2.0 | 94335815425d29059e9e0f183e6266db | 47.869565 | 158 | 0.757454 | 4.916849 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/util/McpConstants.kt | 1 | 667 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.util
object McpConstants {
const val TEXT_FORMATTING = "net.minecraft.util.text.TextFormatting"
const val ENTITY = "net.minecraft.entity.Entity"
const val ENTITY_FX = "net.minecraft.client.particle.EntityFX"
const val WORLD = "net.minecraft.world.World"
const val ITEM_STACK = "net.minecraft.item.ItemStack"
const val BLOCK = "net.minecraft.block.Block"
const val ITEM = "net.minecraft.item.Item"
const val MINECRAFT_SERVER = "net.minecraft.server.MinecraftServer"
}
| mit | 1c5d8127a1cf4d3dc6262c9e43635750 | 28 | 72 | 0.718141 | 3.586022 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineUtils.kt | 2 | 5955 | // 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.debugger.coroutine.util
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.base.util.*
import org.jetbrains.kotlin.idea.debugger.core.canRunEvaluation
import org.jetbrains.kotlin.idea.debugger.core.invokeInManagerThread
import org.jetbrains.kotlin.idea.debugger.coroutine.data.SuspendExitMode
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
const val CREATION_STACK_TRACE_SEPARATOR = "\b\b\b" // the "\b\b\b" is used as creation stacktrace separator in kotlinx.coroutines
const val CREATION_CLASS_NAME = "_COROUTINE._CREATION"
fun Method.isInvokeSuspend(): Boolean =
name() == "invokeSuspend" && signature() == "(Ljava/lang/Object;)Ljava/lang/Object;"
fun Method.isInvoke(): Boolean =
name() == "invoke" && signature().contains("Ljava/lang/Object;)Ljava/lang/Object;")
fun Method.isSuspendLambda() =
isInvokeSuspend() && declaringType().isSuspendLambda()
fun Method.hasContinuationParameter() =
signature().contains("Lkotlin/coroutines/Continuation;)")
fun Location.getSuspendExitMode(): SuspendExitMode {
val method = safeMethod() ?: return SuspendExitMode.NONE
if (method.isSuspendLambda())
return SuspendExitMode.SUSPEND_LAMBDA
else if (method.hasContinuationParameter())
return SuspendExitMode.SUSPEND_METHOD_PARAMETER
else if ((method.isInvokeSuspend() || method.isInvoke()) && safeCoroutineExitPointLineNumber())
return SuspendExitMode.SUSPEND_METHOD
return SuspendExitMode.NONE
}
fun Location.safeCoroutineExitPointLineNumber() =
(wrapIllegalArgumentException { DebuggerUtilsEx.getLineNumber(this, false) } ?: -2) == -1
fun ReferenceType.isContinuation() =
isBaseContinuationImpl() || isSubtype("kotlin.coroutines.Continuation")
fun Type.isBaseContinuationImpl() =
isSubtype("kotlin.coroutines.jvm.internal.BaseContinuationImpl")
fun Type.isAbstractCoroutine() =
isSubtype("kotlinx.coroutines.AbstractCoroutine")
fun Type.isCoroutineScope() =
isSubtype("kotlinx.coroutines.CoroutineScope")
fun Type.isSubTypeOrSame(className: String) =
name() == className || isSubtype(className)
fun ReferenceType.isSuspendLambda() =
SUSPEND_LAMBDA_CLASSES.any { isSubtype(it) }
fun Location.isInvokeSuspend() =
safeMethod()?.isInvokeSuspend() ?: false
fun Location.isInvokeSuspendWithNegativeLineNumber() =
isInvokeSuspend() && safeLineNumber() < 0
fun Location.isFilteredInvokeSuspend() =
isInvokeSuspend() || isInvokeSuspendWithNegativeLineNumber()
fun StackFrameProxyImpl.variableValue(variableName: String): ObjectReference? {
val continuationVariable = safeVisibleVariableByName(variableName) ?: return null
return getValue(continuationVariable) as? ObjectReference ?: return null
}
fun StackFrameProxyImpl.continuationVariableValue(): ObjectReference? =
variableValue("\$continuation")
fun StackFrameProxyImpl.thisVariableValue(): ObjectReference? =
this.thisObject()
private fun Method.isGetCoroutineSuspended() =
signature() == "()Ljava/lang/Object;" && name() == "getCOROUTINE_SUSPENDED" && declaringType().name() == "kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsKt"
fun DefaultExecutionContext.findCoroutineMetadataType() =
debugProcess.invokeInManagerThread { findClassSafe("kotlin.coroutines.jvm.internal.DebugMetadataKt") }
fun DefaultExecutionContext.findDispatchedContinuationReferenceType(): List<ReferenceType>? =
vm.classesByName("kotlinx.coroutines.DispatchedContinuation")
fun DefaultExecutionContext.findCancellableContinuationImplReferenceType(): List<ReferenceType>? =
vm.classesByName("kotlinx.coroutines.CancellableContinuationImpl")
fun hasGetCoroutineSuspended(frames: List<StackFrameProxyImpl>) =
frames.indexOfFirst { it.safeLocation()?.safeMethod()?.isGetCoroutineSuspended() == true }
fun StackTraceElement.isCreationSeparatorFrame() =
className.startsWith(CREATION_STACK_TRACE_SEPARATOR) ||
className == CREATION_CLASS_NAME
fun Location.findPosition(debugProcess: DebugProcessImpl) = runReadAction {
DebuggerUtilsEx.toXSourcePosition(debugProcess.positionManager.getSourcePosition(this))
}
fun SuspendContextImpl.executionContext() =
invokeInManagerThread { DefaultExecutionContext(EvaluationContextImpl(this, this.frameProxy)) }
fun <T : Any> SuspendContextImpl.invokeInManagerThread(f: () -> T?): T? =
debugProcess.invokeInManagerThread { f() }
fun ThreadReferenceProxyImpl.supportsEvaluation(): Boolean =
threadReference?.isSuspended ?: false
fun SuspendContextImpl.supportsEvaluation() =
this.debugProcess.canRunEvaluation || isUnitTestMode()
fun threadAndContextSupportsEvaluation(suspendContext: SuspendContextImpl, frameProxy: StackFrameProxyImpl?) =
suspendContext.invokeInManagerThread {
suspendContext.supportsEvaluation() && frameProxy?.threadProxy()?.supportsEvaluation() ?: false
} ?: false
fun Location.sameLineAndMethod(location: Location?): Boolean =
location != null && location.safeMethod() == safeMethod() && location.safeLineNumber() == safeLineNumber()
fun Location.isFilterFromTop(location: Location?): Boolean =
isFilteredInvokeSuspend() || sameLineAndMethod(location) || location?.safeMethod() == safeMethod()
fun Location.isFilterFromBottom(location: Location?): Boolean =
sameLineAndMethod(location) | apache-2.0 | d70263159903e53b0744e8baea734214 | 43.118519 | 166 | 0.785894 | 4.677926 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHTokenCredentialsUi.kt | 2 | 5205 | // 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 org.jetbrains.plugins.github.authentication.ui
import com.intellij.ide.BrowserUtil.browse
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.layout.*
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil.buildNewTokenUrl
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.exceptions.GithubParseException
import org.jetbrains.plugins.github.i18n.GithubBundle.message
import org.jetbrains.plugins.github.ui.util.DialogValidationUtils.notBlank
import org.jetbrains.plugins.github.ui.util.Validator
import java.net.UnknownHostException
import javax.swing.JComponent
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
internal class GHTokenCredentialsUi(
private val serverTextField: ExtendableTextField,
val factory: GithubApiRequestExecutor.Factory,
val isAccountUnique: UniqueLoginPredicate
) : GHCredentialsUi() {
private val tokenTextField = JBPasswordField()
private var fixedLogin: String? = null
fun setToken(token: String) {
tokenTextField.text = token
}
override fun Panel.centerPanel() {
row(message("credentials.server.field")) { cell(serverTextField).horizontalAlign(HorizontalAlign.FILL) }
row(message("credentials.token.field")) {
cell(tokenTextField)
.comment(message("login.insufficient.scopes", GHSecurityUtil.MASTER_SCOPES))
.horizontalAlign(HorizontalAlign.FILL)
.resizableColumn()
button(message("credentials.button.generate")) { browseNewTokenUrl() }
.enabledIf(serverTextField.serverValid)
}
}
private fun browseNewTokenUrl() = browse(buildNewTokenUrl(serverTextField.tryParseServer()!!))
override fun getPreferredFocusableComponent(): JComponent = tokenTextField
override fun getValidator(): Validator = { notBlank(tokenTextField, message("login.token.cannot.be.empty")) }
override fun createExecutor() = factory.create(tokenTextField.text)
override fun acquireLoginAndToken(
server: GithubServerPath,
executor: GithubApiRequestExecutor,
indicator: ProgressIndicator
): Pair<String, String> {
val login = acquireLogin(server, executor, indicator, isAccountUnique, fixedLogin)
return login to tokenTextField.text
}
override fun handleAcquireError(error: Throwable): ValidationInfo =
when (error) {
is GithubParseException -> ValidationInfo(error.message ?: message("credentials.invalid.server.path"), serverTextField)
else -> handleError(error)
}
override fun setBusy(busy: Boolean) {
tokenTextField.isEnabled = !busy
}
fun setFixedLogin(fixedLogin: String?) {
this.fixedLogin = fixedLogin
}
companion object {
fun acquireLogin(
server: GithubServerPath,
executor: GithubApiRequestExecutor,
indicator: ProgressIndicator,
isAccountUnique: UniqueLoginPredicate,
fixedLogin: String?
): String {
val (details, scopes) = GHSecurityUtil.loadCurrentUserWithScopes(executor, indicator, server)
if (scopes == null || !GHSecurityUtil.isEnoughScopes(scopes))
throw GithubAuthenticationException("Insufficient scopes granted to token.")
val login = details.login
if (fixedLogin != null && fixedLogin != login) throw GithubAuthenticationException("Token should match username \"$fixedLogin\"")
if (!isAccountUnique(login, server)) throw LoginNotUniqueException(login)
return login
}
fun handleError(error: Throwable): ValidationInfo =
when (error) {
is LoginNotUniqueException -> ValidationInfo(message("login.account.already.added", error.login)).withOKEnabled()
is UnknownHostException -> ValidationInfo(message("server.unreachable")).withOKEnabled()
is GithubAuthenticationException -> ValidationInfo(message("credentials.incorrect", error.message.orEmpty())).withOKEnabled()
else -> ValidationInfo(message("credentials.invalid.auth.data", error.message.orEmpty())).withOKEnabled()
}
}
}
private val JTextField.serverValid: ComponentPredicate
get() = object : ComponentPredicate() {
override fun invoke(): Boolean = tryParseServer() != null
override fun addListener(listener: (Boolean) -> Unit) =
document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = listener(tryParseServer() != null)
})
}
private fun JTextField.tryParseServer(): GithubServerPath? =
try {
GithubServerPath.from(text.trim())
}
catch (e: GithubParseException) {
null
} | apache-2.0 | 4ef1a666f47e5b66a7ab32fe705ddfd6 | 39.671875 | 140 | 0.76292 | 4.710407 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExceptionToThrowsFix.kt | 1 | 2844 | // 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.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.idea.core.ShortenReferences
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.konan.diagnostics.ErrorsNative.MISSING_EXCEPTION_IN_THROWS_ON_SUSPEND
class AddExceptionToThrowsFix(
element: KtAnnotationEntry,
private val argumentClassFqName: FqName
) : KotlinQuickFixAction<KtAnnotationEntry>(element) {
override fun getText(): String = KotlinBundle.message(
"fix.add.exception.to.throws",
"${argumentClassFqName.shortName().asString()}::class"
)
override fun getFamilyName() = this.text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val annotationEntry = element ?: return
val psiFactory = KtPsiFactory(project)
val argumentText = "${argumentClassFqName.asString()}::class"
val added = annotationEntry.valueArgumentList?.addArgument(psiFactory.createArgument(argumentText))
if (added != null) ShortenReferences.DEFAULT.process(added)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null
val valueArgumentsList = annotationEntry.valueArgumentList
?: return null // Note: shouldn't reach here, frontend doesn't report MISSING_EXCEPTION_IN_THROWS_ON_SUSPEND in this case.
if (valueArgumentsList.arguments.firstOrNull()?.getArgumentName() != null) {
// E.g. @Throws(exceptionClasses = [Foo::class]).
// Unsupported at the moment:
return null
// Note: AddThrowsAnnotationIntention has the code to support this case, but a refactoring is required to use it.
}
val missingExceptionFqName = when (diagnostic.factory) {
MISSING_EXCEPTION_IN_THROWS_ON_SUSPEND -> MISSING_EXCEPTION_IN_THROWS_ON_SUSPEND.cast(diagnostic).a
else -> return null
}
return AddExceptionToThrowsFix(annotationEntry, missingExceptionFqName)
}
}
}
| apache-2.0 | c499662c97e33ed2bba4373aa5a4e888 | 45.622951 | 158 | 0.725387 | 4.878216 | false | false | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/util.kt | 2 | 4555 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.dataFlow
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiTreeUtil
import it.unimi.dsi.fastutil.objects.Object2IntMap
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrInstanceOfExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.MixinTypeInstruction
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ArgumentsInstruction
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isExpressionStatement
internal fun GrControlFlowOwner.getVarIndexes(): Object2IntMap<VariableDescriptor> {
return CachedValuesManager.getCachedValue(this) {
Result.create(doGetVarIndexes(this), PsiModificationTracker.MODIFICATION_COUNT)
}
}
private fun doGetVarIndexes(owner: GrControlFlowOwner): Object2IntMap<VariableDescriptor> {
val result = Object2IntOpenHashMap<VariableDescriptor>()
var num = 1
for (instruction in owner.controlFlow) {
if (instruction !is ReadWriteVariableInstruction) continue
val descriptor = instruction.descriptor
if (!result.containsKey(descriptor)) {
result.put(descriptor, num++)
}
}
return result
}
private typealias InstructionsByElement = (PsiElement) -> Collection<Instruction>
private typealias ReadInstructions = Collection<ReadWriteVariableInstruction>
internal fun findReadDependencies(writeInstruction: Instruction, instructionsByElement: InstructionsByElement): ReadInstructions {
require(
writeInstruction is ReadWriteVariableInstruction && writeInstruction.isWrite ||
writeInstruction is MixinTypeInstruction ||
writeInstruction is ArgumentsInstruction
)
val element = writeInstruction.element ?: return emptyList()
val scope = findDependencyScope(element) ?: return emptyList()
return findReadsInside(scope, instructionsByElement)
}
private fun findDependencyScope(element: PsiElement): PsiElement? {
if (element is GrVariable) {
val parent = element.parent
if (parent is GrVariableDeclaration && parent.isTuple) {
return parent
}
}
return PsiTreeUtil.findFirstParent(element) {
(it.parent !is GrExpression || it is GrMethodCallExpression || it is GrBinaryExpression || it is GrInstanceOfExpression || isExpressionStatement(it))
}
}
private fun findReadsInside(scope: PsiElement, instructionsByElement: InstructionsByElement): ReadInstructions {
if (scope is GrForInClause) {
val expression = scope.iteratedExpression ?: return emptyList()
return findReadsInside(expression, instructionsByElement)
}
val result = ArrayList<ReadWriteVariableInstruction>()
scope.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
if (element is GrReferenceExpression && !element.isQualified || element is GrParameter && element.parent is GrForInClause) {
val instructions = instructionsByElement(element)
for (instruction in instructions) {
if (instruction !is ReadWriteVariableInstruction || instruction.isWrite) continue
result += instruction
}
}
super.visitElement(element)
}
})
return result
}
| apache-2.0 | 5172145efd549f9b2ac3bb9b03d30f50 | 47.978495 | 153 | 0.806367 | 4.652707 | false | false | false | false |
jshmrsn/klaxon | src/main/kotlin/com/beust/klaxon/Lookup.kt | 1 | 2978 | package com.beust.klaxon
import java.math.BigInteger
import java.util.ArrayList
@Suppress("UNCHECKED_CAST")
public fun <T> JsonObject.array(fieldName: String) : JsonArray<T>? = get(fieldName) as JsonArray<T>?
public fun JsonObject.obj(fieldName: String) : JsonObject? = get(fieldName) as JsonObject?
public fun JsonObject.int(fieldName: String) : Int? {
val value = get(fieldName)
when (value) {
is Number -> return value.toInt()
else -> return value as Int?
}
}
public fun JsonObject.long(fieldName: String) : Long? {
val value = get(fieldName)
when (value) {
is Number -> return value.toLong()
else -> return value as Long?
}
}
public fun JsonObject.bigInt(fieldName: String) : BigInteger? = get(fieldName) as BigInteger
public fun JsonObject.string(fieldName: String) : String? = get(fieldName) as String?
public fun JsonObject.double(fieldName: String) : Double? = get(fieldName) as Double?
public fun JsonObject.boolean(fieldName: String) : Boolean? = get(fieldName) as Boolean?
public fun JsonArray<*>.string(id: String) : JsonArray<String?> = mapChildren { it.string(id) }
public fun JsonArray<*>.obj(id: String) : JsonArray<JsonObject?> = mapChildren { it.obj(id) }
public fun JsonArray<*>.long(id: String) : JsonArray<Long?> = mapChildren { it.long(id) }
public fun JsonArray<*>.int(id: String) : JsonArray<Int?> = mapChildren { it.int(id) }
public fun JsonArray<*>.bigInt(id: String) : JsonArray<BigInteger?> = mapChildren { it.bigInt(id) }
public fun JsonArray<*>.double(id: String) : JsonArray<Double?> = mapChildren { it.double(id) }
public fun <T> JsonArray<*>.mapChildrenObjectsOnly(block : (JsonObject) -> T) : JsonArray<T> =
JsonArray<T>(flatMapTo(ArrayList<T>(size)) {
if (it is JsonObject) listOf<T>(block(it))
else if (it is JsonArray<*>) it.mapChildrenObjectsOnly(block)
else listOf()
})
public fun <T : Any> JsonArray<*>.mapChildren(block : (JsonObject) -> T?) : JsonArray<T?> =
JsonArray<T?>(flatMapTo(ArrayList<T?>(size)) {
if (it is JsonObject) listOf<T?>(block(it))
else if (it is JsonArray<*>) it.mapChildren(block)
else listOf<T?>(null)
})
operator public fun JsonArray<*>.get(key : String) : JsonArray<Any?> = mapChildren { it[key] }
@Suppress("UNCHECKED_CAST")
private fun <T> Any?.ensureArray() : JsonArray<T> =
if (this is JsonArray<*>) this as JsonArray<T>
else JsonArray(this as T)
public fun <T> JsonBase.lookup(key : String) : JsonArray<T> =
key.split("[/\\.]".toRegex())
.filter{ it != "" }
.fold(this) { j, part ->
when (j) {
is JsonArray<*> -> j[part]
is JsonObject -> j[part].ensureArray<T>()
else -> throw IllegalArgumentException("unsupported type of j = $j")
}
}.ensureArray<T>()
| apache-2.0 | ecf057b5b84450cb9eb2bbb040fb61de | 42.794118 | 100 | 0.625923 | 3.852523 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/fragment/SimpleDialogFragment.kt | 1 | 1199 | package jp.cordea.mackerelclient.fragment
import android.app.Dialog
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
class SimpleDialogFragment : DialogFragment() {
private val title get() = arguments!!.getInt(TITLE_KEY, 0)
private val message get() = arguments!!.getInt(MESSAGE_KEY, 0)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
AlertDialog.Builder(context!!)
.apply {
if (message == 0) {
setMessage(title)
} else {
setTitle(title)
setMessage(message)
}
}
.create()
companion object {
private const val TITLE_KEY = "TitleKey"
private const val MESSAGE_KEY = "MessageKey"
fun newInstance(@StringRes title: Int, @StringRes message: Int = 0) =
SimpleDialogFragment().apply {
arguments = bundleOf(
TITLE_KEY to title,
MESSAGE_KEY to message
)
}
}
}
| apache-2.0 | 5b1140732654f360b633f0e4ca1cef04 | 30.552632 | 77 | 0.585488 | 5.102128 | false | false | false | false |
zdary/intellij-community | platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt | 1 | 11850 | // 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.dvcs.ignore
import com.intellij.CommonBundle
import com.intellij.ProjectTopics
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.projectView.actions.MarkExcludeRootAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FilesProcessorImpl
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import java.util.*
private val LOG = logger<IgnoredToExcludedSynchronizer>()
private val excludeAction = object : MarkExcludeRootAction() {
fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) }
}
// Not internal service. Can be used directly in related modules.
@Service
class IgnoredToExcludedSynchronizer(project: Project) : VcsIgnoredHolderUpdateListener, FilesProcessorImpl(project, project) {
override val askedBeforeProperty = ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
override val doForCurrentProjectProperty: String? = null
init {
project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) = updateNotificationState()
})
}
private fun updateNotificationState() {
if (synchronizationTurnOff()) return
// in case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated.
// filter directories which excluded or containing source roots and expire notification if needed.
ChangeListManager.getInstance(project).invokeAfterUpdate(false) {
val fileIndex = ProjectFileIndex.getInstance(project)
val sourceRoots = getProjectSourceRoots(project)
val acquiredFiles = acquireValidFiles()
LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles)
val filesToRemove = acquiredFiles
.asSequence()
.filter { file -> runReadAction { fileIndex.isExcluded(file) } || sourceRoots.contains(file) }
.toList()
LOG.debug("updateNotificationState, filesToRemove", filesToRemove)
if (removeFiles(filesToRemove)) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
}
fun isNotEmpty() = !isFilesEmpty()
fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files)
fun getValidFiles() = with(ChangeListManager.getInstance(project)) { acquireValidFiles().filter(this::isIgnoredFile) }
fun muteForCurrentProject() {
setForCurrentProject(false)
PropertiesComponent.getInstance(project).setValue(askedBeforeProperty, true)
clearFiles()
}
fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject()
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
if (files.isEmpty()) return
markIgnoredAsExcluded(project, files)
}
override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid)
override fun rememberForAllProjects() {}
override fun rememberForCurrentProject() {
VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED = true
}
override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED
override fun updateFinished(ignoredPaths: Collection<FilePath>, isFullRescan: Boolean) {
ProgressManager.checkCanceled()
if (synchronizationTurnOff()) return
if (!isFullRescan) return
if (!VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED && wasAskedBefore()) return
processIgnored(ignoredPaths)
}
private fun processIgnored(ignoredPaths: Collection<FilePath>) {
val ignoredDirs =
determineIgnoredDirsToExclude(project, ignoredPaths)
if (allowShowNotification()) {
processFiles(ignoredDirs)
val editorNotifications = EditorNotifications.getInstance(project)
FileEditorManager.getInstance(project).openFiles
.forEach { openFile ->
if (openFile.fileType is IgnoreFileType) {
editorNotifications.updateNotifications(openFile)
}
}
}
else if (needDoForCurrentProject()) {
doActionOnChosenFiles(doFilterFiles(ignoredDirs))
}
}
}
private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) {
val ignoredDirsByModule =
files
.groupBy { ModuleUtil.findModuleForFile(it, project) }
//if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing.
.filterKeys(Objects::nonNull)
for ((module, ignoredDirs) in ignoredDirsByModule) {
excludeAction.exclude(module!!, ignoredDirs)
}
}
private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction {
OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet()
}
private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) =
FileUtil.isAncestor(shelfPath, filePath.path, false) ||
FileUtil.isAncestor(filePath.path, shelfPath, false)
private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> {
val sourceRoots = getProjectSourceRoots(project)
val fileIndex = ProjectFileIndex.getInstance(project)
val shelfPath = ShelveChangesManager.getShelfPath(project)
return ignoredPaths
.asSequence()
.filter(FilePath::isDirectory)
//shelf directory usually contains in project and excluding it prevents local history to work on it
.filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) }
.mapNotNull(FilePath::getVirtualFile)
.filterNot { runReadAction { fileIndex.isExcluded(it) } }
//do not propose to exclude if there is a source root inside
.filterNot { ignored -> sourceRoots.contains(ignored) }
.toList()
}
private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> {
val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs)
if (!dialog.showAndGet()) return emptyList()
return dialog.selectedFiles
}
private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true)
private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true)
class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider")
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
private fun canCreateNotification(project: Project, file: VirtualFile) =
file.fileType is IgnoreFileType &&
with(project.service<IgnoredToExcludedSynchronizer>()) {
!synchronizationTurnOff() &&
allowShowNotification() &&
!mutedForCurrentProject() &&
isNotEmpty()
}
private fun showIgnoredAction(project: Project) {
val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles()
if (allFiles.isEmpty()) return
val userSelectedFiles = selectFilesToExclude(project, allFiles)
if (userSelectedFiles.isEmpty()) return
with(project.service<IgnoredToExcludedSynchronizer>()) {
markIgnoredAsExcluded(project, userSelectedFiles)
clearFiles(userSelectedFiles)
}
}
private fun muteAction(project: Project) = Runnable {
project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject()
EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider)
}
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (!canCreateNotification(project, file)) return null
return EditorNotificationPanel(fileEditor).apply {
icon(AllIcons.General.Information)
text = message("ignore.to.exclude.notification.message")
createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) }
createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project))
createActionLabel(message("ignore.to.exclude.notification.action.details")) {
BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories") }
}
}
}
internal class CheckIgnoredToExcludeAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changeListManager = ChangeListManager.getInstance(project)
changeListManager.invokeAfterUpdateWithModal(false, ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress")) {
val dirsToExclude = determineIgnoredDirsToExclude(project, changeListManager.ignoredFilePaths)
if (dirsToExclude.isEmpty()) {
VcsNotifier.getInstance(project)
.notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found"))
}
else {
val userSelectedFiles = selectFilesToExclude(project, dirsToExclude)
if (userSelectedFiles.isNotEmpty()) {
markIgnoredAsExcluded(project, userSelectedFiles)
}
}
}
}
}
// do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked
private class IgnoredToExcludeSelectDirectoriesDialog(
project: Project?,
files: List<VirtualFile>
) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) {
init {
title = message("ignore.to.exclude.view.dialog.title")
selectedFiles = files
setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action"))
setCancelButtonText(CommonBundle.getCancelButtonText())
init()
}
}
| apache-2.0 | 4a706bf7e3f39be5fb886bde91d46272 | 40.872792 | 146 | 0.775781 | 4.706116 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanPhases.kt | 1 | 7015 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.backend.konan.util.*
import org.jetbrains.kotlin.konan.util.*
import org.jetbrains.kotlin.konan.target.CompilerOutputKind
enum class KonanPhase(val description: String,
vararg prerequisite: KonanPhase,
var enabled: Boolean = true,
var verbose: Boolean = false) {
/* */ FRONTEND("Frontend builds AST"),
/* */ PSI_TO_IR("Psi to IR conversion"),
/* */ SERIALIZER("Serialize descriptor tree and inline IR bodies"),
/* */ BACKEND("All backend"),
/* ... */ LOWER("IR Lowering"),
/* ... ... */ TEST_PROCESSOR("Unit test processor"),
/* ... ... */ LOWER_BEFORE_INLINE("Special operations processing before inlining"),
/* ... ... */ LOWER_INLINE_CONSTRUCTORS("Inline constructors transformation", LOWER_BEFORE_INLINE),
/* ... ... */ LOWER_INLINE("Functions inlining", LOWER_INLINE_CONSTRUCTORS, LOWER_BEFORE_INLINE),
/* ... ... */ LOWER_AFTER_INLINE("Special operations processing after inlining"),
/* ... ... ... */ DESERIALIZER("Deserialize inline bodies"),
/* ... ... */ LOWER_INTEROP_PART1("Interop lowering, part 1", LOWER_INLINE),
/* ... ... */ LOWER_FOR_LOOPS("For loops lowering"),
/* ... ... */ LOWER_ENUMS("Enum classes lowering"),
/* ... ... */ LOWER_DELEGATION("Delegation lowering"),
/* ... ... */ LOWER_INITIALIZERS("Initializers lowering", LOWER_ENUMS),
/* ... ... */ LOWER_SHARED_VARIABLES("Shared Variable Lowering", LOWER_INITIALIZERS),
/* ... ... */ LOWER_CALLABLES("Callable references Lowering", LOWER_DELEGATION),
/* ... ... */ LOWER_LOCAL_FUNCTIONS("Local Function Lowering", LOWER_SHARED_VARIABLES, LOWER_CALLABLES),
/* ... ... */ LOWER_INTEROP_PART2("Interop lowering, part 2", LOWER_LOCAL_FUNCTIONS),
/* ... ... */ LOWER_VARARG("Vararg lowering", LOWER_CALLABLES),
/* ... ... */ LOWER_TAILREC("tailrec lowering", LOWER_LOCAL_FUNCTIONS),
/* ... ... */ LOWER_FINALLY("Finally blocks lowering", LOWER_INITIALIZERS, LOWER_LOCAL_FUNCTIONS, LOWER_TAILREC),
/* ... ... */ LOWER_DEFAULT_PARAMETER_EXTENT("Default Parameter Extent Lowering", LOWER_TAILREC, LOWER_ENUMS),
/* ... ... */ LOWER_INNER_CLASSES("Inner classes lowering", LOWER_DEFAULT_PARAMETER_EXTENT),
/* ... ... */ LOWER_LATEINIT("Lateinit properties lowering"),
/* ... ... */ LOWER_BUILTIN_OPERATORS("BuiltIn Operators Lowering", LOWER_DEFAULT_PARAMETER_EXTENT, LOWER_LATEINIT),
/* ... ... */ LOWER_COROUTINES("Coroutines lowering", LOWER_LOCAL_FUNCTIONS),
/* ... ... */ LOWER_TYPE_OPERATORS("Type operators lowering", LOWER_COROUTINES),
/* ... ... */ BRIDGES_BUILDING("Bridges building", LOWER_COROUTINES),
/* ... ... */ LOWER_STRING_CONCAT("String concatenation lowering"),
/* ... ... */ LOWER_DATA_CLASSES("Data classes lowering"),
/* ... ... */ AUTOBOX("Autoboxing of primitive types", BRIDGES_BUILDING, LOWER_COROUTINES),
/* ... ... */ RETURNS_INSERTION("Returns insertion for Unit functions", AUTOBOX, LOWER_COROUTINES, LOWER_ENUMS),
/* ... */ BITCODE("LLVM BitCode Generation"),
/* ... ... */ RTTI("RTTI Generation"),
/* ... ... */ BUILD_DFG("Data flow graph building"),
/* ... ... */ SERIALIZE_DFG("Data flow graph serializing", BUILD_DFG),
/* ... ... */ DESERIALIZE_DFG("Data flow graph deserializing"),
/* ... ... */ ESCAPE_ANALYSIS("Escape analysis", BUILD_DFG, DESERIALIZE_DFG, enabled = false),
/* ... ... */ CODEGEN("Code Generation"),
/* ... ... */ BITCODE_LINKER("Bitcode linking"),
/* */ LINK_STAGE("Link stage"),
/* ... */ OBJECT_FILES("Bitcode to object file"),
/* ... */ LINKER("Linker");
val prerequisite = prerequisite.toSet()
}
object KonanPhases {
val phases = KonanPhase.values().associate { it.visibleName to it }
fun known(name: String): String {
if (phases[name] == null) {
error("Unknown phase: $name. Use --list_phases to see the list of phases.")
}
return name
}
fun config(config: KonanConfig) {
with (config.configuration) { with (KonanConfigKeys) {
// Don't serialize anything to a final executable.
KonanPhase.SERIALIZER.enabled =
(config.produce == CompilerOutputKind.LIBRARY)
KonanPhase.LINK_STAGE.enabled = config.produce.isNativeBinary
KonanPhase.TEST_PROCESSOR.enabled = getBoolean(GENERATE_TEST_RUNNER)
val disabled = get(DISABLED_PHASES)
disabled?.forEach { phases[known(it)]!!.enabled = false }
val enabled = get(ENABLED_PHASES)
enabled?.forEach { phases[known(it)]!!.enabled = true }
val verbose = get(VERBOSE_PHASES)
verbose?.forEach { phases[known(it)]!!.verbose = true }
}}
}
fun list() {
phases.forEach { key, phase ->
val enabled = if (phase.enabled) "(Enabled)" else ""
val verbose = if (phase.verbose) "(Verbose)" else ""
println(String.format("%1$-30s%2$-30s%3$-10s", "${key}:", phase.description, "$enabled $verbose"))
}
}
}
internal class PhaseManager(val context: Context) {
val previousPhases = mutableSetOf<KonanPhase>()
internal fun phase(phase: KonanPhase, body: () -> Unit) {
if (!phase.enabled) return
phase.prerequisite.forEach {
if (!previousPhases.contains(it))
throw Error("$phase requires $it")
}
previousPhases.add(phase)
val savePhase = context.phase
context.phase = phase
context.depth ++
with (context) {
profileIf(shouldProfilePhases(), "Phase ${nTabs(depth)} ${phase.name}") {
body()
}
if (shouldVerifyDescriptors()) {
verifyDescriptors()
}
if (shouldVerifyIr()) {
verifyIr()
}
if (shouldPrintDescriptors()) {
printDescriptors()
}
if (shouldPrintIr()) {
printIr()
}
if (shouldPrintIrWithDescriptors()) {
printIrWithDescriptors()
}
if (shouldPrintLocations()) {
printLocations()
}
}
context.depth --
context.phase = savePhase
}
}
| apache-2.0 | 4e8d5af2d84d6cae8591479034002198 | 41.005988 | 120 | 0.596436 | 4.303681 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/worldguard/WorldGuardFlags.kt | 1 | 1711 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.worldguard
object WorldGuardFlags {
const val mythicDrops = "mythic-drops"
const val mythicDropsTiered = "mythic-drops-tiered"
const val mythicDropsCustom = "mythic-drops-custom"
const val mythicDropsSocketGem = "mythic-drops-socket-gem"
const val mythicDropsIdentityTome = "mythic-drops-identity-tome"
const val mythicDropsUnidentifiedItem = "mythic-drops-unidentified-item"
const val mythicDropsSocketExtender = "mythic-drops-socket-extender"
}
| mit | 83bf4a78457cd89027dd3d34d862a094 | 52.46875 | 105 | 0.769725 | 4.421189 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/print/FileUtils.kt | 2 | 2234 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.print
import android.content.Context
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.print.PageRange
import android.print.PrintDocumentAdapter
import android.util.Base64
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.RandomAccessFile
import java.util.*
object FileUtils {
// http://stackoverflow.com/a/38858040/1771921
fun uriFromFile(file: File?): Uri {
return Uri.fromFile(file)
}
@Throws(IOException::class)
fun ensureDirExists(dir: File): File {
if (!(dir.isDirectory || dir.mkdirs())) {
throw IOException("Couldn't create directory '$dir'")
}
return dir
}
@Throws(IOException::class)
fun generateOutputPath(internalDirectory: File, dirName: String, extension: String): String {
val directory = File(internalDirectory.toString() + File.separator + dirName)
ensureDirExists(directory)
val filename = UUID.randomUUID().toString()
return directory.toString() + File.separator + filename + extension
}
@Throws(IOException::class)
fun copyToOutputStream(destination: ParcelFileDescriptor, callback: PrintDocumentAdapter.WriteResultCallback, input: InputStream) {
FileOutputStream(destination.fileDescriptor).use { fileOut ->
input.copyTo(fileOut)
}
callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES))
}
fun decodeDataURI(uri: String): InputStream {
val base64Index = uri.indexOf(";base64,")
val plainBase64 = uri.substring(base64Index + 8)
val byteArray = Base64.decode(plainBase64, Base64.DEFAULT)
return ByteArrayInputStream(byteArray)
}
@Throws(IOException::class)
fun generateFilePath(context: Context): String {
return generateOutputPath(context.cacheDir, "Print", ".pdf")
}
@Throws(IOException::class)
fun encodeFromFile(file: File): String {
val randomAccessFile = RandomAccessFile(file, "r")
val fileBytes = ByteArray(randomAccessFile.length().toInt())
randomAccessFile.readFully(fileBytes)
return Base64.encodeToString(fileBytes, Base64.NO_WRAP)
}
}
| bsd-3-clause | 39252cd4570560e6dffe484b4b5d3f32 | 32.343284 | 133 | 0.749776 | 4.175701 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/StaticImport.kt | 12 | 3221 | // 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 org.jetbrains.plugins.groovy.lang.resolve.imports
import com.intellij.openapi.util.text.StringUtil.getQualifiedName
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils.*
import org.jetbrains.plugins.groovy.lang.resolve.getName
import org.jetbrains.plugins.groovy.lang.resolve.imports.impl.NonFqnImport
import org.jetbrains.plugins.groovy.lang.resolve.isAnnotationResolve
import org.jetbrains.plugins.groovy.lang.resolve.processors.StaticMembersFilteringProcessor
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMembers
/**
* Represents a static import, possibly aliased.
*
* Example: in `import static com.Foo.Bar as Baz`:
* - [classFqn] = `com.Foo`
* - [memberName] = `Bar`
* - [name] = `Baz`
* - [isAliased] = `true`
*
* Example: in `import static com.Foo.Bar`:
* - [classFqn] = `com.Foo`
* - [memberName] = `Bar`
* - [name] = `Bar`
* - [isAliased] = `false`
*/
data class StaticImport constructor(
override val classFqn: String,
val memberName: String,
override val name: String
) : NonFqnImport(), GroovyNamedImport {
constructor(classFqn: String, memberName: String) : this(classFqn, memberName, memberName)
override val isAliased: Boolean = memberName != name
override val shortName: String get() = memberName
override val fullyQualifiedName: String get() = getQualifiedName(classFqn, memberName)
override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement, file: GroovyFileBase): Boolean {
if (processor.isAnnotationResolve()) return true
if (!processor.shouldProcessMembers()) return true
val clazz = resolveImport(file) ?: return true
val namesMapping = namesMapping()
val hintName = processor.getName(state)
for ((memberName, alias) in namesMapping) {
if (hintName != null && hintName != alias) continue
val delegate = StaticMembersFilteringProcessor(processor, memberName)
if (!clazz.processDeclarations(delegate, state.put(importedNameKey, alias), null, place)) return false
}
return true
}
override fun isUnnecessary(imports: GroovyFileImports): Boolean {
if (isAliased) return false
return StaticStarImport(classFqn) in imports.staticStarImports
}
@NonNls
override fun toString(): String = "import static $classFqn.$memberName as $name"
private fun namesMapping() = namesMapping(memberName, name)
companion object {
private fun names(name: String): List<String> = listOf(
name,
getGetterNameNonBoolean(name),
getGetterNameBoolean(name),
getSetterName(name)
)
private fun namesMapping(left: String, right: String): List<Pair<String, String>> {
val leftNames = names(left)
val rightNames = if (left == right) leftNames
else names(
right)
return leftNames.zip(rightNames)
}
}
}
| apache-2.0 | 833b42eec7841087f502752b7b1b6d2a | 36.022989 | 140 | 0.738901 | 4.150773 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/ActionToolbar.kt | 1 | 2646 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.headertoolbar
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionButtonComponent
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.IdeaActionButtonLook
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.ScalableIcon
import com.intellij.util.ui.JBUI
import java.awt.*
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.UIManager
private const val iconSize = 20
internal class ActionToolbar(actions: List<AnAction>) : JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) {
init {
border = null
isOpaque = false
actions.map { createButton(it) }.forEach { add(it)}
}
private fun createButton(action: AnAction): JComponent {
val insets = UIManager.getInsets("MainToolbar.Icon.borderInsets") ?: JBUI.insets(10)
val presentation = action.templatePresentation.clone()
presentation.scaleIcon(iconSize)
presentation.addPropertyChangeListener { evt -> if (evt.propertyName == Presentation.PROP_ICON) presentation.scaleIcon(iconSize) }
if (presentation.icon == null) presentation.icon = AllIcons.Toolbar.Unknown
val size = Dimension(iconSize + insets.left + insets.right,
iconSize + insets.top + insets.bottom)
val button = ActionButton(action, presentation, ActionPlaces.MAIN_TOOLBAR, size)
button.setLook(MainToolbarLook())
return button
}
private fun Presentation.scaleIcon(size: Int) {
if (icon == null) return
if (icon is ScalableIcon && icon.iconWidth != size) {
icon = IconLoader.loadCustomVersionOrScale(icon as ScalableIcon, size.toFloat())
}
}
}
private class MainToolbarLook : IdeaActionButtonLook() {
override fun getStateBackground(component: JComponent, state: Int): Color = when (state) {
ActionButtonComponent.NORMAL -> component.background
ActionButtonComponent.PUSHED -> UIManager.getColor("MainToolbar.Icon.pressedBackground")
?: UIManager.getColor("ActionButton.pressedBackground")
else -> UIManager.getColor("MainToolbar.Icon.hoverBackground")
?: UIManager.getColor("ActionButton.hoverBackground")
}
override fun paintLookBorder(g: Graphics, rect: Rectangle, color: Color) {}
}
| apache-2.0 | edcb7fb530b6e944e00d61fa57afc3b9 | 41 | 158 | 0.752457 | 4.546392 | false | false | false | false |
lapis-mc/yggdrasil | src/main/kotlin/com/lapismc/minecraft/yggdrasil/rest/ErrorResponse.kt | 1 | 1594 | package com.lapismc.minecraft.yggdrasil.rest
import com.lapismc.minecraft.yggdrasil.ForbiddenOperationException
/**
* Response received for all possible errors.
* @param error Error name and type.
* @param message Brief text describing the problem.
* @param cause Error name and type of the issue that caused the original problem.
*/
class ErrorResponse(val error: String, val message: String, val cause: String? = null) : Response() {
/**
* Indicates whether the request was successful.
*/
override val successful = false
/**
* Converts the error to a logical exception.
* @return Exception containing the error information.
*/
fun toException(): Exception {
val klass = errorNameToExceptionClass(error)
return if(cause == null) {
klass.getConstructor(String::class.java).newInstance(message)
} else {
val causedBy = errorNameToExceptionClass(cause).newInstance()
klass.getConstructor(String::class.java, Exception::class.java).newInstance(message, causedBy)
}
}
/**
* Retrieves the class for the corresponding error string.
* @param error Error type.
* @return Exception class type.
*/
private fun errorNameToExceptionClass(error: String) = when(error) {
// TODO: Is it possible to use the Kotlin class instead of the Java class?
"ForbiddenOperationException" -> ForbiddenOperationException::class.java
"IllegalArgumentException" -> IllegalArgumentException::class.java
else -> Exception::class.java
}
} | mit | afbcf88bcf0e252dff899d248ecd8b51 | 36.97619 | 106 | 0.685069 | 4.702065 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/util/Utils.kt | 1 | 3060 | @file:JvmName("Utils")
package ftl.util
import com.fasterxml.jackson.annotation.JsonProperty
import flank.common.logLn
import flank.tool.resource.readRevision
import flank.tool.resource.readVersion
import ftl.run.exception.FlankGeneralError
import java.io.File
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Random
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
fun assertNotEmpty(str: String, e: String) {
if (str.isBlank()) {
throw FlankGeneralError(e)
}
}
// Match _GenerateUniqueGcsObjectName from api_lib/firebase/test/arg_validate.py
//
// Example: 2017-05-31_17:19:36.431540_hRJD
//
// https://cloud.google.com/storage/docs/naming
fun uniqueObjectName(): String {
val bucketName = StringBuilder()
val instant = Instant.now()
bucketName.append(
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss.")
.withZone(ZoneOffset.UTC)
.format(instant)
)
val nanoseconds = instant.nano.toString()
if (nanoseconds.length >= 6) {
bucketName.append(nanoseconds.substring(0, 6))
} else {
bucketName.append(nanoseconds.substring(0, nanoseconds.length - 1))
}
bucketName.append("_")
val random = Random()
// a-z: 97 - 122
// A-Z: 65 - 90
repeat(4) {
val ascii = random.nextInt(26)
var letter = (ascii + 'a'.code).toChar()
if (ascii % 2 == 0) {
letter -= 32 // upcase
}
bucketName.append(letter)
}
return bucketName.toString()
}
fun printVersionInfo() {
logLn("version: ${readVersion()}")
logLn("revision: ${readRevision()}")
logLn()
}
fun <R : MutableMap<String, Any>, T> mutableMapProperty(
name: String? = null,
defaultValue: () -> T
) = object : ReadWriteProperty<R, T> {
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: R, property: KProperty<*>): T =
thisRef.getOrElse(name ?: property.name, defaultValue) as T
override fun setValue(thisRef: R, property: KProperty<*>, value: T) =
thisRef.set(name ?: property.name, value as Any)
}
/**
* Strips all characters except numbers and a period
* Returns 0 when the string is null or blank
*
* Example: z1,23.45 => 123.45 */
fun String?.stripNotNumbers(): String {
if (this.isNullOrBlank()) return "0"
return this.replace(Regex("""[^0-9\\.]"""), "")
}
/**
* Used to validate values from yml config file.
* Should be used only on properties with [JsonProperty] annotation.
*/
fun <T> KMutableProperty<T?>.require() =
getter.call() ?: throw FlankGeneralError(
"Invalid value for [${
setter.annotations.filterIsInstance<JsonProperty>().first().value
}]: no argument value found"
)
fun getGACPathOrEmpty(): String = System.getenv("GOOGLE_APPLICATION_CREDENTIALS").orEmpty()
fun saveToFlankLinks(vararg links: String) = File("flank-links.log").writeText(links.joinToString(System.lineSeparator()))
| apache-2.0 | ee78940e2bd619004373592821f3e207 | 27.333333 | 122 | 0.672549 | 3.858764 | false | false | false | false |
siosio/intellij-community | uast/uast-common/src/org/jetbrains/uast/analysis/DependencyGraphBuilder.kt | 1 | 33446 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.analysis
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.IntRef
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiElement
import com.intellij.util.castSafelyTo
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastVisitor
internal class DependencyGraphBuilder private constructor(
private val currentScope: LocalScopeContext = LocalScopeContext(null),
private var currentDepth: Int,
val dependents: MutableMap<UElement, MutableSet<Dependent>> = mutableMapOf(),
val dependencies: MutableMap<UElement, MutableSet<Dependency>> = mutableMapOf(),
private val implicitReceivers: MutableMap<UCallExpression, UThisExpression> = mutableMapOf(),
val scopesStates: MutableMap<UElement, UScopeObjectsState> = mutableMapOf(),
private val inlinedVariables: MutableMap<ULambdaExpression, Pair<String, String>> = mutableMapOf()
) : AbstractUastVisitor() {
constructor() : this(currentDepth = 0)
private val elementsProcessedAsReceiver: MutableSet<UExpression> = mutableSetOf()
private fun createVisitor(scope: LocalScopeContext) =
DependencyGraphBuilder(scope, currentDepth, dependents, dependencies, implicitReceivers, scopesStates, inlinedVariables)
inline fun <T> checkedDepthCall(node: UElement, body: () -> T): T {
currentDepth++
try {
if (currentDepth > maxBuildDepth) {
thisLogger().info("build overflow in $node because depth is greater than $maxBuildDepth")
throw BuildOverflowException
}
return body()
}
finally {
currentDepth--
}
}
override fun visitLambdaExpression(node: ULambdaExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val parent = (node.uastParent as? UCallExpression)
val isInlined = parent?.let { KotlinExtensionConstants.isExtensionFunctionToIgnore(it) } == true
val child = currentScope.createChild(isInlined)
for (parameter in node.parameters) {
child.declareFakeVariable(parameter, parameter.name)
child[parameter.name] = setOf(parameter)
}
parent
?.takeIf { KotlinExtensionConstants.isExtensionFunctionToIgnore(it) }
?.let { parent.valueArguments.getOrNull(0) as? ULambdaExpression }
?.let {
it.parameters.getOrNull(0)?.name
}?.let {
(parent.receiver ?: parent.getImplicitReceiver())?.let receiverHandle@{ receiver ->
val initElements = setOf(receiver)
child[it] = initElements
updatePotentialEqualReferences(it, initElements, child)
val inlined = currentScope.declareInlined(receiver) ?: return@receiverHandle
child.setPotentialEquality(inlined, it, DependencyEvidence())
child[inlined] = initElements
inlinedVariables[node] = it to inlined
}
}
node.body.accept(createVisitor(child))
scopesStates[node] = child.toUScopeObjectsState()
if (isInlined) {
currentScope.updateForInlined(child)
}
return@checkedDepthCall true
}
override fun visitBinaryExpressionWithType(node: UBinaryExpressionWithType): Boolean = checkedDepthCall(node) {
if (node.operationKind != UastBinaryExpressionWithTypeKind.TypeCast.INSTANCE) {
return@checkedDepthCall super.visitBinaryExpressionWithType(node)
}
registerDependency(Dependent.CommonDependent(node), node.operand.extractBranchesResultAsDependency())
return@checkedDepthCall super.visitBinaryExpressionWithType(node)
}
override fun visitCallExpression(node: UCallExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val resolvedMethod = node.resolve() ?: return@checkedDepthCall super.visitCallExpression(node)
val receiver = (node.uastParent as? UQualifiedReferenceExpression)?.receiver
for ((i, parameter) in resolvedMethod.parameterList.parameters.withIndex()) {
val argument = node.getArgumentForParameter(i) ?: continue
if (argument is UExpressionList && argument.kind == UastSpecialExpressionKind.VARARGS) {
argument.expressions.forEach {
registerDependency(
Dependent.CallExpression(i, node, (parameter.type as PsiArrayType).componentType),
Dependency.ArgumentDependency(it, node)
)
}
}
else {
registerDependency(Dependent.CallExpression(i, node, parameter.type), Dependency.ArgumentDependency(argument, node))
}
// TODO: implicit this as receiver argument
argument.takeIf { it == receiver }?.let { elementsProcessedAsReceiver.add(it) }
}
node.getImplicitReceiver()?.accept(this)
return@checkedDepthCall super.visitCallExpression(node)
}
override fun afterVisitCallExpression(node: UCallExpression) {
node.getImplicitReceiver()?.let { implicitReceiver ->
val inlinedCall = inlineCall(node, node.uastParent)
if (inlinedCall.isNotEmpty()) {
registerDependency(Dependent.CommonDependent(node), Dependency.BranchingDependency(inlinedCall).unwrapIfSingle())
}
else {
registerDependency(Dependent.CommonDependent(node), Dependency.CommonDependency(implicitReceiver))
if (node.uastParent !is UReferenceExpression) {
currentScope.setLastPotentialUpdate(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME, node)
}
}
}
}
override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.receiver.accept(this)
node.selector.accept(this)
if (node.receiver !in elementsProcessedAsReceiver) {
registerDependency(Dependent.CommonDependent(node.selector), Dependency.CommonDependency(node.receiver))
}
else {
// this element unnecessary now, remove it to avoid memory leaks
elementsProcessedAsReceiver.remove(node.receiver)
}
val inlinedExpressions = inlineCall(node.selector, node.uastParent)
if (inlinedExpressions.isNotEmpty()) {
registerDependency(Dependent.CommonDependent(node), Dependency.BranchingDependency(inlinedExpressions).unwrapIfSingle())
}
else {
registerDependency(Dependent.CommonDependent(node), Dependency.CommonDependency(node.selector))
}
if (inlinedExpressions.isEmpty() && node.getOutermostQualified() == node) {
node.getQualifiedChainWithImplicits().first().referenceOrThisIdentifier?.takeIf { it in currentScope }?.let {
currentScope.setLastPotentialUpdate(it, node)
}
}
return@checkedDepthCall true
}
override fun visitParenthesizedExpression(node: UParenthesizedExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
registerDependency(Dependent.CommonDependent(node), node.expression.extractBranchesResultAsDependency())
return@checkedDepthCall super.visitParenthesizedExpression(node)
}
override fun visitReturnExpression(node: UReturnExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.returnExpression?.extractBranchesResultAsDependency()?.let { registerDependency(Dependent.CommonDependent(node), it) }
return@checkedDepthCall super.visitReturnExpression(node)
}
override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.uastParent is UReferenceExpression && (node.uastParent as? UQualifiedReferenceExpression)?.receiver != node)
return@checkedDepthCall true
registerDependenciesForIdentifier(node.identifier, node)
return@checkedDepthCall super.visitSimpleNameReferenceExpression(node)
}
override fun visitThisExpression(node: UThisExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
registerDependenciesForIdentifier(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME, node)
return@checkedDepthCall super.visitThisExpression(node)
}
private fun registerDependenciesForIdentifier(identifier: String, node: UExpression) {
val referenceInfo = DependencyOfReference.ReferenceInfo(identifier, currentScope.getReferencedValues(identifier))
currentScope[identifier]?.let {
registerDependency(
Dependent.CommonDependent(node),
Dependency.BranchingDependency(
it,
referenceInfo
).unwrapIfSingle()
)
}
val potentialDependenciesCandidates = currentScope.getLastPotentialUpdate(identifier)
if (potentialDependenciesCandidates != null) {
registerDependency(Dependent.CommonDependent(node),
Dependency.PotentialSideEffectDependency(potentialDependenciesCandidates, referenceInfo))
}
}
override fun visitVariable(node: UVariable): Boolean = checkedDepthCall(node) {
if (node !is ULocalVariable && !(node is UParameter && node.uastParent is UMethod)) {
return@checkedDepthCall super.visitVariable(node)
}
ProgressManager.checkCanceled()
node.uastInitializer?.accept(this)
val name = node.name ?: return@checkedDepthCall super.visitVariable(node)
currentScope.declare(node)
val initializer = node.uastInitializer ?: return@checkedDepthCall super.visitVariable(node)
val initElements = initializer.extractBranchesResultAsDependency().inlineElementsIfPossible().elements
currentScope[name] = initElements
updatePotentialEqualReferences(name, initElements)
currentScope.setLastPotentialUpdateAsAssignment(name, initElements)
return@checkedDepthCall true
}
override fun visitBinaryExpression(node: UBinaryExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.operator == UastBinaryOperator.ASSIGN &&
(node.leftOperand is UReferenceExpression || node.leftOperand is UArrayAccessExpression)
) {
node.rightOperand.accept(this)
val extractedBranchesResult = node.rightOperand.extractBranchesResultAsDependency().inlineElementsIfPossible()
(node.leftOperand as? USimpleNameReferenceExpression)
?.takeIf { it.identifier in currentScope }
?.let {
currentScope[it.identifier] = extractedBranchesResult.elements
updatePotentialEqualReferences(it.identifier, extractedBranchesResult.elements)
currentScope.setLastPotentialUpdateAsAssignment(it.identifier, extractedBranchesResult.elements)
}
registerDependency(Dependent.Assigment(node.leftOperand), extractedBranchesResult)
return@checkedDepthCall true
}
registerDependency(
Dependent.BinaryOperatorDependent(node, isDependentOfLeftOperand = true),
Dependency.CommonDependency(node.leftOperand)
)
registerDependency(
Dependent.BinaryOperatorDependent(node, isDependentOfLeftOperand = false),
Dependency.CommonDependency(node.rightOperand)
)
return@checkedDepthCall super.visitBinaryExpression(node)
}
private fun Dependency.inlineElementsIfPossible(): Dependency {
val newElements = elements.flatMap { element ->
when (element) {
is UQualifiedReferenceExpression -> inlineCall(element.selector, element.uastParent)
is UCallExpression -> inlineCall(element, element.uastParent)
else -> listOf()
}.takeUnless { it.isEmpty() } ?: listOf(element)
}.toSet()
return Dependency.BranchingDependency(newElements).unwrapIfSingle()
}
override fun visitIfExpression(node: UIfExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.condition.accept(this)
val left = currentScope.createChild()
val right = currentScope.createChild()
node.thenExpression?.accept(createVisitor(left))
node.elseExpression?.accept(createVisitor(right))
currentScope.mergeWith(right, left)
return@checkedDepthCall true
}
override fun visitExpressionList(node: UExpressionList) = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.kind.name != UAST_KT_ELVIS_NAME) {
return super.visitExpressionList(node)
}
val firstExpression = (node.expressions.first() as? UDeclarationsExpression)
?.declarations
?.first()
?.castSafelyTo<ULocalVariable>()
?.uastInitializer
?.extractBranchesResultAsDependency() ?: return@checkedDepthCall super.visitExpressionList(node)
val ifExpression = node.expressions.getOrNull(1)
?.extractBranchesResultAsDependency() ?: return@checkedDepthCall super.visitExpressionList(node)
registerDependency(Dependent.CommonDependent(node), firstExpression.and(ifExpression))
return@checkedDepthCall super.visitExpressionList(node)
}
override fun visitSwitchExpression(node: USwitchExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.expression?.accept(this)
val childrenScopes = mutableListOf<LocalScopeContext>()
for (clause in node.body.expressions.filterIsInstance<USwitchClauseExpressionWithBody>()) {
val childScope = currentScope.createChild()
clause.accept(createVisitor(childScope))
childrenScopes.add(childScope)
}
currentScope.mergeWith(childrenScopes)
return@checkedDepthCall true
}
override fun visitForEachExpression(node: UForEachExpression): Boolean {
ProgressManager.checkCanceled()
node.iteratedValue.accept(this)
return visitLoopExpression(node)
}
override fun visitForExpression(node: UForExpression): Boolean {
ProgressManager.checkCanceled()
node.declaration?.accept(this)
node.condition?.accept(this)
node.update?.accept(this)
return visitLoopExpression(node)
}
override fun visitDoWhileExpression(node: UDoWhileExpression): Boolean {
ProgressManager.checkCanceled()
node.condition.accept(this)
return visitLoopExpression(node)
}
override fun visitWhileExpression(node: UWhileExpression): Boolean {
ProgressManager.checkCanceled()
node.condition.accept(this)
return visitLoopExpression(node)
}
private fun visitLoopExpression(node: ULoopExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val child = currentScope.createChild()
node.body.accept(createVisitor(child))
currentScope.mergeWith(currentScope, child)
return@checkedDepthCall true
}
override fun visitBlockExpression(node: UBlockExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
when (node.uastParent) {
is ULoopExpression, is UIfExpression, is USwitchExpression, is ULambdaExpression ->
return@checkedDepthCall super.visitBlockExpression(node)
}
val child = currentScope.createChild()
val visitor = createVisitor(child)
for (expression in node.expressions) {
expression.accept(visitor)
}
currentScope.update(child)
return@checkedDepthCall true
}
override fun visitTryExpression(node: UTryExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val tryChild = currentScope.createChild()
node.tryClause.accept(createVisitor(tryChild))
val scopeChildren = mutableListOf(tryChild)
node.catchClauses.mapTo(scopeChildren) { clause ->
currentScope.createChild().also { clause.accept(createVisitor(it)) }
}
currentScope.mergeWith(scopeChildren)
node.finallyClause?.accept(this)
return@checkedDepthCall true
}
// Ignore class nodes
override fun visitClass(node: UClass): Boolean = true
override fun afterVisitMethod(node: UMethod) {
scopesStates[node] = currentScope.toUScopeObjectsState()
}
private fun inlineCall(selector: UExpression, parent: UElement?): Set<UExpression> {
val call = selector as? UCallExpression ?: return emptySet()
if (KotlinExtensionConstants.isLetOrRunCall(call)) {
val lambda = call.getArgumentForParameter(1) ?: return emptySet()
return mutableSetOf<UExpression>().apply {
lambda.accept(object : AbstractUastVisitor() {
override fun visitReturnExpression(node: UReturnExpression): Boolean {
if (node.jumpTarget != lambda) return super.visitReturnExpression(node)
node.returnExpression?.let {
val inlinedCall = inlineCall(it, node)
if (inlinedCall.isNotEmpty()) {
addAll(inlinedCall)
}
else {
add(it)
}
}
return super.visitReturnExpression(node)
}
})
}
}
if (KotlinExtensionConstants.isAlsoOrApplyCall(call)) {
val lambda = call.getArgumentForParameter(1) as? ULambdaExpression ?: return emptySet()
val paramName = lambda.parameters.singleOrNull()?.name ?: return emptySet()
val inlinedVarName = inlinedVariables[lambda]?.takeIf { it.first == paramName }?.second ?: return emptySet()
val scopesState = scopesStates[lambda] ?: return emptySet()
val candidates = scopesState.lastVariablesUpdates[paramName] ?: return emptySet()
val values = scopesState.variableToValueMarks[paramName] ?: return emptySet()
val fakeReferenceExpression = UFakeSimpleNameReferenceExpression(parent, inlinedVarName, inlinedVarName)
currentScope[inlinedVarName]?.let {
registerDependency(
Dependent.CommonDependent(fakeReferenceExpression),
Dependency.BranchingDependency(it).unwrapIfSingle()
)
}
registerDependency(
Dependent.CommonDependent(fakeReferenceExpression),
Dependency.PotentialSideEffectDependency(candidates, DependencyOfReference.ReferenceInfo(paramName, values))
)
return setOf(fakeReferenceExpression)
}
return emptySet()
}
private fun updatePotentialEqualReferences(name: String, initElements: Set<UElement>, scope: LocalScopeContext = currentScope) {
scope.clearPotentialReferences(TEMP_VAR_NAME)
fun getInlined(element: UElement, id: String): String? =
element.getParentOfType<ULambdaExpression>()
?.let { inlinedVariables[it] }
?.takeIf { it.first == id }
?.second
fun identToReferenceInfo(element: UElement, identifier: String): Pair<String, UReferenceExpression?>? {
return (identifier.takeIf { id -> id in scope } ?: getInlined(element, identifier))
?.let { id -> id to null } // simple reference => same references
}
val potentialEqualReferences = initElements
.mapNotNull {
when (it) {
is UQualifiedReferenceExpression -> it.getQualifiedChainWithImplicits().firstOrNull()?.referenceOrThisIdentifier?.let { identifier ->
(identifier.takeIf { id -> id in scope } ?: getInlined(it, identifier))?.let { id -> id to it }
}
is USimpleNameReferenceExpression -> identToReferenceInfo(it, it.identifier)
is UThisExpression -> identToReferenceInfo(it, KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME)
is UCallExpression -> {
it.getImplicitReceiver()
?.takeIf { KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME in scope }
?.let { implicitThis ->
KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME to UFakeQualifiedReferenceExpression(implicitThis, it, it.uastParent)
}
}
else -> null
}
}
for ((potentialEqualReference, evidence) in potentialEqualReferences) {
scope.setPotentialEquality(TEMP_VAR_NAME, potentialEqualReference, DependencyEvidence(evidence))
}
scope.clearPotentialReferences(name)
scope.setPotentialEquality(name, TEMP_VAR_NAME, DependencyEvidence())
scope.clearPotentialReferences(TEMP_VAR_NAME)
}
private fun registerDependency(dependent: Dependent, dependency: Dependency) {
if (dependency !is Dependency.PotentialSideEffectDependency) {
for (el in dependency.elements) {
dependents.getOrPut(el) { mutableSetOf() }.add(dependent)
}
}
dependencies.getOrPut(dependent.element) { mutableSetOf() }.add(dependency)
}
private fun UCallExpression.getImplicitReceiver(): UExpression? {
return if (
hasImplicitReceiver(this) &&
(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME in currentScope || this in implicitReceivers)
) {
implicitReceivers.getOrPut(this) { UFakeThisExpression(uastParent) }
}
else {
null
}
}
private fun UQualifiedReferenceExpression.getQualifiedChainWithImplicits(): List<UExpression> {
val chain = getQualifiedChain()
val firstElement = chain.firstOrNull()
return if (firstElement is UCallExpression) {
listOfNotNull(firstElement.getImplicitReceiver()) + chain
}
else {
chain
}
}
companion object {
val maxBuildDepth = Registry.intValue("uast.usage.graph.default.recursion.depth.limit", 30)
object BuildOverflowException : RuntimeException("graph building is overflowed", null, false, false)
}
}
private typealias SideEffectChangeCandidate = Dependency.PotentialSideEffectDependency.SideEffectChangeCandidate
private typealias DependencyEvidence = Dependency.PotentialSideEffectDependency.DependencyEvidence
private typealias CandidatesTree = Dependency.PotentialSideEffectDependency.CandidatesTree
private const val INLINED_PREFIX = "inlined/"
private class LocalScopeContext(
private val parent: LocalScopeContext?,
private val inlinedId: IntRef = IntRef(),
private val isInlined: Boolean = false
) {
private val definedInScopeVariables = mutableSetOf<UElement>()
private val definedInScopeVariablesNames = mutableSetOf<String>()
private val lastAssignmentOf = mutableMapOf<UElement, Set<UElement>>()
private val lastDeclarationOf = mutableMapOf<String?, UElement>()
private val lastPotentialUpdatesOf = mutableMapOf<String, CandidatesTree>()
private val referencesModel: ReferencesModel = ReferencesModel(parent?.referencesModel)
operator fun set(variable: String, values: Set<UElement>) {
getDeclaration(variable)?.let { lastAssignmentOf[it] = values }
}
operator fun set(variable: UElement, values: Set<UElement>) {
lastAssignmentOf[variable] = values
}
operator fun get(variable: String): Set<UElement>? = getDeclaration(variable)?.let { lastAssignmentOf[it] ?: parent?.get(variable) }
operator fun get(variable: UElement): Set<UElement>? = lastAssignmentOf[variable] ?: parent?.get(variable)
fun declare(variable: UVariable) {
definedInScopeVariables.add(variable)
variable.name?.let {
definedInScopeVariablesNames.add(it)
referencesModel.assignValueIfNotAssigned(it)
lastDeclarationOf[it] = variable
}
}
fun declareFakeVariable(element: UElement, name: String) {
definedInScopeVariablesNames.add(name)
referencesModel.assignValueIfNotAssigned(name)
lastDeclarationOf[name] = element
}
fun declareInlined(element: UElement): String? {
if (!isInlined) {
val name = "$INLINED_PREFIX${inlinedId.get()}"
inlinedId.inc()
declareFakeVariable(element, name)
return name
}
return parent?.declareInlined(element)
}
fun getDeclaration(variable: String): UElement? = lastDeclarationOf[variable] ?: parent?.getDeclaration(variable)
operator fun contains(variable: String): Boolean = variable in definedInScopeVariablesNames || parent?.let { variable in it } == true
fun createChild(isInlined: Boolean = false) = LocalScopeContext(this, inlinedId, isInlined)
fun setLastPotentialUpdate(variable: String, updateElement: UElement) {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidate(
SideEffectChangeCandidate(updateElement, DependencyEvidence(),
dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable))
)
for ((reference, evidenceAndWitness) in referencesModel.getAllPossiblyEqualReferences(variable)) {
val (evidence, witness) = evidenceAndWitness
val newCandidate = SideEffectChangeCandidate(updateElement, evidence, witness)
val candidatesForReference = lastPotentialUpdatesOf[reference]
lastPotentialUpdatesOf[reference] = candidatesForReference?.addToBegin(newCandidate) ?: CandidatesTree.fromCandidate(newCandidate)
}
}
fun setLastPotentialUpdateAsAssignment(variable: String, updateElements: Collection<UElement>) {
if (updateElements.size == 1) {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidate(
SideEffectChangeCandidate(
updateElements.first(),
DependencyEvidence(),
dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable))
)
}
else {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidates(
updateElements.mapTo(mutableSetOf()) {
SideEffectChangeCandidate(it, DependencyEvidence(), dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable))
}
)
}
}
fun getLastPotentialUpdate(variable: String): CandidatesTree? =
lastPotentialUpdatesOf[variable] ?: parent?.getLastPotentialUpdate(variable)
fun setPotentialEquality(assigneeReference: String, targetReference: String, evidence: DependencyEvidence) {
referencesModel.setPossibleEquality(assigneeReference, targetReference, evidence)
}
fun clearPotentialReferences(reference: String) {
referencesModel.clearReference(reference)
}
val variables: Iterable<UElement>
get() {
return generateSequence(this) { it.parent }
.flatMap { it.definedInScopeVariables.asSequence() }
.asIterable()
}
val variablesNames: Iterable<String>
get() = generateSequence(this) { it.parent }
.flatMap { it.definedInScopeVariablesNames }
.asIterable()
fun mergeWith(others: Iterable<LocalScopeContext>) {
for (variable in variables) {
this[variable] = mutableSetOf<UElement>().apply {
for (other in others) {
other[variable]?.let { addAll(it) }
}
}
}
for (variableName in variablesNames) {
mutableSetOf<CandidatesTree>().apply {
for (other in others) {
other.getLastPotentialUpdate(variableName)?.let {
add(it)
}
}
}.takeUnless { it.isEmpty() }?.let { candidates ->
lastPotentialUpdatesOf[variableName] = CandidatesTree.merge(candidates)
}
}
}
fun mergeWith(vararg others: LocalScopeContext) {
mergeWith(others.asIterable())
}
fun update(other: LocalScopeContext) {
mergeWith(other)
}
fun updateForInlined(other: LocalScopeContext) {
update(other)
referencesModel.updateForReferences(other.referencesModel, variablesNames.filter { it.startsWith(INLINED_PREFIX) })
}
fun getReferencedValues(identifier: String): Collection<UValueMark> {
return referencesModel.getAllTargetsForReference(identifier)
}
fun toUScopeObjectsState(): UScopeObjectsState {
val variableValueMarks = definedInScopeVariablesNames.associateWith { referencesModel.getAllTargetsForReference(it) }
val lastUpdates = definedInScopeVariablesNames.mapNotNull { getLastPotentialUpdate(it)?.let { tree -> it to tree } }.toMap()
return UScopeObjectsState(lastUpdates, variableValueMarks)
}
private class ReferencesModel(private val parent: ReferencesModel?) {
private val referencesTargets = mutableMapOf<String, MutableMap<UValueMark, DependencyEvidence>>()
private val targetsReferences = mutableMapOf<UValueMark, MutableMap<String, DependencyEvidence>>()
private fun getAllReferences(referencedValue: UValueMark): Map<String, DependencyEvidence> =
parent?.getAllReferences(referencedValue).orEmpty() + targetsReferences[referencedValue].orEmpty()
private fun getAllTargets(reference: String): Map<UValueMark, DependencyEvidence> =
listOfNotNull(referencesTargets[reference], parent?.getAllTargets(reference)).fold(emptyMap()) { result, current ->
(result.keys + current.keys).associateWith { (result[it] ?: current[it])!! }
}
fun assignValueIfNotAssigned(reference: String) {
if (getAllTargets(reference).isNotEmpty()) return
val evidence = DependencyEvidence()
val newTarget = UValueMark()
referencesTargets[reference] = mutableMapOf(newTarget to evidence)
targetsReferences[newTarget] = mutableMapOf(reference to evidence)
}
fun setPossibleEquality(assigneeReference: String, targetReference: String, evidence: DependencyEvidence) {
val targets = getAllTargets(targetReference).toMutableMap()
if (targets.isEmpty()) {
val newTarget = UValueMark()
val targetEvidence = DependencyEvidence()
referencesTargets[targetReference] = mutableMapOf(newTarget to targetEvidence) // equal by default
referencesTargets.getOrPut(assigneeReference) { mutableMapOf() }[newTarget] = evidence
targetsReferences[newTarget] = mutableMapOf(
assigneeReference to evidence,
targetReference to targetEvidence
)
return
}
referencesTargets.getOrPut(assigneeReference) { mutableMapOf() }
.putAll(targets.mapValues { (_, evidenceForTarget) -> evidence.copy(requires = listOf(evidenceForTarget)) })
for (target in targets.keys) {
targetsReferences.getOrPut(target) { mutableMapOf() }[assigneeReference] = evidence
}
}
fun clearReference(reference: String) {
val targets = referencesTargets[reference] ?: return
referencesTargets.remove(reference)
for (target in targets.keys) {
targetsReferences[target]?.let { references ->
references.remove(reference)
if (references.isEmpty()) {
targetsReferences.remove(target)
}
}
}
}
fun getAllPossiblyEqualReferences(reference: String): Map<String, Pair<DependencyEvidence, Collection<UValueMark>>> {
val allTargets = getAllTargets(reference)
return allTargets
.map { (target, evidence) ->
getAllReferences(target).map { (currentReference, referenceEvidence) ->
currentReference to (combineEvidences(evidence, referenceEvidence) to allTargets.keys)
}
}
.flatten()
.filter { it.first != reference }
.toMap()
}
fun getAllTargetsForReference(reference: String): Collection<UValueMark> {
return getAllTargets(reference).keys
}
private val references: Sequence<String>
get() = generateSequence(this) { it.parent }
.flatMap { it.referencesTargets.keys }
.distinct()
// For now works only for inlined variables
fun updateForReferences(other: ReferencesModel, references: List<String>) {
check(other.parent == this)
val newTargets = mutableSetOf<UValueMark>()
for (reference in references) {
other.referencesTargets[reference]?.let {
clearReference(reference)
referencesTargets[reference] = it
newTargets += it.keys
}
}
val ownReferences = this.references.toSet()
for (target in newTargets) {
other.targetsReferences[target]?.filterKeys { it in ownReferences }?.takeUnless { it.isEmpty() }?.let {
targetsReferences[target] = it.toMutableMap()
}
}
}
}
}
private fun combineEvidences(ownEvidence: DependencyEvidence, otherEvidence: DependencyEvidence): DependencyEvidence =
ownEvidence.copy(requires = ownEvidence.requires + otherEvidence)
private const val UAST_KT_ELVIS_NAME = "elvis"
private const val TEMP_VAR_NAME = "@$,()"
private fun hasImplicitReceiver(callExpression: UCallExpression): Boolean =
callExpression.receiver == null && callExpression.receiverType != null
private val UExpression?.referenceOrThisIdentifier: String?
get() = when (this) {
is USimpleNameReferenceExpression -> identifier
is UThisExpression -> KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME
else -> null
}
private class UFakeThisExpression(override val uastParent: UElement?) : UThisExpression, UFakeExpression {
override val label: String?
get() = null
override val labelIdentifier: UIdentifier?
get() = null
}
private class UFakeQualifiedReferenceExpression(
override val receiver: UExpression,
override val selector: UExpression,
override val uastParent: UElement?
) : UQualifiedReferenceExpression, UFakeExpression {
override val accessType: UastQualifiedExpressionAccessType
get() = UastQualifiedExpressionAccessType.SIMPLE
override val resolvedName: String?
get() = null
}
private interface UFakeExpression : UExpression, UResolvable {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiElement?
get() = null
@JvmDefault
override val uAnnotations: List<UAnnotation>
get() = emptyList()
override fun resolve(): PsiElement? = null
}
private class UFakeSimpleNameReferenceExpression(
override val uastParent: UElement?,
override val resolvedName: String?,
override val identifier: String
) : USimpleNameReferenceExpression, UFakeExpression | apache-2.0 | 2c190fca89789872d8f5eccb64d7c43d | 39.008373 | 143 | 0.726514 | 4.826959 | false | false | false | false |
ncoe/rosetta | Determine_if_a_string_is_collapsible/Kotlin/src/Collapsible.kt | 1 | 996 | fun collapse(s: String): String {
val cs = StringBuilder()
var last: Char = 0.toChar()
for (c in s) {
if (c != last) {
cs.append(c)
last = c
}
}
return cs.toString()
}
fun main() {
val strings = arrayOf(
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark"
)
for (s in strings) {
val c = collapse(s)
println("original : length = ${s.length}, string = «««$s»»»")
println("collapsed : length = ${c.length}, string = «««$c»»»")
println()
}
}
| mit | 448e07df9ce22de444d8413edf4ddcb4 | 31.8 | 91 | 0.511179 | 3.741445 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt | 1 | 11309 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.hint.ShowParameterInfoHandler
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructorSubstitution
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.utils.addIfNotNull
object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
private const val DISPLAY_MAX_PARAMS = 5
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val delegator = diagnostic.psiElement as KtSuperTypeEntry
val classOrObjectDeclaration = delegator.parent.parent as? KtClassOrObject ?: return emptyList()
val typeRef = delegator.typeReference ?: return emptyList()
val type = typeRef.analyze()[BindingContext.TYPE, typeRef] ?: return emptyList()
if (type.isError) return emptyList()
val superClass = (type.constructor.declarationDescriptor as? ClassDescriptor) ?: return emptyList()
val classDescriptor = classOrObjectDeclaration.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return emptyList()
val containingPackage = superClass.classId?.packageFqName
val inSamePackage = containingPackage != null && containingPackage == classDescriptor.classId?.packageFqName
val constructors = superClass.constructors.filter {
it.isVisible(classDescriptor) && (superClass.modality != Modality.SEALED || inSamePackage && classDescriptor.visibility != DescriptorVisibilities.LOCAL)
}
if (constructors.isEmpty() && (!superClass.isExpect || superClass.kind != ClassKind.CLASS)) {
return emptyList() // no accessible constructor
}
val fixes = ArrayList<IntentionAction>()
fixes.add(
AddParenthesisFix(
delegator,
putCaretIntoParenthesis = constructors.singleOrNull()?.valueParameters?.isNotEmpty() ?: true
)
)
if (classOrObjectDeclaration is KtClass) {
val superType = classDescriptor.typeConstructor.supertypes.firstOrNull { it.constructor.declarationDescriptor == superClass }
if (superType != null) {
val substitutor = TypeConstructorSubstitution.create(superClass.typeConstructor, superType.arguments).buildSubstitutor()
val substitutedConstructors = constructors
.asSequence()
.filter { it.valueParameters.isNotEmpty() }
.mapNotNull { it.substitute(substitutor) }
.toList()
if (substitutedConstructors.isNotEmpty()) {
val parameterTypes: List<List<KotlinType>> = substitutedConstructors.map {
it.valueParameters.map { it.type }
}
fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size == parameterTypes.size
val maxParams = parameterTypes.maxOf { it.size }
val maxParamsToDisplay = if (maxParams <= DISPLAY_MAX_PARAMS) {
maxParams
} else {
(DISPLAY_MAX_PARAMS until maxParams).firstOrNull(::canRenderOnlyFirstParameters) ?: maxParams
}
for ((constructor, types) in substitutedConstructors.zip(parameterTypes)) {
val typesRendered =
types.asSequence().take(maxParamsToDisplay).map { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) }
.toList()
val parameterString = typesRendered.joinToString(", ", "(", if (types.size <= maxParamsToDisplay) ")" else ",...)")
val text = KotlinBundle.message("add.constructor.parameters.from.0.1", superClass.name.asString(), parameterString)
fixes.addIfNotNull(AddParametersFix.create(delegator, classOrObjectDeclaration, constructor, text))
}
}
}
}
return fixes
}
private class AddParenthesisFix(
element: KtSuperTypeEntry,
val putCaretIntoParenthesis: Boolean
) : KotlinQuickFixAction<KtSuperTypeEntry>(element), HighPriorityAction {
override fun getFamilyName() = KotlinBundle.message("change.to.constructor.invocation") //TODO?
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val context = (element.getStrictParentOfType<KtClassOrObject>() ?: element).analyze()
val baseClass = AddDefaultConstructorFix.superTypeEntryToClass(element, context)
val newSpecifier = element.replaced(KtPsiFactory(project).createSuperTypeCallEntry(element.text + "()"))
if (baseClass != null && baseClass.hasExpectModifier() && baseClass.secondaryConstructors.isEmpty()) {
baseClass.createPrimaryConstructorIfAbsent()
}
if (putCaretIntoParenthesis) {
if (editor != null) {
val offset = newSpecifier.valueArgumentList!!.leftParenthesis!!.endOffset
editor.moveCaret(offset)
if (!ApplicationManager.getApplication().isUnitTestMode) {
ShowParameterInfoHandler.invoke(project, editor, file, offset - 1, null, true)
}
}
}
}
}
private class AddParametersFix(
element: KtSuperTypeEntry,
classDeclaration: KtClass,
parametersToAdd: Collection<KtParameter>,
private val argumentText: String,
private val text: String
) : KotlinQuickFixAction<KtSuperTypeEntry>(element) {
private val classDeclarationPointer = classDeclaration.createSmartPointer()
private val parametersToAddPointers = parametersToAdd.map { it.createSmartPointer() }
companion object {
fun create(
element: KtSuperTypeEntry,
classDeclaration: KtClass,
superConstructor: ConstructorDescriptor,
text: String
): AddParametersFix? {
val superParameters = superConstructor.valueParameters
assert(superParameters.isNotEmpty())
if (superParameters.any { it.type.isError }) return null
val argumentText = StringBuilder()
val oldParameters = classDeclaration.primaryConstructorParameters
val parametersToAdd = ArrayList<KtParameter>()
for (parameter in superParameters) {
val nameRendered = parameter.name.render()
val varargElementType = parameter.varargElementType
if (argumentText.isNotEmpty()) {
argumentText.append(", ")
}
argumentText.append(if (varargElementType != null) "*$nameRendered" else nameRendered)
val nameString = parameter.name.asString()
val existingParameter = oldParameters.firstOrNull { it.name == nameString }
if (existingParameter != null) {
val type = (existingParameter.resolveToParameterDescriptorIfAny() as? VariableDescriptor)?.type
?: return null
if (type.isSubtypeOf(parameter.type)) continue // use existing parameter
}
val defaultValue = if (parameter.declaresDefaultValue()) {
(DescriptorToSourceUtils.descriptorToDeclaration(parameter) as? KtParameter)
?.defaultValue?.text?.let { " = $it" } ?: ""
} else {
""
}
val parameterText = if (varargElementType != null) {
"vararg " + nameRendered + ":" + IdeDescriptorRenderers.SOURCE_CODE.renderType(varargElementType)
} else {
nameRendered + ":" + IdeDescriptorRenderers.SOURCE_CODE.renderType(parameter.type)
} + defaultValue
parametersToAdd.add(KtPsiFactory(element).createParameter(parameterText))
}
return AddParametersFix(element, classDeclaration, parametersToAdd, argumentText.toString(), text)
}
}
override fun getFamilyName() = KotlinBundle.message("add.constructor.parameters.from.superclass")
override fun getText() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val classDeclaration = classDeclarationPointer.element ?: return
val parametersToAdd = parametersToAddPointers.map { it.element ?: return }
val factory = KtPsiFactory(project)
val typeRefsToShorten = ArrayList<KtTypeReference>()
val parameterList = classDeclaration.createPrimaryConstructorParameterListIfAbsent()
for (parameter in parametersToAdd) {
val newParameter = parameterList.addParameter(parameter)
typeRefsToShorten.add(newParameter.typeReference!!)
}
val delegatorCall = factory.createSuperTypeCallEntry(element.text + "(" + argumentText + ")")
element.replace(delegatorCall)
ShortenReferences.DEFAULT.process(typeRefsToShorten)
}
}
}
| apache-2.0 | 38e4dff6d67339c66f54bc5343a0b125 | 49.262222 | 164 | 0.652578 | 5.728977 | false | false | false | false |
siosio/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/AccountsListModelBase.kt | 1 | 1293 | // 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.collaboration.auth.ui
import com.intellij.collaboration.auth.Account
import com.intellij.collaboration.ui.SingleValueModel
import com.intellij.ui.CollectionListModel
import java.util.concurrent.CopyOnWriteArrayList
abstract class AccountsListModelBase<A : Account, Cred> : AccountsListModel<A, Cred> {
override var accounts: Set<A>
get() = accountsListModel.items.toSet()
set(value) {
accountsListModel.removeAll()
accountsListModel.add(value.toList())
}
override var defaultAccount: A? = null
override val newCredentials = mutableMapOf<A, Cred>()
override val accountsListModel = CollectionListModel<A>()
override val busyStateModel = SingleValueModel(false)
private val credentialsChangesListeners = CopyOnWriteArrayList<(A) -> Unit>()
override fun clearNewCredentials() = newCredentials.clear()
protected fun notifyCredentialsChanged(account: A) {
credentialsChangesListeners.forEach { it(account) }
accountsListModel.contentsChanged(account)
}
final override fun addCredentialsChangeListener(listener: (A) -> Unit) {
credentialsChangesListeners.add(listener)
}
} | apache-2.0 | ae20df6c2fe999980f4c271de881dd91 | 37.058824 | 140 | 0.773395 | 4.368243 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/dependencies/KotlinScriptResolveScopeProvider.kt | 1 | 4280 | // 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.core.script.dependencies
import com.intellij.ide.IdeBundle
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.NonPhysicalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.ex.dummy.DummyFileSystem
import com.intellij.psi.PsiManager
import com.intellij.psi.ResolveScopeProvider
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.project.ScriptModuleInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfo
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.util.isKotlinFileType
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import java.io.IOException
import java.io.OutputStream
class KotlinScriptSearchScope(project: Project, baseScope: GlobalSearchScope) : DelegatingGlobalSearchScope(project, baseScope) {
override fun contains(file: VirtualFile): Boolean {
return when (file) {
KotlinScriptMarkerFileSystem.rootFile -> true
else -> super.contains(file)
}
}
}
object KotlinScriptMarkerFileSystem : DummyFileSystem(), NonPhysicalFileSystem {
override fun getProtocol() = "kotlin-script-dummy"
val rootFile = object : VirtualFile() {
override fun getFileSystem() = this@KotlinScriptMarkerFileSystem
override fun getName() = "root"
override fun getPath() = "/$name"
override fun getLength(): Long = 0
override fun isWritable() = false
override fun isDirectory() = true
override fun isValid() = true
override fun getParent() = null
override fun getChildren(): Array<VirtualFile> = emptyArray()
override fun getTimeStamp(): Long = -1
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {}
override fun contentsToByteArray() = throw IOException(IdeBundle.message("file.read.error", url))
override fun getInputStream() = throw IOException(IdeBundle.message("file.read.error", url))
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream {
throw IOException(IdeBundle.message("file.write.error", url))
}
}
}
class KotlinScriptResolveScopeProvider : ResolveScopeProvider() {
companion object {
// Used in LivePlugin (that's probably not true anymore)
@Deprecated("Declaration is deprecated.", level = DeprecationLevel.ERROR)
val USE_NULL_RESOLVE_SCOPE = "USE_NULL_RESOLVE_SCOPE"
}
override fun getResolveScope(file: VirtualFile, project: Project): GlobalSearchScope? {
if (!file.isKotlinFileType()) return null
val ktFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return null
val scriptDefinition = ktFile.findScriptDefinition() ?: return null
// This is a workaround for completion in scripts inside module and REPL to provide module dependencies
if (ktFile.getModuleInfo() !is ScriptModuleInfo) return null
// This is a workaround for completion in REPL to provide module dependencies
if (scriptDefinition.baseClassType.fromClass == Any::class) return null
if (scriptDefinition is ScriptDefinition.FromConfigurationsBase ||
scriptDefinition.asLegacyOrNull<KotlinScriptDefinitionFromAnnotatedTemplate>() != null
) {
val dependenciesScope = ScriptConfigurationManager.getInstance(project).getScriptDependenciesClassFilesScope(file)
return KotlinScriptSearchScope(project, GlobalSearchScope.fileScope(project, file).uniteWith(dependenciesScope))
}
return null
}
} | apache-2.0 | 457607775d52174bc60d04cc39743b1c | 45.032258 | 158 | 0.750701 | 5.023474 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/StoryLinkPreviewView.kt | 1 | 6637 | package org.thoughtcrime.securesms.stories
import android.content.Context
import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import org.signal.core.util.isAbsent
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.ThumbnailView
import org.thoughtcrime.securesms.databinding.StoriesTextPostLinkPreviewBinding
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.linkpreview.LinkPreviewUtil
import org.thoughtcrime.securesms.linkpreview.LinkPreviewViewModel
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.mms.ImageSlide
import org.thoughtcrime.securesms.mms.Slide
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture
import org.thoughtcrime.securesms.util.concurrent.SettableFuture
import org.thoughtcrime.securesms.util.views.Stub
import org.thoughtcrime.securesms.util.visible
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Locale
class StoryLinkPreviewView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
init {
inflate(context, R.layout.stories_text_post_link_preview, this)
}
private val binding = StoriesTextPostLinkPreviewBinding.bind(this)
private val spinnerStub = Stub<View>(binding.loadingSpinner)
init {
binding.linkPreviewImage.isClickable = false
binding.linkPreviewLarge.isClickable = false
}
private fun getThumbnailTarget(useLargeThumbnail: Boolean): ThumbnailView {
return if (useLargeThumbnail) binding.linkPreviewLarge else binding.linkPreviewImage
}
fun getThumbnailViewWidth(useLargeThumbnail: Boolean): Int {
return getThumbnailTarget(useLargeThumbnail).measuredWidth
}
fun getThumbnailViewHeight(useLargeThumbnail: Boolean): Int {
return getThumbnailTarget(useLargeThumbnail).measuredHeight
}
fun setThumbnailDrawable(drawable: Drawable?, useLargeThumbnail: Boolean) {
val image = getThumbnailTarget(useLargeThumbnail)
image.setImageDrawable(GlideApp.with(this), drawable)
}
fun bind(linkPreview: LinkPreview?, hiddenVisibility: Int = View.INVISIBLE, useLargeThumbnail: Boolean, loadThumbnail: Boolean = true): ListenableFuture<Boolean> {
var future: ListenableFuture<Boolean>? = null
if (isPartialLinkPreview(linkPreview)) {
future = bindPartialLinkPreview(linkPreview!!)
} else if (linkPreview != null) {
future = bindFullLinkPreview(linkPreview, useLargeThumbnail, loadThumbnail)
} else {
visibility = hiddenVisibility
}
return future ?: SettableFuture(false)
}
fun bind(linkPreviewState: LinkPreviewViewModel.LinkPreviewState, hiddenVisibility: Int = View.INVISIBLE, useLargeThumbnail: Boolean) {
val linkPreview: LinkPreview? = linkPreviewState.linkPreview.orElseGet {
linkPreviewState.activeUrlForError?.let {
LinkPreview(it, LinkPreviewUtil.getTopLevelDomain(it) ?: it, null, -1L, null)
}
}
bind(linkPreview, hiddenVisibility, useLargeThumbnail)
spinnerStub.get().visible = linkPreviewState.isLoading
if (linkPreviewState.isLoading) {
visible = true
}
}
private fun isPartialLinkPreview(linkPreview: LinkPreview?): Boolean {
return linkPreview != null &&
TextUtils.isEmpty(linkPreview.description) &&
linkPreview.thumbnail.isAbsent() &&
linkPreview.attachmentId == null
}
private fun bindPartialLinkPreview(linkPreview: LinkPreview): ListenableFuture<Boolean> {
visibility = View.VISIBLE
binding.linkPreviewCard.visible = false
binding.linkPreviewPlaceholderCard.visible = true
binding.linkPreviewPlaceholderTitle.text = Uri.parse(linkPreview.url).host
return SettableFuture(false)
}
private fun bindFullLinkPreview(linkPreview: LinkPreview, useLargeThumbnail: Boolean, loadThumbnail: Boolean): ListenableFuture<Boolean> {
visibility = View.VISIBLE
binding.linkPreviewCard.visible = true
binding.linkPreviewPlaceholderCard.visible = false
val image = getThumbnailTarget(useLargeThumbnail)
val notImage = getThumbnailTarget(!useLargeThumbnail)
var future: ListenableFuture<Boolean>? = null
notImage.visible = false
val imageSlide: Slide? = linkPreview.thumbnail.map { ImageSlide(context, it) }.orElse(null)
if (imageSlide != null) {
if (loadThumbnail) {
future = image.setImageResource(
GlideApp.with(this),
imageSlide,
false,
false
)
}
image.visible = true
binding.linkPreviewFallbackIcon.visible = false
} else {
image.visible = false
binding.linkPreviewFallbackIcon.visible = true
}
binding.linkPreviewTitle.text = linkPreview.title
binding.linkPreviewDescription.text = linkPreview.description
binding.linkPreviewDescription.visible = linkPreview.description.isNotEmpty()
formatUrl(linkPreview)
return future ?: SettableFuture(false)
}
private fun formatUrl(linkPreview: LinkPreview) {
val domain: String? = LinkPreviewUtil.getTopLevelDomain(linkPreview.url)
if (linkPreview.title == domain) {
binding.linkPreviewUrl.visibility = View.GONE
return
}
if (domain != null && linkPreview.date > 0) {
binding.linkPreviewUrl.text = context.getString(R.string.LinkPreviewView_domain_date, domain, formatDate(linkPreview.date))
binding.linkPreviewUrl.visibility = View.VISIBLE
} else if (domain != null) {
binding.linkPreviewUrl.text = domain
binding.linkPreviewUrl.visibility = View.VISIBLE
} else if (linkPreview.date > 0) {
binding.linkPreviewUrl.text = formatDate(linkPreview.date)
binding.linkPreviewUrl.visibility = View.VISIBLE
} else {
binding.linkPreviewUrl.visibility = View.GONE
}
}
fun setOnCloseClickListener(onClickListener: OnClickListener?) {
binding.linkPreviewClose.setOnClickListener(onClickListener)
}
fun setOnPreviewClickListener(onClickListener: OnClickListener?) {
binding.linkPreviewCard.setOnClickListener { onClickListener?.onClick(this) }
binding.linkPreviewPlaceholderCard.setOnClickListener { onClickListener?.onClick(this) }
}
fun setCanClose(canClose: Boolean) {
binding.linkPreviewClose.visible = canClose
}
private fun formatDate(date: Long): String? {
val dateFormat: DateFormat = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
return dateFormat.format(date)
}
}
| gpl-3.0 | 4845d041e8ee4fac1f013eb5022c6487 | 34.875676 | 165 | 0.761037 | 4.647759 | false | false | false | false |
androidx/androidx | tv/tv-material/src/main/java/androidx/tv/material/immersivelist/ImmersiveList.kt | 3 | 8386 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.material.immersivelist
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ContentTransform
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.with
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalFocusManager
import androidx.tv.material.ExperimentalTvMaterialApi
import kotlinx.coroutines.launch
/**
* Immersive List consists of a list with multiple items and a background that displays content
* based on the item in focus.
* To animate the background's entry and exit, use [ImmersiveListBackgroundScope.AnimatedContent].
* To display the background only when the list is in focus, use
* [ImmersiveListBackgroundScope.AnimatedVisibility].
*
* @param background Composable defining the background to be displayed for a given item's
* index.
* @param modifier applied to Immersive List.
* @param listAlignment Alignment of the List with respect to the Immersive List.
* @param list composable defining the list of items that has to be rendered.
*/
@Suppress("IllegalExperimentalApiUsage")
@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)
@ExperimentalTvMaterialApi
@Composable
fun ImmersiveList(
background:
@Composable ImmersiveListBackgroundScope.(index: Int, listHasFocus: Boolean) -> Unit,
modifier: Modifier = Modifier,
listAlignment: Alignment = Alignment.BottomEnd,
list: @Composable ImmersiveListScope.() -> Unit,
) {
var currentItemIndex by remember { mutableStateOf(0) }
var listHasFocus by remember { mutableStateOf(false) }
val bringIntoViewRequester = remember { BringIntoViewRequester() }
val coroutineScope = rememberCoroutineScope()
Box(modifier
.bringIntoViewRequester(bringIntoViewRequester)
.onFocusChanged {
if (it.isFocused) {
coroutineScope.launch {
bringIntoViewRequester.bringIntoView()
}
}
}
) {
ImmersiveListBackgroundScope(this).background(currentItemIndex, listHasFocus)
val focusManager = LocalFocusManager.current
Box(Modifier.align(listAlignment).onFocusChanged { listHasFocus = it.hasFocus }) {
ImmersiveListScope {
currentItemIndex = it
focusManager.moveFocus(FocusDirection.Enter)
}.list()
}
}
}
@ExperimentalTvMaterialApi
object ImmersiveListDefaults {
/**
* Default transition used to bring the background content into view
*/
val EnterTransition: EnterTransition = fadeIn(animationSpec = tween(300))
/**
* Default transition used to remove the background content from view
*/
val ExitTransition: ExitTransition = fadeOut(animationSpec = tween(300))
}
@Immutable
@ExperimentalTvMaterialApi
public class ImmersiveListBackgroundScope internal constructor(boxScope: BoxScope) : BoxScope
by boxScope {
/**
* [ImmersiveListBackgroundScope.AnimatedVisibility] composable animates the appearance and
* disappearance of its content, as [visible] value changes. Different [EnterTransition]s and
* [ExitTransition]s can be defined in [enter] and [exit] for the appearance and disappearance
* animation.
*
* @param visible defines whether the content should be visible
* @param modifier modifier for the Layout created to contain the [content]
* @param enter EnterTransition(s) used for the appearing animation, fading in by default
* @param exit ExitTransition(s) used for the disappearing animation, fading out by default
* @param content Content to appear or disappear based on the value of [visible]
*
* @link androidx.compose.animation.AnimatedVisibility
* @see androidx.compose.animation.AnimatedVisibility
* @see EnterTransition
* @see ExitTransition
* @see AnimatedVisibilityScope
*/
@Composable
fun AnimatedVisibility(
visible: Boolean,
modifier: Modifier = Modifier,
enter: EnterTransition = ImmersiveListDefaults.EnterTransition,
exit: ExitTransition = ImmersiveListDefaults.ExitTransition,
label: String = "AnimatedVisibility",
content: @Composable AnimatedVisibilityScope.() -> Unit
) {
androidx.compose.animation.AnimatedVisibility(
visible,
modifier,
enter,
exit,
label,
content)
}
/**
* [ImmersiveListBackgroundScope.AnimatedContent] is a container that automatically animates its
* content when [targetState] changes. Its [content] for different target states is defined in a
* mapping between a target state and a composable function.
*
* @param targetState defines the key to choose the content to be displayed
* @param modifier modifier for the Layout created to contain the [content]
* @param transitionSpec defines the EnterTransition(s) and ExitTransition(s) used to display
* and remove the content, fading in and fading out by default
* @param content Content to appear or disappear based on the value of [targetState]
*
* @link androidx.compose.animation.AnimatedContent
* @see androidx.compose.animation.AnimatedContent
* @see ContentTransform
* @see AnimatedContentScope
*/
@Suppress("IllegalExperimentalApiUsage")
@ExperimentalAnimationApi
@Composable
fun AnimatedContent(
targetState: Int,
modifier: Modifier = Modifier,
transitionSpec: AnimatedContentScope<Int>.() -> ContentTransform = {
ImmersiveListDefaults.EnterTransition.with(ImmersiveListDefaults.ExitTransition)
},
contentAlignment: Alignment = Alignment.TopStart,
content: @Composable AnimatedVisibilityScope.(targetState: Int) -> Unit
) {
androidx.compose.animation.AnimatedContent(
targetState,
modifier,
transitionSpec,
contentAlignment,
content)
}
}
@Immutable
@ExperimentalTvMaterialApi
public class ImmersiveListScope internal constructor(private val onFocused: (Int) -> Unit) {
/**
* Modifier to be added to each of the items of the list within ImmersiveList to inform the
* ImmersiveList of the index of the item in focus.
*
* @param index index of the item within the list.
*/
fun Modifier.focusableItem(index: Int): Modifier {
return onFocusChanged { if (it.hasFocus || it.isFocused) { onFocused(index) } }
.focusable()
}
} | apache-2.0 | 28bc52503d0f93eedee2694a92e2fc99 | 39.516908 | 100 | 0.73265 | 4.935845 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/ComposerIntrinsicTransformer.kt | 3 | 3465 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.lower
import androidx.compose.compiler.plugins.kotlin.ComposeFqNames
import androidx.compose.compiler.plugins.kotlin.lower.decoys.DecoyFqNames
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.util.dump
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class ComposerIntrinsicTransformer(
val context: IrPluginContext,
private val decoysEnabled: Boolean
) :
IrElementTransformerVoid(),
FileLoweringPass,
ModuleLoweringPass {
private val currentComposerIntrinsic = currentComposerFqName()
// get-currentComposer gets transformed as decoy, as the getter now has additional params
private fun currentComposerFqName(): FqName =
if (decoysEnabled) {
DecoyFqNames.CurrentComposerIntrinsic
} else {
ComposeFqNames.CurrentComposerIntrinsic
}
override fun lower(module: IrModuleFragment) {
module.transformChildrenVoid(this)
}
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(this)
}
@OptIn(ObsoleteDescriptorBasedAPI::class)
override fun visitCall(expression: IrCall): IrExpression {
val calleeFqName = expression.symbol.descriptor.fqNameSafe
if (calleeFqName == currentComposerIntrinsic) {
// since this call was transformed by the ComposerParamTransformer, the first argument
// to this call is the composer itself. We just replace this expression with the
// argument expression and we are good.
val expectedArgumentsCount = 1 + // composer parameter
1 // changed parameter
assert(expression.valueArgumentsCount == expectedArgumentsCount) {
"""
Composer call doesn't match expected argument count:
expected: $expectedArgumentsCount,
actual: ${expression.valueArgumentsCount},
expression: ${expression.dump()}
""".trimIndent()
}
val composerExpr = expression.getValueArgument(0)
if (composerExpr == null) error("Expected non-null composer argument")
return composerExpr
}
return super.visitCall(expression)
}
}
| apache-2.0 | 2be3167f10191138b620f6c760e3d403 | 40.746988 | 98 | 0.719192 | 5.058394 | false | false | false | false |
GunoH/intellij-community | platform/dvcs-impl/src/com/intellij/dvcs/MultiMessage.kt | 9 | 2579 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.dvcs
import com.intellij.dvcs.DvcsUtil.joinWithAnd
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsImplUtil.getShortVcsRootName
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
class MultiRootMessage(project: Project, allValues: Collection<VirtualFile>, rootInPrefix: Boolean = false, html: Boolean = true) :
MultiMessage<VirtualFile>(allValues, VirtualFile::getPath, { getShortVcsRootName(project, it) }, rootInPrefix, html)
open class MultiMessage<Aspect>(private val allValues: Collection<Aspect>,
private val logPresentation: (Aspect) -> @Nls String,
private val shortPresentation: (Aspect) -> @Nls String,
private val aspectInPrefix: Boolean,
html: Boolean = true) {
private val LOG = Logger.getInstance(MultiMessage::class.java)
private val messages = linkedMapOf<Aspect, String>()
@NlsSafe
private val lineSeparator = if (html) "<br/>\n" else "\n"
fun append(aspect: Aspect, message: @Nls String): MultiMessage<Aspect> {
if (!allValues.contains(aspect)) {
LOG.error("The aspect value ${logPresentation(aspect)} is unexpected: $allValues")
return this
}
if (messages.containsKey(aspect)) {
LOG.error("Duplicate aspect value ${logPresentation(aspect)} reporting message [$message]")
}
messages.put(aspect, message)
return this
}
fun asString(): @Nls String {
if (messages.isEmpty()) return ""
if (allValues.size == 1) return messages.values.first()
val grouped = messages.keys.groupBy { messages[it]!!.trim() }
if (grouped.size == 1 && allValues.size == messages.size) return messages.values.first()
return grouped.keys.joinToString(lineSeparator) {
val presentableNames = grouped.getValue(it).map { shortPresentation(it) }
val names = joinWithAnd(presentableNames, 5)
if (aspectInPrefix) {
DvcsBundle.message("multi.message.line.prefix.form", names, it)
}
else {
DvcsBundle.message("multi.message.line.suffix.form", names, it)
}
}
}
override fun toString(): @NonNls String {
return messages.toString()
}
}
| apache-2.0 | 7873ca490c3d017c6bef0b3e0b9edd43 | 42.711864 | 140 | 0.692516 | 4.26281 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRDiffPreview.kt | 5 | 8766 | // 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.plugins.github.pullrequest
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.util.DiffUserDataKeys
import com.intellij.diff.util.DiffUtil
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.NonEmptyActionGroup
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.ChangeWrapper
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper
import com.intellij.openapi.vcs.changes.DiffPreview
import com.intellij.openapi.vcs.changes.DiffPreviewController
import com.intellij.openapi.vcs.changes.DiffPreviewControllerBase
import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreview
import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreviewModel
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EditSourceOnDoubleClickHandler
import com.intellij.util.Processor
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.action.GHPRShowDiffActionProvider
import org.jetbrains.plugins.github.pullrequest.comment.action.combined.GHPRCombinedDiffReviewResolvedThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.comment.action.combined.GHPRCombinedDiffReviewThreadsReloadAction
import org.jetbrains.plugins.github.pullrequest.comment.action.combined.GHPRCombinedDiffReviewThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.data.GHPRFilesManager
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDataProvider
import org.jetbrains.plugins.github.util.ChangeDiffRequestProducerFactory
import org.jetbrains.plugins.github.util.GHToolbarLabelAction
import java.util.*
internal class GHPRDiffPreview(private val prId: GHPRIdentifier?,
private val filesManager: GHPRFilesManager) : DiffPreview {
val sourceId = UUID.randomUUID().toString()
override fun updateDiffAction(event: AnActionEvent) {
GHPRShowDiffActionProvider.updateAvailability(event)
}
override fun openPreview(requestFocus: Boolean): Boolean {
if (prId == null) {
filesManager.createAndOpenNewPRDiffPreviewFile(sourceId, false, requestFocus)
}
else {
filesManager.createAndOpenDiffFile(prId, requestFocus)
}
return true
}
override fun closePreview() {
}
}
internal class GHPRCombinedDiffPreview(private val dataProvider: GHPRDataProvider?,
private val filesManager: GHPRFilesManager,
producerFactory: ChangeDiffRequestProducerFactory,
tree: ChangesTree) :
GHPRCombinedDiffPreviewBase(dataProvider, filesManager, producerFactory, tree, filesManager) {
override fun doOpenPreview(requestFocus: Boolean): Boolean {
val sourceId = tree.id
val prId = dataProvider?.id
if (prId == null) {
filesManager.createAndOpenNewPRDiffPreviewFile(sourceId, true, requestFocus)
}
else {
filesManager.createAndOpenDiffPreviewFile(prId, sourceId, requestFocus)
}
return true
}
}
internal abstract class GHPRCombinedDiffPreviewBase(private val dataProvider: GHPRDataProvider?,
private val filesManager: GHPRFilesManager,
private val producerFactory: ChangeDiffRequestProducerFactory,
tree: ChangesTree,
parentDisposable: Disposable) : CombinedDiffPreview(tree, parentDisposable) {
override val previewFile: VirtualFile
get() =
dataProvider?.id.let { prId ->
if (prId == null) {
filesManager.createOrGetNewPRDiffFile(tree.id, true)
}
else {
filesManager.createOrGetDiffFile(prId, tree.id, true)
}
}
override fun createModel(): CombinedDiffPreviewModel =
GHPRCombinedDiffPreviewModel(tree, producerFactory, parentDisposable).also(::setupReviewActions)
private fun setupReviewActions(model: CombinedDiffPreviewModel) {
val context = model.context
DiffUtil.putDataKey(context, GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER, dataProvider)
val viewOptionsGroup = NonEmptyActionGroup().apply {
isPopup = true
templatePresentation.text = GithubBundle.message("pull.request.diff.view.options")
templatePresentation.icon = AllIcons.Actions.Show
add(GHPRCombinedDiffReviewThreadsToggleAction(model))
add(GHPRCombinedDiffReviewResolvedThreadsToggleAction(model))
}
context.putUserData(DiffUserDataKeys.CONTEXT_ACTIONS, listOf(
GHToolbarLabelAction(GithubBundle.message("pull.request.diff.review.label")),
viewOptionsGroup,
GHPRCombinedDiffReviewThreadsReloadAction(model),
ActionManager.getInstance().getAction("Github.PullRequest.Review.Submit")))
}
override fun getCombinedDiffTabTitle(): String = previewFile.name
override fun updateDiffAction(event: AnActionEvent) {
super.updateDiffAction(event)
GHPRShowDiffActionProvider.updateAvailability(event)
}
override fun openPreview(requestFocus: Boolean): Boolean {
if (!ensureHasContent()) return false
return openPreviewEditor(requestFocus)
}
private fun ensureHasContent(): Boolean {
updatePreviewProcessor.refresh(false)
return hasContent()
}
private fun openPreviewEditor(requestFocus: Boolean): Boolean {
escapeHandler?.let { handler -> registerEscapeHandler(previewFile, handler) }
return doOpenPreview(requestFocus)
}
abstract fun doOpenPreview(requestFocus: Boolean): Boolean
companion object {
fun createAndSetupDiffPreview(tree: ChangesTree,
producerFactory: ChangeDiffRequestProducerFactory,
dataProvider: GHPRDataProvider?,
filesManager: GHPRFilesManager): DiffPreviewController {
val diffPreviewHolder =
object : DiffPreviewControllerBase() {
override val simplePreview = GHPRDiffPreview(dataProvider?.id, filesManager)
override fun createCombinedDiffPreview() = GHPRCombinedDiffPreview(dataProvider, filesManager, producerFactory, tree)
}
tree.apply {
doubleClickHandler = Processor { e ->
if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false
diffPreviewHolder.activePreview.performDiffAction()
true
}
enterKeyHandler = Processor {
diffPreviewHolder.activePreview.performDiffAction()
true
}
}
return diffPreviewHolder
}
}
}
private class GHPRCombinedDiffPreviewModel(tree: ChangesTree,
private val producerFactory: ChangeDiffRequestProducerFactory,
parentDisposable: Disposable) :
CombinedDiffPreviewModel(tree, prepareCombinedDiffModelRequests(tree.project, tree.getAllChanges(producerFactory)), parentDisposable) {
override fun iterateAllChanges(): Iterable<Wrapper> {
return tree.iterateAllChanges(producerFactory)
}
override fun iterateSelectedChanges(): Iterable<Wrapper> {
return VcsTreeModelData.selected(tree).iterateUserObjects(Change::class.java)
.map { change -> MyChangeWrapper(change, producerFactory) }
}
private class MyChangeWrapper(change: Change,
private val changeProducerFactory: ChangeDiffRequestProducerFactory) : ChangeWrapper(change) {
override fun createProducer(project: Project?): DiffRequestProducer? = changeProducerFactory.create(project, change)
}
companion object {
private fun ChangesTree.getAllChanges(producerFactory: ChangeDiffRequestProducerFactory) = iterateAllChanges(producerFactory).toList()
private fun ChangesTree.iterateAllChanges(producerFactory: ChangeDiffRequestProducerFactory): Iterable<Wrapper> {
return VcsTreeModelData.all(this).iterateUserObjects(Change::class.java)
.map { change -> MyChangeWrapper(change, producerFactory) }
}
}
}
| apache-2.0 | 378be1be6dae20c0786eceb6424c00c7 | 43.272727 | 138 | 0.739676 | 5.087638 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestShort.kt | 2 | 2127 | // 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 org.jetbrains.plugins.github.api.data.pullrequest
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.intellij.collaboration.api.dto.GraphQLFragment
import com.intellij.collaboration.api.dto.GraphQLNodesDTO
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.plugins.github.api.data.*
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import java.util.*
@GraphQLFragment("/graphql/fragment/pullRequestInfoShort.graphql")
open class GHPullRequestShort(id: String,
val url: String,
override val number: Long,
@NlsSafe val title: String,
val state: GHPullRequestState,
val isDraft: Boolean,
val author: GHActor?,
val createdAt: Date,
@JsonProperty("assignees") assignees: GraphQLNodesDTO<GHUser>,
@JsonProperty("labels") labels: GraphQLNodesDTO<GHLabel>,
@JsonProperty("reviewRequests") reviewRequests: GraphQLNodesDTO<GHPullRequestReviewRequest>,
@JsonProperty("reviewThreads") reviewThreads: GraphQLNodesDTO<ReviewThreadDetails>,
val mergeable: GHPullRequestMergeableState,
val viewerCanUpdate: Boolean,
val viewerDidAuthor: Boolean) : GHNode(id), GHPRIdentifier {
@JsonIgnore
val assignees = assignees.nodes
@JsonIgnore
val labels = labels.nodes
@JsonIgnore
val reviewRequests = reviewRequests.nodes
@JsonIgnore
val unresolvedReviewThreadsCount = reviewThreads.nodes.count { !it.isResolved && !it.isOutdated }
override fun toString(): String = "#$number $title"
class ReviewThreadDetails(val isResolved: Boolean, val isOutdated: Boolean)
} | apache-2.0 | 22f3f491f4ac2372106ed24fc577f339 | 46.288889 | 140 | 0.649271 | 5.291045 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/coroutines/controlFlow_tryCatch1.kt | 4 | 1109 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package codegen.coroutines.controlFlow_tryCatch1
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
val x = try {
s1()
} catch (t: Throwable) {
f2()
}
result = x
}
println(result)
} | apache-2.0 | a43561d79953372252f9b8ac6a322b9c | 18.821429 | 115 | 0.635708 | 3.772109 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/kotlin.search.k2/src/org/jetbrains/kotlin/idea/inheritorsSearch/KotlinFirDefinitionsSearcher.kt | 1 | 6900 | // 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.inheritorsSearch
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.psi.search.searches.FunctionalExpressionSearch
import com.intellij.util.Processor
import com.intellij.util.QueryExecutor
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.actualsForExpected
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import java.util.concurrent.Callable
class KotlinFirDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters> {
override fun execute(queryParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>): Boolean {
val processor = skipDelegatedMethodsConsumer(consumer)
val element = queryParameters.element
val scope = queryParameters.scope
return when (element) {
is KtClass -> {
val isExpectEnum = runReadAction { element.isEnum() && element.isExpectDeclaration() }
if (isExpectEnum) {
processActualDeclarations(element, processor)
} else {
processClassImplementations(element, processor) && processActualDeclarations(element, processor)
}
}
is KtObjectDeclaration -> {
processActualDeclarations(element, processor)
}
is KtNamedFunction, is KtSecondaryConstructor -> {
processFunctionImplementations(element as KtFunction, scope, processor) && processActualDeclarations(element, processor)
}
is KtProperty -> {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
}
is KtParameter -> {
if (isFieldParameter(element)) {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
} else {
true
}
}
else -> true
}
}
companion object {
private fun skipDelegatedMethodsConsumer(baseConsumer: Processor<in PsiElement>): Processor<PsiElement> = Processor { element ->
if (isDelegated(element)) {
return@Processor true
}
baseConsumer.process(element)
}
private fun isDelegated(element: PsiElement): Boolean = element is KtLightMethod && element.isDelegated
private fun isFieldParameter(parameter: KtParameter): Boolean = runReadAction {
KtPsiUtil.getClassIfParameterIsProperty(parameter) != null
}
private fun processClassImplementations(klass: KtClass, consumer: Processor<PsiElement>): Boolean {
val searchScope = runReadAction { klass.useScope }
if (searchScope is LocalSearchScope) {
return processLightClassLocalImplementations(klass, searchScope, consumer)
}
return ContainerUtil.process(klass.findAllInheritors(klass.useScope), consumer)
}
private fun processLightClassLocalImplementations(
ktClass: KtClass,
searchScope: LocalSearchScope,
consumer: Processor<PsiElement>
): Boolean {
// workaround for IDEA optimization that uses Java PSI traversal to locate inheritors in local search scope
val virtualFiles = runReadAction {
searchScope.scope.mapTo(HashSet()) { it.containingFile.virtualFile }
}
val globalScope = GlobalSearchScope.filesScope(ktClass.project, virtualFiles)
return ContainerUtil.process(ktClass.findAllInheritors(globalScope)) { candidate ->
val candidateOrigin = candidate.unwrapped ?: candidate
val inScope = runReadAction { candidateOrigin in searchScope }
if (inScope) {
consumer.process(candidate)
} else {
true
}
}
}
private fun processFunctionImplementations(
function: KtFunction,
scope: SearchScope,
consumer: Processor<PsiElement>,
): Boolean =
ReadAction.nonBlocking(Callable {
if (!function.findAllOverridings(scope).all { consumer.process(it) }) return@Callable false
val method = function.toPossiblyFakeLightMethods().firstOrNull() ?: return@Callable true
FunctionalExpressionSearch.search(method, scope).forEach(consumer)
}).executeSynchronously()
private fun processPropertyImplementations(
declaration: KtCallableDeclaration,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean = runReadAction {
processPropertyImplementationsMethods(declaration, scope, consumer)
}
private fun processActualDeclarations(declaration: KtDeclaration, consumer: Processor<PsiElement>): Boolean = runReadAction {
if (!declaration.isExpectDeclaration()) true
else declaration.actualsForExpected().all(consumer::process)
}
private fun processPropertyImplementationsMethods(
callableDeclaration: KtCallableDeclaration,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean =
callableDeclaration.findAllOverridings(scope).all { implementation ->
if (isDelegated(implementation)) return@all true
val elementToProcess = runReadAction {
when (val mirrorElement = (implementation as? KtLightMethod)?.kotlinOrigin) {
is KtProperty, is KtParameter -> mirrorElement
is KtPropertyAccessor -> if (mirrorElement.parent is KtProperty) mirrorElement.parent else implementation
else -> implementation
}
}
consumer.process(elementToProcess)
}
}
}
| apache-2.0 | 58325d1bb4e646454f4d11b198415ce5 | 42.670886 | 136 | 0.66 | 5.958549 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeFieldPublicFix.kt | 5 | 1914 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier
class MakeFieldPublicFix(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.let { property ->
val currentVisibilityModifier = property.visibilityModifier()
if (currentVisibilityModifier != null && currentVisibilityModifier.elementType != KtTokens.PUBLIC_KEYWORD) {
property.removeModifier(currentVisibilityModifier.elementType as KtModifierKeywordToken)
}
if (!KotlinPsiHeuristics.hasAnnotation(property, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME.shortName())) {
ShortenReferences.DEFAULT.process(
property.addAnnotationEntry(KtPsiFactory(project).createAnnotationEntry("@kotlin.jvm.JvmField"))
)
}
}
}
override fun getText(): String = familyName
override fun getFamilyName(): String = element?.name?.let { KotlinBundle.message("fix.make.field.public", it) } ?: ""
} | apache-2.0 | 15a971714716bd708a12c08b0be68ea3 | 50.756757 | 122 | 0.756008 | 4.725926 | false | false | false | false |
smmribeiro/intellij-community | java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaSoftKeywordHighlighting.kt | 4 | 2627 | // 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.codeInsight.daemon.impl
import com.intellij.codeHighlighting.TextEditorHighlightingPass
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactoryRegistrar
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar
import com.intellij.lang.java.lexer.JavaLexer
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.*
internal class JavaSoftKeywordHighlightingPassFactory : TextEditorHighlightingPassFactory, TextEditorHighlightingPassFactoryRegistrar {
override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) {
registrar.registerTextEditorHighlightingPass(this, null, null, false, -1)
}
override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? =
if (file is PsiJavaFile) JavaSoftKeywordHighlightingPass(file, editor.document) else null
}
private class JavaSoftKeywordHighlightingPass(private val file: PsiJavaFile, document: Document) :
TextEditorHighlightingPass(file.project, document) {
private val results = mutableListOf<HighlightInfo>()
override fun doCollectInformation(progress: ProgressIndicator) {
if (file.name == PsiJavaModule.MODULE_INFO_FILE || file.languageLevel.isAtLeast(LanguageLevel.JDK_10)) {
file.accept(JavaSoftKeywordHighlightingVisitor(results, file.languageLevel))
}
}
override fun doApplyInformationToEditor() {
UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, file.textLength, results, colorsScheme, id)
}
}
private class JavaSoftKeywordHighlightingVisitor(private val results: MutableList<HighlightInfo>, private val level: LanguageLevel) :
JavaRecursiveElementWalkingVisitor() {
override fun visitKeyword(keyword: PsiKeyword) {
if (JavaLexer.isSoftKeyword(keyword.node.chars, level)) {
highlightAsKeyword(keyword)
}
else if (JavaTokenType.NON_SEALED_KEYWORD == keyword.tokenType) {
highlightAsKeyword(keyword)
}
}
private fun highlightAsKeyword(keyword: PsiKeyword) {
val info = HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.JAVA_KEYWORD).range(keyword).create()
if (info != null) {
results += info
}
}
}
| apache-2.0 | 2ea425782c2ac3d0d94d43879b2428d0 | 43.525424 | 140 | 0.806624 | 4.8829 | false | false | false | false |
ianhanniballake/muzei | android-client-common/src/main/java/com/google/android/apps/muzei/room/Artwork.kt | 1 | 2101 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.room
import android.content.ContentResolver
import android.content.ContentUris
import android.net.Uri
import android.provider.BaseColumns
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.google.android.apps.muzei.api.MuzeiContract
import com.google.android.apps.muzei.room.converter.DateTypeConverter
import com.google.android.apps.muzei.room.converter.UriTypeConverter
import java.util.Date
/**
* Artwork's representation in Room
*/
@Entity(indices = [(Index(value = ["providerAuthority"]))])
data class Artwork(
@field:TypeConverters(UriTypeConverter::class)
val imageUri: Uri
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = BaseColumns._ID)
var id: Long = 0
lateinit var providerAuthority: String
var title: String? = null
var byline: String? = null
var attribution: String? = null
var metaFont = ""
@TypeConverters(DateTypeConverter::class)
@ColumnInfo(name = "date_added")
var dateAdded = Date()
val contentUri: Uri
get() = getContentUri(id)
companion object {
fun getContentUri(id: Long): Uri {
return ContentUris.appendId(Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(MuzeiContract.AUTHORITY)
.appendPath("artwork"), id).build()
}
}
}
| apache-2.0 | c94c52c8d762b62416148920b69e751f | 28.591549 | 75 | 0.710138 | 4.253036 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/repository/RepositoryResult.kt | 1 | 920 | package com.cognifide.gradle.aem.common.instance.service.repository
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
class RepositoryResult {
lateinit var title: String
lateinit var path: String
@JsonProperty("status.code")
var statusCode: Int = -1
@JsonProperty("status.message")
var statusMessage: String? = null
lateinit var referer: String
lateinit var location: String
lateinit var parentLocation: String
var error: RepositoryError? = null
lateinit var changes: List<RepositoryChange>
val success: Boolean
get() = !fail
val fail: Boolean
get() = error != null
override fun toString(): String {
return "RepositoryResult(title='$title', path='$path', statusCode=$statusCode, statusMessage=$statusMessage)"
}
}
| apache-2.0 | af0b12bfd202fa6533f1045951c0b2ca | 23.210526 | 117 | 0.715217 | 4.791667 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/fragment/TabArticleFragment.kt | 1 | 3849 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zwq65.unity.ui.fragment
import android.os.Bundle
import androidx.annotation.IntDef
import com.zwq65.unity.R
import com.zwq65.unity.data.network.retrofit.response.enity.Article
import com.zwq65.unity.ui._base.BaseRefreshFragment
import com.zwq65.unity.ui._base.adapter.BaseRecyclerViewAdapter
import com.zwq65.unity.ui.activity.WebArticleActivity
import com.zwq65.unity.ui.adapter.TabArticleAdapter
import com.zwq65.unity.ui.contract.TabArticleContract
import javax.inject.Inject
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/08/31
* Contact with <[email protected]>
* ================================================
*/
class TabArticleFragment : BaseRefreshFragment<Article, TabArticleContract.View<Article>, TabArticleContract.Presenter<TabArticleContract.View<Article>>>(), TabArticleContract.View<Article> {
@Type
private var mType: Int = 0
@Inject
lateinit var mAdapter: TabArticleAdapter<Article>
override val layoutId: Int
get() = R.layout.fragment_tab_article
/**
* 获取RecycleView的spanCount
*
* @return If orientation is vertical, spanCount is number of columns. If orientation is horizontal, spanCount is number of rows.
*/
override val spanCount: Int
get() = 1
override fun initView() {
super.initView()
mAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<Article> {
override fun onClick(t: Article, position: Int) {
gotoDetailActivity(t)
}
})
mRecyclerView.adapter = mAdapter
}
override fun initData(saveInstanceState: Bundle?) {
super.initData(saveInstanceState)
getType()
initData()
}
override fun requestDataRefresh() {
initData()
}
override fun requestDataLoad() {
mPresenter.loadDatas(false)
}
fun initData() {
mPresenter.init()
}
private fun gotoDetailActivity(article: Article) {
val bundle = Bundle()
bundle.putParcelable(WebArticleActivity.ARTICLE, article)
mActivity!!.openActivity(WebArticleActivity::class.java, bundle)
}
override fun refreshData(list: List<Article>) {
super.refreshData(list)
mAdapter.clearItems()
mAdapter.addItems(list)
}
override fun loadData(list: List<Article>) {
super.loadData(list)
mAdapter.addItems(list)
}
private fun getType() {
if (arguments != null) {
mType = arguments!!.getInt(TECH_TAG, ANDROID)
mPresenter.setType(mType)
}
}
@IntDef(ANDROID, IOS, H5)
@kotlin.annotation.Retention
annotation class Type
companion object {
const val TECH_TAG = "TECH_TAG"
const val ANDROID = R.string.android
const val IOS = R.string.ios
const val H5 = R.string.qianduan
fun newInstance(@Type type: Int): TabArticleFragment {
val args = Bundle()
args.putInt(TECH_TAG, type)
val fragment = TabArticleFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | aa8926d5651784861f93edb6b37ec8ad | 29.5 | 191 | 0.649753 | 4.422325 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/SyntaxHighlightView.kt | 1 | 3022 | package ch.rmy.android.http_shortcuts.activities.response
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.webkit.WebView
import androidx.core.text.TextUtilsCompat.htmlEncode
import ch.rmy.android.framework.extensions.isDarkThemeEnabled
import ch.rmy.android.framework.extensions.tryOrLog
import ch.rmy.android.http_shortcuts.utils.GsonUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@SuppressLint("SetJavaScriptEnabled")
class SyntaxHighlightView
@JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : WebView(context, attrs, defStyleAttr) {
init {
setBackgroundColor(Color.TRANSPARENT)
settings.javaScriptEnabled = true
}
suspend fun setCode(content: String, language: Language) {
if (language == Language.JSON) {
tryOrLog {
val prettyJson = withContext(Dispatchers.Default) {
GsonUtil.prettyPrint(content)
}
withContext(Dispatchers.Main) {
apply(prettyJson, language.language)
}
}
} else {
apply(content, language.language)
}
}
private fun apply(content: String, language: String) {
val html = """
<html>
<head>
<link rel="stylesheet" href="file:///android_asset/highlight/styles/${getStyle()}.css">
<link rel="stylesheet" href="file:///android_asset/highlight/style-override.css">
<script src="file:///android_asset/highlight/highlight.pack.js"></script>
<script>
let wrapLines = false;
document.addEventListener("click", function() {
wrapLines = !wrapLines;
const body = document.getElementById("body");
if (wrapLines) {
body.classList.add('wrap-lines');
} else {
body.classList.remove('wrap-lines');
}
});
hljs.initHighlightingOnLoad();
</script>
</head>
<body id="body">
<pre>
<code class="$language">${htmlEncode(content)}</code>
</pre>
</body>
</html>
""".trimIndent()
loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", "")
}
private fun getStyle() = if (context.isDarkThemeEnabled()) {
"darcula"
} else {
"default"
}
enum class Language(val language: String) {
XML("xml"),
JSON("json"),
YAML("yaml")
}
}
| mit | 7b04dea4110561f531108bb112fee42f | 34.552941 | 107 | 0.532429 | 5.096121 | false | false | false | false |
breadwallet/breadwallet-android | ui/ui-gift/src/main/java/CreateGift.kt | 1 | 7970 | /**
* BreadWallet
*
* Created by Ahsan Butt <[email protected]> on 12/09/20.
* Copyright (c) 2020 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.ui.uigift
import com.breadwallet.breadbox.TransferSpeed
import com.breadwallet.crypto.TransferFeeBasis
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.util.CurrencyCode
import dev.zacsweers.redacted.annotations.Redacted
import java.math.BigDecimal
object CreateGift {
enum class State {
LOADING,
READY,
SENDING
}
enum class Error(val isCritical: Boolean) {
PAPER_WALLET_ERROR(true),
SERVER_ERROR(true),
INSUFFICIENT_BALANCE_ERROR(true),
INSUFFICIENT_BALANCE_FOR_AMOUNT_ERROR(false),
INPUT_AMOUNT_ERROR(false),
INPUT_RECIPIENT_NAME_ERROR(false),
TRANSACTION_ERROR( false)
}
enum class PaperWalletError {
UNKNOWN
}
enum class MaxEstimateError {
INSUFFICIENT_BALANCE,
SERVER_ERROR,
INVALID_TARGET
}
enum class FeeEstimateError {
INSUFFICIENT_BALANCE,
SERVER_ERROR,
INVALID_TARGET
}
data class FiatAmountOption(
val amount: BigDecimal,
val enabled: Boolean = false,
val fiatCurrencyCode: String
)
const val MAX_DIGITS = 8
fun getFiatAmountOptions(fiatCurrencyCode: String) = listOf(25, 50, 100, 250, 500)
.map { FiatAmountOption(it.toBigDecimal(), fiatCurrencyCode = fiatCurrencyCode) }
data class M(
val currencyId: String = "",
val currencyCode: CurrencyCode = "btc", // TODO: Get from currencyId
val fiatCurrencyCode: String = BRConstants.USD,
val fiatAmountOptions: List<FiatAmountOption> = getFiatAmountOptions(fiatCurrencyCode),
val transferSpeed: TransferSpeed = TransferSpeed.Regular(currencyCode),
val recipientName: String = "",
val amountSelectionIndex: Int = -1,
val fiatAmount: BigDecimal = BigDecimal.ZERO,
val fiatMaxAmount: BigDecimal = BigDecimal.ZERO,
val fiatPerCryptoUnit: BigDecimal = BigDecimal.ZERO,
val feeEstimate: TransferFeeBasis? = null,
@Redacted val paperKey: String? = null,
@Redacted val address: String? = null,
@Redacted val giftUrl: String? = null,
val txHash: String? = null,
val state: State = State.LOADING,
val attemptedSend: Boolean = false
) {
companion object {
fun createDefault(currencyId: String) =
M(currencyId = currencyId)
}
}
sealed class E {
data class OnNameChanged(val name: String) : E()
data class OnAmountClicked(val index: Int, val isChecked: Boolean) : E()
data class OnPaperWalletCreated(
@Redacted val privateKey: String,
@Redacted val address: String,
@Redacted val giftUrl: String
) : E()
data class OnPaperWalletFailed(val error: PaperWalletError) : E()
data class OnMaxEstimated(val fiatAmount: BigDecimal, val fiatPerCryptoUnit: BigDecimal) : E()
data class OnMaxEstimateFailed(val error: MaxEstimateError) : E()
data class OnFeeUpdated(val feeEstimate: TransferFeeBasis) : E()
data class OnFeeFailed(val error: FeeEstimateError) : E()
data class OnTransactionSent(val txHash: String): E()
object OnTransferFailed : E()
object OnGiftBackupDeleted: E()
object OnGiftSaved: E()
object OnCloseClicked : E()
object OnCreateClicked : E()
object OnTransactionConfirmClicked : E()
object OnTransactionCancelClicked : E()
}
sealed class F {
object CreatePaperWallet : F()
object Close: F(), ViewEffect
data class BackupGift(
@Redacted val address: String,
@Redacted val privateKey: String
): F()
data class DeleteGiftBackup(@Redacted val address: String): F()
data class EstimateMax(
@Redacted val address: String,
val transferSpeed: TransferSpeed,
val fiatCurrencyCode: String
) : F()
data class EstimateFee(
@Redacted val address: String,
val amount: BigDecimal,
val transferSpeed: TransferSpeed
) : F()
data class ConfirmTransaction(
val name: String,
val amount: BigDecimal,
val currencyCode: CurrencyCode,
val fiatAmount: BigDecimal,
val fiatFee: BigDecimal,
val fiatCurrencyCode: String
) : F(), ViewEffect
data class SendTransaction(
@Redacted val address: String,
val amount: BigDecimal,
val transferFeeBasis: TransferFeeBasis
) : F()
data class SaveGift(
@Redacted val address: String,
@Redacted val privateKey: String,
val recipientName: String,
val txHash: String,
val fiatCurrencyCode: String,
val fiatAmount: BigDecimal,
val fiatPerCryptoUnit: BigDecimal
) : F()
data class GoToShareGift(
@Redacted val giftUrl: String,
@Redacted val txHash: String,
@Redacted val recipientName: String,
val giftAmount: BigDecimal,
val giftAmountFiat: BigDecimal,
val pricePerUnit: BigDecimal
) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.ShareGift(
giftUrl,
txHash,
recipientName,
giftAmount,
giftAmountFiat,
pricePerUnit,
replaceTop = true
)
}
data class ShowError(val error: Error) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
error.name,
messageResId = when(error) {
Error.PAPER_WALLET_ERROR -> R.string.CreateGift_unexpectedError
Error.SERVER_ERROR -> R.string.CreateGift_serverError
Error.INSUFFICIENT_BALANCE_ERROR -> R.string.CreateGift_insufficientBalanceError
Error.INSUFFICIENT_BALANCE_FOR_AMOUNT_ERROR -> R.string.CreateGift_insufficientBalanceForAmountError
Error.INPUT_AMOUNT_ERROR -> R.string.CreateGift_inputAmountError
Error.INPUT_RECIPIENT_NAME_ERROR -> R.string.CreateGift_inputRecipientNameError
Error.TRANSACTION_ERROR -> R.string.CreateGift_unexpectedError
},
positiveButtonResId = R.string.Button_ok
)
}
}
}
| mit | 7987ce12e987cf4a603c64e36ca1fa75 | 34.580357 | 120 | 0.638519 | 4.778177 | false | false | false | false |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/views/decorators/DividerItemDEcorator.kt | 1 | 3963 | package com.claraboia.bibleandroid.views.decorators
/**
* Created by lucasbatagliao on 22/10/16.
*/
/*
* Copyright (C) 2014 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.
*/
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.DisplayMetrics
import android.view.Display
import android.view.View
import com.claraboia.bibleandroid.R
class DividerItemDecoration(private val context: Context, orientation: Int) : RecyclerView.ItemDecoration() {
//private val ATTRS: IntArray = intArrayOf(android.R.attr.listDivider)
companion object {
val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL
val VERTICAL_LIST = LinearLayoutManager.VERTICAL
}
private var mDivider: Drawable? = null
private var mOrientation: Int = 0
init {
//val a: TypedArray = context.obtainStyledAttributes(ATTRS)
//mDivider = a.getDrawable(0)
//a.recycle()
mDivider = ContextCompat.getDrawable(context, R.drawable.linedivider)
setOrientation(orientation)
}
fun setOrientation(orientation: Int) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw IllegalArgumentException("invalid orientation")
}
mOrientation = orientation
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
fun drawVertical(c: Canvas, parent: RecyclerView) {
val metrics = context.resources.displayMetrics
val space = (metrics.density * 12).toInt()
val left = parent.paddingLeft + space
val right = parent.width - parent.paddingRight - space
val childCount = parent.childCount
for (i in 0..childCount - 2) { //exclude last item
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider?.intrinsicHeight as Int
mDivider?.setBounds(left, top, right, bottom)
mDivider?.draw(c)
}
}
fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0..childCount - 2) { //exclude last item
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin
val right = left + mDivider?.intrinsicHeight as Int
mDivider?.setBounds(left, top, right, bottom)
mDivider?.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider?.intrinsicHeight as Int)
} else {
outRect.set(0, 0, mDivider?.intrinsicWidth as Int, 0)
}
}
} | apache-2.0 | 8e39d05c2bcd970599b90c7263fdcac2 | 34.392857 | 109 | 0.675246 | 4.597448 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/commands/data/TileSender.kt | 1 | 1039 | package wiresegal.cmdctrl.common.commands.data
import net.minecraft.command.ICommandSender
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.math.Vec3d
import net.minecraft.util.text.ITextComponent
import net.minecraft.util.text.TextComponentString
import net.minecraft.util.text.event.ClickEvent
/**
* @author WireSegal
* Created at 11:19 PM on 12/3/16.
*/
class TileSender(val parent: ICommandSender, val tile: TileEntity) : ICommandSender by parent {
override fun getPosition() = tile.pos
override fun getPositionVector() = Vec3d(tile.pos)
override fun getName(): String {
val display = tile.displayName
return display?.formattedText ?: TileSelector.classToNameMap[tile.javaClass] ?: "INVALID TILE"
}
override fun getDisplayName(): ITextComponent {
val comp = TextComponentString(name)
comp.style.clickEvent = ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, tile.pos.run { "/tp $x $y $z" })
comp.style.insertion = this.name
return comp
}
}
| mit | a01a1dc799e81ab4c1059b1671b405da | 34.827586 | 110 | 0.733397 | 4.07451 | false | false | false | false |
AlmasB/FXGL | fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/trade/Shop.kt | 1 | 1948 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.trade
import javafx.beans.property.IntegerProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
/**
*
* @author Almas Baimagambetov ([email protected])
*/
interface ShopListener<T> {
/**
* Called when this shop sells [item] to another shop.
*/
fun onSold(item: TradeItem<T>)
/**
* Called when this shop buys [item] from another shop.
*/
fun onBought(item: TradeItem<T>)
}
class Shop<T>(initialMoney: Int, items: List<TradeItem<T>>) {
constructor(items: List<TradeItem<T>>) : this(0, items)
var listener: ShopListener<T>? = null
val items: ObservableList<TradeItem<T>> = FXCollections.observableArrayList(items)
private val propMoney = SimpleIntegerProperty(initialMoney)
fun moneyProperty(): IntegerProperty = propMoney
var money: Int
get() = propMoney.value
set(value) { propMoney.value = value }
fun buyFrom(other: Shop<T>, item: TradeItem<T>, qty: Int): Boolean {
if (item.quantity < qty)
return false
if (item !in other.items)
return false
val cost = item.buyPrice * qty
if (money < cost)
return false
// transaction is successful
money -= cost
other.money += cost
val copy = item.copy().also { it.quantity = qty }
listener?.onBought(copy)
other.listener?.onSold(copy)
item.quantity -= qty
if (item in items) {
items.find { it == item }!!.quantity += qty
} else {
items += item.copy().also { it.quantity = qty }
}
if (item.quantity == 0) {
other.items -= item
}
return true
}
}
| mit | 4ffdca0e20ad2bf4d8b418cd25782e36 | 22.46988 | 86 | 0.609856 | 4.024793 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/NewResourceTask.kt | 1 | 11027 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.util
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.ParameterException
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.UnthreadedTaskRunner
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.tickle.Costume
import uk.co.nickthecoder.tickle.CostumeGroup
import uk.co.nickthecoder.tickle.Pose
import uk.co.nickthecoder.tickle.editor.FXCoderStub
import uk.co.nickthecoder.tickle.editor.MainWindow
import uk.co.nickthecoder.tickle.editor.ScriptStub
import uk.co.nickthecoder.tickle.editor.resources.DesignJsonScene
import uk.co.nickthecoder.tickle.editor.resources.DesignSceneResource
import uk.co.nickthecoder.tickle.editor.resources.ResourceType
import uk.co.nickthecoder.tickle.editor.tabs.FXCoderTab
import uk.co.nickthecoder.tickle.events.CompoundInput
import uk.co.nickthecoder.tickle.graphics.*
import uk.co.nickthecoder.tickle.resources.*
import uk.co.nickthecoder.tickle.scripts.Language
import uk.co.nickthecoder.tickle.scripts.ScriptManager
import uk.co.nickthecoder.tickle.sound.Sound
import java.io.File
class NewResourceTask(resourceType: ResourceType = ResourceType.ANY, defaultName: String = "", val newScriptType: Class<*>? = null)
: AbstractTask() {
val nameP = StringParameter("name", label = "${resourceType.label} Name", value = defaultName)
val textureP = FileParameter("textureFile", label = "File", value = File(Resources.instance.file.parentFile, "images").absoluteFile)
val poseP = createTextureParameter()
val costumePoseP = createPoseParameter("costumePose", required = false)
val costumeFontP = createFontParameter("costumeFont")
val costumePoseOrFontP = OneOfParameter("newCostume", label = "From", choiceLabel = "From")
.addChoices("Pose" to costumePoseP, "Font" to costumeFontP)
val costumeP = SimpleGroupParameter("costume")
.addParameters(costumePoseOrFontP, costumePoseP, costumeFontP)
val costumeGroupP = InformationParameter("costumeGroup", information = "")
val layoutP = InformationParameter("layout", information = "")
val inputP = InformationParameter("input", information = "")
val fontP = FontParameter("font")
val sceneDirectoryP = InformationParameter("sceneDirectory", information = "")
val sceneP = FileParameter("scene", label = "Directory", expectFile = false, value = Resources.instance.sceneDirectory.absoluteFile)
val soundP = FileParameter("soundFile", label = "File", value = File(Resources.instance.file.parentFile, "sounds").absoluteFile, extensions = listOf("ogg"))
val scriptLanguageP = ChoiceParameter<Language>("language")
val fxCoderP = InformationParameter("fxCoder", information = "")
init {
ScriptManager.languages().forEach { language ->
scriptLanguageP.addChoice(language.name, language, language.name)
if (scriptLanguageP.value == null) {
scriptLanguageP.value = language
}
}
}
val resourceTypeP = OneOfParameter("resourceType", label = "Resource", choiceLabel = "Type")
override val taskD = TaskDescription("newResource", label = "New ${resourceType.label}", height = if (resourceType == ResourceType.ANY) 300 else null)
.addParameters(nameP, resourceTypeP)
override val taskRunner = UnthreadedTaskRunner(this)
constructor(pose: Pose, defaultName: String = "") : this(ResourceType.COSTUME, defaultName) {
costumePoseOrFontP.value = costumePoseP
costumePoseP.value = pose
}
constructor(fontResource: FontResource, defaultName: String = "") : this(ResourceType.COSTUME, defaultName) {
costumePoseOrFontP.value = costumeFontP
costumeFontP.value = fontResource
}
init {
val parameter = when (resourceType) {
ResourceType.TEXTURE -> textureP
ResourceType.POSE -> poseP
ResourceType.COSTUME -> costumeP
ResourceType.COSTUME_GROUP -> costumeGroupP
ResourceType.LAYOUT -> layoutP
ResourceType.INPUT -> inputP
ResourceType.FONT -> fontP
ResourceType.SCENE_DIRECTORY -> sceneDirectoryP
ResourceType.SCENE -> sceneP
ResourceType.SOUND -> soundP
ResourceType.SCRIPT -> scriptLanguageP
ResourceType.FXCODER -> fxCoderP
else -> null
}
if (parameter == null) {
resourceTypeP.addChoices(
"Texture" to textureP,
"Pose" to poseP,
"Font" to fontP,
"Costume" to costumeP,
"Costume Group" to costumeGroupP,
"Layout" to layoutP,
"Input" to inputP,
"Scene Directory" to sceneDirectoryP,
"Scene" to sceneP,
"Sound" to soundP,
"Script" to scriptLanguageP,
"FXCoder" to fxCoderP)
taskD.addParameters(textureP, poseP, fontP, costumeP, costumeGroupP, layoutP, inputP, sceneDirectoryP, sceneP, soundP, scriptLanguageP, fxCoderP)
} else {
resourceTypeP.hidden = true
resourceTypeP.value = parameter
if (parameter !is InformationParameter) {
taskD.addParameters(parameter)
}
}
}
override fun customCheck() {
val resourceType = when (resourceTypeP.value) {
textureP -> Resources.instance.textures
poseP -> Resources.instance.poses
costumeP -> Resources.instance.costumes
costumeGroupP -> Resources.instance.costumeGroups
layoutP -> Resources.instance.layouts
inputP -> Resources.instance.inputs
fontP -> Resources.instance.fontResources
soundP -> Resources.instance.sounds
else -> null
}
if (resourceType != null) {
if (resourceType.find(nameP.value) != null) {
throw ParameterException(nameP, "Already exists")
}
}
// TODO Do similar tests for sceneDirectory name, scene name and script name.
}
override fun run() {
val name = nameP.value
var data: Any? = null
when (resourceTypeP.value) {
textureP -> {
data = Resources.instance.textures.add(name, Texture.create(textureP.value!!))
}
poseP -> {
val pose = Pose(poseP.value!!)
Resources.instance.poses.add(name, pose)
data = pose
}
costumeP -> {
val costume = Costume()
if (costumePoseOrFontP.value == costumePoseP) {
costumePoseP.value?.let {
costume.addPose("default", it)
}
} else if (costumePoseOrFontP.value == costumeFontP) {
costumeFontP.value?.let { font ->
val textStyle = TextStyle(font, TextHAlignment.LEFT, TextVAlignment.BOTTOM, Color.white())
costume.addTextStyle("default", textStyle)
}
}
Resources.instance.costumes.add(name, costume)
data = costume
}
costumeGroupP -> {
val costumeGroup = CostumeGroup(Resources.instance)
Resources.instance.costumeGroups.add(name, costumeGroup)
data = costumeGroup
}
layoutP -> {
val layout = Layout()
layout.layoutStages["main"] = LayoutStage()
layout.layoutViews["main"] = LayoutView(stageName = "main")
Resources.instance.layouts.add(name, layout)
data = layout
}
inputP -> {
val input = CompoundInput()
Resources.instance.inputs.add(name, input)
data = input
}
sceneDirectoryP -> {
val dir = File(Resources.instance.sceneDirectory, name)
dir.mkdir()
Resources.instance.fireAdded(dir, name)
}
sceneP -> {
val dir = sceneP.value!!
val file = File(dir, "${name}.scene")
val newScene = DesignSceneResource()
var layoutName: String? = "default"
if (Resources.instance.layouts.find(layoutName!!) == null) {
layoutName = Resources.instance.layouts.items().keys.firstOrNull()
if (layoutName == null) {
throw ParameterException(sceneP, "The resources have no layouts. Create a Layout before creating a Scene.")
}
}
newScene.layoutName = layoutName
DesignJsonScene(newScene).save(file)
Resources.instance.fireAdded(file, name)
}
fontP -> {
val fontResource = FontResource()
fontP.update(fontResource)
Resources.instance.fontResources.add(name, fontResource)
data = fontResource
}
soundP -> {
val sound = Sound(soundP.value!!)
Resources.instance.sounds.add(name, sound)
data = sound
}
scriptLanguageP -> {
scriptLanguageP.value?.createScript(Resources.instance.scriptDirectory(), name, newScriptType)?.let { file ->
data = ScriptStub(file)
Resources.instance.fireAdded(file, name)
}
}
fxCoderP -> {
val file = File(Resources.instance.fxcoderDirectory(), "$name.groovy")
file.writeText(FXCoderTab.defaultCode)
data = FXCoderStub(file)
Resources.instance.fireAdded(file, name)
}
}
data?.let {
MainWindow.instance.openTab(name, it)
}
}
fun prompt() {
val taskPrompter = TaskPrompter(this)
taskPrompter.placeOnStage(Stage())
}
}
| gpl-3.0 | 5c2d212c15558a61fd9a7621838ccf86 | 38.665468 | 160 | 0.611771 | 4.678405 | false | false | false | false |
UniversityOfBrightonComputing/iCurves | src/main/kotlin/icurves/recomposition/PiercingData.kt | 1 | 994 | package icurves.recomposition
import icurves.diagram.BasicRegion
import javafx.geometry.Point2D
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
class PiercingData(cluster: List<BasicRegion>, basicRegions: List<BasicRegion>) {
val center: Point2D?
val radius: Double
init {
center = cluster.map { it.getPolygonShape().vertices() }
.flatten()
.groupBy({ it.asInt })
// we search for a vertex that is present in all four regions
.filter { it.value.size == 4 }
.map { Point2D(it.key.getX(), it.key.getY()) }
.firstOrNull()
if (center != null) {
radius = basicRegions
.minus(cluster)
.map { it.getPolygonShape().distance(center.x, center.y) }
.sorted()
.first()
} else {
radius = 0.0
}
}
fun isPiercing() = center != null
} | mit | c1e6471dbedc6010ca675860ca885638 | 25.891892 | 81 | 0.525151 | 4.229787 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/Vector2iParameter.kt | 1 | 2417 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.util
import javafx.util.StringConverter
import org.joml.Vector2i
import uk.co.nickthecoder.paratask.parameters.CompoundParameter
import uk.co.nickthecoder.paratask.parameters.IntParameter
import uk.co.nickthecoder.paratask.parameters.addParameters
import uk.co.nickthecoder.paratask.util.uncamel
import uk.co.nickthecoder.tickle.vector2iFromString
import uk.co.nickthecoder.tickle.vector2iToString
class Vector2iParameter(
name: String,
label: String = name.uncamel(),
value: Vector2i = Vector2i(),
description: String = "",
showXY: Boolean = true)
: CompoundParameter<Vector2i>(
name, label, description) {
val xP = IntParameter("${name}_x", label = if (showXY) "X" else "", minValue = -Int.MAX_VALUE)
var x by xP
val yP = IntParameter("${name}_y", label = if (showXY) "Y" else ",", minValue = -Int.MAX_VALUE)
var y by yP
override val converter = object : StringConverter<Vector2i>() {
override fun fromString(string: String): Vector2i {
return vector2iFromString(string)
}
override fun toString(obj: Vector2i): String {
return vector2iToString(obj)
}
}
override var value: Vector2i
get() {
return Vector2i(xP.value ?: 0, yP.value ?: 0)
}
set(value) {
xP.value = value.x
yP.value = value.y
}
init {
this.value = value
addParameters(xP, yP)
}
override fun toString(): String {
return "Vector2iParameter : $value"
}
override fun copy(): Vector2iParameter {
val copy = Vector2iParameter(name, label, value, description)
return copy
}
}
| gpl-3.0 | adcd279691cc392277f3112575998ad0 | 28.839506 | 99 | 0.678941 | 4.021631 | false | false | false | false |
nfrankel/kaadin | kaadin-core/src/test/kotlin/ch/frankel/kaadin/structure/SplitPanelTest.kt | 1 | 2534 | /*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin.structure
import ch.frankel.kaadin.*
import com.vaadin.ui.*
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.Test
class SplitPanelTest {
@Test
fun `split panel should be added to layout`() {
val layout = horizontalLayout {
verticalSplitPanel()
}
assertThat(layout.componentCount).isEqualTo(1)
val component = layout.getComponent(0)
assertThat(component).isNotNull.isInstanceOf(AbstractSplitPanel::class.java)
}
@Test(dependsOnMethods = ["split panel should be added to layout"])
fun `split panel should accept one child component`() {
val layout = horizontalLayout {
horizontalSplitPanel {
label()
}
}
val component = layout.getComponent(0) as AbstractSplitPanel
assertThat(component.componentCount).isEqualTo(1)
assertThat(component.iterator().next()).isExactlyInstanceOf(Label::class.java)
}
@Test(dependsOnMethods = ["split panel should be added to layout"])
fun `split panel should accept 2 child components`() {
val layout = horizontalLayout {
horizontalSplitPanel {
label()
textField()
}
}
val component = layout.getComponent(0) as AbstractSplitPanel
assertThat(component.componentCount).isEqualTo(2)
val components = component.iterator()
assertThat(components.next()).isExactlyInstanceOf(Label::class.java)
assertThat(components.next()).isExactlyInstanceOf(TextField::class.java)
}
@Test(expectedExceptions = [IllegalArgumentException::class])
fun `panel should not accept more than 2 child components`() {
horizontalLayout {
horizontalSplitPanel {
label()
textField()
label()
}
}
}
} | apache-2.0 | 7622a57df8abbcea6de10983031012a7 | 34.194444 | 86 | 0.659297 | 4.889961 | false | true | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/InjectionTargetsAnalyzer.kt | 1 | 4593 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.analysis
import io.michaelrocks.grip.FieldsResult
import io.michaelrocks.grip.Grip
import io.michaelrocks.grip.MethodsResult
import io.michaelrocks.grip.annotatedWith
import io.michaelrocks.grip.fields
import io.michaelrocks.grip.methods
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.isConstructor
import io.michaelrocks.lightsaber.processor.ErrorReporter
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.commons.cast
import io.michaelrocks.lightsaber.processor.commons.given
import io.michaelrocks.lightsaber.processor.logging.getLogger
import io.michaelrocks.lightsaber.processor.model.InjectionPoint
import io.michaelrocks.lightsaber.processor.model.InjectionTarget
import java.io.File
import java.util.ArrayList
import java.util.HashSet
interface InjectionTargetsAnalyzer {
fun analyze(files: Collection<File>): Result
data class Result(
val injectableTargets: Collection<InjectionTarget>,
val providableTargets: Collection<InjectionTarget>
)
}
class InjectionTargetsAnalyzerImpl(
private val grip: Grip,
private val analyzerHelper: AnalyzerHelper,
private val errorReporter: ErrorReporter
) : InjectionTargetsAnalyzer {
private val logger = getLogger()
override fun analyze(files: Collection<File>): InjectionTargetsAnalyzer.Result {
val context = createInjectionTargetsContext(files)
val injectableTargets = analyzeInjectableTargets(context)
val providableTargets = analyzeProvidableTargets(context)
return InjectionTargetsAnalyzer.Result(injectableTargets, providableTargets)
}
private fun createInjectionTargetsContext(files: Collection<File>): InjectionTargetsContext {
val methodsQuery = grip select methods from files where annotatedWith(Types.INJECT_TYPE)
val fieldsQuery = grip select fields from files where annotatedWith(Types.INJECT_TYPE)
val methodsResult = methodsQuery.execute()
val fieldsResult = fieldsQuery.execute()
val types = HashSet<Type.Object>(methodsResult.size + fieldsResult.size).apply {
addAll(methodsResult.types)
addAll(fieldsResult.types)
}
return InjectionTargetsContext(types, methodsResult, fieldsResult)
}
private fun analyzeInjectableTargets(context: InjectionTargetsContext): Collection<InjectionTarget> {
return context.types.mapNotNull { type ->
logger.debug("Target: {}", type)
val injectionPoints = ArrayList<InjectionPoint>()
context.methods[type]?.mapNotNullTo(injectionPoints) { method ->
logger.debug(" Method: {}", method)
given(!method.isConstructor) { analyzerHelper.convertToInjectionPoint(method, type) }
}
context.fields[type]?.mapTo(injectionPoints) { field ->
logger.debug(" Field: {}", field)
analyzerHelper.convertToInjectionPoint(field, type)
}
given(injectionPoints.isNotEmpty()) { InjectionTarget(type, injectionPoints) }
}
}
private fun analyzeProvidableTargets(context: InjectionTargetsContext): Collection<InjectionTarget> {
return context.types.mapNotNull { type ->
logger.debug("Target: {}", type)
val constructors = context.methods[type].orEmpty().mapNotNull { method ->
logger.debug(" Method: {}", method)
given(method.isConstructor) { analyzerHelper.convertToInjectionPoint(method, type) }
}
given(constructors.isNotEmpty()) {
if (constructors.size > 1) {
val separator = "\n "
val constructorsString = constructors.map { it.cast<InjectionPoint.Method>().method }.joinToString(separator)
errorReporter.reportError("Class has multiple injectable constructors:$separator$constructorsString")
}
InjectionTarget(type, constructors)
}
}
}
private class InjectionTargetsContext(
val types: Collection<Type.Object>,
val methods: MethodsResult,
val fields: FieldsResult
)
}
| apache-2.0 | c385bb1170a146bec1eca999b2ac4af9 | 36.958678 | 119 | 0.755933 | 4.611446 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/TokeiImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/tokeiimporter/strategy/TokeiTwelveStrategy.kt | 1 | 2140 | package de.maibornwolff.codecharta.importer.tokeiimporter.strategy
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import de.maibornwolff.codecharta.importer.tokeiimporter.analysisObject.AnalysisObjectTwelve
import de.maibornwolff.codecharta.importer.tokeiimporter.analysisObject.Report
import de.maibornwolff.codecharta.model.MutableNode
import de.maibornwolff.codecharta.model.PathFactory
import de.maibornwolff.codecharta.model.ProjectBuilder
class TokeiTwelveStrategy(rootName: String, pathSeparator: String) : ImporterStrategy {
override var rootName = ""
override var pathSeparator = ""
init {
this.rootName = rootName
this.pathSeparator = pathSeparator
}
override fun buildCCJson(languageSummaries: JsonObject, projectBuilder: ProjectBuilder) {
val gson = Gson()
for (languageEntry in languageSummaries.entrySet()) {
val languageAnalysisObject = gson.fromJson(languageEntry.value, AnalysisObjectTwelve::class.java)
if (languageAnalysisObject.hasChildren()) {
for (report in languageAnalysisObject.reports) {
addAsNode(report, projectBuilder)
}
}
}
}
override fun getLanguageSummaries(root: JsonElement): JsonObject {
return root.asJsonObject
}
private fun addAsNode(report: Report, projectBuilder: ProjectBuilder) {
val sanitizedName = report.name.removePrefix(rootName).replace(pathSeparator, "/")
val directory = sanitizedName.substringBeforeLast("/")
val fileName = sanitizedName.substringAfterLast("/")
val node = MutableNode(
fileName,
attributes = mapOf(
"empty_lines" to report.stats.blanks,
"rloc" to report.stats.code,
"comment_lines" to report.stats.comments,
"loc" to report.stats.blanks + report.stats.code + report.stats.comments
)
)
val path = PathFactory.fromFileSystemPath(directory)
projectBuilder.insertByPath(path, node)
}
}
| bsd-3-clause | ad2d93c75d2f0a8ef93ef7e1d98b0bf5 | 37.909091 | 109 | 0.68972 | 4.8307 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/QueueSpec.kt | 1 | 7853 | /*
* 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
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.q.Queue.Companion.maxRedeliveries
import com.netflix.spinnaker.orca.time.MutableClock
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.io.Closeable
import java.time.Duration
import java.time.Instant
abstract class QueueSpec<out Q : Queue>(
createQueue: ((Queue, Message) -> Unit) -> Q,
triggerRedeliveryCheck: Q.() -> Unit,
shutdownCallback: (() -> Unit)? = null
) : Spek({
var queue: Q? = null
val callback: QueueCallback = mock()
val deadLetterCallback: (Queue, Message) -> Unit = mock()
fun resetMocks() = reset(callback)
fun stopQueue() {
queue?.let { q ->
if (q is Closeable) {
q.close()
}
}
shutdownCallback?.invoke()
}
describe("polling the queue") {
context("there are no messages") {
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled") {
queue!!.poll(callback)
}
it("does not invoke the callback") {
verifyZeroInteractions(callback)
}
}
context("there is a single message") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled") {
queue!!.poll(callback)
}
it("passes the queued message to the callback") {
verify(callback).invoke(eq(message), any())
}
}
context("there are multiple messages") {
val message1 = StartExecution(Pipeline::class.java, "1", "foo")
val message2 = StartExecution(Pipeline::class.java, "2", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback).apply {
push(message1)
clock.incrementBy(Duration.ofSeconds(1))
push(message2)
}
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled twice") {
queue!!.apply {
poll(callback)
poll(callback)
}
}
it("passes the messages to the callback in the order they were queued") {
verify(callback).invoke(eq(message1), any())
verify(callback).invoke(eq(message2), any())
}
}
context("there is a delayed message") {
val delay = Duration.ofHours(1)
context("whose delay has not expired") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message, delay)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled") {
queue!!.poll(callback)
}
it("does not invoke the callback") {
verifyZeroInteractions(callback)
}
}
context("whose delay has expired") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message, delay)
clock.incrementBy(delay)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled") {
queue!!.poll(callback)
}
it("passes the message to the callback") {
verify(callback).invoke(eq(message), any())
}
}
}
}
describe("message redelivery") {
context("a message is acknowledged") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled and the message is acknowledged") {
queue!!.apply {
poll { _, ack ->
ack.invoke()
}
clock.incrementBy(ackTimeout)
triggerRedeliveryCheck()
poll(callback)
}
}
it("does not re-deliver the message") {
verifyZeroInteractions(callback)
}
}
context("a message is not acknowledged") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled then the message is not acknowledged") {
queue!!.apply {
poll { _, _ -> }
clock.incrementBy(ackTimeout)
triggerRedeliveryCheck()
poll(callback)
}
}
it("re-delivers the message") {
verify(callback).invoke(eq(message), any())
}
}
context("a message is not acknowledged more than once") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled and the message is not acknowledged") {
queue!!.apply {
repeat(2) {
poll { _, _ -> }
clock.incrementBy(ackTimeout)
triggerRedeliveryCheck()
}
poll(callback)
}
}
it("re-delivers the message") {
verify(callback).invoke(eq(message), any())
}
}
context("a message is not acknowledged more than $maxRedeliveries times") {
val message = StartExecution(Pipeline::class.java, "1", "foo")
beforeGroup {
queue = createQueue.invoke(deadLetterCallback)
queue!!.push(message)
}
afterGroup(::stopQueue)
afterGroup(::resetMocks)
action("the queue is polled and the message is not acknowledged") {
queue!!.apply {
repeat(maxRedeliveries) {
poll { _, _ -> }
clock.incrementBy(ackTimeout)
triggerRedeliveryCheck()
}
poll(callback)
}
}
it("stops re-delivering the message") {
verifyZeroInteractions(callback)
}
it("passes the failed message to the dead letter handler") {
verify(deadLetterCallback).invoke(queue!!, message)
}
context("once the message has been dead-lettered") {
action("the next time re-delivery checks happen") {
queue!!.apply {
triggerRedeliveryCheck()
poll(callback)
}
}
it("it does not get redelivered again") {
verifyZeroInteractions(callback)
}
it("no longer gets sent to the dead letter handler") {
verify(deadLetterCallback).invoke(queue!!, message)
}
}
}
}
}) {
companion object {
val clock = MutableClock(Instant.now())
}
}
| apache-2.0 | a95bb60ec22d090326624741bf6fd2e6 | 25.530405 | 79 | 0.599898 | 4.387151 | false | false | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/cargo/project/RustProjectSettingsServiceTest.kt | 1 | 1687 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project
import com.intellij.configurationStore.deserialize
import com.intellij.configurationStore.serialize
import com.intellij.testFramework.LightPlatformTestCase
import org.rust.cargo.project.settings.RustProjectSettingsService
import org.rust.cargo.project.settings.impl.RustProjectSettingsServiceImpl
import org.rust.cargo.toolchain.RustToolchain
import org.rust.openapiext.elementFromXmlString
import org.rust.openapiext.toXmlString
import java.nio.file.Paths
class RustProjectSettingsServiceTest : LightPlatformTestCase() {
fun `test serialization`() {
val service = RustProjectSettingsServiceImpl(LightPlatformTestCase.getProject())
val text = """
<State>
<option name="explicitPathToStdlib" value="/stdlib" />
<option name="toolchainHomeDirectory" value="/" />
<option name="useCargoCheckAnnotator" value="true" />
<option name="useCargoCheckForBuild" value="false" />
</State>
""".trimIndent()
service.loadState(elementFromXmlString(text).deserialize())
val actual = service.state.serialize()!!.toXmlString()
check(actual == text.trimIndent()) {
"Expected:\n$text\nActual:\n$actual"
}
check(service.data == RustProjectSettingsService.Data(
toolchain = RustToolchain(Paths.get("/")),
autoUpdateEnabled = true,
explicitPathToStdlib = "/stdlib",
useCargoCheckForBuild = false,
useCargoCheckAnnotator = true
))
}
}
| mit | 10e2512bdc5cc4e67ac64d548f87cbf6 | 37.340909 | 88 | 0.687018 | 4.847701 | false | true | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/app/res/Bitmaps.kt | 1 | 2819 | package cn.thens.kdroid.core.app.res
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.Drawable
@Suppress("unused")
object Bitmaps {
@JvmStatic
fun compress(resources: Resources, resId: Int, width: Int, height: Int): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, resId, options)
options.inSampleSize = computeInSampleSize(options.outWidth, options.outHeight, width, height)
options.inJustDecodeBounds = false
// Logdog.info("out = (${options.outWidth}, ${options.outHeight}), target = ($width, $height) inSampleSize = ${options.inSampleSize}")
return BitmapFactory.decodeResource(resources, resId, options)
}
private fun computeInSampleSize(outWidth: Int, outHeight: Int, targetWith: Int, targetHeight: Int): Int {
if (targetWith == 0 || targetHeight == 0) return 1
if (outWidth <= targetWith || outHeight <= targetHeight) return 1
val scaleSize = Math.min(1.0 * outWidth / targetWith, 1.0 * outHeight / targetHeight)
var inSampleSize = 1
while (scaleSize > inSampleSize) {
inSampleSize *= 2
}
return Math.max(inSampleSize, 1)
}
@JvmStatic
fun compress(drawable: Drawable, width: Int, height: Int): Bitmap {
val originalWidth = drawable.intrinsicWidth
val originalHeight = drawable.intrinsicHeight
val scaleSize = Math.min(1F * width / originalWidth, 1F * height / originalHeight)
val targetWidth = (scaleSize * originalWidth).toInt()
val targetHeight = (scaleSize * originalHeight).toInt()
val bitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888)
drawable.setBounds(0, 0, targetWidth, targetHeight)
drawable.draw(Canvas(bitmap))
return bitmap
}
@JvmStatic
fun from(drawable: Drawable): Bitmap {
val w = drawable.intrinsicWidth
val h = drawable.intrinsicHeight
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, w, h)
drawable.draw(canvas)
return bitmap
}
@JvmStatic
fun zoom(bitmap: Bitmap, width: Int, height: Int): Bitmap {
val w = bitmap.width
val h = bitmap.height
val matrix = Matrix()
val scaleWidth = width.toFloat() / w
val scaleHeight = height.toFloat() / h
val scaleSize = Math.min(scaleWidth, scaleHeight)
matrix.postScale(scaleSize, scaleSize)
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true)
}
} | apache-2.0 | e33af137d03f0ea8fa4be5ec39a04aea | 39.285714 | 141 | 0.670451 | 4.481717 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionHolder.kt | 1 | 3321 | package eu.kanade.tachiyomi.ui.browse.extension
import android.view.View
import androidx.core.view.isVisible
import coil.clear
import coil.load
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.databinding.ExtensionItemBinding
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.InstallStep
import eu.kanade.tachiyomi.util.system.LocaleHelper
class ExtensionHolder(view: View, val adapter: ExtensionAdapter) :
FlexibleViewHolder(view, adapter) {
private val binding = ExtensionItemBinding.bind(view)
init {
binding.extButton.setOnClickListener {
adapter.buttonClickListener.onButtonClick(bindingAdapterPosition)
}
binding.cancelButton.setOnClickListener {
adapter.buttonClickListener.onCancelButtonClick(bindingAdapterPosition)
}
}
fun bind(item: ExtensionItem) {
val extension = item.extension
binding.name.text = extension.name
binding.version.text = extension.versionName
binding.lang.text = LocaleHelper.getSourceDisplayName(extension.lang, itemView.context)
binding.warning.text = when {
extension is Extension.Untrusted -> itemView.context.getString(R.string.ext_untrusted)
extension is Extension.Installed && extension.isUnofficial -> itemView.context.getString(R.string.ext_unofficial)
extension is Extension.Installed && extension.isObsolete -> itemView.context.getString(R.string.ext_obsolete)
extension.isNsfw -> itemView.context.getString(R.string.ext_nsfw_short)
else -> ""
}.uppercase()
binding.icon.clear()
if (extension is Extension.Available) {
binding.icon.load(extension.iconUrl)
} else {
extension.getApplicationIcon(itemView.context)?.let { binding.icon.setImageDrawable(it) }
}
bindButtons(item)
}
@Suppress("ResourceType")
fun bindButtons(item: ExtensionItem) = with(binding.extButton) {
val extension = item.extension
val installStep = item.installStep
setText(
when (installStep) {
InstallStep.Pending -> R.string.ext_pending
InstallStep.Downloading -> R.string.ext_downloading
InstallStep.Installing -> R.string.ext_installing
InstallStep.Installed -> R.string.ext_installed
InstallStep.Error -> R.string.action_retry
InstallStep.Idle -> {
when (extension) {
is Extension.Installed -> {
if (extension.hasUpdate) {
R.string.ext_update
} else {
R.string.action_settings
}
}
is Extension.Untrusted -> R.string.ext_trust
is Extension.Available -> R.string.ext_install
}
}
}
)
val isIdle = installStep == InstallStep.Idle || installStep == InstallStep.Error
binding.cancelButton.isVisible = !isIdle
isEnabled = isIdle
isClickable = isIdle
}
}
| apache-2.0 | becfa0db36a3f02306360c0ba04b9e37 | 38.535714 | 125 | 0.623908 | 5.031818 | false | false | false | false |
kory33/SignVote | src/main/kotlin/com/github/kory33/signvote/vote/VoteLimit.kt | 1 | 2237 | package com.github.kory33.signvote.vote
import com.github.kory33.signvote.exception.data.InvalidLimitDataException
import com.google.gson.JsonObject
import org.bukkit.entity.Player
/**
* A class that represents a limit of vote counts
*/
data class VoteLimit
constructor(val score: VoteScore, val limit: Limit, private val permission: String?) {
constructor(score: VoteScore, limit: Limit) : this(score, limit, null)
/**
* Returns if the limit applies to the given player
* @param player player to be inspected
* *
* @return true if the player has permissions associated to this vote-limit
*/
fun isApplicable(player: Player): Boolean {
return this.permission == null || player.hasPermission(this.permission)
}
fun toJsonObject(): JsonObject {
val jsonObject = JsonObject()
jsonObject.addProperty(JSON_SCORE_KEY, this.score.toInt())
jsonObject.addProperty(JSON_LIMIT_KEY, this.limit.toString())
jsonObject.addProperty(JSON_PERMS_KEY, this.permission)
return jsonObject
}
companion object {
/** Json keys */
private val JSON_SCORE_KEY = "score"
private val JSON_LIMIT_KEY = "limit"
private val JSON_PERMS_KEY = "permission"
/**
* Construct a VoteLimit object from a json object
* @param jsonObject object to be converted to a VoteLimit
* *
* @return converted object
* *
* @throws InvalidLimitDataException when the given jsonObject is invalid
*/
@Throws(InvalidLimitDataException::class)
fun fromJsonObject(jsonObject: JsonObject): VoteLimit {
val scoreElement = jsonObject.get(JSON_SCORE_KEY)
val limitElement = jsonObject.get(JSON_LIMIT_KEY)
val permissionElement = jsonObject.get(JSON_PERMS_KEY)
val score = VoteScore(scoreElement.asInt)
val limit = Limit.fromString(limitElement.asString)
if (permissionElement.isJsonNull) {
return VoteLimit(score, limit)
}
val permissionString = permissionElement.asString
return VoteLimit(score, limit, permissionString)
}
}
}
| gpl-3.0 | d9dc1f754423857099983a6c8f433c93 | 32.893939 | 86 | 0.654001 | 4.574642 | false | false | false | false |
google/ksp | integration-tests/src/test/resources/kmp/test-processor/src/main/kotlin/ValidateProcessor.kt | 1 | 1061 | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.validate
class ValidateProcessor(val codeGenerator: CodeGenerator, val logger: KSPLogger) : SymbolProcessor {
var invoked = false
override fun process(resolver: Resolver): List<KSAnnotated> {
if (invoked) {
return emptyList()
}
invoked = true
val toValidate = resolver.getSymbolsWithAnnotation("com.example.MyAnnotation")
if (toValidate.firstOrNull() == null || !toValidate.all { it.validate() }) {
logger.error("$toValidate.validate(): not ok")
}
if ((toValidate as? KSClassDeclaration)?.asStarProjectedType()?.isError == true) {
logger.error("$toValidate.asStarProjectedType(): not ok")
}
return emptyList()
}
}
class ValidateProcessorProvider : SymbolProcessorProvider {
override fun create(env: SymbolProcessorEnvironment): SymbolProcessor {
return ValidateProcessor(env.codeGenerator, env.logger)
}
}
| apache-2.0 | b2d3ea5ee55105cb2e08d791c6f2938d | 35.586207 | 100 | 0.678605 | 4.779279 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/ui/vnsummary/SummaryFragment.kt | 1 | 6409 | package com.booboot.vndbandroid.ui.vnsummary
import android.content.res.ColorStateList
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.util.TypedValue
import android.view.View
import androidx.asynclayoutinflater.view.AsyncLayoutInflater
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.extensions.observeNonNull
import com.booboot.vndbandroid.extensions.observeOnce
import com.booboot.vndbandroid.extensions.openURL
import com.booboot.vndbandroid.extensions.scrollToTop
import com.booboot.vndbandroid.extensions.setPadding
import com.booboot.vndbandroid.extensions.startParentEnterTransition
import com.booboot.vndbandroid.extensions.toggle
import com.booboot.vndbandroid.extensions.toggleText
import com.booboot.vndbandroid.model.vndb.Links
import com.booboot.vndbandroid.model.vndbandroid.LANGUAGES
import com.booboot.vndbandroid.model.vndbandroid.PLATFORMS
import com.booboot.vndbandroid.model.vndbandroid.Vote
import com.booboot.vndbandroid.ui.base.BaseFragment
import com.booboot.vndbandroid.ui.vndetails.VNDetailsFragment
import com.booboot.vndbandroid.util.Utils
import com.google.android.material.chip.Chip
import kotlinx.android.synthetic.main.info_bubble.view.*
import kotlinx.android.synthetic.main.platform_tag.view.*
import kotlinx.android.synthetic.main.summary_fragment.*
class SummaryFragment : BaseFragment<SummaryViewModel>() {
override val layout = R.layout.summary_fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (activity == null) return
val vnId = arguments?.getLong(VNDetailsFragment.EXTRA_VN_ID) ?: 0
viewModel = ViewModelProvider(this).get(SummaryViewModel::class.java)
viewModel.summaryData.observeNonNull(this, ::showVn)
viewModel.loadingData.observeNonNull(this) { vnDetailsFragment()?.showLoading(it) }
viewModel.errorData.observeOnce(this, ::showError)
viewModel.loadVn(vnId, false)
}
private fun showVn(summaryVN: SummaryVN) {
context?.let { ctx ->
val vn = summaryVN.vn
title.text = vn.title
originalTitle.text = vn.original
originalTitle.toggle(vn.original?.isNotEmpty() == true)
aliases.text = vn.aliases
aliases.toggle(vn.aliases?.isNotEmpty() == true)
description.movementMethod = LinkMovementMethod.getInstance()
description.text = summaryVN.description
description.toggle(description.text.isNotEmpty())
val asyncInflater = AsyncLayoutInflater(ctx)
platforms.removeAllViews()
vn.platforms.forEach {
asyncInflater.inflate(R.layout.platform_tag, platforms) { view, _, _ ->
context?.let { ctx ->
val platform = PLATFORMS[it] ?: return@inflate
view.tagText.text = platform.text
view.tagText.setTextColor(platform.textColor(ctx))
view.tagText.setBackgroundColor(platform.backgroundColor(ctx))
platforms?.addView(view)
}
}
}
languages.removeAllViews()
vn.languages.forEach {
asyncInflater.inflate(R.layout.language_tag, languages) { view, _, _ ->
context?.let { ctx ->
val language = LANGUAGES[it] ?: return@inflate
val chip = view as Chip
chip.chipIcon = VectorDrawableCompat.create(ctx.resources, language.flag, ctx.theme)
chip.setPadding()
chip.setOnClickListener { chip.toggleText(language.text) }
languages?.addView(chip)
}
}
}
val white = ContextCompat.getColor(ctx, R.color.white)
length.apply {
icon.setImageResource(R.drawable.ic_access_time_black_48dp)
title.text = vn.lengthString()
value.text = vn.lengthInHours()
value.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
}
released.apply {
icon.setImageResource(R.drawable.ic_event_black_48dp)
title.setText(R.string.released_on)
value.text = Utils.formatDateMedium(context, vn.released)
value.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
}
with(popularity) {
this as CardView
setCardBackgroundColor(ContextCompat.getColor(context, vn.popularityColor()))
icon.setImageResource(R.drawable.ic_whatshot_black_48dp)
title.setText(R.string.popularity)
value.text = String.format(getString(R.string.percent), vn.popularity)
icon.imageTintList = ColorStateList.valueOf(white)
title.setTextColor(white)
value.setTextColor(white)
}
rating.apply {
this as CardView
setCardBackgroundColor(ContextCompat.getColor(context, Vote.getColor(vn.rating)))
icon.setImageResource(R.drawable.ic_trending_up_black_48dp)
title.text = String.format(getString(R.string.x_votes), vn.votecount)
value.text = String.format("%.2f", vn.rating)
icon.imageTintList = ColorStateList.valueOf(white)
title.setTextColor(white)
value.setTextColor(white)
}
wikipediaButton.toggle(vn.links.wikipedia?.isNotEmpty() == true)
renaiButton.toggle(vn.links.renai?.isNotEmpty() == true)
encubedButton.toggle(vn.links.encubed?.isNotEmpty() == true)
wikipediaButton.setOnClickListener { ctx.openURL(Links.WIKIPEDIA + vn.links.wikipedia) }
renaiButton.setOnClickListener { ctx.openURL(Links.RENAI + vn.links.renai) }
encubedButton.setOnClickListener { ctx.openURL(Links.ENCUBED + vn.links.encubed) }
startParentEnterTransition()
}
}
override fun scrollToTop() {
scrollView.scrollToTop()
}
} | gpl-3.0 | b050103ba9230c810af559a81ccf24a4 | 45.449275 | 108 | 0.65174 | 4.688369 | false | false | false | false |
googlecodelabs/slices-basic-codelab | complete/src/main/java/com/example/android/slicesbasiccodelab/MainActivity.kt | 1 | 5698 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.slicesbasiccodelab
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
/**
* Displays the current temperature and allows user to adjust it up and down. Any adjustments from
* the external slice will also change this temperature value.
*/
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var temperatureTextView: TextView
private lateinit var sliceViewerPackageName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
temperatureTextView = findViewById(R.id.temperature)
// Used for launching external app to preview Slice.
sliceViewerPackageName = getString(R.string.slice_viewer_application_package_name)
findViewById<Button>(R.id.increase_temp).setOnClickListener(this)
findViewById<Button>(R.id.decrease_temp).setOnClickListener(this)
findViewById<Button>(R.id.launch_slice_viewer_application).setOnClickListener(this)
}
public override fun onResume() {
super.onResume()
temperatureTextView.text = getTemperatureString(applicationContext)
}
override fun onClick(view: View) {
when (view.id) {
R.id.increase_temp -> updateTemperature(applicationContext, temperature + 1)
R.id.decrease_temp -> updateTemperature(applicationContext, temperature - 1)
R.id.launch_slice_viewer_application -> launchSliceViewerApplication()
else -> return
}
temperatureTextView.text = getTemperatureString(applicationContext)
}
private fun launchSliceViewerApplication() {
if (isSliceViewerApplicationInstalled() && isSliceViewerApplicationEnabled()) {
val uri = getString(R.string.uri_specific_for_slice_viewer_application)
val sliceViewerIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
startActivity(sliceViewerIntent)
}
}
private fun isSliceViewerApplicationInstalled(): Boolean {
val packageManager = applicationContext.packageManager
try {
packageManager.getPackageInfo(sliceViewerPackageName, PackageManager.GET_ACTIVITIES)
return true
} catch (ignored: PackageManager.NameNotFoundException) {
val notInstalledToast = Toast.makeText(
applicationContext,
getString(R.string.slice_viewer_application_not_installed),
Toast.LENGTH_LONG)
notInstalledToast.show()
Log.e(TAG, getString(R.string.error_message_slice_viewer_APK_missing))
}
return false
}
private fun isSliceViewerApplicationEnabled(): Boolean {
var status = false
try {
val applicationInfo =
applicationContext.packageManager.getApplicationInfo(sliceViewerPackageName, 0)
if (applicationInfo != null) {
status = applicationInfo.enabled
}
} catch (ignored: PackageManager.NameNotFoundException) {
val notEnabledToast = Toast.makeText(
applicationContext,
getString(R.string.slice_viewer_application_not_enabled),
Toast.LENGTH_LONG)
notEnabledToast.show()
Log.e(TAG, getString(R.string.error_message_slice_viewer_APK_disabled))
}
return status
}
companion object {
private const val TAG = "MainActivity"
/* Temperature is in Celsius.
*
* NOTE: You should store your data in a more permanent way that doesn't disappear when the
* app is killed. This drastically simplified sample is focused on learning Slices.
*/
private var temperature = 16
fun getTemperatureString(context: Context): String {
return context.getString(R.string.temperature, temperature)
}
fun getTemperature(): Int {
return temperature
}
fun updateTemperature(context: Context, newTemperature: Int) {
Log.d(TAG, "updateTemperature(): $newTemperature")
// TODO: Step 2.2, Notify TemperatureSliceProvider the temperature changed.
if (temperature != newTemperature) {
temperature = newTemperature
// Notify slice via URI that the temperature has changed so they can update views.
// NOTE: TemperatureSliceProvider inherits from ContentProvider, so we are
// actually assigning a ContentProvider to this authority (URI).
val uri = TemperatureSliceProvider.getUri(context, "temperature")
context.contentResolver.notifyChange(uri, null)
}
}
}
}
| apache-2.0 | a2d860073a1dd58251d4f3f493d663ce | 34.391304 | 99 | 0.675325 | 5.042478 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/util/ToDoExtensions.kt | 1 | 845 | package com.airbnb.mvrx.todomvrx.util
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.snackbar.Snackbar
fun <T> List<T>.upsert(value: T, finder: (T) -> Boolean) = indexOfFirst(finder).let { index ->
if (index >= 0) copy(index, value) else this + value
}
fun <T> List<T>.copy(i: Int, value: T): List<T> = toMutableList().apply { set(i, value) }
inline fun <T> List<T>.delete(filter: (T) -> Boolean): List<T> = toMutableList().apply { removeAt(indexOfFirst(filter)) }
fun CoordinatorLayout.showLongSnackbar(@StringRes stringRes: Int) {
Snackbar.make(this, stringRes, Snackbar.LENGTH_LONG).show()
}
fun ViewGroup.asSequence(): Sequence<View> = (0..childCount).asSequence().map { getChildAt(it) }
| apache-2.0 | 3a9aeb627301f2399d25930d232ab1a9 | 39.238095 | 121 | 0.734911 | 3.506224 | false | false | false | false |
letroll/githubbookmarkmanager | app/src/main/kotlin/fr/letroll/githubbookmarkmanager/data/model/Owner.kt | 1 | 891 | package fr.letroll.githubbookmarkmanager.data.model
/**
* Created by jquievreux on 01/12/14.
*/
data class Owner {
private var login: String = ""
private var id: kotlin.Int = -1
private var avatarUrl: String = ""
private var gravatarId: String = ""
private var url: String = ""
private var htmlUrl: String = ""
private var followersUrl: String = ""
private var followingUrl: String = ""
private var gistsUrl: String = ""
private var starredUrl: String = ""
private var subscriptionsUrl: String = ""
private var organizationsUrl: String = ""
private var reposUrl: String = ""
private var eventsUrl: String = ""
private var receivedEventsUrl: String = ""
private var type: String = ""
private var siteAdmin: Boolean = false
// private var additionalProperties: Map<String, kotlin> = HashMap<String, kotlin.Any>()
} | apache-2.0 | 7a82a5d8dd80bfc68035a6ffe8b68568 | 33.307692 | 95 | 0.665544 | 4.144186 | false | false | false | false |
Tunous/SwipeActionView | library/src/main/kotlin/me/thanel/swipeactionview/SwipeRippleDrawable.kt | 1 | 3044 | /*
* Copyright © 2016-2018 Łukasz Rutkowski
*
* 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.thanel.swipeactionview
import android.animation.ObjectAnimator
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.util.Property
import androidx.annotation.ColorInt
internal class SwipeRippleDrawable : Drawable(), Animatable {
companion object {
private val PROGRESS =
object : Property<SwipeRippleDrawable, Float>(Float::class.java, "progress") {
override fun get(drawable: SwipeRippleDrawable) = drawable.progress
override fun set(drawable: SwipeRippleDrawable, value: Float) {
drawable.progress = value
drawable.invalidateSelf()
}
}
}
private val animator = ObjectAnimator.ofFloat(this, PROGRESS, 0f, 1f)
private val drawBounds = Rect()
private val paint = Paint()
private var centerX = 0f
private var centerY = 0f
internal var progress = 0f
fun restart() {
stop()
start()
}
fun setCenter(x: Float, y: Float) {
centerX = x
centerY = y
invalidateSelf()
}
val hasColor: Boolean
get() = color != -1
var maxRadius = 0f
set(value) {
field = value
invalidateSelf()
}
var color: Int
@ColorInt get() = paint.color
set(@ColorInt value) {
paint.color = value
invalidateSelf()
}
var duration: Long
get() = animator.duration
set(value) {
animator.duration = value
}
override fun draw(canvas: Canvas) {
paint.alpha = ((1f - progress) * 255f).toInt()
val saveCount = canvas.save()
canvas.clipRect(drawBounds)
canvas.drawCircle(centerX, centerY, maxRadius * progress, paint)
canvas.restoreToCount(saveCount)
}
override fun isRunning() = animator.isRunning
override fun start() = animator.start()
override fun stop() = animator.cancel()
override fun onBoundsChange(bounds: Rect) {
drawBounds.set(bounds)
}
override fun getOpacity() = PixelFormat.OPAQUE
override fun setColorFilter(colorFilter: ColorFilter?) {
}
override fun setAlpha(value: Int) {
}
}
| apache-2.0 | 1e9e12766e6ae3243991a8ac5ecea025 | 26.654545 | 90 | 0.647929 | 4.588235 | false | false | false | false |
msebire/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/KindsResolverProcessor.kt | 1 | 2108 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import com.intellij.util.enumMapOf
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.util.elementInfo
import org.jetbrains.plugins.groovy.lang.resolve.*
open class KindsResolverProcessor(
protected val name: String,
protected val place: PsiElement,
protected val kinds: Set<GroovyResolveKind>
) : ProcessorWithHints(),
NameHint,
GroovyResolveKind.Hint {
init {
@Suppress("LeakingThis") hint(NameHint.KEY, this)
@Suppress("LeakingThis") hint(GroovyResolveKind.HINT_KEY, this)
}
final override fun getName(state: ResolveState): String? = name
final override fun shouldProcess(kind: GroovyResolveKind): Boolean = kind in kinds
private val candidates = enumMapOf<GroovyResolveKind, GroovyResolveResult>()
final override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (element !is PsiNamedElement) return true
require(element.isValid) {
"Invalid element. ${elementInfo(element)}"
}
val elementName = getName(state, element)
if (name != elementName) return true
val kind = getResolveKind(element)
if (kind == null) {
log.warn("Unknown kind. ${elementInfo(element)}")
}
else if (kind !in kinds) {
if (state[sorryCannotKnowElementKind] != true) {
log.error("Unneeded kind: $kind. ${elementInfo(element)}")
}
}
else if (kind !in candidates) {
candidates[kind] = BaseGroovyResolveResult(element, place, state)
}
return true
}
fun getCandidate(kind: GroovyResolveKind): GroovyResolveResult? = candidates[kind]
fun getAllCandidates(): List<GroovyResolveResult> = candidates.values.toList()
}
| apache-2.0 | 44d3a99ce139a211c519dde2253508cd | 34.133333 | 140 | 0.740512 | 4.302041 | false | false | false | false |
rock3r/detekt | detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/MaximumLineLength.kt | 1 | 1401 | package io.gitlab.arturbosch.detekt.formatting.wrappers
import com.pinterest.ktlint.core.EditorConfig
import com.pinterest.ktlint.ruleset.standard.MaxLineLengthRule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.formatting.ANDROID_MAX_LINE_LENGTH
import io.gitlab.arturbosch.detekt.formatting.DEFAULT_IDEA_LINE_LENGTH
import io.gitlab.arturbosch.detekt.formatting.FormattingRule
import io.gitlab.arturbosch.detekt.formatting.merge
/**
* See <a href="https://ktlint.github.io">ktlint-website</a> for documentation.
*
* @configuration maxLineLength - maximum line length (default: `120`)
*
* @active since v1.0.0
*/
class MaximumLineLength(config: Config) : FormattingRule(config) {
override val wrapping = MaxLineLengthRule()
override val issue = issueFor("Reports lines with exceeded length")
override val defaultRuleIdAliases: Set<String>
get() = setOf("MaxLineLength")
private val defaultMaxLineLength =
if (isAndroid) ANDROID_MAX_LINE_LENGTH
else DEFAULT_IDEA_LINE_LENGTH
private val maxLineLength: Int = valueOrDefault(MAX_LINE_LENGTH, defaultMaxLineLength)
override fun editorConfigUpdater(): ((oldEditorConfig: EditorConfig?) -> EditorConfig)? = {
EditorConfig.merge(it, maxLineLength = maxLineLength)
}
companion object {
const val MAX_LINE_LENGTH = "maxLineLength"
}
}
| apache-2.0 | 002fb1bc9ac2e0407b03d0362bffa863 | 34.923077 | 95 | 0.753747 | 4.310769 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/update_tags/StringMapChanges.kt | 1 | 2346 | package de.westnordost.streetcomplete.data.osm.edits.update_tags
import kotlinx.serialization.Serializable
/** A diff that can be applied on a map of strings. Use StringMapChangesBuilder to conveniently build
* it. A StringMapChanges is immutable. */
@Serializable
class StringMapChanges(val changes: Collection<StringMapEntryChange>) {
fun isEmpty() = changes.isEmpty()
/** @return a StringMapChanges that exactly reverses this StringMapChanges */
fun reversed() = StringMapChanges(changes.map { it.reversed() })
/** Return whether the changes have a conflict with the given map */
fun hasConflictsTo(map: Map<String, String>) = ConflictIterator(map).hasNext()
/** Return an iterable to iterate through the changes that have conflicts with the given map */
fun getConflictsTo(map: Map<String, String>) = object : Iterable<StringMapEntryChange> {
override fun iterator() = ConflictIterator(map)
}
/** Applies this diff to the given map. */
fun applyTo(map: MutableMap<String, String>) {
check(!hasConflictsTo(map)) { "Could not apply the diff, there is at least one conflict." }
for (change in changes) {
change.applyTo(map)
}
}
override fun equals(other: Any?) = changes == (other as? StringMapChanges)?.changes
override fun hashCode() = changes.hashCode()
override fun toString() = changes.joinToString()
private inner class ConflictIterator(private val map: Map<String, String>) : Iterator<StringMapEntryChange> {
private var next: StringMapEntryChange? = null
private val it = changes.iterator()
override fun hasNext(): Boolean {
findNext()
return next != null
}
override fun next(): StringMapEntryChange {
findNext()
val result = next
next = null
if (result == null) {
throw NoSuchElementException()
}
return result
}
private fun findNext() {
if (next == null) {
while (it.hasNext()) {
val change = it.next()
if (change.conflictsWith(map)) {
next = change
return
}
}
}
}
}
}
| gpl-3.0 | cf77f7cfc12127c67a7a4826831bc95e | 34.014925 | 113 | 0.603154 | 4.938947 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json-tests/commonTest/src/kotlinx/serialization/json/polymorphic/JsonPolymorphicObjectTest.kt | 1 | 1171 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json.polymorphic
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.test.*
class JsonPolymorphicObjectTest : JsonTestBase() {
@Serializable
data class Holder(@Polymorphic val a: Any)
@Serializable
@SerialName("MyObject")
object MyObject {
@Suppress("unused")
val unused = 42
}
val json = Json {
serializersModule = SerializersModule {
polymorphic(Any::class) {
subclass(MyObject::class, MyObject.serializer()) // JS bug workaround
}
}
}
@Test
fun testRegularPolymorphism() {
assertJsonFormAndRestored(Holder.serializer(), Holder(MyObject), """{"a":{"type":"MyObject"}}""", json)
}
@Test
fun testArrayPolymorphism() {
val json = Json(from = json) {
useArrayPolymorphism = true
}
assertJsonFormAndRestored(Holder.serializer(), Holder(MyObject), """{"a":["MyObject",{}]}""", json)
}
}
| apache-2.0 | 56fbcb3b14a4e5914831bb3129965e89 | 25.613636 | 111 | 0.631939 | 4.665339 | false | true | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/util/ImageBinPoster.kt | 5 | 1732 | package com.github.pockethub.android.util
import android.content.Context
import android.net.Uri
import io.reactivex.Single
import okhttp3.*
import okio.Okio
import java.io.IOException
object ImageBinPoster {
private val client = OkHttpClient()
/**
* Post the image to ImageBin
*
* @param context A context
* @param uri The content URI
* @return Single containing the network Response
*/
@JvmStatic
fun post(context: Context, uri: Uri): Single<Response> {
var bytes: ByteArray? = null
try {
val stream = context.contentResolver.openInputStream(uri)
if (stream != null) {
val source = Okio.source(stream)
bytes = Okio.buffer(source).readByteArray()
}
} catch (e: IOException) {
return Single.error(e)
}
return post(bytes)
}
/**
* Post the image to ImageBin
*
* @param bytes Bytes of the image to post
* @return Single containing the network Response
*/
@JvmStatic
fun post(bytes: ByteArray?): Single<Response> {
val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes!!))
.build()
val request = Request.Builder()
.url("https://imagebin.ca/upload.php")
.post(requestBody)
.build()
return Single.fromCallable { client.newCall(request).execute() }
}
@JvmStatic
fun getUrl(body: String): String? {
return body.split("\n").last { it.startsWith("url") }.substringAfter(':')
}
}
| apache-2.0 | 228188d962daebffd83f42b3ddc190a1 | 26.492063 | 105 | 0.588337 | 4.534031 | false | false | false | false |
jcam3ron/cassandra-migration | src/test/java/com/builtamont/cassandra/migration/internal/resolver/CompositeMigrationResolverSpec.kt | 1 | 5221 | /**
* File : CompositeMigrationResolverSpec.kt
* License :
* Original - Copyright (c) 2015 - 2016 Contrast Security
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* 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.builtamont.cassandra.migration.internal.resolver
import com.builtamont.cassandra.migration.api.CassandraMigrationException
import com.builtamont.cassandra.migration.api.MigrationType
import com.builtamont.cassandra.migration.api.MigrationVersion
import com.builtamont.cassandra.migration.api.resolver.MigrationResolver
import com.builtamont.cassandra.migration.api.resolver.ResolvedMigration
import com.builtamont.cassandra.migration.internal.util.Locations
import io.kotlintest.matchers.have
import io.kotlintest.specs.FreeSpec
/**
* CompositeMigrationResolverSpec unit tests.
*/
class CompositeMigrationResolverSpec : FreeSpec() {
/**
* Creates a resolved migration for testing.
*
* @param type The migration type.
* @param version The resolved migration version.
* @param description The description.
* @param script The migration script.
* @param checksum The migration script checksum.
* @return Resolved migration.
*/
fun createResolvedMigration(type: MigrationType, version: String, description: String, script: String, checksum: Int): ResolvedMigration {
val migration = ResolvedMigrationImpl()
migration.type = type
migration.version = MigrationVersion.fromVersion(version)
migration.description = description
migration.script = script
migration.checksum = checksum
return migration
}
init {
"CompositeMigrationResolver" - {
"should resolve migrations in multiple locations" {
val resolver = CompositeMigrationResolver(
Thread.currentThread().contextClassLoader,
Locations("migration/subdir/dir2", "migration.outoforder", "migration/subdir/dir1"),
"UTF-8"
)
val migrations = resolver.resolveMigrations()
migrations.size shouldBe 3
migrations[0].description shouldBe "First"
migrations[1].description shouldBe "Late arrival"
migrations[2].description shouldBe "Add contents table"
}
"should collect migrations and eliminate duplicates" {
val resolver = object : MigrationResolver {
override fun resolveMigrations(): List<ResolvedMigration> {
return arrayListOf(
createResolvedMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123),
createResolvedMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123),
createResolvedMigration(MigrationType.CQL, "2", "Description2", "Migration2", 1234)
)
}
}
val resolvers = arrayListOf(resolver)
val migrations = CompositeMigrationResolver.collectMigrations(resolvers)
migrations.size shouldBe 2
}
"should check for incompatibilities provided no conflict" {
val migrations = arrayListOf(
createResolvedMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123),
createResolvedMigration(MigrationType.CQL, "2", "Description2", "Migration2", 1234)
)
CompositeMigrationResolver.checkForIncompatibilities(migrations)
}
"should check for incompatibilities error message in conflicted migrations" {
val migration1 = createResolvedMigration(MigrationType.CQL, "1", "First", "V1__First.cql", 123)
migration1.physicalLocation = "target/test-classes/migration/validate/V1__First.cql"
val migration2 = createResolvedMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123)
migration2.physicalLocation = "Migration1"
val migrations = arrayListOf(migration1, migration2)
try {
CompositeMigrationResolver.checkForIncompatibilities(migrations)
} catch (e: CassandraMigrationException) {
e.message!! should have substring "target/test-classes/migration/validate/V1__First.cql"
e.message!! should have substring "Migration1"
}
}
}
}
}
| apache-2.0 | 7aecab56c37e09f1d88f391f795584e9 | 42.87395 | 142 | 0.643555 | 5.128684 | false | true | false | false |
aucd29/common | library/src/main/java/net/sarangnamu/common/arch/adapter/BkAdapter.kt | 1 | 5766 | /*
* Copyright 2016 Burke Choi All rights reserved.
* http://www.sarangnamu.net
*
* 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 net.sarangnamu.common.arch.adapter
import android.arch.lifecycle.ViewModel
import android.content.Context
import android.databinding.ViewDataBinding
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.slf4j.LoggerFactory
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/>
*/
interface IBkItem {
fun type() : Int
}
interface BkContentDiffCallback {
fun diffContent(oldItem: Any?, newItem: Any?): Boolean
}
class BkViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var binding: ViewDataBinding
}
class BkAdapter<I> : RecyclerView.Adapter<BkViewHolder> {
companion object {
private val log = LoggerFactory.getLogger(BkAdapter::class.java)
protected fun bindClassName(context: Context, layoutId: String): String {
val sb = StringBuilder()
sb.append(context.packageName)
sb.append(".databinding.")
sb.append(Character.toUpperCase(layoutId[0]))
var i = 1
while (i < layoutId.length) {
var c = layoutId[i]
if (c == '_') {
c = layoutId[++i]
sb.append(Character.toUpperCase(c))
} else {
sb.append(c)
}
}
sb.append("Binding")
return sb.toString()
}
protected fun invokeMethod(binding: ViewDataBinding, methodName: String, argType: Class<Any>, argVal: Any, logmsg: Boolean) {
try {
val method = binding.javaClass.getDeclaredMethod(methodName, argType)
method.invoke(binding, argVal)
} catch (e: Exception) {
if (logmsg) {
if (log.isDebugEnabled) {
log.debug("NOT FOUND : ${e.message}")
}
}
}
}
}
private lateinit var layoutIds: Array<String>
var items: List<I>? = null
var vmodel: ViewModel? = null
var diffCallback: BkContentDiffCallback? = null
constructor(layoutId : String) {
layoutIds = arrayOf(layoutId)
}
constructor(layoutIds: Array<String>) {
this.layoutIds = layoutIds
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BkViewHolder? {
val context = parent.context
val layoutId = context.resources.getIdentifier(layoutIds[viewType], "layout", context.packageName)
val view = LayoutInflater.from(context).inflate(layoutId, parent, false)
if (log.isTraceEnabled()) {
log.trace(String.format("LAYOUT ID : %s (%d)", layoutIds[viewType], layoutId))
}
try {
val classPath = bindClassName(context, layoutIds[viewType])
if (log.isTraceEnabled()) {
log.trace("BINDING CLASS : $classPath")
}
val bindingClass = Class.forName(classPath)
val method = bindingClass.getDeclaredMethod("bind", View::class.java)
val vh = BkViewHolder(view)
vh.binding = method.invoke(null, view) as ViewDataBinding
return vh
} catch (e: Exception) {
e.printStackTrace()
log.error("ERROR: ${e.message}")
return null
}
}
override fun onBindViewHolder(holder: BkViewHolder?, position: Int) {
holder?.let { h ->
vmodel?.let { invokeMethod(h.binding, "setModel", it.javaClass, it, false) }
items?.let { invokeMethod(h.binding, "setItem", it.javaClass, it, false) }
}
}
override fun getItemCount(): Int = items?.size ?: 0
override fun getItemViewType(position: Int): Int {
if (items == null) {
return 0
}
val item = items!!.get(position)
return if (item is IBkItem) item.type() else 0
}
fun changeItems(newItems: ArrayList<I>) {
if (this.items == null) {
this.items = newItems
notifyItemRangeInserted(0, newItems.size)
return
}
if (diffCallback != null) {
val diffRes = DiffUtil.calculateDiff(object: DiffUtil.Callback() {
override fun getOldListSize(): Int = items!!.size
override fun getNewListSize(): Int = newItems.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
items!!.get(oldItemPosition) == newItems.get(newItemPosition)
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return diffCallback!!.diffContent(items!!.get(oldItemPosition), newItems.get(newItemPosition))
}
})
this.items = newItems
diffRes.dispatchUpdatesTo(this)
} else {
this.items = newItems
}
}
}
| apache-2.0 | 680c4e1c0f2468cea70f15928ad0df89 | 31.761364 | 133 | 0.597815 | 4.601756 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt | 1 | 34762 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.cache
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.cache.DiskLruCache.Editor
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.Task
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.io.FileSystem
import okhttp3.internal.isCivilized
import okhttp3.internal.okHttpName
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.Companion.WARN
import okio.*
import java.io.*
import java.io.EOFException
import java.io.IOException
import java.util.*
/**
* A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key
* and a fixed number of values. Each key must match the regex `[a-z0-9_-]{1,64}`. Values are byte
* sequences, accessible as streams or files. Each value must be between `0` and `Int.MAX_VALUE`
* bytes in length.
*
* The cache stores its data in a directory on the filesystem. This directory must be exclusive to
* the cache; the cache may delete or overwrite files from its directory. It is an error for
* multiple processes to use the same cache directory at the same time.
*
* This cache limits the number of bytes that it will store on the filesystem. When the number of
* stored bytes exceeds the limit, the cache will remove entries in the background until the limit
* is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for
* files to be deleted. The limit does not include filesystem overhead or the cache journal so
* space-sensitive applications should set a conservative limit.
*
* Clients call [edit] to create or update the values of an entry. An entry may have only one editor
* at one time; if a value is not available to be edited then [edit] will return null.
*
* * When an entry is being **created** it is necessary to supply a full set of values; the empty
* value should be used as a placeholder if necessary.
*
* * When an entry is being **edited**, it is not necessary to supply data for every value; values
* default to their previous value.
*
* Every [edit] call must be matched by a call to [Editor.commit] or [Editor.abort]. Committing is
* atomic: a read observes the full set of values as they were before or after the commit, but never
* a mix of values.
*
* Clients call [get] to read a snapshot of an entry. The read will observe the value at the time
* that [get] was called. Updates and removals after the call do not impact ongoing reads.
*
* This class is tolerant of some I/O errors. If files are missing from the filesystem, the
* corresponding entries will be dropped from the cache. If an error occurs while writing a cache
* value, the edit will fail silently. Callers should handle other problems by catching
* `IOException` and responding appropriately.
*
* @constructor Create a cache which will reside in [directory]. This cache is lazily initialized on
* first access and will be created if it does not exist.
* @param directory a writable directory.
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store.
*/
class DiskLruCache(
internal val fileSystem: FileSystem,
/** Returns the directory where this cache stores its data. */
val directory: File,
private val appVersion: Int,
internal val valueCount: Int,
/** Returns the maximum number of bytes that this cache should use to store its data. */
maxSize: Long,
/** Used for asynchronous journal rebuilds. */
taskRunner: TaskRunner
) : Closeable, Flushable {
/** The maximum number of bytes that this cache should use to store its data. */
@get:Synchronized @set:Synchronized var maxSize: Long = maxSize
set(value) {
field = value
if (initialized) {
cleanupQueue.schedule(cleanupTask) // Trim the existing store if necessary.
}
}
/*
* This cache uses a journal file named "journal". A typical journal file looks like this:
*
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the constant string
* "libcore.io.DiskLruCache", the disk cache's version, the application's version, the value
* count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a cache entry. Each line
* contains space-separated values: a state, a key, and optional state-specific values.
*
* o DIRTY lines track that an entry is actively being created or updated. Every successful
* DIRTY action should be followed by a CLEAN or REMOVE action. DIRTY lines without a matching
* CLEAN or REMOVE indicate that temporary files may need to be deleted.
*
* o CLEAN lines track a cache entry that has been successfully published and may be read. A
* publish line is followed by the lengths of each of its values.
*
* o READ lines track accesses for LRU.
*
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may occasionally be
* compacted by dropping redundant lines. A temporary file named "journal.tmp" will be used during
* compaction; that file should be deleted if it exists when the cache is opened.
*/
private val journalFile: File
private val journalFileTmp: File
private val journalFileBackup: File
private var size: Long = 0L
private var journalWriter: BufferedSink? = null
internal val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true)
private var redundantOpCount: Int = 0
private var hasJournalErrors: Boolean = false
private var civilizedFileSystem: Boolean = false
// Must be read and written when synchronized on 'this'.
private var initialized: Boolean = false
internal var closed: Boolean = false
private var mostRecentTrimFailed: Boolean = false
private var mostRecentRebuildFailed: Boolean = false
/**
* To differentiate between old and current snapshots, each entry is given a sequence number each
* time an edit is committed. A snapshot is stale if its sequence number is not equal to its
* entry's sequence number.
*/
private var nextSequenceNumber: Long = 0
private val cleanupQueue = taskRunner.newQueue()
private val cleanupTask = object : Task("$okHttpName Cache") {
override fun runOnce(): Long {
synchronized(this@DiskLruCache) {
if (!initialized || closed) {
return -1L // Nothing to do.
}
try {
trimToSize()
} catch (_: IOException) {
mostRecentTrimFailed = true
}
try {
if (journalRebuildRequired()) {
rebuildJournal()
redundantOpCount = 0
}
} catch (_: IOException) {
mostRecentRebuildFailed = true
journalWriter = blackholeSink().buffer()
}
return -1L
}
}
}
init {
require(maxSize > 0L) { "maxSize <= 0" }
require(valueCount > 0) { "valueCount <= 0" }
this.journalFile = File(directory, JOURNAL_FILE)
this.journalFileTmp = File(directory, JOURNAL_FILE_TEMP)
this.journalFileBackup = File(directory, JOURNAL_FILE_BACKUP)
}
@Synchronized @Throws(IOException::class)
fun initialize() {
this.assertThreadHoldsLock()
if (initialized) {
return // Already initialized.
}
// If a bkp file exists, use it instead.
if (fileSystem.exists(journalFileBackup)) {
// If journal file also exists just delete backup file.
if (fileSystem.exists(journalFile)) {
fileSystem.delete(journalFileBackup)
} else {
fileSystem.rename(journalFileBackup, journalFile)
}
}
civilizedFileSystem = fileSystem.isCivilized(journalFileBackup)
// Prefer to pick up where we left off.
if (fileSystem.exists(journalFile)) {
try {
readJournal()
processJournal()
initialized = true
return
} catch (journalIsCorrupt: IOException) {
Platform.get().log(
"DiskLruCache $directory is corrupt: ${journalIsCorrupt.message}, removing",
WARN,
journalIsCorrupt)
}
// The cache is corrupted, attempt to delete the contents of the directory. This can throw and
// we'll let that propagate out as it likely means there is a severe filesystem problem.
try {
delete()
} finally {
closed = false
}
}
rebuildJournal()
initialized = true
}
@Throws(IOException::class)
private fun readJournal() {
fileSystem.source(journalFile).buffer().use { source ->
val magic = source.readUtf8LineStrict()
val version = source.readUtf8LineStrict()
val appVersionString = source.readUtf8LineStrict()
val valueCountString = source.readUtf8LineStrict()
val blank = source.readUtf8LineStrict()
if (MAGIC != magic ||
VERSION_1 != version ||
appVersion.toString() != appVersionString ||
valueCount.toString() != valueCountString ||
blank.isNotEmpty()) {
throw IOException(
"unexpected journal header: [$magic, $version, $valueCountString, $blank]")
}
var lineCount = 0
while (true) {
try {
readJournalLine(source.readUtf8LineStrict())
lineCount++
} catch (_: EOFException) {
break // End of journal.
}
}
redundantOpCount = lineCount - lruEntries.size
// If we ended on a truncated line, rebuild the journal before appending to it.
if (!source.exhausted()) {
rebuildJournal()
} else {
journalWriter = newJournalWriter()
}
}
}
@Throws(FileNotFoundException::class)
private fun newJournalWriter(): BufferedSink {
val fileSink = fileSystem.appendingSink(journalFile)
val faultHidingSink = FaultHidingSink(fileSink) {
[email protected]()
hasJournalErrors = true
}
return faultHidingSink.buffer()
}
@Throws(IOException::class)
private fun readJournalLine(line: String) {
val firstSpace = line.indexOf(' ')
if (firstSpace == -1) throw IOException("unexpected journal line: $line")
val keyBegin = firstSpace + 1
val secondSpace = line.indexOf(' ', keyBegin)
val key: String
if (secondSpace == -1) {
key = line.substring(keyBegin)
if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) {
lruEntries.remove(key)
return
}
} else {
key = line.substring(keyBegin, secondSpace)
}
var entry: Entry? = lruEntries[key]
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
}
when {
secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> {
val parts = line.substring(secondSpace + 1)
.split(' ')
entry.readable = true
entry.currentEditor = null
entry.setLengths(parts)
}
secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> {
entry.currentEditor = Editor(entry)
}
secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) -> {
// This work was already done by calling lruEntries.get().
}
else -> throw IOException("unexpected journal line: $line")
}
}
/**
* Computes the initial size and collects garbage as a part of opening the cache. Dirty entries
* are assumed to be inconsistent and will be deleted.
*/
@Throws(IOException::class)
private fun processJournal() {
fileSystem.delete(journalFileTmp)
val i = lruEntries.values.iterator()
while (i.hasNext()) {
val entry = i.next()
if (entry.currentEditor == null) {
for (t in 0 until valueCount) {
size += entry.lengths[t]
}
} else {
entry.currentEditor = null
for (t in 0 until valueCount) {
fileSystem.delete(entry.cleanFiles[t])
fileSystem.delete(entry.dirtyFiles[t])
}
i.remove()
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the current journal if it
* exists.
*/
@Synchronized @Throws(IOException::class)
internal fun rebuildJournal() {
journalWriter?.close()
fileSystem.sink(journalFileTmp).buffer().use { sink ->
sink.writeUtf8(MAGIC).writeByte('\n'.toInt())
sink.writeUtf8(VERSION_1).writeByte('\n'.toInt())
sink.writeDecimalLong(appVersion.toLong()).writeByte('\n'.toInt())
sink.writeDecimalLong(valueCount.toLong()).writeByte('\n'.toInt())
sink.writeByte('\n'.toInt())
for (entry in lruEntries.values) {
if (entry.currentEditor != null) {
sink.writeUtf8(DIRTY).writeByte(' '.toInt())
sink.writeUtf8(entry.key)
sink.writeByte('\n'.toInt())
} else {
sink.writeUtf8(CLEAN).writeByte(' '.toInt())
sink.writeUtf8(entry.key)
entry.writeLengths(sink)
sink.writeByte('\n'.toInt())
}
}
}
if (fileSystem.exists(journalFile)) {
fileSystem.rename(journalFile, journalFileBackup)
}
fileSystem.rename(journalFileTmp, journalFile)
fileSystem.delete(journalFileBackup)
journalWriter = newJournalWriter()
hasJournalErrors = false
mostRecentRebuildFailed = false
}
/**
* Returns a snapshot of the entry named [key], or null if it doesn't exist is not currently
* readable. If a value is returned, it is moved to the head of the LRU queue.
*/
@Synchronized @Throws(IOException::class)
operator fun get(key: String): Snapshot? {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return null
val snapshot = entry.snapshot() ?: return null
redundantOpCount++
journalWriter!!.writeUtf8(READ)
.writeByte(' '.toInt())
.writeUtf8(key)
.writeByte('\n'.toInt())
if (journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
return snapshot
}
/** Returns an editor for the entry named [key], or null if another edit is in progress. */
@Synchronized @Throws(IOException::class)
@JvmOverloads
fun edit(key: String, expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER): Editor? {
initialize()
checkNotClosed()
validateKey(key)
var entry: Entry? = lruEntries[key]
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER &&
(entry == null || entry.sequenceNumber != expectedSequenceNumber)) {
return null // Snapshot is stale.
}
if (entry?.currentEditor != null) {
return null // Another edit is in progress.
}
if (entry != null && entry.lockingSourceCount != 0) {
return null // We can't write this file because a reader is still reading it.
}
if (mostRecentTrimFailed || mostRecentRebuildFailed) {
// The OS has become our enemy! If the trim job failed, it means we are storing more data than
// requested by the user. Do not allow edits so we do not go over that limit any further. If
// the journal rebuild failed, the journal writer will not be active, meaning we will not be
// able to record the edit, causing file leaks. In both cases, we want to retry the clean up
// so we can get out of this state!
cleanupQueue.schedule(cleanupTask)
return null
}
// Flush the journal before creating files to prevent file leaks.
val journalWriter = this.journalWriter!!
journalWriter.writeUtf8(DIRTY)
.writeByte(' '.toInt())
.writeUtf8(key)
.writeByte('\n'.toInt())
journalWriter.flush()
if (hasJournalErrors) {
return null // Don't edit; the journal can't be written.
}
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
}
val editor = Editor(entry)
entry.currentEditor = editor
return editor
}
/**
* Returns the number of bytes currently being used to store the values in this cache. This may be
* greater than the max size if a background deletion is pending.
*/
@Synchronized @Throws(IOException::class)
fun size(): Long {
initialize()
return size
}
@Synchronized @Throws(IOException::class)
internal fun completeEdit(editor: Editor, success: Boolean) {
val entry = editor.entry
check(entry.currentEditor == editor)
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (i in 0 until valueCount) {
if (!editor.written!![i]) {
editor.abort()
throw IllegalStateException("Newly created entry didn't create value for index $i")
}
if (!fileSystem.exists(entry.dirtyFiles[i])) {
editor.abort()
return
}
}
}
for (i in 0 until valueCount) {
val dirty = entry.dirtyFiles[i]
if (success && !entry.zombie) {
if (fileSystem.exists(dirty)) {
val clean = entry.cleanFiles[i]
fileSystem.rename(dirty, clean)
val oldLength = entry.lengths[i]
val newLength = fileSystem.size(clean)
entry.lengths[i] = newLength
size = size - oldLength + newLength
}
} else {
fileSystem.delete(dirty)
}
}
entry.currentEditor = null
if (entry.zombie) {
removeEntry(entry)
return
}
redundantOpCount++
journalWriter!!.apply {
if (entry.readable || success) {
entry.readable = true
writeUtf8(CLEAN).writeByte(' '.toInt())
writeUtf8(entry.key)
entry.writeLengths(this)
writeByte('\n'.toInt())
if (success) {
entry.sequenceNumber = nextSequenceNumber++
}
} else {
lruEntries.remove(entry.key)
writeUtf8(REMOVE).writeByte(' '.toInt())
writeUtf8(entry.key)
writeByte('\n'.toInt())
}
flush()
}
if (size > maxSize || journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
}
/**
* We only rebuild the journal when it will halve the size of the journal and eliminate at least
* 2000 ops.
*/
private fun journalRebuildRequired(): Boolean {
val redundantOpCompactThreshold = 2000
return redundantOpCount >= redundantOpCompactThreshold &&
redundantOpCount >= lruEntries.size
}
/**
* Drops the entry for [key] if it exists and can be removed. If the entry for [key] is currently
* being edited, that edit will complete normally but its value will not be stored.
*
* @return true if an entry was removed.
*/
@Synchronized @Throws(IOException::class)
fun remove(key: String): Boolean {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return false
val removed = removeEntry(entry)
if (removed && size <= maxSize) mostRecentTrimFailed = false
return removed
}
@Throws(IOException::class)
internal fun removeEntry(entry: Entry): Boolean {
// If we can't delete files that are still open, mark this entry as a zombie so its files will
// be deleted when those files are closed.
if (!civilizedFileSystem) {
if (entry.lockingSourceCount > 0) {
// Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used.
journalWriter?.let {
it.writeUtf8(DIRTY)
it.writeByte(' '.toInt())
it.writeUtf8(entry.key)
it.writeByte('\n'.toInt())
it.flush()
}
}
if (entry.lockingSourceCount > 0 || entry.currentEditor != null) {
entry.zombie = true
return true
}
}
entry.currentEditor?.detach() // Prevent the edit from completing normally.
for (i in 0 until valueCount) {
fileSystem.delete(entry.cleanFiles[i])
size -= entry.lengths[i]
entry.lengths[i] = 0
}
redundantOpCount++
journalWriter?.let {
it.writeUtf8(REMOVE)
it.writeByte(' '.toInt())
it.writeUtf8(entry.key)
it.writeByte('\n'.toInt())
}
lruEntries.remove(entry.key)
if (journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
return true
}
@Synchronized private fun checkNotClosed() {
check(!closed) { "cache is closed" }
}
/** Force buffered operations to the filesystem. */
@Synchronized @Throws(IOException::class)
override fun flush() {
if (!initialized) return
checkNotClosed()
trimToSize()
journalWriter!!.flush()
}
@Synchronized fun isClosed(): Boolean = closed
/** Closes this cache. Stored values will remain on the filesystem. */
@Synchronized @Throws(IOException::class)
override fun close() {
if (!initialized || closed) {
closed = true
return
}
// Copying for concurrent iteration.
for (entry in lruEntries.values.toTypedArray()) {
if (entry.currentEditor != null) {
entry.currentEditor?.detach() // Prevent the edit from completing normally.
}
}
trimToSize()
journalWriter!!.close()
journalWriter = null
closed = true
}
@Throws(IOException::class)
fun trimToSize() {
while (size > maxSize) {
if (!removeOldestEntry()) return
}
mostRecentTrimFailed = false
}
/** Returns true if an entry was removed. This will return false if all entries are zombies. */
private fun removeOldestEntry(): Boolean {
for (toEvict in lruEntries.values) {
if (!toEvict.zombie) {
removeEntry(toEvict)
return true
}
}
return false
}
/**
* Closes the cache and deletes all of its stored values. This will delete all files in the cache
* directory including files that weren't created by the cache.
*/
@Throws(IOException::class)
fun delete() {
close()
fileSystem.deleteContents(directory)
}
/**
* Deletes all stored values from the cache. In-flight edits will complete normally but their
* values will not be stored.
*/
@Synchronized @Throws(IOException::class)
fun evictAll() {
initialize()
// Copying for concurrent iteration.
for (entry in lruEntries.values.toTypedArray()) {
removeEntry(entry)
}
mostRecentTrimFailed = false
}
private fun validateKey(key: String) {
require(LEGAL_KEY_PATTERN.matches(key)) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" }
}
/**
* Returns an iterator over the cache's current entries. This iterator doesn't throw
* `ConcurrentModificationException`, but if new entries are added while iterating, those new
* entries will not be returned by the iterator. If existing entries are removed during iteration,
* they will be absent (unless they were already returned).
*
* If there are I/O problems during iteration, this iterator fails silently. For example, if the
* hosting filesystem becomes unreachable, the iterator will omit elements rather than throwing
* exceptions.
*
* **The caller must [close][Snapshot.close]** each snapshot returned by [Iterator.next]. Failing
* to do so leaks open files!
*/
@Synchronized @Throws(IOException::class)
fun snapshots(): MutableIterator<Snapshot> {
initialize()
return object : MutableIterator<Snapshot> {
/** Iterate a copy of the entries to defend against concurrent modification errors. */
private val delegate = ArrayList(lruEntries.values).iterator()
/** The snapshot to return from [next]. Null if we haven't computed that yet. */
private var nextSnapshot: Snapshot? = null
/** The snapshot to remove with [remove]. Null if removal is illegal. */
private var removeSnapshot: Snapshot? = null
override fun hasNext(): Boolean {
if (nextSnapshot != null) return true
synchronized(this@DiskLruCache) {
// If the cache is closed, truncate the iterator.
if (closed) return false
while (delegate.hasNext()) {
nextSnapshot = delegate.next()?.snapshot() ?: continue
return true
}
}
return false
}
override fun next(): Snapshot {
if (!hasNext()) throw NoSuchElementException()
removeSnapshot = nextSnapshot
nextSnapshot = null
return removeSnapshot!!
}
override fun remove() {
val removeSnapshot = this.removeSnapshot
checkNotNull(removeSnapshot) { "remove() before next()" }
try {
[email protected](removeSnapshot.key())
} catch (_: IOException) {
// Nothing useful to do here. We failed to remove from the cache. Most likely that's
// because we couldn't update the journal, but the cached entry will still be gone.
} finally {
this.removeSnapshot = null
}
}
}
}
/** A snapshot of the values for an entry. */
inner class Snapshot internal constructor(
private val key: String,
private val sequenceNumber: Long,
private val sources: List<Source>,
private val lengths: LongArray
) : Closeable {
fun key(): String = key
/**
* Returns an editor for this snapshot's entry, or null if either the entry has changed since
* this snapshot was created or if another edit is in progress.
*/
@Throws(IOException::class)
fun edit(): Editor? = [email protected](key, sequenceNumber)
/** Returns the unbuffered stream with the value for [index]. */
fun getSource(index: Int): Source = sources[index]
/** Returns the byte length of the value for [index]. */
fun getLength(index: Int): Long = lengths[index]
override fun close() {
for (source in sources) {
source.closeQuietly()
}
}
}
/** Edits the values for an entry. */
inner class Editor internal constructor(internal val entry: Entry) {
internal val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount)
private var done: Boolean = false
/**
* Prevents this editor from completing normally. This is necessary either when the edit causes
* an I/O error, or if the target entry is evicted while this editor is active. In either case
* we delete the editor's created files and prevent new files from being created. Note that once
* an editor has been detached it is possible for another editor to edit the entry.
*/
internal fun detach() {
if (entry.currentEditor == this) {
if (civilizedFileSystem) {
completeEdit(this, false) // Delete it now.
} else {
entry.zombie = true // We can't delete it until the current edit completes.
}
}
}
/**
* Returns an unbuffered input stream to read the last committed value, or null if no value has
* been committed.
*/
fun newSource(index: Int): Source? {
synchronized(this@DiskLruCache) {
check(!done)
if (!entry.readable || entry.currentEditor != this || entry.zombie) {
return null
}
return try {
fileSystem.source(entry.cleanFiles[index])
} catch (_: FileNotFoundException) {
null
}
}
}
/**
* Returns a new unbuffered output stream to write the value at [index]. If the underlying
* output stream encounters errors when writing to the filesystem, this edit will be aborted
* when [commit] is called. The returned output stream does not throw IOExceptions.
*/
fun newSink(index: Int): Sink {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor != this) {
return blackholeSink()
}
if (!entry.readable) {
written!![index] = true
}
val dirtyFile = entry.dirtyFiles[index]
val sink: Sink
try {
sink = fileSystem.sink(dirtyFile)
} catch (_: FileNotFoundException) {
return blackholeSink()
}
return FaultHidingSink(sink) {
synchronized(this@DiskLruCache) {
detach()
}
}
}
}
/**
* Commits this edit so it is visible to readers. This releases the edit lock so another edit
* may be started on the same key.
*/
@Throws(IOException::class)
fun commit() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, true)
}
done = true
}
}
/**
* Aborts this edit. This releases the edit lock so another edit may be started on the same
* key.
*/
@Throws(IOException::class)
fun abort() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, false)
}
done = true
}
}
}
internal inner class Entry internal constructor(
internal val key: String
) {
/** Lengths of this entry's files. */
internal val lengths: LongArray = LongArray(valueCount)
internal val cleanFiles = mutableListOf<File>()
internal val dirtyFiles = mutableListOf<File>()
/** True if this entry has ever been published. */
internal var readable: Boolean = false
/** True if this entry must be deleted when the current edit or read completes. */
internal var zombie: Boolean = false
/**
* The ongoing edit or null if this entry is not being edited. When setting this to null the
* entry must be removed if it is a zombie.
*/
internal var currentEditor: Editor? = null
/**
* Sources currently reading this entry before a write or delete can proceed. When decrementing
* this to zero, the entry must be removed if it is a zombie.
*/
internal var lockingSourceCount = 0
/** The sequence number of the most recently committed edit to this entry. */
internal var sequenceNumber: Long = 0
init {
// The names are repetitive so re-use the same builder to avoid allocations.
val fileBuilder = StringBuilder(key).append('.')
val truncateTo = fileBuilder.length
for (i in 0 until valueCount) {
fileBuilder.append(i)
cleanFiles += File(directory, fileBuilder.toString())
fileBuilder.append(".tmp")
dirtyFiles += File(directory, fileBuilder.toString())
fileBuilder.setLength(truncateTo)
}
}
/** Set lengths using decimal numbers like "10123". */
@Throws(IOException::class)
internal fun setLengths(strings: List<String>) {
if (strings.size != valueCount) {
throw invalidLengths(strings)
}
try {
for (i in strings.indices) {
lengths[i] = strings[i].toLong()
}
} catch (_: NumberFormatException) {
throw invalidLengths(strings)
}
}
/** Append space-prefixed lengths to [writer]. */
@Throws(IOException::class)
internal fun writeLengths(writer: BufferedSink) {
for (length in lengths) {
writer.writeByte(' '.toInt()).writeDecimalLong(length)
}
}
@Throws(IOException::class)
private fun invalidLengths(strings: List<String>): Nothing {
throw IOException("unexpected journal line: $strings")
}
/**
* Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a
* single published snapshot. If we opened streams lazily then the streams could come from
* different edits.
*/
internal fun snapshot(): Snapshot? {
[email protected]()
if (!readable) return null
if (!civilizedFileSystem && (currentEditor != null || zombie)) return null
val sources = mutableListOf<Source>()
val lengths = this.lengths.clone() // Defensive copy since these can be zeroed out.
try {
for (i in 0 until valueCount) {
sources += newSource(i)
}
return Snapshot(key, sequenceNumber, sources, lengths)
} catch (_: FileNotFoundException) {
// A file must have been deleted manually!
for (source in sources) {
source.closeQuietly()
}
// Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache
// size.)
try {
removeEntry(this)
} catch (_: IOException) {
}
return null
}
}
private fun newSource(index: Int): Source {
val fileSource = fileSystem.source(cleanFiles[index])
if (civilizedFileSystem) return fileSource
lockingSourceCount++
return object : ForwardingSource(fileSource) {
private var closed = false
override fun close() {
super.close()
if (!closed) {
closed = true
synchronized(this@DiskLruCache) {
lockingSourceCount--
if (lockingSourceCount == 0 && zombie) {
removeEntry(this@Entry)
}
}
}
}
}
}
}
companion object {
@JvmField val JOURNAL_FILE = "journal"
@JvmField val JOURNAL_FILE_TEMP = "journal.tmp"
@JvmField val JOURNAL_FILE_BACKUP = "journal.bkp"
@JvmField val MAGIC = "libcore.io.DiskLruCache"
@JvmField val VERSION_1 = "1"
@JvmField val ANY_SEQUENCE_NUMBER: Long = -1
@JvmField val LEGAL_KEY_PATTERN = "[a-z0-9_-]{1,120}".toRegex()
@JvmField val CLEAN = "CLEAN"
@JvmField val DIRTY = "DIRTY"
@JvmField val REMOVE = "REMOVE"
@JvmField val READ = "READ"
}
}
| apache-2.0 | 95258bf0c3f819f37b55eba2380ef719 | 31.981025 | 100 | 0.647661 | 4.592681 | false | false | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/BuildFilterServiceImpl.kt | 1 | 14340 | package net.nemerosa.ontrack.service
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.buildfilter.*
import net.nemerosa.ontrack.model.exceptions.BuildFilterNotFoundException
import net.nemerosa.ontrack.model.exceptions.BuildFilterNotLoggedException
import net.nemerosa.ontrack.model.security.BranchFilterMgt
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.Branch
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.StandardBuildFilterData
import net.nemerosa.ontrack.model.structure.StructureService
import net.nemerosa.ontrack.repository.BuildFilterRepository
import net.nemerosa.ontrack.repository.TBuildFilter
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.util.*
@Service
@Transactional
class BuildFilterServiceImpl(
buildFilterProviders: Collection<BuildFilterProvider<*>>,
private val buildFilterRepository: BuildFilterRepository,
private val structureService: StructureService,
private val securityService: SecurityService
) : BuildFilterService {
private val buildFilterProviders: Map<String, BuildFilterProvider<*>> = buildFilterProviders
.associateBy { it.type }
override fun defaultFilterProviderData(): BuildFilterProviderData<*> {
return standardFilterProviderData(10).build()
}
override fun lastPromotedBuildsFilterData(): BuildFilterProviderData<*> {
return getBuildFilterProviderByType<Any>(PromotionLevelBuildFilterProvider::class.java.name)
?.withData(null)
?: throw BuildFilterProviderNotFoundException(PromotionLevelBuildFilterProvider::class.java.name)
}
inner class DefaultStandardFilterProviderDataBuilder(count: Int) : StandardFilterProviderDataBuilder {
private var data: StandardBuildFilterData = StandardBuildFilterData.of(count)
override fun build(): BuildFilterProviderData<*> {
val provider = getBuildFilterProviderByType<Any>(StandardBuildFilterProvider::class.java.name)
?: throw BuildFilterProviderNotFoundException(StandardBuildFilterProvider::class.java.name)
@Suppress("UNCHECKED_CAST")
return (provider as BuildFilterProvider<StandardBuildFilterData>).withData(data)
}
override fun withSincePromotionLevel(sincePromotionLevel: String): StandardFilterProviderDataBuilder {
data = data.withSincePromotionLevel(sincePromotionLevel)
return this
}
override fun withWithPromotionLevel(withPromotionLevel: String): StandardFilterProviderDataBuilder {
data = data.withWithPromotionLevel(withPromotionLevel)
return this
}
override fun withAfterDate(afterDate: LocalDate): StandardFilterProviderDataBuilder {
data = data.withAfterDate(afterDate)
return this
}
override fun withBeforeDate(beforeDate: LocalDate): StandardFilterProviderDataBuilder {
data = data.withBeforeDate(beforeDate)
return this
}
override fun withSinceValidationStamp(sinceValidationStamp: String): StandardFilterProviderDataBuilder {
data = data.withSinceValidationStamp(sinceValidationStamp)
return this
}
override fun withSinceValidationStampStatus(sinceValidationStampStatus: String): StandardFilterProviderDataBuilder {
data = data.withSinceValidationStampStatus(sinceValidationStampStatus)
return this
}
override fun withWithValidationStamp(withValidationStamp: String): StandardFilterProviderDataBuilder {
data = data.withWithValidationStamp(withValidationStamp)
return this
}
override fun withWithValidationStampStatus(withValidationStampStatus: String): StandardFilterProviderDataBuilder {
data = data.withWithValidationStampStatus(withValidationStampStatus)
return this
}
override fun withWithProperty(withProperty: String): StandardFilterProviderDataBuilder {
data = data.withWithProperty(withProperty)
return this
}
override fun withWithPropertyValue(withPropertyValue: String): StandardFilterProviderDataBuilder {
data = data.withWithPropertyValue(withPropertyValue)
return this
}
override fun withSinceProperty(sinceProperty: String): StandardFilterProviderDataBuilder {
data = data.withSinceProperty(sinceProperty)
return this
}
override fun withSincePropertyValue(sincePropertyValue: String): StandardFilterProviderDataBuilder {
data = data.withSincePropertyValue(sincePropertyValue)
return this
}
override fun withLinkedFrom(linkedFrom: String): StandardFilterProviderDataBuilder {
data = data.withLinkedFrom(linkedFrom)
return this
}
override fun withLinkedFromPromotion(linkedFromPromotion: String): StandardFilterProviderDataBuilder {
data = data.withLinkedFromPromotion(linkedFromPromotion)
return this
}
override fun withLinkedTo(linkedTo: String): StandardFilterProviderDataBuilder {
data = data.withLinkedTo(linkedTo)
return this
}
override fun withLinkedToPromotion(linkedToPromotion: String): StandardFilterProviderDataBuilder {
data = data.withLinkedToPromotion(linkedToPromotion)
return this
}
}
override fun standardFilterProviderData(count: Int): StandardFilterProviderDataBuilder {
return DefaultStandardFilterProviderDataBuilder(count)
}
override fun standardFilterProviderData(node: JsonNode): BuildFilterProviderData<*> {
return getBuildFilterProviderData<Any>(
StandardBuildFilterProvider::class.java.name,
node
)
}
override fun getBuildFilters(branchId: ID): Collection<BuildFilterResource<*>> {
val branch = structureService.getBranch(branchId)
// Are we logged?
val account = securityService.currentAccount
return if (account != null) {
// Gets the filters for this account and the branch
buildFilterRepository.findForBranch(OptionalInt.of(account.id()), branchId.value)
.mapNotNull { t -> loadBuildFilterResource<Any>(branch, t) }
}
// Not logged, no filter
else {
// Gets the filters for the branch
buildFilterRepository.findForBranch(OptionalInt.empty(), branchId.get())
.mapNotNull { t -> loadBuildFilterResource<Any>(branch, t) }
}
}
override fun getBuildFilterForms(branchId: ID): Collection<BuildFilterForm> {
return buildFilterProviders.values
.map { provider -> provider.newFilterForm(branchId) }
}
override fun <T> getBuildFilterProviderData(filterType: String, parameters: JsonNode): BuildFilterProviderData<T> {
val buildFilterProvider = getBuildFilterProviderByType<T>(filterType)
return buildFilterProvider
?.let { getBuildFilterProviderData(it, parameters) }
?: throw BuildFilterProviderNotFoundException(filterType)
}
override fun <T> getBuildFilterProviderData(filterType: String, parameters: T): BuildFilterProviderData<T> {
val buildFilterProvider = getBuildFilterProviderByType<T>(filterType)
return buildFilterProvider?.withData(parameters)
?: throw BuildFilterProviderNotFoundException(filterType)
}
override fun validateBuildFilterProviderData(branch: Branch, filterType: String, parameters: JsonNode): String? {
val buildFilterProvider: BuildFilterProvider<*>? = getBuildFilterProviderByType<Any>(filterType)
return if (buildFilterProvider != null) {
validateBuildFilterProviderData(branch, buildFilterProvider, parameters)
} else {
BuildFilterProviderNotFoundException(filterType).message
}
}
private fun <T> validateBuildFilterProviderData(
branch: Branch,
buildFilterProvider: BuildFilterProvider<T>,
parameters: JsonNode
): String? {
// Parsing
val data: T? = try {
buildFilterProvider.parse(parameters).orElse(null)
} catch (ex: Exception) {
return "Cannot parse build filter data: ${ex.message}"
}
// Validation
return data?.run { buildFilterProvider.validateData(branch, this) }
}
protected fun <T> getBuildFilterProviderData(provider: BuildFilterProvider<T>, parameters: JsonNode): BuildFilterProviderData<T> {
val data = provider.parse(parameters)
return if (data.isPresent) {
BuildFilterProviderData.of(provider, data.get())
} else {
throw BuildFilterProviderDataParsingException(provider.javaClass.name)
}
}
@Throws(BuildFilterNotFoundException::class)
override fun getEditionForm(branchId: ID, name: String): BuildFilterForm {
return securityService.currentAccount
?.let { account -> buildFilterRepository.findByBranchAndName(account.id(), branchId.value, name).getOrNull() }
?.let { this.getBuildFilterForm<Any>(it) }
?: throw BuildFilterNotLoggedException()
}
private fun <T> getBuildFilterForm(t: TBuildFilter): BuildFilterForm? {
val provider = getBuildFilterProviderByType<T>(t.type)
return provider
?.parse(t.data)
?.map { data ->
provider.getFilterForm(
ID.of(t.branchId),
data
)
}
?.orElse(null)
}
override fun saveFilter(branchId: ID, shared: Boolean, name: String, type: String, parameters: JsonNode): Ack {
// Checks the account
if (shared) {
val account = securityService.currentAccount
return if (account != null) {
// Gets the branch
val branch = structureService.getBranch(branchId)
// Checks access rights
securityService.checkProjectFunction(branch, BranchFilterMgt::class.java)
// Deletes any previous filter
val currentAccountId = account.id()
buildFilterRepository.findByBranchAndName(currentAccountId, branchId.get(), name).ifPresent {
buildFilterRepository.delete(currentAccountId, branchId.get(), name, true)
}
// No account to be used
doSaveFilter(OptionalInt.empty(), branchId, name, type, parameters)
} else {
Ack.NOK
}
} else {
val account = securityService.currentAccount
return if (account == null) {
Ack.NOK
} else {
// Saves it for this account
doSaveFilter(OptionalInt.of(account.id()), branchId, name, type, parameters)
}
}
}
private fun doSaveFilter(accountId: OptionalInt, branchId: ID, name: String, type: String, parameters: JsonNode): Ack {
// Checks the provider
val provider = getBuildFilterProviderByType<Any>(type)
return if (provider == null) {
Ack.NOK
}
// Excludes predefined filters
else if (provider.isPredefined) {
Ack.NOK
}
// Checks the data
else if (!provider.parse(parameters).isPresent) {
Ack.NOK
} else {
// Saving
buildFilterRepository.save(accountId, branchId.value, name, type, parameters)
}
}
override fun deleteFilter(branchId: ID, name: String): Ack {
val user = securityService.currentAccount
return if (user != null) {
// Gets the branch
val branch = structureService.getBranch(branchId)
// If user is allowed to manage shared filters, this filter might have to be deleted from the shared filters
// as well
val sharedFilter = securityService.isProjectFunctionGranted(branch, BranchFilterMgt::class.java)
// Deleting the filter
buildFilterRepository.delete(user.id(), branchId.get(), name, sharedFilter)
} else {
Ack.NOK
}
}
override fun copyToBranch(sourceBranchId: ID, targetBranchId: ID) {
// Gets all the filters for the source branch
buildFilterRepository.findForBranch(sourceBranchId.value).forEach { filter ->
buildFilterRepository.save(
filter.accountId,
targetBranchId.get(),
filter.name,
filter.type,
filter.data
)
}
}
private fun <T> getBuildFilterProviderByType(type: String): BuildFilterProvider<T>? {
@Suppress("UNCHECKED_CAST")
return buildFilterProviders[type] as BuildFilterProvider<T>?
}
private fun <T> loadBuildFilterResource(branch: Branch, t: TBuildFilter): BuildFilterResource<T>? {
return getBuildFilterProviderByType<Any>(t.type)
?.let {
@Suppress("UNCHECKED_CAST")
loadBuildFilterResource(it as BuildFilterProvider<T>, branch, t.isShared, t.name, t.data)
}
}
private fun <T> loadBuildFilterResource(provider: BuildFilterProvider<T>, branch: Branch, shared: Boolean, name: String, data: JsonNode): BuildFilterResource<T>? {
return provider.parse(data)
.getOrNull()
?.run {
BuildFilterResource(
branch,
shared,
name,
provider.type,
this,
provider.validateData(branch, this)
)
}
}
}
| mit | c77a4de69ea60f681a329d23ca0ea104 | 40.929825 | 167 | 0.655718 | 5.233577 | false | false | false | false |
olonho/carkot | server/src/main/java/algorithm/geometry/Line.kt | 1 | 1116 | package algorithm.geometry
class Line(var A: Double, var B: Double, var C: Double) {
init {
normalize()
}
fun intersect(lineTwo: Line): Point {
val slope = this.A * lineTwo.B - this.B * lineTwo.A
if (Math.abs(slope) < 0.001) {
throw ArithmeticException("lines is parallel")
}
val xIntersection = (this.B * lineTwo.C - lineTwo.B * this.C) / slope
val yIntersection = (this.C * lineTwo.A - lineTwo.C * this.A) / slope
return Point(xIntersection, yIntersection)
}
override fun toString(): String {
return "Line(A=$A, B=$B, C=$C)"
}
fun normalize() {
val div = Math.sqrt(A * A + B * B)
A /= div
B /= div
C /= div
if (A.eq(0.0)) {
if (B.lt(0.0)) {
A *= -1
B *= -1
C *= -1
}
} else {
if (A.lt(0.0)) {
A *= -1
B *= -1
C *= -1
}
}
}
fun getDirectionVector(): Vector {
return Vector(A, -B)
}
} | mit | f641864d40ffbe15d63b21ec384e42d7 | 22.270833 | 77 | 0.43638 | 3.576923 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/data/local/model/DbPlaylist.kt | 1 | 778 | package be.florien.anyflow.data.local.model
import androidx.room.*
/**
* Database structure that represents to playlist
*/
@Entity(tableName = "Playlist")
data class DbPlaylist(
@PrimaryKey
val id: Long,
val name: String,
val owner: String)
@Entity(tableName = "PlaylistSongs",
primaryKeys = ["songId", "playlistId"])
data class DbPlaylistSongs(
val songId: Long,
val playlistId: Long)
data class DbPlaylistWithSongs(
@Embedded val playlist: DbPlaylist,
@Relation(
parentColumn = "id",
entityColumn = "id",
associateBy = Junction(DbPlaylistSongs::class, parentColumn = "playlistId", entityColumn = "songId")
)
val songs: List<DbSong>
) | gpl-3.0 | 0f1b030c48716a0029028c0bbe2287ff | 24.966667 | 116 | 0.620823 | 4.274725 | false | false | false | false |
synyx/calenope | modules/core.google/src/main/kotlin/de/synyx/calenope/core/google/service/GoogleBoard.kt | 1 | 2574 | package de.synyx.calenope.core.google.service
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.services.admin.directory.Directory
import com.google.api.services.admin.directory.model.CalendarResource
import com.google.api.services.calendar.model.CalendarListEntry
import de.synyx.calenope.core.api.model.Calendar
import de.synyx.calenope.core.api.service.Board
import de.synyx.calenope.core.api.service.Query
import de.synyx.calenope.core.google.GoogleApi
import de.synyx.calenope.core.std.model.MemoryCalendar
import java.util.*
/**
* @author clausen - [email protected]
*/
class GoogleBoard constructor (api: GoogleApi) : Board {
private val calendar : com.google.api.services.calendar.Calendar
private val directory : Directory
init {
calendar = api.calendar ()
directory = api.directory ()
}
override fun all () : Collection<Calendar> {
return byCalendar () + byDirectory ()
}
protected fun byDirectory () : Collection<Calendar> {
val list = directory.resources ().calendars ().list ("my_customer")
val resources = ArrayList<CalendarResource> ()
var token: String? = null
do {
val calendars = tryremote (list.setPageToken (token)) {
execute ()
}
resources += calendars?.items ?: emptyList ()
token = calendars?.nextPageToken
} while (token != null)
return resources.map { MemoryCalendar (id = it.resourceName, query = query (it.resourceEmail)) }
}
protected fun byCalendar (): Collection<Calendar> {
val list = calendar.calendarList ().list ()
val resources = ArrayList<CalendarListEntry> ()
var token: String? = null
do {
val calendars = tryremote (list.setPageToken (token)) {
execute ()
}
resources += calendars?.items ?: emptyList ()
token = calendars?.nextPageToken
} while (token != null)
return resources.map { MemoryCalendar (id = it.id, query = query (it.id)) }
}
private fun query (name: String): Query = GoogleQuery { calendar.events ().list (name) }
private fun <T, R> tryremote (receiver : T, action : T.() -> R) : R? {
return try {
action (receiver)
} catch (e : Exception) {
when (e) {
is GoogleJsonResponseException -> if (e.statusCode == 404) return@tryremote null
}
throw e
}
}
}
| apache-2.0 | 7be8ad0337c87f6e42235e4d383b3419 | 29.282353 | 104 | 0.62432 | 4.282862 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/ext/web/token/TokenHelper.kt | 1 | 4338 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.ext.web.token
import org.apache.commons.codec.DecoderException
import org.apache.commons.codec.binary.Hex
import org.jose4j.jwe.JsonWebEncryption
import org.jose4j.jwt.JwtClaims
import org.jose4j.jwt.MalformedClaimException
import org.jose4j.jwt.NumericDate
import org.jose4j.jwt.consumer.InvalidJwtException
import org.jose4j.lang.JoseException
import svnserver.HashHelper
import svnserver.Loggers
import svnserver.UserType
import svnserver.auth.User
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.regex.Pattern
/**
* Helper for working with authentication tokens.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object TokenHelper {
private val log = Loggers.web
private val hex = Pattern.compile("^[0-9a-fA-F]+$")
fun createToken(jwe: JsonWebEncryption, user: User, expireAt: NumericDate): String {
return try {
val claims = JwtClaims()
claims.expirationTime = expireAt
claims.setGeneratedJwtId() // a unique identifier for the token
claims.setIssuedAtToNow() // when the token was issued/created (now)
claims.setNotBeforeMinutesInThePast(0.5f) // time before which the token is not yet valid (30 seconds ago)
if (!user.isAnonymous) {
claims.subject = user.username // the subject/principal is whom the token is about
setClaim(claims, "email", user.email)
setClaim(claims, "name", user.realName)
setClaim(claims, "external", user.externalId)
setClaim(claims, "type", user.type.name)
}
jwe.payload = claims.toJson()
jwe.compactSerialization
} catch (e: JoseException) {
throw IllegalStateException(e)
}
}
private fun setClaim(claims: JwtClaims, name: String, value: Any?) {
if (value != null) {
claims.setClaim(name, value)
}
}
fun parseToken(jwe: JsonWebEncryption, token: String, tokenEnsureTime: Int): User? {
return try {
jwe.compactSerialization = token
val claims = JwtClaims.parse(jwe.payload)
val now = NumericDate.now()
val expire = NumericDate.fromMilliseconds(now.valueInMillis)
if (tokenEnsureTime > 0) {
expire.addSeconds(tokenEnsureTime.toLong())
}
if (claims.expirationTime == null || claims.expirationTime.isBefore(expire)) {
return null
}
if (claims.notBefore == null || claims.notBefore.isAfter(now)) {
return null
}
if (claims.subject == null) {
User.anonymous
} else User.create(
claims.subject,
claims.getClaimValue("name", String::class.java),
claims.getClaimValue("email", String::class.java),
claims.getClaimValue("external", String::class.java),
UserType.valueOf(claims.getClaimValue("type", String::class.java)),
null
)
} catch (e: JoseException) {
log.warn("Token parsing error: " + e.message)
null
} catch (e: MalformedClaimException) {
log.warn("Token parsing error: " + e.message)
null
} catch (e: InvalidJwtException) {
log.warn("Token parsing error: " + e.message)
null
}
}
fun secretToBytes(secret: String, length: Int): ByteArray {
return try {
if (secret.length == length * 2 && hex.matcher(secret).find()) {
return Hex.decodeHex(secret.toCharArray())
}
val hash = HashHelper.sha256().digest(secret.toByteArray(StandardCharsets.UTF_8))
Arrays.copyOf(hash, length)
} catch (e: DecoderException) {
throw IllegalStateException(e)
}
}
}
| gpl-2.0 | 9ec39281bcc9dab81d20c38b561e6ce1 | 38.798165 | 118 | 0.618949 | 4.248776 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/SqlDelightEnvironment.kt | 1 | 13518 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.core
import app.cash.sqldelight.core.compiler.SqlDelightCompiler
import app.cash.sqldelight.core.lang.DatabaseFileType
import app.cash.sqldelight.core.lang.DatabaseFileViewProviderFactory
import app.cash.sqldelight.core.lang.MigrationFile
import app.cash.sqldelight.core.lang.MigrationFileType
import app.cash.sqldelight.core.lang.MigrationParserDefinition
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.core.lang.SqlDelightFileType
import app.cash.sqldelight.core.lang.SqlDelightParserDefinition
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.core.lang.util.migrationFiles
import app.cash.sqldelight.core.lang.util.sqFile
import app.cash.sqldelight.core.lang.validation.OptimisticLockValidator
import app.cash.sqldelight.core.psi.SqlDelightImportStmt
import app.cash.sqldelight.dialect.api.SqlDelightDialect
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.SqlCoreEnvironment
import com.alecstrong.sql.psi.core.SqlFileBase
import com.alecstrong.sql.psi.core.psi.SqlCreateTableStmt
import com.alecstrong.sql.psi.core.psi.SqlStmt
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.mock.MockModule
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleExtension
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileTypeFileViewProviders
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
import org.picocontainer.MutablePicoContainer
import java.io.File
import java.util.StringTokenizer
import kotlin.math.log10
import kotlin.system.measureTimeMillis
/**
* Mocks an intellij environment for compiling sqldelight files without an instance of intellij
* running.
*/
class SqlDelightEnvironment(
private val properties: SqlDelightDatabaseProperties,
private val compilationUnit: SqlDelightCompilationUnit,
private val verifyMigrations: Boolean,
override var dialect: SqlDelightDialect,
moduleName: String,
private val sourceFolders: List<File> = compilationUnit.sourceFolders
.filter { it.folder.exists() && !it.dependency }
.map { it.folder },
private val dependencyFolders: List<File> = compilationUnit.sourceFolders
.filter { it.folder.exists() && it.dependency }
.map { it.folder },
) : SqlCoreEnvironment(sourceFolders, dependencyFolders),
SqlDelightProjectService {
val project: Project = projectEnvironment.project
val module = MockModule(project, projectEnvironment.parentDisposable)
private val moduleName = SqlDelightFileIndex.sanitizeDirectoryName(moduleName)
init {
(project.picoContainer as MutablePicoContainer).registerComponentInstance(
SqlDelightProjectService::class.java.name,
this,
)
CoreApplicationEnvironment.registerExtensionPoint(
module.extensionArea,
ModuleExtension.EP_NAME,
ModuleExtension::class.java,
)
initializeApplication {
registerFileType(MigrationFileType, MigrationFileType.defaultExtension)
registerParserDefinition(MigrationParserDefinition())
registerFileType(SqlDelightFileType, SqlDelightFileType.defaultExtension)
registerParserDefinition(SqlDelightParserDefinition())
registerFileType(DatabaseFileType, DatabaseFileType.defaultExtension)
FileTypeFileViewProviders.INSTANCE.addExplicitExtension(DatabaseFileType, DatabaseFileViewProviderFactory())
}
}
override var treatNullAsUnknownForEquality: Boolean = properties.treatNullAsUnknownForEquality
override var generateAsync: Boolean = properties.generateAsync
override fun module(vFile: VirtualFile) = module
override fun fileIndex(module: Module): SqlDelightFileIndex = FileIndex()
override fun resetIndex() = throw UnsupportedOperationException()
override fun clearIndex() = throw UnsupportedOperationException()
override fun forSourceFiles(action: (SqlFileBase) -> Unit) {
super.forSourceFiles {
if (it.fileType != MigrationFileType ||
verifyMigrations ||
properties.deriveSchemaFromMigrations
) {
action(it)
}
}
}
/**
* Run the SQLDelight compiler and return the error or success status.
*/
fun generateSqlDelightFiles(logger: (String) -> Unit): CompilationStatus {
val errors = sortedMapOf<Int, MutableList<String>>()
val extraAnnotators = listOf(OptimisticLockValidator())
annotate(
object : SqlAnnotationHolder {
override fun createErrorAnnotation(element: PsiElement, s: String) {
val key = element.sqFile().order ?: Integer.MAX_VALUE
errors.putIfAbsent(key, ArrayList())
errors[key]!!.add(errorMessage(element, s))
}
},
extraAnnotators,
)
if (errors.isNotEmpty()) return CompilationStatus.Failure(errors.values.flatten())
val writer = writer@{ fileName: String ->
val file = File(fileName)
if (!file.exists()) {
file.parentFile.mkdirs()
file.createNewFile()
}
return@writer file.writer()
}
var sourceFile: SqlDelightFile? = null
var topMigrationFile: MigrationFile? = null
forSourceFiles {
if (it is MigrationFile && properties.deriveSchemaFromMigrations) {
if (topMigrationFile == null || it.order > topMigrationFile!!.order) topMigrationFile = it
if (sourceFile == null) sourceFile = it
}
if (it !is SqlDelightQueriesFile) return@forSourceFiles
logger("----- START ${it.name} ms -------")
val timeTaken = measureTimeMillis {
SqlDelightCompiler.writeInterfaces(module, dialect, it, writer)
sourceFile = it
}
logger("----- END ${it.name} in $timeTaken ms ------")
}
topMigrationFile?.let { migrationFile ->
logger("----- START ${migrationFile.name} ms -------")
val timeTaken = measureTimeMillis {
SqlDelightCompiler.writeInterfaces(
file = migrationFile,
output = writer,
includeAll = true,
)
SqlDelightCompiler.writeImplementations(module, migrationFile, moduleName, writer)
}
logger("----- END ${migrationFile.name} in $timeTaken ms ------")
}
sourceFile?.let {
SqlDelightCompiler.writeDatabaseInterface(module, it, moduleName, writer)
if (it is SqlDelightQueriesFile) {
SqlDelightCompiler.writeImplementations(module, it, moduleName, writer)
}
}
return CompilationStatus.Success()
}
fun forMigrationFiles(body: (MigrationFile) -> Unit) {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
val migrationFiles: Collection<MigrationFile> = sourceFolders
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
.map { psiManager.findDirectory(it)!! }
.flatMap { directory: PsiDirectory -> directory.migrationFiles() }
migrationFiles.sortedBy { it.version }
.forEach {
val errorElements = ArrayList<PsiErrorElement>()
PsiTreeUtil.processElements(it) { element ->
when (element) {
is PsiErrorElement -> errorElements.add(element)
// Uncomment when sqm files understand their state of the world.
// is SqlAnnotatedElement -> element.annotate(annotationHolder)
}
return@processElements true
}
if (errorElements.isNotEmpty()) {
throw SqlDelightException(
"Error Reading ${it.name}:\n\n" +
errorElements.joinToString(separator = "\n") { errorMessage(it, it.errorDescription) },
)
}
body(it)
}
}
private fun errorMessage(element: PsiElement, message: String): String =
"${element.containingFile.virtualFile.path}: (${element.lineStart}, ${element.charPositionInLine}): $message\n${detailText(element)}"
private fun detailText(element: PsiElement) = try {
val context = context(element) ?: element
val result = StringBuilder()
val tokenizer = StringTokenizer(context.text, "\n", false)
val maxDigits = (log10(context.lineEnd.toDouble()) + 1).toInt()
for (line in context.lineStart..context.lineEnd) {
if (!tokenizer.hasMoreTokens()) break
result.append(("%0${maxDigits}d %s\n").format(line, tokenizer.nextToken()))
if (element.lineStart == element.lineEnd && element.lineStart == line) {
// If its an error on a single line highlight where on the line.
result.append(("%${maxDigits}s ").format(""))
if (element.charPositionInLine > 0) {
result.append(("%${element.charPositionInLine}s").format(""))
}
result.append(("%s\n").format("^".repeat(element.textLength)))
}
}
result.toString()
} catch (e: Exception) {
// If there is an exception while trying to print an error, just give back the unformatted error
// and print the stack trace for more debugging.
e.printStackTrace()
element.text
}
private val PsiElement.charPositionInLine: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return textOffset - file.getLineStartOffset(file.getLineNumber(textOffset))
}
private val PsiElement.lineStart: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return file.getLineNumber(textOffset) + 1
}
private val PsiElement.lineEnd: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return file.getLineNumber(textOffset + textLength) + 1
}
private fun context(element: PsiElement?): PsiElement? =
when (element) {
null -> element
is SqlCreateTableStmt -> element
is SqlStmt -> element
is SqlDelightImportStmt -> element
else -> context(element.parent)
}
sealed class CompilationStatus {
class Success : CompilationStatus()
class Failure(val errors: List<String>) : CompilationStatus()
}
private inner class FileIndex : SqlDelightFileIndex {
override val contentRoot
get() = throw UnsupportedOperationException("Content root only usable from IDE")
override val packageName = properties.packageName
override val className = properties.className
override val dependencies = properties.dependencies
override val isConfigured = true
override val deriveSchemaFromMigrations = properties.deriveSchemaFromMigrations
override fun outputDirectory(file: SqlDelightFile) = outputDirectories()
override fun outputDirectories(): List<String> {
return listOf(compilationUnit.outputDirectoryFile.absolutePath)
}
private val virtualDirectoriesWithDependencies: List<VirtualFile> by lazy {
return@lazy (sourceFolders + dependencyFolders)
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
}
private val directoriesWithDependencies: List<PsiDirectory> by lazy {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
return@lazy virtualDirectoriesWithDependencies.map { psiManager.findDirectory(it)!! }
}
private val virtualDirectories: List<VirtualFile> by lazy {
return@lazy sourceFolders
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
}
private val directories: List<PsiDirectory> by lazy {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
return@lazy virtualDirectories.map { psiManager.findDirectory(it)!! }
}
override fun packageName(file: SqlDelightFile): String {
fun PsiFileSystemItem.relativePathUnder(ancestor: PsiDirectory): List<String>? {
if (this.virtualFile.path == ancestor.virtualFile.path) return emptyList()
parent?.let {
return it.relativePathUnder(ancestor)?.plus(name)
}
return null
}
for (sourceFolder in sourceFolders(file)) {
val path = file.parent!!.relativePathUnder(sourceFolder)
if (path != null) return path.joinToString(separator = ".") {
SqlDelightFileIndex.sanitizeDirectoryName(
it,
)
}
}
throw IllegalStateException(
"Tried to find package name of file ${file.virtualFile!!.path} when" +
" it is not under any of the source folders $sourceFolders",
)
}
override fun sourceFolders(file: VirtualFile, includeDependencies: Boolean) =
if (includeDependencies) virtualDirectoriesWithDependencies else virtualDirectories
override fun sourceFolders(file: SqlDelightFile, includeDependencies: Boolean) =
if (includeDependencies) directoriesWithDependencies else directories
}
}
| apache-2.0 | bbe2f25b99767f8ce14ef70c432e2fe9 | 38.069364 | 137 | 0.720077 | 4.785133 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/builders/grouping/FigureTests.kt | 1 | 3125 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.vdom.builders.grouping
import jvm.katydid.vdom.api.checkBuild
import o.katydid.vdom.application.katydid
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
@Suppress("RemoveRedundantBackticks")
class FigureTests {
@Test
fun `A simple figure produces correct HTML`() {
val vdomNode = katydid<Unit> {
figure("#notmuch2it") {
pre {
text("Some preformatted code\n covering two lines")
}
figCaption {
text("This is a figure")
}
}
}
val html = """<figure id="notmuch2it">
| <pre>
| Some preformatted code
| covering two lines
| </pre>
| <figcaption>
| This is a figure
| </figcaption>
|</figure>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `A figcaption cannot appear outside a figure`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
figCaption { }
}
}
}
@Test
fun `A figure can have only one figcaption`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
figure {
figCaption { }
figCaption { }
}
}
}
}
@Test
fun `A figure can have only one figcaption even if one is nested`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
figure {
figCaption { }
div {
figCaption { }
}
}
}
}
}
@Test
fun `A figure can have only one figcaption even if both are nested`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
figure {
div {
figCaption { }
}
div {
figCaption { }
}
}
}
}
}
@Test
fun `A figure can have a nested figure with a nested caption`() {
val vdomNode = katydid<Unit> {
figure {
figCaption { text("Outer") }
figure {
figCaption { text("Inner") }
}
}
}
val html = """<figure>
| <figcaption>
| Outer
| </figcaption>
| <figure>
| <figcaption>
| Inner
| </figcaption>
| </figure>
|</figure>""".trimMargin()
checkBuild(html, vdomNode)
}
} | apache-2.0 | 3c3d95ad773fd3144f5409d2082301d8 | 17.945455 | 75 | 0.40288 | 5.278716 | false | false | false | false |
apixandru/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/SourceMap.kt | 2 | 3696 | /*
* 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.sourcemap
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Url
// sources - is not originally specified, but canonicalized/normalized
// lines and columns are zero-based according to specification
interface SourceMap {
val outFile: String?
/**
* note: Nested map returns only parent sources
*/
val sources: Array<Url>
val generatedMappings: Mappings
val hasNameMappings: Boolean
val sourceResolver: SourceResolver
fun findSourceMappings(sourceIndex: Int): Mappings
fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int
fun findSourceMappings(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Mappings? {
val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly)
return if (sourceIndex >= 0) findSourceMappings(sourceIndex) else null
}
fun getSourceLineByRawLocation(rawLine: Int, rawColumn: Int) = generatedMappings.get(rawLine, rawColumn)?.sourceLine ?: -1
fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int
fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean
fun processSourceMappingsInLine(sourceUrls: List<Url>, sourceLine: Int, mappingProcessor: MappingsProcessorInLine, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Boolean {
val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly)
return sourceIndex >= 0 && processSourceMappingsInLine(sourceIndex, sourceLine, mappingProcessor)
}
}
class OneLevelSourceMap(override val outFile: String?,
override val generatedMappings: Mappings,
private val sourceIndexToMappings: Array<MappingList?>,
override val sourceResolver: SourceResolver,
override val hasNameMappings: Boolean) : SourceMap {
override val sources: Array<Url>
get() = sourceResolver.canonicalizedUrls
override fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int {
val index = sourceResolver.findSourceIndex(sourceUrls, sourceFile, localFileUrlOnly)
if (index == -1 && resolver != null) {
return resolver.value?.let { sourceResolver.findSourceIndex(sourceFile, it) } ?: -1
}
return index
}
// returns SourceMappingList
override fun findSourceMappings(sourceIndex: Int) = sourceIndexToMappings.get(sourceIndex)!!
override fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean) = sourceResolver.findSourceIndexByFile(sourceFile, localFileUrlOnly)
override fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean {
return findSourceMappings(sourceIndex).processMappingsInLine(sourceLine, mappingProcessor)
}
} | apache-2.0 | 3a620b6f2f768273d638f56425e554c8 | 44.641975 | 218 | 0.761364 | 4.895364 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/setting/SettingsActivity.kt | 1 | 3221 | package ffc.app.setting
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.v7.preference.EditTextPreference
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.widget.Toast
import ffc.api.FfcCentral
import ffc.app.BuildConfig
import ffc.app.FamilyFolderActivity
import ffc.app.R
import org.jetbrains.anko.support.v4.toast
class SettingsActivity : FamilyFolderActivity(),
PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preference)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportFragmentManager
.beginTransaction()
.replace(R.id.contentContainer, SettingsFragment())
.commit()
}
override fun onPreferenceStartFragment(caller: PreferenceFragmentCompat, pref: Preference): Boolean {
val fragment = findPreferenceFragmentByName(pref.fragment)
fragment.arguments = pref.extras
fragment.setTargetFragment(caller, 0)
supportFragmentManager.beginTransaction()
.replace(R.id.contentContainer, fragment)
.addToBackStack(null)
.commit()
Settings.ACTION_DISPLAY_SETTINGS
return true
}
fun findPreferenceFragmentByName(name: String): PreferenceFragmentCompat {
return when (name) {
AboutActivity.AboutPreferenceFragment::class.java.name -> AboutActivity.AboutPreferenceFragment()
else -> throw IllegalArgumentException("Not found fragment")
}
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
setPreferencesFromResource(ffc.app.R.xml.pref_settings, rootKey)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
preferenceScreen.sharedPreferences.edit().putString("api_url", FfcCentral.url).apply()
with(findPreference("api_url")) {
this as EditTextPreference
summary = FfcCentral.url
text = FfcCentral.url
isVisible = BuildConfig.DEBUG
setOnPreferenceChangeListener { preference, input ->
try {
input as String
require(input.startsWith("https://")) { "must start with https://" }
FfcCentral.saveUrl(context!!, Uri.parse(input))
preference as EditTextPreference
preference.summary = input
toast("updated API address!")
return@setOnPreferenceChangeListener true
} catch (ex: IllegalArgumentException) {
Toast.makeText(context!!, "Url ${ex.message}", Toast.LENGTH_SHORT).show()
return@setOnPreferenceChangeListener false
}
}
}
}
}
}
| apache-2.0 | bb4882684770720025161caacc95f4eb | 38.280488 | 109 | 0.645452 | 5.867031 | false | false | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/activities/explorer/navigator/adapters/FilesListAdapter.kt | 1 | 2507 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.activities.explorer.navigator.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.njlabs.showjava.R
import com.njlabs.showjava.data.FileItem
import kotlinx.android.synthetic.main.layout_app_list_item.view.*
/**
* List adapter for the code navigator
*/
class FilesListAdapter(
private var fileItems: List<FileItem>,
private val itemClick: (FileItem) -> Unit
) : androidx.recyclerview.widget.RecyclerView.Adapter<FilesListAdapter.ViewHolder>() {
class ViewHolder(view: View, private val itemClick: (FileItem) -> Unit) :
androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
fun bindSourceInfo(fileItem: FileItem) {
with(fileItem) {
itemView.itemLabel.text = fileItem.name
itemView.itemSecondaryLabel.text = fileItem.fileSize
itemView.itemIcon.setImageResource(fileItem.iconResource)
itemView.itemCard.cardElevation = 1F
itemView.itemCard.setOnClickListener { itemClick(this) }
}
}
}
fun updateData(fileItems: List<FileItem>?) {
if (fileItems != null) {
this.fileItems = fileItems
notifyDataSetChanged()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.layout_app_list_item, parent, false)
return ViewHolder(view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindSourceInfo(fileItems[position])
}
override fun getItemCount(): Int {
return fileItems.size
}
}
| gpl-3.0 | c339efc3a84e88f84f6b57aafeb5efa6 | 35.333333 | 86 | 0.697647 | 4.390543 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/identification/IdentificationEvent.kt | 1 | 1877 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.identification
import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent
import org.bukkit.entity.Player
import org.bukkit.event.HandlerList
import org.bukkit.inventory.ItemStack
class IdentificationEvent(result: ItemStack, val identifier: Player) : MythicDropsCancellableEvent() {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
var isModified: Boolean = false
private set
var result: ItemStack = result
set(value) {
field = value
isModified = true
}
override fun getHandlers(): HandlerList = handlerList
}
| mit | 69434c8f8f7ded0b6f31463c8b7291f5 | 41.659091 | 105 | 0.747469 | 4.788265 | false | false | false | false |
Undin/intellij-rust | coverage/src/main/kotlin/org/rust/coverage/RsCoverageRunner.kt | 3 | 3185 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.coverage
import com.intellij.coverage.CoverageEngine
import com.intellij.coverage.CoverageRunner
import com.intellij.coverage.CoverageSuite
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.rt.coverage.data.LineData
import com.intellij.rt.coverage.data.ProjectData
import org.rust.coverage.LcovCoverageReport.Serialization.readLcov
import org.rust.openapiext.computeWithCancelableProgress
import org.rust.openapiext.isDispatchThread
import java.io.File
import java.io.IOException
class RsCoverageRunner : CoverageRunner() {
override fun getPresentableName(): String = "Rust"
override fun getDataFileExtension(): String = "info"
override fun getId(): String = "RsCoverageRunner"
override fun acceptsCoverageEngine(engine: CoverageEngine): Boolean = engine is RsCoverageEngine
override fun loadCoverageData(sessionDataFile: File, baseCoverageSuite: CoverageSuite?): ProjectData? {
if (baseCoverageSuite !is RsCoverageSuite) return null
return try {
if (isDispatchThread) {
baseCoverageSuite.project.computeWithCancelableProgress("Loading Coverage Data...") {
readProjectData(sessionDataFile, baseCoverageSuite)
}
} else {
readProjectData(sessionDataFile, baseCoverageSuite)
}
} catch (e: IOException) {
LOG.warn("Can't read coverage data", e)
null
}
}
companion object {
private val LOG: Logger = logger<RsCoverageRunner>()
@Throws(IOException::class)
private fun readProjectData(dataFile: File, coverageSuite: RsCoverageSuite): ProjectData? {
val coverageProcess = coverageSuite.coverageProcess
// coverageProcess == null means that we are switching to data gathered earlier
if (coverageProcess != null) {
repeat(100) {
ProgressManager.checkCanceled()
if (coverageProcess.waitFor(100)) return@repeat
}
if (!coverageProcess.isProcessTerminated) {
coverageProcess.destroyProcess()
return null
}
}
val projectData = ProjectData()
val report = readLcov(dataFile, coverageSuite.contextFilePath)
for ((filePath, lineHitsList) in report.records) {
val classData = projectData.getOrCreateClassData(filePath)
val max = lineHitsList.lastOrNull()?.lineNumber ?: 0
val lines = arrayOfNulls<LineData>(max + 1)
for (lineHits in lineHitsList) {
val lineData = LineData(lineHits.lineNumber, null)
lineData.hits = lineHits.hits
lines[lineHits.lineNumber] = lineData
}
classData.setLines(lines)
}
return projectData
}
}
}
| mit | d76f794bdc56a8304c1f678ef5cf2d4b | 37.841463 | 107 | 0.646154 | 5.055556 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/inspections/RsAssignToImmutableInspectionTest.kt | 2 | 3984 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import org.rust.ExpandMacros
import org.rust.ProjectDescriptor
import org.rust.WithStdlibRustProjectDescriptor
import org.rust.lang.core.macros.MacroExpansionScope
class RsAssignToImmutableInspectionTest : RsInspectionsTestBase(RsAssignToImmutableInspection::class) {
fun `test E0594 assign to immutable borrowed content`() = checkByText("""
fn main() {
let mut y = 1;
let x = &y;
<error descr="Cannot assign to immutable borrowed content [E0594]">*x = 2</error>;
}
""")
fun `test E0594 assign to immutable borrowed content with parentheses`() = checkByText("""
fn main() {
let mut y = 1;
let x = &y;
<error descr="Cannot assign to immutable borrowed content [E0594]">((*x)) = 2</error>;
}
""")
fun `test E0594 assign to immutable borrowed content of literal`() = checkByText("""
fn main() {
let foo = &16;
<error descr="Cannot assign to immutable borrowed content [E0594]">*foo = 32</error>;
}
""")
fun `test E0594 assign to mutable field of immutable binding`() = checkByText("""
struct Foo { a: i32 }
fn main() {
let mut foo = Foo { a: 1 };
let x = &foo;
<error descr="Cannot assign to field of immutable binding [E0594]">x.a = 2</error>;
}
""")
fun `test E0594 assign to immutable field of immutable binding`() = checkByText("""
struct Foo { a: i32 }
fn main() {
let foo = Foo { a: 1 };
let x = &foo;
<error descr="Cannot assign to field of immutable binding [E0594]">x.a = 2</error>;
}
""")
fun `test E0594 assign to field of immutable binding`() = checkByText("""
struct Foo { a: i32 }
fn main() {
let foo = Foo { a: 1 };
<error descr="Cannot assign to field of immutable binding [E0594]">foo.a = 2</error>;
}
""")
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test E0594 assign to field of immutable binding while iterating`() = checkByText("""
struct Foo { a: i32 }
fn main() {
let mut foos: [Foo; 1] = [Foo { a: 1 }];
for foo in foos.iter() {
<error descr="Cannot assign to field of immutable binding [E0594]">foo.a = 2</error>;
}
}
""")
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
fun `test E0594 assign to indexed content of immutable binding`() = checkByText("""
fn main() {
let a: [i32; 3] = [0; 3];
<error descr="Cannot assign to indexed content of immutable binding [E0594]">a[1] = 5</error>;
}
""")
fun `test E0594 assign to immutable dereference of raw pointer`() = checkByText("""
struct Foo { a: i32 }
fn main() {}
unsafe fn f() {
let x = 5;
let p = &x as *const i32;
<error descr="Cannot assign to immutable dereference of raw pointer [E0594]">*p = 1</error>;
}
""")
fun `test assign to index expr of unknown type`() = checkByText("""
fn main() {
let xs = &mut unknownType;
xs[0] = 1;
}
""")
fun `test assign to field of expr of unknown type`() = checkByText("""
fn foo(x: &mut Unknown) {
x.a = 1;
}
""")
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
fun `test no E0594 for mutable generic slice of Copy types`() = checkByText("""
fn swap<T>(index_a: usize, index_b: usize, arr: &mut [T]) where T: Copy {
let temp = arr[index_a];
arr[index_a] = arr[index_b];
arr[index_b] = temp;
}
""")
}
| mit | a9ba7f6d6b772819d6ddead50e7fbf1f | 33.643478 | 106 | 0.560994 | 4.137072 | false | true | false | false |
colesadam/hill-lists | app/src/main/java/uk/colessoft/android/hilllist/domain/entity/Hill.kt | 1 | 6117 | package uk.colessoft.android.hilllist.domain.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
@Entity(tableName = "hills")
data class Hill(
@PrimaryKey val h_id: Long,
@ColumnInfo(name = "Name") val hillname: String?,
@ColumnInfo(name = "Parent (SMC)") val parentSMC: String?,
@ColumnInfo(name = "Parent name (SMC)") val parentnameSMC: String?,
@ColumnInfo(name = "Section") val hSection: String?,
@ColumnInfo(name = "Section name") val sectionname: String?,
@ColumnInfo(name = "Area") val area: String?,
@ColumnInfo(name = "Island") val island: String?,
@ColumnInfo(name = "Topo Section") val topoSection: String?,
@ColumnInfo(name = "County") val county: String?,
@ColumnInfo(name = "Classification") val classification: String?,
@ColumnInfo(name = "Map 1:50k") val map: String?,
@ColumnInfo(name = "Map 1:25k") val map25: String?,
@ColumnInfo(name = "Metres") val heightm: Float?,
@ColumnInfo(name = "Feet") val heightf: Float?,
@ColumnInfo(name = "Grid ref") val gridref: String?,
@ColumnInfo(name = "Grid ref 10") val gridref10: String?,
@ColumnInfo(name = "Drop") val drop: Float?,
@ColumnInfo(name = "Col grid ref") val colgridref: String?,
@ColumnInfo(name = "Col height") val colheight: Float?,
@ColumnInfo(name = "Feature") val feature: String?,
@ColumnInfo(name = "Observations") val observations: String?,
@ColumnInfo(name = "Survey") val survey: String?,
@ColumnInfo(name = "Climbed") val climbed: String?,
@ColumnInfo(name = "Country") val country: String?,
@ColumnInfo(name = "County Top") val countyTop: String?,
@ColumnInfo(name = "Revision") val revision: String?,
@ColumnInfo(name = "Comments") val comments: String?,
@ColumnInfo(name = "Streetmap/OSiViewer") val streetmap: String?,
@ColumnInfo(name = "Geograph/MountainViews") val geographMountainViews: String?,
@ColumnInfo(name = "HillDetail-bagging") val hillBagging: String?,
@ColumnInfo(name = "Xcoord") val xcoord: Int?,
@ColumnInfo(name = "Ycoord") val ycoord: Int?,
@ColumnInfo(name = "Latitude") val latitude: Double?,
@ColumnInfo(name = "Longitude") val longitude: Double?,
@ColumnInfo(name = "GridrefXY") val gridrefXY: String?,
@ColumnInfo(name = "_Section") val _section: String?,
@ColumnInfo(name = "Parent (Ma)") val parentMa: String?,
@ColumnInfo(name = "Parent name (Ma)") val parentnameMa: String?,
@ColumnInfo(name = "MVNumber") val mVNumber: String?,
@ColumnInfo(name = "Ma") val ma: String?,
@ColumnInfo(name = "Ma=") val maTop: String?,
@ColumnInfo(name = "Hu") val hu: String?,
@ColumnInfo(name = "Hu=") val huTop: String?,
@ColumnInfo(name = "Tu") val tu: String?,
@ColumnInfo(name = "Tu=") val tuTop: String?,
@ColumnInfo(name = "Sim") val sim: String?,
@ColumnInfo(name = "M") val m: String?,
@ColumnInfo(name = "MT") val mT: String?,
@ColumnInfo(name = "F") val f: String?,
@ColumnInfo(name = "C") val c: String?,
@ColumnInfo(name = "G") val g: String?,
@ColumnInfo(name = "D") val d: String?,
@ColumnInfo(name = "DT") val dT: String?,
@ColumnInfo(name = "Mur") val mur: String?,
@ColumnInfo(name = "CT") val cT: String?,
@ColumnInfo(name = "GT") val gT: String?,
@ColumnInfo(name = "Hew") val hew: String?,
@ColumnInfo(name = "N") val n: String?,
@ColumnInfo(name = "5") val five: String?,
@ColumnInfo(name = "5D") val fiveD: String?,
@ColumnInfo(name = "5H") val fiveH: String?,
@ColumnInfo(name = "4") val four: String?,
@ColumnInfo(name = "3") val three: String?,
@ColumnInfo(name = "2") val two: String?,
@ColumnInfo(name = "1") val one: String?,
@ColumnInfo(name = "1=") val oneTop: String?,
@ColumnInfo(name = "0") val zero: String?,
@ColumnInfo(name = "W") val w: String?,
@ColumnInfo(name = "WO") val wO: String?,
@ColumnInfo(name = "B") val b: String?,
@ColumnInfo(name = "CoH") val coH: String?,
@ColumnInfo(name = "CoH=") val coHTop: String?,
@ColumnInfo(name = "CoU") val coU: String?,
@ColumnInfo(name = "CoU=") val coUTop: String?,
@ColumnInfo(name = "CoA") val coA: String?,
@ColumnInfo(name = "CoA=") val coATop: String?,
@ColumnInfo(name = "CoL") val coL: String?,
@ColumnInfo(name = "CoL=") val coLTop: String?,
@ColumnInfo(name = "SIB") val sIB: String?,
@ColumnInfo(name = "sMa") val sMa: String?,
@ColumnInfo(name = "sHu") val sHu: String?,
@ColumnInfo(name = "sSim") val sSim: String?,
@ColumnInfo(name = "s5") val s5: String?,
@ColumnInfo(name = "s5D") val s5D: String?,
@ColumnInfo(name = "s5H") val s5H: String?,
@ColumnInfo(name = "s5M") val s5M: String?,
@ColumnInfo(name = "s4") val s4: String?,
@ColumnInfo(name = "Sy") val sy: String?,
@ColumnInfo(name = "Fel") val fel: String?,
@ColumnInfo(name = "BL") val bL: String?,
@ColumnInfo(name = "Bg") val bg: String?,
@ColumnInfo(name = "T100") val t100: String?,
@ColumnInfo(name = "xMT") val xMT: String?,
@ColumnInfo(name = "xC") val xC: String?,
@ColumnInfo(name = "xG") val xG: String?,
@ColumnInfo(name = "xN") val xN: String?,
@ColumnInfo(name = "xDT") val xDT: String?,
@ColumnInfo(name = "Dil") val dil: String?,
@ColumnInfo(name = "VL") val vL: String?,
@ColumnInfo(name = "A") val a: String?,
@ColumnInfo(name = "5M") val fiveM: String?,
@ColumnInfo(name = "Ca") val ca: String?,
@ColumnInfo(name = "Bin") val bin: String?,
@ColumnInfo(name = "O") val o: String?,
@ColumnInfo(name = "Un") val un: String?)
| mit | 97dbff6cbbacfbded7878a217f52f70c | 50.838983 | 88 | 0.589341 | 3.581382 | false | false | false | false |
Senspark/ee-x | src/android/notification/src/main/java/com/ee/NotificationBridge.kt | 1 | 3908 | package com.ee
import android.app.Activity
import android.app.Application
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.annotation.AnyThread
import com.ee.internal.NotificationReceiver
import com.ee.internal.NotificationUtils
import com.ee.internal.deserialize
import kotlinx.serialization.Serializable
/**
* Created by Zinge on 3/29/17.
*/
class NotificationBridge(
private val _bridge: IMessageBridge,
private val _logger: ILogger,
private val _application: Application,
private var _activity: Activity?) : IPlugin {
companion object {
private val kTag = NotificationBridge::class.java.name
private const val kPrefix = "NotificationBridge"
private const val kSchedule = "${kPrefix}Schedule"
private const val kUnschedule = "${kPrefix}Unschedule"
private const val kUnscheduleAll = "${kPrefix}UnscheduleAll"
private const val kClearAll = "${kPrefix}ClearAll"
}
init {
_logger.info("$kTag: constructor begin: application = $_application activity = $_activity")
registerHandlers()
_logger.info("$kTag: constructor end")
}
override fun onCreate(activity: Activity) {
_activity = activity
}
override fun onStart() {}
override fun onStop() {}
override fun onResume() {}
override fun onPause() {}
override fun onDestroy() {
_activity = null
}
override fun destroy() {
deregisterHandlers()
}
@Serializable
private class ScheduleRequest(
val title: String,
val ticker: String,
val body: String,
val delay: Int,
val interval: Int,
val tag: Int
)
@Serializable
private class UnscheduleRequest(
val tag: Int
)
@AnyThread
private fun registerHandlers() {
_bridge.registerHandler(kSchedule) { message ->
val request = deserialize<ScheduleRequest>(message)
schedule(request.ticker, request.title, request.body, request.delay, request.interval, request.tag)
""
}
_bridge.registerHandler(kUnscheduleAll) {
unscheduleAll()
""
}
_bridge.registerHandler(kUnschedule) { message ->
val request = deserialize<UnscheduleRequest>(message)
unschedule(request.tag)
""
}
_bridge.registerHandler(kClearAll) {
clearAll()
""
}
}
@AnyThread
private fun deregisterHandlers() {
_bridge.deregisterHandler(kSchedule)
_bridge.deregisterHandler(kUnscheduleAll)
_bridge.deregisterHandler(kUnschedule)
_bridge.deregisterHandler(kClearAll)
}
fun schedule(ticker: String, title: String, body: String, delay: Int, interval: Int, tag: Int) {
val activity = _activity ?: return
val intent = Intent(_application, NotificationReceiver::class.java)
intent.putExtra("ticker", ticker)
intent.putExtra("title", title)
intent.putExtra("body", body)
intent.putExtra("tag", tag)
intent.putExtra("className", activity::class.java.name)
NotificationUtils.scheduleAlarm(_application, intent, tag, PendingIntent.FLAG_UPDATE_CURRENT,
delay, interval)
}
fun unschedule(tag: Int) {
_logger.debug("$kTag: ${this::unschedule.name}: tag = $tag")
val intent = Intent(_application, NotificationReceiver::class.java)
NotificationUtils.unscheduleAlarm(_application, intent, tag)
}
fun unscheduleAll() {
_logger.debug("$kTag: ${this::unscheduleAll.name}: not supported.")
}
fun clearAll() {
val manager = _application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.cancelAll()
}
} | mit | 958f967743a0bd55d5e1495b594461c0 | 30.02381 | 111 | 0.648925 | 4.657926 | false | false | false | false |
stuartcarnie/toml-plugin | src/main/kotlin/org/toml/lang/colorscheme/TomlColorSettingsPage.kt | 1 | 1662 | package org.toml.lang.colorscheme
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import com.intellij.openapi.util.io.StreamUtil
import org.toml.lang.TomlHighlighter
import org.toml.lang.icons.TomlIcons
public class TomlColorSettingsPage : ColorSettingsPage {
private fun d(displayName: String, key: TextAttributesKey) = AttributesDescriptor(displayName, key)
private val ATTRS = arrayOf(
d("Key", TomlColors.KEY),
d("String", TomlColors.STRING),
d("Number", TomlColors.NUMBER),
d("Boolean", TomlColors.BOOLEAN),
d("Date", TomlColors.DATE),
d("Line comment", TomlColors.LINE_COMMENT),
d("Brackets", TomlColors.BRACKETS),
d("Braces", TomlColors.BRACES),
d("Comma", TomlColors.COMMA)
)
// This tags should be kept in sync with RustAnnotator highlighting logic
private val DEMO_TEXT by lazy {
val stream = javaClass.classLoader.getResourceAsStream("org/toml/lang/colorscheme/highlighterDemoText.toml")
StreamUtil.readText(stream, "UTF-8")
}
override fun getDisplayName() = "Toml"
override fun getIcon() = TomlIcons.TOML
override fun getAttributeDescriptors() = ATTRS
override fun getColorDescriptors() = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter() = TomlHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap() = null
override fun getDemoText() = DEMO_TEXT
}
| mit | 09ae76993f565de5e8ef4f2a1f057ec7 | 42.736842 | 116 | 0.72142 | 4.642458 | false | false | false | false |
brave-warrior/TravisClient_Android | app-v3/src/main/java/com/khmelenko/lab/varis/log/AnsiParser.kt | 2 | 3534 | package com.khmelenko.lab.varis.log
import java.util.Stack
/**
* Parser for ANSI escape sequences.
*
* @see [Wikipedia](https://en.wikipedia.org/wiki/ANSI_escape_code)
*/
internal class AnsiParser {
private val result = Stack<TextLeaf>()
private var options = FormattingOptions.fromAnsiCodes()
/**
* @see .parseText
*/
private fun parse(inputText: String): Stack<TextLeaf> {
var text = inputText
// Remove character when followed by a BACKSPACE character
while (text.contains("\b")) {
text = text.replace("^\b+|[^\b]\b".toRegex(), "")
}
var controlStartPosition: Int
var lastControlPosition = 0
var controlEndPosition: Int
while (true) {
controlStartPosition = text.indexOf("\u001b[", lastControlPosition)
if (controlStartPosition == -1) {
break
}
val textBeforeEscape = text.substring(lastControlPosition, controlStartPosition)
emitText(textBeforeEscape)
if (isResetLineEscape(text, controlStartPosition)) {
controlEndPosition = text.indexOf('K', controlStartPosition + 2)
removeCurrentLine()
options = FormattingOptions.fromAnsiCodes()
} else {
controlEndPosition = text.indexOf('m', controlStartPosition + 2)
if (controlEndPosition == -1) {
break
}
val matchingData = text.substring(controlStartPosition + 2, controlEndPosition)
val ansiStates = matchingData.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
options = FormattingOptions.fromAnsiCodes(*ansiStates)
}
lastControlPosition = controlEndPosition + 1
}
emitText(text.substring(lastControlPosition))
if (result.isEmpty()) {
result.push(TextLeaf())
}
return result
}
private fun emitText(text: String) {
if (!text.isEmpty()) {
result.push(TextLeaf(text, options))
}
}
private fun removeCurrentLine() {
if (result.isEmpty()) {
return
}
var textLeaf = result.peek()
var i: Int
while (true) {
i = Math.max(textLeaf.text.lastIndexOf("\r"), textLeaf.text.lastIndexOf("\n"))
if (i != -1) {
break
}
result.pop()
if (result.isEmpty()) {
break
}
textLeaf = result.peek()
}
if (textLeaf.text.length > i && i > 0) {
val end = textLeaf.text.substring(i - 1, i + 1)
textLeaf.text = textLeaf.text.substring(0, i)
if (end == "\r\n" || end == "\n\r") {
textLeaf.text = textLeaf.text.substring(0, i - 1)
}
} else {
textLeaf.text = ""
}
}
private fun isResetLineEscape(str: String, controlStartPosition: Int): Boolean {
val substring = str.substring(controlStartPosition)
return substring.startsWith("\u001b[0K") || substring.startsWith("\u001b[K")
}
companion object {
/**
* Parses the given log for ANSI escape sequences and builds a list of text chunks, which
* share the same color and text formatting.
*/
fun parseText(text: String): Stack<TextLeaf> {
return AnsiParser().parse(text)
}
}
}
| apache-2.0 | d5fe5a3c8a372f7bec9e1a7c37539cef | 31.127273 | 112 | 0.551783 | 4.524968 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentTransitionAnimTest.kt | 3 | 13100 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.os.Build
import android.transition.ChangeBounds
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.annotation.AnimRes
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
class FragmentTransitionAnimTest(
private val reorderingAllowed: ReorderingAllowed,
) {
private var onBackStackChangedTimes: Int = 0
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Before
fun setup() {
onBackStackChangedTimes = 0
}
// Ensure when transition duration is shorter than animation duration, we will get both end
// callbacks
@Test
fun transitionShorterThanAnimation() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fragment = TransitionAnimationFragment()
fragment.exitTransition.duration = 100
val fragmentManager = withActivity { supportFragmentManager }
fragmentManager.addOnBackStackChangedListener { onBackStackChangedTimes++ }
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
.add(R.id.fragmentContainer, fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
assertThat(onBackStackChangedTimes).isEqualTo(1)
fragment.waitForTransition()
val blue = withActivity { findViewById<View>(R.id.blueSquare) }
val green = withActivity { findViewById<View>(R.id.greenSquare) }
fragment.enterTransition.verifyAndClearTransition {
enteringViews += listOf(blue, green)
}
verifyNoOtherTransitions(fragment)
val changeBoundsExitTransition = ChangeBounds().apply {
duration = 100
}
fragment.setExitTransition(changeBoundsExitTransition)
changeBoundsExitTransition.addListener(fragment.listener)
// exit transition
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
.remove(fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
val startAnimationRan = fragment.startAnimationLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(startAnimationRan).isFalse()
fragment.waitForTransition()
val exitAnimationRan = fragment.exitAnimationLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(exitAnimationRan).isFalse()
assertThat(onBackStackChangedTimes).isEqualTo(2)
}
}
// Ensure when transition duration is longer than animation duration, we will get both end
// callbacks
@Test
fun transitionLongerThanAnimation() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fragment = TransitionAnimationFragment()
fragment.exitTransition.duration = 1000
val fragmentManager = withActivity { supportFragmentManager }
fragmentManager.addOnBackStackChangedListener { onBackStackChangedTimes++ }
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
.add(R.id.fragmentContainer, fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
assertThat(onBackStackChangedTimes).isEqualTo(1)
fragment.waitForTransition()
val blue = withActivity { findViewById<View>(R.id.blueSquare) }
val green = withActivity { findViewById<View>(R.id.greenSquare) }
fragment.enterTransition.verifyAndClearTransition {
enteringViews += listOf(blue, green)
}
verifyNoOtherTransitions(fragment)
val changeBoundsExitTransition = ChangeBounds().apply {
duration = 1000
}
fragment.setExitTransition(changeBoundsExitTransition)
changeBoundsExitTransition.addListener(fragment.listener)
// exit transition
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
.remove(fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
val startAnimationRan = fragment.startAnimationLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(startAnimationRan).isFalse()
fragment.waitForTransition()
val exitAnimationRan = fragment.exitAnimationLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(exitAnimationRan).isFalse()
assertThat(onBackStackChangedTimes).isEqualTo(2)
}
}
// Ensure when transition duration is shorter than animator duration, we will get both end
// callbacks
@Test
fun transitionShorterThanAnimator() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fragment = TransitionAnimatorFragment()
fragment.exitTransition.duration = 100
val fragmentManager = withActivity { supportFragmentManager }
fragmentManager.addOnBackStackChangedListener { onBackStackChangedTimes++ }
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(ENTER, EXIT)
.add(R.id.fragmentContainer, fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
assertThat(onBackStackChangedTimes).isEqualTo(1)
fragment.waitForTransition()
val blue = withActivity { findViewById<View>(R.id.blueSquare) }
val green = withActivity { findViewById<View>(R.id.greenSquare) }
fragment.enterTransition.verifyAndClearTransition {
enteringViews += listOf(blue, green)
}
verifyNoOtherTransitions(fragment)
val changeBoundsExitTransition = ChangeBounds().apply {
duration = 100
}
fragment.setExitTransition(changeBoundsExitTransition)
changeBoundsExitTransition.addListener(fragment.listener)
// exit transition
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(ENTER, EXIT)
.remove(fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
fragment.waitForTransition()
val exitAnimatorRan = fragment.exitAnimatorLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(exitAnimatorRan).isFalse()
assertThat(onBackStackChangedTimes).isEqualTo(2)
}
}
// Ensure when transition duration is longer than animator duration, we will get both end
// callbacks
@Test
fun transitionLongerThanAnimator() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fragment = TransitionAnimatorFragment()
fragment.exitTransition.duration = 1000
val fragmentManager = withActivity { supportFragmentManager }
fragmentManager.addOnBackStackChangedListener { onBackStackChangedTimes++ }
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(ENTER, EXIT)
.add(R.id.fragmentContainer, fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
assertThat(onBackStackChangedTimes).isEqualTo(1)
fragment.waitForTransition()
val blue = withActivity { findViewById<View>(R.id.blueSquare) }
val green = withActivity { findViewById<View>(R.id.greenSquare) }
fragment.enterTransition.verifyAndClearTransition {
enteringViews += listOf(blue, green)
}
verifyNoOtherTransitions(fragment)
val changeBoundsExitTransition = ChangeBounds().apply {
duration = 1000
}
fragment.setExitTransition(changeBoundsExitTransition)
changeBoundsExitTransition.addListener(fragment.listener)
// exit transition
fragmentManager.beginTransaction()
.setReorderingAllowed(reorderingAllowed)
.setCustomAnimations(ENTER, EXIT)
.remove(fragment)
.addToBackStack(null)
.commit()
executePendingTransactions()
fragment.waitForTransition()
val exitAnimatorRan = fragment.exitAnimatorLatch.await(
TIMEOUT,
TimeUnit.MILLISECONDS
)
assertThat(exitAnimatorRan).isFalse()
assertThat(onBackStackChangedTimes).isEqualTo(2)
}
}
class TransitionAnimationFragment : TransitionFragment(R.layout.scene1) {
val startAnimationLatch = CountDownLatch(1)
val exitAnimationLatch = CountDownLatch(1)
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
if (nextAnim == 0) {
return null
}
return AnimationUtils.loadAnimation(activity, nextAnim).apply {
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
startAnimationLatch.countDown()
}
override fun onAnimationEnd(animation: Animation) {
if (!enter) {
exitAnimationLatch.countDown()
}
}
override fun onAnimationRepeat(animation: Animation) {}
})
}
}
}
class TransitionAnimatorFragment : TransitionFragment(R.layout.scene1) {
val exitAnimatorLatch = CountDownLatch(1)
override fun onCreateAnimator(
transit: Int,
enter: Boolean,
nextAnim: Int
) = ValueAnimator.ofFloat(0f, 1f).setDuration(300)?.apply {
if (nextAnim == 0) {
return null
}
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
if (!enter) {
exitAnimatorLatch.countDown()
}
}
})
}
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "ordering={0}")
fun data() = mutableListOf<Array<Any>>().apply {
arrayOf(
Ordered,
Reordered
)
}
@AnimRes
private val ENTER = 1
@AnimRes
private val EXIT = 2
private const val TIMEOUT = 1000L
}
} | apache-2.0 | 31c03f42960b9b621133eccba2ebf798 | 35.594972 | 97 | 0.624504 | 5.750658 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/hover/KotlinTextHover.kt | 1 | 4119 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.hover
import com.intellij.psi.util.PsiTreeUtil
import org.eclipse.jdt.internal.ui.text.JavaWordFinder
import org.eclipse.jface.text.IInformationControlCreator
import org.eclipse.jface.text.IRegion
import org.eclipse.jface.text.ITextHover
import org.eclipse.jface.text.ITextHoverExtension
import org.eclipse.jface.text.ITextHoverExtension2
import org.eclipse.jface.text.ITextViewer
import org.eclipse.jface.text.Region
import org.jetbrains.kotlin.core.model.loadExecutableEP
import org.jetbrains.kotlin.eclipse.ui.utils.findElementByDocumentOffset
import org.jetbrains.kotlin.eclipse.ui.utils.getOffsetByDocument
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.ui.editors.KotlinEditor
import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor
const val TEXT_HOVER_EP_ID = "org.jetbrains.kotlin.ui.editor.textHover"
class KotlinTextHover(private val editor: KotlinEditor) : ITextHover, ITextHoverExtension, ITextHoverExtension2 {
val extensionsHovers = loadExecutableEP<KotlinEditorTextHover<*>>(TEXT_HOVER_EP_ID).mapNotNull { it.createProvider() }
private var hoverData: HoverData? = null
private var bestHover: KotlinEditorTextHover<*>? = null
override fun getHoverRegion(textViewer: ITextViewer, offset: Int): IRegion? {
return JavaWordFinder.findWord(textViewer.getDocument(), offset)
}
override fun getHoverInfo(textViewer: ITextViewer?, hoverRegion: IRegion): String? {
return getHoverInfo2(textViewer, hoverRegion)?.toString()
}
override fun getHoverControlCreator(): IInformationControlCreator? {
return bestHover?.getHoverControlCreator(editor)
}
override fun getHoverInfo2(textViewer: ITextViewer?, hoverRegion: IRegion): Any? {
val data: HoverData = createHoverData(hoverRegion.offset) ?: return null
bestHover = null
var hoverInfo: Any? = null
for (hover in extensionsHovers) {
if (hover.isAvailable(data)) {
hoverInfo = hover.getHoverInfo(data)
if (hoverInfo != null) {
bestHover = hover
break
}
}
}
return hoverInfo
}
private fun createHoverData(offset: Int): HoverData? {
val ktFile = editor.parsedFile ?: return null
val psiElement = ktFile.findElementByDocumentOffset(offset, editor.document) ?: return null
val ktElement = PsiTreeUtil.getParentOfType(psiElement, KtElement::class.java) ?: return null
return HoverData(ktElement, editor)
}
}
interface KotlinEditorTextHover<out Info> {
fun getHoverInfo(hoverData: HoverData): Info?
fun isAvailable(hoverData: HoverData): Boolean
fun getHoverControlCreator(editor: KotlinEditor): IInformationControlCreator?
}
data class HoverData(val hoverElement: KtElement, val editor: KotlinEditor)
fun HoverData.getRegion(): Region? {
val (element, editor) = this
val psiTextRange = element.getTextRange()
val document = if (editor is KotlinCommonEditor) editor.getDocumentSafely() else editor.document
if (document == null) return null
val startOffset = element.getOffsetByDocument(document, psiTextRange.startOffset)
return Region(startOffset, psiTextRange.length)
} | apache-2.0 | f4d8d1f3808f7f03e82488429d6eaa9d | 39 | 122 | 0.700898 | 4.377258 | false | false | false | false |
google/android-auto-companion-android | calendarsync/tests/unit/src/com/google/android/libraries/car/calendarsync/feature/CalendarSyncManagerNoPermissionTest.kt | 1 | 2583 | // Copyright 2021 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.android.libraries.car.calendarsync.feature
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.connecteddevice.calendarsync.proto.Calendars
import com.google.android.libraries.car.calendarsync.feature.repository.CalendarRepository
import com.google.android.libraries.car.trustagent.Car
import com.google.common.time.testing.FakeTimeSource
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import java.time.Clock
import java.util.UUID
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
private val CAR_ID = UUID.fromString("eefeb989-e593-4a50-a2c7-623dbfc408f4")
@RunWith(AndroidJUnit4::class)
class CalendarSyncManagerNoPermissionTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val mockCar: Car = mock {
on { deviceId } doReturn CAR_ID
}
private lateinit var calendarSyncManager: CalendarSyncManager
private lateinit var fakeTimeSource: FakeTimeSource
private lateinit var mockCalendarRepository: CalendarRepository
@Before
fun setUp() {
mockCalendarRepository = mock()
fakeTimeSource = FakeTimeSource.create()
whenever(
mockCalendarRepository.getCalendars(any(), any())
) doReturn Calendars.getDefaultInstance()
calendarSyncManager = CalendarSyncManager(
context,
mockCalendarRepository,
Clock.systemDefaultZone()
)
}
@Test
fun permissionNotGranted_doesNotSync() {
calendarSyncManager.enableCar(CAR_ID)
calendarSyncManager.setCalendarIdsToSync(setOf("1234", "5678"), CAR_ID)
calendarSyncManager.notifyCarConnected(mockCar)
Mockito.verify(mockCar, Mockito.never()).sendMessage(anyOrNull(), anyOrNull())
}
}
| apache-2.0 | 198b17b856edce3df362e8df17b2a784 | 33.905405 | 90 | 0.787456 | 4.46114 | false | true | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/editor/formatter/blocks/LuaParenExprBlock.kt | 2 | 1630 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.editor.formatter.blocks
import com.intellij.formatting.Alignment
import com.intellij.formatting.ChildAttributes
import com.intellij.formatting.Indent
import com.intellij.formatting.Wrap
import com.intellij.psi.PsiElement
import com.tang.intellij.lua.editor.formatter.LuaFormatContext
import com.tang.intellij.lua.psi.LuaParenExpr
import com.tang.intellij.lua.psi.LuaTypes
class LuaParenExprBlock(psi: LuaParenExpr, wrap: Wrap?, alignment: Alignment?, indent: Indent, ctx: LuaFormatContext)
: LuaScriptBlock(psi, wrap, alignment, indent, ctx) {
override fun buildChild(child: PsiElement, indent: Indent?): LuaScriptBlock {
if (child.node.elementType == LuaTypes.LPAREN || child.node.elementType == LuaTypes.RPAREN)
return super.buildChild(child, indent)
return super.buildChild(child, Indent.getContinuationIndent())
}
override fun getChildAttributes(newChildIndex: Int) =
ChildAttributes(Indent.getContinuationIndent(), null)
} | apache-2.0 | c16bd4a38947433ece9c7068b67c4194 | 40.820513 | 117 | 0.760123 | 4.085213 | false | false | false | false |
MaTriXy/android-topeka | app/src/main/java/com/google/samples/apps/topeka/helper/AnswerHelper.kt | 1 | 1951 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.helper
import android.util.SparseBooleanArray
/**
* Collection of methods to convert answers to human readable forms.
*/
object AnswerHelper {
val SEPARATOR: String = System.getProperty("line.separator")
/**
* Converts an array of answers to a readable answer.
* @param answers The answers to display.
*
* @return The readable answer.
*/
fun getReadableAnswer(answers: Array<String>): String {
val readableAnswer = StringBuilder()
//Iterate over all answers
answers.indices.forEach {
val answer = answers[it]
readableAnswer.append(answer)
//Don't add a separator for the last answer
if (it < answers.size - 1) {
readableAnswer.append(SEPARATOR)
}
}
return readableAnswer.toString()
}
/**
* Checks whether a provided answer is correct.
* @param checkedItems The items that were selected.
*
* @param answerIds The actual correct answer ids.
*
* @return `true` if correct else `false`.
*/
fun isAnswerCorrect(checkedItems: SparseBooleanArray, answerIds: IntArray): Boolean {
return if (answerIds.any { checkedItems.indexOfKey(it) < 0 }) false
else checkedItems.size() == answerIds.size
}
} | apache-2.0 | 55c2497839c5aec1bb73111a51c7c3a4 | 29.984127 | 89 | 0.66325 | 4.444191 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/music/search/YoutubeCommand.kt | 1 | 4403 | package xyz.gnarbot.gnar.commands.music.search
import com.jagrosh.jdautilities.selector
import xyz.gnarbot.gnar.commands.*
import xyz.gnarbot.gnar.commands.music.embedTitle
import xyz.gnarbot.gnar.music.MusicLimitException
import xyz.gnarbot.gnar.music.TrackContext
import xyz.gnarbot.gnar.utils.Utils
import java.awt.Color
@Command(
aliases = ["youtube", "yt"],
usage = "(query...)",
description = "Search and see YouTube results."
)
@BotInfo(
id = 64,
scope = Scope.TEXT,
category = Category.MUSIC
)
class YoutubeCommand : xyz.gnarbot.gnar.commands.CommandExecutor() {
override fun execute(context: Context, label: String, args: Array<String>) {
if (!context.bot.configuration.searchEnabled) {
context.send().error("Search is currently disabled. Try direct links instead.").queue()
return
}
if (args.isEmpty()) {
context.send().error("Input a query to search YouTube.").queue()
return
}
val query = args.joinToString(" ")
context.bot.players.get(context.guild).search("ytsearch:$query", 5) { results ->
if (results.isEmpty()) {
context.send().error("No search results for `$query`.").queue()
return@search
}
val botChannel = context.selfMember.voiceState?.channel
val userChannel = context.guild.getMember(context.message.author)?.voiceState?.channel
if (!context.bot.configuration.musicEnabled || userChannel == null || botChannel != null && botChannel != userChannel) {
context.send().embed {
setAuthor("YouTube Results", "https://www.youtube.com", "https://www.youtube.com/favicon.ico")
thumbnail { "https://octave.gg/assets/img/youtube.png" }
color { Color(141, 20, 0) }
desc {
buildString {
for (result in results) {
val title = result.info.embedTitle
val url = result.info.uri
val length = Utils.getTimestamp(result.duration)
val author = result.info.author
append("**[$title]($url)**\n")
append("**`").append(length).append("`** by **").append(author).append("**\n")
}
}
}
setFooter("Want to play one of these music tracks? Join a voice channel and reenter this command.", null)
}.action().queue()
return@search
} else {
context.bot.eventWaiter.selector {
title { "YouTube Results" }
desc { "Select one of the following options to play them in your current music channel." }
color { Color(141, 20, 0) }
setUser(context.user)
for (result in results) {
addOption("`${Utils.getTimestamp(result.info.length)}` **[${result.info.embedTitle}](${result.info.uri})**") {
if (context.member.voiceState!!.inVoiceChannel()) {
val manager = try {
context.bot.players.get(context.guild)
} catch (e: MusicLimitException) {
e.sendToContext(context)
return@addOption
}
manager.loadAndPlay(
context,
result.info.uri,
TrackContext(
context.member.user.idLong,
context.textChannel.idLong
)
)
} else {
context.send().error("You're not in a voice channel anymore!").queue()
}
}
}
}.display(context.textChannel)
}
}
}
}
| mit | 8cba9c46641b4e795d0fa715ff7076eb | 40.537736 | 134 | 0.469226 | 5.4291 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.