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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545TransitData.kt | 1 | 6141 | /*
* IntercodeTransitData.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.en1545
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.Preferences
abstract class En1545TransitData : TransitData {
protected val mTicketEnvParsed: En1545Parsed
override val info: List<ListItem>?
get() {
val li = mutableListOf<ListItem>()
val tz = lookup.timeZone
if (mTicketEnvParsed.contains(ENV_NETWORK_ID))
li.add(ListItem(R.string.en1545_network_id,
mTicketEnvParsed.getIntOrZero(ENV_NETWORK_ID).toString(16)))
mTicketEnvParsed.getTimeStamp(ENV_APPLICATION_VALIDITY_END, tz)?.let {
li.add(ListItem(R.string.expiry_date, it.format()))
}
if (!Preferences.hideCardNumbers && !Preferences.obfuscateTripDates)
mTicketEnvParsed.getTimeStamp(HOLDER_BIRTH_DATE, tz)?.let {
li.add(ListItem(R.string.date_of_birth, it.format()))
}
if (mTicketEnvParsed.getIntOrZero(ENV_APPLICATION_ISSUER_ID) != 0)
li.add(ListItem(R.string.card_issuer,
lookup.getAgencyName(mTicketEnvParsed.getIntOrZero(ENV_APPLICATION_ISSUER_ID), false)))
mTicketEnvParsed.getTimeStamp(ENV_APPLICATION_ISSUE, tz)?.let {
li.add(ListItem(R.string.issue_date, it.format()))
}
mTicketEnvParsed.getTimeStamp(HOLDER_PROFILE, tz)?.let {
li.add(ListItem(R.string.en1545_card_expiry_date_profile, it.format()))
}
if (!Preferences.hideCardNumbers && !Preferences.obfuscateTripDates)
// Only Mobib sets this, and Belgium has numeric postal codes.
mTicketEnvParsed.getInt(HOLDER_INT_POSTAL_CODE)?.let {
if (it != 0)
li.add(ListItem(R.string.postal_code, it.toString()))
}
mTicketEnvParsed.getInt(HOLDER_CARD_TYPE).let {
li.add(ListItem(R.string.card_type, when (it) {
0 -> R.string.card_type_anonymous
1 -> R.string.card_type_declarative
2 -> R.string.card_type_personal
else -> R.string.card_type_provider_specific
}))
}
return li
}
protected abstract val lookup: En1545Lookup
protected constructor() {
mTicketEnvParsed = En1545Parsed()
}
protected constructor(parsed: En1545Parsed) {
mTicketEnvParsed = parsed
}
override fun getRawFields(level: RawLevel): List<ListItem>? =
mTicketEnvParsed.getInfo(
when (level) {
RawLevel.UNKNOWN_ONLY -> setOf(
ENV_NETWORK_ID,
En1545FixedInteger.datePackedName(ENV_APPLICATION_VALIDITY_END),
En1545FixedInteger.dateName(ENV_APPLICATION_VALIDITY_END),
En1545FixedInteger.dateBCDName(HOLDER_BIRTH_DATE),
ENV_APPLICATION_ISSUER_ID,
HOLDER_CARD_TYPE,
En1545FixedInteger.datePackedName(ENV_APPLICATION_ISSUE),
En1545FixedInteger.dateName(ENV_APPLICATION_ISSUE),
En1545FixedInteger.datePackedName(HOLDER_PROFILE),
En1545FixedInteger.dateName(HOLDER_PROFILE),
HOLDER_INT_POSTAL_CODE,
ENV_CARD_SERIAL,
ENV_AUTHENTICATOR
)
else -> setOf()
})
companion object {
const val ENV_NETWORK_ID = "EnvNetworkId"
const val ENV_VERSION_NUMBER = "EnvVersionNumber"
const val HOLDER_BIRTH_DATE = "HolderBirth"
const val ENV_APPLICATION_VALIDITY_END = "EnvApplicationValidityEnd"
const val ENV_APPLICATION_ISSUER_ID = "EnvApplicationIssuerId"
const val ENV_APPLICATION_ISSUE = "EnvApplicationIssue"
const val HOLDER_PROFILE = "HolderProfile"
const val HOLDER_INT_POSTAL_CODE = "HolderIntPostalCode"
const val HOLDER_CARD_TYPE = "HolderDataCardStatus"
const val ENV_AUTHENTICATOR = "EnvAuthenticator"
const val ENV_UNKNOWN_A = "EnvUnknownA"
const val ENV_UNKNOWN_B = "EnvUnknownB"
const val ENV_UNKNOWN_C = "EnvUnknownC"
const val ENV_UNKNOWN_D = "EnvUnknownD"
const val ENV_UNKNOWN_E = "EnvUnknownE"
const val ENV_CARD_SERIAL = "EnvCardSerial"
const val HOLDER_ID_NUMBER = "HolderIdNumber"
const val HOLDER_UNKNOWN_A = "HolderUnknownA"
const val HOLDER_UNKNOWN_B = "HolderUnknownB"
const val HOLDER_UNKNOWN_C = "HolderUnknownC"
const val HOLDER_UNKNOWN_D = "HolderUnknownD"
const val CONTRACTS_PROVIDER = "ContractsProvider"
const val CONTRACTS_POINTER = "ContractsPointer"
const val CONTRACTS_TARIFF = "ContractsTariff"
const val CONTRACTS_UNKNOWN_A = "ContractsUnknownA"
const val CONTRACTS_UNKNOWN_B = "ContractsUnknownB"
const val CONTRACTS_NETWORK_ID = "ContractsNetworkId"
}
}
| gpl-3.0 | e402267ce4c3799018b766800ba91b41 | 43.179856 | 111 | 0.605765 | 4.34915 | false | false | false | false |
krsnvijay/Black-Board-App | app/src/main/java/com/notadeveloper/app/blackboard/ui/adapters/facultytimetable_adapter.kt | 1 | 1351 | package com.notadeveloper.app.blackboard.ui.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.notadeveloper.app.blackboard.R
import com.notadeveloper.app.blackboard.models.Schedule
/**
* Created by krsnv on 10/11/2017.
*/
/**
* Created by krsnv on 10/10/2017.
*/
class facultytimetable_adapter(
private val list: List<Schedule>?) : RecyclerView.Adapter<facultytimetable_adapter.viewholder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewholder {
val context = parent.context
val itemView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)
return viewholder(itemView)
}
override fun onBindViewHolder(holder: viewholder, position: Int) {
val schedule = list?.get(position)
holder.tv1.text = schedule?.day + " hour-" + schedule?.hour + " " + schedule?.classId
holder.tv2.text = schedule?.subjCode + " " + schedule?.classLocation
}
class viewholder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tv1: TextView
val tv2: TextView
init {
tv1 = itemView.findViewById(R.id.text1)
tv2 = itemView.findViewById(R.id.text2)
}
}
override fun getItemCount(): Int = list?.size?:0
} | mit | 7011b957372d3fe9f9d4bf4fd63db74f | 26.591837 | 102 | 0.726869 | 3.721763 | false | false | false | false |
GunoH/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/FixWidthSegmentedActionToolbarComponent.kt | 4 | 7597 | // 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.execution.runToolbar
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedActionToolbarComponent
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ComparatorUtil
import com.intellij.util.ui.JBValue
import java.awt.Component
import java.awt.Dimension
import java.awt.Rectangle
import javax.swing.JComponent
open class FixWidthSegmentedActionToolbarComponent(place: String, group: ActionGroup) : SegmentedActionToolbarComponent(place, group) {
private var project: Project? = null
private var runWidgetWidthHelper: RunWidgetWidthHelper? = null
private val listener = object : UpdateWidth {
override fun updated() {
updateWidthHandler()
}
}
override fun addNotify() {
super.addNotify()
CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(this))?.let {
project = it
runWidgetWidthHelper = RunWidgetWidthHelper.getInstance(it).apply {
addListener(listener)
}
}
}
override fun removeNotify() {
runWidgetWidthHelper?.removeListener(listener)
project = null
super.removeNotify()
}
protected open fun updateWidthHandler() {
preferredSize
revalidate()
repaint()
}
override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
val controlButtonsPrefWidth = ((0 until componentCount).map {
getComponent(it)
}.firstOrNull { it is ActionButton }?.preferredSize?.height ?: 0) * RunToolbarProcess.ACTIVE_STATE_BUTTONS_COUNT
val executorButtonsPrefWidth = (0 until componentCount).mapNotNull {
val actionComponent = getComponent(it) as JComponent
val anAction = actionComponent.getClientProperty(RUN_TOOLBAR_COMPONENT_ACTION)
if (anAction is RTBarAction) {
when (anAction) {
is ExecutorRunToolbarAction -> getChildPreferredSize(it).width
is RTRunConfiguration -> {
if (anAction.isStable()) {
val configWidth = getChildPreferredSize(it).width.toFloat()
runWidgetWidthHelper?.runConfigWidth?.let { float ->
if (configWidth > float.float) {
runWidgetWidthHelper?.runConfigWidth = JBValue.Float(configWidth, true)
}
} ?: kotlin.run {
runWidgetWidthHelper?.runConfigWidth = JBValue.Float(configWidth, true)
}
}
null
}
else -> null
}
}
else null
}.sumOf { it }
val max = ComparatorUtil.max(executorButtonsPrefWidth, controlButtonsPrefWidth)
if ((runWidgetWidthHelper?.rightSideWidth?.get() ?: 0) < max) {
runWidgetWidthHelper?.rightSideWidth = JBValue.Float(max.toFloat(), true)
}
runWidgetWidthHelper?.rightSideWidth?.let {
calculateBoundsToFit(size2Fit, bounds)
} ?: run {
super.calculateBounds(size2Fit, bounds)
}
}
private fun calculateBoundsToFit(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
val right_flexible = mutableListOf<Component>()
val right_stable = mutableListOf<Component>()
val flexible = mutableListOf<Component>()
(0 until componentCount).forEach {
val actionComponent = getComponent(it) as JComponent
actionComponent.getClientProperty(RUN_TOOLBAR_COMPONENT_ACTION)?.let {
if (it is RTBarAction) {
if (it is RTRunConfiguration) {
(if (it.isStable()) null else flexible)?.add(actionComponent)
}
else {
when (it.getRightSideType()) {
RTBarAction.Type.RIGHT_FLEXIBLE -> right_flexible
RTBarAction.Type.RIGHT_STABLE -> right_stable
RTBarAction.Type.FLEXIBLE -> flexible
else -> null
}?.add(actionComponent)
}
}
}
}
runWidgetWidthHelper?.rightSideWidth?.get()?.let { rightWidth ->
bounds.clear()
for (i in 0 until componentCount) {
bounds.add(Rectangle())
}
if (right_flexible.isNotEmpty()) {
val flexiblePrefWidth = (0 until componentCount).filter {
right_flexible.contains(getComponent(it))
}.sumOf { getChildPreferredSize(it).width }
val stablePrefWidth = (0 until componentCount).filter {
right_stable.contains(getComponent(it))
}.sumOf { getChildPreferredSize(it).width }
val delta = rightWidth - stablePrefWidth - flexiblePrefWidth
val rightAdditionWidth = if (delta > 0) delta / right_flexible.size else 0
val lastAddition = if(delta <= 0) 0 else rightWidth - stablePrefWidth - flexiblePrefWidth - (rightAdditionWidth * right_flexible.size).let { gap ->
if (gap < 0) 0 else gap
}
setComponentsBounds(right_flexible, rightAdditionWidth, lastAddition, bounds)
return
}
else if (flexible.size == 1) {
val stablePrefWidth = (0 until componentCount).filter {
right_stable.contains(getComponent(it))
}.sumOf { getChildPreferredSize(it).width }
runWidgetWidthHelper?.configWithArrow?.let { (rightWidth + it - stablePrefWidth).let {
if (it > 0) it else null
} } ?.let {
var offset = 0
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
var w = d.width
val component = getComponent(i)
if(component == flexible[0]) {
w = it
}
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, w, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += w
}
return
} ?: run {
super.calculateBounds(size2Fit, bounds)
}
} else if(right_stable.isNotEmpty() && flexible.isEmpty()) {
val stablePrefWidth = (0 until componentCount).filter {
right_stable.contains(getComponent(it))
}.sumOf { getChildPreferredSize(it).width }
val delta = rightWidth - stablePrefWidth
val rightAdditionWidth = if (delta > 0) delta / right_stable.size else 0
val lastAddition = if(delta <= 0) 0 else rightWidth - stablePrefWidth - (rightAdditionWidth * right_stable.size).let { gap ->
if (gap < 0) 0 else gap
}
setComponentsBounds(right_stable, rightAdditionWidth, lastAddition, bounds)
return
} else {
super.calculateBounds(size2Fit, bounds)
}
} ?: run {
super.calculateBounds(size2Fit, bounds)
}
}
private fun setComponentsBounds(flexible: MutableList<Component>,
additionWidth: Int,
lastAddition: Int,
bounds: MutableList<Rectangle>) {
var offset = 0
val last = flexible[flexible.lastIndex]
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
var w = d.width
val component = getComponent(i)
if (flexible.contains(component)) {
w += additionWidth
if (component == last) w += lastAddition
}
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, w, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += w
}
}
}
| apache-2.0 | ac4e73baa9f4a1c280da443ae608114e | 33.220721 | 155 | 0.641306 | 4.584792 | false | false | false | false |
GunoH/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/ui/TextComponentHint.kt | 2 | 2714 | package com.intellij.remoteDev.ui
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Font
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import javax.swing.JLabel
import javax.swing.border.EmptyBorder
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.text.Document
import javax.swing.text.JTextComponent
@ApiStatus.Experimental
class TextComponentHint(val component: JTextComponent, @Nls text: String, var state: State = State.FOCUS_LOST) : JLabel(text) {
enum class State {
ALWAYS, FOCUS_GAINED, FOCUS_LOST
}
private val document: Document = component.document
private var showHintOnce = false
private var focusLost = 0
private val documentListener = object : DocumentListener {
override fun insertUpdate(e: DocumentEvent) {
checkForHint()
}
override fun removeUpdate(e: DocumentEvent) {
checkForHint()
}
override fun changedUpdate(e: DocumentEvent) {}
}
private val focusListener = object : FocusListener {
override fun focusGained(e: FocusEvent) {
checkForHint()
}
override fun focusLost(e: FocusEvent) {
focusLost++
checkForHint()
}
}
init {
font = component.font
foreground = component.foreground
border = EmptyBorder(component.insets)
horizontalAlignment = LEADING
setAlpha(0.5f)
setStyle(Font.ITALIC)
component.addFocusListener(focusListener)
document.addDocumentListener(documentListener)
component.layout = BorderLayout()
component.add(this)
checkForHint()
}
private fun setAlpha(alpha: Float) {
setAlpha((alpha * 255).toInt())
}
private fun setAlpha(value: Int) {
var alpha = value
alpha = if (alpha > 255) 255 else if (alpha < 0) 0 else alpha
val foreground = foreground
val red = foreground.red
val green = foreground.green
val blue = foreground.blue
val withAlpha = Color(red, green, blue, alpha)
super.setForeground(withAlpha)
}
private fun setStyle(style: Int) {
font = font.deriveFont(style)
}
fun getShowHintOnce(): Boolean {
return showHintOnce
}
fun setShowHintOnce(showHintOnce: Boolean) {
this.showHintOnce = showHintOnce
}
private fun checkForHint() {
if (document.length > 0) {
isVisible = false
return
}
if (showHintOnce && focusLost > 0) {
isVisible = false
return
}
isVisible = if (component.hasFocus()) {
state == State.ALWAYS || state == State.FOCUS_GAINED
}
else {
state == State.ALWAYS || state == State.FOCUS_LOST
}
}
} | apache-2.0 | 862f1b59405ea6f777e583ad7d5373ee | 23.241071 | 127 | 0.696389 | 4.247261 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/ChannelPager.kt | 1 | 14655 | /*
* Copyright © 2015 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.fragments
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.view.*
import android.widget.AdapterView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.PagerTitleStrip
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import org.apache.commons.collections4.CollectionUtils
import org.apache.commons.lang3.StringUtils
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.DbHelper
import org.dvbviewer.controller.data.channel.ChannelGroupViewModel
import org.dvbviewer.controller.data.channel.ChannelGroupViewModelFactory
import org.dvbviewer.controller.data.channel.ChannelRepository
import org.dvbviewer.controller.data.entities.ChannelGroup
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.data.version.VersionRepository
import org.dvbviewer.controller.ui.base.BaseFragment
import org.dvbviewer.controller.utils.Config
import org.dvbviewer.controller.utils.UIUtils
import java.util.*
/**
* The Class EpgPager.
*
* @author RayBa82
*/
class ChannelPager : BaseFragment(), OnPageChangeListener {
private var mGroupIndex = AdapterView.INVALID_POSITION
@SuppressLint("UseSparseArrays")
private var index = HashMap<Int, Int>()
private var showFavs: Boolean = false
private var showNowPlaying: Boolean = false
private var showNowPlayingWifi: Boolean = false
private var refreshGroupType: Boolean = false
private var hideFavSwitch = false
private var mGroupCHangedListener: OnGroupChangedListener? = null
private var mOnGroupTypeCHangedListener: OnGroupTypeChangedListener? = null
private var mNetworkInfo: NetworkInfo? = null
private lateinit var mProgress: View
private lateinit var mPager: ViewPager
private lateinit var mAdapter: ChannelPagerAdapter
private lateinit var mPagerIndicator: PagerTitleStrip
private lateinit var prefs: DVBViewerPreferences
private lateinit var versionRepository: VersionRepository
private lateinit var channelRepository: ChannelRepository
private lateinit var mDbHelper: DbHelper
private lateinit var groupViewModel: ChannelGroupViewModel
/*
* (non-Javadoc)
*
* @see
* com.actionbarsherlock.app.SherlockFragment#onAttach(android.app.Activity)
*/
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnGroupTypeChangedListener) {
mOnGroupTypeCHangedListener = context
}
if (context is OnGroupChangedListener) {
mGroupCHangedListener = context
}
}
/*
* (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
prefs = DVBViewerPreferences(activity?.applicationContext)
mDbHelper = DbHelper(activity?.applicationContext)
versionRepository = VersionRepository(activity!!.applicationContext, getDmsInterface())
channelRepository = ChannelRepository(getDmsInterface(), mDbHelper)
mAdapter = ChannelPagerAdapter(childFragmentManager)
val connManager = activity!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
mNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
showFavs = prefs.prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false)
showNowPlaying = prefs.prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING, true)
showNowPlayingWifi = prefs.prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING_WIFI_ONLY, true)
if (savedInstanceState == null && arguments != null) {
hideFavSwitch = arguments!!.getBoolean(KEY_HIDE_FAV_SWITCH, false)
if (arguments!!.containsKey(KEY_GROUP_INDEX)) {
mGroupIndex = arguments!!.getInt(KEY_GROUP_INDEX)
}
val initialChanIndex = arguments!!.getInt(ChannelList.KEY_CHANNEL_INDEX)
index[mGroupIndex] = initialChanIndex
} else if (savedInstanceState != null) {
mGroupIndex = savedInstanceState.getInt(KEY_GROUP_INDEX)
index = (savedInstanceState.getSerializable(KEY_INDEX) as HashMap<Int, Int>?)!!
}
}
fun setPosition(position: Int) {
mGroupIndex = position
mPager.setCurrentItem(mGroupIndex, false)
}
override fun onDestroy() {
mDbHelper.close()
super.onDestroy()
}
/*
* (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.setTitle(if (showFavs) R.string.favourites else R.string.channelList)
mPager.adapter = mAdapter
mPager.pageMargin = UIUtils.dipToPixel(context!!, 25).toInt()
mPager.addOnPageChangeListener(this)
if (savedInstanceState == null) {
/**
* Prüfung ob das EPG in der Senderliste angezeigt werden soll.
*/
if (!Config.CHANNELS_SYNCED) {
} else if (showNowPlaying && !showNowPlayingWifi || showNowPlaying && mNetworkInfo!!.isConnected) {
}
}
mPager.currentItem = mGroupIndex
val groupObserver = Observer<List<ChannelGroup>> { response -> onGroupChanged(response!!) }
val channelGroupViewModelFactory = ChannelGroupViewModelFactory(prefs, channelRepository)
groupViewModel = ViewModelProvider(this, channelGroupViewModelFactory)
.get(ChannelGroupViewModel::class.java)
groupViewModel.getGroupList(showFavs).observe(this, groupObserver)
showProgress(savedInstanceState == null)
}
fun onGroupChanged(groupList: List<ChannelGroup>) {
mAdapter.groups = groupList
mAdapter.notifyDataSetChanged()
mPager.setCurrentItem(mGroupIndex, false)
// mPager.setPageTransformer(true, new DepthPageTransformer());
activity?.invalidateOptionsMenu()
showProgress(false)
if (refreshGroupType) {
mOnGroupTypeCHangedListener?.groupTypeChanged(if (showFavs) ChannelGroup.TYPE_FAV else ChannelGroup.TYPE_CHAN)
}
refreshGroupType = false
}
/*
* (non-Javadoc)
*
* @see
* android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.pager, container, false)
mProgress = view.findViewById(android.R.id.progress)
mPager = view.findViewById(R.id.pager)
mPagerIndicator = view.findViewById(R.id.titles)
val c = view.findViewById<View>(R.id.bottom_container)
if (c != null) {
c.visibility = View.GONE
}
return view
}
/*
* (non-Javadoc)
*
* @see
* com.actionbarsherlock.app.SherlockListFragment#onCreateOptionsMenu(android
* .view.Menu, android.view.MenuInflater)
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.channel_pager, menu)
if (!hideFavSwitch) {
menu.findItem(R.id.menuChannelList).isVisible = showFavs
menu.findItem(R.id.menuFavourties).isVisible = !showFavs
} else {
menu.findItem(R.id.menuChannelList).isVisible = false
menu.findItem(R.id.menuFavourties).isVisible = false
}
}
/*
* (non-Javadoc)
*
* @see
* com.actionbarsherlock.app.SherlockListFragment#onOptionsItemSelected(
* android.view.MenuItem)
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuRefresh -> {
groupViewModel.fetchEpg()
return true
}
R.id.menuSyncChannels -> {
mPager.adapter = null
mAdapter.notifyDataSetChanged()
mAdapter = ChannelPagerAdapter(childFragmentManager)
mPager.adapter = mAdapter
mAdapter.notifyDataSetChanged()
persistChannelConfigConfig()
mGroupIndex = 0
groupViewModel.syncChannels(showFavs)
return true
}
R.id.menuChannelList, R.id.menuFavourties -> {
mPager.adapter = null
mAdapter.notifyDataSetChanged()
mAdapter = ChannelPagerAdapter(childFragmentManager)
mPager.adapter = mAdapter
mAdapter.notifyDataSetChanged()
showFavs = !showFavs
persistChannelConfigConfig()
mGroupIndex = 0
groupViewModel.getGroupList(showFavs, true)
return true
}
else -> return false
}
}
/**
* Persist channel config config.
*/
@SuppressLint("CommitPrefEdits")
private fun persistChannelConfigConfig() {
val editor = prefs.prefs.edit()
editor.putBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, showFavs)
editor.commit()
super.onPause()
}
/**
* The Class PagerAdapter.
*/
internal inner class ChannelPagerAdapter
/**
* Instantiates a new pager adapter.
*
* @param fm the fm
*/
(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
var groups: List<ChannelGroup>? = null
/*
* (non-Javadoc)
*
* @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
override fun getItem(position: Int): Fragment {
val groupId = groups?.get(position)?.id
val bundle = Bundle()
groupId?.let { bundle.putLong(KEY_GROUP_ID, it) }
bundle.putInt(KEY_GROUP_INDEX, position)
bundle.putInt(ChannelList.KEY_CHANNEL_INDEX, getChannelIndex(position))
bundle.putBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, showFavs)
val fragment = fragmentManager!!.fragmentFactory.instantiate(javaClass.classLoader!!, ChannelList::class.java.name)
fragment.arguments = bundle
return fragment
}
override fun getItemPosition(`object`: Any): Int {
return PagerAdapter.POSITION_NONE
}
fun getGroupId(position: Int): Long {
return groups!![position].id
}
/*
* (non-Javadoc)
*
* @see android.support.v4.view.PagerAdapter#getCount()
*/
override fun getCount(): Int {
return if (CollectionUtils.isNotEmpty(groups)) {
groups!!.size
} else 0
}
override fun getPageTitle(position: Int): CharSequence? {
val groupName = groups!![position].name
return if (StringUtils.isNotBlank(groupName)) groupName else StringUtils.EMPTY
}
}
/**
* Sets the position.
*
* @param channelIndex the new channel index
*/
fun setChannelSelection(groupId: Long, channelIndex: Int) {
val uri = ChannelList.BASE_CONTENT_URI.buildUpon().appendPath(groupId.toString()).appendQueryParameter("index", channelIndex.toString()).build()
index[mPager.currentItem] = channelIndex
context?.contentResolver?.notifyChange(uri, null)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_GROUP_INDEX, mPager.currentItem)
outState.putSerializable(KEY_INDEX, index)
}
private fun showProgress(show: Boolean) {
mProgress.visibility = if (show) View.VISIBLE else View.GONE
mPager.visibility = if (show) View.GONE else View.VISIBLE
mPagerIndicator.visibility = if (show) View.GONE else View.VISIBLE
}
public override fun getStringSafely(resId: Int): String {
var result = ""
if (!isDetached && isAdded && isVisible) {
try {
result = getString(resId)
} catch (e: Exception) {
e.printStackTrace()
}
}
return result
}
interface OnGroupTypeChangedListener {
fun groupTypeChanged(type: Int)
}
interface OnGroupChangedListener {
fun groupChanged(groupId: Long, groupIndex: Int, channelIndex: Int)
}
override fun onPageScrollStateChanged(arg0: Int) {
}
override fun onPageScrolled(arg0: Int, arg1: Float, arg2: Int) {
}
override fun onPageSelected(position: Int) {
mGroupIndex = position
mGroupCHangedListener?.groupChanged(mAdapter.getGroupId(mGroupIndex), mGroupIndex, getChannelIndex(mGroupIndex))
}
fun updateIndex(groupIndex: Int, channelIndex: Int) {
index[groupIndex] = channelIndex
}
private fun getChannelIndex(groupIndex: Int): Int {
val channelIndex = index[groupIndex]
return channelIndex ?: 0
}
companion object {
private val KEY_INDEX = ChannelPager::class.java.name + "KEY_INDEX"
val KEY_GROUP_INDEX = ChannelPager::class.java.name + "KEY_GROUP_INDEX"
val KEY_GROUP_ID = ChannelPager::class.java.name + "KEY_GROUP_ID"
val KEY_HIDE_FAV_SWITCH = ChannelPager::class.java.name + "KEY_HIDE_FAV_SWITCH"
}
}
| apache-2.0 | 6486176f9f84594cd66c9c968fe40b94 | 35.180247 | 152 | 0.674947 | 4.691963 | false | false | false | false |
ktorio/ktor | ktor-io/common/src/io/ktor/utils/io/Coroutines.kt | 1 | 4929 | package io.ktor.utils.io
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* A coroutine job that is reading from a byte channel
*/
public interface ReaderJob : Job {
/**
* A reference to the channel that this coroutine is reading from
*/
public val channel: ByteWriteChannel
}
/**
* A coroutine job that is writing to a byte channel
*/
public interface WriterJob : Job {
/**
* A reference to the channel that this coroutine is writing to
*/
public val channel: ByteReadChannel
}
public interface ReaderScope : CoroutineScope {
public val channel: ByteReadChannel
}
public interface WriterScope : CoroutineScope {
public val channel: ByteWriteChannel
}
public fun CoroutineScope.reader(
coroutineContext: CoroutineContext = EmptyCoroutineContext,
channel: ByteChannel,
block: suspend ReaderScope.() -> Unit
): ReaderJob = launchChannel(coroutineContext, channel, attachJob = false, block = block)
public fun CoroutineScope.reader(
coroutineContext: CoroutineContext = EmptyCoroutineContext,
autoFlush: Boolean = false,
block: suspend ReaderScope.() -> Unit
): ReaderJob = launchChannel(coroutineContext, ByteChannel(autoFlush), attachJob = true, block = block)
@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
@Deprecated("Use scope.reader instead")
public fun reader(
coroutineContext: CoroutineContext,
channel: ByteChannel,
parent: Job? = null,
block: suspend ReaderScope.() -> Unit
): ReaderJob {
val newContext = if (parent != null) GlobalScope.newCoroutineContext(coroutineContext + parent)
else GlobalScope.newCoroutineContext(coroutineContext)
return CoroutineScope(newContext).reader(EmptyCoroutineContext, channel, block)
}
@Suppress("DEPRECATION")
@Deprecated("Use scope.reader instead")
public fun reader(
coroutineContext: CoroutineContext,
autoFlush: Boolean = false,
parent: Job? = null,
block: suspend ReaderScope.() -> Unit
): ReaderJob {
val channel = ByteChannel(autoFlush)
return reader(coroutineContext, channel, parent, block).also {
channel.attachJob(it)
}
}
public fun CoroutineScope.writer(
coroutineContext: CoroutineContext = EmptyCoroutineContext,
channel: ByteChannel,
block: suspend WriterScope.() -> Unit
): WriterJob = launchChannel(coroutineContext, channel, attachJob = false, block = block)
public fun CoroutineScope.writer(
coroutineContext: CoroutineContext = EmptyCoroutineContext,
autoFlush: Boolean = false,
block: suspend WriterScope.() -> Unit
): WriterJob = launchChannel(coroutineContext, ByteChannel(autoFlush), attachJob = true, block = block)
@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
@Deprecated("Use scope.writer instead")
public fun writer(
coroutineContext: CoroutineContext,
channel: ByteChannel,
parent: Job? = null,
block: suspend WriterScope.() -> Unit
): WriterJob {
val newContext = if (parent != null) GlobalScope.newCoroutineContext(coroutineContext + parent)
else GlobalScope.newCoroutineContext(coroutineContext)
return CoroutineScope(newContext).writer(EmptyCoroutineContext, channel, block)
}
@Suppress("DEPRECATION")
@Deprecated("Use scope.writer instead")
public fun writer(
coroutineContext: CoroutineContext,
autoFlush: Boolean = false,
parent: Job? = null,
block: suspend WriterScope.() -> Unit
): WriterJob {
val channel = ByteChannel(autoFlush)
return writer(coroutineContext, channel, parent, block).also {
channel.attachJob(it)
}
}
/**
* @param S not exactly safe (unchecked cast is used) so should be [ReaderScope] or [WriterScope]
*/
@OptIn(ExperimentalStdlibApi::class)
private fun <S : CoroutineScope> CoroutineScope.launchChannel(
context: CoroutineContext,
channel: ByteChannel,
attachJob: Boolean,
block: suspend S.() -> Unit
): ChannelJob {
val dispatcher = coroutineContext[CoroutineDispatcher]
val job = launch(context) {
if (attachJob) {
channel.attachJob(coroutineContext[Job]!!)
}
@Suppress("UNCHECKED_CAST")
val scope = ChannelScope(this, channel) as S
try {
block(scope)
} catch (cause: Throwable) {
if (dispatcher != Dispatchers.Unconfined && dispatcher != null) {
throw cause
}
channel.cancel(cause)
}
}
job.invokeOnCompletion { cause ->
channel.close(cause)
}
return ChannelJob(job, channel)
}
private class ChannelScope(
delegate: CoroutineScope,
override val channel: ByteChannel
) : ReaderScope, WriterScope, CoroutineScope by delegate
private class ChannelJob(
private val delegate: Job,
override val channel: ByteChannel
) : ReaderJob, WriterJob, Job by delegate {
override fun toString(): String = "ChannelJob[$delegate]"
}
| apache-2.0 | c0f4fe95fe2b30cf465d240cddfc1134 | 29.614907 | 103 | 0.711706 | 4.703244 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt | 1 | 2014 | package eu.kanade.tachiyomi.extension.model
import android.graphics.drawable.Drawable
import eu.kanade.tachiyomi.source.Source
sealed class Extension {
abstract val name: String
abstract val pkgName: String
abstract val versionName: String
abstract val versionCode: Long
abstract val lang: String?
abstract val isNsfw: Boolean
abstract val hasReadme: Boolean
abstract val hasChangelog: Boolean
data class Installed(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
override val lang: String,
override val isNsfw: Boolean,
override val hasReadme: Boolean,
override val hasChangelog: Boolean,
val pkgFactory: String?,
val sources: List<Source>,
val icon: Drawable?,
val hasUpdate: Boolean = false,
val isObsolete: Boolean = false,
val isUnofficial: Boolean = false
) : Extension()
data class Available(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
override val lang: String,
override val isNsfw: Boolean,
override val hasReadme: Boolean,
override val hasChangelog: Boolean,
val sources: List<AvailableExtensionSources>,
val apkName: String,
val iconUrl: String
) : Extension()
data class Untrusted(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
val signatureHash: String,
override val lang: String? = null,
override val isNsfw: Boolean = false,
override val hasReadme: Boolean = false,
override val hasChangelog: Boolean = false,
) : Extension()
}
data class AvailableExtensionSources(
val name: String,
val id: Long,
val baseUrl: String
)
| apache-2.0 | b509883cd9c4da6690e36c53a7eb6e63 | 29.984615 | 53 | 0.659881 | 4.948403 | false | false | false | false |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/ui/license/LicenseActivity.kt | 1 | 1804 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.ui.license
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.ayatk.biblio.R
import com.ayatk.biblio.databinding.ActivityWebBinding
import com.ayatk.biblio.ui.util.initBackToolbar
import com.ayatk.biblio.util.ext.extraOf
class LicenseActivity : AppCompatActivity() {
private val binding: ActivityWebBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_web)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val title = intent.getStringExtra(EXTRA_TITLE)
val url = intent.getStringExtra(EXTRA_URL)
binding.toolbar.title = title
initBackToolbar(binding.toolbar)
// WebViewによる表示
binding.webView.loadUrl(url!!)
}
companion object {
private const val EXTRA_TITLE = "TITLE"
private const val EXTRA_URL = "URL"
fun createIntent(context: Context?, title: String, url: String): Intent =
Intent(context, LicenseActivity::class.java).extraOf(
EXTRA_TITLE to title,
EXTRA_URL to url
)
}
}
| apache-2.0 | 03dae7e13ff4cdb67500f803e19f3d7f | 29.40678 | 77 | 0.744147 | 4.105263 | false | false | false | false |
vba/type-providers | core/src/main/kotlin/org/typeproviders/App.kt | 1 | 3371 | package org.typeproviders
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.JsonNodeType
import java.lang.reflect.Type
import kotlin.reflect.jvm.internal.impl.load.kotlin.JvmType
typealias JacksonObjectNode = com.fasterxml.jackson.databind.node.ObjectNode
typealias JacksonObjectPair = Pair<String, JsonNode>
data class NodeWrapper(val name: String,
val level: Int,
val node: JsonNode,
val isArray: Boolean = false,
var parent: NodeWrapper? = null)
open class TPType private constructor() {
data class Primitive(val type: Class<Any>, val isArray : Boolean = false) : TPType()
data class Reference(val type: TPClass, val isArray : Boolean = false) : TPType()
}
data class TPClass(val fields: Iterable<TPField>)
data class TPField(val name: String, val type: TPType)
fun main(args: Array<String>) {
// val buildFolder = "/Users/victor/projects/type-providers/core/build/typeproviders"
// val jsonUrl = URL("https://api.github.com/users/vba/repos")
val jsonUrl = Any().javaClass.getResource("/json/sample1.json")
// ByteBuddy()
// .subclass(Any::class.java)
// .name("org.typeproviders.Class1")
// .method(named("toString"))
// .intercept(FixedValue.node("Hello World!"))
// .make()
// .saveIn(File(buildFolder))
val mapper = ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY)
val tree = mapper.readTree(jsonUrl)
val map = mapper.convertValue<Map<String, *>>(tree, object : TypeReference<Map<String, *>>(){})
//val f5 = map["field5"]?.javaClass?.canonicalName
//val f6 = map["field6"]
// tree.get(0).fields().asSequence().toList()[2].node.nodeType
getTType(map)
//makeObjectNode("", tree)
println(tree)
/*
* Structured sources
* download / load a structure
* convert it to java representation
* compile it to the disk
*
*
* */
}
fun getTType(map: Map<String, *>): TPType {
map.entries
var nodes = emptyList<NodeWrapper>()
val awaitingNodes = mutableListOf<Pair<String, *>>()
awaitingNodes.addAll(map.entries.map {Pair(it.key, it.value)})
var current : Pair<String, *>? = null
var prev : Pair<String, *>?
while (!awaitingNodes.isEmpty()) {
prev = current
current = awaitingNodes.removeAt(0)
if(current.second is Map<*, *>) {
val subMap = current.second as Map<*, *>
awaitingNodes.addAll(0, subMap.entries.map { Pair(it.key.toString(), it.value) })
} else {
val type = (current.second?.javaClass ?: Any::class.java)
TPField(current.first, TPType.Primitive(type))
}
}
return TPType.Primitive(object : Any() {}.javaClass)
}
open class Tree private constructor() {
class Leaf<out T>(val name: String, val value: T) : Tree()
class Node(val name: String, var subTrees: List<Tree> = listOf()) : Tree()
}
| gpl-3.0 | 4e3434fbddcc22aa8d6395762a9c5a23 | 35.641304 | 99 | 0.650549 | 3.919767 | false | false | false | false |
code-disaster/lwjgl3 | modules/extract/src/main/kotlin/org/lwjgl/extract/Documentation.kt | 2 | 18909 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.extract
import org.lwjgl.llvm.*
import org.lwjgl.llvm.ClangDocumentation.*
import org.lwjgl.system.MemoryStack.*
import java.util.regex.*
internal class Documentation(
val doc: StringBuilder = StringBuilder(),
val params: HashMap<String, StringBuilder> = HashMap(),
val paramList: ArrayList<StringBuilder?> = ArrayList(),
val returnDoc: StringBuilder = StringBuilder(),
val see: ArrayList<StringBuilder> = ArrayList()
) {
fun format(linePrefix: String, blockIndent: String = linePrefix, blockPrefix: String = "") =
doc.formatDocumentation(linePrefix, blockIndent, blockPrefix)
fun formatReturnDoc() =
if (returnDoc.isEmpty())
""
else
",\n\n$t${t}returnDoc = ${formatParamDoc(returnDoc).formatDocumentation("$t${t}returnDoc = ", "$t$t", "\n$t$t")}"
fun formatParamDoc(doc: StringBuilder): String {
return doc.toString().trim()
.let { if (it.startsWith("-")) it.substring(1).trim() else it }
.let {
if (it.isEmpty()) {
""
} else {
"${it[0].let { f ->
if (it.length < 2 || !it[1].isUpperCase())
f.lowercase()
else
f
}}${it.substring(1, if (it.endsWith('.') && it.indexOf('.') == it.lastIndex) it.lastIndex else it.length)}"
}
}
}
}
internal fun CXComment.parse(doc: Documentation = Documentation(), builder: StringBuilder = doc.doc) =
parse(doc, builder, DocContext())
private class DocContext {
var skipNextWhitespace = false
val firstStack = Array(16) { false }
private var firstIndex = -1
val first: Boolean get() = firstStack[firstIndex]
fun pushFirst(i: Int) {
firstStack[++firstIndex] = i == 0
}
fun popFirst() {
firstIndex--
}
}
private fun CXComment.parseChildren(doc: Documentation, builder: StringBuilder, context: DocContext) {
for (i in 0 until clang_Comment_getNumChildren(this)) {
stackPush().use { frame ->
context.pushFirst(i)
clang_Comment_getChild(this, i, CXComment.malloc(frame)).parse(doc, builder, context)
context.popFirst()
}
}
}
private fun CXComment.parse(doc: Documentation, builder: StringBuilder, context: DocContext): Documentation {
stackPush().use { stack ->
when (val kind = clang_Comment_getKind(this)) {
CXComment_Null -> {
if (clang_Comment_getNumChildren(this) != 0) {
TODO()
}
}
CXComment_Text -> {
if (clang_Comment_isWhitespace(this)) {
//builder.append(" ")
} else {
when (val text = clang_TextComment_getText(this, stack.str).str.trim()) {
"\\" -> {
if (builder.isNotEmpty() && builder.last().let { it.isLetter() || it == ':' }) {
builder.append(" ")
}
builder.append("\\\\")
context.skipNextWhitespace = true
}
"#" -> {
if (builder.isNotEmpty() && builder.last().isLetter()) {
builder.append(" ")
}
builder.append("\\#")
context.skipNextWhitespace = true
}
"<" -> {
builder.append(" <")
context.skipNextWhitespace = true
}
">" -> {
builder.append(">")
}
else -> {
if (!context.first && builder.isNotEmpty() && text.isNotEmpty()) {
if (text[0].let { it == '-' || it == '*' }) {
if (builder.last() == ':') {
builder.append("\n")
}
builder.append("\n$t$t")
} else if (!context.skipNextWhitespace) {
builder.append(" ")
}
}
builder.append(text.replace("\"", "\\\""))
context.skipNextWhitespace = false
}
}
}
}
CXComment_InlineCommand -> {
when (clang_InlineCommandComment_getRenderKind(this)) {
CXCommentInlineCommandRenderKind_Normal -> {
builder.append(" \\")
builder.append(clang_InlineCommandComment_getCommandName(this, stack.str).str)
/*for (i in 0 until clang_InlineCommandComment_getNumArgs(this)) {
builder.append(clang_InlineCommandComment_getArgText(this, i, stack.str).str)
}*/
}
CXCommentInlineCommandRenderKind_Bold -> {
val index = builder.length
builder.append(" <b>")
closeInlineCommand(builder, index, "</b>")
}
CXCommentInlineCommandRenderKind_Monospaced -> {
if (clang_InlineCommandComment_getCommandName(this, stack.str).str.let { it != "c" && it != "p" }) {
println(clang_InlineCommandComment_getCommandName(this, stack.str).str)
TODO()
}
val index = builder.length
if (builder.isNotEmpty() && builder.last() != '(') {
builder.append(' ')
}
builder.append("{@code ")
closeInlineCommand(builder, index, "}")
if (builder.indexOf(" {@code NULL}", index) != -1) {
builder.replace(index, index + " {@code NULL}".length, " #NULL")
}
}
CXCommentInlineCommandRenderKind_Emphasized -> {
when (val cmd = clang_InlineCommandComment_getCommandName(this, stack.str).str) {
"a" -> {
builder.append(" #")
for (i in 0 until clang_InlineCommandComment_getNumArgs(this)) {
builder.append(clang_InlineCommandComment_getArgText(this, i, stack.str).str)
}
}
"e" -> {
val index = builder.length
builder.append(" <em>")
closeInlineCommand(builder, index, "</em>")
}
else -> {
System.err.println("Unsupported CXCommentInlineCommandRenderKind_Emphasized command: $cmd")
TODO()
}
}
}
else -> {
println("\trenderKind = " + clang_InlineCommandComment_getRenderKind(this))
println("\t" + clang_InlineCommandComment_getCommandName(this, stack.str).str)
var i = 0
val len = clang_InlineCommandComment_getNumArgs(this)
while (i < len) {
println("\t" + clang_InlineCommandComment_getArgText(this, i, stack.str).str)
i++
}
TODO()
}
}
}
CXComment_HTMLStartTag -> {
// TODO:
builder.append(clang_HTMLTagComment_getAsString(this, stack.str).str)
}
CXComment_HTMLEndTag -> {
// TODO:
builder.append(clang_HTMLTagComment_getAsString(this, stack.str).str)
}
CXComment_Paragraph -> {
if (!clang_Comment_isWhitespace(this)) {
if (!context.first) {
builder.append("\n\n$t$t")
}
parseChildren(doc, builder, context)
}
}
CXComment_BlockCommand -> {
when (clang_BlockCommandComment_getCommandName(this, stack.str).str) {
"brief" -> {
parseChildren(doc, builder, context)
}
"deprecated" -> {
builder.append("Deprecated: ")
parseChildren(doc, builder, context)
}
"li" -> {
if (!builder.endsWith("\n")) {
builder.append("\n\n")
}
builder.append("- ")
parseChildren(doc, builder, context)
builder.append("\n")
}
"note" -> {
builder.append("\n\n$t$t\${note(\"\"\"")
parseChildren(doc, builder, context)
builder.append("\"\"\")}")
}
"par" -> {
builder.append("<h3>")
parseChildren(doc, builder, context)
builder.append("</h3>")
}
"pre" -> {
builder.append("Precondition: ")
parseChildren(doc, builder, context)
}
"return",
"returns",
"result" -> {
parseChildren(doc, doc.returnDoc, context)
}
"retval" -> {
doc.returnDoc.append(" {@code ")
parseChildren(doc, doc.returnDoc, context)
doc.returnDoc.append("}")
}
"sa" -> {
for (i in 0 until clang_Comment_getNumChildren(this)) {
stack.push().use { frame ->
val saBuilder = StringBuilder()
doc.see.add(saBuilder)
context.pushFirst(i)
clang_Comment_getChild(this, i, CXComment.malloc(frame)).parse(doc, saBuilder, context)
context.popFirst()
}
}
}
"see",
"since" -> {
// TODO: ignored for now
}
"todo" -> {
builder.append("TODO: ")
parseChildren(doc, builder, context)
}
"warning" -> {
builder.append("Warning: ")
parseChildren(doc, builder, context)
}
else -> {
println(clang_BlockCommandComment_getCommandName(this, stack.str).str)
TODO()
}
}
}
CXComment_ParamCommand -> {
val paramBuilder = StringBuilder()
if (clang_ParamCommandComment_isParamIndexValid(this)) {
doc.params[clang_ParamCommandComment_getParamName(this, stack.str).str] = paramBuilder
doc.paramList.add(null)
} else {
doc.paramList.add(paramBuilder)
}
parseChildren(doc, paramBuilder, context)
}
CXComment_VerbatimBlockCommand -> {
when (clang_BlockCommandComment_getCommandName(this, stack.str).str) {
"code",
"verbatim" -> {
builder.append("\n\n$t$t\${codeBlock(\"\"\"\n")
parseChildren(doc, builder, context)
builder.append("\"\"\")}")
}
else -> {
builder.append("\n\n$t$t")
parseChildren(doc, builder, context)
}
}
}
CXComment_VerbatimBlockLine -> {
if (!context.first) {
builder.append("\n")
}
val line = clang_VerbatimBlockLineComment_getText(this, stack.str).str
if (!line.contains('\n')) { // sigh... libclang bug?
builder.append(line)
}
}
CXComment_VerbatimLine -> {
builder.append(clang_VerbatimLineComment_getText(this, stack.str).str)
}
CXComment_FullComment -> {
parseChildren(doc, builder, context)
}
else -> {
println("kind = $kind")
TODO()
}
}
Unit
}
return doc
}
private fun CXComment.closeInlineCommand(builder: StringBuilder, index: Int, text: String) {
val stack = stackGet()
for (i in 0 until clang_InlineCommandComment_getNumArgs(this)) {
stack.push().use { frame ->
builder.append(clang_InlineCommandComment_getArgText(this, i, frame.str).str)
}
}
if (builder.subSequence(index, builder.length)
.let {
it.count { c -> c == '(' } < it.count { c -> c == ')' }
}
) {
builder.insert(builder.lastIndexOf(')'), text)
} else {
when (builder.last()) {
'.',
',' -> builder.insert(builder.lastIndex, text)
else -> builder.append(text)
}
}
}
internal fun CharSequence.formatDocumentation(linePrefix: String, blockIndent: String = linePrefix, blockPrefix: String = ""): String {
if (this.indexOf('\n') == -1) {
if (linePrefix.length + this.length + 2 < 160) {
return "\"$this\""
}
if (blockPrefix.isNotEmpty() && blockPrefix.length - (blockPrefix.lastIndexOf('\n') + 1) + this.length + 2 < 160) {
return "$blockPrefix\"$this\""
}
}
return "$blockPrefix\"\"\"\n${formatDocumentation(this, blockIndent)}\n$blockIndent\"\"\""
}
private val PARAGRAPH = Pattern.compile("\\n(\\s*\\n)+\\s*")
private val WHITESPACE = Pattern.compile("\\s+|$")
private fun formatDocumentation(input: CharSequence, indent: String): String {
val doc = input.trim()
val builder = StringBuilder(doc.length)
val paragraphMatcher = PARAGRAPH.matcher(doc)
var lastParagraphMatch = 0
while (paragraphMatcher.find()) {
lastParagraphMatch = formatParagraph(doc, indent, lastParagraphMatch, paragraphMatcher, builder)
}
if (lastParagraphMatch < doc.length) {
formatParagraph(doc, indent, lastParagraphMatch, paragraphMatcher, builder)
}
return builder.toString()
}
private fun formatParagraph(
input: CharSequence,
indent: String,
lastParagraphMatch: Int,
matcher: Matcher,
builder: StringBuilder
): Int {
if (builder.isNotEmpty()) {
builder.append("\n\n")
}
val paragraph = input.substring(lastParagraphMatch, if (matcher.hitEnd()) input.length else matcher.start())
if (paragraph.startsWith("\${codeBlock(\"\"\"")) {
if (!matcher.hitEnd()) {
var lastMatch = lastParagraphMatch
while (matcher.start() - lastMatch < 5 || input.substring(matcher.start() - 5, matcher.start()) != "\"\"\")}") {
lastMatch = matcher.end()
if (!matcher.find()) {
break
}
}
}
builder
.append(indent)
.append(input, lastParagraphMatch, if (matcher.hitEnd()) input.length else matcher.start())
} else if (paragraph.startsWith("<table")) {
if (!matcher.hitEnd()) {
var lastMatch = lastParagraphMatch
while (matcher.start() - lastMatch < 8 || input.substring(matcher.start() - 8, matcher.start()) != "</table>") {
lastMatch = matcher.end()
if (!matcher.find()) {
break
}
}
}
builder
.append(indent)
.append(input, lastParagraphMatch, if (matcher.hitEnd()) input.length else matcher.start())
} else if (paragraph[0].let { it == '-' || it == '*' }) {
builder
.append(indent)
.append("\${ul(")
val c = paragraph[0]
"""(?<=^|\n)\s*[$c]\s*(.+?)(?=\n\s*[$c]|$)"""
.toRegex(RegexOption.DOT_MATCHES_ALL)
.findAll(paragraph)
.forEach {
val comma = if (it.range.last < paragraph.lastIndex) "," else ""
builder.append("\n$indent$t${it.groupValues[1].formatDocumentation("$indent$t$comma", "$indent$t")}$comma")
}
builder.append("\n$indent)}")
} else {
wordWrapParagraph(
paragraph
.replace("""\\([^\\#])""".toRegex(), "$1")
.replace("\\\\", "\\"),
indent,
builder
)
}
return if (matcher.hitEnd()) input.length else matcher.end()
}
private fun wordWrapParagraph(paragraph: String, indent: String, builder: StringBuilder) {
val matcher = WHITESPACE.matcher(paragraph)
var lineLen = indent.length
var lastMatch = 0
while (matcher.find()) {
val wordLen = matcher.start() - lastMatch
if (160 < lineLen + wordLen + 1) {
builder.append("\n")
lineLen = indent.length
}
builder.append(if (lineLen == indent.length) indent else " ")
builder.append(paragraph, lastMatch, matcher.start())
lineLen += wordLen + 1
lastMatch = matcher.end()
}
} | bsd-3-clause | 5cb96b889c48a9256c1c28fb40709b53 | 39.930736 | 135 | 0.44106 | 5.088536 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/domain/aggregated/data/internal/AggregatedDataCallBundleFactoryShould.kt | 1 | 5466 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.domain.aggregated.data.internal
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.dataset.DataSet
import org.hisp.dhis.android.core.dataset.DataSetCollectionRepository
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitCollectionRepository
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodType
import org.hisp.dhis.android.core.period.internal.PeriodForDataSetManager
import org.hisp.dhis.android.core.settings.DataSetSettings
import org.hisp.dhis.android.core.settings.DataSetSettingsObjectRepository
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AggregatedDataCallBundleFactoryShould {
private val dataSetRepository: DataSetCollectionRepository = mock()
private val organisationUnitRepository: OrganisationUnitCollectionRepository = mock()
private val dataSetSettingsObjectRepository: DataSetSettingsObjectRepository = mock()
private val periodManager: PeriodForDataSetManager = mock()
private val aggregatedDataSyncStore: ObjectWithoutUidStore<AggregatedDataSync> = mock()
private val lastUpdatedCalculator: AggregatedDataSyncLastUpdatedCalculator = mock()
private val dataSetSettings: DataSetSettings = mock()
private val dataSet1: DataSet = mock()
private val dataSet2: DataSet = mock()
private val ds1 = "ds1"
private val ds2 = "ds2"
private val ou1 = "ou1"
private val ou2 = "ou2"
private val rootOrgUnits = listOf(ou1, ou2)
private val allOrgUnits = rootOrgUnits.toSet()
private val periods = listOf(Period.builder().periodId("202002").build())
// Object to test
private lateinit var bundleFactory: AggregatedDataCallBundleFactory
@Before
fun setUp() {
whenever(dataSet1.uid()).doReturn(ds1)
whenever(dataSet2.uid()).doReturn(ds2)
whenever(dataSetSettings.specificSettings()).doReturn(emptyMap())
whenever(periodManager.getPeriodsInRange(PeriodType.Monthly, 0, 0)).doReturn(emptyList())
whenever(periodManager.getPeriodsInRange(any(), any(), any())).doReturn(periods)
bundleFactory = AggregatedDataCallBundleFactory(
dataSetRepository, organisationUnitRepository,
dataSetSettingsObjectRepository, periodManager, aggregatedDataSyncStore, lastUpdatedCalculator
)
}
@Test
fun create_single_bundle_if_same_periods() {
whenever(dataSet1.openFuturePeriods()).doReturn(1)
whenever(dataSet1.periodType()).doReturn(PeriodType.Monthly)
whenever(dataSet2.openFuturePeriods()).doReturn(1)
whenever(dataSet2.periodType()).doReturn(PeriodType.Monthly)
val bundles = bundleFactory.getBundlesInternal(
listOf(dataSet1, dataSet2),
dataSetSettings, rootOrgUnits, allOrgUnits, emptyMap()
)
assertThat(bundles.size).isEqualTo(1)
assertThat(bundles[0].dataSets).containsExactly(dataSet1, dataSet2)
}
@Test
fun create_different_bundles_if_different_periods() {
whenever(dataSet1.openFuturePeriods()).doReturn(1)
whenever(dataSet1.periodType()).doReturn(PeriodType.Monthly)
whenever(dataSet2.openFuturePeriods()).doReturn(2)
whenever(dataSet2.periodType()).doReturn(PeriodType.Monthly)
val bundles = bundleFactory.getBundlesInternal(
listOf(dataSet1, dataSet2),
dataSetSettings, rootOrgUnits, allOrgUnits, emptyMap()
)
assertThat(bundles.size).isEqualTo(2)
}
}
| bsd-3-clause | 6c9f2b40294acd3aa5afdb194a786854 | 44.932773 | 106 | 0.757592 | 4.454768 | false | false | false | false |
mdanielwork/intellij-community | python/pydevSrc/com/jetbrains/python/console/pydev/PydevXmlRpcClient.kt | 6 | 4820 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.console.pydev
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.net.NetUtils
import org.apache.xmlrpc.*
import java.net.MalformedURLException
import java.net.URL
import java.util.*
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
/**
* Subclass of XmlRpcClient that will monitor the process so that if the process is destroyed, we stop waiting
* for messages from it.
* @author Fabio
*/
class PydevXmlRpcClient
/**
* Constructor (see fields description)
*/
@Throws(MalformedURLException::class)
constructor(private val process: Process, hostname: String?, port: Int) : IPydevXmlRpcClient {
/**
* Internal xml-rpc client (responsible for the actual communication with the server)
*/
private val impl: XmlRpcClient
private val requestSynchronizer = Semaphore(1, true)
init {
XmlRpc.setDefaultInputEncoding("UTF8") //even though it uses UTF anyway
impl = XmlRpcClientLite(hostname ?: NetUtils.getLocalHostString(), port)
impl.maxThreads = 1
}
constructor(process: Process, port: Int) : this(process = process, hostname = null, port = port)
override fun execute(command: String, args: Array<Any>): Any {
return execute(command, args, TIME_LIMIT)
}
/**
* Executes a command in the server.
*
*
* Within this method, we should be careful about being able to return if the server dies.
* If we wanted to have a timeout, this would be the place to add it.
* @return the result from executing the given command in the server.
*/
@Throws(XmlRpcException::class)
override fun execute(command: String, args: Array<Any>, timeoutMillis: Long): Any {
val result = arrayOf<Any?>(null)
val started = System.currentTimeMillis()
/* Try to leave at least 'MIN_TIME_SLICE' time for actual execution
if not possible then divide the wait times evenly
*/
val semTimeout = maxOf(timeoutMillis - MIN_TIME_SLICE, MIN_TIME_SLICE / 2)
val progress = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator()
try {
if (!requestSynchronizer.tryAcquireWithIndicator(progress, timeoutMillis = semTimeout)) {
throw XmlRpcException(-1, "Timeout while connecting to server")
}
}
catch (e: ProcessCanceledException) {
throw e
}
//make an async call so that we can keep track of not actually having an answer.
try {
impl.executeAsync(command, Vector(Arrays.asList(*args)), object : AsyncCallback {
override fun handleError(error: Exception, url: URL, method: String) {
requestSynchronizer.release()
result[0] = makeError(error.message ?: "Unknown Error")
}
override fun handleResult(recievedResult: Any, url: URL, method: String) {
requestSynchronizer.release()
result[0] = recievedResult
}
})
}
catch (t: Throwable) { // Should not show but just in case!
requestSynchronizer.release()
throw t
}
//busy loop waiting for the answer (or having the console die).
while (result[0] == null && System.currentTimeMillis() - started < timeoutMillis) {
progress.checkCanceled()
val exitValue = process.waitFor(10, TimeUnit.MILLISECONDS)
if (exitValue) {
result[0] = makeError(String.format("Console already exited with value: %s while waiting for an answer.\n", exitValue))
break
}
}
return result[0] ?: throw XmlRpcException(-1, "Timeout while connecting to server")
}
fun makeError(error: String): Array<Any> {
return arrayOf(error)
}
private fun Semaphore.tryAcquireWithIndicator(indicator: ProgressIndicator,
timeoutMillis: Long = TIME_LIMIT,
pollIntervalMillis: Long = 50): Boolean {
indicator.checkCanceled()
val started = System.currentTimeMillis()
while (!this.tryAcquire(1, pollIntervalMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
indicator.checkCanceled()
if (System.currentTimeMillis() - started >= timeoutMillis) {
return false
}
}
return true
}
companion object {
/**
* ItelliJ Logging
*/
private val LOG = Logger.getInstance(PydevXmlRpcClient::class.java.name)
private const val MIN_TIME_SLICE: Long = 1000
private const val TIME_LIMIT: Long = 40000
}
}
| apache-2.0 | d3849323c635c723e25b84b684d246bb | 34.182482 | 140 | 0.690871 | 4.401826 | false | false | false | false |
GreenDelta/olca-conversion-service | src/main/kotlin/app/routes/Converter.kt | 1 | 3192 | package app.routes
import app.Server
import app.model.ConversionResult
import app.model.ConversionSetup
import app.model.Export
import app.model.ExportEcoSpold1
import app.model.ExportEcoSpold2
import app.model.ExportILCD
import app.model.ExportJSON
import app.model.Format
import app.model.Import
import app.model.ImportEcoSpold1
import app.model.ImportEcoSpold2
import app.model.ImportILCD
import app.model.ImportJSON
import app.model.ImportSimaProCsv
import com.google.gson.Gson
import org.openlca.core.database.IDatabase
import jakarta.ws.rs.Consumes
import jakarta.ws.rs.POST
import jakarta.ws.rs.Path
import jakarta.ws.rs.core.MediaType
import jakarta.ws.rs.core.Response
import jakarta.ws.rs.core.Response.Status
@Path("convert")
class Converter {
@POST
@Consumes(MediaType.APPLICATION_JSON)
fun convert(body: String): Response {
val info = Gson().fromJson(body, ConversionSetup::class.java)
val imp = getImport(info)
if (imp == null) {
val msg = "unsupported source format: ${info.sourceFormat}"
return respond(msg, Status.NOT_IMPLEMENTED)
}
val exp = getExport(info)
if (exp == null) {
val msg = "unsupported target format: ${info.targetFormat}"
return respond(msg, Status.NOT_IMPLEMENTED)
}
return doIt(info, imp, exp)
}
private fun doIt(setup: ConversionSetup, imp: Import, exp: Export): Response {
var db: IDatabase? = null
return try {
val refSystem = Server.getRefSystem(setup.refSystem)
db = refSystem.newDB()
imp.doIt(setup, db)
val zipFile = exp.doIt(db)
val result = ConversionResult()
result.zipFile = zipFile.name
result.process = Server.cache!!.firstProcess(db, zipFile)
result.format = exp.format.label
Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build()
} catch (e: Exception) {
val msg = "Conversion failed: ${e.message}"
respond(msg, Status.INTERNAL_SERVER_ERROR)
} finally {
db?.let {
db.close()
db.fileStorageLocation.deleteRecursively()
}
}
}
private fun respond(msg: String, stat: Status): Response {
return Response.status(stat)
.entity(msg)
.type(MediaType.TEXT_PLAIN)
.build()
}
private fun getImport(setup: ConversionSetup): Import? {
return when(Format.get(setup.sourceFormat)) {
Format.ILCD -> ImportILCD()
Format.ECOSPOLD_1 -> ImportEcoSpold1()
Format.ECOSPOLD_2 -> ImportEcoSpold2()
Format.JSON_LD -> ImportJSON()
Format.SIMAPRO_CSV -> ImportSimaProCsv()
else -> null
}
}
private fun getExport(setup: ConversionSetup): Export? {
return when(Format.get(setup.targetFormat)) {
Format.JSON_LD -> ExportJSON()
Format.ILCD -> ExportILCD()
Format.ECOSPOLD_1 -> ExportEcoSpold1()
Format.ECOSPOLD_2 -> ExportEcoSpold2()
else -> null
}
}
}
| mpl-2.0 | eb2234052b88257b10835cc284292891 | 31.907216 | 82 | 0.623747 | 3.921376 | false | false | false | false |
ogarcia/ultrasonic | ultrasonic/src/test/kotlin/org/moire/ultrasonic/domain/APISearchConverterTest.kt | 2 | 3116 | @file:Suppress("IllegalIdentifier")
package org.moire.ultrasonic.domain
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.`should not equal`
import org.junit.Test
import org.moire.ultrasonic.api.subsonic.models.Album
import org.moire.ultrasonic.api.subsonic.models.Artist
import org.moire.ultrasonic.api.subsonic.models.MusicDirectoryChild
import org.moire.ultrasonic.api.subsonic.models.SearchResult
import org.moire.ultrasonic.api.subsonic.models.SearchThreeResult
import org.moire.ultrasonic.api.subsonic.models.SearchTwoResult
/**
* Unit test for extension function in APISearchConverter.kt file.
*/
class APISearchConverterTest {
@Test
fun `Should convert SearchResult to domain entity`() {
val entity = SearchResult(
offset = 10,
totalHits = 3,
matchList = listOf(
MusicDirectoryChild(id = "101")
)
)
val convertedEntity = entity.toDomainEntity()
with(convertedEntity) {
albums `should not equal` null
albums.size `should be equal to` 0
artists `should not equal` null
artists.size `should be equal to` 0
songs.size `should be equal to` entity.matchList.size
songs[0] `should equal` entity.matchList[0].toDomainEntity()
}
}
@Test
fun `Should convert SearchTwoResult to domain entity`() {
val entity = SearchTwoResult(
listOf(Artist(id = "82", name = "great-artist-name")),
listOf(MusicDirectoryChild(id = "762", artist = "bzz")),
listOf(MusicDirectoryChild(id = "9118", parent = "112"))
)
val convertedEntity = entity.toDomainEntity()
with(convertedEntity) {
artists.size `should be equal to` entity.artistList.size
artists[0] `should equal` entity.artistList[0].toDomainEntity()
albums.size `should be equal to` entity.albumList.size
albums[0] `should equal` entity.albumList[0].toDomainEntity()
songs.size `should be equal to` entity.songList.size
songs[0] `should equal` entity.songList[0].toDomainEntity()
}
}
@Test
fun `Should convert SearchThreeResult to domain entity`() {
val entity = SearchThreeResult(
artistList = listOf(Artist(id = "612", name = "artist1")),
albumList = listOf(Album(id = "221", name = "album1")),
songList = listOf(MusicDirectoryChild(id = "7123", title = "song1"))
)
val convertedEntity = entity.toDomainEntity()
with(convertedEntity) {
artists.size `should be equal to` entity.artistList.size
artists[0] `should equal` entity.artistList[0].toDomainEntity()
albums.size `should be equal to` entity.albumList.size
albums[0] `should equal` entity.albumList[0].toDomainEntity()
songs.size `should be equal to` entity.songList.size
songs[0] `should equal` entity.songList[0].toDomainEntity()
}
}
}
| gpl-3.0 | c87e174908212ef2ea5cdf6c0ee5a0cb | 37.469136 | 80 | 0.645058 | 4.262654 | false | true | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt | 1 | 19432 | /**
* ****************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations
* under the License.
* ****************************************************************************
*/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.SpeedSearchComparator
import com.intellij.ui.TableSpeedSearch
import com.intellij.ui.TableUtil
import com.intellij.ui.hover.TableHoverListener
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.awt.Color
import java.awt.Cursor
import java.awt.KeyboardFocusManager
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.JTable
import javax.swing.ListSelectionModel
import javax.swing.event.ListSelectionListener
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableColumn
import kotlin.math.roundToInt
internal typealias SearchResultStateChangeListener =
(PackageModel.SearchResult, NormalizedPackageVersion<*>?, PackageScope?) -> Unit
@Suppress("MagicNumber") // Swing dimension constants
internal class PackagesTable(
private val project: Project,
private val operationExecutor: OperationExecutor,
private val onSearchResultStateChanged: SearchResultStateChangeListener
) : JBTable(), CopyProvider, DataProvider {
private var lastSelectedDependency: UnifiedDependency? = null
private val operationFactory = PackageSearchOperationFactory()
private val tableModel: PackagesTableModel
get() = model as PackagesTableModel
var transferFocusUp: () -> Unit = { transferFocusBackward() }
private val columnWeights = listOf(
.5f, // Name column
.2f, // Scope column
.2f, // Version column
.1f // Actions column
)
private val nameColumn = NameColumn()
private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) }
private val versionColumn = VersionColumn { packageModel, newVersion ->
updatePackageVersion(packageModel, newVersion)
}
private val actionsColumn = ActionsColumn(project, operationExecutor = ::executeActionColumnOperations)
private val actionsColumnIndex: Int
private val autosizingColumnsIndices: List<Int>
private var targetModules: TargetModules = TargetModules.None
private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY
val selectedPackageStateFlow = MutableStateFlow<UiPackageModel<*>?>(null)
private val listSelectionListener = ListSelectionListener {
val item = getSelectedTableItem()
if (selectedIndex >= 0 && item != null) {
TableUtil.scrollSelectionToVisible(this)
updateAndRepaint()
selectedPackageStateFlow.tryEmit(item.uiPackageModel)
} else {
selectedPackageStateFlow.tryEmit(null)
}
}
val hasInstalledItems: Boolean
get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage }
val firstPackageIndex: Int
get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage }
var selectedIndex: Int
get() = selectedRow
set(value) {
if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) {
setRowSelectionInterval(value, value)
} else {
clearSelection()
}
}
init {
require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" }
model = PackagesTableModel(
nameColumn = nameColumn,
scopeColumn = scopeColumn,
versionColumn = versionColumn,
actionsColumn = actionsColumn
)
val columnInfos = tableModel.columnInfos
actionsColumnIndex = columnInfos.indexOf(actionsColumn)
autosizingColumnsIndices = listOf(
columnInfos.indexOf(scopeColumn),
columnInfos.indexOf(versionColumn),
actionsColumnIndex
)
setTableHeader(InvisibleResizableHeader())
getTableHeader().apply {
reorderingAllowed = false
resizingAllowed = true
}
columnSelectionAllowed = false
setShowGrid(false)
rowHeight = JBUI.getInt(
"PackageSearch.PackagesList.rowHeight",
JBUI.getInt("List.rowHeight", if (PackageSearchUI.isNewUI) 24.scaled() else 20.scaled())
)
setExpandableItemsEnabled(false)
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
putClientProperty("terminateEditOnFocusLost", true)
// By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable.
// In this table, we don't want to navigate between cells - so override the traversal keys by default values.
setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)
)
setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (tableModel.rowCount > 0 && selectedRows.isEmpty()) {
setRowSelectionInterval(0, 0)
}
}
})
PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "shift ENTER") {
clearSelection()
transferFocusUp()
}
selectionModel.addListSelectionListener(listSelectionListener)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (selectedIndex == -1) {
selectedIndex = firstPackageIndex
}
}
})
TableSpeedSearch(this) { item, _ ->
if (item is PackagesTableItem<*>) {
val rawIdentifier = item.packageModel.identifier.rawValue
val name = item.packageModel.remoteInfo?.name?.takeIf { !it.equals(rawIdentifier, ignoreCase = true) }
if (name != null) rawIdentifier + name else rawIdentifier
} else {
""
}
}.apply {
comparator = SpeedSearchComparator(false)
}
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights)
removeComponentListener(this)
}
})
val hoverListener = object : TableHoverListener() {
override fun onHover(table: JTable, row: Int, column: Int) {
val currentCursor = cursor
if (tableModel.items.isEmpty() || row < 0) {
if (currentCursor != Cursor.getDefaultCursor()) cursor = Cursor.getDefaultCursor()
return
}
val isHoveringActionsColumn = column == actionsColumnIndex
val desiredCursor = if (isHoveringActionsColumn) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor()
if (currentCursor != desiredCursor) cursor = desiredCursor
}
}
hoverListener.addTo(this)
project.uiStateSource.selectedDependencyFlow.onEach { lastSelectedDependency = it }
.onEach { setSelection(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private fun setSelection(lastSelectedDependencyCopy: UnifiedDependency): Boolean {
val index = tableModel.items.map { it.uiPackageModel }
.indexOfFirst {
it is UiPackageModel.Installed &&
it.selectedVersion.displayName == lastSelectedDependencyCopy.coordinates.version &&
it.packageModel.artifactId == lastSelectedDependencyCopy.coordinates.artifactId &&
it.packageModel.groupId == lastSelectedDependencyCopy.coordinates.groupId &&
(it.selectedScope.displayName == lastSelectedDependencyCopy.scope ||
(it.selectedScope.displayName == "[default]" && lastSelectedDependencyCopy.scope == null))
}
val indexFound = index >= 0
if (indexFound) setRowSelectionInterval(index, index)
return indexFound
}
override fun getCellRenderer(row: Int, column: Int): TableCellRenderer =
tableModel.columns.getOrNull(column)?.getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer()
override fun getCellEditor(row: Int, column: Int): TableCellEditor? =
tableModel.columns.getOrNull(column)?.getEditor(tableModel.items[row])
internal data class ViewModel(
val items: TableItems,
val onlyStable: Boolean,
val targetModules: TargetModules,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
) {
data class TableItems(
val items: List<PackagesTableItem<*>>,
) : List<PackagesTableItem<*>> by items {
companion object {
val EMPTY = TableItems(items = emptyList())
}
}
}
fun display(viewModel: ViewModel) {
knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules
targetModules = viewModel.targetModules
// We need to update those immediately before setting the items, on EDT, to avoid timing issues
// where the target modules or only stable flags get updated after the items data change, thus
// causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages)
versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules)
actionsColumn.updateData(
viewModel.onlyStable,
viewModel.targetModules,
viewModel.knownRepositoriesInTargetModules
)
selectionModel.removeListSelectionListener(listSelectionListener)
tableModel.items = viewModel.items
// TODO size columns
selectionModel.addListSelectionListener(listSelectionListener)
lastSelectedDependency?.let { lastSelectedDependencyCopy ->
if (setSelection(lastSelectedDependencyCopy)) {
lastSelectedDependency = null
}
}
updateAndRepaint()
}
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun performCopy(dataContext: DataContext) {
getSelectedTableItem()?.performCopy(dataContext)
}
override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false
override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false
private fun getSelectedTableItem(): PackagesTableItem<*>? {
if (selectedIndex == -1) {
return null
}
return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*>
}
private fun updatePackageScope(uiPackageModel: UiPackageModel<*>, newScope: PackageScope) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = operationFactory.createChangePackageScopeOperations(
packageModel = uiPackageModel.packageModel,
newScope = newScope,
targetModules = targetModules,
repoToInstall = null
)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for ${uiPackageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
val selectedVersion = uiPackageModel.selectedVersion
onSearchResultStateChanged(uiPackageModel.packageModel, selectedVersion, newScope)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for search result ${uiPackageModel.identifier}: '$newScope'."
}
updateAndRepaint()
}
}
}
private fun updatePackageVersion(uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = uiPackageModel.packageModel.usageInfo.flatMap {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
project = project,
packageModel = uiPackageModel.packageModel,
selectedVersion = newVersion.originalVersion
)
operationFactory.createChangePackageVersionOperations(
packageModel = uiPackageModel.packageModel,
newVersion = newVersion.originalVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for ${uiPackageModel.identifier}: '$newVersion'. " +
"This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
onSearchResultStateChanged(uiPackageModel.packageModel, newVersion, uiPackageModel.selectedScope)
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for search result ${uiPackageModel.identifier}: '$newVersion'."
}
updateAndRepaint()
}
}
}
private fun executeActionColumnOperations(operations: Deferred<List<PackageSearchOperation<*>>>) {
logDebug("PackagesTable#executeActionColumnOperations()") {
"The user has clicked the action for a package. This resulted in many operation(s)."
}
operationExecutor.executeOperations(operations)
}
private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) {
require(columnWeights.size == columns.size) {
"Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights"
}
for (column in columns) {
column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt()
}
}
override fun getBackground(): Color =
if (PackageSearchUI.isNewUI) PackageSearchUI.Colors.panelBackground else UIUtil.getTableBackground()
override fun getForeground(): Color =
if (PackageSearchUI.isNewUI) UIUtil.getListForeground() else UIUtil.getTableForeground()
override fun getSelectionBackground(): Color =
if (PackageSearchUI.isNewUI) UIUtil.getListSelectionBackground(true) else UIUtil.getTableSelectionBackground(true)
override fun getSelectionForeground(): Color =
if (PackageSearchUI.isNewUI) UIUtil.getListSelectionForeground(true) else UIUtil.getTableSelectionForeground(true)
override fun getHoveredRowBackground() = null // Renderers will take care of it
}
| apache-2.0 | 184fa974fa9609506341627517e4e28b | 43.063492 | 152 | 0.682997 | 5.752516 | false | false | false | false |
google/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/SourceFolderManagerImpl.kt | 2 | 13976 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.ProjectTopics
import com.intellij.ide.projectView.actions.MarkRootActionBase
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.MultiMap
import com.intellij.util.xmlb.annotations.XCollection
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.RootConfigurationAccessorForWorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.toBuilder
import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import java.util.concurrent.Future
@State(name = "sourceFolderManager", storages = [Storage(StoragePathMacros.CACHE_FILE)])
class SourceFolderManagerImpl(private val project: Project) : SourceFolderManager, Disposable, PersistentStateComponent<SourceFolderManagerState> {
private val moduleNamesToSourceFolderState: MultiMap<String, SourceFolderModelState> = MultiMap.create()
private var isDisposed = false
private val mutex = Any()
private var sourceFolders = PathPrefixTreeMap<SourceFolderModel>()
private var sourceFoldersByModule = HashMap<String, ModuleModel>()
private val operationsStates = mutableListOf<Future<*>>()
override fun addSourceFolder(module: Module, url: String, type: JpsModuleSourceRootType<*>) {
synchronized(mutex) {
sourceFolders[url] = SourceFolderModel(module, url, type)
addUrlToModuleModel(module, url)
}
ApplicationManager.getApplication().invokeLater(Runnable {
VirtualFileManager.getInstance().refreshAndFindFileByUrl(url)
}, project.disposed)
}
override fun setSourceFolderPackagePrefix(url: String, packagePrefix: String?) {
synchronized(mutex) {
val sourceFolder = sourceFolders[url] ?: return
sourceFolder.packagePrefix = packagePrefix
}
}
override fun setSourceFolderGenerated(url: String, generated: Boolean) {
synchronized(mutex) {
val sourceFolder = sourceFolders[url] ?: return
sourceFolder.generated = generated
}
}
override fun removeSourceFolders(module: Module) {
synchronized(mutex) {
val moduleModel = sourceFoldersByModule.remove(module.name) ?: return
moduleModel.sourceFolders.forEach { sourceFolders.remove(it) }
}
}
override fun dispose() {
assert(!isDisposed) { "Source folder manager already disposed" }
isDisposed = true
}
@TestOnly
fun isDisposed() = isDisposed
@TestOnly
fun getSourceFolders(moduleName: String) = synchronized(mutex) {
sourceFoldersByModule[moduleName]?.sourceFolders
}
private fun removeSourceFolder(url: String) {
synchronized(mutex) {
val sourceFolder = sourceFolders.remove(url) ?: return
val module = sourceFolder.module
val moduleModel = sourceFoldersByModule[module.name] ?: return
val sourceFolders = moduleModel.sourceFolders
sourceFolders.remove(url)
if (sourceFolders.isEmpty()) {
sourceFoldersByModule.remove(module.name)
}
}
}
private data class SourceFolderModel(
val module: Module,
val url: String,
val type: JpsModuleSourceRootType<*>,
var packagePrefix: String? = null,
var generated: Boolean = false
)
private data class ModuleModel(
val module: Module,
val sourceFolders: MutableSet<String> = CollectionFactory.createFilePathSet()
)
init {
project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>()
val virtualFileManager = VirtualFileManager.getInstance()
for (event in events) {
if (event !is VFileCreateEvent) {
continue
}
val allDescendantValues = synchronized(mutex) { sourceFolders.getAllDescendantValues(VfsUtilCore.pathToUrl(event.path)) }
for (sourceFolder in allDescendantValues) {
val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url)
if (sourceFolderFile != null && sourceFolderFile.isValid) {
sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(event.file!!, sourceFolder))
removeSourceFolder(sourceFolder.url)
}
}
}
val application = ApplicationManager.getApplication()
val future = project.coroutineScope.async { updateSourceFolders(sourceFoldersToChange) }.asCompletableFuture()
if (application.isUnitTestMode) {
ApplicationManager.getApplication().assertIsDispatchThread()
operationsStates.removeIf { it.isDone }
operationsStates.add(future)
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun modulesAdded(project: Project, modules: List<Module>) {
synchronized(mutex) {
for (module in modules) {
moduleNamesToSourceFolderState[module.name].forEach {
loadSourceFolderState(it, module)
}
moduleNamesToSourceFolderState.remove(module.name)
}
}
}
})
}
fun rescanAndUpdateSourceFolders() {
val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>()
val virtualFileManager = VirtualFileManager.getInstance()
val values = synchronized(mutex) { sourceFolders.values }
for (sourceFolder in values) {
val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url)
if (sourceFolderFile != null && sourceFolderFile.isValid) {
sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(sourceFolderFile, sourceFolder))
removeSourceFolder(sourceFolder.url)
}
}
updateSourceFolders(sourceFoldersToChange)
}
private fun updateSourceFolders(sourceFoldersToChange: Map<Module, List<Pair<VirtualFile, SourceFolderModel>>>) {
sourceFoldersToChange.keys.groupBy { it.project }.forEach { (key, values) ->
batchUpdateModels(key, values) { model ->
val p = sourceFoldersToChange[model.module] ?: error("Value for the module ${model.module.name} should be available")
for ((eventFile, sourceFolders) in p) {
val (_, url, type, packagePrefix, generated) = sourceFolders
val contentEntry = MarkRootActionBase.findContentEntry(model, eventFile)
?: model.addContentEntry(url)
val sourceFolder = contentEntry.addSourceFolder(url, type)
if (!packagePrefix.isNullOrEmpty()) {
sourceFolder.packagePrefix = packagePrefix
}
setForGeneratedSources(sourceFolder, generated)
}
}
}
}
private fun batchUpdateModels(project: Project, modules: Collection<Module>, modifier: (ModifiableRootModel) -> Unit) {
val diffBuilder = WorkspaceModel.getInstance(project).entityStorage.current.toBuilder()
val modifiableRootModels = modules.asSequence().filter { !it.isDisposed }.map { module ->
val moduleRootComponentBridge = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge
val modifiableRootModel = moduleRootComponentBridge.getModifiableModelForMultiCommit(ExternalSystemRootConfigurationAccessor(diffBuilder),
false)
modifiableRootModel as ModifiableRootModelBridge
modifier.invoke(modifiableRootModel)
modifiableRootModel.prepareForCommit()
modifiableRootModel
}.toList()
ApplicationManager.getApplication().invokeAndWait {
WriteAction.run<RuntimeException> {
if (project.isDisposed) return@run
WorkspaceModel.getInstance(project).updateProjectModel { updater ->
updater.addDiff(diffBuilder)
}
modifiableRootModels.forEach { it.postCommit() }
}
}
}
private fun setForGeneratedSources(folder: SourceFolder, generated: Boolean) {
val jpsElement = folder.jpsElement
val properties = jpsElement.getProperties(JavaModuleSourceRootTypes.SOURCES)
if (properties != null) properties.isForGeneratedSources = generated
}
override fun getState(): SourceFolderManagerState {
synchronized(mutex) {
return SourceFolderManagerState(sourceFolders.valueSequence
.mapNotNull { model ->
val modelTypeName = dictionary.entries.find { it.value == model.type }?.key ?: return@mapNotNull null
SourceFolderModelState(model.module.name,
model.url,
modelTypeName,
model.packagePrefix,
model.generated)
}
.toList())
}
}
override fun loadState(state: SourceFolderManagerState) {
synchronized(mutex) {
resetModuleAddedListeners()
if (isDisposed) {
return
}
sourceFolders = PathPrefixTreeMap()
sourceFoldersByModule = HashMap()
val moduleManager = ModuleManager.getInstance(project)
state.sourceFolders.forEach { model ->
val module = moduleManager.findModuleByName(model.moduleName)
if (module == null) {
listenToModuleAdded(model)
return@forEach
}
loadSourceFolderState(model, module)
}
}
}
private fun resetModuleAddedListeners() = moduleNamesToSourceFolderState.clear()
private fun listenToModuleAdded(model: SourceFolderModelState) = moduleNamesToSourceFolderState.putValue(model.moduleName, model)
private fun loadSourceFolderState(model: SourceFolderModelState,
module: Module) {
val rootType: JpsModuleSourceRootType<*> = dictionary[model.type] ?: return
val url = model.url
sourceFolders[url] = SourceFolderModel(module, url, rootType, model.packagePrefix, model.generated)
addUrlToModuleModel(module, url)
}
private fun addUrlToModuleModel(module: Module, url: String) {
val moduleModel = sourceFoldersByModule.getOrPut(module.name) {
ModuleModel(module).also {
Disposer.register(module, Disposable {
removeSourceFolders(module)
})
}
}
moduleModel.sourceFolders.add(url)
}
@TestOnly
@Throws(Exception::class)
fun consumeBulkOperationsState(stateConsumer: (Future<*>) -> Unit) {
ApplicationManager.getApplication().assertIsDispatchThread()
assert(ApplicationManager.getApplication().isUnitTestMode)
for (operationsState in operationsStates) {
stateConsumer.invoke(operationsState)
}
}
companion object {
val dictionary = mapOf<String, JpsModuleSourceRootType<*>>(
"SOURCE" to JavaSourceRootType.SOURCE,
"TEST_SOURCE" to JavaSourceRootType.TEST_SOURCE,
"RESOURCE" to JavaResourceRootType.RESOURCE,
"TEST_RESOURCE" to JavaResourceRootType.TEST_RESOURCE
)
}
}
class ExternalSystemRootConfigurationAccessor(override val actualDiffBuilder: MutableEntityStorage) : RootConfigurationAccessor(),
RootConfigurationAccessorForWorkspaceModel
data class SourceFolderManagerState(@get:XCollection(style = XCollection.Style.v2) val sourceFolders: Collection<SourceFolderModelState>) {
constructor() : this(mutableListOf())
}
data class SourceFolderModelState(var moduleName: String,
var url: String,
var type: String,
var packagePrefix: String?,
var generated: Boolean) {
constructor(): this("", "", "", null, false)
}
| apache-2.0 | 55668b70b8b541499f72cf815f858cb9 | 42.003077 | 147 | 0.702633 | 5.365067 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/InventoryDebug.kt | 1 | 822 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.api.game.live.Inventory
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
class InventoryDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val cn = Inventory.container ?: return@subscribe
cn.forEach { i ->
g.drawString(i.toString(), x, y)
y += g.font.size + 5
}
})
}
} | mit | 2785c299a6b2c0201da45d6889671977 | 29.481481 | 60 | 0.63382 | 4.151515 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2019/Day06.kt | 1 | 769 | package com.nibado.projects.advent.y2019
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day06 : Day {
private val orbitMap = resourceLines(2019, 6).map { it.split(")").let { (a, b) -> b to a } }.toMap()
private fun path(current: String) : List<String> =
if(current == "COM") listOf("COM") else path(orbitMap.getValue(current)) + current
override fun part1() = orbitMap.keys.map { path(it).size - 1 }.sum()
override fun part2() : Int {
val you = path("YOU").toMutableList()
val santa = path("SAN").toMutableList()
while(you.first() == santa.first()) {
you.removeAt(0)
santa.removeAt(0)
}
return you.size + santa.size - 2
}
} | mit | f83dc7747e4d76b63765f685581059ff | 29.8 | 104 | 0.609883 | 3.527523 | false | false | false | false |
youdonghai/intellij-community | plugins/settings-repository/src/git/JGitMergeProvider.kt | 5 | 4359 | /*
* 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.settingsRepository.git
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.vcs.merge.MergeData
import com.intellij.openapi.vcs.merge.MergeProvider2
import com.intellij.openapi.vcs.merge.MergeSession
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.ui.ColumnInfo
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.RepositoryVirtualFile
import java.nio.CharBuffer
import java.util.*
internal fun conflictsToVirtualFiles(map: Map<String, Any>): MutableList<VirtualFile> {
val result = ArrayList<VirtualFile>(map.size)
for (path in map.keys) {
result.add(RepositoryVirtualFile(path))
}
return result
}
/**
* If content null:
* Ours or Theirs - deleted.
* Base - missed (no base).
*/
class JGitMergeProvider<T>(private val repository: Repository, private val conflicts: Map<String, T>, private val pathToContent: Map<String, T>.(path: String, index: Int) -> ByteArray?) : MergeProvider2 {
override fun createMergeSession(files: List<VirtualFile>): MergeSession = JGitMergeSession()
override fun conflictResolvedForFile(file: VirtualFile) {
// we can postpone dir cache update (on merge dialog close) to reduce number of flush, but it can leads to data loss (if app crashed during merge - nothing will be saved)
// update dir cache
val bytes = (file as RepositoryVirtualFile).content
// not null if user accepts some revision (virtual file will be directly modified), otherwise document will be modified
if (bytes == null) {
val chars = FileDocumentManager.getInstance().getCachedDocument(file)!!.immutableCharSequence
val byteBuffer = Charsets.UTF_8.encode(CharBuffer.wrap(chars))
addFile(byteBuffer.array(), file, byteBuffer.remaining())
}
else {
addFile(bytes, file)
}
}
private fun addFile(bytes: ByteArray, file: VirtualFile, size: Int = bytes.size) {
repository.writePath(file.path, bytes, size)
}
override fun isBinary(file: VirtualFile) = file.fileType.isBinary
override fun loadRevisions(file: VirtualFile): MergeData {
val path = file.path
val mergeData = MergeData()
mergeData.ORIGINAL = getContentOrEmpty(path, 0)
mergeData.CURRENT = getContentOrEmpty(path, 1)
mergeData.LAST = getContentOrEmpty(path, 2)
return mergeData
}
private fun getContentOrEmpty(path: String, index: Int) = conflicts.pathToContent(path, index) ?: ArrayUtil.EMPTY_BYTE_ARRAY
private inner class JGitMergeSession : MergeSession {
override fun getMergeInfoColumns(): Array<ColumnInfo<out Any?, out Any?>> {
return arrayOf(StatusColumn(false), StatusColumn(true))
}
override fun canMerge(file: VirtualFile) = conflicts.contains(file.path)
override fun conflictResolvedForFile(file: VirtualFile, resolution: MergeSession.Resolution) {
if (resolution == MergeSession.Resolution.Merged) {
conflictResolvedForFile(file)
}
else {
val content = getContent(file, resolution == MergeSession.Resolution.AcceptedTheirs)
if (content == null) {
repository.deletePath(file.path)
}
else {
addFile(content, file)
}
}
}
private fun getContent(file: VirtualFile, isTheirs: Boolean) = conflicts.pathToContent(file.path, if (isTheirs) 2 else 1)
inner class StatusColumn(private val isTheirs: Boolean) : ColumnInfo<VirtualFile, String>(if (isTheirs) "Theirs" else "Yours") {
override fun valueOf(file: VirtualFile?) = if (getContent(file!!, isTheirs) == null) "Deleted" else "Modified"
override fun getMaxStringValue() = "Modified"
override fun getAdditionalWidth() = 10
}
}
} | apache-2.0 | 1f0994509d2011bc1dd0415fb079b0f4 | 38.636364 | 204 | 0.729525 | 4.286136 | false | false | false | false |
Leifzhang/AndroidRouter | app/src/main/java/com/kronos/sample/viewbinding/viewbind/ViewHolderViewBinding.kt | 2 | 914 | package com.kronos.sample.viewbinding.viewbind
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.kronos.sample.viewbinding.ext.bindMethod
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* <pre>
* author: dhl
* date : 2020/12/17
* desc :
* </pre>
*/
class ViewHolderViewBinding<T : ViewBinding>(
classes: Class<T>
) : ReadOnlyProperty<RecyclerView.ViewHolder, T> {
private var viewBinding: T? = null
private val bindView = classes.bindMethod()
override fun getValue(thisRef: RecyclerView.ViewHolder, property: KProperty<*>): T {
return viewBinding?.run {
this
} ?: let {
val bind = bindView.invoke(null, thisRef.itemView) as T
bind.apply { viewBinding = this }
}
}
private fun destroyed() {
viewBinding = null
}
} | mit | 613cdaab260763c5cbef38380ac1ccec | 24.416667 | 88 | 0.665208 | 4.251163 | false | false | false | false |
bmunzenb/feed-buddy | src/main/kotlin/com/munzenberger/feed/handler/SendEmail.kt | 1 | 3351 | package com.munzenberger.feed.handler
import com.munzenberger.feed.Enclosure
import com.munzenberger.feed.FeedContext
import com.munzenberger.feed.Item
import org.apache.commons.mail.HtmlEmail
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.io.InputStreamReader
import java.io.StringWriter
import java.text.DecimalFormat
import java.util.Date
import java.util.Properties
import javax.mail.Address
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
class SendEmail : ItemHandler {
lateinit var to: String
lateinit var from: String
lateinit var smtpHost: String
var smtpPort: Int = 0
var auth: Boolean = false
var startTLSEnable: Boolean = false
var startTLSRequired: Boolean = false
var username: String = ""
var password: String = ""
private val session: Session by lazy {
val properties = Properties().apply {
put("mail.transport.protocol", "smtp")
put("mail.smtp.host", smtpHost)
put("mail.smtp.port", smtpPort)
put("mail.smtp.auth", auth)
put("mail.smtp.user", username)
put("mail.smtp.password", password)
put("mail.smtp.starttls.enable", startTLSEnable)
put("mail.smtp.starttls.required", startTLSRequired)
}
Session.getInstance(properties)
}
private val transport: Transport by lazy {
session.transport
}
override fun execute(context: FeedContext, item: Item) {
val htmlEmail = HtmlEmail().apply {
addTo(to)
setFrom(from, context.feedTitle)
item.timestampAsInstant?.let { sentDate = Date.from(it) }
subject = item.title
setHtmlMsg(toHtmlMessage(item))
mailSession = session
buildMimeMessage()
}
if (!transport.isConnected) {
print("Connecting to mail transport $smtpHost:$smtpPort... ")
transport.connect(smtpHost, smtpPort, username, password)
println("connected.")
}
print("Sending email to $to... ")
val message = htmlEmail.mimeMessage
val recipients = arrayOf<Address>(InternetAddress(to))
transport.sendMessage(message, recipients)
println("sent.")
}
private fun toHtmlMessage(item: Item): String {
val mailItem = MailItem(item)
val context = VelocityContext().apply { put("item", mailItem) }
val writer = StringWriter()
val template = javaClass.getResourceAsStream("SendEmail.vm")
?: throw IllegalStateException("Could not open SendEmail.vm")
val reader = InputStreamReader(template)
Velocity.evaluate(context, writer, "", reader)
return writer.toString()
}
}
class MailItem(item: Item) {
val description: String = item.content.encodeForEmail()
val link: String = item.link
val id: String = item.guid
val enclosures: List<Enclosure> = item.enclosures
}
private fun String.encodeForEmail(): String {
val sb = StringBuilder()
val df = DecimalFormat("0000")
forEach { c ->
val i = c.code
when {
i >= 0x7F -> sb.append("&#${df.format(i)};")
else -> sb.append(c)
}
}
return sb.toString()
}
| apache-2.0 | cab8dcb2ff8af15ebcfe5f04c85481fb | 29.743119 | 77 | 0.642495 | 4.285166 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesViewProvider.kt | 1 | 3963 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache.COMMITTED_TOPIC
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentProvider
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier.showOverChangesView
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.ui.content.Content
import com.intellij.util.NotNullFunction
import java.util.function.Supplier
class IncomingChangesViewProvider(private val project: Project) : ChangesViewContentProvider {
private var browser: CommittedChangesTreeBrowser? = null
override fun initTabContent(content: Content) =
createIncomingChangesBrowser().let {
browser = it
content.component = it
content.setDisposer(Disposable { browser = null })
project.messageBus.connect(it).subscribe(COMMITTED_TOPIC, IncomingChangesListener())
loadIncomingChanges(false)
}
private fun createIncomingChangesBrowser(): CommittedChangesTreeBrowser =
CommittedChangesTreeBrowser(project, emptyList()).apply {
emptyText.text = message("incoming.changes.not.loaded.message")
val group = ActionManager.getInstance().getAction("IncomingChangesToolbar") as ActionGroup
setToolBar(createGroupFilterToolbar(project, group, null, emptyList()).component)
setTableContextMenu(group, emptyList())
}
private fun loadIncomingChanges(inBackground: Boolean) {
val cache = CommittedChangesCache.getInstance(project)
cache.hasCachesForAnyRoot { hasCaches: Boolean ->
if (!hasCaches) return@hasCachesForAnyRoot
val cachedIncomingChanges = cache.cachedIncomingChanges
if (cachedIncomingChanges != null) {
browser?.setIncomingChanges(cachedIncomingChanges)
}
else {
cache.loadIncomingChangesAsync(
{ incomingChanges -> runInEdt { browser?.setIncomingChanges(incomingChanges) } },
inBackground
)
}
}
}
private fun CommittedChangesTreeBrowser.setIncomingChanges(changeLists: List<CommittedChangeList>) {
emptyText.text = message("incoming.changes.empty.message")
setItems(changeLists, CommittedChangesBrowserUseCase.INCOMING)
}
private inner class IncomingChangesListener : CommittedChangesListener {
override fun changesLoaded(location: RepositoryLocation, changes: List<CommittedChangeList>) = updateModel()
override fun incomingChangesUpdated(receivedChanges: List<CommittedChangeList>?) = updateModel()
override fun changesCleared() {
browser?.setIncomingChanges(emptyList())
}
override fun refreshErrorStatusChanged(lastError: VcsException?) {
lastError?.let { showOverChangesView(project, it.message, MessageType.ERROR) }
}
private fun updateModel() =
runInEdt {
if (project.isDisposed || browser == null) return@runInEdt
loadIncomingChanges(true)
}
}
class VisibilityPredicate : NotNullFunction<Project, Boolean> {
override fun `fun`(project: Project): Boolean =
ProjectLevelVcsManager.getInstance(project).allActiveVcss.any { isIncomingChangesAvailable(it) }
}
class DisplayNameSupplier : Supplier<String> {
override fun get(): String = message("incoming.changes.tab")
}
companion object {
fun isIncomingChangesAvailable(vcs: AbstractVcs): Boolean =
vcs.cachingCommittedChangesProvider?.supportsIncomingChanges() == true
}
} | apache-2.0 | cbb39812099ff3ab68fd025ab6d4d63e | 38.247525 | 140 | 0.765329 | 4.763221 | false | false | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/internal/ResourceFileSystem.kt | 1 | 7289 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio.internal
import okio.FileHandle
import okio.FileMetadata
import okio.FileNotFoundException
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toOkioPath
import okio.Path.Companion.toPath
import okio.Sink
import okio.Source
import java.io.File
import java.io.IOException
import java.net.URI
import java.net.URL
/**
* A file system exposing Java classpath resources. It is equivalent to the files returned by
* [ClassLoader.getResource] but supports extra features like [metadataOrNull] and [list].
*
* If `.jar` files overlap, this returns an arbitrary element. For overlapping directories it unions
* their contents.
*
* ResourceFileSystem excludes `.class` files.
*
* This file system is read-only.
*/
internal class ResourceFileSystem internal constructor(
classLoader: ClassLoader,
indexEagerly: Boolean,
) : FileSystem() {
private val roots: List<Pair<FileSystem, Path>> by lazy { classLoader.toClasspathRoots() }
init {
if (indexEagerly) {
roots.size
}
}
override fun canonicalize(path: Path): Path {
// TODO(jwilson): throw FileNotFoundException if the canonical file doesn't exist.
return canonicalizeInternal(path)
}
/** Don't throw [FileNotFoundException] if the path doesn't identify a file. */
private fun canonicalizeInternal(path: Path): Path {
return ROOT.resolve(path, normalize = true)
}
override fun list(dir: Path): List<Path> {
val relativePath = dir.toRelativePath()
val result = mutableSetOf<Path>()
var foundAny = false
for ((fileSystem, base) in roots) {
try {
result += fileSystem.list(base / relativePath)
.filter { keepPath(it) }
.map { it.removeBase(base) }
foundAny = true
} catch (_: IOException) {
}
}
if (!foundAny) throw FileNotFoundException("file not found: $dir")
return result.toList()
}
override fun listOrNull(dir: Path): List<Path>? {
val relativePath = dir.toRelativePath()
val result = mutableSetOf<Path>()
var foundAny = false
for ((fileSystem, base) in roots) {
val baseResult = fileSystem.listOrNull(base / relativePath)
?.filter { keepPath(it) }
?.map { it.removeBase(base) }
if (baseResult != null) {
result += baseResult
foundAny = true
}
}
return if (foundAny) result.toList() else null
}
override fun openReadOnly(file: Path): FileHandle {
if (!keepPath(file)) throw FileNotFoundException("file not found: $file")
val relativePath = file.toRelativePath()
for ((fileSystem, base) in roots) {
try {
return fileSystem.openReadOnly(base / relativePath)
} catch (_: FileNotFoundException) {
}
}
throw FileNotFoundException("file not found: $file")
}
override fun openReadWrite(file: Path, mustCreate: Boolean, mustExist: Boolean): FileHandle {
throw IOException("resources are not writable")
}
override fun metadataOrNull(path: Path): FileMetadata? {
if (!keepPath(path)) return null
val relativePath = path.toRelativePath()
for ((fileSystem, base) in roots) {
return fileSystem.metadataOrNull(base / relativePath) ?: continue
}
return null
}
override fun source(file: Path): Source {
if (!keepPath(file)) throw FileNotFoundException("file not found: $file")
val relativePath = file.toRelativePath()
for ((fileSystem, base) in roots) {
try {
return fileSystem.source(base / relativePath)
} catch (_: FileNotFoundException) {
}
}
throw FileNotFoundException("file not found: $file")
}
override fun sink(file: Path, mustCreate: Boolean): Sink {
throw IOException("$this is read-only")
}
override fun appendingSink(file: Path, mustExist: Boolean): Sink {
throw IOException("$this is read-only")
}
override fun createDirectory(dir: Path, mustCreate: Boolean): Unit =
throw IOException("$this is read-only")
override fun atomicMove(source: Path, target: Path): Unit =
throw IOException("$this is read-only")
override fun delete(path: Path, mustExist: Boolean): Unit =
throw IOException("$this is read-only")
override fun createSymlink(source: Path, target: Path): Unit =
throw IOException("$this is read-only")
private fun Path.toRelativePath(): String {
val canonicalThis = canonicalizeInternal(this)
return canonicalThis.relativeTo(ROOT).toString()
}
private companion object {
val ROOT = "/".toPath()
fun Path.removeBase(base: Path): Path {
val prefix = base.toString()
return ROOT / (toString().removePrefix(prefix).replace('\\', '/'))
}
/**
* Returns a search path of classpath roots. Each element contains a file system to use, and
* the base directory of that file system to search from.
*/
fun ClassLoader.toClasspathRoots(): List<Pair<FileSystem, Path>> {
// We'd like to build this upon an API like ClassLoader.getURLs() but unfortunately that
// API exists only on URLClassLoader (and that isn't the default class loader implementation).
//
// The closest we have is `ClassLoader.getResources("")`. It returns all classpath roots that
// are directories but none that are .jar files. To mitigate that we also search for all
// `META-INF/MANIFEST.MF` files, hastily assuming that every .jar file will have such an
// entry.
//
// Classpath entries that aren't directories and don't have a META-INF/MANIFEST.MF file will
// not be visible in this file system.
return getResources("").toList().mapNotNull { it.toFileRoot() } +
getResources("META-INF/MANIFEST.MF").toList().mapNotNull { it.toJarRoot() }
}
fun URL.toFileRoot(): Pair<FileSystem, Path>? {
if (protocol != "file") return null // Ignore unexpected URLs.
return SYSTEM to File(toURI()).toOkioPath()
}
fun URL.toJarRoot(): Pair<FileSystem, Path>? {
val urlString = toString()
if (!urlString.startsWith("jar:file:")) return null // Ignore unexpected URLs.
// Given a URL like `jar:file:/tmp/foo.jar!/META-INF/MANIFEST.MF`, get the path to the archive
// file, like `/tmp/foo.jar`.
val suffixStart = urlString.lastIndexOf("!")
if (suffixStart == -1) return null
val path = File(URI.create(urlString.substring("jar:".length, suffixStart))).toOkioPath()
val zip = openZip(
zipPath = path,
fileSystem = SYSTEM,
predicate = { entry -> keepPath(entry.canonicalPath) }
)
return zip to ROOT
}
private fun keepPath(path: Path) = !path.name.endsWith(".class", ignoreCase = true)
}
}
| apache-2.0 | 68ca9e11dbe899bc21494179e63112e6 | 33.545024 | 100 | 0.677185 | 4.275073 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingJcefHtmlPanel.kt | 2 | 3817 | // 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.jetbrains.python.packaging.toolwindow
import com.google.common.io.Resources
import com.intellij.ide.BrowserUtil
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.jcef.JBCefBrowserBase
import com.intellij.ui.jcef.JBCefJSQuery
import com.intellij.ui.jcef.JCEFHtmlPanel
import com.intellij.util.ui.UIUtil
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandler
import org.cef.handler.CefLoadHandlerAdapter
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicInteger
class PyPackagingJcefHtmlPanel(project: Project) : JCEFHtmlPanel(uniqueUrl) {
private val openInBrowser = JBCefJSQuery.create(this as JBCefBrowserBase)
private val loadedStyles: MutableMap<String, String> = mutableMapOf()
private val myCefLoadHandler: CefLoadHandler
private var myLastHtml: @NlsSafe String? = null
private val jsCodeToInject: String
private val cssStyleCodeToInject: String
get() {
val styleKey = if (UIUtil.isUnderDarcula()) "python_packaging_toolwindow_darcula.css" else "python_packaging_toolwindow_default.css"
return loadedStyles.getOrPut(styleKey) {
try {
val resource = PyPackagingJcefHtmlPanel::class.java.getResource("/styles/$styleKey") ?: error("Failed to load $styleKey")
val loadedCss = Resources.toString(resource, StandardCharsets.UTF_8)
"<style>$loadedCss</style>"
}
catch (e: IOException) {
throw RuntimeException("Failed to load $styleKey", e)
}
}
}
init {
try {
val script = PyPackagingJcefHtmlPanel::class.java.getResource("/js/pkg_toolwindow_open_in_browser.js")
?: error("Failed to load js script for Python Packaging toolwindow.")
jsCodeToInject = Resources.toString(script, StandardCharsets.UTF_8)
}
catch (e: IOException) {
throw RuntimeException("Failed to load js script for Python Packaging toolwindow.", e)
}
myCefLoadHandler = object : CefLoadHandlerAdapter() {
override fun onLoadingStateChange(browser: CefBrowser, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean) {
if (jsCodeToInject != null) {
browser.executeJavaScript(jsCodeToInject, cefBrowser.url, 0)
browser.executeJavaScript("window.__IntelliJTools.openInBrowserCallback = link => {"
+ openInBrowser.inject("link") + "}",
cefBrowser.url, 0)
}
}
}
jbCefClient.addLoadHandler(myCefLoadHandler, cefBrowser)
openInBrowser.addHandler {
if (it.isNotEmpty()) BrowserUtil.browse(it)
null
}
Disposer.register(this, openInBrowser)
project.messageBus.connect(this).subscribe(LafManagerListener.TOPIC, LafManagerListener {
if (myLastHtml != null) setHtml(myLastHtml!!)
})
}
override fun prepareHtml(html: String): String = html.replaceFirst("<head>", "<head>$cssStyleCodeToInject")
override fun setHtml(html: String) {
myLastHtml = html
super.setHtml(html)
}
override fun dispose() {
super.dispose()
jbCefClient.removeLoadHandler(myCefLoadHandler, cefBrowser)
}
companion object {
private val ourCounter = AtomicInteger(-1)
private val ourClassUrl = PyPackagingJcefHtmlPanel::class.java.getResource(
PyPackagingJcefHtmlPanel::class.java.simpleName + ".class")!!.toExternalForm()
private val uniqueUrl: String
get() = ourClassUrl + "@" + ourCounter.incrementAndGet()
}
} | apache-2.0 | 6696e0ed63d9f7a43c834f97b64c4d2e | 38.360825 | 140 | 0.716531 | 4.303269 | false | false | false | false |
rightfromleft/weather-app | remote/src/main/java/com/rightfromleftsw/weather/remote/WeatherRemoteImpl.kt | 1 | 2129 | package com.rightfromleftsw.weather.remote
import com.rightfromleftsw.weather.data.model.WeatherEntityData
import com.rightfromleftsw.weather.data.repository.IWeatherRemote
import com.rightfromleftsw.weather.domain.model.Location
import com.rightfromleftsw.weather.remote.mapper.WeatherRemoteEntityMapper
import com.rightfromleftsw.weather.remote.model.WeatherModel
import io.reactivex.Single
import javax.inject.Inject
/**
* Remote implementation for retrieving Bufferoo instances. This class implements the
* [WeatherRemote] from the Data layer as it is that layers responsibility for defining the
* operations in which data store implementation layers can carry out.
*/
class WeatherRemoteImpl @Inject constructor(
private val weatherService: WeatherService,
private val entityMapper: WeatherRemoteEntityMapper):
IWeatherRemote {
override fun getWeatherList(location: Location): Single<List<WeatherEntityData>> {
return weatherService.getWeatherList(location.latitude, location.longitude)
.map { it.weatherModelList }
.map {
val entities = mutableListOf<WeatherEntityData>()
it.forEach { entities.add(entityMapper.mapFromRemote(it)) }
entities
}
}
override fun getWeather(location: Location): Single<WeatherEntityData> {
return weatherService.getWeather(location.latitude, location.longitude)
.map {
val currObsv = it.asJsonObject.get("current_observation").asJsonObject
val temperature = currObsv.get("temperature_string").asString
val locationObj = currObsv.get("display_location").asJsonObject
val longitude = locationObj.get("longitude").asFloat
val latitude = locationObj.get("latitude").asFloat
val timeEpoch = currObsv.get("local_epoch").asLong
WeatherModel(temperature, Location(longitude, latitude), timeEpoch)
}
.map { entityMapper.mapFromRemote(it) }
}
} | mit | 554dccf96bdfda5bfa67cc46e0273533 | 46.333333 | 91 | 0.686238 | 5.180049 | false | false | false | false |
ruslanys/vkmusic | src/main/kotlin/me/ruslanys/vkmusic/Application.kt | 1 | 953 | package me.ruslanys.vkmusic
import javafx.application.Application
import javafx.scene.Scene
import javafx.stage.Stage
import me.ruslanys.vkmusic.controller.LoginController
import me.ruslanys.vkmusic.util.IconUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class Application : AbstractJavaFxApplicationSupport() {
@set:Autowired
lateinit var loginController: LoginController
override fun start(stage: Stage) {
stage.icons.add(IconUtils.getDesktopIcon())
stage.title = "Авторизация"
stage.scene = Scene(loginController.rootView!!)
stage.minWidth = 640.0
stage.minHeight = 480.0
stage.isResizable = true
stage.centerOnScreen()
stage.show()
}
}
fun main(args: Array<String>) {
Application.launch(me.ruslanys.vkmusic.Application::class.java)
} | mit | 1bedaaa9a24cafb3d7c532b5d05c88e5 | 25.942857 | 67 | 0.748408 | 4.077922 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/classes/PSClassConstraint.kt | 1 | 1041 | package org.purescript.psi.classes
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiReference
import org.purescript.psi.name.PSProperName
import org.purescript.psi.PSPsiElement
import org.purescript.psi.PSTypeAtom
import org.purescript.psi.name.PSClassName
/**
* An individual constraint in a class declaration, e.g.
* ```
* Semigroup m
* ```
* in
* ```
* class Semigroup m <= Monoid m
* ```
*/
class PSClassConstraint(node: ASTNode) : PSPsiElement(node) {
/**
* @return the [PSClassName] that identifies this constraint
*/
val identifier: PSClassName
get() = findNotNullChildByClass(PSClassName::class.java)
/**
* @return the [PSTypeAtom] elements that this constraint contains,
* or an empty array if it does not contain any.
*/
val typeAtoms: Array<PSTypeAtom>
get() = findChildrenByClass(PSTypeAtom::class.java)
override fun getName(): String = identifier.name
override fun getReference(): PsiReference =
ClassConstraintReference(this)
}
| bsd-3-clause | 01e2be34b235e2a563d1a1d74b089b43 | 25.692308 | 71 | 0.70317 | 3.988506 | false | false | false | false |
zdary/intellij-community | platform/service-container/src/com/intellij/serviceContainer/containerUtil.kt | 1 | 1798 | // 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.serviceContainer
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.components.Service
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import java.lang.reflect.Modifier
internal fun checkCanceledIfNotInClassInit() {
try {
ProgressManager.checkCanceled()
}
catch (e: ProcessCanceledException) {
// otherwise ExceptionInInitializerError happens and the class is screwed forever
@Suppress("SpellCheckingInspection")
if (!e.stackTrace.any { it.methodName == "<clinit>" }) {
throw e
}
}
}
internal fun isGettingServiceAllowedDuringPluginUnloading(descriptor: PluginDescriptor): Boolean {
return descriptor.isRequireRestart ||
descriptor.pluginId == PluginManagerCore.CORE_ID || descriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID
}
internal fun throwAlreadyDisposedError(serviceDescription: String, componentManager: ComponentManagerImpl, indicator: ProgressIndicator?) {
val error = AlreadyDisposedException("Cannot create $serviceDescription because container is already disposed (container=${componentManager})")
if (indicator == null) {
throw error
}
else {
throw ProcessCanceledException(error)
}
}
internal fun isLightService(serviceClass: Class<*>): Boolean {
// to avoid potentially expensive isAnnotationPresent call, first we check isInterface
return Modifier.isFinal(serviceClass.modifiers) && serviceClass.isAnnotationPresent(Service::class.java)
} | apache-2.0 | d0efb5342d8a20084c4b822d9bfbbe75 | 40.837209 | 145 | 0.791991 | 4.966851 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/ranges/expression/progressionDownToMinValue.kt | 2 | 2445 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// TODO: muted automatically, investigate should it be ran for NATIVE or not
// IGNORE_BACKEND: NATIVE
// Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT!
// WITH_RUNTIME
import java.lang.Integer.MAX_VALUE as MaxI
import java.lang.Integer.MIN_VALUE as MinI
import java.lang.Byte.MAX_VALUE as MaxB
import java.lang.Byte.MIN_VALUE as MinB
import java.lang.Short.MAX_VALUE as MaxS
import java.lang.Short.MIN_VALUE as MinS
import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC
fun box(): String {
val list1 = ArrayList<Int>()
val range1 = (MinI + 2) downTo MinI step 1
for (i in range1) {
list1.add(i)
if (list1.size > 23) break
}
if (list1 != listOf<Int>(MinI + 2, MinI + 1, MinI)) {
return "Wrong elements for (MinI + 2) downTo MinI step 1: $list1"
}
val list2 = ArrayList<Int>()
val range2 = (MinB + 2).toByte() downTo MinB step 1
for (i in range2) {
list2.add(i)
if (list2.size > 23) break
}
if (list2 != listOf<Int>((MinB + 2).toInt(), (MinB + 1).toInt(), MinB.toInt())) {
return "Wrong elements for (MinB + 2).toByte() downTo MinB step 1: $list2"
}
val list3 = ArrayList<Int>()
val range3 = (MinS + 2).toShort() downTo MinS step 1
for (i in range3) {
list3.add(i)
if (list3.size > 23) break
}
if (list3 != listOf<Int>((MinS + 2).toInt(), (MinS + 1).toInt(), MinS.toInt())) {
return "Wrong elements for (MinS + 2).toShort() downTo MinS step 1: $list3"
}
val list4 = ArrayList<Long>()
val range4 = (MinL + 2).toLong() downTo MinL step 1
for (i in range4) {
list4.add(i)
if (list4.size > 23) break
}
if (list4 != listOf<Long>((MinL + 2).toLong(), (MinL + 1).toLong(), MinL)) {
return "Wrong elements for (MinL + 2).toLong() downTo MinL step 1: $list4"
}
val list5 = ArrayList<Char>()
val range5 = (MinC + 2) downTo MinC step 1
for (i in range5) {
list5.add(i)
if (list5.size > 23) break
}
if (list5 != listOf<Char>((MinC + 2), (MinC + 1), MinC)) {
return "Wrong elements for (MinC + 2) downTo MinC step 1: $list5"
}
return "OK"
}
| apache-2.0 | 44fc704d8d8f744eae1010ed26d291ae | 32.040541 | 102 | 0.619223 | 3.134615 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/argumentOrder/varargAndDefaultParameters_ForNative.kt | 1 | 1653 | // NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
// WITH_RUNTIME
// TARGET_BACKEND: NATIVE
package test
open class A(val value: String)
var invokeOrder = ""
inline fun inlineFun(
vararg constraints: A,
receiver: String = { invokeOrder += " default receiver"; "DEFAULT" }(),
init: String
): String {
return constraints.map { it.value }.joinToString() + ", " + receiver + ", " + init
}
// FILE: 2.kt
import test.*
var result = ""
fun box(): String {
result = ""
invokeOrder = ""
result = inlineFun(constraints = { invokeOrder += "constraints";A("C") }(),
receiver = { invokeOrder += " receiver"; "R" }(),
init = { invokeOrder += " init"; "I" }())
if (result != "C, R, I") return "fail 1: $result"
if (invokeOrder != "constraints receiver init") return "fail 2: $invokeOrder"
result = ""
invokeOrder = ""
result = inlineFun(init = { invokeOrder += "init"; "I" }(),
constraints = { invokeOrder += "constraints";A("C") }(),
receiver = { invokeOrder += " receiver"; "R" }()
)
if (result != "C, R, I") return "fail 3: $result"
//Change test after KT-17691 FIX
if (invokeOrder != "init receiverconstraints") return "fail 4: $invokeOrder"
result = ""
invokeOrder = ""
result = inlineFun(init = { invokeOrder += "init"; "I" }(),
constraints = { invokeOrder += " constraints";A("C") }())
if (result != "C, DEFAULT, I") return "fail 5: $result"
if (invokeOrder != "init constraints default receiver") return "fail 6: $invokeOrder"
return "OK"
}
| apache-2.0 | b64f94c5a938de50ee0ef5a5ca924e1f | 29.611111 | 89 | 0.554144 | 3.791284 | false | true | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/shard/TestMethodTime.kt | 1 | 1192 | package ftl.shard
import ftl.args.IArgs
import ftl.util.FlankTestMethod
fun getTestMethodTime(
flankTestMethod: FlankTestMethod,
previousMethodDurations: Map<String, Double>,
defaultTestTime: Double,
defaultClassTestTime: Double
) = if (flankTestMethod.ignored) IGNORE_TEST_TIME else previousMethodDurations.getOrElse(flankTestMethod.testName) {
if (flankTestMethod.isParameterizedClass) defaultClassTestTime
else defaultTestTime
}
fun IArgs.fallbackTestTime(
previousMethodDurations: Map<String, Double>
) = if (useAverageTestTimeForNewTests) previousMethodDurations.averageTestTime(defaultTestTime) else defaultTestTime
fun IArgs.fallbackClassTestTime(
previousMethodDurations: Map<String, Double>
) = if (useAverageTestTimeForNewTests) previousMethodDurations.averageTestTime(defaultClassTestTime) else defaultClassTestTime
private fun Map<String, Double>.averageTestTime(defaultTestTime: Double) = values
.filter { it > IGNORE_TEST_TIME }
.average()
.takeIf { !it.isNaN() }
?: defaultTestTime
const val IGNORE_TEST_TIME = 0.0
const val DEFAULT_TEST_TIME_SEC = 120.0
const val DEFAULT_CLASS_TEST_TIME_SEC = DEFAULT_TEST_TIME_SEC * 2
| apache-2.0 | c90b9c8d32e82de1f37dec9eb464dffe | 34.058824 | 126 | 0.790268 | 4.027027 | false | true | false | false |
fabmax/kool | kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/RigidBody.kt | 1 | 4186 | package de.fabmax.kool.physics
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import org.lwjgl.system.MemoryStack
import physx.common.PxVec3
import physx.extensions.PxRigidBodyExt
import physx.physics.PxForceModeEnum
import physx.physics.PxRigidBody
actual abstract class RigidBody : RigidActor() {
internal val pxRigidBody: PxRigidBody
get() = pxRigidActor as PxRigidBody
actual var mass: Float
get() = pxRigidBody.mass
set(value) { pxRigidBody.mass = value }
private var isInertiaSet = false
actual var inertia: Vec3f
get() = pxRigidBody.massSpaceInertiaTensor.toVec3f(bufInertia)
set(value) {
pxRigidBody.massSpaceInertiaTensor = value.toPxVec3(pxTmpVec)
isInertiaSet = true
}
actual var linearVelocity: Vec3f
get() = pxRigidBody.linearVelocity.toVec3f(bufLinVelocity)
set(value) { pxRigidBody.linearVelocity = value.toPxVec3(pxTmpVec) }
actual var angularVelocity: Vec3f
get() = pxRigidBody.angularVelocity.toVec3f(bufAngVelocity)
set(value) { pxRigidBody.angularVelocity = value.toPxVec3(pxTmpVec) }
actual var maxLinearVelocity: Float
get() = pxRigidBody.maxLinearVelocity
set(value) { pxRigidBody.maxLinearVelocity = value }
actual var maxAngularVelocity: Float
get() = pxRigidBody.maxAngularVelocity
set(value) { pxRigidBody.maxAngularVelocity = value }
actual var linearDamping: Float
get() = pxRigidBody.linearDamping
set(value) { pxRigidBody.linearDamping = value }
actual var angularDamping: Float
get() = pxRigidBody.angularDamping
set(value) { pxRigidBody.angularDamping = value }
private val bufInertia = MutableVec3f()
private val bufLinVelocity = MutableVec3f()
private val bufAngVelocity = MutableVec3f()
private val tmpVec = MutableVec3f()
private val pxTmpVec = PxVec3()
override fun attachShape(shape: Shape) {
super.attachShape(shape)
if (!isInertiaSet) {
inertia = shape.geometry.estimateInertiaForMass(mass)
}
}
override fun release() {
super.release()
pxTmpVec.destroy()
}
actual fun updateInertiaFromShapesAndMass() {
PxRigidBodyExt.setMassAndUpdateInertia(pxRigidBody, mass)
}
actual fun addForceAtPos(force: Vec3f, pos: Vec3f, isLocalForce: Boolean, isLocalPos: Boolean) {
MemoryStack.stackPush().use { mem ->
val pxForce = force.toPxVec3(mem.createPxVec3())
val pxPos = pos.toPxVec3(mem.createPxVec3())
when {
isLocalForce && isLocalPos -> PxRigidBodyExt.addLocalForceAtLocalPos(pxRigidBody, pxForce, pxPos)
isLocalForce && !isLocalPos -> PxRigidBodyExt.addLocalForceAtPos(pxRigidBody, pxForce, pxPos)
!isLocalForce && isLocalPos -> PxRigidBodyExt.addForceAtLocalPos(pxRigidBody, pxForce, pxPos)
else -> PxRigidBodyExt.addForceAtPos(pxRigidBody, pxForce, pxPos)
}
}
}
actual fun addImpulseAtPos(impulse: Vec3f, pos: Vec3f, isLocalImpulse: Boolean, isLocalPos: Boolean) {
MemoryStack.stackPush().use { mem ->
val pxImpulse = impulse.toPxVec3(mem.createPxVec3())
val pxPos = pos.toPxVec3(mem.createPxVec3())
when {
isLocalImpulse && isLocalPos -> PxRigidBodyExt.addLocalForceAtLocalPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
isLocalImpulse && !isLocalPos -> PxRigidBodyExt.addLocalForceAtPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
!isLocalImpulse && isLocalPos -> PxRigidBodyExt.addForceAtLocalPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
else -> PxRigidBodyExt.addForceAtPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
}
}
}
actual fun addTorque(torque: Vec3f, isLocalTorque: Boolean) {
tmpVec.set(torque)
if (isLocalTorque) {
transform.transform(tmpVec, 0f)
}
pxRigidBody.addTorque(tmpVec.toPxVec3(pxTmpVec))
}
} | apache-2.0 | b6bd7c07b539d1d3365e39bbdb41ff85 | 38.130841 | 143 | 0.679169 | 3.87234 | false | false | false | false |
DanielGrech/anko | dsl/testData/functional/15/PropertyTest.kt | 3 | 40245 | public val android.view.SurfaceView.holder: android.view.SurfaceHolder?
get() = getHolder()
public val android.view.TextureView.bitmap: android.graphics.Bitmap?
get() = getBitmap()
public val android.view.TextureView.layerType: Int
get() = getLayerType()
public val android.view.TextureView.surfaceTexture: android.graphics.SurfaceTexture?
get() = getSurfaceTexture()
public val android.view.TextureView.available: Boolean
get() = isAvailable()
public var android.view.TextureView.opaque: Boolean
get() = isOpaque()
set(v) = setOpaque(v)
public var android.view.View.alpha: Float
get() = getAlpha()
set(v) = setAlpha(v)
public var android.view.View.animation: android.view.animation.Animation?
get() = getAnimation()
set(v) = setAnimation(v)
public val android.view.View.baseline: Int
get() = getBaseline()
public var android.view.View.bottom: Int
get() = getBottom()
set(v) = setBottom(v)
public var android.view.View.contentDescription: CharSequence?
get() = getContentDescription()
set(v) = setContentDescription(v)
public val android.view.View.drawableState: IntArray
get() = getDrawableState()
public val android.view.View.drawingCache: android.graphics.Bitmap?
get() = getDrawingCache()
public var android.view.View.drawingCacheBackgroundColor: Int
get() = getDrawingCacheBackgroundColor()
set(v) = setDrawingCacheBackgroundColor(v)
public var android.view.View.drawingCacheQuality: Int
get() = getDrawingCacheQuality()
set(v) = setDrawingCacheQuality(v)
public val android.view.View.drawingTime: Long
get() = getDrawingTime()
public var android.view.View.filterTouchesWhenObscured: Boolean
get() = getFilterTouchesWhenObscured()
set(v) = setFilterTouchesWhenObscured(v)
public val android.view.View.height: Int
get() = getHeight()
public val android.view.View.horizontalFadingEdgeLength: Int
get() = getHorizontalFadingEdgeLength()
public var android.view.View.id: Int
get() = getId()
set(v) = setId(v)
public var android.view.View.keepScreenOn: Boolean
get() = getKeepScreenOn()
set(v) = setKeepScreenOn(v)
public val android.view.View.layerType: Int
get() = getLayerType()
public var android.view.View.layoutParams: android.view.ViewGroup.LayoutParams?
get() = getLayoutParams()
set(v) = setLayoutParams(v)
public var android.view.View.left: Int
get() = getLeft()
set(v) = setLeft(v)
public val android.view.View.matrix: android.graphics.Matrix?
get() = getMatrix()
public val android.view.View.measuredHeight: Int
get() = getMeasuredHeight()
public val android.view.View.measuredHeightAndState: Int
get() = getMeasuredHeightAndState()
public val android.view.View.measuredState: Int
get() = getMeasuredState()
public val android.view.View.measuredWidth: Int
get() = getMeasuredWidth()
public val android.view.View.measuredWidthAndState: Int
get() = getMeasuredWidthAndState()
public var android.view.View.overScrollMode: Int
get() = getOverScrollMode()
set(v) = setOverScrollMode(v)
public val android.view.View.parent: android.view.ViewParent?
get() = getParent()
public var android.view.View.pivotX: Float
get() = getPivotX()
set(v) = setPivotX(v)
public var android.view.View.pivotY: Float
get() = getPivotY()
set(v) = setPivotY(v)
public val android.view.View.resources: android.content.res.Resources?
get() = getResources()
public var android.view.View.right: Int
get() = getRight()
set(v) = setRight(v)
public val android.view.View.rootView: android.view.View?
get() = getRootView()
public var android.view.View.rotation: Float
get() = getRotation()
set(v) = setRotation(v)
public var android.view.View.rotationX: Float
get() = getRotationX()
set(v) = setRotationX(v)
public var android.view.View.rotationY: Float
get() = getRotationY()
set(v) = setRotationY(v)
public var android.view.View.scaleX: Float
get() = getScaleX()
set(v) = setScaleX(v)
public var android.view.View.scaleY: Float
get() = getScaleY()
set(v) = setScaleY(v)
public var android.view.View.scrollBarStyle: Int
get() = getScrollBarStyle()
set(v) = setScrollBarStyle(v)
public var android.view.View.scrollX: Int
get() = getScrollX()
set(v) = setScrollX(v)
public var android.view.View.scrollY: Int
get() = getScrollY()
set(v) = setScrollY(v)
public val android.view.View.solidColor: Int
get() = getSolidColor()
public var android.view.View.systemUiVisibility: Int
get() = getSystemUiVisibility()
set(v) = setSystemUiVisibility(v)
public var android.view.View.tag: Any?
get() = getTag()
set(v) = setTag(v)
public var android.view.View.top: Int
get() = getTop()
set(v) = setTop(v)
public var android.view.View.touchDelegate: android.view.TouchDelegate?
get() = getTouchDelegate()
set(v) = setTouchDelegate(v)
public var android.view.View.translationX: Float
get() = getTranslationX()
set(v) = setTranslationX(v)
public var android.view.View.translationY: Float
get() = getTranslationY()
set(v) = setTranslationY(v)
public val android.view.View.verticalFadingEdgeLength: Int
get() = getVerticalFadingEdgeLength()
public var android.view.View.verticalScrollbarPosition: Int
get() = getVerticalScrollbarPosition()
set(v) = setVerticalScrollbarPosition(v)
public val android.view.View.verticalScrollbarWidth: Int
get() = getVerticalScrollbarWidth()
public val android.view.View.viewTreeObserver: android.view.ViewTreeObserver?
get() = getViewTreeObserver()
public var android.view.View.visibility: Int
get() = getVisibility()
set(v) = setVisibility(v)
public val android.view.View.width: Int
get() = getWidth()
public val android.view.View.windowToken: android.os.IBinder?
get() = getWindowToken()
public val android.view.View.windowVisibility: Int
get() = getWindowVisibility()
public var android.view.View.x: Float
get() = getX()
set(v) = setX(v)
public var android.view.View.y: Float
get() = getY()
set(v) = setY(v)
public var android.view.View.activated: Boolean
get() = isActivated()
set(v) = setActivated(v)
public var android.view.View.clickable: Boolean
get() = isClickable()
set(v) = setClickable(v)
public val android.view.View.dirty: Boolean
get() = isDirty()
public var android.view.View.drawingCacheEnabled: Boolean
get() = isDrawingCacheEnabled()
set(v) = setDrawingCacheEnabled(v)
public var android.view.View.duplicateParentStateEnabled: Boolean
get() = isDuplicateParentStateEnabled()
set(v) = setDuplicateParentStateEnabled(v)
public var android.view.View.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.view.View.focusable: Boolean
get() = isFocusable()
set(v) = setFocusable(v)
public var android.view.View.focusableInTouchMode: Boolean
get() = isFocusableInTouchMode()
set(v) = setFocusableInTouchMode(v)
public val android.view.View.focused: Boolean
get() = isFocused()
public var android.view.View.hapticFeedbackEnabled: Boolean
get() = isHapticFeedbackEnabled()
set(v) = setHapticFeedbackEnabled(v)
public val android.view.View.hardwareAccelerated: Boolean
get() = isHardwareAccelerated()
public var android.view.View.horizontalFadingEdgeEnabled: Boolean
get() = isHorizontalFadingEdgeEnabled()
set(v) = setHorizontalFadingEdgeEnabled(v)
public var android.view.View.horizontalScrollBarEnabled: Boolean
get() = isHorizontalScrollBarEnabled()
set(v) = setHorizontalScrollBarEnabled(v)
public var android.view.View.hovered: Boolean
get() = isHovered()
set(v) = setHovered(v)
public val android.view.View.inEditMode: Boolean
get() = isInEditMode()
public val android.view.View.inTouchMode: Boolean
get() = isInTouchMode()
public val android.view.View.layoutRequested: Boolean
get() = isLayoutRequested()
public var android.view.View.longClickable: Boolean
get() = isLongClickable()
set(v) = setLongClickable(v)
public val android.view.View.opaque: Boolean
get() = isOpaque()
public var android.view.View.pressed: Boolean
get() = isPressed()
set(v) = setPressed(v)
public var android.view.View.saveEnabled: Boolean
get() = isSaveEnabled()
set(v) = setSaveEnabled(v)
public var android.view.View.saveFromParentEnabled: Boolean
get() = isSaveFromParentEnabled()
set(v) = setSaveFromParentEnabled(v)
public var android.view.View.scrollbarFadingEnabled: Boolean
get() = isScrollbarFadingEnabled()
set(v) = setScrollbarFadingEnabled(v)
public var android.view.View.selected: Boolean
get() = isSelected()
set(v) = setSelected(v)
public val android.view.View.shown: Boolean
get() = isShown()
public var android.view.View.soundEffectsEnabled: Boolean
get() = isSoundEffectsEnabled()
set(v) = setSoundEffectsEnabled(v)
public var android.view.View.verticalFadingEdgeEnabled: Boolean
get() = isVerticalFadingEdgeEnabled()
set(v) = setVerticalFadingEdgeEnabled(v)
public var android.view.View.verticalScrollBarEnabled: Boolean
get() = isVerticalScrollBarEnabled()
set(v) = setVerticalScrollBarEnabled(v)
public var android.view.ViewGroup.descendantFocusability: Int
get() = getDescendantFocusability()
set(v) = setDescendantFocusability(v)
public var android.view.ViewGroup.layoutAnimation: android.view.animation.LayoutAnimationController?
get() = getLayoutAnimation()
set(v) = setLayoutAnimation(v)
public var android.view.ViewGroup.layoutTransition: android.animation.LayoutTransition?
get() = getLayoutTransition()
set(v) = setLayoutTransition(v)
public var android.view.ViewGroup.persistentDrawingCache: Int
get() = getPersistentDrawingCache()
set(v) = setPersistentDrawingCache(v)
public var android.view.ViewGroup.alwaysDrawnWithCacheEnabled: Boolean
get() = isAlwaysDrawnWithCacheEnabled()
set(v) = setAlwaysDrawnWithCacheEnabled(v)
public var android.view.ViewGroup.animationCacheEnabled: Boolean
get() = isAnimationCacheEnabled()
set(v) = setAnimationCacheEnabled(v)
public var android.view.ViewGroup.motionEventSplittingEnabled: Boolean
get() = isMotionEventSplittingEnabled()
set(v) = setMotionEventSplittingEnabled(v)
public var android.view.ViewStub.inflatedId: Int
get() = getInflatedId()
set(v) = setInflatedId(v)
public var android.view.ViewStub.layoutResource: Int
get() = getLayoutResource()
set(v) = setLayoutResource(v)
public val android.webkit.WebView.contentHeight: Int
get() = getContentHeight()
public val android.webkit.WebView.favicon: android.graphics.Bitmap?
get() = getFavicon()
public val android.webkit.WebView.hitTestResult: android.webkit.WebView.HitTestResult?
get() = getHitTestResult()
public val android.webkit.WebView.originalUrl: String?
get() = getOriginalUrl()
public val android.webkit.WebView.progress: Int
get() = getProgress()
public val android.webkit.WebView.scale: Float
get() = getScale()
public val android.webkit.WebView.settings: android.webkit.WebSettings?
get() = getSettings()
public val android.webkit.WebView.title: String?
get() = getTitle()
public val android.webkit.WebView.url: String?
get() = getUrl()
public val android.webkit.WebView.privateBrowsingEnabled: Boolean
get() = isPrivateBrowsingEnabled()
public var android.widget.AbsListView.cacheColorHint: Int
get() = getCacheColorHint()
set(v) = setCacheColorHint(v)
public val android.widget.AbsListView.checkedItemIds: LongArray
get() = getCheckedItemIds()
public var android.widget.AbsListView.choiceMode: Int
get() = getChoiceMode()
set(v) = setChoiceMode(v)
public val android.widget.AbsListView.selectedView: android.view.View?
get() = getSelectedView()
public var android.widget.AbsListView.selector: android.graphics.drawable.Drawable?
get() = getSelector()
set(v) = setSelector(v)
public var android.widget.AbsListView.selectorResource: Int
get() = throw AnkoException("'android.widget.AbsListView.selectorResource' property does not have a getter")
set(v) = setSelector(v)
public var android.widget.AbsListView.transcriptMode: Int
get() = getTranscriptMode()
set(v) = setTranscriptMode(v)
public var android.widget.AbsListView.fastScrollAlwaysVisible: Boolean
get() = isFastScrollAlwaysVisible()
set(v) = setFastScrollAlwaysVisible(v)
public var android.widget.AbsListView.fastScrollEnabled: Boolean
get() = isFastScrollEnabled()
set(v) = setFastScrollEnabled(v)
public var android.widget.AbsListView.scrollingCacheEnabled: Boolean
get() = isScrollingCacheEnabled()
set(v) = setScrollingCacheEnabled(v)
public var android.widget.AbsListView.smoothScrollbarEnabled: Boolean
get() = isSmoothScrollbarEnabled()
set(v) = setSmoothScrollbarEnabled(v)
public var android.widget.AbsListView.stackFromBottom: Boolean
get() = isStackFromBottom()
set(v) = setStackFromBottom(v)
public var android.widget.AbsListView.textFilterEnabled: Boolean
get() = isTextFilterEnabled()
set(v) = setTextFilterEnabled(v)
public var android.widget.AbsSeekBar.keyProgressIncrement: Int
get() = getKeyProgressIncrement()
set(v) = setKeyProgressIncrement(v)
public var android.widget.AbsSeekBar.thumbOffset: Int
get() = getThumbOffset()
set(v) = setThumbOffset(v)
public var android.widget.AdapterView<out android.widget.Adapter?>.emptyView: android.view.View?
get() = getEmptyView()
set(v) = setEmptyView(v)
public val android.widget.AdapterView<out android.widget.Adapter?>.firstVisiblePosition: Int
get() = getFirstVisiblePosition()
public val android.widget.AdapterView<out android.widget.Adapter?>.lastVisiblePosition: Int
get() = getLastVisiblePosition()
public var android.widget.AdapterViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.AdapterViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.AutoCompleteTextView.adapter: android.widget.ListAdapter?
get() = getAdapter()
public var android.widget.AutoCompleteTextView.dropDownAnchor: Int
get() = getDropDownAnchor()
set(v) = setDropDownAnchor(v)
public val android.widget.AutoCompleteTextView.dropDownBackground: android.graphics.drawable.Drawable?
get() = getDropDownBackground()
public var android.widget.AutoCompleteTextView.dropDownHeight: Int
get() = getDropDownHeight()
set(v) = setDropDownHeight(v)
public var android.widget.AutoCompleteTextView.dropDownHorizontalOffset: Int
get() = getDropDownHorizontalOffset()
set(v) = setDropDownHorizontalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownVerticalOffset: Int
get() = getDropDownVerticalOffset()
set(v) = setDropDownVerticalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownWidth: Int
get() = getDropDownWidth()
set(v) = setDropDownWidth(v)
public var android.widget.AutoCompleteTextView.listSelection: Int
get() = getListSelection()
set(v) = setListSelection(v)
public var android.widget.AutoCompleteTextView.threshold: Int
get() = getThreshold()
set(v) = setThreshold(v)
public var android.widget.AutoCompleteTextView.validator: android.widget.AutoCompleteTextView.Validator?
get() = getValidator()
set(v) = setValidator(v)
public val android.widget.AutoCompleteTextView.performingCompletion: Boolean
get() = isPerformingCompletion()
public val android.widget.AutoCompleteTextView.popupShowing: Boolean
get() = isPopupShowing()
public var android.widget.CalendarView.date: Long
get() = getDate()
set(v) = setDate(v)
public var android.widget.CalendarView.firstDayOfWeek: Int
get() = getFirstDayOfWeek()
set(v) = setFirstDayOfWeek(v)
public var android.widget.CalendarView.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.CalendarView.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public var android.widget.CalendarView.showWeekNumber: Boolean
get() = getShowWeekNumber()
set(v) = setShowWeekNumber(v)
public var android.widget.CalendarView.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.CheckedTextView.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public var android.widget.Chronometer.base: Long
get() = getBase()
set(v) = setBase(v)
public var android.widget.Chronometer.format: String?
get() = getFormat()
set(v) = setFormat(v)
public var android.widget.CompoundButton.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public val android.widget.DatePicker.calendarView: android.widget.CalendarView?
get() = getCalendarView()
public var android.widget.DatePicker.calendarViewShown: Boolean
get() = getCalendarViewShown()
set(v) = setCalendarViewShown(v)
public val android.widget.DatePicker.dayOfMonth: Int
get() = getDayOfMonth()
public var android.widget.DatePicker.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.DatePicker.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public val android.widget.DatePicker.month: Int
get() = getMonth()
public var android.widget.DatePicker.spinnersShown: Boolean
get() = getSpinnersShown()
set(v) = setSpinnersShown(v)
public val android.widget.DatePicker.year: Int
get() = getYear()
public var android.widget.DatePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public val android.widget.DialerFilter.digits: CharSequence?
get() = getDigits()
public val android.widget.DialerFilter.filterText: CharSequence?
get() = getFilterText()
public val android.widget.DialerFilter.letters: CharSequence?
get() = getLetters()
public var android.widget.DialerFilter.mode: Int
get() = getMode()
set(v) = setMode(v)
public val android.widget.DialerFilter.qwertyKeyboard: Boolean
get() = isQwertyKeyboard()
public var android.widget.ExpandableListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ExpandableListView.expandableListAdapter: android.widget.ExpandableListAdapter?
get() = getExpandableListAdapter()
public val android.widget.ExpandableListView.selectedId: Long
get() = getSelectedId()
public val android.widget.ExpandableListView.selectedPosition: Long
get() = getSelectedPosition()
public val android.widget.FrameLayout.considerGoneChildrenWhenMeasuring: Boolean
get() = getConsiderGoneChildrenWhenMeasuring()
public var android.widget.FrameLayout.foreground: android.graphics.drawable.Drawable?
get() = getForeground()
set(v) = setForeground(v)
public var android.widget.FrameLayout.measureAllChildren: Boolean
get() = getMeasureAllChildren()
set(v) = setMeasureAllChildren(v)
public var android.widget.GridLayout.alignmentMode: Int
get() = getAlignmentMode()
set(v) = setAlignmentMode(v)
public var android.widget.GridLayout.columnCount: Int
get() = getColumnCount()
set(v) = setColumnCount(v)
public var android.widget.GridLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.GridLayout.rowCount: Int
get() = getRowCount()
set(v) = setRowCount(v)
public var android.widget.GridLayout.useDefaultMargins: Boolean
get() = getUseDefaultMargins()
set(v) = setUseDefaultMargins(v)
public var android.widget.GridLayout.columnOrderPreserved: Boolean
get() = isColumnOrderPreserved()
set(v) = setColumnOrderPreserved(v)
public var android.widget.GridLayout.rowOrderPreserved: Boolean
get() = isRowOrderPreserved()
set(v) = setRowOrderPreserved(v)
public var android.widget.GridView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public var android.widget.GridView.numColumns: Int
get() = getNumColumns()
set(v) = setNumColumns(v)
public var android.widget.GridView.stretchMode: Int
get() = getStretchMode()
set(v) = setStretchMode(v)
public val android.widget.HorizontalScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.HorizontalScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.HorizontalScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.widget.ImageView.baseline: Int
get() = getBaseline()
set(v) = setBaseline(v)
public var android.widget.ImageView.baselineAlignBottom: Boolean
get() = getBaselineAlignBottom()
set(v) = setBaselineAlignBottom(v)
public var android.widget.ImageView.imageMatrix: android.graphics.Matrix?
get() = getImageMatrix()
set(v) = setImageMatrix(v)
public var android.widget.ImageView.scaleType: android.widget.ImageView.ScaleType?
get() = getScaleType()
set(v) = setScaleType(v)
public val android.widget.LinearLayout.baseline: Int
get() = getBaseline()
public var android.widget.LinearLayout.baselineAlignedChildIndex: Int
get() = getBaselineAlignedChildIndex()
set(v) = setBaselineAlignedChildIndex(v)
public var android.widget.LinearLayout.dividerPadding: Int
get() = getDividerPadding()
set(v) = setDividerPadding(v)
public var android.widget.LinearLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.LinearLayout.showDividers: Int
get() = getShowDividers()
set(v) = setShowDividers(v)
public var android.widget.LinearLayout.weightSum: Float
get() = getWeightSum()
set(v) = setWeightSum(v)
public var android.widget.LinearLayout.baselineAligned: Boolean
get() = isBaselineAligned()
set(v) = setBaselineAligned(v)
public var android.widget.LinearLayout.measureWithLargestChildEnabled: Boolean
get() = isMeasureWithLargestChildEnabled()
set(v) = setMeasureWithLargestChildEnabled(v)
public var android.widget.ListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ListView.checkItemIds: LongArray
get() = getCheckItemIds()
public var android.widget.ListView.divider: android.graphics.drawable.Drawable?
get() = getDivider()
set(v) = setDivider(v)
public var android.widget.ListView.dividerHeight: Int
get() = getDividerHeight()
set(v) = setDividerHeight(v)
public val android.widget.ListView.footerViewsCount: Int
get() = getFooterViewsCount()
public val android.widget.ListView.headerViewsCount: Int
get() = getHeaderViewsCount()
public var android.widget.ListView.itemsCanFocus: Boolean
get() = getItemsCanFocus()
set(v) = setItemsCanFocus(v)
public val android.widget.ListView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ListView.overscrollFooter: android.graphics.drawable.Drawable?
get() = getOverscrollFooter()
set(v) = setOverscrollFooter(v)
public var android.widget.ListView.overscrollHeader: android.graphics.drawable.Drawable?
get() = getOverscrollHeader()
set(v) = setOverscrollHeader(v)
public val android.widget.ListView.opaque: Boolean
get() = isOpaque()
public var android.widget.NumberPicker.displayedValues: Array<String>?
get() = getDisplayedValues()
set(v) = setDisplayedValues(v)
public var android.widget.NumberPicker.maxValue: Int
get() = getMaxValue()
set(v) = setMaxValue(v)
public var android.widget.NumberPicker.minValue: Int
get() = getMinValue()
set(v) = setMinValue(v)
public val android.widget.NumberPicker.solidColor: Int
get() = getSolidColor()
public var android.widget.NumberPicker.value: Int
get() = getValue()
set(v) = setValue(v)
public var android.widget.NumberPicker.wrapSelectorWheel: Boolean
get() = getWrapSelectorWheel()
set(v) = setWrapSelectorWheel(v)
public var android.widget.ProgressBar.indeterminateDrawable: android.graphics.drawable.Drawable?
get() = getIndeterminateDrawable()
set(v) = setIndeterminateDrawable(v)
public var android.widget.ProgressBar.interpolator: android.view.animation.Interpolator?
get() = getInterpolator()
set(v) = setInterpolator(v)
public var android.widget.ProgressBar.max: Int
get() = getMax()
set(v) = setMax(v)
public var android.widget.ProgressBar.progress: Int
get() = getProgress()
set(v) = setProgress(v)
public var android.widget.ProgressBar.progressDrawable: android.graphics.drawable.Drawable?
get() = getProgressDrawable()
set(v) = setProgressDrawable(v)
public var android.widget.ProgressBar.secondaryProgress: Int
get() = getSecondaryProgress()
set(v) = setSecondaryProgress(v)
public var android.widget.ProgressBar.indeterminate: Boolean
get() = isIndeterminate()
set(v) = setIndeterminate(v)
public var android.widget.RatingBar.numStars: Int
get() = getNumStars()
set(v) = setNumStars(v)
public var android.widget.RatingBar.rating: Float
get() = getRating()
set(v) = setRating(v)
public var android.widget.RatingBar.stepSize: Float
get() = getStepSize()
set(v) = setStepSize(v)
public val android.widget.RatingBar.indicator: Boolean
get() = isIndicator()
public val android.widget.RelativeLayout.baseline: Int
get() = getBaseline()
public val android.widget.ScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.ScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public val android.widget.SearchView.query: CharSequence?
get() = getQuery()
public var android.widget.SearchView.suggestionsAdapter: android.widget.CursorAdapter?
get() = getSuggestionsAdapter()
set(v) = setSuggestionsAdapter(v)
public val android.widget.SearchView.iconfiedByDefault: Boolean
get() = isIconfiedByDefault()
public var android.widget.SearchView.iconified: Boolean
get() = isIconified()
set(v) = setIconified(v)
public var android.widget.SearchView.queryRefinementEnabled: Boolean
get() = isQueryRefinementEnabled()
set(v) = setQueryRefinementEnabled(v)
public var android.widget.SearchView.submitButtonEnabled: Boolean
get() = isSubmitButtonEnabled()
set(v) = setSubmitButtonEnabled(v)
public val android.widget.SlidingDrawer.content: android.view.View?
get() = getContent()
public val android.widget.SlidingDrawer.handle: android.view.View?
get() = getHandle()
public val android.widget.SlidingDrawer.moving: Boolean
get() = isMoving()
public val android.widget.SlidingDrawer.opened: Boolean
get() = isOpened()
public val android.widget.Spinner.baseline: Int
get() = getBaseline()
public var android.widget.Spinner.prompt: CharSequence?
get() = getPrompt()
set(v) = setPrompt(v)
public val android.widget.Switch.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.widget.Switch.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.Switch.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.widget.TabHost.currentTab: Int
get() = getCurrentTab()
set(v) = setCurrentTab(v)
public val android.widget.TabHost.currentTabTag: String?
get() = getCurrentTabTag()
public val android.widget.TabHost.currentTabView: android.view.View?
get() = getCurrentTabView()
public val android.widget.TabHost.currentView: android.view.View?
get() = getCurrentView()
public val android.widget.TabHost.tabContentView: android.widget.FrameLayout?
get() = getTabContentView()
public val android.widget.TabHost.tabWidget: android.widget.TabWidget?
get() = getTabWidget()
public val android.widget.TabWidget.tabCount: Int
get() = getTabCount()
public var android.widget.TabWidget.stripEnabled: Boolean
get() = isStripEnabled()
set(v) = setStripEnabled(v)
public var android.widget.TableLayout.shrinkAllColumns: Boolean
get() = isShrinkAllColumns()
set(v) = setShrinkAllColumns(v)
public var android.widget.TableLayout.stretchAllColumns: Boolean
get() = isStretchAllColumns()
set(v) = setStretchAllColumns(v)
public val android.widget.TableRow.virtualChildCount: Int
get() = getVirtualChildCount()
public var android.widget.TextView.autoLinkMask: Int
get() = getAutoLinkMask()
set(v) = setAutoLinkMask(v)
public val android.widget.TextView.baseline: Int
get() = getBaseline()
public var android.widget.TextView.compoundDrawablePadding: Int
get() = getCompoundDrawablePadding()
set(v) = setCompoundDrawablePadding(v)
public val android.widget.TextView.compoundDrawables: Array<android.graphics.drawable.Drawable>?
get() = getCompoundDrawables()
public val android.widget.TextView.compoundPaddingBottom: Int
get() = getCompoundPaddingBottom()
public val android.widget.TextView.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.widget.TextView.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public val android.widget.TextView.compoundPaddingTop: Int
get() = getCompoundPaddingTop()
public val android.widget.TextView.currentHintTextColor: Int
get() = getCurrentHintTextColor()
public val android.widget.TextView.currentTextColor: Int
get() = getCurrentTextColor()
public var android.widget.TextView.customSelectionActionModeCallback: android.view.ActionMode.Callback?
get() = getCustomSelectionActionModeCallback()
set(v) = setCustomSelectionActionModeCallback(v)
public val android.widget.TextView.editableText: android.text.Editable?
get() = getEditableText()
public var android.widget.TextView.ellipsize: android.text.TextUtils.TruncateAt?
get() = getEllipsize()
set(v) = setEllipsize(v)
public var android.widget.TextView.error: CharSequence?
get() = getError()
set(v) = setError(v)
public val android.widget.TextView.extendedPaddingBottom: Int
get() = getExtendedPaddingBottom()
public val android.widget.TextView.extendedPaddingTop: Int
get() = getExtendedPaddingTop()
public var android.widget.TextView.filters: Array<android.text.InputFilter>?
get() = getFilters()
set(v) = setFilters(v)
public var android.widget.TextView.freezesText: Boolean
get() = getFreezesText()
set(v) = setFreezesText(v)
public var android.widget.TextView.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public var android.widget.TextView.hint: CharSequence?
get() = getHint()
set(v) = setHint(v)
public var android.widget.TextView.hintResource: Int
get() = throw AnkoException("'android.widget.TextView.hintResource' property does not have a getter")
set(v) = setHint(v)
public val android.widget.TextView.hintTextColors: android.content.res.ColorStateList?
get() = getHintTextColors()
public val android.widget.TextView.imeActionId: Int
get() = getImeActionId()
public val android.widget.TextView.imeActionLabel: CharSequence?
get() = getImeActionLabel()
public var android.widget.TextView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.widget.TextView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public val android.widget.TextView.layout: android.text.Layout?
get() = getLayout()
public val android.widget.TextView.lineCount: Int
get() = getLineCount()
public val android.widget.TextView.lineHeight: Int
get() = getLineHeight()
public val android.widget.TextView.linkTextColors: android.content.res.ColorStateList?
get() = getLinkTextColors()
public var android.widget.TextView.linksClickable: Boolean
get() = getLinksClickable()
set(v) = setLinksClickable(v)
public var android.widget.TextView.movementMethod: android.text.method.MovementMethod?
get() = getMovementMethod()
set(v) = setMovementMethod(v)
public val android.widget.TextView.paint: android.text.TextPaint
get() = getPaint()
public var android.widget.TextView.paintFlags: Int
get() = getPaintFlags()
set(v) = setPaintFlags(v)
public var android.widget.TextView.privateImeOptions: String?
get() = getPrivateImeOptions()
set(v) = setPrivateImeOptions(v)
public val android.widget.TextView.selectionEnd: Int
get() = getSelectionEnd()
public val android.widget.TextView.selectionStart: Int
get() = getSelectionStart()
public var android.widget.TextView.text: CharSequence
get() = getText()
set(v) = setText(v)
public var android.widget.TextView.textResource: Int
get() = throw AnkoException("'android.widget.TextView.textResource' property does not have a getter")
set(v) = setText(v)
public val android.widget.TextView.textColors: android.content.res.ColorStateList?
get() = getTextColors()
public var android.widget.TextView.textScaleX: Float
get() = getTextScaleX()
set(v) = setTextScaleX(v)
public var android.widget.TextView.textSize: Float
get() = getTextSize()
set(v) = setTextSize(v)
public var android.widget.TextView.transformationMethod: android.text.method.TransformationMethod?
get() = getTransformationMethod()
set(v) = setTransformationMethod(v)
public var android.widget.TextView.typeface: android.graphics.Typeface?
get() = getTypeface()
set(v) = setTypeface(v)
public val android.widget.TextView.urls: Array<android.text.style.URLSpan>?
get() = getUrls()
public val android.widget.TextView.inputMethodTarget: Boolean
get() = isInputMethodTarget()
public val android.widget.TextView.suggestionsEnabled: Boolean
get() = isSuggestionsEnabled()
public val android.widget.TimePicker.baseline: Int
get() = getBaseline()
public var android.widget.TimePicker.currentHour: Int?
get() = getCurrentHour()
set(v) = setCurrentHour(v)
public var android.widget.TimePicker.currentMinute: Int?
get() = getCurrentMinute()
set(v) = setCurrentMinute(v)
public var android.widget.TimePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.ToggleButton.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.ToggleButton.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public val android.widget.TwoLineListItem.text1: android.widget.TextView?
get() = getText1()
public val android.widget.TwoLineListItem.text2: android.widget.TextView?
get() = getText2()
public val android.widget.VideoView.bufferPercentage: Int
get() = getBufferPercentage()
public val android.widget.VideoView.currentPosition: Int
get() = getCurrentPosition()
public val android.widget.VideoView.duration: Int
get() = getDuration()
public val android.widget.VideoView.playing: Boolean
get() = isPlaying()
public val android.widget.ViewAnimator.baseline: Int
get() = getBaseline()
public val android.widget.ViewAnimator.currentView: android.view.View?
get() = getCurrentView()
public var android.widget.ViewAnimator.displayedChild: Int
get() = getDisplayedChild()
set(v) = setDisplayedChild(v)
public var android.widget.ViewAnimator.inAnimation: android.view.animation.Animation?
get() = getInAnimation()
set(v) = setInAnimation(v)
public var android.widget.ViewAnimator.outAnimation: android.view.animation.Animation?
get() = getOutAnimation()
set(v) = setOutAnimation(v)
public var android.widget.ViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.ViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.ViewSwitcher.nextView: android.view.View?
get() = getNextView()
public var android.view.View.minimumHeight: Int
get() = throw AnkoException("'android.view.View.minimumHeight' property does not have a getter")
set(v) = setMinimumHeight(v)
public var android.view.View.minimumWidth: Int
get() = throw AnkoException("'android.view.View.minimumWidth' property does not have a getter")
set(v) = setMinimumWidth(v)
public var android.widget.TextView.enabled: Boolean
get() = throw AnkoException("'android.widget.TextView.enabled' property does not have a getter")
set(v) = setEnabled(v)
public var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(v)
public var android.widget.TextView.highlightColor: Int
get() = throw AnkoException("'android.widget.TextView.highlightColor' property does not have a getter")
set(v) = setHighlightColor(v)
public var android.widget.TextView.hintTextColor: Int
get() = throw AnkoException("'android.widget.TextView.hintTextColor' property does not have a getter")
set(v) = setHintTextColor(v)
public var android.widget.TextView.linkTextColor: Int
get() = throw AnkoException("'android.widget.TextView.linkTextColor' property does not have a getter")
set(v) = setLinkTextColor(v)
public var android.widget.TextView.minLines: Int
get() = throw AnkoException("'android.widget.TextView.minLines' property does not have a getter")
set(v) = setMinLines(v)
public var android.widget.TextView.maxLines: Int
get() = throw AnkoException("'android.widget.TextView.maxLines' property does not have a getter")
set(v) = setMaxLines(v)
public var android.widget.TextView.lines: Int
get() = throw AnkoException("'android.widget.TextView.lines' property does not have a getter")
set(v) = setLines(v)
public var android.widget.TextView.minEms: Int
get() = throw AnkoException("'android.widget.TextView.minEms' property does not have a getter")
set(v) = setMinEms(v)
public var android.widget.TextView.maxEms: Int
get() = throw AnkoException("'android.widget.TextView.maxEms' property does not have a getter")
set(v) = setMaxEms(v)
public var android.widget.TextView.singleLine: Boolean
get() = throw AnkoException("'android.widget.TextView.singleLine' property does not have a getter")
set(v) = setSingleLine(v)
public var android.widget.TextView.marqueeRepeatLimit: Int
get() = throw AnkoException("'android.widget.TextView.marqueeRepeatLimit' property does not have a getter")
set(v) = setMarqueeRepeatLimit(v)
public var android.widget.TextView.cursorVisible: Boolean
get() = throw AnkoException("'android.widget.TextView.cursorVisible' property does not have a getter")
set(v) = setCursorVisible(v)
public var android.widget.ImageView.imageURI: android.net.Uri?
get() = throw AnkoException("'android.widget.ImageView.imageURI' property does not have a getter")
set(v) = setImageURI(v)
public var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
get() = throw AnkoException("'android.widget.ImageView.imageBitmap' property does not have a getter")
set(v) = setImageBitmap(v)
public var android.widget.RelativeLayout.gravity: Int
get() = throw AnkoException("'android.widget.RelativeLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.LinearLayout.gravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Gallery.gravity: Int
get() = throw AnkoException("'android.widget.Gallery.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Spinner.gravity: Int
get() = throw AnkoException("'android.widget.Spinner.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.GridView.gravity: Int
get() = throw AnkoException("'android.widget.GridView.gravity' property does not have a getter")
set(v) = setGravity(v) | apache-2.0 | 935ccf08c6ac31c9276d751ec0d4abfb | 31.300161 | 112 | 0.740887 | 3.862655 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt | 1 | 10101 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.inspections.RedundantSamConstructorInspection
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
@Suppress("DEPRECATION")
class ObjectLiteralToLambdaInspection : IntentionBasedInspection<KtObjectLiteralExpression>(ObjectLiteralToLambdaIntention::class) {
override fun problemHighlightType(element: KtObjectLiteralExpression): ProblemHighlightType {
val (_, baseType, singleFunction) = extractData(element) ?: return super.problemHighlightType(element)
val bodyBlock = singleFunction.bodyBlockExpression
val lastStatement = bodyBlock?.statements?.lastOrNull()
if (bodyBlock?.anyDescendantOfType<KtReturnExpression> { it != lastStatement } == true) return ProblemHighlightType.INFORMATION
val valueArgument = element.parent as? KtValueArgument
val call = valueArgument?.getStrictParentOfType<KtCallExpression>()
if (call != null) {
val argumentMatch = call.resolveToCall()?.getArgumentMapping(valueArgument) as? ArgumentMatch
if (baseType.constructor != argumentMatch?.valueParameter?.type?.constructor) return ProblemHighlightType.INFORMATION
}
return super.problemHighlightType(element)
}
}
class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention<KtObjectLiteralExpression>(
KtObjectLiteralExpression::class.java,
KotlinBundle.lazyMessage("convert.to.lambda"),
KotlinBundle.lazyMessage("convert.object.literal.to.lambda")
) {
override fun applicabilityRange(element: KtObjectLiteralExpression): TextRange? {
val (baseTypeRef, baseType, singleFunction) = extractData(element) ?: return null
if (!JavaSingleAbstractMethodUtils.isSamType(baseType)) return null
val functionDescriptor = singleFunction.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return null
val overridden = functionDescriptor.overriddenDescriptors.singleOrNull() ?: return null
if (overridden.modality != Modality.ABSTRACT) return null
if (!singleFunction.hasBody()) return null
if (singleFunction.valueParameters.any { it.name == null }) return null
val bodyExpression = singleFunction.bodyExpression!!
val context = bodyExpression.analyze()
val containingDeclaration = functionDescriptor.containingDeclaration
// this-reference
if (bodyExpression.anyDescendantOfType<KtThisExpression> { thisReference ->
context[BindingContext.REFERENCE_TARGET, thisReference.instanceReference] == containingDeclaration
}
) return null
// Recursive call, skip labels
if (ReferencesSearch.search(singleFunction, LocalSearchScope(bodyExpression)).any { it.element !is KtLabelReferenceExpression }) {
return null
}
fun ReceiverValue?.isImplicitClassFor(descriptor: DeclarationDescriptor) =
this is ImplicitClassReceiver && classDescriptor == descriptor
if (bodyExpression.anyDescendantOfType<KtExpression> { expression ->
val resolvedCall = expression.getResolvedCall(context)
resolvedCall?.let {
it.dispatchReceiver.isImplicitClassFor(containingDeclaration) || it.extensionReceiver
.isImplicitClassFor(containingDeclaration)
} == true
}
) return null
return TextRange(element.objectDeclaration.getObjectKeyword()!!.startOffset, baseTypeRef.endOffset)
}
override fun applyTo(element: KtObjectLiteralExpression, editor: Editor?) {
val (_, baseType, singleFunction) = extractData(element)!!
val commentSaver = CommentSaver(element)
val returnSaver = ReturnSaver(singleFunction)
val body = singleFunction.bodyExpression!!
val factory = KtPsiFactory(element)
val newExpression = factory.buildExpression {
appendFixedText(IdeDescriptorRenderers.SOURCE_CODE.renderType(baseType))
appendFixedText("{")
val parameters = singleFunction.valueParameters
val needParameters =
parameters.count() > 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() }
if (needParameters) {
parameters.forEachIndexed { index, parameter ->
if (index > 0) {
appendFixedText(",")
}
appendName(parameter.nameAsSafeName)
}
appendFixedText("->")
}
val lastCommentOwner = if (singleFunction.hasBlockBody()) {
val contentRange = (body as KtBlockExpression).contentRange()
appendChildRange(contentRange)
contentRange.last
} else {
appendExpression(body)
body
}
if (lastCommentOwner?.anyDescendantOfType<PsiComment> { it.tokenType == KtTokens.EOL_COMMENT } == true) {
appendFixedText("\n")
}
appendFixedText("}")
}
val replaced = runWriteActionIfPhysical(element) { element.replaced(newExpression) }
val pointerToReplaced = replaced.createSmartPointer()
val callee = replaced.callee
val callExpression = callee.parent as KtCallExpression
val functionLiteral = callExpression.lambdaArguments.single().getLambdaExpression()!!
val returnLabel = callee.getReferencedNameAsName()
runWriteActionIfPhysical(element) {
returnSaver.restore(functionLiteral, returnLabel)
}
val parentCall = ((replaced.parent as? KtValueArgument)
?.parent as? KtValueArgumentList)
?.parent as? KtCallExpression
if (parentCall != null && RedundantSamConstructorInspection.samConstructorCallsToBeConverted(parentCall)
.singleOrNull() == callExpression
) {
runWriteActionIfPhysical(element) {
commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */)
}
RedundantSamConstructorInspection.replaceSamConstructorCall(callExpression)
if (parentCall.canMoveLambdaOutsideParentheses()) runWriteActionIfPhysical(element) {
parentCall.moveFunctionLiteralOutsideParentheses()
}
} else {
runWriteActionIfPhysical(element) {
commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */)
}
pointerToReplaced.element?.let { replacedByPointer ->
val endOffset = (replacedByPointer.callee.parent as? KtCallExpression)?.typeArgumentList?.endOffset
?: replacedByPointer.callee.endOffset
ShortenReferences.DEFAULT.process(replacedByPointer.containingKtFile, replacedByPointer.startOffset, endOffset)
}
}
}
private val KtExpression.callee
get() = getCalleeExpressionIfAny() as KtNameReferenceExpression
}
private data class Data(
val baseTypeRef: KtTypeReference,
val baseType: KotlinType,
val singleFunction: KtNamedFunction
)
private fun extractData(element: KtObjectLiteralExpression): Data? {
val objectDeclaration = element.objectDeclaration
val singleFunction = objectDeclaration.declarations.singleOrNull() as? KtNamedFunction ?: return null
if (!singleFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val delegationSpecifier = objectDeclaration.superTypeListEntries.singleOrNull() ?: return null
val typeRef = delegationSpecifier.typeReference ?: return null
val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL)
val baseType = bindingContext[BindingContext.TYPE, typeRef] ?: return null
return Data(typeRef, baseType, singleFunction)
} | apache-2.0 | 270abc3a635c594e9e25f8c15263640e | 47.567308 | 158 | 0.72478 | 5.633575 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/export/ExportIntent.kt | 1 | 1504 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.export
import android.content.Intent
import com.vrem.annotation.OpenClass
@OpenClass
class ExportIntent {
internal fun intent(title: String, data: String): Intent {
val intentSend: Intent = intentSend()
intentSend.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intentSend.type = "text/plain"
intentSend.putExtra(Intent.EXTRA_TITLE, title)
intentSend.putExtra(Intent.EXTRA_SUBJECT, title)
intentSend.putExtra(Intent.EXTRA_TEXT, data)
return intentChooser(intentSend, title)
}
internal fun intentSend(): Intent = Intent(Intent.ACTION_SEND)
internal fun intentChooser(intent: Intent, title: String): Intent = Intent.createChooser(intent, title)
} | gpl-3.0 | 97df188b81f4fd54ef3bdbda3d2eb9fe | 36.625 | 107 | 0.734707 | 4.189415 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/adblock/parser/HostsFileParser.kt | 1 | 3410 | package acr.browser.lightning.adblock.parser
import acr.browser.lightning.database.adblock.Host
import acr.browser.lightning.extensions.containsChar
import acr.browser.lightning.extensions.indexOfChar
import acr.browser.lightning.extensions.inlineReplace
import acr.browser.lightning.extensions.inlineReplaceChar
import acr.browser.lightning.extensions.inlineTrim
import acr.browser.lightning.extensions.stringEquals
import acr.browser.lightning.extensions.substringToBuilder
import acr.browser.lightning.log.Logger
import java.io.InputStreamReader
import javax.inject.Inject
/**
* A single threaded parser for a hosts file.
*/
class HostsFileParser @Inject constructor(
private val logger: Logger
) {
private val lineBuilder = StringBuilder()
/**
* Parse the lines of the [input] from a hosts file and return the list of [String] domains held
* in that file.
*/
fun parseInput(input: InputStreamReader): List<Host> {
val time = System.currentTimeMillis()
val domains = ArrayList<Host>(100)
input.use { inputStreamReader ->
inputStreamReader.forEachLine {
parseLine(it, domains)
}
}
logger.log(TAG, "Parsed ad list in: ${(System.currentTimeMillis() - time)} ms")
return domains
}
/**
* Parse a [line] from a hosts file and populate the [parsedList] with the extracted hosts.
*/
private fun parseLine(line: String, parsedList: MutableList<Host>) {
lineBuilder.setLength(0)
lineBuilder.append(line)
if (lineBuilder.isNotEmpty() && lineBuilder[0] != COMMENT_CHAR) {
lineBuilder.inlineReplace(LOCAL_IP_V4, EMPTY)
lineBuilder.inlineReplace(LOCAL_IP_V4_ALT, EMPTY)
lineBuilder.inlineReplace(LOCAL_IP_V6, EMPTY)
lineBuilder.inlineReplaceChar(TAB_CHAR, SPACE_CHAR)
val comment = lineBuilder.indexOfChar(COMMENT_CHAR)
if (comment > 0) {
lineBuilder.setLength(comment)
} else if (comment == 0) {
return
}
lineBuilder.inlineTrim()
if (lineBuilder.isNotEmpty() && !lineBuilder.stringEquals(LOCALHOST)) {
while (lineBuilder.containsChar(SPACE_CHAR)) {
val space = lineBuilder.indexOfChar(SPACE_CHAR)
val partial = lineBuilder.substringToBuilder(0, space)
partial.inlineTrim()
val partialLine = partial.toString()
// Add string to list
parsedList.add(Host(partialLine))
lineBuilder.inlineReplace(partialLine, EMPTY)
lineBuilder.inlineTrim()
}
if (lineBuilder.isNotEmpty()) {
// Add string to list.
parsedList.add(Host(lineBuilder.toString()))
}
}
}
}
companion object {
private const val TAG = "HostsFileParser"
private const val LOCAL_IP_V4 = "127.0.0.1"
private const val LOCAL_IP_V4_ALT = "0.0.0.0"
private const val LOCAL_IP_V6 = "::1"
private const val LOCALHOST = "localhost"
private const val COMMENT_CHAR = '#'
private const val TAB_CHAR = '\t'
private const val SPACE_CHAR = ' '
private const val EMPTY = ""
}
}
| mpl-2.0 | 68aa1d1d5579c4c03e4b9a82c8806ce0 | 33.795918 | 100 | 0.617889 | 4.457516 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/permission/SystemPermissionTest.kt | 1 | 5831 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.permission
import android.app.Activity
import android.content.Context
import android.location.LocationManager
import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(sdk = [Build.VERSION_CODES.S])
class SystemPermissionTest {
private val activity: Activity = mock()
private val locationManager: LocationManager = mock()
private val fixture: SystemPermission = SystemPermission(activity)
@After
fun tearDown() {
verifyNoMoreInteractions(activity)
verifyNoMoreInteractions(locationManager)
}
@Test
fun testEnabledWhenGPSProviderIsEnabled() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManager)
whenever(locationManager.isLocationEnabled).thenReturn(false)
whenever(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)).thenReturn(false)
whenever(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true)
// execute
val actual = fixture.enabled()
// validate
assertTrue(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
verify(locationManager).isLocationEnabled
verify(locationManager).isProviderEnabled(LocationManager.NETWORK_PROVIDER)
verify(locationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)
}
@Test
fun testEnabledWhenLocationEnabled() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManager)
whenever(locationManager.isLocationEnabled).thenReturn(true)
// execute
val actual = fixture.enabled()
// validate
assertTrue(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
verify(locationManager).isLocationEnabled
}
@Test
fun testEnabledWhenNetworkProviderEnabled() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManager)
whenever(locationManager.isLocationEnabled).thenReturn(false)
whenever(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)).thenReturn(true)
// execute
val actual = fixture.enabled()
// validate
assertTrue(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
verify(locationManager).isLocationEnabled
verify(locationManager).isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
@Test
fun testEnabledWhenAllProvidersAreDisabled() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManager)
whenever(locationManager.isLocationEnabled).thenReturn(false)
whenever(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)).thenReturn(false)
whenever(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(false)
// execute
val actual = fixture.enabled()
// validate
assertFalse(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
verify(locationManager).isLocationEnabled
verify(locationManager).isProviderEnabled(LocationManager.NETWORK_PROVIDER)
verify(locationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)
}
@Test
fun testEnabledWhenAllProvidersThrowException() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManager)
whenever(locationManager.isLocationEnabled).thenThrow(RuntimeException::class.java)
whenever(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)).thenThrow(RuntimeException::class.java)
whenever(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenThrow(RuntimeException::class.java)
// execute
val actual = fixture.enabled()
// validate
assertFalse(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
verify(locationManager).isLocationEnabled
verify(locationManager).isProviderEnabled(LocationManager.NETWORK_PROVIDER)
verify(locationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)
}
@Test
fun testEnabled() {
// setup
whenever(activity.getSystemService(Context.LOCATION_SERVICE)).thenThrow(RuntimeException::class.java)
// execute
val actual = fixture.enabled()
// validate
assertFalse(actual)
verify(activity).getSystemService(Context.LOCATION_SERVICE)
}
} | gpl-3.0 | 840f5a2d08c5e27212045279628e2257 | 41.26087 | 125 | 0.743097 | 5.160177 | false | true | false | false |
siosio/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/WorkspaceEntityStorage.kt | 1 | 10409 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
/**
* A prototype of a storage system for the project model which stores data in typed entities. Entities are represented by interfaces
* implementing WorkspaceEntity interface.
*/
/**
* A base interface for entities. A entity may have properties of the following types:
* * primitive types;
* * String;
* * enum;
* * [VirtualFileUrl];
* * [WorkspaceEntity] or [PersistentEntityId];
* * [List] of another allowed type;
* * [Array] of another allowed type;
* * another data class with properties of the allowed types (references to entities must be wrapped into [EntityReference]);
* * sealed abstract class where all implementations satisfy these requirements.
*
* Currently the entities are representing by classes inheriting from WorkspaceEntityBase, and need to have a separate class with `Data`
* suffix extending WorkspaceEntityData to store the actual data.
*/
interface WorkspaceEntity {
val entitySource: EntitySource
/**
* Returns `true` if this entity and [e] have the same type and the same properties. Properties of type [WorkspaceEntity] are compared by
* internal IDs of the corresponding entities.
*/
fun hasEqualProperties(e: WorkspaceEntity): Boolean
fun <E : WorkspaceEntity> createReference(): EntityReference<E>
}
/**
* Base interface for modifiable variant of [Unmodifiable] entity. The implementation can be used to [create a new entity][WorkspaceEntityStorageBuilder.addEntity]
* or [modify an existing value][WorkspaceEntityStorageBuilder.modifyEntity].
*
* Currently the class must inherit from ModifiableWorkspaceEntityBase.
*/
interface ModifiableWorkspaceEntity<Unmodifiable : WorkspaceEntity> : WorkspaceEntity
/**
* Declares a place from which an entity came.
* Usually contains enough information to identify a project location.
* An entity source must be serializable along with entities, so there are some limits to implementation.
* It must be a data class which contains read-only properties of the following types:
* * primitive types;
* * String;
* * enum;
* * [List] of another allowed type;
* * another data class with properties of the allowed types;
* * sealed abstract class where all implementations satisfy these requirements.
*/
interface EntitySource {
val virtualFileUrl: VirtualFileUrl?
get() = null
}
/**
* Marker interface to represent entities which properties aren't loaded and which were added to the storage because other entities requires
* them. Entities which sources implements this interface don't replace existing entities when [WorkspaceEntityStorageBuilder.replaceBySource]
* is called.
*
* For example if we have `FacetEntity` which requires `ModuleEntity`, and need to load facet configuration from *.iml file and load the module
* configuration from some other source, we may use this interface to mark `entitySource` for `ModuleEntity`. This way when content of *.iml
* file is applied to the model via [WorkspaceEntityStorageBuilder.replaceBySource], it won't overwrite actual configuration
* of `ModuleEntity`.
*/
interface DummyParentEntitySource : EntitySource
/**
* Base interface for entities which may need to find all entities referring to them.
*/
interface ReferableWorkspaceEntity : WorkspaceEntity {
/**
* Returns all entities of type [R] which [propertyName] property refers to this entity. Consider using type-safe variant referrers(KProperty1) instead.
*/
fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R>
}
/**
* Returns all entities of type [R] which [property] refers to this entity.
*/
inline fun <E : ReferableWorkspaceEntity, reified R : WorkspaceEntity> E.referrers(property: KProperty1<R, E?>): Sequence<R> {
return referrers(R::class.java, property.name)
}
/**
* Represents a reference to an entity inside of [WorkspaceEntity].
*
* The reference can be obtained via [WorkspaceEntityStorage.createReference].
*
* The reference will return the same entity for the same storage, but the changes in storages should be tracked if the client want to
* use this reference between different storages. For example, if the referred entity was removed from the storage, this reference may
* return null, but it can also return a different (newly added) entity.
*/
abstract class EntityReference<out E : WorkspaceEntity> {
abstract fun resolve(storage: WorkspaceEntityStorage): E?
}
/**
* A base class for typed hierarchical entity IDs. An implementation must be a data class which contains read-only properties of the following types:
* * primitive types,
* * String,
* * enum,
* * another data class with properties of the allowed types;
* * sealed abstract class where all implementations satisfy these requirements.
*/
abstract class PersistentEntityId<out E : WorkspaceEntityWithPersistentId> {
abstract val parentId: PersistentEntityId<*>?
/** Text which can be shown in an error message if id cannot be resolved */
abstract val presentableName: String
fun resolve(storage: WorkspaceEntityStorage): E? = storage.resolve(this)
abstract override fun toString(): String
}
interface WorkspaceEntityWithPersistentId : WorkspaceEntity {
// TODO Make it a property
fun persistentId(): PersistentEntityId<*>
}
/**
* Read-only interface to a storage. Use [WorkspaceEntityStorageBuilder] or [WorkspaceEntityStorageDiffBuilder] to modify it.
*/
interface WorkspaceEntityStorage {
fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E>
fun <E : WorkspaceEntity> entitiesAmount(entityClass: Class<E>): Int
fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>, property: KProperty1<R, EntityReference<E>>): Sequence<R>
fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R>
fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E?
/**
* Please select a name for your mapping in a form `<product_id>.<mapping_name>`.
* E.g.:
* - intellij.modules.bridge
* - intellij.facets.bridge
* - rider.backend.id
*/
fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T>
fun getVirtualFileUrlIndex(): VirtualFileUrlIndex
fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>
fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E>
}
/**
* Writeable interface to a storage. Use it if you need to build a storage from scratch or modify an existing storage in a way which requires
* reading its state after modifications. For simple modifications use [WorkspaceEntityStorageDiffBuilder] instead.
*/
interface WorkspaceEntityStorageBuilder : WorkspaceEntityStorage, WorkspaceEntityStorageDiffBuilder {
override fun <M : ModifiableWorkspaceEntity<T>, T : WorkspaceEntity> addEntity(clazz: Class<M>,
source: EntitySource,
initializer: M.() -> Unit): T
override fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T
override fun <T : WorkspaceEntity> changeSource(e: T, newSource: EntitySource): T
override fun removeEntity(e: WorkspaceEntity)
fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: WorkspaceEntityStorage)
/**
* Return changes in entities recorded in this instance. [original] parameter is used to get the old instances of modified
* and removed entities.
*/
fun collectChanges(original: WorkspaceEntityStorage): Map<Class<*>, List<EntityChange<*>>>
fun toStorage(): WorkspaceEntityStorage
companion object {
@JvmStatic
fun create(): WorkspaceEntityStorageBuilder = WorkspaceEntityStorageBuilderImpl.create()
@JvmStatic
fun from(storage: WorkspaceEntityStorage): WorkspaceEntityStorageBuilder = WorkspaceEntityStorageBuilderImpl.from(storage)
}
}
fun WorkspaceEntityStorage.toBuilder(): WorkspaceEntityStorageBuilder {
return WorkspaceEntityStorageBuilder.from(this)
}
sealed class EntityChange<T : WorkspaceEntity> {
data class Added<T : WorkspaceEntity>(val entity: T) : EntityChange<T>()
data class Removed<T : WorkspaceEntity>(val entity: T) : EntityChange<T>()
data class Replaced<T : WorkspaceEntity>(val oldEntity: T, val newEntity: T) : EntityChange<T>()
}
/**
* Write-only interface to a storage.
*/
interface WorkspaceEntityStorageDiffBuilder {
fun isEmpty(): Boolean
fun <M : ModifiableWorkspaceEntity<T>, T : WorkspaceEntity> addEntity(clazz: Class<M>, source: EntitySource, initializer: M.() -> Unit): T
fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T
fun removeEntity(e: WorkspaceEntity)
fun <T : WorkspaceEntity> changeSource(e: T, newSource: EntitySource): T
fun addDiff(diff: WorkspaceEntityStorageDiffBuilder)
/**
* Please see [WorkspaceEntityStorage.getExternalMapping] for naming conventions
*/
fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T>
/**
* Please see [WorkspaceEntityStorage.getExternalMapping] for naming conventions
*/
fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T>
fun getVirtualFileUrlIndex(): VirtualFileUrlIndex
fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex
val modificationCount: Long
companion object {
@JvmStatic
fun create(underlyingStorage: WorkspaceEntityStorage): WorkspaceEntityStorageDiffBuilder = WorkspaceEntityStorageBuilder.from(underlyingStorage)
}
}
| apache-2.0 | 4d609a37978aec18295b3e46382df1f3 | 44.060606 | 163 | 0.755308 | 4.933175 | false | false | false | false |
alisle/Penella | src/main/java/org/penella/shards/Shard.kt | 1 | 9002 | package org.penella.shards
import io.vertx.core.*
import io.vertx.core.eventbus.Message
import org.penella.MailBoxes
import org.penella.codecs.ShardAddCodec
import org.penella.codecs.ShardGetCodec
import org.penella.codecs.ShardSizeCodec
import org.penella.codecs.ShardSizeResponseCodec
import org.penella.index.IIndexFactory
import org.penella.index.IndexType
import org.penella.index.IndexVertical
import org.penella.index.bstree.InvalidIndexRequest
import org.penella.messages.*
import org.penella.structures.triples.HashTriple
import org.penella.structures.triples.TripleType
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.atomic.AtomicLong
/**
* 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.
*
* Created by alisle on 11/1/16.
*/
class Shard constructor(private val name : String, private val indexFactory: IIndexFactory) : IShard, AbstractVerticle() {
companion object {
private val log: Logger = LoggerFactory.getLogger(Shard::class.java)
fun registerCodecs(vertx: Vertx) {
try {
vertx.eventBus().registerDefaultCodec(ShardGet::class.java, ShardGetCodec())
vertx.eventBus().registerDefaultCodec(ShardSize::class.java, ShardSizeCodec())
vertx.eventBus().registerDefaultCodec(ShardSizeResponse::class.java, ShardSizeResponseCodec())
vertx.eventBus().registerDefaultCodec(ShardAdd::class.java, ShardAddCodec())
} catch (exception : java.lang.IllegalStateException) {
log.info("Unable to register codecs, most likely already registered")
}
}
}
private val indexes = Array(IndexType.values().size, { i -> indexFactory.createIndex(IndexType.values()[i]) })
private val sizeHandler = Handler<Message<ShardSize>> { msg ->
msg.reply(ShardSizeResponse(size()))
}
private val getHandler = Handler<Message<ShardGet>> { msg ->
val get = msg.body()
val type = get.indexType
val triple = get.triple
if(log.isDebugEnabled) log.debug("VERTX Grabbing triple: $triple")
when(type) {
IndexType.SPO -> {
if(triple.hashProperty != 0L) {
vertx.eventBus().send(MailBoxes.INDEX_GET_SECOND.mailbox + "$name-${type.ID}",
IndexGetSecondLayer(TripleType.SUBJECT, triple.hashSubject, TripleType.PROPERTY, triple.hashProperty),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
} else {
vertx.eventBus().send(MailBoxes.INDEX_GET_FIRST.mailbox + "$name-${type.ID}",
IndexGetFirstLayer(TripleType.SUBJECT, triple.hashSubject),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
}
}
IndexType.O -> {
if(triple.hashProperty == 0L && triple.hashSubject == 0L) {
vertx.eventBus().send(MailBoxes.INDEX_GET_FIRST.mailbox + "$name-${type.ID}",
IndexGetFirstLayer(TripleType.OBJECT, triple.hashObj),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
} else {
throw InvalidIndexRequest();
}
}
IndexType.PO -> {
if(triple.hashObj != 0L) {
vertx.eventBus().send(MailBoxes.INDEX_GET_SECOND.mailbox + "$name-${type.ID}",
IndexGetSecondLayer(TripleType.PROPERTY, triple.hashProperty, TripleType.OBJECT, triple.hashObj),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
} else {
vertx.eventBus().send(MailBoxes.INDEX_GET_FIRST.mailbox + "$name-${type.ID}",
IndexGetFirstLayer(TripleType.PROPERTY, triple.hashProperty),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
}
}
IndexType.SO -> {
if(triple.hashObj != 0L) {
vertx.eventBus().send(MailBoxes.INDEX_GET_SECOND.mailbox + "$name-${type.ID}",
IndexGetSecondLayer(TripleType.SUBJECT, triple.hashSubject, TripleType.OBJECT, triple.hashObj),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
} else {
vertx.eventBus().send(MailBoxes.INDEX_GET_FIRST.mailbox + "$name-${type.ID}",
IndexGetFirstLayer(TripleType.SUBJECT, triple.hashSubject),
Handler<AsyncResult<Message<IndexResultSet>>> { response ->
msg.reply(response.result().body())
})
}
}
}
}
private val addHandler = Handler<Message<ShardAdd>> { msg ->
val triple = msg.body().triple
if(log.isDebugEnabled) log.debug("Inserting triple: $triple")
val futures = Array<Future<Message<StatusMessage>>>(IndexType.values().size, { x -> Future.future<Message<StatusMessage>>() })
IndexType.values().forEach { type -> vertx.eventBus().send(MailBoxes.INDEX_ADD_TRIPLE.mailbox + "$name-${type.ID}", IndexAdd(triple), futures[type.ID].completer()) }
val composite = CompositeFuture.all(futures.toList())
composite.setHandler { result ->
msg.reply(StatusMessage(Status.SUCESSFUL, "OK"))
counter.incrementAndGet()
}
}
override fun start(startFuture: Future<Void>?) {
vertx.eventBus().consumer<ShardGet>(MailBoxes.SHARD_GET.mailbox + name).handler(getHandler)
vertx.eventBus().consumer<ShardSize>(MailBoxes.SHARD_SIZE.mailbox + name).handler(sizeHandler)
vertx.eventBus().consumer<ShardAdd>(MailBoxes.SHARD_ADD.mailbox + name).handler(addHandler)
IndexType.values().forEach { type -> vertx.deployVerticle(IndexVertical("$name-${type.ID}", indexes[type.ID])) }
startFuture?.complete()
}
private val counter = AtomicLong(0L)
override fun size() = counter.get()
override fun get(indexType: IndexType, triple: HashTriple): IndexResultSet {
if(log.isDebugEnabled) log.debug("Grabbing triple: $triple")
return when(indexType) {
IndexType.SPO -> {
if(triple.hashProperty != 0L) {
indexes[indexType.ID].get(TripleType.SUBJECT, TripleType.PROPERTY, triple.hashSubject, triple.hashProperty)
} else {
indexes[indexType.ID].get(TripleType.SUBJECT, triple.hashSubject)
}
}
IndexType.O -> {
if(triple.hashProperty == 0L && triple.hashSubject == 0L) {
indexes[indexType.ID].get(TripleType.OBJECT, triple.hashObj)
} else {
throw InvalidIndexRequest();
}
}
IndexType.PO -> {
if(triple.hashObj != 0L) {
indexes[indexType.ID].get(TripleType.PROPERTY, TripleType.OBJECT, triple.hashProperty, triple.hashObj)
} else {
indexes[indexType.ID].get(TripleType.PROPERTY, triple.hashProperty)
}
}
IndexType.SO -> {
if(triple.hashObj != 0L) {
indexes[indexType.ID].get(TripleType.SUBJECT, TripleType.OBJECT, triple.hashSubject, triple.hashObj)
} else {
indexes[indexType.ID].get(TripleType.SUBJECT, triple.hashSubject)
}
}
}
}
override fun add(triple: HashTriple) {
if(log.isDebugEnabled) log.debug("Inserting triple: $triple")
counter.incrementAndGet()
indexes.forEach { x -> x.add(triple) }
}
} | apache-2.0 | ada5f06a9401f7c15b3927eb36bd24d5 | 44.469697 | 173 | 0.58176 | 4.705698 | false | false | false | false |
jwren/intellij-community | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJunitBeforeAfterClassInspectionTest.kt | 1 | 6430 | package com.intellij.codeInspection.tests.kotlin.test.junit
import com.intellij.codeInspection.tests.ULanguage
import com.intellij.codeInspection.tests.test.junit.JUnitBeforeAfterClassInspectionTestBase
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.PathUtil
import java.io.File
class KotlinJunitBeforeAfterClassInspectionTest : JUnitBeforeAfterClassInspectionTestBase() {
override fun getProjectDescriptor(): LightProjectDescriptor = object : ProjectDescriptor(sdkLevel) {
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
super.configureModule(module, model, contentEntry)
val jar = File(PathUtil.getJarPathForClass(JvmStatic::class.java))
PsiTestUtil.addLibrary(model, "kotlin-stdlib", jar.parent, jar.name)
}
}
fun `test @BeforeClass non-static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.BeforeClass
fun <warning descr="'beforeClass()' has incorrect signature for a '@org.junit.BeforeClass' method">beforeClass</warning>() { }
}
""".trimIndent())
}
fun `test @BeforeClass private highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
private fun <warning descr="'beforeClass()' has incorrect signature for a '@org.junit.BeforeClass' method">beforeClass</warning>() { }
}
}
""".trimIndent())
}
fun `test @BeforeClass parameter highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="'beforeClass()' has incorrect signature for a '@org.junit.BeforeClass' method">beforeClass</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test @BeforeClass return type highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="'beforeClass()' has incorrect signature for a '@org.junit.BeforeClass' method">beforeClass</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test @BeforeClass no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun beforeClass() { }
}
}
""".trimIndent())
}
fun `test @BeforeAll non-static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeAll
fun <warning descr="'beforeAll()' has incorrect signature for a '@org.junit.jupiter.api.BeforeAll' method">beforeAll</warning>() { }
}
""".trimIndent())
}
fun `test @BeforeAll private highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
private fun <warning descr="'beforeAll()' has incorrect signature for a '@org.junit.jupiter.api.BeforeAll' method">beforeAll</warning>() { }
}
}
""".trimIndent())
}
fun `test @BeforeAll parameter highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="'beforeAll()' has incorrect signature for a '@org.junit.jupiter.api.BeforeAll' method">beforeAll</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test @BeforeAll return type highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="'beforeAll()' has incorrect signature for a '@org.junit.jupiter.api.BeforeAll' method">beforeAll</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test @BeforeAll no highlighting test instance per class`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MainTest {
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
""".trimIndent())
}
fun `test @BeforeAll no highlighting static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
}
""".trimIndent())
}
fun `test parameter resolver no highlighting`() {
myFixture.addClass("""
package com.intellij.test;
import org.junit.jupiter.api.extension.ParameterResolver;
public class TestParameterResolver implements ParameterResolver { }
""".trimIndent())
myFixture.testHighlighting(ULanguage.KOTLIN, """
import org.junit.jupiter.api.extension.*
import com.intellij.test.TestParameterResolver
@ExtendWith(TestParameterResolver::class)
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
""".trimIndent())
}
fun `test quickfix change full signature`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.api.BeforeAll
class MainTest {
@BeforeAll
fun before<caret>All(i: Int): String { return "" }
}
""".trimIndent(), """
import org.junit.jupiter.api.BeforeAll
class MainTest {
companion object {
@JvmStatic
@BeforeAll
fun beforeAll(): Unit {
return ""
}
}
}
""".trimIndent(), "Fix 'beforeAll' method signature")
}
} | apache-2.0 | 88d8496a106f5aa438e3a6822b4800fc | 32.494792 | 170 | 0.642768 | 4.900915 | false | true | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt | 3 | 3876 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.JBRadioButton
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.awt.event.ActionListener
import javax.swing.AbstractButton
import javax.swing.ButtonGroup
open class LayoutBuilder @PublishedApi internal constructor(@PublishedApi internal val builder: LayoutBuilderImpl) : RowBuilder by builder.rootRow {
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) {
builder.withButtonGroup(buttonGroup, body)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
inline fun buttonGroup(crossinline elementActionListener: () -> Unit, crossinline init: LayoutBuilder.() -> Unit): ButtonGroup {
val group = ButtonGroup()
builder.withButtonGroup(group) {
LayoutBuilder(builder).init()
}
val listener = ActionListener { elementActionListener() }
for (button in group.elements) {
button.addActionListener(listener)
}
return group
}
@Suppress("PropertyName")
@PublishedApi
@get:Deprecated("", replaceWith = ReplaceWith("builder"), level = DeprecationLevel.ERROR)
@get:ApiStatus.ScheduledForRemoval
internal val `$`: LayoutBuilderImpl
get() = builder
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
class CellBuilderWithButtonGroupProperty<T : Any>
@PublishedApi internal constructor(private val prop: PropertyBinding<T>) {
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun Cell.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, prop.get() == value)
return component(comment = comment).bindValue(value)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value)
}
class RowBuilderWithButtonGroupProperty<T : Any>
@PublishedApi internal constructor(private val builder: RowBuilder, private val prop: PropertyBinding<T>) : RowBuilder by builder {
fun Row.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, prop.get() == value)
attachSubRowsEnabled(component)
return component(comment = comment).bindValue(value)
}
fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value)
}
private fun <T> CellBuilder<JBRadioButton>.bindValueToProperty(prop: PropertyBinding<T>, value: T): CellBuilder<JBRadioButton> = apply {
onApply { if (component.isSelected) prop.set(value) }
onReset { component.isSelected = prop.get() == value }
onIsModified { component.isSelected != (prop.get() == value) }
}
fun FileChooserDescriptor.chooseFile(event: AnActionEvent, fileChosen: (chosenFile: VirtualFile) -> Unit) {
FileChooser.chooseFile(this, event.getData(PlatformDataKeys.PROJECT), event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT), null, fileChosen)
}
fun Row.attachSubRowsEnabled(component: AbstractButton) {
enableSubRowsIf(component.selected)
}
| apache-2.0 | 2f2441f8422c913358d7f49daa1aea4f | 41.130435 | 148 | 0.776058 | 4.528037 | false | false | false | false |
jwren/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/reorderJars.kt | 1 | 7872 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.tasks
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.context.Context
import it.unimi.dsi.fastutil.longs.LongSet
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import org.jetbrains.intellij.build.io.*
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.*
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val excludedLibJars = java.util.Set.of("testFramework.core.jar", "testFramework.jar", "testFramework-java.jar")
private fun getClassLoadingLog(): InputStream {
val osName = System.getProperty("os.name")
val classifier = when {
osName.startsWith("windows", ignoreCase = true) -> "windows"
osName.startsWith("mac", ignoreCase = true) -> "mac"
else -> "linux"
}
return PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!!
}
private val sourceToNames: Map<String, MutableList<String>> by lazy {
val sourceToNames = LinkedHashMap<String, MutableList<String>>()
getClassLoadingLog().bufferedReader().forEachLine {
val data = it.split(':', limit = 2)
val sourcePath = data[1]
// main jar is scrambled - doesn't make sense to reorder it
if (sourcePath != "lib/idea.jar") {
sourceToNames.computeIfAbsent(sourcePath) { mutableListOf() }.add(data[0])
}
}
sourceToNames
}
internal fun reorderJar(relativePath: String, file: Path, traceContext: Context) {
val orderedNames = sourceToNames.get(relativePath) ?: return
tracer.spanBuilder("reorder jar")
.setParent(traceContext)
.setAttribute("relativePath", relativePath)
.setAttribute("file", file.toString())
.startSpan()
.use {
reorderJar(jarFile = file, orderedNames = orderedNames, resultJarFile = file)
}
}
fun generateClasspath(homeDir: Path, mainJarName: String, antTargetFile: Path?): List<String> {
val libDir = homeDir.resolve("lib")
val appFile = libDir.resolve("app.jar")
tracer.spanBuilder("generate app.jar")
.setAttribute("dir", homeDir.toString())
.setAttribute("mainJarName", mainJarName)
.startSpan()
.use {
transformFile(appFile) { target ->
writeNewZip(target) { zipCreator ->
val packageIndexBuilder = PackageIndexBuilder()
copyZipRaw(appFile, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
val mainJar = libDir.resolve(mainJarName)
if (Files.exists(mainJar)) {
// no such file in community (no closed sources)
copyZipRaw(mainJar, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
Files.delete(mainJar)
}
// packing to product.jar maybe disabled
val productJar = libDir.resolve("product.jar")
if (Files.exists(productJar)) {
copyZipRaw(productJar, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
Files.delete(productJar)
}
packageIndexBuilder.writePackageIndex(zipCreator)
}
}
}
reorderJar("lib/app.jar", appFile, Context.current())
tracer.spanBuilder("generate classpath")
.setAttribute("dir", homeDir.toString())
.startSpan()
.use { span ->
val osName = System.getProperty("os.name")
val classifier = when {
osName.startsWith("windows", ignoreCase = true) -> "windows"
osName.startsWith("mac", ignoreCase = true) -> "mac"
else -> "linux"
}
val sourceToNames = readClassLoadingLog(
classLoadingLog = PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!!,
rootDir = homeDir,
mainJarName = mainJarName
)
val files = computeAppClassPath(sourceToNames, libDir)
if (antTargetFile != null) {
files.add(antTargetFile)
}
val result = files.map { libDir.relativize(it).toString() }
span.setAttribute(AttributeKey.stringArrayKey("result"), result)
return result
}
}
private fun computeAppClassPath(sourceToNames: Map<Path, List<String>>, libDir: Path): LinkedHashSet<Path> {
// sorted to ensure stable performance results
val existing = TreeSet<Path>()
addJarsFromDir(libDir) { paths ->
paths.filterTo(existing) { !excludedLibJars.contains(it.fileName.toString()) }
}
val result = LinkedHashSet<Path>()
// add first - should be listed first
sourceToNames.keys.filterTo(result) { it.parent == libDir && existing.contains(it) }
result.addAll(existing)
return result
}
private inline fun addJarsFromDir(dir: Path, consumer: (Sequence<Path>) -> Unit) {
Files.newDirectoryStream(dir).use { stream ->
consumer(stream.asSequence().filter { it.toString().endsWith(".jar") })
}
}
internal fun readClassLoadingLog(classLoadingLog: InputStream, rootDir: Path, mainJarName: String): Map<Path, List<String>> {
val sourceToNames = LinkedHashMap<Path, MutableList<String>>()
classLoadingLog.bufferedReader().forEachLine {
val data = it.split(':', limit = 2)
var sourcePath = data[1]
if (sourcePath == "lib/idea.jar") {
sourcePath = "lib/$mainJarName"
}
sourceToNames.computeIfAbsent(rootDir.resolve(sourcePath)) { mutableListOf() }.add(data[0])
}
return sourceToNames
}
data class PackageIndexEntry(val path: Path, val classPackageIndex: LongSet, val resourcePackageIndex: LongSet)
private class EntryData(@JvmField val name: String, @JvmField val entry: ZipEntry)
fun reorderJar(jarFile: Path, orderedNames: List<String>, resultJarFile: Path): PackageIndexEntry {
val orderedNameToIndex = Object2IntOpenHashMap<String>(orderedNames.size)
orderedNameToIndex.defaultReturnValue(-1)
for ((index, orderedName) in orderedNames.withIndex()) {
orderedNameToIndex.put(orderedName, index)
}
val tempJarFile = resultJarFile.resolveSibling("${resultJarFile.fileName}_reorder")
val packageIndexBuilder = PackageIndexBuilder()
mapFileAndUse(jarFile) { sourceBuffer, fileSize ->
val entries = mutableListOf<EntryData>()
readZipEntries(sourceBuffer, fileSize) { name, entry ->
entries.add(EntryData(name, entry))
}
// ignore existing package index on reorder - a new one will be computed even if it is the same, do not optimize for simplicity
entries.sortWith(Comparator { o1, o2 ->
val o2p = o2.name
if ("META-INF/plugin.xml" == o2p) {
return@Comparator Int.MAX_VALUE
}
val o1p = o1.name
if ("META-INF/plugin.xml" == o1p) {
-Int.MAX_VALUE
}
else {
val i1 = orderedNameToIndex.getInt(o1p)
if (i1 == -1) {
if (orderedNameToIndex.containsKey(o2p)) 1 else 0
}
else {
val i2 = orderedNameToIndex.getInt(o2p)
if (i2 == -1) -1 else (i1 - i2)
}
}
})
writeNewZip(tempJarFile) { zipCreator ->
for (item in entries) {
packageIndexBuilder.addFile(item.name)
zipCreator.uncompressedData(item.name, item.entry.getByteBuffer())
}
packageIndexBuilder.writePackageIndex(zipCreator)
}
}
try {
Files.move(tempJarFile, resultJarFile, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: Exception) {
throw e
}
finally {
Files.deleteIfExists(tempJarFile)
}
return PackageIndexEntry(path = resultJarFile, packageIndexBuilder.classPackageHashSet, packageIndexBuilder.resourcePackageHashSet)
} | apache-2.0 | 94db8c034fb49186bce8b323d02c44fe | 35.281106 | 158 | 0.687246 | 4.193926 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSingleIntentionActionFactory.kt | 1 | 1943 | // 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.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
abstract class KotlinSingleIntentionActionFactory : KotlinIntentionActionsFactory() {
protected abstract fun createAction(diagnostic: Diagnostic): IntentionAction?
final override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> = listOfNotNull(createAction(diagnostic))
companion object {
inline fun <reified PSI : PsiElement> createFromQuickFixesPsiBasedFactory(
psiBasedFactory: QuickFixesPsiBasedFactory<PSI>
): KotlinSingleIntentionActionFactory = object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val factories = psiBasedFactory.createQuickFix(diagnostic.psiElement as PSI)
return when (factories.size) {
0 -> null
1 -> factories.single()
else -> error("To convert QuickFixesPsiBasedFactory to KotlinSingleIntentionActionFactory, it should always return one or zero quickfixes")
}
}
}
}
}
fun QuickFixFactory.asKotlinIntentionActionsFactory(): KotlinIntentionActionsFactory = when (this) {
is KotlinIntentionActionsFactory -> this
is QuickFixesPsiBasedFactory<*> -> object : KotlinIntentionActionsFactory() {
@Suppress("UNCHECKED_CAST")
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val psiElement = diagnostic.psiElement
return createQuickFix(psiElement)
}
}
else -> error("Unexpected QuickFixFactory ${this::class}")
} | apache-2.0 | 2a2e6b6335465cc555e486b7bfad1ed3 | 47.6 | 159 | 0.716418 | 6.05296 | false | false | false | false |
jwren/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastContext.kt | 5 | 8942 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.map2Array
import org.jetbrains.annotations.Contract
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.ClassSetsWrapper
import org.jetbrains.uast.util.emptyClassSet
import java.util.*
@Deprecated("use UastFacade or UastLanguagePlugin instead", ReplaceWith("UastFacade"))
class UastContext(val project: Project) : UastLanguagePlugin by UastFacade {
val languagePlugins: Collection<UastLanguagePlugin>
get() = UastFacade.languagePlugins
fun findPlugin(element: PsiElement): UastLanguagePlugin? = UastFacade.findPlugin(element)
fun getMethod(method: PsiMethod): UMethod = convertWithParent<UMethod>(method)!!
fun getVariable(variable: PsiVariable): UVariable = convertWithParent<UVariable>(variable)!!
fun getClass(clazz: PsiClass): UClass = convertWithParent<UClass>(clazz)!!
}
/**
* The main entry point to uast-conversions.
*
* In the most cases you could use [toUElement] or [toUElementOfExpectedTypes] extension methods instead of using the `UastFacade` directly
*/
object UastFacade : UastLanguagePlugin {
override val language: Language = object : Language("UastContextLanguage") {}
override val priority: Int
get() = 0
val languagePlugins: Collection<UastLanguagePlugin>
get() = UastLanguagePlugin.getInstances()
fun findPlugin(element: PsiElement): UastLanguagePlugin? = UastLanguagePlugin.byLanguage(element.language)
override fun isFileSupported(fileName: String): Boolean = languagePlugins.any { it.isFileSupported(fileName) }
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
return findPlugin(element)?.convertElement(element, parent, requiredType)
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
if (element is PsiWhiteSpace) {
return null
}
return findPlugin(element)?.convertElementWithParent(element, requiredType)
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
return findPlugin(element)?.getMethodCallExpression(element, containingClassFqName, methodName)
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
return findPlugin(element)?.getConstructorCallExpression(element, fqName)
}
override fun isExpressionValueUsed(element: UExpression): Boolean {
val language = element.getLanguage()
return UastLanguagePlugin.byLanguage(language)?.isExpressionValueUsed(element) ?: false
}
private tailrec fun UElement.getLanguage(): Language {
sourcePsi?.language?.let { return it }
val containingElement = this.uastParent ?: throw IllegalStateException("At least UFile should have a language")
return containingElement.getLanguage()
}
override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? =
findPlugin(element)?.convertElementWithParent(element, requiredTypes)
override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> =
findPlugin(element)?.convertToAlternatives(element, requiredTypes) ?: emptySequence()
private interface UastPluginListener {
fun onPluginsChanged()
}
private val exposedListeners = Collections.newSetFromMap(CollectionFactory.createConcurrentWeakIdentityMap<UastPluginListener, Boolean>())
init {
UastLanguagePlugin.extensionPointName.addChangeListener({ exposedListeners.forEach(UastPluginListener::onPluginsChanged) }, null);
}
override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> =
object : ClassSet<PsiElement>, UastPluginListener {
fun initInner() = ClassSetsWrapper(languagePlugins.map2Array { it.getPossiblePsiSourceTypes(*uastTypes) })
private var inner: ClassSetsWrapper<PsiElement> = initInner()
override fun onPluginsChanged() {
inner = initInner()
}
override fun isEmpty(): Boolean = inner.isEmpty()
override fun contains(element: Class<out PsiElement>): Boolean = inner.contains(element)
override fun toList(): List<Class<out PsiElement>> = inner.toList()
}.also { exposedListeners.add(it) }
}
/**
* Converts the element to UAST.
*/
fun PsiElement?.toUElement(): UElement? = this?.let { UastFacade.convertElementWithParent(this, null) }
/**
* Converts the element to an UAST element of the given type. Returns null if the PSI element type does not correspond
* to the given UAST element type.
*/
@Suppress("UNCHECKED_CAST")
@Contract("null, _ -> null")
fun <T : UElement> PsiElement?.toUElement(cls: Class<out T>): T? = this?.let { UastFacade.convertElementWithParent(this, cls) as T? }
@Suppress("UNCHECKED_CAST")
@SafeVarargs
fun <T : UElement> PsiElement?.toUElementOfExpectedTypes(vararg clss: Class<out T>): T? =
this?.let {
UastFacade.convertElementWithParent(this, if (clss.isNotEmpty()) clss else DEFAULT_TYPES_LIST) as T?
}
inline fun <reified T : UElement> PsiElement?.toUElementOfType(): T? = toUElement(T::class.java)
/**
* Finds an UAST element of a given type at the given [offset] in the specified file. Returns null if there is no UAST
* element of the given type at the given offset.
*/
fun <T : UElement> PsiFile.findUElementAt(offset: Int, cls: Class<out T>): T? {
val element = findElementAt(offset) ?: return null
val uElement = element.toUElement() ?: return null
@Suppress("UNCHECKED_CAST")
return uElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T?
}
/**
* Finds an UAST element of the given type among the parents of the given PSI element.
*/
@JvmOverloads
fun <T : UElement> PsiElement?.getUastParentOfType(cls: Class<out T>, strict: Boolean = false): T? = this?.run {
val firstUElement = getFirstUElement(this, strict) ?: return null
@Suppress("UNCHECKED_CAST")
return firstUElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T?
}
/**
* Finds an UAST element of any given type among the parents of the given PSI element.
*/
@JvmOverloads
fun PsiElement?.getUastParentOfTypes(classes: Array<Class<out UElement>>, strict: Boolean = false): UElement? = this?.run {
val firstUElement = getFirstUElement(this, strict) ?: return null
@Suppress("UNCHECKED_CAST")
return firstUElement.withContainingElements.firstOrNull { uElement ->
classes.any { cls -> cls.isInstance(uElement) }
}
}
inline fun <reified T : UElement> PsiElement?.getUastParentOfType(strict: Boolean = false): T? = getUastParentOfType(T::class.java, strict)
@JvmField
val DEFAULT_TYPES_LIST: Array<Class<out UElement>> = arrayOf(UElement::class.java)
@JvmField
val DEFAULT_EXPRESSION_TYPES_LIST: Array<Class<out UExpression>> = arrayOf(UExpression::class.java)
/**
* @return types of possible source PSI elements of [language], which instances in principle
* can be converted to at least one of the specified [uastTypes]
* (or to [UElement] if no type was specified)
*
* @see UastFacade.getPossiblePsiSourceTypes
*/
fun getPossiblePsiSourceTypes(language: Language, vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> =
UastLanguagePlugin.byLanguage(language)?.getPossiblePsiSourceTypes(*uastTypes) ?: emptyClassSet()
/**
* @return types of possible source PSI elements of [language], which instances in principle
* can be converted to the specified `U` type
*/
inline fun <reified U : UElement> getPossiblePsiSourceTypesFor(language: Language): ClassSet<PsiElement> =
UastLanguagePlugin.byLanguage(language)?.getPossiblePsiSourceTypes(U::class.java) ?: emptyClassSet()
private fun getFirstUElement(psiElement: PsiElement, strict: Boolean = false): UElement? {
val startingElement = if (strict) psiElement.parent else psiElement
val parentSequence = generateSequence(startingElement, PsiElement::getParent)
return parentSequence.mapNotNull { it.toUElement() }.firstOrNull()
}
| apache-2.0 | e98ca75b302b596e8000350f32ee4134 | 38.742222 | 140 | 0.756207 | 4.536783 | false | false | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ide/startup/CheckProjectActivity.kt | 1 | 2727 | // 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.ide.startup
import com.intellij.configurationStore.checkUnknownMacros
import com.intellij.ide.IdeCoreBundle
import com.intellij.internal.statistic.collectors.fus.project.ProjectFsStatsCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.milliseconds
private class CheckProjectActivity : ProjectPostStartupActivity {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment || ApplicationManager.getApplication().isUnitTestMode) {
throw ExtensionNotApplicableException.create()
}
}
override suspend fun execute(project: Project) {
checkUnknownMacros(project, true)
checkProjectRoots(project)
}
private suspend fun checkProjectRoots(project: Project) {
val roots = ProjectRootManager.getInstance(project).contentRoots
if (roots.isEmpty()) {
return
}
val watcher = (LocalFileSystem.getInstance() as? LocalFileSystemImpl)?.fileWatcher
if (watcher == null || !watcher.isOperational) {
ProjectFsStatsCollector.watchedRoots(project, -1)
return
}
val logger = logger<CheckProjectActivity>()
logger.debug("FW/roots waiting started")
while (watcher.isSettingRoots) {
delay(10.milliseconds)
}
logger.debug("FW/roots waiting finished")
val manualWatchRoots = watcher.manualWatchRoots
var pctNonWatched = 0
if (manualWatchRoots.isNotEmpty()) {
val unwatched = roots.filter { root -> root.isInLocalFileSystem && manualWatchRoots.any { VfsUtilCore.isAncestorOrSelf(it, root) } }
if (unwatched.isNotEmpty()) {
val message = IdeCoreBundle.message("watcher.non.watchable.project", ApplicationNamesInfo.getInstance().fullProductName)
watcher.notifyOnFailure(message, null)
logger.info("unwatched roots: ${unwatched.map { it.presentableUrl }}")
logger.info("manual watches: ${manualWatchRoots}")
pctNonWatched = (100.0 * unwatched.size / roots.size).toInt()
}
}
ProjectFsStatsCollector.watchedRoots(project, pctNonWatched)
}
}
| apache-2.0 | 83c66088b7f008d763e9823130547f77 | 40.953846 | 138 | 0.769344 | 4.669521 | false | false | false | false |
androidx/androidx | room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/testutil/PagingEntity.kt | 3 | 1428 | /*
* 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.room.androidx.room.integration.kotlintestapp.testutil
import androidx.recyclerview.widget.DiffUtil
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class PagingEntity(
@PrimaryKey
val id: Int,
val value: String = "item_$id"
) {
companion object {
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<PagingEntity>() {
override fun areItemsTheSame(
oldItem: PagingEntity,
newItem: PagingEntity
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: PagingEntity,
newItem: PagingEntity
): Boolean {
return oldItem == newItem
}
}
}
}
| apache-2.0 | 95193ee6ee566136d1663719fea4e7f3 | 30.043478 | 76 | 0.653361 | 4.744186 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/strictmode/FragmentStrictModeTest.kt | 3 | 20325 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app.strictmode
import android.os.Looper
import androidx.fragment.app.StrictFragment
import androidx.fragment.app.StrictViewFragment
import androidx.fragment.app.executePendingTransactions
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
public class FragmentStrictModeTest {
private val fragmentClass = StrictFragment::class.java
private lateinit var originalPolicy: FragmentStrictMode.Policy
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Before
public fun setup() {
originalPolicy = FragmentStrictMode.defaultPolicy
}
@After
public fun teardown() {
FragmentStrictMode.defaultPolicy = originalPolicy
}
@Test
public fun penaltyDeath() {
val policy = FragmentStrictMode.Policy.Builder()
.penaltyDeath()
.build()
FragmentStrictMode.defaultPolicy = policy
var violation: Violation? = null
try {
val fragment = StrictFragment()
FragmentStrictMode.onPolicyViolation(object : Violation(fragment) {})
} catch (thrown: Violation) {
violation = thrown
}
assertWithMessage("No exception thrown on policy violation").that(violation).isNotNull()
}
@Test
public fun policyHierarchy() {
var lastTriggeredPolicy = ""
fun policy(name: String) = FragmentStrictMode.Policy.Builder()
.penaltyListener { lastTriggeredPolicy = name }
.build()
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fragmentManager = withActivity { supportFragmentManager }
val parentFragment = StrictFragment()
fragmentManager.beginTransaction()
.add(parentFragment, "parentFragment")
.commit()
executePendingTransactions()
val childFragment = StrictFragment()
parentFragment.childFragmentManager.beginTransaction()
.add(childFragment, "childFragment")
.commit()
executePendingTransactions()
val violation = object : Violation(childFragment) {}
FragmentStrictMode.defaultPolicy = policy("Default policy")
FragmentStrictMode.onPolicyViolation(violation)
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(lastTriggeredPolicy).isEqualTo("Default policy")
fragmentManager.strictModePolicy = policy("Parent policy")
FragmentStrictMode.onPolicyViolation(violation)
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(lastTriggeredPolicy).isEqualTo("Parent policy")
parentFragment.childFragmentManager.strictModePolicy = policy("Child policy")
FragmentStrictMode.onPolicyViolation(violation)
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(lastTriggeredPolicy).isEqualTo("Child policy")
}
}
@Test
public fun listenerCalledOnCorrectThread() {
var thread: Thread? = null
val policy = FragmentStrictMode.Policy.Builder()
.penaltyListener { thread = Thread.currentThread() }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fragmentManager = withActivity { supportFragmentManager }
val fragment = StrictFragment()
fragmentManager.beginTransaction()
.add(fragment, null)
.commit()
executePendingTransactions()
FragmentStrictMode.onPolicyViolation(object : Violation(fragment) {})
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(thread).isEqualTo(Looper.getMainLooper().thread)
}
}
@Test
public fun detectFragmentReuse() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectFragmentReuse()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fragmentManager = withActivity { supportFragmentManager }
val fragment = StrictFragment()
fragmentManager.beginTransaction()
.add(fragment, null)
.commit()
executePendingTransactions()
fragmentManager.beginTransaction()
.remove(fragment)
.commit()
executePendingTransactions()
fragmentManager.beginTransaction()
.add(fragment, null)
.commit()
executePendingTransactions()
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(violation).isInstanceOf(FragmentReuseViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to reuse fragment $fragment with previous ID ${fragment.mPreviousWho}"
)
}
}
@Test
public fun detectFragmentReuseInFlightTransaction() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectFragmentReuse()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fragmentManager = withActivity { supportFragmentManager }
val fragment = StrictFragment()
fragmentManager.beginTransaction()
.add(fragment, null)
.commit()
executePendingTransactions()
fragmentManager.beginTransaction()
.remove(fragment)
.commit()
// Don't execute transaction here, keep it in-flight
fragmentManager.beginTransaction()
.add(fragment, null)
.commit()
executePendingTransactions()
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
assertThat(violation).isInstanceOf(FragmentReuseViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to reuse fragment $fragment with previous ID ${fragment.mPreviousWho}"
)
}
}
@Suppress("DEPRECATION")
@Test
public fun detectFragmentTagUsage() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectFragmentTagUsage()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
withActivity { setContentView(R.layout.activity_inflated_fragment) }
val fragment = withActivity {
supportFragmentManager.findFragmentById(R.id.inflated_fragment)!!
}
val container = withActivity { findViewById(R.id.inflated_layout) }
assertThat(violation).isInstanceOf(FragmentTagUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to use <fragment> tag to add fragment $fragment to container $container"
)
}
}
@Test
public fun detectWrongNestedHierarchyNoParent() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectWrongNestedHierarchy()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val outerFragment = StrictViewFragment(R.layout.scene1)
val innerFragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction()
.add(R.id.fragmentContainer, outerFragment)
.setReorderingAllowed(false)
.commit()
// Here we add childFragment to a layout within parentFragment, but we
// specifically don't use parentFragment.childFragmentManager
fm.beginTransaction()
.add(R.id.squareContainer, innerFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions()
assertThat(violation).isInstanceOf(WrongNestedHierarchyViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to nest fragment $innerFragment within the view " +
"of parent fragment $outerFragment via container with ID " +
"${R.id.squareContainer} without using parent's childFragmentManager"
)
}
}
@Test
public fun detectWrongNestedHierarchyWrongParent() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectWrongNestedHierarchy()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val grandParent = StrictViewFragment(R.layout.scene1)
val parentFragment = StrictViewFragment(R.layout.scene5)
val childFragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction()
.add(R.id.fragmentContainer, grandParent)
.setReorderingAllowed(false)
.commit()
executePendingTransactions()
grandParent.childFragmentManager.beginTransaction()
.add(R.id.squareContainer, parentFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions()
// Here we use the grandParent.childFragmentManager for the child
// fragment, though we should actually be using parentFragment.childFragmentManager
grandParent.childFragmentManager.beginTransaction()
.add(R.id.sharedElementContainer, childFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions(parentFragment.childFragmentManager)
assertThat(violation).isInstanceOf(WrongNestedHierarchyViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to nest fragment $childFragment within the view " +
"of parent fragment $parentFragment via container with ID " +
"${R.id.sharedElementContainer} without using parent's childFragmentManager"
)
}
}
@Suppress("DEPRECATION")
@Test
public fun detectRetainInstanceUsage() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectRetainInstanceUsage()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
val fragment = StrictFragment()
fragment.retainInstance = true
assertThat(violation).isInstanceOf(SetRetainInstanceUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to set retain instance for fragment $fragment"
)
violation = null
fragment.retainInstance
assertThat(violation).isInstanceOf(GetRetainInstanceUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to get retain instance for fragment $fragment"
)
}
@Suppress("DEPRECATION")
@Test
public fun detectSetUserVisibleHint() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectSetUserVisibleHint()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
val fragment = StrictFragment()
fragment.userVisibleHint = true
assertThat(violation).isInstanceOf(SetUserVisibleHintViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to set user visible hint to true for fragment $fragment"
)
}
@Suppress("DEPRECATION")
@Test
public fun detectTargetFragmentUsage() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectTargetFragmentUsage()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
val fragment = StrictFragment()
val targetFragment = StrictFragment()
val requestCode = 1
fragment.setTargetFragment(targetFragment, requestCode)
assertThat(violation).isInstanceOf(SetTargetFragmentUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to set target fragment $targetFragment " +
"with request code $requestCode for fragment $fragment"
)
violation = null
fragment.targetFragment
assertThat(violation).isInstanceOf(GetTargetFragmentUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to get target fragment from fragment $fragment"
)
violation = null
fragment.targetRequestCode
assertThat(violation).isInstanceOf(GetTargetFragmentRequestCodeUsageViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to get target request code from fragment $fragment"
)
}
@Test
public fun detectWrongFragmentContainer() {
var violation: Violation? = null
val policy = FragmentStrictMode.Policy.Builder()
.detectWrongFragmentContainer()
.penaltyListener { violation = it }
.build()
FragmentStrictMode.defaultPolicy = policy
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fragmentManager = withActivity { supportFragmentManager }
val fragment1 = StrictFragment()
fragmentManager.beginTransaction()
.add(R.id.content, fragment1)
.commit()
executePendingTransactions()
val container1 = withActivity { findViewById(R.id.content) }
assertThat(violation).isInstanceOf(WrongFragmentContainerViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to add fragment $fragment1 to container " +
"$container1 which is not a FragmentContainerView"
)
violation = null
val fragment2 = StrictFragment()
fragmentManager.beginTransaction()
.replace(R.id.content, fragment2)
.commit()
executePendingTransactions()
val container2 = withActivity { findViewById(R.id.content) }
assertThat(violation).isInstanceOf(WrongFragmentContainerViolation::class.java)
assertThat(violation).hasMessageThat().contains(
"Attempting to add fragment $fragment2 to container " +
"$container2 which is not a FragmentContainerView"
)
}
}
@Suppress("DEPRECATION")
@Test
public fun detectAllowedViolations() {
val violationClass1 = RetainInstanceUsageViolation::class.java
val violationClass2 = SetUserVisibleHintViolation::class.java
val violationClass3 = GetTargetFragmentUsageViolation::class.java
val violationClassList = listOf(violationClass1, violationClass2, violationClass3)
var violation: Violation? = null
var policyBuilder = FragmentStrictMode.Policy.Builder()
.detectRetainInstanceUsage()
.detectSetUserVisibleHint()
.penaltyListener { violation = it }
for (violationClass in violationClassList) {
policyBuilder = policyBuilder.allowViolation(fragmentClass, violationClass)
}
FragmentStrictMode.defaultPolicy = policyBuilder.build()
StrictFragment().retainInstance = true
assertThat(violation).isNotInstanceOf(violationClass1)
assertThat(violation).isNotInstanceOf(SetRetainInstanceUsageViolation::class.java)
violation = null
StrictFragment().retainInstance
assertThat(violation).isNotInstanceOf(violationClass1)
assertThat(violation).isNotInstanceOf(GetRetainInstanceUsageViolation::class.java)
violation = null
StrictFragment().userVisibleHint = true
assertThat(violation).isNotInstanceOf(violationClass2)
violation = null
StrictFragment().targetFragment
assertThat(violation).isNotInstanceOf(violationClass3)
}
@Suppress("DEPRECATION")
@Test
public fun detectAllowedViolationByClassString() {
val violationClass1 = RetainInstanceUsageViolation::class.java
val violationClass2 = SetUserVisibleHintViolation::class.java
val violationClass3 = GetTargetFragmentUsageViolation::class.java
val violationClassList = listOf(violationClass1, violationClass2, violationClass3)
var violation: Violation? = null
var policyBuilder = FragmentStrictMode.Policy.Builder()
.detectRetainInstanceUsage()
.detectSetUserVisibleHint()
.penaltyListener { violation = it }
for (violationClass in violationClassList) {
policyBuilder = policyBuilder.allowViolation(fragmentClass.name, violationClass)
}
FragmentStrictMode.defaultPolicy = policyBuilder.build()
StrictFragment().retainInstance = true
assertThat(violation).isNotInstanceOf(violationClass1)
assertThat(violation).isNotInstanceOf(SetRetainInstanceUsageViolation::class.java)
violation = null
StrictFragment().retainInstance
assertThat(violation).isNotInstanceOf(violationClass1)
assertThat(violation).isNotInstanceOf(GetRetainInstanceUsageViolation::class.java)
violation = null
StrictFragment().userVisibleHint = true
assertThat(violation).isNotInstanceOf(violationClass2)
violation = null
StrictFragment().targetFragment
assertThat(violation).isNotInstanceOf(violationClass3)
}
}
| apache-2.0 | 51d8df7b1f8cb8c65ef4de68dc469477 | 39.088757 | 100 | 0.658647 | 5.614641 | false | true | false | false |
androidx/androidx | activity/activity-ktx/src/main/java/androidx/activity/ActivityViewModelLazy.kt | 3 | 2911 | /*
* Copyright 2018 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.activity
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.Factory
import androidx.lifecycle.viewmodel.CreationExtras
/**
* Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer]
* is specified then [ViewModelProvider.Factory] returned by it will be used
* to create [ViewModel] first time.
*
* ```
* class MyComponentActivity : ComponentActivity() {
* val viewmodel: MyViewModel by viewModels()
* }
* ```
*
* This property can be accessed only after the Activity is attached to the Application,
* and access prior to that will result in IllegalArgumentException.
*/
@Deprecated(
"Superseded by viewModels that takes a CreationExtras",
level = DeprecationLevel.HIDDEN
)
@MainThread
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(
VM::class,
{ viewModelStore },
factoryPromise,
{ this.defaultViewModelCreationExtras }
)
}
/**
* Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer]
* is specified then [ViewModelProvider.Factory] returned by it will be used
* to create [ViewModel] first time.
*
* ```
* class MyComponentActivity : ComponentActivity() {
* val viewmodel: MyViewModel by viewModels()
* }
* ```
*
* This property can be accessed only after the Activity is attached to the Application,
* and access prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(
VM::class,
{ viewModelStore },
factoryPromise,
{ extrasProducer?.invoke() ?: this.defaultViewModelCreationExtras }
)
}
| apache-2.0 | 79ea4a473c0c76ac61fe3ca5fefbc3a4 | 31.707865 | 94 | 0.724493 | 4.6576 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/list/LazyListItemPlacementAnimator.kt | 3 | 18917 | /*
* 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.foundation.lazy.list
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.VisibilityThreshold
import androidx.compose.animation.core.spring
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.util.fastAny
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastForEachIndexed
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* Handles the item placement animations when it is set via [LazyItemScope.animateItemPlacement].
*
* This class is responsible for detecting when item position changed, figuring our start/end
* offsets and starting the animations.
*/
internal class LazyListItemPlacementAnimator(
private val scope: CoroutineScope,
private val isVertical: Boolean
) {
// state containing an animation and all relevant info for each item.
private val keyToItemInfoMap = mutableMapOf<Any, ItemInfo>()
// snapshot of the key to index map used for the last measuring.
private var keyToIndexMap: Map<Any, Int> = emptyMap()
// keeps the first and the last items positioned in the viewport and their visible part sizes.
private var viewportStartItemIndex = -1
private var viewportStartItemNotVisiblePartSize = 0
private var viewportEndItemIndex = -1
private var viewportEndItemNotVisiblePartSize = 0
// stored to not allocate it every pass.
private val positionedKeys = mutableSetOf<Any>()
/**
* Should be called after the measuring so we can detect position changes and start animations.
*
* Note that this method can compose new item and add it into the [positionedItems] list.
*/
fun onMeasured(
consumedScroll: Int,
layoutWidth: Int,
layoutHeight: Int,
reverseLayout: Boolean,
positionedItems: MutableList<LazyListPositionedItem>,
itemProvider: LazyMeasuredItemProvider,
) {
if (!positionedItems.fastAny { it.hasAnimations } && keyToItemInfoMap.isEmpty()) {
// no animations specified - no work needed
reset()
return
}
val mainAxisLayoutSize = if (isVertical) layoutHeight else layoutWidth
// the consumed scroll is considered as a delta we don't need to animate
val notAnimatableDelta = (if (reverseLayout) -consumedScroll else consumedScroll).toOffset()
val newFirstItem = positionedItems.first()
val newLastItem = positionedItems.last()
var totalItemsSize = 0
// update known indexes and calculate the average size
positionedItems.fastForEach { item ->
keyToItemInfoMap[item.key]?.index = item.index
totalItemsSize += item.sizeWithSpacings
}
val averageItemSize = totalItemsSize / positionedItems.size
positionedKeys.clear()
// iterate through the items which are visible (without animated offsets)
positionedItems.fastForEach { item ->
positionedKeys.add(item.key)
val itemInfo = keyToItemInfoMap[item.key]
if (itemInfo == null) {
// there is no state associated with this item yet
if (item.hasAnimations) {
val newItemInfo = ItemInfo(item.index)
val previousIndex = keyToIndexMap[item.key]
val firstPlaceableOffset = item.getOffset(0)
val firstPlaceableSize = item.getMainAxisSize(0)
val targetFirstPlaceableOffsetMainAxis = if (previousIndex == null) {
// it is a completely new item. no animation is needed
firstPlaceableOffset.mainAxis
} else {
val fallback = if (!reverseLayout) {
firstPlaceableOffset.mainAxis
} else {
firstPlaceableOffset.mainAxis - item.sizeWithSpacings +
firstPlaceableSize
}
calculateExpectedOffset(
index = previousIndex,
sizeWithSpacings = item.sizeWithSpacings,
averageItemsSize = averageItemSize,
scrolledBy = notAnimatableDelta,
fallback = fallback,
reverseLayout = reverseLayout,
mainAxisLayoutSize = mainAxisLayoutSize,
visibleItems = positionedItems
) + if (reverseLayout) {
item.size - firstPlaceableSize
} else {
0
}
}
val targetFirstPlaceableOffset = if (isVertical) {
firstPlaceableOffset.copy(y = targetFirstPlaceableOffsetMainAxis)
} else {
firstPlaceableOffset.copy(x = targetFirstPlaceableOffsetMainAxis)
}
// populate placeable info list
repeat(item.placeablesCount) { placeableIndex ->
val diffToFirstPlaceableOffset =
item.getOffset(placeableIndex) - firstPlaceableOffset
newItemInfo.placeables.add(
PlaceableInfo(
targetFirstPlaceableOffset + diffToFirstPlaceableOffset,
item.getMainAxisSize(placeableIndex)
)
)
}
keyToItemInfoMap[item.key] = newItemInfo
startAnimationsIfNeeded(item, newItemInfo)
}
} else {
if (item.hasAnimations) {
// apply new not animatable offset
itemInfo.notAnimatableDelta += notAnimatableDelta
startAnimationsIfNeeded(item, itemInfo)
} else {
// no animation, clean up if needed
keyToItemInfoMap.remove(item.key)
}
}
}
// previously we were animating items which are visible in the end state so we had to
// compare the current state with the state used for the previous measuring.
// now we will animate disappearing items so the current state is their starting state
// so we can update current viewport start/end items
if (!reverseLayout) {
viewportStartItemIndex = newFirstItem.index
viewportStartItemNotVisiblePartSize = newFirstItem.offset
viewportEndItemIndex = newLastItem.index
viewportEndItemNotVisiblePartSize =
newLastItem.offset + newLastItem.sizeWithSpacings - mainAxisLayoutSize
} else {
viewportStartItemIndex = newLastItem.index
viewportStartItemNotVisiblePartSize =
mainAxisLayoutSize - newLastItem.offset - newLastItem.size
viewportEndItemIndex = newFirstItem.index
viewportEndItemNotVisiblePartSize =
-newFirstItem.offset + (newFirstItem.sizeWithSpacings - newFirstItem.size)
}
val iterator = keyToItemInfoMap.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (!positionedKeys.contains(entry.key)) {
// found an item which was in our map previously but is not a part of the
// positionedItems now
val itemInfo = entry.value
// apply new not animatable delta for this item
itemInfo.notAnimatableDelta += notAnimatableDelta
val index = itemProvider.keyToIndexMap[entry.key]
// whether at least one placeable is within the viewport bounds.
// this usually means that we will start animation for it right now
val withinBounds = itemInfo.placeables.fastAny {
val currentTarget = it.targetOffset + itemInfo.notAnimatableDelta
currentTarget.mainAxis + it.size > 0 &&
currentTarget.mainAxis < mainAxisLayoutSize
}
// whether the animation associated with the item has been finished
val isFinished = !itemInfo.placeables.fastAny { it.inProgress }
if ((!withinBounds && isFinished) ||
index == null ||
itemInfo.placeables.isEmpty()
) {
iterator.remove()
} else {
val measuredItem = itemProvider.getAndMeasure(DataIndex(index))
// calculate the target offset for the animation.
val absoluteTargetOffset = calculateExpectedOffset(
index = index,
sizeWithSpacings = measuredItem.sizeWithSpacings,
averageItemsSize = averageItemSize,
scrolledBy = notAnimatableDelta,
fallback = mainAxisLayoutSize,
reverseLayout = reverseLayout,
mainAxisLayoutSize = mainAxisLayoutSize,
visibleItems = positionedItems
)
val targetOffset = if (reverseLayout) {
mainAxisLayoutSize - absoluteTargetOffset - measuredItem.size
} else {
absoluteTargetOffset
}
val item = measuredItem.position(targetOffset, layoutWidth, layoutHeight)
positionedItems.add(item)
startAnimationsIfNeeded(item, itemInfo)
}
}
}
keyToIndexMap = itemProvider.keyToIndexMap
}
/**
* Returns the current animated item placement offset. By calling it only during the layout
* phase we can skip doing remeasure on every animation frame.
*/
fun getAnimatedOffset(
key: Any,
placeableIndex: Int,
minOffset: Int,
maxOffset: Int,
rawOffset: IntOffset
): IntOffset {
val itemInfo = keyToItemInfoMap[key] ?: return rawOffset
val item = itemInfo.placeables[placeableIndex]
val currentValue = item.animatedOffset.value + itemInfo.notAnimatableDelta
val currentTarget = item.targetOffset + itemInfo.notAnimatableDelta
// cancel the animation if it is fully out of the bounds.
if (item.inProgress &&
((currentTarget.mainAxis < minOffset && currentValue.mainAxis < minOffset) ||
(currentTarget.mainAxis > maxOffset && currentValue.mainAxis > maxOffset))
) {
scope.launch {
item.animatedOffset.snapTo(item.targetOffset)
item.inProgress = false
}
}
return currentValue
}
/**
* Should be called when the animations are not needed for the next positions change,
* for example when we snap to a new position.
*/
fun reset() {
keyToItemInfoMap.clear()
keyToIndexMap = emptyMap()
viewportStartItemIndex = -1
viewportStartItemNotVisiblePartSize = 0
viewportEndItemIndex = -1
viewportEndItemNotVisiblePartSize = 0
}
/**
* Estimates the outside of the viewport offset for the item. Used to understand from
* where to start animation for the item which wasn't visible previously or where it should
* end for the item which is not going to be visible in the end.
*/
private fun calculateExpectedOffset(
index: Int,
sizeWithSpacings: Int,
averageItemsSize: Int,
scrolledBy: IntOffset,
reverseLayout: Boolean,
mainAxisLayoutSize: Int,
fallback: Int,
visibleItems: List<LazyListPositionedItem>
): Int {
val afterViewportEnd =
if (!reverseLayout) viewportEndItemIndex < index else viewportEndItemIndex > index
val beforeViewportStart =
if (!reverseLayout) viewportStartItemIndex > index else viewportStartItemIndex < index
return when {
afterViewportEnd -> {
var itemsSizes = 0
// add sizes of the items between the last visible one and this one.
val range = if (!reverseLayout) {
viewportEndItemIndex + 1 until index
} else {
index + 1 until viewportEndItemIndex
}
for (i in range) {
itemsSizes += visibleItems.getItemSize(
itemIndex = i,
fallback = averageItemsSize
)
}
mainAxisLayoutSize + viewportEndItemNotVisiblePartSize + itemsSizes +
scrolledBy.mainAxis
}
beforeViewportStart -> {
// add the size of this item as we need the start offset of this item.
var itemsSizes = sizeWithSpacings
// add sizes of the items between the first visible one and this one.
val range = if (!reverseLayout) {
index + 1 until viewportStartItemIndex
} else {
viewportStartItemIndex + 1 until index
}
for (i in range) {
itemsSizes += visibleItems.getItemSize(
itemIndex = i,
fallback = averageItemsSize
)
}
viewportStartItemNotVisiblePartSize - itemsSizes + scrolledBy.mainAxis
}
else -> {
fallback
}
}
}
private fun List<LazyListPositionedItem>.getItemSize(itemIndex: Int, fallback: Int): Int {
if (isEmpty() || itemIndex < first().index || itemIndex > last().index) return fallback
if ((itemIndex - first().index) < (last().index - itemIndex)) {
for (index in indices) {
val item = get(index)
if (item.index == itemIndex) return item.sizeWithSpacings
if (item.index > itemIndex) break
}
} else {
for (index in lastIndex downTo 0) {
val item = get(index)
if (item.index == itemIndex) return item.sizeWithSpacings
if (item.index < itemIndex) break
}
}
return fallback
}
private fun startAnimationsIfNeeded(item: LazyListPositionedItem, itemInfo: ItemInfo) {
// first we make sure our item info is up to date (has the item placeables count)
while (itemInfo.placeables.size > item.placeablesCount) {
itemInfo.placeables.removeLast()
}
while (itemInfo.placeables.size < item.placeablesCount) {
val newPlaceableInfoIndex = itemInfo.placeables.size
val rawOffset = item.getOffset(newPlaceableInfoIndex)
itemInfo.placeables.add(
PlaceableInfo(
rawOffset - itemInfo.notAnimatableDelta,
item.getMainAxisSize(newPlaceableInfoIndex)
)
)
}
itemInfo.placeables.fastForEachIndexed { index, placeableInfo ->
val currentTarget = placeableInfo.targetOffset + itemInfo.notAnimatableDelta
val currentOffset = item.getOffset(index)
placeableInfo.size = item.getMainAxisSize(index)
val animationSpec = item.getAnimationSpec(index)
if (currentTarget != currentOffset) {
placeableInfo.targetOffset = currentOffset - itemInfo.notAnimatableDelta
if (animationSpec != null) {
placeableInfo.inProgress = true
scope.launch {
val finalSpec = if (placeableInfo.animatedOffset.isRunning) {
// when interrupted, use the default spring, unless the spec is a spring.
if (animationSpec is SpringSpec<IntOffset>) animationSpec else
InterruptionSpec
} else {
animationSpec
}
try {
placeableInfo.animatedOffset.animateTo(
placeableInfo.targetOffset,
finalSpec
)
placeableInfo.inProgress = false
} catch (_: CancellationException) {
// we don't reset inProgress in case of cancellation as it means
// there is a new animation started which would reset it later
}
}
}
}
}
}
private fun Int.toOffset() =
IntOffset(if (isVertical) 0 else this, if (!isVertical) 0 else this)
private val IntOffset.mainAxis get() = if (isVertical) y else x
}
private class ItemInfo(var index: Int) {
var notAnimatableDelta: IntOffset = IntOffset.Zero
val placeables = mutableListOf<PlaceableInfo>()
}
private class PlaceableInfo(
initialOffset: IntOffset,
var size: Int
) {
val animatedOffset = Animatable(initialOffset, IntOffset.VectorConverter)
var targetOffset: IntOffset = initialOffset
var inProgress by mutableStateOf(false)
}
/**
* We switch to this spec when a duration based animation is being interrupted.
*/
private val InterruptionSpec = spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
)
| apache-2.0 | 87f87fbee166bf7c7f49188b1f39f989 | 41.895692 | 101 | 0.585135 | 5.715106 | false | false | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/codeInsight/hints/settings/ParameterNameHintsSettings.kt | 2 | 6846 | // 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.codeInsight.hints.settings
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import org.jdom.Element
private object XmlTagHelper {
const val BLACKLISTS = "blacklists"
const val LANGUAGE_LIST = "blacklist"
const val LANGUAGE = "language"
const val ADDED = "added"
const val REMOVED = "removed"
const val PATTERN = "pattern"
const val DISABLED_LANGUAGES = "disabledLanguages"
const val DISABLED_LANGUAGE_ITEM = "language"
const val DISABLED_LANGUAGE_ID = "id"
}
class Diff(val added: Set<String>, val removed: Set<String>) {
fun applyOn(base: Set<String>): Set<String> {
val baseSet = base.toMutableSet()
added.forEach { baseSet.add(it) }
removed.forEach { baseSet.remove(it) }
return baseSet
}
companion object Builder {
fun build(base: Set<String>, updated: Set<String>): Diff {
val removed = base.toMutableSet()
removed.removeAll(updated)
val added = updated.toMutableSet()
added.removeAll(base)
return Diff(added, removed)
}
}
}
@State(name = "ParameterNameHintsSettings", storages = [(Storage("parameter.hints.xml"))], category = SettingsCategory.CODE)
class ParameterNameHintsSettings : PersistentStateComponent<Element> {
private val removedPatterns = hashMapOf<String, Set<String>>()
private val addedPatterns = hashMapOf<String, Set<String>>()
private val options = hashMapOf<String, Boolean>()
private val disabledLanguages = hashSetOf<String>()
fun addIgnorePattern(language: Language, pattern: String) {
val patternsBefore = getAddedPatterns(language)
setAddedPatterns(language, patternsBefore + pattern)
}
fun getExcludeListDiff(language: Language): Diff {
val added = getAddedPatterns(language)
val removed = getRemovedPatterns(language)
return Diff(added, removed)
}
fun setExcludeListDiff(language: Language, diff: Diff) {
setAddedPatterns(language, diff.added)
setRemovedPatterns(language, diff.removed)
}
override fun getState(): Element {
val root = Element("settings")
if (removedPatterns.isNotEmpty() || addedPatterns.isNotEmpty()) {
val blacklists = Element(XmlTagHelper.BLACKLISTS)
root.addContent(blacklists)
val allLanguages = removedPatterns.keys + addedPatterns.keys
allLanguages.forEach {
val removed = removedPatterns[it] ?: emptySet()
val added = addedPatterns[it] ?: emptySet()
val languageBlacklist = Element(XmlTagHelper.LANGUAGE_LIST).apply {
setAttribute(XmlTagHelper.LANGUAGE, it)
val removedElements = removed.map { it.toPatternElement(XmlTagHelper.REMOVED) }
val addedElements = added.map { it.toPatternElement(XmlTagHelper.ADDED) }
addContent(addedElements + removedElements)
}
blacklists.addContent(languageBlacklist)
}
}
options.forEach { (id, value) ->
val element = Element("option")
element.setAttribute("id", id)
element.setAttribute("value", value.toString())
root.addContent(element)
}
if (disabledLanguages.isNotEmpty()) {
val disabledLanguagesElement = Element(XmlTagHelper.DISABLED_LANGUAGES)
disabledLanguagesElement.addContent(disabledLanguages.map {
val element = Element(XmlTagHelper.DISABLED_LANGUAGE_ITEM)
element.setAttribute(XmlTagHelper.DISABLED_LANGUAGE_ID, it)
element
})
root.addContent(disabledLanguagesElement)
}
return root
}
fun setIsEnabledForLanguage(enabled: Boolean, language: Language) {
if (!enabled) {
disabledLanguages.add(language.id)
} else {
disabledLanguages.remove(language.id)
}
}
fun isEnabledForLanguage(language: Language): Boolean {
return language.id !in disabledLanguages
}
override fun loadState(state: Element) {
addedPatterns.clear()
removedPatterns.clear()
options.clear()
disabledLanguages.clear()
val allBlacklistElements = state.getChild(XmlTagHelper.BLACKLISTS)
?.getChildren(XmlTagHelper.LANGUAGE_LIST) ?: emptyList()
allBlacklistElements.forEach { blacklistElement ->
val language = blacklistElement.attributeValue(XmlTagHelper.LANGUAGE) ?: return@forEach
val added = blacklistElement.extractPatterns(XmlTagHelper.ADDED)
addedPatterns[language] = addedPatterns[language]?.plus(added) ?: added
val removed = blacklistElement.extractPatterns(XmlTagHelper.REMOVED)
removedPatterns[language] = removedPatterns[language]?.plus(removed) ?: removed
}
state.getChildren("option").forEach {
val id = it.getAttributeValue("id")
options[id] = it.getAttributeBooleanValue("value")
}
state.getChild(XmlTagHelper.DISABLED_LANGUAGES)?.apply {
getChildren(XmlTagHelper.DISABLED_LANGUAGE_ITEM).forEach {
val languageId = it.attributeValue(XmlTagHelper.DISABLED_LANGUAGE_ID) ?: return@forEach
disabledLanguages.add(languageId)
}
}
}
companion object {
@JvmStatic
fun getInstance(): ParameterNameHintsSettings = ApplicationManager.getApplication().getService(ParameterNameHintsSettings::class.java)
}
fun getOption(optionId: String): Boolean? {
return options[optionId]
}
fun setOption(optionId: String, value: Boolean?) {
if (value == null) {
options.remove(optionId)
}
else {
options[optionId] = value
}
}
private fun getAddedPatterns(language: Language): Set<String> {
val key = language.displayName
return addedPatterns[key] ?: emptySet()
}
private fun getRemovedPatterns(language: Language): Set<String> {
val key = language.displayName
return removedPatterns[key] ?: emptySet()
}
private fun setRemovedPatterns(language: Language, removed: Set<String>) {
val key = language.displayName
removedPatterns[key] = removed
}
private fun setAddedPatterns(language: Language, added: Set<String>) {
val key = language.displayName
addedPatterns[key] = added
}
}
private fun Element.extractPatterns(tag: String): Set<String> {
return getChildren(tag).mapNotNull { it.attributeValue(XmlTagHelper.PATTERN) }.toSet()
}
private fun Element.attributeValue(attr: String): String? = this.getAttribute(attr)?.value
private fun String.toPatternElement(status: String): Element {
val element = Element(status)
element.setAttribute(XmlTagHelper.PATTERN, this)
return element
} | apache-2.0 | 82c8fafc8a2f215260101c78e0e95f82 | 31.760766 | 158 | 0.717207 | 4.428202 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/override-implement-k1/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMembersHandler.kt | 2 | 5112 | // 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.core.overrideImplement
import com.intellij.openapi.project.Project
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
private val METHODS_OF_ANY = listOf("equals", "hashCode", "toString").map { FqName("kotlin.Any.$it") }.toSet()
class OverrideMembersHandler(private val preferConstructorParameters: Boolean = false) : GenerateMembersHandler(false) {
override fun collectMembersToGenerate(descriptor: ClassDescriptor, project: Project): Collection<OverrideMemberChooserObject> {
val result = ArrayList<OverrideMemberChooserObject>()
for (member in descriptor.unsubstitutedMemberScope.getContributedDescriptors()) {
if (member is CallableMemberDescriptor && (member.kind != CallableMemberDescriptor.Kind.DECLARATION)) {
val overridden = member.overriddenDescriptors
if (overridden.any { it.modality == Modality.FINAL || DescriptorVisibilities.isPrivate(it.visibility.normalize()) }) continue
if (DescriptorUtils.isInterface(descriptor) && overridden.any { descriptor.builtIns.isMemberOfAny(it) }) continue
if ((descriptor.isValue || descriptor.isInline) &&
overridden.any { descriptor.builtIns.isMemberOfAny(it) && it.name.asString() in listOf("equals", "hashCode") }
) continue
class Data(
val realSuper: CallableMemberDescriptor,
val immediateSupers: MutableList<CallableMemberDescriptor> = SmartList()
)
val byOriginalRealSupers = LinkedHashMap<CallableMemberDescriptor, Data>()
for (immediateSuper in overridden) {
for (realSuper in toRealSupers(immediateSuper)) {
byOriginalRealSupers.getOrPut(realSuper.original) { Data(realSuper) }.immediateSupers.add(immediateSuper)
}
}
var realSupers = byOriginalRealSupers.values.map(Data::realSuper)
if (realSupers.size > 1) {
realSupers = realSupers.filter { it.fqNameSafe !in METHODS_OF_ANY }
}
val nonAbstractRealSupers = realSupers.filter { it.modality != Modality.ABSTRACT }
val realSupersToUse = if (nonAbstractRealSupers.isNotEmpty()) {
nonAbstractRealSupers
} else {
listOf(realSupers.firstOrNull() ?: continue)
}
for (realSuper in realSupersToUse) {
val immediateSupers = byOriginalRealSupers[realSuper.original]!!.immediateSupers
assert(immediateSupers.isNotEmpty())
val immediateSuperToUse = if (immediateSupers.size == 1) {
immediateSupers.single()
} else {
immediateSupers.singleOrNull { (it.containingDeclaration as? ClassDescriptor)?.kind == ClassKind.CLASS }
?: immediateSupers.first()
}
val bodyType = when {
descriptor.kind == ClassKind.INTERFACE && realSuper.builtIns.isMemberOfAny(realSuper) ->
BodyType.NoBody
immediateSuperToUse.modality == Modality.ABSTRACT ->
BodyType.FromTemplate
realSupersToUse.size == 1 ->
BodyType.Super
else ->
BodyType.QualifiedSuper
}
result.add(
OverrideMemberChooserObject.create(
project,
realSuper,
immediateSuperToUse,
bodyType,
preferConstructorParameters
)
)
}
}
}
return result
}
private fun toRealSupers(immediateSuper: CallableMemberDescriptor): Collection<CallableMemberDescriptor> {
if (immediateSuper.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return listOf(immediateSuper)
}
val overridden = immediateSuper.overriddenDescriptors
assert(overridden.isNotEmpty())
return overridden.flatMap { toRealSupers(it) }.distinctBy { it.original }
}
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint")
} | apache-2.0 | ed2f750d26847ebfbd8f93c3d7e48040 | 48.640777 | 141 | 0.606416 | 5.916667 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/InlineFunctionHyperLinkInfo.kt | 1 | 3531 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.execution.filters.FileHyperlinkInfo
import com.intellij.execution.filters.HyperlinkInfoBase
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.awt.RelativePoint
import java.awt.Component
import javax.swing.JList
import javax.swing.ListCellRenderer
class InlineFunctionHyperLinkInfo(
private val project: Project,
private val inlineInfo: List<InlineInfo>
) : HyperlinkInfoBase(), FileHyperlinkInfo {
override fun navigate(project: Project, hyperlinkLocationPoint: RelativePoint?) {
if (inlineInfo.isEmpty()) return
if (inlineInfo.size == 1) {
OpenFileHyperlinkInfo(project, inlineInfo.first().file, inlineInfo.first().line).navigate(project)
} else {
val popup = JBPopupFactory.getInstance().createPopupChooserBuilder(inlineInfo)
.setTitle(KotlinDebuggerCoreBundle.message("filters.title.navigate.to"))
.setRenderer(InlineInfoCellRenderer())
.setItemChosenCallback { fileInfo ->
fileInfo?.let { OpenFileHyperlinkInfo(project, fileInfo.file, fileInfo.line).navigate(project) }
}
.createPopup()
if (hyperlinkLocationPoint != null) {
popup.show(hyperlinkLocationPoint)
} else {
popup.showInFocusCenter()
}
}
}
override fun getDescriptor(): OpenFileDescriptor? {
val file = inlineInfo.firstOrNull()
return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) }
}
val callSiteDescriptor: OpenFileDescriptor?
get() {
val file = inlineInfo.firstOrNull { it is InlineInfo.CallSiteInfo }
return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) }
}
sealed class InlineInfo(val prefix: String, val file: VirtualFile, val line: Int) {
class CallSiteInfo(file: VirtualFile, line: Int) :
InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.call.site"), file, line)
class InlineFunctionBodyInfo(file: VirtualFile, line: Int) :
InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.body"), file, line)
}
private class InlineInfoCellRenderer : SimpleColoredComponent(), ListCellRenderer<InlineInfo> {
init {
isOpaque = true
}
override fun getListCellRendererComponent(
list: JList<out InlineInfo>?,
value: InlineInfo?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
clear()
if (value != null) {
append(value.prefix)
}
if (isSelected) {
background = list?.selectionBackground
foreground = list?.selectionForeground
} else {
background = list?.background
foreground = list?.foreground
}
return this
}
}
}
| apache-2.0 | 3430cb16f4dedde6547f21d68de8ca3f | 36.967742 | 158 | 0.654206 | 4.980254 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/local/feed/service/FeedUpdateInfo.kt | 1 | 987 | package org.schabi.newpipe.local.feed.service
import org.schabi.newpipe.database.subscription.NotificationMode
import org.schabi.newpipe.database.subscription.SubscriptionEntity
import org.schabi.newpipe.extractor.ListInfo
import org.schabi.newpipe.extractor.stream.StreamInfoItem
data class FeedUpdateInfo(
val uid: Long,
@NotificationMode
val notificationMode: Int,
val name: String,
val avatarUrl: String,
val listInfo: ListInfo<StreamInfoItem>,
) {
constructor(
subscription: SubscriptionEntity,
listInfo: ListInfo<StreamInfoItem>,
) : this(
uid = subscription.uid,
notificationMode = subscription.notificationMode,
name = subscription.name,
avatarUrl = subscription.avatarUrl,
listInfo = listInfo,
)
/**
* Integer id, can be used as notification id, etc.
*/
val pseudoId: Int
get() = listInfo.url.hashCode()
lateinit var newStreams: List<StreamInfoItem>
}
| gpl-3.0 | 19b5be4880f11424c3ff2bcb190a04c5 | 28.029412 | 66 | 0.70618 | 4.348018 | false | false | false | false |
chemickypes/Glitchy | glitchappcore/src/main/java/me/bemind/glitchappcore/ImageStorage.kt | 1 | 3028 | package me.bemind.glitchappcore
import android.content.Context
import android.graphics.Bitmap
import android.util.LruCache
import me.bemind.glitch.Effect
import me.bemind.glitch.GlitcherUtil
import java.io.*
/**
* Created by angelomoroni on 13/04/17.
*
* This file contains ImageStorage class, a cache system of bitmap
*/
object ImageStorage {
private val dimCache = 8 * 1024 * 1024
private val MAX_SIZE_STACK: Int = 12
val stack : LinkedStack<ImageDescriptor> = LinkedStack()
private var lruCache = LruCache<String,Bitmap>(dimCache)
var context : Context? = null
private val stackLenght: Int
get() = stack.size()
fun addBitmap(bitmap: Bitmap, effect: Effect, base:Boolean = false) {
var index : Int = 0
if(!base) {
val lastImage = stack.peek()
index = (((lastImage?.index ?: 0) + 1) % (MAX_SIZE_STACK-1))+1
if (stackLenght == 12) {
val imD = stack.removeOld()
if (imD != null) lruCache.remove(imD.imageName)
}
}
val imageName = "image_$index.jpg"
stack.push(ImageDescriptor(index,imageName,effect,base))
lruCache.put(imageName,bitmap)
createTemporaryFile(imageName,bitmap)
}
fun getLastBitmap(): Bitmap?{
return getBitmap(stack.peek()?.imageName?:"")
}
fun getImageToPutEffect(): Bitmap?{
val lastImage = stack.peek()
if(lastImage?.saved?:false){
return getBitmap(lastImage?.imageName?:"")
}else{
removeLast()
return getBitmap(stack.peek()?.imageName?:"")
}
}
/**
* save effect to last image
*/
fun saveEffect() {
stack.peek()?.saved = true
}
fun back() : Bitmap? {
removeLast()
return getBitmap(stack.peek()?.imageName?:"")
}
fun firstBitmap() :Bitmap? = getBitmap(stack.first()?.imageName?:"")
fun size() = stackLenght
fun canBack() = !(stack.isEmpty()|| stackLenght == 1)
fun clear() {
stack.clear()
lruCache = LruCache<String,Bitmap>(dimCache)
Utils.deleteCache(context?.cacheDir?: File("void"))
}
fun removeLast() {
val ls = stack.pop()
lruCache.remove(ls?.imageName)
}
fun removeLastNonSaved() {
val last = stack.peek()
if(!(last?.saved?:true)){
removeLast()
}
}
private fun getBitmap(imageName:String) : Bitmap?{
var b = lruCache.get(imageName)
if(b == null){
val f = File(context?.cacheDir,imageName)
b = Utils.getBitmapFromFile(f)
lruCache.put(imageName,b)
}
return b
}
private fun createTemporaryFile(fileName:String,bitmap: Bitmap){
val s = fileName.split(".")
val f = createTempFile(s[0],s[1], context?.cacheDir)
val b = BufferedOutputStream(f.outputStream())
b.write(GlitcherUtil.byteArrayFromBitmap(bitmap))
b.close()
}
} | apache-2.0 | 42219f382e9dc418ba1c19ea9d7dd19d | 23.427419 | 74 | 0.586856 | 4.048128 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/longrun/PendingTxMonitor.kt | 1 | 7991 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.longrun
import com.googlecode.jsonrpc4j.JsonRpcHttpClient
import com.googlecode.jsonrpc4j.ProxyUtil
import com.typesafe.config.ConfigFactory
import org.apache.commons.lang3.tuple.Pair
import org.apache.commons.lang3.tuple.Triple
import org.ethereum.config.SystemProperties
import org.ethereum.core.Block
import org.ethereum.core.TransactionReceipt
import org.ethereum.facade.EthereumFactory
import org.ethereum.jsonrpc.JsonRpc
import org.ethereum.jsonrpc.TransactionResultDTO
import org.ethereum.listener.EthereumListener
import org.ethereum.listener.EthereumListenerAdapter
import org.ethereum.util.ByteArrayMap
import org.junit.Ignore
import org.junit.Test
import org.slf4j.LoggerFactory
import org.spongycastle.util.encoders.Hex
import org.springframework.context.annotation.Bean
import java.net.URL
import java.util.*
/**
* Matches pending transactions from EthereumJ and any other JSON-RPC client
* Created by Anton Nashatyrev on 15.02.2017.
*/
@Ignore
class PendingTxMonitor : BasicNode("sampleNode") {
private val localTxs = ByteArrayMap<Triple<Long, TransactionReceipt, EthereumListener.PendingTransactionState>>()
private var remoteTxs: ByteArrayMap<Pair<Long, TransactionResultDTO>>? = null
override fun run() {
try {
setupRemoteRpc()
} catch (e: Exception) {
throw RuntimeException(e)
}
super.run()
}
@Throws(Exception::class)
private fun setupRemoteRpc() {
println("Creating RPC interface...")
val httpClient = JsonRpcHttpClient(URL("http://localhost:8545"))
val jsonRpc = ProxyUtil.createClientProxy(javaClass.classLoader, JsonRpc::class.java, httpClient)
println("Pinging remote RPC...")
val protocolVersion = jsonRpc.eth_protocolVersion()
println("Remote OK. Version: " + protocolVersion)
val pTxFilterId = jsonRpc.eth_newPendingTransactionFilter()
Thread(Runnable {
try {
while (java.lang.Boolean.TRUE) {
val changes = jsonRpc.eth_getFilterChanges(pTxFilterId)
if (changes.isNotEmpty()) {
changes
.map { jsonRpc.eth_getTransactionByHash(it as String) }
.forEach { newRemotePendingTx(it) }
}
Thread.sleep(100)
}
} catch (e: Exception) {
e.printStackTrace()
}
}).start()
}
override fun onSyncDoneImpl(state: EthereumListener.SyncState) {
super.onSyncDoneImpl(state)
if (remoteTxs == null) {
remoteTxs = ByteArrayMap<Pair<Long, TransactionResultDTO>>()
println("Sync Done!!!")
ethereum!!.addListener(object : EthereumListenerAdapter() {
override fun onPendingTransactionUpdate(txReceipt: TransactionReceipt, state: EthereumListener.PendingTransactionState, block: Block) {
[email protected](txReceipt, state, block)
}
})
}
}
private fun checkUnmatched() {
for (txHash in HashSet(localTxs.keys)) {
val tx = localTxs[txHash]
if (System.currentTimeMillis() - tx?.left as Long > 60000) {
localTxs.remove(txHash)
System.err.println("Local tx doesn't match: " + tx.middle?.transaction)
}
}
for (txHash in HashSet(remoteTxs!!.keys)) {
val tx = remoteTxs!![txHash]
if ((System.currentTimeMillis() - tx?.left as Long) > 60000) {
remoteTxs!!.remove(txHash)
System.err.println("Remote tx doesn't match: " + tx.right)
}
}
}
private fun onPendingTransactionUpdate(txReceipt: TransactionReceipt, state: EthereumListener.PendingTransactionState, block: Block) {
val txHash = txReceipt.transaction.hash
val removed = remoteTxs!!.remove(txHash)
if (state == EthereumListener.PendingTransactionState.DROPPED) {
if (localTxs.remove(txHash) != null) {
println("Dropped due to timeout (matchned: " + (removed != null) + "): " + Hex.toHexString(txHash))
} else {
if (remoteTxs!!.containsKey(txHash)) {
System.err.println("Dropped but matching: " + Hex.toHexString(txHash) + ": \n" + txReceipt)
}
}
} else if (state == EthereumListener.PendingTransactionState.NEW_PENDING) {
println("Local: " + Hex.toHexString(txHash))
if (removed == null) {
localTxs.put(txHash, Triple.of<Long, TransactionReceipt, EthereumListener.PendingTransactionState>(System.currentTimeMillis(), txReceipt, state))
} else {
println("Tx matched: " + Hex.toHexString(txHash))
}
}
checkUnmatched()
}
private fun newRemotePendingTx(tx: TransactionResultDTO) {
val txHash = Hex.decode(tx.hash.substring(2))
if (remoteTxs == null) return
println("Remote: " + Hex.toHexString(txHash))
val removed = localTxs.remove(txHash)
if (removed == null) {
remoteTxs!!.put(txHash, Pair.of(System.currentTimeMillis(), tx))
} else {
println("Tx matched: " + Hex.toHexString(txHash))
}
checkUnmatched()
}
@Test
@Throws(Exception::class)
fun test() {
testLogger.info("Starting EthereumJ regular instance!")
EthereumFactory.createEthereum(RegularConfig::class.java)
Thread.sleep(100000000000L)
}
/**
* Spring configuration class for the Regular peer
*/
private open class RegularConfig {
@Bean
open fun node(): PendingTxMonitor {
return PendingTxMonitor()
}
/**
* Instead of supplying properties via config file for the peer
* we are substituting the corresponding bean which returns required
* config for this instance.
*/
@Bean
open fun systemProperties(): SystemProperties {
val props = SystemProperties()
props.overrideParams(ConfigFactory.parseString(
"peer.discovery.enabled = true\n" +
"sync.enabled = true\n" +
"sync.fast.enabled = true\n" +
"database.dir = database-test-ptx\n" +
"database.reset = false\n"
))
return props
}
}
companion object {
private val testLogger = LoggerFactory.getLogger("TestLogger")
}
}
| mit | 0289ea3335cf4fe26619d22b97659a7a | 37.603865 | 161 | 0.632211 | 4.563678 | false | false | false | false |
GunoH/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/roots/impl/ModuleRootsInProjectFileIndexTest.kt | 1 | 14668 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.EXCLUDED
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.IN_CONTENT
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.IN_SOURCE
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.IN_TEST_SOURCE
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.NOT_IN_PROJECT
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.UNDER_IGNORED
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.assertScope
import com.intellij.openapi.roots.impl.ProjectFileIndexScopes.assertInModule
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.PsiTestUtil
import com.intellij.testFramework.junit5.RunInEdt
import com.intellij.testFramework.junit5.TestApplication
import com.intellij.testFramework.rules.ProjectModelExtension
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import kotlin.test.assertFalse
@TestApplication
@RunInEdt
class ModuleRootsInProjectFileIndexTest {
@JvmField
@RegisterExtension
val projectModel: ProjectModelExtension = ProjectModelExtension()
private lateinit var module: Module
private lateinit var moduleDir: VirtualFile
private val fileIndex
get() = ProjectFileIndex.getInstance(projectModel.project)
@BeforeEach
internal fun setUp() {
module = projectModel.createModule()
moduleDir = projectModel.baseProjectDir.newVirtualDirectory("module")
}
@Test
fun `add remove content root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/file.txt")
fileIndex.assertScope(moduleDir, NOT_IN_PROJECT)
fileIndex.assertScope(file, NOT_IN_PROJECT)
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(moduleDir)
assertInModule(file)
PsiTestUtil.removeContentEntry(module, moduleDir)
fileIndex.assertScope(moduleDir, NOT_IN_PROJECT)
fileIndex.assertScope(file, NOT_IN_PROJECT)
}
@Test
fun `add remove excluded root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/file.txt")
val excludedDir = projectModel.baseProjectDir.newVirtualDirectory("module/excluded")
val excludedFile = projectModel.baseProjectDir.newVirtualFile("module/excluded/excluded.txt")
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(file)
assertInModule(excludedDir)
assertInModule(excludedFile)
PsiTestUtil.addExcludedRoot(module, excludedDir)
assertInModule(file)
assertExcludedFromModule(excludedDir)
assertExcludedFromModule(excludedFile)
PsiTestUtil.removeExcludedRoot(module, excludedDir)
assertInModule(file)
assertInModule(excludedDir)
assertInModule(excludedFile)
}
@Test
fun `add remove source root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/src/A.java")
val srcDir = file.parent
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(file)
assertNull(fileIndex.getSourceRootForFile(file))
PsiTestUtil.addSourceRoot(module, srcDir)
assertInContentSource(file)
assertEquals(srcDir, fileIndex.getSourceRootForFile(file))
assertNull(fileIndex.getClassRootForFile(file))
PsiTestUtil.removeSourceRoot(module, srcDir)
assertInModule(file)
assertNull(fileIndex.getSourceRootForFile(file))
}
@Test
fun `source root types`() {
val srcDir = projectModel.baseProjectDir.newVirtualFile("module/main/java")
val testDir = projectModel.baseProjectDir.newVirtualFile("module/test/java")
val resourceDir = projectModel.baseProjectDir.newVirtualFile("module/main/resources")
val testResourceDir = projectModel.baseProjectDir.newVirtualFile("module/test/resources")
val contentRoot = srcDir.parent.parent
PsiTestUtil.addContentRoot(module, contentRoot)
PsiTestUtil.addSourceRoot(module, srcDir)
PsiTestUtil.addSourceRoot(module, testDir, true)
PsiTestUtil.addSourceRoot(module, resourceDir, JavaResourceRootType.RESOURCE)
PsiTestUtil.addSourceRoot(module, testResourceDir, JavaResourceRootType.TEST_RESOURCE)
val roots = listOf(srcDir, testDir, resourceDir, testResourceDir)
roots.forEach { dir ->
val isTest = dir.parent.name == "test"
val isResources = dir.name == "resources"
fileIndex.assertInModule(dir, module, contentRoot, if (isTest) IN_CONTENT or IN_SOURCE or IN_TEST_SOURCE else IN_CONTENT or IN_SOURCE)
assertEquals(isTest, fileIndex.isUnderSourceRootOfType(dir, JavaModuleSourceRootTypes.TESTS))
assertEquals(!isTest, fileIndex.isUnderSourceRootOfType(dir, JavaModuleSourceRootTypes.PRODUCTION))
assertEquals(isResources, fileIndex.isUnderSourceRootOfType(dir, JavaModuleSourceRootTypes.RESOURCES))
assertEquals(!isResources, fileIndex.isUnderSourceRootOfType(dir, JavaModuleSourceRootTypes.SOURCES))
}
}
@Test
fun `add remove source root under excluded`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded/src/A.java")
val srcDir = file.parent
val excludedDir = srcDir.parent
PsiTestUtil.addContentRoot(module, moduleDir)
PsiTestUtil.addExcludedRoot(module, excludedDir)
assertExcludedFromModule(file)
PsiTestUtil.addSourceRoot(module, srcDir)
assertInContentSource(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(srcDir, file), listOf(excludedDir))
PsiTestUtil.removeSourceRoot(module, srcDir)
assertExcludedFromModule(file)
}
@Test
fun `add remove content root under source root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/src/content/A.java")
val contentDir = file.parent
val srcDir = contentDir.parent
PsiTestUtil.addContentRoot(module, moduleDir)
PsiTestUtil.addSourceRoot(module, srcDir)
assertInContentSource(file)
PsiTestUtil.addContentRoot(module, contentDir)
fileIndex.assertInModule(file, module, contentDir)
PsiTestUtil.removeContentEntry(module, contentDir)
assertInContentSource(file)
}
@Test
fun `add remove source content root under excluded`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded/content-src/A.java")
val excludedFile = projectModel.baseProjectDir.newVirtualFile("module/excluded/excluded.txt")
val contentSourceDir = file.parent
val excludedDir = contentSourceDir.parent
PsiTestUtil.addContentRoot(module, moduleDir)
PsiTestUtil.addExcludedRoot(module, excludedDir)
assertExcludedFromModule(file)
PsiTestUtil.addContentRoot(module, contentSourceDir)
PsiTestUtil.addSourceRoot(module, contentSourceDir)
fileIndex.assertInModule(file, module, contentSourceDir, IN_CONTENT or IN_SOURCE)
assertExcludedFromModule(excludedFile)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(file, contentSourceDir), listOf(excludedDir, excludedFile))
PsiTestUtil.removeSourceRoot(module, contentSourceDir)
PsiTestUtil.removeContentEntry(module, contentSourceDir)
assertExcludedFromModule(file)
DirectoryIndexTestCase.assertIteratedContent(module, emptyList(), listOf(file, contentSourceDir, excludedDir, excludedFile))
}
@Test
fun `add remove excluded source root under excluded`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded/excluded-src/A.java")
val excludedSourceDir = file.parent
val excludedDir = excludedSourceDir.parent
PsiTestUtil.addContentRoot(module, moduleDir)
PsiTestUtil.addExcludedRoot(module, excludedDir)
assertExcludedFromModule(file)
PsiTestUtil.addSourceRoot(module, excludedSourceDir)
assertInContentSource(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(file, excludedSourceDir), listOf(excludedDir))
PsiTestUtil.addExcludedRoot(module, excludedSourceDir)
assertExcludedFromModule(file)
DirectoryIndexTestCase.assertIteratedContent(module, emptyList(), listOf(file, excludedSourceDir, excludedDir))
PsiTestUtil.removeExcludedRoot(module, excludedSourceDir)
assertInContentSource(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(file, excludedSourceDir), listOf(excludedDir))
}
@Test
fun `excluded content root`() {
PsiTestUtil.addContentRoot(module, moduleDir)
PsiTestUtil.addExcludedRoot(module, moduleDir)
assertExcludedFromModule(moduleDir)
val file = projectModel.baseProjectDir.newVirtualFile("module/file.txt")
assertExcludedFromModule(file)
}
@Test
fun `excluded source root`() {
PsiTestUtil.addContentRoot(module, moduleDir)
val file = projectModel.baseProjectDir.newVirtualFile("module/src/file.txt")
val srcDir = file.parent
PsiTestUtil.addSourceRoot(module, srcDir)
PsiTestUtil.addExcludedRoot(module, srcDir)
assertInModule(moduleDir)
assertExcludedFromModule(srcDir)
assertExcludedFromModule(file)
}
@Test
fun `excluded source root under excluded`() {
PsiTestUtil.addContentRoot(module, moduleDir)
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded/src/file.txt")
val srcDir = file.parent
val excludedDir = srcDir.parent
PsiTestUtil.addExcludedRoot(module, excludedDir)
PsiTestUtil.addSourceRoot(module, srcDir)
PsiTestUtil.addExcludedRoot(module, srcDir)
assertInModule(moduleDir)
assertExcludedFromModule(srcDir)
assertExcludedFromModule(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(moduleDir), listOf(file, srcDir, excludedDir))
}
@Test
fun `file as content root`() {
val file = projectModel.baseProjectDir.newVirtualFile("content.txt")
fileIndex.assertScope(file, NOT_IN_PROJECT)
PsiTestUtil.addContentRoot(module, file)
fileIndex.assertInModule(file, module, file)
PsiTestUtil.removeContentEntry(module, file)
fileIndex.assertScope(file, NOT_IN_PROJECT)
}
@Test
fun `file as source root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/source.txt")
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(file)
PsiTestUtil.addSourceRoot(module, file)
assertInContentSource(file)
PsiTestUtil.removeSourceRoot(module, file)
assertInModule(file)
}
@Test
fun `file as test source root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/source.txt")
PsiTestUtil.addSourceRoot(module, file, true)
fileIndex.assertInModule(file, module, file, IN_CONTENT or IN_SOURCE or IN_TEST_SOURCE)
PsiTestUtil.removeSourceRoot(module, file)
fileIndex.assertInModule(file, module, file)
}
@Test
fun `file as excluded root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded.txt")
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(file)
PsiTestUtil.addExcludedRoot(module, file)
assertExcludedFromModule(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(moduleDir), listOf(file))
PsiTestUtil.removeExcludedRoot(module, file)
assertInModule(file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(moduleDir, file), emptyList())
}
@Test
fun `file as excluded content root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/excluded.txt")
PsiTestUtil.addContentRoot(module, file)
fileIndex.assertInModule(file, module, file)
PsiTestUtil.addExcludedRoot(module, file)
fileIndex.assertInModule(file, module, file, EXCLUDED)
DirectoryIndexTestCase.assertIteratedContent(module, emptyList(), listOf(file))
PsiTestUtil.removeExcludedRoot(module, file)
fileIndex.assertInModule(file, module, file)
DirectoryIndexTestCase.assertIteratedContent(module, listOf(file), emptyList())
}
@Test
fun `ignored file`() {
PsiTestUtil.addContentRoot(module, moduleDir)
val file = projectModel.baseProjectDir.newVirtualFile("module/CVS")
assertTrue(FileTypeManager.getInstance().isFileIgnored(file))
fileIndex.assertScope(file, UNDER_IGNORED)
}
@Test
fun `content root under ignored dir`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/.git/content/file.txt")
val contentDir = file.parent
PsiTestUtil.addContentRoot(module, moduleDir)
assertTrue(FileTypeManager.getInstance().isFileIgnored(contentDir.parent))
assertFalse(FileTypeManager.getInstance().isFileIgnored(file))
fileIndex.assertScope(file, UNDER_IGNORED)
PsiTestUtil.addContentRoot(module, contentDir)
fileIndex.assertInModule(file, module, contentDir)
}
@Test
fun `ignored dir as content root`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/.git/file.txt")
val ignoredContentDir = file.parent
PsiTestUtil.addContentRoot(module, moduleDir)
assertTrue(FileTypeManager.getInstance().isFileIgnored(ignoredContentDir))
assertFalse(FileTypeManager.getInstance().isFileIgnored(file))
fileIndex.assertScope(file, UNDER_IGNORED)
PsiTestUtil.addContentRoot(module, ignoredContentDir)
fileIndex.assertInModule(file, module, ignoredContentDir)
}
@Test
fun `change ignored files list`() {
val file = projectModel.baseProjectDir.newVirtualFile("module/newDir/file.txt")
PsiTestUtil.addContentRoot(module, moduleDir)
assertInModule(file)
val fileTypeManager = FileTypeManager.getInstance() as FileTypeManagerEx
val oldValue = fileTypeManager.ignoredFilesList
try {
runWriteAction { fileTypeManager.ignoredFilesList = "$oldValue;newDir" }
fileIndex.assertScope(file, UNDER_IGNORED)
}
finally {
runWriteAction { fileTypeManager.ignoredFilesList = oldValue }
assertInModule(file)
}
}
private fun assertInModule(file: VirtualFile) {
fileIndex.assertInModule(file, module, moduleDir)
}
private fun assertExcludedFromModule(file: VirtualFile) {
fileIndex.assertInModule(file, module, moduleDir, EXCLUDED)
}
private fun assertInContentSource(file: VirtualFile) {
fileIndex.assertInModule(file, module, moduleDir, IN_CONTENT or IN_SOURCE)
}
} | apache-2.0 | 17d1083be37b401bdc34c08b8cbd5b24 | 38.970027 | 140 | 0.779384 | 4.646183 | false | true | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/CommitDialogConfigurable.kt | 2 | 2924 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.configurable
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsApplicationSettings
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.commit.AbstractCommitWorkflowHandler.Companion.getDefaultCommitActionName
import com.intellij.vcs.commit.CommitModeManager
import com.intellij.vcs.commit.CommitOptionsPanel
import com.intellij.vcs.commit.message.CommitMessageInspectionsPanel
import org.jetbrains.annotations.NonNls
class CommitDialogConfigurable(private val project: Project)
: BoundSearchableConfigurable(VcsBundle.message("commit.dialog.configurable"), HELP_ID, ID) {
override fun createPanel(): DialogPanel {
val disposable = disposable!!
val appSettings = VcsApplicationSettings.getInstance()
val settings = VcsConfiguration.getInstance(project)
return panel {
row {
checkBox(VcsBundle.message("settings.commit.without.dialog"))
.comment(VcsBundle.message("settings.commit.without.dialog.applies.to.git.mercurial"))
.bindSelected({ appSettings.COMMIT_FROM_LOCAL_CHANGES }, { CommitModeManager.setCommitFromLocalChanges(project, it) })
}
row {
checkBox(VcsBundle.message("checkbox.clear.initial.commit.message"))
.bindSelected(settings::CLEAR_INITIAL_COMMIT_MESSAGE)
}
group(VcsBundle.message("settings.commit.message.inspections")) {
row {
val panel = CommitMessageInspectionsPanel(project)
Disposer.register(disposable, panel)
cell(panel)
.align(AlignX.FILL)
.onApply { panel.apply() }
.onReset { panel.reset() }
.onIsModified { panel.isModified }
}.resizableRow()
}
val actionName = UIUtil.removeMnemonic(getDefaultCommitActionName(emptyList()))
group(CommitOptionsPanel.commitChecksGroupTitle(project, actionName)) {
val panel = CommitOptionsConfigurable(project)
Disposer.register(disposable, panel)
row {
cell(panel)
.align(AlignX.FILL)
.onApply { panel.apply() }
.onReset { panel.reset() }
.onIsModified { panel.isModified }
}.resizableRow()
}
}
}
companion object {
const val ID: @NonNls String = "project.propVCSSupport.CommitDialog"
private const val HELP_ID: @NonNls String = "reference.settings.VCS.CommitDialog"
}
}
| apache-2.0 | cf7cff181a7dddd353f1706d53456658 | 40.183099 | 128 | 0.725034 | 4.512346 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/OptionalExpectationInspection.kt | 4 | 4518 | // 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.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.quickfix.expectactual.CreateActualClassFix
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.oldFashionedDescription
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.classOrObjectVisitor
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker.Companion.allStrongIncompatibilities
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.multiplatform.ExpectActualCompatibility
import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver
import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil
import org.jetbrains.kotlin.resolve.multiplatform.onlyFromThisModule
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class OptionalExpectationInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return classOrObjectVisitor(fun(classOrObject: KtClassOrObject) {
if (classOrObject !is KtClass || !classOrObject.isAnnotation()) return
if (!classOrObject.hasExpectModifier()) return
val descriptor = classOrObject.resolveToDescriptorIfAny() ?: return
if (!descriptor.annotations.hasAnnotation(OptionalAnnotationUtil.OPTIONAL_EXPECTATION_FQ_NAME)) return
// FIXME(dsavvinov): this is wrong in HMPP model, use logic similar to ExpectedActualDeclarationChecker
val implementingModules = classOrObject.findModuleDescriptor().implementingDescriptors
if (implementingModules.isEmpty()) return
for (actualModuleDescriptor in implementingModules) {
val compatibility = ExpectedActualResolver.findActualForExpected(
descriptor, actualModuleDescriptor, onlyFromThisModule(actualModuleDescriptor)
) ?: continue
if (!compatibility.allStrongIncompatibilities() &&
(ExpectActualCompatibility.Compatible in compatibility ||
!compatibility.values.flatMapTo(
hashSetOf()
) { it }.all { actual ->
val expectedOnes = ExpectedActualResolver.findExpectedForActual(
actual, onlyFromThisModule(descriptor.module)
)
expectedOnes != null && ExpectActualCompatibility.Compatible in expectedOnes.keys
})
) continue
val platform = actualModuleDescriptor.platform ?: continue
if (platform.isCommon()) continue
val displayedName = actualModuleDescriptor.getCapability(ModuleInfo.Capability)?.displayedName ?: ""
val actualModule = (actualModuleDescriptor.getCapability(ModuleInfo.Capability) as? ModuleSourceInfo)?.module ?: continue
holder.registerProblem(
classOrObject.nameIdentifier ?: classOrObject,
KotlinBundle.message(
"optionally.expected.annotation.has.no.actual.annotation.in.module.0.for.platform.1",
displayedName,
platform.oldFashionedDescription
),
IntentionWrapper(CreateActualClassFix(classOrObject, actualModule, platform))
)
}
})
}
}
| apache-2.0 | dcf351fe82c106b6be6f605760e60acc | 57.675325 | 158 | 0.715361 | 5.718987 | false | false | false | false |
GunoH/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/uploader/EventLogExternalUploader.kt | 7 | 8994 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.eventLog.uploader
import com.google.gson.Gson
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.eventLog.*
import com.intellij.internal.statistic.eventLog.connection.metadata.EventGroupsFilterRules
import com.intellij.internal.statistic.eventLog.uploader.EventLogUploadException.EventLogUploadErrorType.*
import com.intellij.internal.statistic.uploader.EventLogUploaderOptions
import com.intellij.internal.statistic.uploader.EventLogUploaderOptions.*
import com.intellij.internal.statistic.uploader.events.*
import com.intellij.internal.statistic.uploader.util.ExtraHTTPHeadersParser
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.Strings
import com.intellij.util.ArrayUtil
import org.jetbrains.annotations.NotNull
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
object EventLogExternalUploader {
private val LOG = Logger.getInstance(EventLogExternalUploader.javaClass)
private const val UPLOADER_MAIN_CLASS = "com.intellij.internal.statistic.uploader.EventLogUploader"
fun logPreviousExternalUploadResult(providers: List<StatisticsEventLoggerProvider>) {
val enabledProviders = providers.filter { it.isSendEnabled() }
if (enabledProviders.isEmpty()) {
return
}
try {
val tempDir = getTempFile()
if (tempDir.exists()) {
val events = ExternalEventsLogger.parseEvents(tempDir)
for (provider in enabledProviders) {
logPreviousExternalUploadResultByRecorder(provider.recorderId, events)
}
}
tempDir.deleteRecursively()
}
catch (e: Exception) {
LOG.warn("Failed reading previous upload result: " + e.message)
}
}
private fun logPreviousExternalUploadResultByRecorder(recorderId: String, events: List<ExternalSystemEvent>) {
for (event in events) {
val eventRecorderId = event.recorderId
if (eventRecorderId != recorderId && eventRecorderId != ExternalSystemEvent.ALL_RECORDERS) {
continue
}
when (event) {
is ExternalUploadStartedEvent -> {
EventLogSystemLogger.logStartingExternalSend(recorderId, event.timestamp)
}
is ExternalUploadSendEvent -> {
val files = event.successfullySentFiles
val errors = event.errors
EventLogSystemLogger.logFilesSend(recorderId, event.total, event.succeed, event.failed, true, files, errors)
}
is ExternalUploadFinishedEvent -> {
EventLogSystemLogger.logFinishedExternalSend(recorderId, event.error, event.timestamp)
}
is ExternalSystemErrorEvent -> {
EventLogSystemLogger.logSystemError(recorderId, event.event, event.errorClass, event.timestamp)
}
}
}
}
fun startExternalUpload(recordersProviders: List<StatisticsEventLoggerProvider>, isTest: Boolean) {
val enabledRecordersProviders = recordersProviders.filter { it.isSendEnabled() }
if (enabledRecordersProviders.isEmpty()) {
LOG.info("Don't start external process because sending logs is disabled for all recorders")
return
}
val recorderIds = enabledRecordersProviders.map { it.recorderId }
EventLogSystemLogger.logCreatingExternalSendCommand(recorderIds)
val application = EventLogInternalApplicationInfo(isTest)
try {
val command = prepareUploadCommand(enabledRecordersProviders, application)
EventLogSystemLogger.logFinishedCreatingExternalSendCommand(recorderIds, null)
if (LOG.isDebugEnabled) {
LOG.debug("Starting external process: '${command.joinToString(separator = " ")}'")
}
Runtime.getRuntime().exec(command)
LOG.info("Started external process for uploading event log")
}
catch (e: EventLogUploadException) {
EventLogSystemLogger.logFinishedCreatingExternalSendCommand(recorderIds, e.errorType)
LOG.info(e)
}
}
private fun prepareUploadCommand(recorders: List<StatisticsEventLoggerProvider>, applicationInfo: EventLogApplicationInfo): Array<out String> {
val sendConfigs = recorders.map { EventLogInternalSendConfig.createByRecorder(it.recorderId, false) }
if (sendConfigs.isEmpty()) {
throw EventLogUploadException("No available logs to send", NO_LOGS)
}
val tempDir = getOrCreateTempDir()
val uploader = findUploader()
val libPaths = ArrayList<String>()
libPaths.add(findLibraryByClass(kotlin.coroutines.Continuation::class.java)) // add kotlin-std to classpath
libPaths.add(findLibraryByClass(NotNull::class.java))
libPaths.add(findLibraryByClass(Gson::class.java))
libPaths.add(findLibraryByClass(EventGroupsFilterRules::class.java))
val classpath = joinAsClasspath(libPaths, uploader)
return createExternalUploadCommand(applicationInfo, sendConfigs, classpath, tempDir)
}
fun createExternalUploadCommand(applicationInfo: EventLogApplicationInfo,
configs: List<EventLogSendConfig>,
classpath: String,
tempDir: File): Array<out String> {
val args = arrayListOf<String>()
val java = findJavaHome()
args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path
addArgument(args, "-cp", classpath)
args += "-Djava.io.tmpdir=${tempDir.path}"
args += UPLOADER_MAIN_CLASS
addArgument(args, IDE_TOKEN, Paths.get(PathManager.getSystemPath(), "token").toAbsolutePath().toString())
addArgument(args, RECORDERS_OPTION, configs.joinToString(separator = ";") { it.getRecorderId() })
for (config in configs) {
addRecorderConfiguration(args, config)
}
addArgument(args, URL_OPTION, applicationInfo.templateUrl)
addArgument(args, PRODUCT_OPTION, applicationInfo.productCode)
addArgument(args, PRODUCT_VERSION_OPTION, applicationInfo.productVersion)
addArgument(args, USER_AGENT_OPTION, applicationInfo.connectionSettings.getUserAgent())
addArgument(args, EXTRA_HEADERS, ExtraHTTPHeadersParser.serialize(applicationInfo.connectionSettings.getExtraHeaders()))
if (applicationInfo.isInternal) {
args += INTERNAL_OPTION
}
if (applicationInfo.isTest) {
args += TEST_OPTION
}
if (applicationInfo.isEAP) {
args += EAP_OPTION
}
return ArrayUtil.toStringArray(args)
}
private fun addRecorderConfiguration(args: ArrayList<String>, config: EventLogSendConfig) {
val recorderIdLowerCase = Strings.toLowerCase(config.getRecorderId())
addArgument(args, DEVICE_OPTION + recorderIdLowerCase, config.getDeviceId())
addArgument(args, BUCKET_OPTION + recorderIdLowerCase, config.getBucket().toString())
addArgument(args, MACHINE_ID_OPTION + recorderIdLowerCase, config.getMachineId().id)
addArgument(args, ID_REVISION_OPTION + recorderIdLowerCase, config.getMachineId().revision.toString())
val filesToSend = config.getFilesToSendProvider().getFilesToSend().map { it.file }
addArgument(args, LOGS_OPTION + recorderIdLowerCase, filesToSend.joinToString(separator = File.pathSeparator))
}
private fun addArgument(args: ArrayList<String>, name: String, value: String) {
args += name
args += value
}
private fun joinAsClasspath(libCopies: List<String>, uploaderCopy: Path): String {
if (libCopies.isEmpty()) {
return uploaderCopy.toString()
}
val libClassPath = libCopies.joinToString(separator = File.pathSeparator)
return "$libClassPath${File.pathSeparator}$uploaderCopy"
}
private fun findUploader(): Path {
val uploader = if (PluginManagerCore.isRunningFromSources()) {
Paths.get(PathManager.getHomePath(), "out/artifacts/statistics-uploader.jar")
}
else {
PathManager.getJarForClass(EventLogUploaderOptions::class.java)
}
if (uploader == null || !Files.isRegularFile(uploader)) {
throw EventLogUploadException("Cannot find uploader jar", NO_UPLOADER)
}
return uploader
}
private fun findLibraryByClass(clazz: Class<*>): String {
val library = PathManager.getJarForClass(clazz)
if (library == null || !Files.isRegularFile(library)) {
throw EventLogUploadException("Cannot find jar for $clazz", NO_UPLOADER)
}
return library.toString()
}
private fun findJavaHome(): String {
return System.getProperty("java.home")
}
private fun getOrCreateTempDir(): File {
val tempDir = getTempFile()
if (!(tempDir.exists() || tempDir.mkdirs())) {
throw EventLogUploadException("Cannot create temp directory: $tempDir", NO_TEMP_FOLDER)
}
return tempDir
}
private fun getTempFile(): File {
return File(PathManager.getTempPath(), "statistics-uploader")
}
}
| apache-2.0 | a542c9a17d79ce915a63bb1ea3684e58 | 39.696833 | 145 | 0.730598 | 4.600512 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/dependencies/KotlinScriptDependenciesLibraryRootProvider.kt | 1 | 5360 | // 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.core.script.dependencies
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.AdditionalLibraryRootsProvider
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.roots.impl.CustomEntityProjectModelInfoProvider
import com.intellij.openapi.roots.impl.CustomEntityProjectModelInfoProvider.LibraryRoots
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRootTypeId
import org.jetbrains.deft.annotations.Child
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptEntity
import org.jetbrains.kotlin.idea.core.script.ucache.scriptsAsEntities
import javax.swing.Icon
/**
* See recommendations for custom entities indexing
* [here](https://youtrack.jetbrains.com/articles/IDEA-A-239/Integration-of-custom-workspace-entities-with-platform-functionality)
*/
class KotlinScriptProjectModelInfoProvider : CustomEntityProjectModelInfoProvider<KotlinScriptEntity> {
override fun getEntityClass(): Class<KotlinScriptEntity> = KotlinScriptEntity::class.java
override fun getLibraryRoots(
entities: Sequence<KotlinScriptEntity>,
entityStorage: EntityStorage
): Sequence<LibraryRoots<KotlinScriptEntity>> =
if (!scriptsAsEntities) { // see KotlinScriptDependenciesLibraryRootProvider
emptySequence()
} else {
entities.flatMap { scriptEntity ->
scriptEntity.dependencies.map<@Child LibraryEntity, LibraryRoots<KotlinScriptEntity>> { libEntity ->
val (classes, sources) = libEntity.roots.partition { it.type == LibraryRootTypeId.COMPILED }
val classFiles = classes.mapNotNull { it.url.virtualFile }
val sourceFiles = sources.mapNotNull { it.url.virtualFile }
LibraryRoots(scriptEntity, sourceFiles, classFiles, emptyList(), null)
}
}
}
}
class KotlinScriptDependenciesLibraryRootProvider : AdditionalLibraryRootsProvider() {
override fun getAdditionalProjectLibraries(project: Project): Collection<SyntheticLibrary> { // RootIndex & FileBasedIndexEx need it
if (scriptsAsEntities) return emptyList() // see KotlinScriptProjectModelInfoProvider
val manager = ScriptConfigurationManager.getInstance(project)
val classes = manager.getAllScriptsDependenciesClassFiles().filterValid()
val sources = manager.getAllScriptDependenciesSources().filterValid()
val sdkClasses = manager.getAllScriptsSdkDependenciesClassFiles().filterValid()
val sdkSources = manager.getAllScriptSdkDependenciesSources().filterValid()
return if (classes.isEmpty() && sources.isEmpty() && sdkClasses.isEmpty() && sdkSources.isEmpty()) {
emptyList()
} else {
val library = KotlinScriptDependenciesLibrary(classes = classes, sources = sources)
if (sdkClasses.isEmpty() && sdkSources.isEmpty()) {
listOf(library)
} else {
listOf(ScriptSdk(manager.getFirstScriptsSdk(), sdkClasses, sdkSources), library)
}
}
}
private fun Collection<VirtualFile>.filterValid() = this.filterTo(LinkedHashSet(), VirtualFile::isValid)
override fun getRootsToWatch(project: Project): Collection<VirtualFile> = if (scriptsAsEntities) {
emptyList()
} else {
ScriptConfigurationManager.allExtraRoots(project).filterValid()
}
private data class KotlinScriptDependenciesLibrary(val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) :
SyntheticLibrary("KotlinScriptDependenciesLibrary", null), ItemPresentation {
override fun getBinaryRoots(): Collection<VirtualFile> = classes
override fun getSourceRoots(): Collection<VirtualFile> = sources
override fun getPresentableText(): String = KotlinBaseScriptingBundle.message("script.name.kotlin.script.dependencies")
override fun getIcon(unused: Boolean): Icon = KotlinIcons.SCRIPT
}
private data class ScriptSdk(val sdk: Sdk?, val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) :
SyntheticLibrary(), ItemPresentation {
override fun getBinaryRoots(): Collection<VirtualFile> = classes
override fun getSourceRoots(): Collection<VirtualFile> = sources
override fun getPresentableText(): String =
sdk?.let { KotlinBaseScriptingBundle.message("script.name.kotlin.script.sdk.dependencies.0", it.name) }
?: KotlinBaseScriptingBundle.message("script.name.kotlin.script.sdk.dependencies")
override fun getIcon(unused: Boolean): Icon = KotlinIcons.GRADLE_SCRIPT
}
} | apache-2.0 | 52b02ac40f2a04b14b62485296d7efc3 | 50.548077 | 136 | 0.744403 | 5.168756 | false | false | false | false |
LouisCAD/Splitties | modules/bitflags/src/commonMain/kotlin/splitties/bitflags/BitFlags.kt | 1 | 1864 | /*
* Copyright 2019-2021 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.bitflags
import kotlin.experimental.and
import kotlin.experimental.inv
import kotlin.experimental.or
inline fun Long.hasFlag(flag: Long): Boolean = flag and this == flag
inline fun Long.withFlag(flag: Long): Long = this or flag
inline fun Long.minusFlag(flag: Long): Long = this and flag.inv()
inline fun Int.hasFlag(flag: Int): Boolean = flag and this == flag
inline fun Int.withFlag(flag: Int): Int = this or flag
inline fun Int.minusFlag(flag: Int): Int = this and flag.inv()
inline fun Short.hasFlag(flag: Short): Boolean = flag and this == flag
inline fun Short.withFlag(flag: Short): Short = this or flag
inline fun Short.minusFlag(flag: Short): Short = this and flag.inv()
inline fun Byte.hasFlag(flag: Byte): Boolean = flag and this == flag
inline fun Byte.withFlag(flag: Byte): Byte = this or flag
inline fun Byte.minusFlag(flag: Byte): Byte = this and flag.inv()
inline fun ULong.hasFlag(flag: ULong): Boolean = flag and this == flag
inline fun ULong.withFlag(flag: ULong): ULong = this or flag
inline fun ULong.minusFlag(flag: ULong): ULong = this and flag.inv()
inline fun UInt.hasFlag(flag: UInt): Boolean = flag and this == flag
inline fun UInt.withFlag(flag: UInt): UInt = this or flag
inline fun UInt.minusFlag(flag: UInt): UInt = this and flag.inv()
inline fun UShort.hasFlag(flag: UShort): Boolean = flag and this == flag
inline fun UShort.withFlag(flag: UShort): UShort = this or flag
inline fun UShort.minusFlag(flag: UShort): UShort = this and flag.inv()
inline fun UByte.hasFlag(flag: UByte): Boolean = flag and this == flag
inline fun UByte.withFlag(flag: UByte): UByte = this or flag
inline fun UByte.minusFlag(flag: UByte): UByte = this and flag.inv()
| apache-2.0 | c2cb27929408bd89a77982cd8132b240 | 42.348837 | 114 | 0.74088 | 3.584615 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/DocumentTracker.kt | 1 | 28241 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.ex
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.comparison.iterables.FairDiffIterable
import com.intellij.diff.comparison.trimStart
import com.intellij.diff.tools.util.text.LineOffsets
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Range
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationAdapter
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.DocumentBulkUpdateListener
import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vcs.ex.DocumentTracker.Listener
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.annotations.CalledInAwt
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.read
import kotlin.concurrent.withLock
class DocumentTracker : Disposable {
private val dispatcher: EventDispatcher<Listener> = EventDispatcher.create(Listener::class.java)
private val multicaster = dispatcher.multicaster
// Any external calls (ex: Document modifications) must be avoided under lock,
// do avoid deadlock with ChangeListManager
internal val LOCK: Lock = Lock()
val document1: Document
val document2: Document
private val tracker: LineTracker = LineTracker(dispatcher)
private val freezeHelper: FreezeHelper = FreezeHelper()
private var isDisposed: Boolean = false
constructor(document1: Document, document2: Document) {
assert(document1 != document2)
this.document1 = document1
this.document2 = document2
val changes = compareLines(document1.immutableCharSequence,
document2.immutableCharSequence,
document1.lineOffsets,
document2.lineOffsets).iterateChanges().toList()
tracker.setRanges(changes, false)
val application = ApplicationManager.getApplication()
application.addApplicationListener(MyApplicationListener(), this)
application.messageBus.connect(this)
.subscribe(DocumentBulkUpdateListener.TOPIC, MyDocumentBulkUpdateListener())
document1.addDocumentListener(MyDocumentListener(Side.LEFT), this)
document2.addDocumentListener(MyDocumentListener(Side.RIGHT), this)
}
@CalledInAwt
override fun dispose() {
ApplicationManager.getApplication().assertIsDispatchThread()
if (isDisposed) return
isDisposed = true
LOCK.write {
tracker.destroy()
}
}
val blocks: List<Block> get() = tracker.blocks
fun addListener(listener: Listener) {
dispatcher.addListener(listener)
}
fun <T> readLock(task: () -> T): T = LOCK.read(task)
fun <T> writeLock(task: () -> T): T = LOCK.write(task)
val isLockHeldByCurrentThread: Boolean get() = LOCK.isHeldByCurrentThread
fun isFrozen(): Boolean {
LOCK.read {
return freezeHelper.isFrozen()
}
}
@CalledInAwt
fun freeze(side: Side) {
LOCK.write {
freezeHelper.freeze(side)
}
}
@CalledInAwt
fun unfreeze(side: Side) {
LOCK.write {
freezeHelper.unfreeze(side)
}
}
@CalledInAwt
inline fun doFrozen(task: () -> Unit) {
doFrozen(Side.LEFT) {
doFrozen(Side.RIGHT) {
task()
}
}
}
@CalledInAwt
inline fun doFrozen(side: Side, task: () -> Unit) {
freeze(side)
try {
task()
}
finally {
unfreeze(side)
}
}
fun getContent(side: Side): CharSequence {
LOCK.read {
val frozenContent = freezeHelper.getFrozenContent(side)
if (frozenContent != null) return frozenContent
return side[document1, document2].immutableCharSequence
}
}
@CalledInAwt
fun refreshDirty(fastRefresh: Boolean, forceInFrozen: Boolean = false) {
if (isDisposed) return
if (!forceInFrozen && freezeHelper.isFrozen()) return
LOCK.write {
if (!blocks.isEmpty() &&
StringUtil.equals(document1.immutableCharSequence, document2.immutableCharSequence)) {
tracker.setRanges(emptyList(), false)
return
}
tracker.refreshDirty(document1.immutableCharSequence,
document2.immutableCharSequence,
document1.lineOffsets,
document2.lineOffsets,
fastRefresh)
}
}
private fun unfreeze(side: Side, oldText: CharSequence) {
assert(LOCK.isHeldByCurrentThread)
if (isDisposed) return
val newText = side[document1, document2]
var shift = 0
val iterable = compareLines(oldText, newText.immutableCharSequence, oldText.lineOffsets, newText.lineOffsets)
for (range in iterable.changes()) {
val beforeLength = range.end1 - range.start1
val afterLength = range.end2 - range.start2
tracker.rangeChanged(side, range.start1 + shift, beforeLength, afterLength)
shift += afterLength - beforeLength
}
}
private fun updateFrozenContentIfNeeded(side: Side) {
assert(LOCK.isHeldByCurrentThread)
if (!freezeHelper.isFrozen(side)) return
unfreeze(side, freezeHelper.getFrozenContent(side)!!)
freezeHelper.setFrozenContent(side, side[document1, document2].immutableCharSequence)
}
@CalledInAwt
fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean, consumer: (Block, shift: Int) -> Unit) {
if (isDisposed) return
val otherSide = side.other()
val document = side[document1, document2]
val otherDocument = otherSide[document1, document2]
doFrozen(side) {
val appliedBlocks = LOCK.write {
// ensure blocks are up to date
updateFrozenContentIfNeeded(Side.LEFT)
updateFrozenContentIfNeeded(Side.RIGHT)
refreshDirty(fastRefresh = false, forceInFrozen = true)
tracker.partiallyApplyBlocks(side, condition)
}
// We use already filtered blocks here, because conditions might have been changed from other thread.
// The documents/blocks themselves did not change though.
LineTracker.processAppliedRanges(appliedBlocks, { true }, side) { block, shift, _ ->
DiffUtil.applyModification(document, block.range.start(side) + shift, block.range.end(side) + shift,
otherDocument, block.range.start(otherSide), block.range.end(otherSide))
consumer(block, shift)
}
LOCK.write {
freezeHelper.setFrozenContent(side, document.immutableCharSequence)
}
}
}
fun getContentWithPartiallyAppliedBlocks(side: Side, condition: (Block) -> Boolean): String {
val otherSide = side.other()
val affectedBlocks = LOCK.read {
tracker.blocks.filter(condition)
}
val content = getContent(side)
val otherContent = getContent(otherSide)
val lineOffsets = content.lineOffsets
val otherLineOffsets = otherContent.lineOffsets
val ranges = affectedBlocks.map {
Range(it.range.start(side), it.range.end(side),
it.range.start(otherSide), it.range.end(otherSide))
}
return DiffUtil.applyModification(content, lineOffsets, otherContent, otherLineOffsets, ranges)
}
fun setFrozenState(content1: CharSequence, content2: CharSequence, lineRanges: List<Range>): Boolean {
assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT))
if (isDisposed) return false
LOCK.write {
if (!isValidState(content1, content2, lineRanges)) return false
freezeHelper.setFrozenContent(Side.LEFT, content1)
freezeHelper.setFrozenContent(Side.RIGHT, content2)
tracker.setRanges(lineRanges, true)
return true
}
}
@CalledInAwt
fun setFrozenState(lineRanges: List<Range>): Boolean {
if (isDisposed) return false
assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT))
LOCK.write {
val content1 = getContent(Side.LEFT)
val content2 = getContent(Side.RIGHT)
if (!isValidState(content1, content2, lineRanges)) return false
tracker.setRanges(lineRanges, true)
return true
}
}
private fun isValidState(content1: CharSequence,
content2: CharSequence,
lineRanges: List<Range>): Boolean {
val lineOffset1 = content1.lineOffsets
val lineOffset2 = content2.lineOffsets
val iterable = DiffIterableUtil.create(lineRanges, lineOffset1.lineCount, lineOffset2.lineCount)
for (range in iterable.unchanged()) {
val lines1 = DiffUtil.getLines(content1, lineOffset1, range.start1, range.end1)
val lines2 = DiffUtil.getLines(content2, lineOffset2, range.start2, range.end2)
if (lines1 != lines2) return false
}
return true
}
private inner class MyDocumentBulkUpdateListener : DocumentBulkUpdateListener {
init {
if ((document1 as DocumentEx).isInBulkUpdate) freeze(Side.LEFT)
if ((document2 as DocumentEx).isInBulkUpdate) freeze(Side.RIGHT)
}
override fun updateStarted(doc: Document) {
if (document1 == doc) freeze(Side.LEFT)
if (document2 == doc) freeze(Side.RIGHT)
}
override fun updateFinished(doc: Document) {
if (document1 == doc) unfreeze(Side.LEFT)
if (document2 == doc) unfreeze(Side.RIGHT)
}
}
private inner class MyApplicationListener : ApplicationAdapter() {
override fun afterWriteActionFinished(action: Any) {
refreshDirty(fastRefresh = true)
}
}
private inner class MyDocumentListener(val side: Side) : DocumentListener {
private val document = side[document1, document2]
private var line1: Int = 0
private var line2: Int = 0
override fun beforeDocumentChange(e: DocumentEvent) {
if (isDisposed || freezeHelper.isFrozen(side)) return
line1 = document.getLineNumber(e.offset)
if (e.oldLength == 0) {
line2 = line1 + 1
}
else {
line2 = document.getLineNumber(e.offset + e.oldLength) + 1
}
}
override fun documentChanged(e: DocumentEvent) {
if (isDisposed || freezeHelper.isFrozen(side)) return
val newLine2: Int
if (e.newLength == 0) {
newLine2 = line1 + 1
}
else {
newLine2 = document.getLineNumber(e.offset + e.newLength) + 1
}
val (startLine, afterLength, beforeLength) = getAffectedRange(line1, line2, newLine2, e)
LOCK.write {
tracker.rangeChanged(side, startLine, beforeLength, afterLength)
}
}
private fun getAffectedRange(line1: Int, oldLine2: Int, newLine2: Int, e: DocumentEvent): Triple<Int, Int, Int> {
val afterLength = newLine2 - line1
val beforeLength = line2 - line1
// Whole line insertion / deletion
if (e.oldLength == 0 && e.newLength != 0) {
if (StringUtil.endsWithChar(e.newFragment, '\n') && isNewlineBefore(e)) {
return Triple(line1, afterLength - 1, beforeLength - 1)
}
if (StringUtil.startsWithChar(e.newFragment, '\n') && isNewlineAfter(e)) {
return Triple(line1 + 1, afterLength - 1, beforeLength - 1)
}
}
if (e.oldLength != 0 && e.newLength == 0) {
if (StringUtil.endsWithChar(e.oldFragment, '\n') && isNewlineBefore(e)) {
return Triple(line1, afterLength - 1, beforeLength - 1)
}
if (StringUtil.startsWithChar(e.oldFragment, '\n') && isNewlineAfter(e)) {
return Triple(line1 + 1, afterLength - 1, beforeLength - 1)
}
}
return Triple(line1, afterLength, beforeLength)
}
private fun isNewlineBefore(e: DocumentEvent): Boolean {
if (e.offset == 0) return true
return e.document.immutableCharSequence[e.offset - 1] == '\n'
}
private fun isNewlineAfter(e: DocumentEvent): Boolean {
if (e.offset + e.newLength == e.document.immutableCharSequence.length) return true
return e.document.immutableCharSequence[e.offset + e.newLength] == '\n'
}
}
private inner class FreezeHelper {
private var data1: FreezeData? = null
private var data2: FreezeData? = null
fun isFrozen(side: Side) = getData(side) != null
fun isFrozen() = isFrozen(Side.LEFT) || isFrozen(Side.RIGHT)
fun freeze(side: Side) {
var data = getData(side)
if (data == null) {
data = FreezeData(side[document1, document2])
setData(side, data)
data.counter++
multicaster.onFreeze(side)
}
else {
data.counter++
}
}
fun unfreeze(side: Side) {
val data = getData(side)
if (data == null || data.counter == 0) {
LOG.error("DocumentTracker is not freezed: $side, ${data1?.counter ?: -1}, ${data2?.counter ?: -1}")
return
}
data.counter--
if (data.counter == 0) {
unfreeze(side, data.textBeforeFreeze)
setData(side, null)
refreshDirty(fastRefresh = false)
multicaster.onUnfreeze(side)
}
}
private fun getData(side: Side) = side[data1, data2]
private fun setData(side: Side, data: FreezeData?) {
if (side.isLeft) {
data1 = data
}
else {
data2 = data
}
}
fun getFrozenContent(side: Side): CharSequence? = getData(side)?.textBeforeFreeze
fun setFrozenContent(side: Side, newContent: CharSequence) {
setData(side, FreezeData(getData(side)!!, newContent))
}
}
private class FreezeData(val textBeforeFreeze: CharSequence, var counter: Int) {
constructor(document: Document) : this(document.immutableCharSequence, 0)
constructor(data: FreezeData, textBeforeFreeze: CharSequence) : this(textBeforeFreeze, data.counter)
}
internal inner class Lock {
private val myLock = ReentrantLock()
internal inline fun <T> read(task: () -> T): T {
return myLock.withLock(task)
}
internal inline fun <T> write(task: () -> T): T {
return myLock.withLock(task)
}
internal val isHeldByCurrentThread: Boolean
get() = myLock.isHeldByCurrentThread
}
interface Listener : EventListener {
fun onRangeRefreshed(before: Block, after: List<Block>) {}
fun onRangesChanged(before: List<Block>, after: Block) {}
fun onRangeShifted(before: Block, after: Block) {}
fun onRangesMerged(range1: Block, range2: Block, merged: Block): Boolean = true
fun onRangeRemoved(block: Block) {}
fun onRangeAdded(block: Block) {}
fun afterRefresh() {}
fun afterRangeChange() {}
fun afterExplicitChange() {}
fun onFreeze(side: Side) {}
fun onUnfreeze(side: Side) {}
}
class Block(val range: Range, internal val isDirty: Boolean, internal val isTooBig: Boolean) {
var data: Any? = null
}
companion object {
private val LOG = Logger.getInstance(DocumentTracker::class.java)
}
}
private class LineTracker(private val dispatcher: EventDispatcher<Listener>) {
private val multicaster = dispatcher.multicaster
var blocks: List<Block> = emptyList()
private set
private var isDirty: Boolean = false
fun destroy() {
multicaster.onRangesRemoved(blocks)
blocks = emptyList()
}
fun refreshDirty(text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets,
fastRefresh: Boolean) {
if (!isDirty) return
val removedBlocks = ArrayList<Block>()
val addedBlocks = ArrayList<Block>()
val newBlocks = ArrayList<Block>()
BlockGroupsProcessor(text1, lineOffsets1).processMergeableGroups(blocks) { group ->
if (group.any { it.isDirty }) {
MergingBlockProcessor(dispatcher).processMergedBlocks(group) { original, mergedBlock ->
val freshBlocks = refreshBlock(mergedBlock, text1, text2, lineOffsets1, lineOffsets2, fastRefresh)
removedBlocks.addAll(original)
addedBlocks.addAll(freshBlocks)
multicaster.onRangeRefreshed(mergedBlock, freshBlocks)
newBlocks.addAll(freshBlocks)
}
}
else {
newBlocks.addAll(group)
}
}
multicaster.onRangesRemoved(removedBlocks)
multicaster.onRangesAdded(addedBlocks)
blocks = newBlocks
isDirty = false
multicaster.afterRefresh()
}
fun rangeChanged(side: Side, startLine: Int, beforeLength: Int, afterLength: Int) {
val data = handleRangeChange(blocks, side, startLine, beforeLength, afterLength)
multicaster.onRangesChanged(data.affectedBlocks, data.newAffectedBlock)
for (i in data.afterBlocks.indices) {
multicaster.onRangeShifted(data.afterBlocks[i], data.newAfterBlocks[i])
}
multicaster.onRangesRemoved(data.affectedBlocks)
multicaster.onRangesRemoved(data.afterBlocks)
multicaster.onRangeAdded(data.newAffectedBlock)
multicaster.onRangesAdded(data.newAfterBlocks)
blocks = ContainerUtil.concat(data.beforeBlocks, listOf(data.newAffectedBlock), data.newAfterBlocks)
isDirty = true
multicaster.afterRangeChange()
}
private fun refreshBlock(block: Block,
text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets,
fastRefresh: Boolean): List<Block> {
if (block.range.isEmpty) return emptyList()
val iterable: FairDiffIterable
val isTooBig: Boolean
if (block.isTooBig && fastRefresh) {
iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
isTooBig = true
}
else {
val realIterable = tryCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
if (realIterable != null) {
iterable = realIterable
isTooBig = false
}
else {
iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
isTooBig = true
}
}
return iterable.iterateChanges().map {
Block(shiftRange(it, block.range.start1, block.range.start2), false, isTooBig)
}
}
fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean): List<Block> {
val oldBlocks = blocks
val newBlocks = mutableListOf<Block>()
val appliedBlocks = mutableListOf<Block>()
processAppliedRanges(blocks, condition, side) { block, shift, isApplied ->
if (isApplied) {
appliedBlocks += block
}
else {
val newBlock = block.shift(side, shift)
multicaster.onRangeShifted(block, newBlock)
newBlocks.add(newBlock)
}
}
multicaster.onRangesRemoved(oldBlocks)
multicaster.onRangesAdded(newBlocks)
blocks = newBlocks
multicaster.afterExplicitChange()
return appliedBlocks
}
fun setRanges(ranges: List<Range>, dirty: Boolean) {
val oldBlocks = blocks
val newBlocks = ranges.map { Block(it, dirty, false) }
multicaster.onRangesRemoved(oldBlocks)
multicaster.onRangesAdded(newBlocks)
blocks = newBlocks
if (dirty) isDirty = true
multicaster.afterExplicitChange()
}
companion object {
private fun handleRangeChange(blocks: List<Block>,
side: Side,
startLine: Int,
beforeLength: Int,
afterLength: Int): BlockChangeData {
val endLine = startLine + beforeLength
val rangeSizeDelta = afterLength - beforeLength
val (beforeBlocks, affectedBlocks, afterBlocks) = sortRanges(blocks, side, startLine, endLine)
val ourToOtherShift: Int = getOurToOtherShift(side, beforeBlocks)
val newAffectedBlock = getNewAffectedBlock(side, startLine, endLine, rangeSizeDelta, ourToOtherShift,
affectedBlocks)
val newAfterBlocks = afterBlocks.map { it.shift(side, rangeSizeDelta) }
return BlockChangeData(beforeBlocks,
affectedBlocks, afterBlocks,
newAffectedBlock, newAfterBlocks)
}
private fun sortRanges(blocks: List<Block>,
side: Side,
line1: Int,
line2: Int): Triple<List<Block>, List<Block>, List<Block>> {
val beforeChange = ArrayList<Block>()
val affected = ArrayList<Block>()
val afterChange = ArrayList<Block>()
for (block in blocks) {
if (block.range.end(side) < line1) {
beforeChange.add(block)
}
else if (block.range.start(side) > line2) {
afterChange.add(block)
}
else {
affected.add(block)
}
}
return Triple(beforeChange, affected, afterChange)
}
private fun getOurToOtherShift(side: Side, beforeBlocks: List<Block>): Int {
val lastBefore = beforeBlocks.lastOrNull()?.range
val otherShift: Int
if (lastBefore == null) {
otherShift = 0
}
else {
otherShift = lastBefore.end(side.other()) - lastBefore.end(side)
}
return otherShift
}
private fun getNewAffectedBlock(side: Side,
startLine: Int,
endLine: Int,
rangeSizeDelta: Int,
ourToOtherShift: Int,
affectedBlocks: List<Block>): Block {
val rangeStart: Int
val rangeEnd: Int
val rangeStartOther: Int
val rangeEndOther: Int
if (affectedBlocks.isEmpty()) {
rangeStart = startLine
rangeEnd = endLine + rangeSizeDelta
rangeStartOther = startLine + ourToOtherShift
rangeEndOther = endLine + ourToOtherShift
}
else {
val firstAffected = affectedBlocks.first().range
val lastAffected = affectedBlocks.last().range
val affectedStart = firstAffected.start(side)
val affectedStartOther = firstAffected.start(side.other())
val affectedEnd = lastAffected.end(side)
val affectedEndOther = lastAffected.end(side.other())
if (affectedStart <= startLine) {
rangeStart = affectedStart
rangeStartOther = affectedStartOther
}
else {
rangeStart = startLine
rangeStartOther = startLine + (affectedStartOther - affectedStart)
}
if (affectedEnd >= endLine) {
rangeEnd = affectedEnd + rangeSizeDelta
rangeEndOther = affectedEndOther
}
else {
rangeEnd = endLine + rangeSizeDelta
rangeEndOther = endLine + (affectedEndOther - affectedEnd)
}
}
val isTooBig = affectedBlocks.any { it.isTooBig }
val range = createRange(side, rangeStart, rangeEnd, rangeStartOther, rangeEndOther)
return Block(range, true, isTooBig)
}
fun processAppliedRanges(blocks: List<Block>, condition: (Block) -> Boolean, side: Side,
handler: (block: Block, shift: Int, isApplied: Boolean) -> Unit) {
val otherSide = side.other()
var shift = 0
for (block in blocks) {
if (condition(block)) {
handler(block, shift, true)
val deleted = block.range.end(side) - block.range.start(side)
val inserted = block.range.end(otherSide) - block.range.start(otherSide)
shift += inserted - deleted
}
else {
handler(block, shift, false)
}
}
}
private fun Block.shift(side: Side, delta: Int) = Block(
shiftRange(this.range, side, delta), this.isDirty, this.isTooBig)
private fun createRange(side: Side, start: Int, end: Int, otherStart: Int, otherEnd: Int): Range {
return Range(side[start, otherStart], side[end, otherEnd],
side[otherStart, start], side[otherEnd, end])
}
private fun shiftRange(range: Range, side: Side, shift: Int) = shiftRange(
range, side[shift, 0], side[0, shift])
private fun shiftRange(range: Range, shift1: Int, shift2: Int) = Range(range.start1 + shift1,
range.end1 + shift1,
range.start2 + shift2,
range.end2 + shift2)
}
private data class BlockChangeData(val beforeBlocks: List<Block>,
val affectedBlocks: List<Block>, val afterBlocks: List<Block>,
val newAffectedBlock: Block, val newAfterBlocks: List<Block>)
private fun Listener.onRangesRemoved(blocks: List<Block>) {
blocks.forEach(this::onRangeRemoved)
}
private fun Listener.onRangesAdded(blocks: List<Block>) {
blocks.forEach(this::onRangeAdded)
}
}
private class BlockGroupsProcessor(private val text1: CharSequence,
private val lineOffsets1: LineOffsets) {
fun processMergeableGroups(blocks: List<Block>,
processGroup: (group: List<Block>) -> Unit) {
if (blocks.isEmpty()) return
var i = 0
var blockStart = 0
while (i < blocks.size - 1) {
if (!isWhitespaceOnlySeparated(blocks[i], blocks[i + 1])) {
processGroup(blocks.subList(blockStart, i + 1))
blockStart = i + 1
}
i += 1
}
processGroup(blocks.subList(blockStart, i + 1))
}
private fun isWhitespaceOnlySeparated(block1: Block, block2: Block): Boolean {
val range1 = DiffUtil.getLinesRange(lineOffsets1, block1.range.start1, block1.range.end1, false)
val range2 = DiffUtil.getLinesRange(lineOffsets1, block2.range.start1, block2.range.end1, false)
val start = range1.endOffset
val end = range2.startOffset
return trimStart(text1, start, end) == end
}
}
private class MergingBlockProcessor(private val dispatcher: EventDispatcher<Listener>) {
fun processMergedBlocks(group: List<Block>,
processBlock: (original: List<Block>, merged: Block) -> Unit) {
assert(!group.isEmpty())
val originalGroup = mutableListOf<Block>()
var merged: Block? = null
for (block in group) {
if (merged == null) {
originalGroup.add(block)
merged = block
}
else {
val newMerged = mergeBlocks(merged, block)
if (newMerged != null) {
originalGroup.add(block)
merged = newMerged
}
else {
processBlock(originalGroup, merged)
originalGroup.clear()
originalGroup.add(block)
merged = block
}
}
}
processBlock(originalGroup, merged!!)
}
private fun mergeBlocks(block1: Block, block2: Block): Block? {
val isDirty = block1.isDirty || block2.isDirty
val isTooBig = block1.isTooBig || block2.isTooBig
val range = Range(block1.range.start1, block2.range.end1,
block1.range.start2, block2.range.end2)
val merged = Block(range, isDirty, isTooBig)
for (listener in dispatcher.listeners) {
if (!listener.onRangesMerged(block1, block2, merged)) {
return null // merging vetoed
}
}
return merged
}
} | apache-2.0 | 07e99f88d730bb3ddf736bafdc08f4fd | 31.239726 | 117 | 0.647923 | 4.480565 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/activity/VectorSettingsActivity.kt | 2 | 5231 | /*
* Copyright 2018 New Vector 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 im.vector.activity
import android.content.Context
import android.content.Intent
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import im.vector.Matrix
import im.vector.R
import im.vector.fragments.VectorSettingsAdvancedNotificationPreferenceFragment
import im.vector.fragments.VectorSettingsFragmentInteractionListener
import im.vector.fragments.VectorSettingsNotificationsTroubleshootFragment
import im.vector.fragments.VectorSettingsPreferencesFragment
import im.vector.fragments.discovery.VectorSettingsDiscoveryFragment
import im.vector.util.PreferencesManager
/**
* Displays the client settings.
*/
class VectorSettingsActivity : MXCActionBarActivity(),
PreferenceFragmentCompat.OnPreferenceStartFragmentCallback,
androidx.fragment.app.FragmentManager.OnBackStackChangedListener,
VectorSettingsFragmentInteractionListener {
private lateinit var vectorSettingsPreferencesFragment: VectorSettingsPreferencesFragment
override fun getLayoutRes() = R.layout.activity_vector_settings
override fun getTitleRes() = R.string.title_activity_settings
private var keyToHighlight: String? = null
override fun initUiAndData() {
configureToolbar()
var session = getSession(intent)
if (null == session) {
session = Matrix.getInstance(this).defaultSession
}
if (session == null) {
finish()
return
}
if (isFirstCreation()) {
vectorSettingsPreferencesFragment = VectorSettingsPreferencesFragment.newInstance(session.myUserId)
// display the fragment
supportFragmentManager.beginTransaction()
.replace(R.id.vector_settings_page, vectorSettingsPreferencesFragment, FRAGMENT_TAG)
.commit()
} else {
vectorSettingsPreferencesFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as VectorSettingsPreferencesFragment
}
supportFragmentManager.addOnBackStackChangedListener(this)
}
override fun onDestroy() {
supportFragmentManager.removeOnBackStackChangedListener(this)
super.onDestroy()
}
override fun onBackStackChanged() {
if (0 == supportFragmentManager.backStackEntryCount) {
supportActionBar?.title = getString(getTitleRes())
}
}
override fun onPreferenceStartFragment(caller: PreferenceFragmentCompat, pref: Preference): Boolean {
var session = getSession(intent)
if (null == session) {
session = Matrix.getInstance(this).defaultSession
}
if (session == null) {
return false
}
val oFragment = when (pref.key) {
PreferencesManager.SETTINGS_NOTIFICATION_TROUBLESHOOT_PREFERENCE_KEY ->
VectorSettingsNotificationsTroubleshootFragment.newInstance(session.myUserId)
PreferencesManager.SETTINGS_NOTIFICATION_ADVANCED_PREFERENCE_KEY ->
VectorSettingsAdvancedNotificationPreferenceFragment.newInstance(session.myUserId)
PreferencesManager.SETTINGS_DISCOVERY_PREFERENCE_KEY,
PreferencesManager.SETTINGS_IDENTITY_SERVER_PREFERENCE_KEY ->
VectorSettingsDiscoveryFragment.newInstance(session.myUserId)
else -> null
}
if (oFragment != null) {
oFragment.setTargetFragment(caller, 0)
// Replace the existing Fragment with the new Fragment
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom,
R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom)
.replace(R.id.vector_settings_page, oFragment, pref?.title.toString())
.addToBackStack(null)
.commit()
return true
}
return false
}
override fun requestHighlightPreferenceKeyOnResume(key: String?) {
keyToHighlight = key
}
override fun requestedKeyToHighlight(): String? {
return keyToHighlight
}
companion object {
@JvmStatic
fun getIntent(context: Context, userId: String) = Intent(context, VectorSettingsActivity::class.java)
.apply {
putExtra(MXCActionBarActivity.EXTRA_MATRIX_ID, userId)
}
private const val FRAGMENT_TAG = "VectorSettingsPreferencesFragment"
}
}
| apache-2.0 | 3f3291e8c9945e16aabf5fc0597d7718 | 35.838028 | 139 | 0.681132 | 5.38723 | false | false | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/processor/src/test/kotlin/com/android/tools/build/jetifier/processor/transform/resource/XmlResourcesTransformerTest.kt | 1 | 16910 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.processor.transform.resource
import com.android.tools.build.jetifier.core.PackageMap
import com.android.tools.build.jetifier.core.config.Config
import com.android.tools.build.jetifier.core.rule.RewriteRule
import com.android.tools.build.jetifier.core.rule.RewriteRulesMap
import com.android.tools.build.jetifier.core.type.JavaType
import com.android.tools.build.jetifier.core.type.TypesMap
import com.android.tools.build.jetifier.processor.archive.ArchiveFile
import com.android.tools.build.jetifier.processor.transform.TransformationContext
import com.google.common.truth.Truth
import org.junit.Test
import java.nio.charset.Charset
import java.nio.file.Paths
class XmlResourcesTransformerTest {
@Test fun layout_noRule_noChange() {
testRewriteToTheSame(
givenAndExpectedXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
prefixes = setOf("android/support/v7/"),
map = mapOf(),
errorsExpected = true
)
}
@Test fun layout_notApplicablePrefix_shouldStillWork() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
expectedXml =
"<android.test.pref.Preference>\n" +
"</android.test.pref.Preference>",
prefixes = setOf("android/support/v14/"),
typesMap = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_notApplicablePrefix2_noChange() {
testRewriteToTheSame(
givenAndExpectedXml =
"<my.android.support.v7.preference.Preference>\n" +
"</my.android.support.v7.preference.Preference>",
prefixes = setOf("android/support/v7/"),
map = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_notApplicableRule_noChange() {
testRewriteToTheSame(
givenAndExpectedXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
prefixes = setOf("android/support/"),
map = mapOf(
"android/support2/v7/preference/Preference" to "android/test/pref/Preference"
),
errorsExpected = true
)
}
@Test fun layout_onePrefix_oneRule_oneRewrite() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference/>",
expectedXml =
"<android.test.pref.Preference/>",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_onePrefix_oneRule_attribute_oneRewrite() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference \n" +
" someAttribute=\"android.support.v7.preference.Preference\"/>",
expectedXml =
"<android.test.pref.Preference \n" +
" someAttribute=\"android.test.pref.Preference\"/>",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_onePrefix_oneRule_twoRewrites() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
expectedXml =
"<android.test.pref.Preference>\n" +
"</android.test.pref.Preference>",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_onePrefix_oneRule_viewTag_simple() {
testRewrite(
givenXml =
"<view class=\"android.support.v7.preference.Preference\">",
expectedXml =
"<view class=\"android.test.pref.Preference\">",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_onePrefix_oneRule_viewInText() {
testRewriteToTheSame(
givenAndExpectedXml =
"<test attribute=\"view\" class=\"something.Else\">",
prefixes = setOf("android/support/"),
map = mapOf(
"android/support/v7/preference/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun application_appComponentFactory() {
testRewrite(
givenXml =
"<application android:appComponentFactory=\"android.support.v7.Preference\" />",
expectedXml =
"<application android:appComponentFactory=\"android.test.pref.Preference\" />",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/Preference" to "android/test/pref/Preference"
)
)
}
@Test fun layout_onePrefix_oneRule_identity() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
expectedXml =
"<android.support.v7.preference.Preference>\n" +
"</android.support.v7.preference.Preference>",
prefixes = setOf("android/support/"),
typesMap = mapOf(
"android/support/v7/preference/Preference"
to "android/support/v7/preference/Preference"
)
)
}
@Test fun layout_twoPrefixes_threeRules_ignoreRule_multipleRewrites() {
testRewrite(
givenXml =
"<android.support.v7.preference.Preference>\n" +
" <android.support.v14.preference.DialogPreference" +
" someAttribute=\"someValue\"/>\n" +
" <android.support.v14.preference.DialogPreference" +
" someAttribute=\"someValue2\"/>\n" +
" <!-- This one should be ignored --> \n" +
" <android.support.v21.preference.DialogPreference" +
" someAttribute=\"someValue2\"/>\n" +
"</android.support.v7.preference.Preference>\n" +
"\n" +
"<android.support.v7.preference.ListPreference/>",
expectedXml =
"<android.test.pref.Preference>\n" +
" <android.test14.pref.DialogPreference" +
" someAttribute=\"someValue\"/>\n" +
" <android.test14.pref.DialogPreference" +
" someAttribute=\"someValue2\"/>\n" +
" <!-- This one should be ignored --> \n" +
" <android.support.v21.preference.DialogPreference" +
" someAttribute=\"someValue2\"/>\n" +
"</android.test.pref.Preference>\n" +
"\n" +
"<android.test.pref.ListPref/>",
prefixes = setOf(
"android/support/v7/",
"android/support/v14/"
),
rulesMap = RewriteRulesMap(
RewriteRule(from = "android/support/v21/(.*)", to = "ignore")),
typesMap = mapOf(
"android/support/v7/preference/ListPreference"
to "android/test/pref/ListPref",
"android/support/v7/preference/Preference"
to "android/test/pref/Preference",
"android/support/v14/preference/DialogPreference"
to "android/test14/pref/DialogPreference"
)
)
}
@Test fun manifestFile_packageRewrite() {
testRewrite(
givenXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"android.support.v7.preference\">\n" +
" <uses-sdk android:minSdkVersion=\"14\"/>\n" +
"</manifest>",
expectedXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"androidx.preference\">\n" +
" <uses-sdk android:minSdkVersion=\"14\"/>\n" +
"</manifest>",
prefixes = setOf(
"android/support"
),
typesMap = mapOf(
),
packageMap = PackageMap(listOf(
PackageMap.PackageRule(
from = "android/support/v7/preference",
to = "androidx/preference")
)),
rewritingSupportLib = true
)
}
@Test fun manifestFile_packageRewrite_prefixMismatchShouldNotAffectRewrite() {
testRewrite(
givenXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"android.support.v7.preference\">\n" +
" <uses-sdk android:minSdkVersion=\"14\"/>\n" +
"</manifest>",
expectedXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"androidx.preference\">\n" +
" <uses-sdk android:minSdkVersion=\"14\"/>\n" +
"</manifest>",
prefixes = setOf(
"android/something/else"
),
typesMap = mapOf(
),
packageMap = PackageMap(listOf(
PackageMap.PackageRule(
from = "android/support/v7/preference",
to = "androidx/preference")
)),
rewritingSupportLib = true
)
}
@Test fun manifestFile_packageRewrite_shouldIgnore() {
testRewrite(
givenXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"android.support.test\">\n" +
"</manifest>",
expectedXml =
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" package=\"android.support.test\">\n" +
"</manifest>",
prefixes = setOf(
"android/support/"
),
rulesMap = RewriteRulesMap(
RewriteRule("android/support/test/(.*)", "ignore")
),
packageMap = PackageMap.EMPTY,
rewritingSupportLib = true
)
}
@Test fun generic_sample_provider() {
testRewrite(
givenXml =
"<provider\n" +
" android:authorities=\"support.Something\"\n" +
" android:name=\"support.Something\">\n" +
" <meta-data android:name=\"support.Something\">\n" +
"</provider>",
expectedXml =
"<provider\n" +
" android:authorities=\"test.Something\"\n" +
" android:name=\"test.Something\">\n" +
" <meta-data android:name=\"test.Something\">\n" +
"</provider>",
prefixes = setOf("support/"),
typesMap = mapOf(
"support/Something" to "test/Something"
)
)
}
@Test fun generic_sample_intent() {
testRewrite(
givenXml =
"<activity android:name=\"some\" android:configChanges=\"orientation\">\n" +
" <intent-filter>\n" +
" <action android:name=\"support.Something\" />\n" +
" </intent-filter>\n" +
"</activity>",
expectedXml =
"<activity android:name=\"some\" android:configChanges=\"orientation\">\n" +
" <intent-filter>\n" +
" <action android:name=\"test.Something\" />\n" +
" </intent-filter>\n" +
"</activity>",
prefixes = setOf("support/"),
typesMap = mapOf(
"support/Something" to "test/Something"
)
)
}
@Test fun generic_sample_style() {
testRewrite(
givenXml =
"<style name=\"AppCompat\" parent=\"Platform.AppCompat\">\n" +
" <item name=\"viewInflaterClass\">support.Something</item>\n" +
"</style>",
expectedXml =
"<style name=\"AppCompat\" parent=\"Platform.AppCompat\">\n" +
" <item name=\"viewInflaterClass\">test.Something</item>\n" +
"</style>",
prefixes = setOf("support/"),
typesMap = mapOf(
"support/Something" to "test/Something"
)
)
}
@Test fun generic_sample_transition() {
testRewrite(
givenXml =
"<transition\n" +
" xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" xmlns:lb=\"http://schemas.android.com/apk/res-auto\"\n" +
" class=\"support.Something\"\n" +
" lb:lb_slideEdge=\"top\" >\n" +
"</transition>",
expectedXml =
"<transition\n" +
" xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
" xmlns:lb=\"http://schemas.android.com/apk/res-auto\"\n" +
" class=\"test.Something\"\n" +
" lb:lb_slideEdge=\"top\" >\n" +
"</transition>",
prefixes = setOf("support/"),
typesMap = mapOf(
"support/Something" to "test/Something"
)
)
}
private fun testRewriteToTheSame(
givenAndExpectedXml: String,
prefixes: Set<String>,
map: Map<String, String>,
errorsExpected: Boolean = false
) {
testRewrite(givenAndExpectedXml, givenAndExpectedXml, prefixes, map,
errorsExpected = errorsExpected)
}
private fun testRewrite(
givenXml: String,
expectedXml: String,
prefixes: Set<String>,
typesMap: Map<String, String> = emptyMap(),
rulesMap: RewriteRulesMap = RewriteRulesMap.EMPTY,
packageMap: PackageMap = PackageMap.EMPTY,
rewritingSupportLib: Boolean = false,
errorsExpected: Boolean = false
) {
val given =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"$givenXml\n"
val expected =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"$expectedXml\n"
val typeMap = TypesMap(typesMap.map { JavaType(it.key) to JavaType(it.value) }.toMap())
val config = Config.fromOptional(
restrictToPackagePrefixes = prefixes,
rulesMap = rulesMap,
typesMap = typeMap,
packageMap = packageMap
)
val context = TransformationContext(
config,
rewritingSupportLib = rewritingSupportLib,
useFallbackIfTypeIsMissing = false)
val processor = XmlResourcesTransformer(context)
val fileName = Paths.get("random.xml")
val file = ArchiveFile(fileName, given.toByteArray())
processor.runTransform(file)
val strResult = file.data.toString(Charset.defaultCharset())
Truth.assertThat(strResult).isEqualTo(expected)
if (errorsExpected) {
Truth.assertThat(context.errorsTotal()).isAtLeast(1)
} else {
Truth.assertThat(context.errorsTotal()).isEqualTo(0)
}
}
}
| apache-2.0 | 4124b005312554426597dd187e3e4aa0 | 38.053118 | 96 | 0.533353 | 4.567801 | false | true | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/core/src/test/kotlin/com/android/tools/build/jetifier/core/rule/RewriteRuleTest.kt | 1 | 3228 | /*
* Copyright 2017 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 android.support.tools.jetifier.processor.transform
import com.android.tools.build.jetifier.core.rule.RewriteRule
import com.android.tools.build.jetifier.core.type.JavaType
import com.google.common.truth.Truth
import org.junit.Test
class RewriteRuleTest {
@Test fun noRegEx_shouldRewrite() {
RuleTester
.testThatRule("A/B", "A/C")
.rewritesType("A/B")
.into("A/C")
}
@Test fun noRegEx_underscore_shouldRewrite() {
RuleTester
.testThatRule("A/B_B", "A/C")
.rewritesType("A/B_B")
.into("A/C")
}
@Test fun groupRegEx_shouldRewrite() {
RuleTester
.testThatRule("A/B/(.*)", "A/{0}")
.rewritesType("A/B/C/D")
.into("A/C/D")
}
@Test fun groupRegEx__innerClass_shouldRewrite() {
RuleTester
.testThatRule("A/B/(.*)", "A/{0}")
.rewritesType("A/B/C\$D")
.into("A/C\$D")
}
@Test fun fieldRule_innerClass_groupRegEx_shouldRewrite() {
RuleTester
.testThatRule("A/B$(.*)", "A/C\${0}")
.rewritesType("A/B\$D")
.into("A/C\$D")
}
@Test fun typeRewrite_ignore() {
RuleTester
.testThatRule("A/B", "ignore")
.rewritesType("A/B")
.isIgnored()
}
@Test fun typeRewrite_ignoreInPreprocessor() {
RuleTester
.testThatRule("A/B", "ignoreInPreprocessorOnly")
.rewritesType("A/B")
.isIgnored()
}
object RuleTester {
fun testThatRule(from: String, to: String) = RuleTesterStep1(from, to)
class RuleTesterStep1(val from: String, val to: String) {
fun rewritesType(inputType: String) = RuleTesterFinalTypeStep(from, to, inputType)
}
class RuleTesterFinalTypeStep(
val fromType: String,
val toType: String,
val inputType: String
) {
fun into(expectedResult: String) {
val fieldRule = RewriteRule(fromType, toType)
val result = fieldRule.apply(JavaType(inputType))
Truth.assertThat(result).isNotNull()
Truth.assertThat(result.result!!.fullName).isEqualTo(expectedResult)
}
fun isIgnored() {
val fieldRule = RewriteRule(fromType, toType)
val result = fieldRule.apply(JavaType(inputType))
Truth.assertThat(result).isNotNull()
Truth.assertThat(result.isIgnored).isTrue()
}
}
}
}
| apache-2.0 | 9bb369b2ae6e9d4b6f7534936381329f | 28.888889 | 94 | 0.58767 | 4.055276 | false | true | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/dynarek2/D2Gen.kt | 1 | 1910 | package com.soywiz.dynarek2
import kotlin.RuntimeException
import kotlin.math.*
import kotlin.reflect.*
expect fun D2Context.registerDefaultFunctions(): Unit
class D2FuncName(val name: String)
/*
class D2Context {
val funcs = LinkedHashMap<KFunction<*>, Long>()
init {
registerDefaultFunctions()
}
fun getFunc(name: KFunction<*>): Long = funcs[name] ?: error("Can't find function $name")
fun registerFunc(name: KFunction<*>, address: Long) {
funcs[name] = address
}
}
*/
class D2FuncInfo(val address: Long, val rettype: D2TYPE<*>, val args: Array<out D2TYPE<*>>)
class D2Context {
val funcs = LinkedHashMap<String, D2FuncInfo>()
init {
registerDefaultFunctions()
}
fun getFunc(name: KFunction<*>): D2FuncInfo = funcs[name.name] ?: error("Can't find function $name")
fun _registerFunc(name: KFunction<*>, address: Long, rettype: D2TYPE<*>, vararg args: D2TYPE<*>) {
funcs[name.name] = D2FuncInfo(address, rettype, args)
}
val KClass<*>.d2type get() = when (this) {
Float::class -> D2FLOAT
Int::class -> D2INT
else -> D2INT
}
}
class MyClass {
var demo = 7
override fun toString(): String {
return "MyClass(demo=$demo)"
}
}
fun dyna_getDemo(cl: MyClass) = cl.demo
fun iprint(v: Int): Int {
println("iprint:$v")
return 0
}
fun isqrt(v: Int): Int {
val res = sqrt(v.toDouble()).toInt()
//println("isqrt($v)=$res")
return res
}
class MyDemoException : RuntimeException()
fun demo_ithrow(): Int {
throw MyDemoException()
}
fun isub(a: Int, b: Int): Int {
val res = a - b
//println("isub($a,$b)=$res")
return res
}
fun fsub(a: Float, b: Float): Float {
val res = a - b
//println("isub($a,$b)=$res")
return res
}
expect fun D2Func.generate(context: D2Context, name: String? = null, debug: Boolean = false): D2Result
| mit | a601078bb8706184168ea90b32cb6814 | 20.954023 | 104 | 0.626702 | 3.327526 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlMultiPolygonGene.kt | 1 | 5089 | package org.evomaster.core.search.gene.sql.geometric
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.search.gene.*
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.collection.ArrayGene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Represents a collection of polygons.
* It is intended to hold values for Column types MULTIPOLYGON
* of databases H2 and MySQL.
*/
class SqlMultiPolygonGene(
name: String,
/**
* The database type of the source column for this gene
*/
val databaseType: DatabaseType = DatabaseType.H2,
val polygons: ArrayGene<SqlPolygonGene> = ArrayGene(
name = "polygons",
minSize = 1,
template = SqlPolygonGene("polygon",
minLengthOfPolygonRing = 3,
databaseType = databaseType))
) : CompositeFixedGene(name, mutableListOf(polygons)) {
companion object {
val log: Logger = LoggerFactory.getLogger(SqlMultiPolygonGene::class.java)
}
init {
if (databaseType!=DatabaseType.H2 && databaseType!=DatabaseType.MYSQL) {
IllegalArgumentException("Cannot create a SqlMultiPolygonGene with database type ${databaseType}")
}
}
override fun copyContent(): Gene = SqlMultiPolygonGene(
name,
databaseType = this.databaseType,
polygons = polygons.copy() as ArrayGene<SqlPolygonGene>
)
override fun isLocallyValid() = polygons.isLocallyValid()
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
polygons.randomize(randomness, tryToForceNewValue)
}
override fun getValueAsPrintableString(
previousGenes: List<Gene>,
mode: GeneUtils.EscapeMode?,
targetFormat: OutputFormat?,
extraCheck: Boolean
): String {
return when (databaseType) {
DatabaseType.H2 -> "\"${getValueAsRawString()}\""
DatabaseType.MYSQL -> getValueAsRawString()
else -> throw IllegalArgumentException("Unsupported SqlMultiPolygonGene.getValueAsPrintableString() for $databaseType")
}
}
override fun getValueAsRawString(): String {
return when (databaseType) {
DatabaseType.H2 -> {
if (polygons.getViewOfElements().isEmpty()) "MULTIPOLYGON EMPTY"
else
"MULTIPOLYGON(${
polygons.getViewOfElements().joinToString(", ") { polygon ->
"((${
polygon.points.getViewOfElements().joinToString(", ") { point ->
point.x.getValueAsRawString() +
" " + point.y.getValueAsRawString()
} + ", " + polygon.points.getViewOfElements()[0].x.getValueAsRawString() +
" " + polygon.points.getViewOfElements()[0].y.getValueAsRawString()
}))"
}
})"
}
DatabaseType.MYSQL -> {
"MULTIPOLYGON(${polygons.getViewOfElements().joinToString(", "){ it.getValueAsRawString() }})"
}
else -> throw IllegalArgumentException("Unsupported SqlMultiPointGene.getValueAsRawString() for $databaseType")
}
}
override fun copyValueFrom(other: Gene) {
if (other !is SqlMultiPolygonGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
this.polygons.copyValueFrom(other.polygons)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is SqlMultiPolygonGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.polygons.containsSameValueAs(other.polygons)
}
override fun bindValueBasedOn(gene: Gene): Boolean {
return when {
gene is SqlMultiPolygonGene -> {
polygons.bindValueBasedOn(gene.polygons)
}
else -> {
LoggingUtil.uniqueWarn(log, "cannot bind PathGene with ${gene::class.java.simpleName}")
false
}
}
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | lgpl-3.0 | 166b9c495a74cd4bf5237140a7d1310d | 36.985075 | 131 | 0.623895 | 5.466165 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | core/commonMain/src/implementations/persistentOrderedSet/PersistentOrderedSetBuilder.kt | 1 | 2920 | /*
* Copyright 2016-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.txt file.
*/
package kotlinx.collections.immutable.implementations.persistentOrderedSet
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.internal.EndOfChain
import kotlinx.collections.immutable.internal.assert
internal class PersistentOrderedSetBuilder<E>(private var set: PersistentOrderedSet<E>) : AbstractMutableSet<E>(), PersistentSet.Builder<E> {
internal var firstElement = set.firstElement
private var lastElement = set.lastElement
internal val hashMapBuilder = set.hashMap.builder()
override val size: Int
get() = hashMapBuilder.size
override fun build(): PersistentSet<E> {
val newMap = hashMapBuilder.build()
set = if (newMap === set.hashMap) {
assert(firstElement === set.firstElement)
assert(lastElement === set.lastElement)
set
} else {
PersistentOrderedSet(firstElement, lastElement, newMap)
}
return set
}
override fun contains(element: E): Boolean {
return hashMapBuilder.containsKey(element)
}
override fun add(element: E): Boolean {
if (hashMapBuilder.containsKey(element)) {
return false
}
if (isEmpty()) {
firstElement = element
lastElement = element
hashMapBuilder[element] = Links()
return true
}
val lastLinks = hashMapBuilder[lastElement]!!
// assert(!lastLinks.hasNext)
@Suppress("UNCHECKED_CAST")
hashMapBuilder[lastElement as E] = lastLinks.withNext(element)
hashMapBuilder[element] = Links(previous = lastElement)
lastElement = element
return true
}
override fun remove(element: E): Boolean {
val links = hashMapBuilder.remove(element) ?: return false
if (links.hasPrevious) {
val previousLinks = hashMapBuilder[links.previous]!!
// assert(previousLinks.next == element)
@Suppress("UNCHECKED_CAST")
hashMapBuilder[links.previous as E] = previousLinks.withNext(links.next)
} else {
firstElement = links.next
}
if (links.hasNext) {
val nextLinks = hashMapBuilder[links.next]!!
// assert(nextLinks.previous == element)
@Suppress("UNCHECKED_CAST")
hashMapBuilder[links.next as E] = nextLinks.withPrevious(links.previous)
} else {
lastElement = links.previous
}
return true
}
override fun clear() {
hashMapBuilder.clear()
firstElement = EndOfChain
lastElement = EndOfChain
}
override fun iterator(): MutableIterator<E> {
return PersistentOrderedSetMutableIterator(this)
}
} | apache-2.0 | 2817ba69da5cc55a71e055a09230f270 | 31.820225 | 141 | 0.638699 | 5.017182 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/versions/test2.gradle.kt | 1 | 2730 | @file:Suppress("UNUSED_PARAMETER")
fun compile(a : Any) {}
fun compile(group: String, name: String, version: String? = null) {}
fun dependencies(a: Any) {}
val gdxVersion = "1.9.0"
val gdx = "1.9.0"
val visUiVersion = ""
val ktxCollectionsVersion = ""
val websocketSerializationVersion = ""
val websocketVersion = ""
val overlap2dVersion = ""
val ktxVisStyleVersion = ""
val noise4jVersion = ""
val ktxScene2DVersion = ""
val bladeInkVersion = ""
val jaciVersion = ""
val utilsBox2dVersion = ""
fun f() {
dependencies {
compile(<warning descr="A newer version of LibGDX is available (version 1.9.5)">"com.badlogicgames.gdx:gdx:1.9.2"</warning>)
compile<warning descr="A newer version of LibGDX is available (version 1.9.5)">(group = "com.badlogicgames.gdx", name = "gdx", version = "1.9.4")</warning>
compile("com.badlogicgames.gdx:gdx:1.9.8")
compile(group = "com.badlogicgames.gdx", name = "gdx", version = "1.9.8")
compile("com.underwaterapps.overlap2druntime:overlap2d-runtime-libgdx:0.1.1")
compile(<warning descr="A newer version of Overlap2D is available (version 0.1.1)">"com.underwaterapps.overlap2druntime:overlap2d-runtime-libgdx:0.1.0"</warning>)
compile(group = "com.underwaterapps.overlap2druntime", name = "overlap2d-runtime-libgdx", version = "0.1.1")
compile<warning descr="A newer version of Overlap2D is available (version 0.1.1)">(group = "com.underwaterapps.overlap2druntime", name = "overlap2d-runtime-libgdx", version = "0.1.0")</warning>
compile<warning descr="A newer version of Overlap2D is available (version 0.1.1)">(group = "com.underwaterapps.overlap2druntime", name = "overlap2d-runtime-libgdx")</warning>
compile(<warning>"com.badlogicgames.gdx:gdx:$gdxVersion"</warning>)
compile(<warning>"com.badlogicgames.gdx:gdx:$gdx"</warning>)
compile(<warning descr="A newer version of VisUI is available (version 1.2.5)">"com.kotcrab.vis:vis-ui:$visUiVersion"</warning>)
compile("com.github.czyzby:ktx-collections:$ktxCollectionsVersion")
compile("com.github.czyzby:gdx-websocket-serialization:$websocketSerializationVersion")
compile("com.github.czyzby:gdx-websocket:$websocketVersion")
compile(<warning descr="A newer version of Overlap2D is available (version 0.1.1)">"com.underwaterapps.overlap2druntime:overlap2d-runtime-libgdx:$overlap2dVersion"</warning>)
compile("com.github.czyzby:ktx-vis-style:$ktxVisStyleVersion")
compile("com.github.czyzby:noise4j:$noise4jVersion")
compile("com.github.czyzby:ktx-scene2d:$ktxScene2DVersion")
compile("com.bladecoder.ink:blade-ink:$bladeInkVersion")
compile("com.github.ykrasik:jaci-libgdx-cli-java:$jaciVersion")
}
}
| apache-2.0 | b072e2e8f845233fc7a80de7ab0b269e | 53.6 | 199 | 0.720147 | 3.333333 | false | false | false | false |
ibinti/intellij-community | platform/configuration-store-impl/src/ComponentStoreImpl.kt | 4 | 22761 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.configurationStore.StateStorageManager.ExternalizationSession
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.project.isDirectoryBased
import com.intellij.ui.AppUIUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.MessageBus
import com.intellij.util.xmlb.JDOMXIncluder
import gnu.trove.THashMap
import io.netty.util.internal.SystemPropertyUtil
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
import java.util.*
import com.intellij.openapi.util.Pair as JBPair
internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java)
internal val deprecatedComparator = Comparator<Storage> { o1, o2 ->
val w1 = if (o1.deprecated) 1 else 0
val w2 = if (o2.deprecated) 1 else 0
w1 - w2
}
abstract class ComponentStoreImpl : IComponentStore {
private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>())
private val settingsSavingComponents = com.intellij.util.containers.ContainerUtil.createLockFreeCopyOnWriteList<SettingsSavingComponent>();
internal open val project: Project?
get() = null
open val loadPolicy: StateLoadPolicy
get() = StateLoadPolicy.LOAD
abstract val storageManager: StateStorageManager
override final fun getStateStorageManager() = storageManager
override final fun initComponent(component: Any, service: Boolean) {
if (component is SettingsSavingComponent) {
settingsSavingComponents.add(component)
}
var componentName = ""
try {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
val stateSpec = StoreUtil.getStateSpec(component)
componentName = stateSpec.name
val info = doAddComponent(componentName, component)
if (initComponent(stateSpec, component, info, null, false) && service) {
// if not service, so, component manager will check it later for all components
project?.let {
val app = ApplicationManager.getApplication()
if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) {
notifyUnknownMacros(this, it, componentName)
}
}
}
}
else if (component is JDOMExternalizable) {
componentName = ComponentManagerImpl.getComponentName(component)
@Suppress("DEPRECATION")
initJdomExternalizable(component, componentName)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Cannot init ${componentName} component state", e)
return
}
}
override fun save(readonlyFiles: MutableList<JBPair<StateStorage.SaveSession, VirtualFile>>) {
var errors: MutableList<Throwable>? = null
// component state uses scheme manager in an ipr project, so, we must save it before
val isIprProject = project?.let { !it.isDirectoryBased } ?: false
if (isIprProject) {
settingsSavingComponents.firstOrNull { it is SchemeManagerFactoryBase }?.let {
try {
it.save()
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
}
val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true)
val externalizationSession = if (components.isEmpty()) null else storageManager.startExternalization()
if (externalizationSession != null) {
val names = ArrayUtilRt.toStringArray(components.keys)
Arrays.sort(names)
val timeLogPrefix = "Saving"
val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null
for (name in names) {
val start = if (timeLog == null) 0 else System.currentTimeMillis()
try {
val info = components.get(name)!!
var currentModificationCount = -1L
if (info.isModificationTrackingSupported) {
currentModificationCount = info.currentModificationCount
if (currentModificationCount == info.lastModificationCount) {
LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" }
if (isUseModificationCount) {
continue
}
}
}
commitComponent(externalizationSession, info.component, name)
info.updateModificationCount(currentModificationCount)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(Exception("Cannot get $name component state", e))
}
timeLog?.let {
val duration = System.currentTimeMillis() - start
if (duration > 10) {
it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(((duration % 60000) / 1000)).append("sec")
}
}
}
if (timeLog != null && timeLog.length > timeLogPrefix.length) {
LOG.debug(timeLog.toString())
}
}
for (settingsSavingComponent in settingsSavingComponents) {
try {
if (!isIprProject || settingsSavingComponent !is SchemeManagerFactoryBase) {
settingsSavingComponent.save()
}
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
if (externalizationSession != null) {
errors = doSave(externalizationSession.createSaveSessions(), readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
override @TestOnly fun saveApplicationComponent(component: PersistentStateComponent<*>) {
val externalizationSession = storageManager.startExternalization() ?: return
commitComponent(externalizationSession, component, null)
val sessions = externalizationSession.createSaveSessions()
if (sessions.isEmpty()) {
return
}
val state = StoreUtil.getStateSpec(component.javaClass) ?: throw AssertionError("${component.javaClass} doesn't have @State annotation and doesn't implement ExportableApplicationComponent")
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(state.storages).path)).toAbsolutePath().toString()
runUndoTransparentWriteAction {
try {
VfsRootAccess.allowRootAccess(absolutePath)
CompoundRuntimeException.throwIfNotEmpty(doSave(sessions))
}
finally {
VfsRootAccess.disallowRootAccess(absolutePath)
}
}
}
private fun commitComponent(session: ExternalizationSession, component: Any, componentName: String?) {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
component.state?.let {
val stateSpec = StoreUtil.getStateSpec(component)
session.setState(getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE), component, componentName ?: stateSpec.name, it)
}
}
else if (component is JDOMExternalizable) {
session.setStateInOldStorage(component, componentName ?: ComponentManagerImpl.getComponentName(component), component)
}
}
protected open fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>> = arrayListOf(), prevErrors: MutableList<Throwable>? = null): MutableList<Throwable>? {
var errors = prevErrors
for (session in saveSessions) {
errors = executeSave(session, readonlyFiles, prevErrors)
}
return errors
}
private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? {
doAddComponent(componentName, component)
if (loadPolicy != StateLoadPolicy.LOAD) {
return null
}
try {
getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) }
}
catch (e: Throwable) {
LOG.error(e)
}
val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName, Element::class.java, null, false) ?: return null
try {
component.readExternal(element)
}
catch (e: InvalidDataException) {
LOG.error(e)
return null
}
return componentName
}
private fun doAddComponent(name: String, component: Any): ComponentInfo {
val newInfo = when (component) {
is ModificationTracker -> ComponentWithModificationTrackerInfo(component)
is PersistentStateComponentWithModificationTracker<*> -> ComponentWithStateModificationTrackerInfo(component)
else -> ComponentInfoImpl(component)
}
val existing = components.put(name, newInfo)
if (existing != null && existing.component !== component) {
components.put(name, existing)
LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}")
return existing
}
return newInfo
}
private fun <T: Any> initComponent(stateSpec: State, component: PersistentStateComponent<T>, info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
if (loadPolicy == StateLoadPolicy.NOT_LOAD) {
return false
}
if (doInitComponent(stateSpec, component, changedStorages, reloadData)) {
// if component was initialized, update lastModificationCount
info.updateModificationCount()
return true
}
return false
}
private fun <T: Any> doInitComponent(stateSpec: State, component: PersistentStateComponent<T>, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
val name = stateSpec.name
val stateClass = ComponentSerializationUtil.getStateClass<T>(component.javaClass)
if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) {
LOG.error("$name has default state, but not marked to load it")
}
val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null
if (loadPolicy == StateLoadPolicy.LOAD) {
val storageChooser = component as? StateStorageChooserEx
for (storageSpec in getStorageSpecs(component, stateSpec, StateStorageOperation.READ)) {
if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
val stateGetter = if (isUseLoadedStateAsExisting(storage, name)) (storage as? StorageBaseEx<*>)?.createGetSession(component, name, stateClass) else null
var state = if (stateGetter == null) storage.getState(component, name, stateClass, defaultState, reloadData) else stateGetter.getState(defaultState)
if (state == null) {
if (changedStorages != null && changedStorages.contains(storage)) {
// state will be null if file deleted
// we must create empty (initial) state to reinit component
state = deserializeState(Element("state"), stateClass, null)!!
}
else {
continue
}
}
try {
component.loadState(state)
}
finally {
stateGetter?.close()
}
return true
}
}
// we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists)
if (defaultState == null) {
component.noStateLoaded()
}
else {
component.loadState(defaultState)
}
return true
}
// todo "ProjectModuleManager" investigate why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest
// todo fix FacetManager
// use.loaded.state.as.existing used in upsource
private fun isUseLoadedStateAsExisting(storage: StateStorage, name: String): Boolean {
return isUseLoadedStateAsExisting(storage) &&
name != "AntConfiguration" &&
name != "ProjectModuleManager" &&
name != "FacetManager" &&
name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ &&
name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ &&
SystemPropertyUtil.getBoolean("use.loaded.state.as.existing", true)
}
protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED
protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null
private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? {
val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null
try {
val documentElement = JDOMXIncluder.resolve(JDOMUtil.loadDocument(url), url.toExternalForm()).detachRootElement()
getPathMacroManagerForDefaults()?.expandPaths(documentElement)
return deserializeState(documentElement, stateClass, null)
}
catch (e: Throwable) {
throw IOException("Error loading default state from $url", e)
}
}
protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.size == 1 || component is StateStorageChooserEx) {
return storages.toList()
}
if (storages.isEmpty()) {
if (stateSpec.defaultStateAsResource) {
return emptyList()
}
throw AssertionError("No storage specified")
}
return storages.sortByDeprecated()
}
override final fun isReloadPossible(componentNames: MutableSet<String>) = !componentNames.any { isNotReloadable(it) }
private fun isNotReloadable(name: String): Boolean {
val component = components.get(name)?.component ?: return false
return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable
}
fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> {
var notReloadableComponents: MutableSet<String>? = null
for (componentName in componentNames) {
if (isNotReloadable(componentName)) {
if (notReloadableComponents == null) {
notReloadableComponents = LinkedHashSet<String>()
}
notReloadableComponents.add(componentName)
}
}
return notReloadableComponents ?: emptySet<String>()
}
override final fun reloadStates(componentNames: MutableSet<String>, messageBus: MessageBus) {
runBatchUpdate(messageBus) {
reinitComponents(componentNames)
}
}
override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) {
val stateSpec = StoreUtil.getStateSpecOrError(componentClass)
val info = components.get(stateSpec.name) ?: return
(info.component as? PersistentStateComponent<*>)?.let {
initComponent(stateSpec, it, info, emptySet(), true)
}
}
private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean {
val info = components.get(componentName) ?: return false
val component = info.component as? PersistentStateComponent<*> ?: return false
val changedStoragesEmpty = changedStorages.isEmpty()
initComponent(StoreUtil.getStateSpec(component), component, info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty)
return true
}
/**
* null if reloaded
* empty list if nothing to reload
* list of not reloadable components (reload is not performed)
*/
fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
if (changedStorages.isEmpty()) {
return emptySet()
}
val componentNames = SmartHashSet<String>()
for (storage in changedStorages) {
try {
// we must update (reload in-memory storage data) even if non-reloadable component will be detected later
// not saved -> user does own modification -> new (on disk) state will be overwritten and not applied
storage.analyzeExternalChangesAndUpdateIfNeed(componentNames)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (componentNames.isEmpty) {
return emptySet()
}
val notReloadableComponents = getNotReloadableComponents(componentNames)
reinitComponents(componentNames, changedStorages, notReloadableComponents)
return if (notReloadableComponents.isEmpty()) null else notReloadableComponents
}
// used in settings repository plugin
/**
* You must call it in batch mode (use runBatchUpdate)
*/
fun reinitComponents(componentNames: Set<String>, changedStorages: Set<StateStorage> = emptySet(), notReloadableComponents: Collection<String> = emptySet()) {
for (componentName in componentNames) {
if (!notReloadableComponents.contains(componentName)) {
reloadState(componentName, changedStorages)
}
}
}
@TestOnly fun removeComponent(name: String) {
components.remove(name)
}
}
internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>>, previousErrors: MutableList<Throwable>?): MutableList<Throwable>? {
var errors = previousErrors
try {
session.save()
}
catch (e: ReadOnlyModificationException) {
LOG.warn(e)
readonlyFiles.add(JBPair.create<SaveSession, VirtualFile>(e.session ?: session, e.file))
}
catch (e: Exception) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors.add(e)
}
return errors
}
private fun findNonDeprecated(storages: Array<Storage>) = storages.firstOrNull { !it.deprecated } ?: throw AssertionError("All storages are deprecated")
enum class StateLoadPolicy {
LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD
}
internal fun Array<out Storage>.sortByDeprecated(): List<Storage> {
if (size < 2) {
return toList()
}
if (!first().deprecated) {
var othersAreDeprecated = true
for (i in 1..size - 1) {
if (!get(i).deprecated) {
othersAreDeprecated = false
break
}
}
if (othersAreDeprecated) {
return toList()
}
}
return sortedWith(deprecatedComparator)
}
private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) {
val substitutor = store.stateStorageManager.macroSubstitutor ?: return
val immutableMacros = substitutor.getUnknownMacros(componentName)
if (immutableMacros.isEmpty()) {
return
}
val macros = LinkedHashSet(immutableMacros)
AppUIUtil.invokeOnEdt(Runnable {
var notified: MutableList<String>? = null
val manager = NotificationsManager.getNotificationsManager()
for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (notified == null) {
notified = SmartList<String>()
}
notified.addAll(notification.macros)
}
if (!notified.isNullOrEmpty()) {
macros.removeAll(notified!!)
}
if (macros.isEmpty()) {
return@Runnable
}
LOG.debug("Reporting unknown path macros $macros in component $componentName")
doNotify(macros, project, Collections.singletonMap(substitutor, store))
}, project.disposed)
}
private interface ComponentInfo {
val component: Any
val lastModificationCount: Long
val currentModificationCount: Long
val isModificationTrackingSupported: Boolean
fun updateModificationCount(newCount: Long = currentModificationCount) {
}
}
private class ComponentInfoImpl(override val component: Any) : ComponentInfo {
override val isModificationTrackingSupported = false
override val lastModificationCount: Long
get() = -1
override val currentModificationCount: Long
get() = -1
}
private abstract class ModificationTrackerAwareComponentInfo : ComponentInfo {
override final val isModificationTrackingSupported = true
override abstract var lastModificationCount: Long
override final fun updateModificationCount(newCount: Long) {
lastModificationCount = newCount
}
}
private class ComponentWithStateModificationTrackerInfo(override val component: PersistentStateComponentWithModificationTracker<*>) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.stateModificationCount
override var lastModificationCount = currentModificationCount
}
private class ComponentWithModificationTrackerInfo(override val component: ModificationTracker) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.modificationCount
override var lastModificationCount = currentModificationCount
} | apache-2.0 | dc947de096e88cc7aa3dd996b34655d6 | 36.747927 | 209 | 0.713984 | 5.071524 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/test/kotlin/me/proxer/library/api/list/IndustryProjectListEndpointTest.kt | 2 | 2436 | package me.proxer.library.api.list
import me.proxer.library.ProxerTest
import me.proxer.library.entity.list.IndustryProject
import me.proxer.library.enums.IndustryType
import me.proxer.library.enums.MediaState
import me.proxer.library.enums.Medium
import me.proxer.library.runRequest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class IndustryProjectListEndpointTest : ProxerTest() {
private val expectedIndustryProject = IndustryProject(
id = "10198", name = "&Dropout", genres = setOf("Comedy", "SciFi", "Yuri"), fskConstraints = emptySet(),
medium = Medium.ONESHOT, industryType = IndustryType.PUBLISHER, state = MediaState.FINISHED, ratingSum = 109,
ratingAmount = 23
)
@Test
fun testDefault() {
val (result, _) = server.runRequest("industry_project_list.json") {
api.list
.industryProjectList("333")
.build()
.safeExecute()
}
result.first() shouldBeEqualTo expectedIndustryProject
}
@Test
fun testPath() {
val (_, request) = server.runRequest("industry_project_list.json") {
api.list.industryProjectList("543")
.includeHentai(true)
.type(IndustryType.RECORD_LABEL)
.page(3)
.limit(12)
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/list/industryprojects?id=543&type=record_label&isH=true&p=3&limit=12"
}
@Test
fun testPathNoHentai() {
val (_, request) = server.runRequest("industry_project_list.json") {
api.list.industryProjectList("543")
.includeHentai(false)
.type(IndustryType.RECORD_LABEL)
.page(3)
.limit(12)
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/list/industryprojects?id=543&type=record_label&isH=false&p=3&limit=12"
}
@Test
fun testHentaiNull() {
val (_, request) = server.runRequest("industry_project_list.json") {
api.list.industryProjectList("543")
.includeHentai(true)
.includeHentai(null)
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/list/industryprojects?id=543"
}
}
| gpl-3.0 | f8c12d114cd2babf5e69c7d96abe9646 | 30.636364 | 117 | 0.595649 | 4.207254 | false | true | false | false |
AlekseyZhelo/LBM | LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/render/GLRenderer.kt | 1 | 5193 | package com.alekseyzhelo.lbm.gui.lwjgl.render
import com.alekseyzhelo.lbm.cli.CLISettings
import com.alekseyzhelo.lbm.core.cell.CellD2Q9
import com.alekseyzhelo.lbm.gui.lwjgl.cli.CMSettings
import com.alekseyzhelo.lbm.gui.lwjgl.color.colormap.*
import com.alekseyzhelo.lbm.statistics.LatticeStatistics
import com.alekseyzhelo.lbm.util.norm
import org.lwjgl.BufferUtils
import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.glfw.GLFWErrorCallback
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11
import org.lwjgl.system.MemoryUtil
/**
* @author Aleks on 03-07-2016.
*/
abstract class GLRenderer<Cell : CellD2Q9>(
val cli: CLISettings,
val cm: CMSettings,
val WIDTH: Int = 750,
val HEIGHT: Int = 750
) {
// The window handle
protected var window: Long = 0
protected val width = BufferUtils.createIntBuffer(1)
protected val height = BufferUtils.createIntBuffer(1)
protected val colormap: Colormap
protected val minValue: () -> Double
protected val maxValue: () -> Double
protected val cellValue: (cell: CellD2Q9) -> Double
init {
colormap = resolveColormap()
if (cli.drawVelocities) {
minValue = { 0.0 }
maxValue = { LatticeStatistics.maxVelocity }
cellValue = { cell: CellD2Q9 -> norm(cell.U) } // TODO: indicate that we are one iteration behind like this
} else {
minValue = { LatticeStatistics.minDensity }
maxValue = { LatticeStatistics.maxDensity }
cellValue = { cell: CellD2Q9 -> cell.computeRho() }
}
}
val frame: (cells: Array<Array<Cell>>) -> Unit = if (cli.headless) { x -> Unit } else { x -> doFrame(x) }
fun initialize() {
if (cli.headless) {
return
}
doInit()
}
fun terminate() {
if (cli.headless) {
return
}
try {
// Free the window callbacks and destroy the window
glfwFreeCallbacks(window)
glfwDestroyWindow(window)
extraTerminate()
} finally {
// Terminate GLFW and free the error callback
glfwTerminate()
glfwSetErrorCallback(null).free()
}
}
protected open fun extraTerminate() {
}
protected open fun doInit() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
GLFWErrorCallback.createPrint(System.err).set()
// Initialize GLFW. Most GLFW functions will not work before doing this.
if (!glfwInit())
throw IllegalStateException("Unable to initialize GLFW")
// Configure our window
glfwDefaultWindowHints() // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE) // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE) // the window will be resizable
// Create the window
window = glfwCreateWindow(WIDTH, HEIGHT, "Hello World!", MemoryUtil.NULL, MemoryUtil.NULL)
if (window == MemoryUtil.NULL)
throw RuntimeException("Failed to create the GLFW window")
// Setup a key callback. It will be called every time a key is pressed, repeated or released.
glfwSetKeyCallback(window) { window, key, scanCode, action, mods ->
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, true) // We will detect this in our rendering loop
}
// Get the resolution of the primary monitor
val vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor())
// Center our window
glfwSetWindowPos(
window,
(vidMode.width() - WIDTH) / 2,
(vidMode.height() - HEIGHT) / 2)
// Make the OpenGL context current
glfwMakeContextCurrent(window)
// Disable v-sync
glfwSwapInterval(0)
// Make the window visible
glfwShowWindow(window)
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the GLCapabilities instance and makes the OpenGL
// bindings available for use.
GL.createCapabilities()
// Set the clear color
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f)
}
fun windowShouldClose() = if (cli.headless) false else glfwWindowShouldClose(window)
protected abstract fun doFrame(cells: Array<Array<Cell>>)
private fun resolveColormap(): Colormap {
// TODO: automatically list all implemented colormaps?
return when (cm.colormap) {
CoolwarmDiscreteColormap.getName() -> CoolwarmDiscreteColormap
CoolwarmRGBInterpolatedColormap.getName() -> CoolwarmRGBInterpolatedColormap
BluerJetColormap.getName() -> BluerJetColormap
BlueRedColormap.getName() -> BlueRedColormap
else -> CoolwarmDiscreteColormap
}
}
} | apache-2.0 | d4e5f3cde75acdccf21abb44be204a54 | 33.397351 | 119 | 0.644136 | 4.519582 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/core/kotlin/universum/studios/gradle/github/task/BaseTaskConfigurator.kt | 1 | 3595 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.task
import universum.studios.gradle.github.extension.DefaultConfigExtension
import universum.studios.gradle.github.extension.RepositoryExtension
import universum.studios.gradle.github.task.configuration.TaskConfigurator
/**
* A [TaskConfigurator] implementation that may be used as base for concrete task configurator
* implementations. This configurator implementation does not perform any task configuration.
*
* @author Martin Albedinsky
* @since 1.0
*
* @constructor Creates a new instance of BaseTaskConfigurator.
*/
open class BaseTaskConfigurator<T : BaseTask> : TaskConfigurator<T> {
/*
* Companion ===================================================================================
*/
/*
* Interface ===================================================================================
*/
/*
* Members =====================================================================================
*/
/**
* Repository on which should all task configured via [configureTask] perform theirs related
* operations.
*/
private var repository: RepositoryExtension = RepositoryExtension()
/**
* Default configuration to be attached to all tasks passed to [configureTask].
*/
private var defaultConfig: DefaultConfigExtension = DefaultConfigExtension()
/*
* Constructors ================================================================================
*/
/*
* Methods =====================================================================================
*/
/*
*/
override fun setRepository(repository: RepositoryExtension) {
this.repository = repository
}
/**
* Returns the repository specified for this configurator.
*
* @return The attached repository.
*
* @see setRepository
*/
fun getRepository() = repository
/*
*/
override fun setDefaultConfig(defaultConfig: DefaultConfigExtension) {
this.defaultConfig = defaultConfig
}
/**
* Returns the default configuration specified for this configurator.
*
* @return The attached default configuration.
*
* @see setDefaultConfig
*/
fun getDefaultConfig() = defaultConfig
/**
*/
override fun configureTask(task: T): T {
task.setRepository(repository)
return task
}
/*
* Inner classes ===============================================================================
*/
} | apache-2.0 | f5eb0f5e6208308dc185a282653edf3c | 32.607477 | 101 | 0.500417 | 6.307018 | false | true | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/TrackableLog.kt | 1 | 2076 | package com.arcao.geocaching4locus.data.api.model
import com.arcao.geocaching4locus.data.api.util.ReferenceCode
import com.squareup.moshi.JsonClass
import java.time.Instant
@JsonClass(generateAdapter = true)
data class TrackableLog(
val referenceCode: String, // string
val ownerCode: String, // string
val imageCount: Int, // 0
val trackableCode: String, // string
val geocacheCode: String, // string
val geocacheName: String, // string
val loggedDate: Instant, // 2018-06-06T06:16:54.589Z
val text: String, // string
val isRot13Encoded: Boolean, // true
val trackableLogType: TrackableLogType, // type
val coordinates: Coordinates, // Coordinates
val url: String, // string
val owner: User // user
) {
val id by lazy {
ReferenceCode.toId(referenceCode)
}
companion object {
private const val FIELD_REFERENCE_CODE = "referenceCode"
private const val FIELD_OWNER_CODE = "ownerCode"
private const val FIELD_IMAGE_COUNT = "imageCount"
private const val FIELD_TRACKABLE_CODE = "trackableCode"
private const val FIELD_GEOCACHE_CODE = "geocacheCode"
private const val FIELD_GEOCACHE_NAME = "geocacheName"
private const val FIELD_LOGGED_DATE = "loggedDate"
private const val FIELD_TEXT = "text"
private const val FIELD_IS_ROT13_ENCODED = "isRot13Encoded"
private const val FIELD_TRACKABLE_LOG_TYPE = "trackableLogType"
private const val FIELD_COORDINATES = "coordinates"
private const val FIELD_URL = "url"
private const val FIELD_OWNER = "owner"
val FIELDS_ALL = fieldsOf(
FIELD_REFERENCE_CODE,
FIELD_OWNER_CODE,
FIELD_IMAGE_COUNT,
FIELD_TRACKABLE_CODE,
FIELD_GEOCACHE_CODE,
FIELD_GEOCACHE_NAME,
FIELD_LOGGED_DATE,
FIELD_TEXT,
FIELD_IS_ROT13_ENCODED,
FIELD_TRACKABLE_LOG_TYPE,
FIELD_COORDINATES,
FIELD_URL,
FIELD_OWNER
)
}
}
| gpl-3.0 | 0879a6dde72ca69e9b10687f93327656 | 34.793103 | 71 | 0.645954 | 4.110891 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AccessibilityCodelab/app/src/main/java/com/example/jetnews/ui/theme/Theme.kt | 1 | 1677 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetnews.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val LightThemeColors = lightColors(
primary = Red700,
primaryVariant = Red900,
onPrimary = Color.White,
secondary = Red700,
secondaryVariant = Red900,
onSecondary = Color.White,
error = Red800
)
private val DarkThemeColors = darkColors(
primary = Red300,
primaryVariant = Red700,
onPrimary = Color.Black,
secondary = Red300,
onSecondary = Color.Black,
error = Red200
)
@Composable
fun JetnewsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
MaterialTheme(
colors = if (darkTheme) DarkThemeColors else LightThemeColors,
typography = JetnewsTypography,
shapes = JetnewsShapes,
content = content
)
}
| apache-2.0 | f9de413e20c0ba22da531b4db45975c5 | 28.946429 | 75 | 0.734049 | 4.390052 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/customselector/ui/selector/FolderFragment.kt | 2 | 4825 | package fr.free.nrw.commons.customselector.ui.selector
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import fr.free.nrw.commons.customselector.helper.ImageHelper
import fr.free.nrw.commons.customselector.model.Result
import fr.free.nrw.commons.customselector.listeners.FolderClickListener
import fr.free.nrw.commons.customselector.model.CallbackStatus
import fr.free.nrw.commons.customselector.model.Folder
import fr.free.nrw.commons.customselector.ui.adapter.FolderAdapter
import fr.free.nrw.commons.databinding.FragmentCustomSelectorBinding
import fr.free.nrw.commons.di.CommonsDaggerSupportFragment
import fr.free.nrw.commons.media.MediaClient
import fr.free.nrw.commons.upload.FileProcessor
import javax.inject.Inject
/**
* Custom selector folder fragment.
*/
class FolderFragment : CommonsDaggerSupportFragment() {
/**
* ViewBinding
*/
private var _binding: FragmentCustomSelectorBinding? = null
private val binding get() = _binding
/**
* View Model for images.
*/
private var viewModel: CustomSelectorViewModel? = null
/**
* View Elements
*/
private var selectorRV: RecyclerView? = null
private var loader: ProgressBar? = null
/**
* View Model Factory.
*/
var customSelectorViewModelFactory: CustomSelectorViewModelFactory? = null
@Inject set
var fileProcessor: FileProcessor? = null
@Inject set
var mediaClient: MediaClient? = null
@Inject set
/**
* Folder Adapter.
*/
private lateinit var folderAdapter: FolderAdapter
/**
* Grid Layout Manager for recycler view.
*/
private lateinit var gridLayoutManager: GridLayoutManager
/**
* Folder List.
*/
private lateinit var folders : ArrayList<Folder>
/**
* Companion newInstance.
*/
companion object{
fun newInstance(): FolderFragment {
return FolderFragment()
}
}
/**
* OnCreate Fragment, get the view model.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(requireActivity(),customSelectorViewModelFactory!!).get(CustomSelectorViewModel::class.java)
}
/**
* OnCreateView.
* Inflate Layout, init adapter, init gridLayoutManager, setUp recycler view, observe the view model for result.
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentCustomSelectorBinding.inflate(inflater, container, false)
folderAdapter = FolderAdapter(activity!!, activity as FolderClickListener)
gridLayoutManager = GridLayoutManager(context, columnCount())
selectorRV = binding?.selectorRv
loader = binding?.loader
with(binding?.selectorRv){
this?.layoutManager = gridLayoutManager
this?.setHasFixedSize(true)
this?.adapter = folderAdapter
}
viewModel?.result?.observe(viewLifecycleOwner) {
handleResult(it)
}
return binding?.root
}
/**
* Handle view model result.
* Get folders from images.
* Load adapter.
*/
private fun handleResult(result: Result) {
if(result.status is CallbackStatus.SUCCESS){
val images = result.images
if(images.isNullOrEmpty())
{
binding?.emptyText?.let {
it.visibility = View.VISIBLE
}
}
folders = ImageHelper.folderListFromImages(result.images)
folderAdapter.init(folders)
folderAdapter.notifyDataSetChanged()
selectorRV?.let {
it.visibility = View.VISIBLE
}
}
loader?.let {
it.visibility = if (result.status is CallbackStatus.FETCHING) View.VISIBLE else View.GONE
}
}
/**
* onResume
* notifyDataSetChanged, rebuild the holder views to account for deleted images, folders.
*/
override fun onResume() {
folderAdapter.notifyDataSetChanged()
super.onResume()
}
/**
* onDestroyView
* clearing view binding
*/
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
/**
* Return Column count ie span count for grid view adapter.
*/
private fun columnCount(): Int {
return 2
// todo change column count depending on the orientation of the device.
}
} | apache-2.0 | 503b7cca8c3434004599b897fd8ea0ce | 28.790123 | 130 | 0.66342 | 5.015593 | false | false | false | false |
google/grpc-kapt | processor/src/main/kotlin/com/google/api/grpc/kapt/generator/proto/ProtoInterfaceGenerator.kt | 1 | 12918 | /*
*
* * Copyright 2019 Google LLC
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * https://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.google.api.grpc.kapt.generator.proto
import com.google.api.grpc.kapt.GrpcClient
import com.google.api.grpc.kapt.generator.ClientGenerator
import com.google.api.grpc.kapt.generator.CodeGenerationException
import com.google.api.grpc.kapt.generator.GeneratedInterface
import com.google.api.grpc.kapt.generator.GeneratedInterfaceProvider
import com.google.api.grpc.kapt.generator.Generator
import com.google.api.grpc.kapt.generator.KotlinMethodInfo
import com.google.api.grpc.kapt.generator.ParameterInfo
import com.google.api.grpc.kapt.generator.RpcInfo
import com.google.api.grpc.kapt.generator.SchemaDescriptorProvider
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.Descriptors
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import io.grpc.MethodDescriptor
import io.grpc.protobuf.ProtoFileDescriptorSupplier
import io.grpc.protobuf.ProtoMethodDescriptorSupplier
import io.grpc.protobuf.ProtoServiceDescriptorSupplier
import kotlinx.coroutines.channels.ReceiveChannel
import java.io.File
import java.util.Base64
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
internal const val KAPT_PROTO_DESCRIPTOR_OPTION_NAME = "protos"
private const val PROPTO_SOURCE_CLASS_NAME = "ProtoSourceSupplier"
/**
* Generates an interface from a protocol buffer file descriptor that can be consumed
* by the other code generators.
*/
internal class ProtoInterfaceGenerator(
environment: ProcessingEnvironment
) : Generator<GeneratedInterface>(environment), GeneratedInterfaceProvider {
// read the descriptor from the kapt options
private val descriptor: DescriptorProtos.FileDescriptorSet by lazy {
val descriptorFile = File(
environment.options[KAPT_PROTO_DESCRIPTOR_OPTION_NAME]
?: throw CodeGenerationException("The protobuf file descriptor set is not available to the annotation processor. Please set the kapt '$KAPT_PROTO_DESCRIPTOR_OPTION_NAME' option.")
)
DescriptorProtos.FileDescriptorSet.parseFrom(descriptorFile.readBytes())
}
// create mappings from proto to Kotlin types
private val typeMapper by lazy {
ProtobufTypeMapper.fromProtos(descriptor.fileList)
}
override fun generate(element: Element): GeneratedInterface {
val annotation = element.getAnnotation(GrpcClient::class.java)
?: throw CodeGenerationException("expected @GrpcClient element")
// find the service
val serviceInfo = findServiceOrNull(annotation.definedBy)
?: throw CodeGenerationException("service defined by '${annotation.definedBy}' was not found in the descriptor set.")
val file = serviceInfo.file
val service = serviceInfo.service
// create the interface type
val typeBuilder = TypeSpec.interfaceBuilder(service.name)
.addSuperinterface(element.asType().asTypeName())
.addType(
TypeSpec.companionObjectBuilder()
.addFunctions(ClientGenerator.createChannelBuilders("${service.name}Ext", service.name))
.build()
)
val funMap = mutableMapOf<FunSpec, KotlinMethodInfo>()
// add all the functions
for (method in service.methodList) {
val (func, metadata) = method.asClientMethod(typeMapper, file, service)
typeBuilder.addFunction(func)
funMap[func] = metadata
}
val extendedTypeBuilder = TypeSpec.interfaceBuilder("${service.name}Ext")
.addSuperinterface(TypeVariableName(service.name))
.addSuperinterface(AutoCloseable::class)
.addProperties(ClientGenerator.COMMON_INTERFACE_PROPERTIES)
return GeneratedInterface(
typeName = "${service.name}Ext",
simpleTypeName = service.name,
methodInfo = funMap,
types = listOf(typeBuilder.build(), extendedTypeBuilder.build())
)
}
private data class ServiceInfo(
val file: DescriptorProtos.FileDescriptorProto,
val service: DescriptorProtos.ServiceDescriptorProto
) {
fun asFullyQualifiedServiceName() = "${file.`package`}.${service.name}"
}
private fun findServiceOrNull(name: String): ServiceInfo? {
for (file in descriptor.fileList) {
val service = file.serviceList.firstOrNull { "${file.`package`}.${it.name}" == name }
if (service != null) {
return ServiceInfo(file, service)
}
}
return null
}
override fun isDefinedBy(value: String): Boolean = value.isNotBlank()
override fun findFullyQualifiedServiceName(value: String): String =
this.findServiceOrNull(value)?.asFullyQualifiedServiceName()
?: throw CodeGenerationException("no service found with name: '$value'")
override fun getSource(value: String): SchemaDescriptorProvider? {
val serviceInfo = findServiceOrNull(value) ?: return null
return object : SchemaDescriptorProvider {
override fun getSchemaDescriptorType(): TypeSpec? {
return TypeSpec.classBuilder(PROPTO_SOURCE_CLASS_NAME)
.addModifiers(KModifier.PRIVATE)
.addSuperinterface(ProtoMethodDescriptorSupplier::class.asTypeName())
.addSuperinterface(ProtoFileDescriptorSupplier::class.asTypeName())
.addSuperinterface(ProtoServiceDescriptorSupplier::class.asTypeName())
.addProperty(
PropertySpec.builder("proto", String::class.asClassName())
.initializer(
"%S",
Base64.getEncoder().encodeToString(serviceInfo.file.toByteArray() ?: ByteArray(0))
)
.build()
)
.addProperty(
PropertySpec.builder("methodName", String::class.asTypeName(), KModifier.PRIVATE)
.initializer("methodName").build()
)
.addProperty(
PropertySpec.builder(
"descriptor",
Descriptors.FileDescriptor::class.asTypeName(),
KModifier.PRIVATE
).build()
)
.primaryConstructor(
FunSpec.constructorBuilder()
.addModifiers(KModifier.INTERNAL)
.addParameter("methodName", String::class.asTypeName())
.build()
)
.addInitializerBlock(
CodeBlock.of(
"""
|descriptor = %T.buildFrom(
| %T.parseFrom(%T.getDecoder().decode(this.proto)),
| arrayOfNulls(0),
| true
|)
""".trimMargin(),
Descriptors.FileDescriptor::class.asTypeName(),
DescriptorProtos.FileDescriptorProto::class.asTypeName(),
Base64::class.asTypeName()
)
)
.addFunction(
FunSpec.builder("getMethodDescriptor")
.addModifiers(KModifier.OVERRIDE)
.returns(Descriptors.MethodDescriptor::class.asTypeName())
.addCode("return this.serviceDescriptor.findMethodByName(this.methodName)")
.build()
)
.addFunction(
FunSpec.builder("getFileDescriptor")
.addModifiers(KModifier.OVERRIDE)
.returns(Descriptors.FileDescriptor::class.asTypeName())
.addCode("return this.descriptor")
.build()
)
.addFunction(
FunSpec.builder("getServiceDescriptor")
.addModifiers(KModifier.OVERRIDE)
.returns(Descriptors.ServiceDescriptor::class.asTypeName())
.addCode("return this.fileDescriptor.findServiceByName(%S)", serviceInfo.service.name)
.build()
)
.build()
}
override fun getSchemaDescriptorFor(methodName: String?) =
CodeBlock.of("$PROPTO_SOURCE_CLASS_NAME(%S)", methodName ?: "")
}
}
}
private fun DescriptorProtos.MethodDescriptorProto.asClientMethod(
typeMapper: ProtobufTypeMapper,
file: DescriptorProtos.FileDescriptorProto,
service: DescriptorProtos.ServiceDescriptorProto
): Pair<FunSpec, KotlinMethodInfo> {
val kotlinOutputType = getKotlinOutputType(typeMapper)
val kotlinInputType = getKotlinInputType(typeMapper)
val requestVar = "request"
val builder = FunSpec.builder(name.decapitalize())
.addModifiers(KModifier.SUSPEND, KModifier.ABSTRACT)
.returns(kotlinOutputType)
.addParameter(requestVar, kotlinInputType)
val comments = file.getMethodComments(service, this) ?: ""
if (comments.isNotBlank()) {
builder.addKdoc(comments)
}
val methodInfo = KotlinMethodInfo(
name = name.decapitalize(),
isSuspend = true,
parameters = listOf(ParameterInfo(requestVar, kotlinInputType)),
returns = kotlinOutputType,
rpc = RpcInfo(
name = name,
type = when {
serverStreaming && clientStreaming -> MethodDescriptor.MethodType.BIDI_STREAMING
serverStreaming -> MethodDescriptor.MethodType.SERVER_STREAMING
clientStreaming -> MethodDescriptor.MethodType.CLIENT_STREAMING
else -> MethodDescriptor.MethodType.UNARY
},
inputType = typeMapper.getKotlinType(inputType),
outputType = typeMapper.getKotlinType(outputType)
)
)
return Pair(builder.build(), methodInfo)
}
private val RECEIVE_CHANNEL = ReceiveChannel::class.asTypeName()
private fun DescriptorProtos.MethodDescriptorProto.getKotlinOutputType(typeMapper: ProtobufTypeMapper): TypeName {
val baseType = typeMapper.getKotlinType(outputType)
return if (serverStreaming) {
RECEIVE_CHANNEL.parameterizedBy(baseType)
} else {
baseType
}
}
private fun DescriptorProtos.MethodDescriptorProto.getKotlinInputType(typeMapper: ProtobufTypeMapper): TypeName {
val baseType = typeMapper.getKotlinType(inputType)
return if (clientStreaming) {
RECEIVE_CHANNEL.parameterizedBy(baseType)
} else {
baseType
}
}
/** Get the comments of a service method in this .proto file, or null if not available */
internal fun DescriptorProtos.FileDescriptorProto.getMethodComments(
service: DescriptorProtos.ServiceDescriptorProto,
method: DescriptorProtos.MethodDescriptorProto
): String? {
// find the magic numbers
val serviceNumber = this.serviceList.indexOf(service)
val methodNumber = service.methodList.indexOf(method)
// location is [6, serviceNumber, 2, methodNumber]
return this.sourceCodeInfo.locationList.filter {
it.pathCount == 4 &&
it.pathList[0] == 6 && // 6 is for service
it.pathList[1] == serviceNumber &&
it.pathList[2] == 2 && // 2 is for method (rpc)
it.pathList[3] == methodNumber &&
it.hasLeadingComments()
}.map { it.leadingComments }.firstOrNull()
}
| apache-2.0 | efc60a3f2428eee115333152470b29c2 | 42.204013 | 195 | 0.63129 | 5.364618 | false | false | false | false |
nfrankel/kaadin | kaadin-core/src/main/kotlin/ch/frankel/kaadin/StructureHierarchy.kt | 1 | 2463 | /*
* 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
import com.vaadin.server.*
import com.vaadin.ui.*
/**
* http://demo.vaadin.com/sampler/#ui/structure
*/
fun HasComponents.panel(caption: String? = null, init: Panel.() -> Unit = {}) = Panel()
.apply {
caption?.let { this.caption = caption }
content?.let { this.content = content }
}.apply(init)
.addTo(this)
fun HasComponents.verticalSplitPanel(init: VerticalSplitPanel.() -> Unit = {}) = VerticalSplitPanel()
.apply(init)
.addTo(this)
fun HasComponents.horizontalSplitPanel(init: HorizontalSplitPanel.() -> Unit = {}) = HorizontalSplitPanel()
.apply(init)
.addTo(this)
fun HasComponents.accordion(init: Accordion.() -> Unit = {}) = Accordion()
.apply(init)
.addTo(this)
fun HasComponents.tabSheet(init: TabSheet.() -> Unit = {}) = TabSheet()
.apply(init)
.addTo(this)
fun TabSheet.tab(caption: String? = null, icon: Resource? = null, init: TabContainer.() -> Unit = {}) = TabContainer(this, caption, icon).apply(init)
/** Used in InternalUtils.kt. */
class TabContainer(internal val tabSheet: TabSheet,
internal val caption: String?,
internal val icon: Resource?) : AbstractSingleComponentContainer()
fun HasComponents.popupView(content: PopupView.Content, init: PopupView.() -> Unit = {}) = PopupView(content).addTo(this).apply(init)
fun HasComponents.popupView(html: String, init: PopupView.() -> Unit): PopupView = InternalPopupView(html).addTo(this).apply(init)
/** Just to be able to call static createContent from super class */
internal class InternalPopupView(val html: String): PopupView() {
companion object {
fun createContent(minimizedValue: String, popupContent: Component): Content? = PopupView.createContent(minimizedValue, popupContent)
}
}
| apache-2.0 | 7c732d110005af57c477360690183f23 | 38.079365 | 149 | 0.683184 | 4.003252 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/videos/ChavesOpeningExecutor.kt | 1 | 4270 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.videos
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.gabrielaimageserver.data.ChavesOpeningRequest
import net.perfectdreams.gabrielaimageserver.data.URLImageData
import net.perfectdreams.gabrielaimageserver.exceptions.InvalidChavesOpeningTextException
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.common.utils.TodoFixThisData
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.gabrielaimageserver.handleExceptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.videos.declarations.ChavesCommand
class ChavesOpeningExecutor(
loritta: LorittaBot,
val client: GabrielaImageServerClient
) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
// The description is replaced with "User, URL or Emote" so we don't really care that we are using "TodoFixThisData" here
val chiquinhaImage = imageReference("chiquinha")
val girafalesImage = imageReference("girafales")
val bruxaImage = imageReference("bruxa")
val quicoImage = imageReference("quico")
val florindaImage = imageReference("florinda")
val madrugaImage = imageReference("madruga")
val barrigaImage = imageReference("barriga")
val chavesImage = imageReference("chaves")
val showName = string("show_name", ChavesCommand.I18N_PREFIX.Opening.Options.ShowName.Text)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage() // Defer message because image manipulation is kinda heavy
val chiquinha = args[options.chiquinhaImage].get(context)
val girafales = args[options.girafalesImage].get(context)
val bruxa = args[options.bruxaImage].get(context)
val quico = args[options.quicoImage].get(context)
val florinda = args[options.florindaImage].get(context)
val madruga = args[options.madrugaImage].get(context)
val barriga = args[options.barrigaImage].get(context)
val chaves = args[options.chavesImage].get(context)
val showName = args[options.showName]
val result = try {
client.handleExceptions(context) {
client.videos.chavesOpening(
ChavesOpeningRequest(
URLImageData(
chiquinha.url
),
URLImageData(
girafales.url
),
URLImageData(
bruxa.url
),
URLImageData(
quico.url
),
URLImageData(
florinda.url
),
URLImageData(
madruga.url
),
URLImageData(
barriga.url
),
URLImageData(
chaves.url
),
showName
)
)
}
} catch (e: InvalidChavesOpeningTextException) {
context.fail(
context.i18nContext.get(ChavesCommand.I18N_PREFIX.Opening.InvalidShowName),
Emotes.LoriSob
)
}
context.sendMessage {
addFile("chaves_opening.mp4", result.inputStream())
}
}
} | agpl-3.0 | a7d56a5935a3cd7f5b5e865c4fc2a633 | 41.71 | 129 | 0.633255 | 5.047281 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/Pager.kt | 3 | 879 | package eu.kanade.tachiyomi.ui.catalogue.browse
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.SManga
import rx.Observable
/**
* A general pager for source requests (latest updates, popular, search)
*/
abstract class Pager(var currentPage: Int = 1) {
var hasNextPage = true
private set
protected val results: PublishRelay<Pair<Int, List<SManga>>> = PublishRelay.create()
fun results(): Observable<Pair<Int, List<SManga>>> {
return results.asObservable()
}
abstract fun requestNext(): Observable<MangasPage>
fun onPageReceived(mangasPage: MangasPage) {
val page = currentPage
currentPage++
hasNextPage = mangasPage.hasNextPage && !mangasPage.mangas.isEmpty()
results.call(Pair(page, mangasPage.mangas))
}
} | apache-2.0 | 6516f50e1c7e76a4383a2826992cf056 | 27.387097 | 88 | 0.714448 | 4.351485 | false | false | false | false |
ZhuoKeTeam/JueDiQiuSheng | app/src/main/java/cc/zkteam/juediqiusheng/module/pic/category/PicCategoryActivity.kt | 1 | 1735 | package cc.zkteam.juediqiusheng.module.pic.category
import android.support.v7.widget.LinearLayoutManager
import cc.zkteam.juediqiusheng.R
import cc.zkteam.juediqiusheng.activity.BaseActivity
import cc.zkteam.juediqiusheng.bean.PicBean
import cc.zkteam.juediqiusheng.managers.ZKConnectionManager
import cc.zkteam.juediqiusheng.module.pic.category.adapter.PicCategoryAdapter
import cc.zkteam.juediqiusheng.retrofit2.ZKCallback
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.android.synthetic.main.fragment_pic_main_layout.*
import org.jetbrains.anko.ctx
/**
* Created by kutear on 2017/11/1.
*
* 图片分类
*/
@Route(path = "/modules/pic/category")
class PicCategoryActivity : BaseActivity() {
@Autowired(name = "categoryId")
lateinit var categoryId: String
private val adapter = PicCategoryAdapter()
override fun getLayoutId(): Int {
return R.layout.fragment_pic_main_layout
}
override fun initViews() {
ARouter.getInstance().inject(this)
pic_main_list.layoutManager = LinearLayoutManager(ctx)
pic_main_list.adapter = adapter
}
override fun initListener() {
}
override fun initData() {
ZKConnectionManager.getInstance()
.zkApi.getCategoryList(categoryId, 20)
.enqueue(object : ZKCallback<List<PicBean>>() {
override fun onResponse(result: List<PicBean>?) {
adapter.covertData(result)
}
override fun onFailure(throwable: Throwable?) {
}
})
}
} | bsd-3-clause | adaf48f40ce5521686270ff0d10478d8 | 30.418182 | 77 | 0.691951 | 3.951945 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/view/components/inputs/NumberField.kt | 1 | 1461 | package at.cpickl.gadsu.view.components.inputs
import at.cpickl.gadsu.service.LOG
import at.cpickl.gadsu.view.swing.enforceCharactersByRegexp
import at.cpickl.gadsu.view.swing.rightAligned
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.util.regex.Pattern
import javax.swing.JTextField
open class NumberField(columns: Int = 100, initValue: Int? = null) : JTextField(columns) {
companion object {
private val NUMBER_REGEXP = Pattern.compile("""\d+""")
}
private val log = LOG(javaClass)
var numberValue: Int
get() {
if (text.trim().isEmpty()) {
return 0
}
return text.toInt()
}
set(value) {
text = value.toString()
}
init {
// initValue?.let { numberValue = it }
if (initValue != null) {
numberValue = initValue
}
rightAligned()
enforceCharactersByRegexp(NUMBER_REGEXP)
addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent) {
log.trace("focusGained; selectAll()")
selectAll()
}
override fun focusLost(e: FocusEvent) {
if (text.isEmpty()) {
text = "0"
}
}
})
}
}
//class MinutesField() : NumberField(3) {
// val duration: Duration get() = minutes(numberValue)
//}
| apache-2.0 | 97b06c8086e1299d96826c4bd3e25876 | 26.055556 | 90 | 0.572211 | 4.400602 | false | false | false | false |
esafirm/android-image-picker | imagepicker/src/main/java/com/esafirm/imagepicker/helper/ImagePickerUtils.kt | 1 | 5360 | package com.esafirm.imagepicker.helper
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.webkit.MimeTypeMap
import com.esafirm.imagepicker.features.ImagePickerSavePath
import com.esafirm.imagepicker.features.IpCons
import com.esafirm.imagepicker.helper.IpLogger.d
import com.esafirm.imagepicker.model.Image
import java.io.File
import java.net.URLConnection
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.Locale
object ImagePickerUtils {
private const val DEFAULT_DURATION_LABEL = "00:00"
private fun createFileInDirectory(savePath: ImagePickerSavePath, context: Context): File? {
// External sdcard location
val path = savePath.path
val mediaStorageDir: File = if (savePath.isRelative) {
val parent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
} else {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
}
File(parent, path)
} else {
File(path)
}
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
d("Oops! Failed create $path")
return null
}
}
return mediaStorageDir
}
fun createImageFile(savePath: ImagePickerSavePath, context: Context): File? {
val mediaStorageDir = createFileInDirectory(savePath, context) ?: return null
// Create a media file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.getDefault()).format(Date())
var result = File(mediaStorageDir, "IMG_$timeStamp.jpg")
var counter = 0
while (result.exists()) {
counter++
result = File(mediaStorageDir, "IMG_$timeStamp($counter).jpg")
}
return result
}
fun getNameFromFilePath(path: String): String {
return if (path.contains(File.separator)) {
path.substring(path.lastIndexOf(File.separator) + 1)
} else path
}
fun grantAppPermission(context: Context, intent: Intent, fileUri: Uri?) {
val resolvedIntentActivities = context.packageManager
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolvedIntentInfo in resolvedIntentActivities) {
val packageName = resolvedIntentInfo.activityInfo.packageName
context.grantUriPermission(
packageName, fileUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
}
fun revokeAppPermission(context: Context, fileUri: Uri?) {
context.revokeUriPermission(
fileUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
fun isGifFormat(image: Image): Boolean {
return isGifFormat(image.path)
}
fun isGifFormat(path: String): Boolean {
val extension = getExtension(path)
return extension.equals("gif", ignoreCase = true)
}
fun isVideoFormat(image: Image): Boolean {
val extension = getExtension(image.path)
val mimeType =
if (TextUtils.isEmpty(extension)) URLConnection.guessContentTypeFromName(image.path) else MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(extension)
return mimeType != null && mimeType.startsWith("video")
}
fun getVideoDurationLabel(context: Context?, uri: Uri): String {
try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(context, uri)
val durationData =
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
retriever.release()
// Return default duration label if null
val duration = durationData?.toLongOrNull() ?: return DEFAULT_DURATION_LABEL
val second = duration / 1000 % 60
val minute = duration / (1000 * 60) % 60
val hour = duration / (1000 * 60 * 60) % 24
return if (hour > 0) {
String.format("%02d:%02d:%02d", hour, minute, second)
} else {
String.format("%02d:%02d", minute, second)
}
} catch (e: Exception) {
return DEFAULT_DURATION_LABEL
}
}
private fun getExtension(path: String): String {
val extension = MimeTypeMap.getFileExtensionFromUrl(path)
if (!TextUtils.isEmpty(extension)) {
return extension
}
return if (path.contains(".")) {
path.substring(path.lastIndexOf(".") + 1, path.length)
} else {
""
}
}
fun createResultIntent(images: List<Image>?): Intent {
val data = Intent()
val imageArrayList = ArrayList(images ?: emptyList())
data.putParcelableArrayListExtra(IpCons.EXTRA_SELECTED_IMAGES, imageArrayList)
return data
}
} | mit | be574d9fcfe66351af7c3546ab6c0f25 | 35.222973 | 128 | 0.639739 | 4.781445 | false | false | false | false |
shyiko/ktlint | ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/EditorConfig.kt | 1 | 1662 | package com.pinterest.ktlint.core
/**
* @see [EditorConfig](http://editorconfig.org/)
*
* This class is injected into the user data, so it is available to rules via [KtLint.EDITOR_CONFIG_USER_DATA_KEY]
*/
interface EditorConfig {
enum class IndentStyle { SPACE, TAB }
val indentStyle: IndentStyle
val indentSize: Int
val tabWidth: Int
val maxLineLength: Int
@Deprecated(
message = "Not used anymore by rules, please use 'insert_final_newline' directly via get()"
)
val insertFinalNewline: Boolean
operator fun get(key: String): String?
companion object {
fun fromMap(map: Map<String, String>): EditorConfig {
val indentStyle = when {
map["indent_style"]?.toLowerCase() == "tab" -> IndentStyle.TAB
else -> IndentStyle.SPACE
}
val indentSize = map["indent_size"].let { v ->
if (v?.toLowerCase() == "unset") -1 else v?.toIntOrNull() ?: 4
}
val tabWidth = map["indent_size"]?.toIntOrNull()
val maxLineLength = map["max_line_length"]?.toIntOrNull() ?: -1
val insertFinalNewline = map["insert_final_newline"]?.toBoolean() ?: true
return object : EditorConfig {
override val indentStyle = indentStyle
override val indentSize = indentSize
override val tabWidth = tabWidth ?: indentSize
override val maxLineLength = maxLineLength
override val insertFinalNewline = insertFinalNewline
override fun get(key: String): String? = map[key]
}
}
}
}
| mit | db32f7f790588d7aef10845f966d846a | 35.130435 | 114 | 0.595668 | 4.735043 | false | true | false | false |
vsch/SmartData | src/com/vladsch/smart/MarkdownTableFormatter.kt | 1 | 15230 | /*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.vladsch.smart
import java.util.*
/**
* markdown table formatter
*
* spacePadPipes:Boolean - true to put spaces before and after | characters
* discretionaryAlignMarker:Int - -1 to always remove, 0 to leave as is, 1 to always add
*/
class MarkdownTableFormatter(val settings: MarkdownTableFormatSettings) {
constructor() : this(MarkdownTableFormatSettings())
private var myAlignmentDataPoints: List<SmartVersionedDataAlias<TextAlignment>> = listOf()
private var myColumnWidthDataPoints: List<SmartVersionedDataAlias<Int>> = listOf()
// private val myRowColumns: ArrayList<List<SmartCharSequence>> = ArrayList()
// private val myRows: ArrayList<SmartCharSequence> = ArrayList()
val columnCount: Int get() = myColumnWidthDataPoints.size
fun columnWidth(index: Int): Int {
return myColumnWidthDataPoints[index].get()
}
fun columnAlignmentDataPoint(index: Int): TextAlignment {
return myAlignmentDataPoints[index].get()
}
fun formatTable(table: SmartCharSequence): SmartCharSequence {
return formatTable(table, -1, CharWidthProvider.UNITY_PROVIDER)
}
// val rows: Int get() = myRows.size
//
// fun rowSequence(index: Int): SmartCharSequence {
// return myRows[index]
// }
//
// fun rowColumns(index: Int): List<SmartCharSequence> {
// return myRowColumns[index]
// }
fun formatTable(tableChars: SmartCharSequence, caretOffset: Int, charWidthProvider: CharWidthProvider): SmartCharSequence {
val table = parseTable(tableChars, caretOffset, !settings.TABLE_ADJUST_COLUMN_WIDTH && settings.TABLE_TRIM_CELLS)
if (settings.TABLE_FILL_MISSING_COLUMNS) {
val unbalancedTable = table.minColumns != table.maxColumns
if (unbalancedTable) table.fillMissingColumns(null)
}
return formatTable(table, table.indentPrefix, charWidthProvider)
}
fun formatTable(markdownTable: MarkdownTable, indentPrefix: CharSequence = EMPTY_SEQUENCE, charWidthProvider: CharWidthProvider): SmartCharSequence {
val tableBalancer = SmartTableColumnBalancer(charWidthProvider)
var formattedTable = EditableCharSequence()
val pipeSequence = RepeatedCharSequence('|')
val endOfLine = RepeatedCharSequence('\n')
val space = RepeatedCharSequence(' ')
val pipePadding = if (settings.TABLE_SPACE_AROUND_PIPE) space else EMPTY_SEQUENCE // or empty if don't want padding around pipes
val alignMarker = RepeatedCharSequence(':')
var rowColumns = ArrayList<SmartCharSequence>()
var row = 0
val addLeadTrailPipes = settings.TABLE_LEAD_TRAIL_PIPES || !indentPrefix.isEmpty() || markdownTable.minColumns < 2
for (tableRow in markdownTable.rows) {
var formattedRow = EditableCharSequence()
if (addLeadTrailPipes) {
formattedRow.append(indentPrefix, pipeSequence)
} else {
formattedRow.append(indentPrefix)
}
val segments = tableRow.rowCells
var colIndex = 0
var col = 0
var lastSpan = 1
var lastColumnEmpty = false
while (colIndex < segments.size) {
val tableCell = segments[colIndex]
var columnChars:SmartCharSequence = SmartCharSequenceWrapper(tableCell.charSequence)
if (settings.TABLE_TRIM_CELLS) columnChars = columnChars.trim()
if (columnChars.isEmpty()) columnChars = columnChars.append(space)
val separatorParts = if (row == markdownTable.separatorRow) columnChars.extractGroupsSegmented(SEPARATOR_COLUMN_PATTERN) else null
assert(row != markdownTable.separatorRow || separatorParts != null, { "isSeparator but column does not match separator col" })
val formattedCol: SmartVariableCharSequence
if (separatorParts != null) {
val haveLeft = separatorParts.segments[2] != NULL_SEQUENCE
val haveRight = separatorParts.segments[4] != NULL_SEQUENCE
formattedCol = SmartVariableCharSequence(columnChars, SmartRepeatedCharSequence('-', 3 - haveLeft.ifElse(1, 0) - haveRight.ifElse(1, 0)), charWidthProvider)
formattedCol.leftPadChar = '-'
formattedCol.rightPadChar = '-'
when {
haveLeft && haveRight -> {
if (settings.TABLE_APPLY_COLUMN_ALIGNMENT) tableBalancer.alignment(colIndex, SmartImmutableData(TextAlignment.CENTER))
formattedCol.prefix = alignMarker
formattedCol.suffix = alignMarker
}
haveRight -> {
if (settings.TABLE_APPLY_COLUMN_ALIGNMENT) tableBalancer.alignment(colIndex, SmartImmutableData(TextAlignment.RIGHT))
formattedCol.suffix = alignMarker
}
else -> {
// when no alignment given use centered for header cells and left for body
if (settings.TABLE_APPLY_COLUMN_ALIGNMENT) {
val tableHeadingDefaultAlignment = !haveLeft && settings.TABLE_LEFT_ALIGN_MARKER != 1 || haveLeft && !haveRight && settings.TABLE_LEFT_ALIGN_MARKER == -1
tableBalancer.alignment(colIndex, SmartImmutableData(if (tableHeadingDefaultAlignment) TextAlignment.DEFAULT else TextAlignment.LEFT))
}
if (settings.TABLE_LEFT_ALIGN_MARKER == 1 || settings.TABLE_LEFT_ALIGN_MARKER == 0 && haveLeft) formattedCol.prefix = alignMarker
}
}
} else {
formattedCol = SmartVariableCharSequence(columnChars, columnChars, charWidthProvider)
if (addLeadTrailPipes || colIndex > 0) formattedCol.prefix = pipePadding
if (addLeadTrailPipes || colIndex < segments.size - 1) formattedCol.suffix = if (columnChars.length > 0 && columnChars[columnChars.length - 1] != ' ') pipePadding else EMPTY_SEQUENCE
}
// see if we have spanned columns
if (colIndex > 0) formattedRow.append(pipeSequence.repeat(lastSpan))
formattedRow.append(formattedCol)
rowColumns.add(formattedCol)
val colSpan = tableCell.colSpan
val widthOffset = if (colSpan > 1 && colIndex == segments.size - 1 && !addLeadTrailPipes) 1 else 0
val dataPoint = tableBalancer.width(col, formattedCol.lengthDataPoint, colSpan, widthOffset)
if (settings.TABLE_ADJUST_COLUMN_WIDTH) formattedCol.widthDataPoint = dataPoint
else if (settings.TABLE_TRIM_CELLS) formattedCol.width = columnChars.length
else formattedCol.width = tableCell.untrimmedWidth
if (settings.TABLE_APPLY_COLUMN_ALIGNMENT) formattedCol.alignmentDataPoint = tableBalancer.alignmentDataPoint(col, row < markdownTable.separatorRow)
lastSpan = colSpan
colIndex++
col += colSpan
lastColumnEmpty = columnChars.isBlank()
}
// here if we add pipes then add lastSpan, else lastSpan-1
if (addLeadTrailPipes) {
formattedRow.append(pipeSequence.repeat(lastSpan), endOfLine)
formattedTable.append(formattedRow)
} else {
formattedRow.append(if (lastSpan > 1 || lastColumnEmpty) pipeSequence.repeat(lastSpan) else EMPTY_SEQUENCE, endOfLine)
formattedTable.append(formattedRow)
}
row++
}
// take care of caption
var caption = markdownTable.caption
when (settings.TABLE_CAPTION) {
MarkdownTableFormatSettings.TABLE_CAPTION_ADD -> if (caption == null) caption = ""
MarkdownTableFormatSettings.TABLE_CAPTION_REMOVE_EMPTY -> if (caption?.isBlank() == true) caption = null
MarkdownTableFormatSettings.TABLE_CAPTION_REMOVE -> caption = null
else -> {
}
}
if (caption != null) {
when (settings.TABLE_CAPTION_SPACES) {
MarkdownTableFormatSettings.TABLE_CAPTION_SPACES_REMOVE -> caption = caption.trim()
MarkdownTableFormatSettings.TABLE_CAPTION_SPACES_ADD -> caption = " ${caption.trim()} "
else -> {
}
}
formattedTable.append("[$caption]\n")
}
tableBalancer.finalizeTable()
myAlignmentDataPoints = tableBalancer.columnAlignmentDataPoints
myColumnWidthDataPoints = tableBalancer.columnWidthDataPoints
return formattedTable.contents //.cachedProxy
}
companion object {
@JvmStatic
val SEPARATOR_COLUMN_PATTERN = "(\\s+)?(:)?(-{1,})(:)?(\\s+)?"
@JvmStatic
val SEPARATOR_COLUMN_PATTERN_REGEX = SEPARATOR_COLUMN_PATTERN.toRegex()
@JvmStatic
val SEPARATOR_COLUMN = SmartRepeatedCharSequence('-', 3)
@JvmStatic
val EMPTY_COLUMN = SmartRepeatedCharSequence(' ', 1)
fun parseTable(table: SmartCharSequence, caretOffset: Int, trimCells: Boolean): MarkdownTable {
val space = RepeatedCharSequence(' ')
var indentPrefix: CharSequence = EMPTY_SEQUENCE
val tableRows = table.splitPartsSegmented('\n', false)
var row = 0
val tableRowCells = ArrayList<TableRow>()
var offsetRow: Int? = null
var offsetCol: Int? = null
// see if there is an indentation prefix, these are always spaces in multiples of 4
var minIndent: Int? = null
for (line in tableRows.segments) {
val tableRow = SafeCharSequenceIndex(line)
val spaceCount = tableRow.tabExpandedColumnOf((tableRow.firstNonBlank - 1).minLimit(0), 4)
if (minIndent == null || minIndent > spaceCount) minIndent = spaceCount
}
val removeSpaces = ((minIndent ?: 0) / 4) * 4
val stripPrefix = if (removeSpaces > 0) "\\s{1,$removeSpaces}".toRegex() else "".toRegex()
if (removeSpaces > 0) {
indentPrefix = RepeatedCharSequence(' ', removeSpaces)
}
for (line in tableRows.segments) {
var rowText = line // line.trimEnd()
// remove the indent prefix
if (!indentPrefix.isEmpty()) {
rowText = rowText.removePrefix(stripPrefix) as SmartCharSequence
}
// remove leading pipes, and trailing pipes that are singles
if (rowText.length > 0 && rowText[0] == '|') rowText = rowText.subSequence(1, rowText.length)
if (rowText.length > 2 && rowText[rowText.length - 2] != '|' && rowText[rowText.length - 1] == '|') rowText = rowText.subSequence(0, rowText.length - 1)
val segments = rowText.splitPartsSegmented('|', false).segments
val tableColumns = ArrayList<TableCell>()
var col = 0
var hadSeparatorCols = false
var allSeparatorCols = true
while (col < segments.size) {
var column = segments[col]
val untrimmedWidth = if (trimCells) column.trim().length else column.length
val origColumn = if (column.isEmpty()) space else column
if (!column.isEmpty()) {
val colStart = column.trackedSourceLocation(0)
val colEnd = column.trackedSourceLocation(column.lastIndex)
if (!(colStart.offset <= caretOffset && caretOffset <= colEnd.offset + 1)) {
column = column.trim()
//println("caretOffset $caretOffset starCol: ${colStart.offset}, endCol: ${colEnd.offset}")
} else {
//println("> caretOffset $caretOffset starCol: ${colStart.offset}, endCol: ${colEnd.offset} <")
// trim spaces after caret
offsetCol = col
offsetRow = row
if (trimCells) {
column = column.trim()
} else {
val caretIndex = caretOffset - colStart.offset
column = column.subSequence(0, caretIndex).append(column.subSequence(caretIndex, column.length).trimEnd())
if (!column.isEmpty()) {
// can trim off leading since we may add spaces
val leadingSpaces = column.countLeading(' ', '\t').maxLimit(caretIndex)
if (leadingSpaces > 0) column = column.subSequence(leadingSpaces, column.length)
}
}
}
}
if (column.isEmpty()) column = column.append(origColumn.subSequence(0, 1))
val headerParts = column.extractGroupsSegmented(SEPARATOR_COLUMN_PATTERN)
if (headerParts != null) {
hadSeparatorCols = true
} else {
allSeparatorCols = false
}
// see if we have spanned columns
var span = 1
while (col + span < segments.size && segments[col + span].isEmpty()) span++
tableColumns.add(TableCell(column, untrimmedWidth, span))
col += span
}
val isSeparator = hadSeparatorCols && allSeparatorCols
tableRowCells.add(TableRow(tableColumns, isSeparator))
row++
}
return MarkdownTable(tableRowCells, null, indentPrefix, null, offsetRow, offsetCol)
}
}
}
| apache-2.0 | a54fa7dbb92c14f2ce6dc04a81d54e8f | 46.445483 | 202 | 0.589429 | 5.117608 | false | false | false | false |
Bombe/Sone | src/test/kotlin/net/pterodactylus/sone/template/ParserFilterTest.kt | 1 | 2752 | package net.pterodactylus.sone.template
import com.google.inject.Guice
import net.pterodactylus.sone.core.Core
import net.pterodactylus.sone.data.Sone
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.text.SoneTextParser
import net.pterodactylus.sone.text.SoneTextParserContext
import net.pterodactylus.util.template.TemplateContext
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.emptyIterable
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.Matchers.sameInstance
import org.junit.Test
import org.mockito.ArgumentCaptor.forClass
import org.mockito.Mockito.eq
import org.mockito.Mockito.verify
/**
* Unit test for [ParserFilter].
*/
class ParserFilterTest {
companion object {
private const val SONE_IDENTITY = "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"
}
private val core = mock<Core>()
private val sone = setupSone(SONE_IDENTITY)
private val soneTextParser = mock<SoneTextParser>()
private val templateContext = TemplateContext()
private val parameters = mutableMapOf<String, Any?>()
private val filter = ParserFilter(core, soneTextParser)
private fun setupSone(identity: String): Sone {
val sone = mock<Sone>()
whenever(sone.id).thenReturn(identity)
whenever(core.getSone(identity)).thenReturn(sone)
return sone
}
@Test
fun `parsing null returns an empty iterable`() {
assertThat(filter.format(templateContext, null, mutableMapOf()) as Iterable<*>, emptyIterable())
}
@Test
fun `given sone is used to create parser context`() {
setupSoneAndVerifyItIsUsedInContext(sone, sone)
}
@Test
fun `sone with given sone ID is used to create parser context`() {
setupSoneAndVerifyItIsUsedInContext(SONE_IDENTITY, sone)
}
private fun setupSoneAndVerifyItIsUsedInContext(soneOrSoneId: Any, sone: Sone) {
parameters.put("sone", soneOrSoneId)
filter.format(templateContext, "text", parameters)
val context = forClass(SoneTextParserContext::class.java)
verify(soneTextParser).parse(eq<String>("text") ?: "", context.capture())
assertThat(context.value.postingSone, equalTo(sone))
}
@Test
fun `parser filter can be created by guice`() {
val injector = Guice.createInjector(
Core::class.isProvidedByMock(),
SoneTextParser::class.isProvidedByMock()
)
assertThat(injector.getInstance<ParserFilter>(), notNullValue())
}
@Test
fun `parser filter is created as singleton`() {
val injector = Guice.createInjector(
Core::class.isProvidedByMock(),
SoneTextParser::class.isProvidedByMock()
)
val firstInstance = injector.getInstance<ParserFilter>()
val secondInstance = injector.getInstance<ParserFilter>()
assertThat(firstInstance, sameInstance(secondInstance))
}
}
| gpl-3.0 | a50ed3b3c1ce59283202208b4666173d | 30.632184 | 98 | 0.772892 | 3.728997 | false | true | false | false |
MichaelObi/PaperPlayer | app/src/main/java/xyz/michaelobi/paperplayer/presentation/musiclibrary/fragment/miniplayer/MiniPlayerFragment.kt | 1 | 4678 | /*
* MIT License
*
* Copyright (c) 2017 MIchael Obi
*
* 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 xyz.michaelobi.paperplayer.presentation.musiclibrary.fragment.miniplayer
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import xyz.michaelobi.paperplayer.R
import xyz.michaelobi.paperplayer.injection.Injector
import xyz.michaelobi.paperplayer.playback.events.PlaybackState
import xyz.michaelobi.paperplayer.presentation.player.PlayerActivity
import xyz.michaelobi.paperplayer.widget.PlayPauseButton
/**
* PaperPlayer
* Michael Obi
* 08 04 2017 10:34 AM
*/
class MiniPlayerFragment : androidx.fragment.app.Fragment(), MiniPlayerContract.View, View.OnClickListener {
lateinit var presenter: MiniPlayerPresenter
var miniPlayerSongName: TextView? = null
var miniPlayerSongArtist: TextView? = null
var miniAlbumArt: ImageView? = null
var playPauseButton: PlayPauseButton? = null
var miniPlayer: View? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.mini_player, container, false)
presenter = MiniPlayerPresenter(Injector.provideMusicRepository(activity))
presenter.attachView(this)
miniPlayerSongName = view.findViewById(R.id.song_name_mini) as TextView?
miniPlayer = view.findViewById(R.id.mini_player)
miniPlayerSongArtist = view.findViewById(R.id.song_artist_mini) as TextView?
miniAlbumArt = view.findViewById(R.id.album_art_mini) as ImageView?
playPauseButton = view.findViewById(R.id.play_pause) as PlayPauseButton?
playPauseButton?.setOnClickListener(this)
miniPlayer?.setOnClickListener(this)
return view
}
override fun onResume() {
super.onResume()
presenter.initialize()
}
override fun onDestroyView() {
super.onDestroyView()
presenter.detachView()
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.play_pause -> presenter.onPlayButtonClicked()
else -> {
val intent = Intent(activity, PlayerActivity::class.java)
startActivity(intent)
}
}
}
override fun updateSongArt(uri: String?) {
if (uri.isNullOrEmpty()) {
val defaultAlbumArt: Drawable? = ContextCompat.getDrawable(requireActivity(), R.drawable
.default_artwork_dark)
miniAlbumArt?.setImageDrawable(defaultAlbumArt)
return
}
val options = BitmapFactory.Options()
options.inJustDecodeBounds = false
options.inPreferredConfig = Bitmap.Config.ARGB_8888
options.inDither = true
val artWork = BitmapDrawable(resources, BitmapFactory.decodeFile(uri, options))
miniAlbumArt?.setImageDrawable(artWork)
}
override fun updateTitleAndArtist(playbackState: PlaybackState) {
val song = playbackState.song
miniPlayerSongName?.text = song?.title
miniPlayerSongArtist?.text = song?.artist
}
override fun updatePlayPauseButton(isPlaying: Boolean) {
if (isPlaying) playPauseButton?.pause() else playPauseButton?.play()
}
} | mit | 15b7bd0f2c0dae9b0f41f1bc1d2c5ec9 | 38.652542 | 116 | 0.726379 | 4.627102 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ExtensionContainerExtensions.kt | 1 | 4241 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl
import org.gradle.api.Incubating
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.plugins.ExtensionContainer
import kotlin.reflect.KProperty
/**
* Looks for the extension of a given name. If none found it will throw an exception.
*
* @param name extension name
* @return extension
* @throws [UnknownDomainObjectException] When the given extension is not found.
*
* @see [ExtensionContainer.getByName]
*/
operator fun ExtensionContainer.get(name: String): Any =
getByName(name)
/**
* Looks for the extension of a given name and casts it to the expected type [T].
*
* If none found it will throw an [UnknownDomainObjectException].
* If the extension is found but cannot be cast to the expected type it will throw an [IllegalStateException].
*
* @param name extension name
* @return extension, never null
* @throws [UnknownDomainObjectException] When the given extension is not found.
* @throws [IllegalStateException] When the given extension cannot be cast to the expected type.
*/
@Suppress("extension_shadowed_by_member")
inline fun <reified T : Any> ExtensionContainer.getByName(name: String) =
getByName(name).let {
it as? T
?: throw IllegalStateException(
"Element '$name' of type '${it::class.java.name}' from container '$this' cannot be cast to '${T::class.qualifiedName}'.")
}
/**
* Delegated property getter that locates extensions.
*/
inline operator fun <reified T : Any> ExtensionContainer.getValue(thisRef: Any?, property: KProperty<*>): T =
getByName<T>(property.name)
/**
* Adds a new extension to this container.
*
* @param T the public type of the added extension
* @param name the name of the extension
* @param extension the extension instance
*
* @throws IllegalArgumentException When an extension with the given name already exists.
*
* @see [ExtensionContainer.add]
* @since 5.0
*/
@Incubating
@Suppress("extension_shadowed_by_member")
inline fun <reified T : Any> ExtensionContainer.add(name: String, extension: T) {
add(typeOf<T>(), name, extension)
}
/**
* Creates and adds a new extension to this container.
*
* @param T the instance type of the new extension
* @param name the extension's name
* @param constructionArguments construction arguments
* @return the created instance
*
* @see [ExtensionContainer.create]
* @since 5.0
*/
@Incubating
inline fun <reified T : Any> ExtensionContainer.create(name: String, vararg constructionArguments: Any): T =
create(name, T::class.java, *constructionArguments)
/**
* Looks for the extension of a given type.
*
* @param T the extension type
* @return the extension
* @throws UnknownDomainObjectException when no matching extension can be found
*
* @see [ExtensionContainer.getByType]
* @since 5.0
*/
@Incubating
inline fun <reified T : Any> ExtensionContainer.getByType(): T =
getByType(typeOf<T>())
/**
* Looks for the extension of a given type.
*
* @param T the extension type
* @return the extension or null if not found
*
* @see [ExtensionContainer.findByType]
* @since 5.0
*/
@Incubating
inline fun <reified T : Any> ExtensionContainer.findByType(): T? =
findByType(typeOf<T>())
/**
* Looks for the extension of the specified type and configures it with the supplied action.
*
* @param T the extension type
* @param action the configuration action
*
* @see [ExtensionContainer.configure]
* @since 5.0
*/
@Incubating
inline fun <reified T : Any> ExtensionContainer.configure(noinline action: T.() -> Unit) {
configure(typeOf<T>(), action)
}
| apache-2.0 | c9addfbf5d29d8663fd42c4c10736935 | 28.866197 | 137 | 0.722235 | 4.105518 | false | false | false | false |
xfournet/intellij-community | platform/vcs-impl/src/com/intellij/vfs/AsyncVfsEventsPostProcessorImpl.kt | 10 | 2901 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vfs
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.annotations.CalledInBackground
class AsyncVfsEventsPostProcessorImpl : AsyncVfsEventsPostProcessor, Disposable {
private val LOG = logger<AsyncVfsEventsPostProcessorImpl>()
private val queue = QueueProcessor<List<VFileEvent>> { events -> processEvents(events) }
private val messageBus = ApplicationManager.getApplication().messageBus
private data class ListenerAndDisposable(val listener: AsyncVfsEventsListener, val disposable: Disposable)
private val listeners = ContainerUtil.createConcurrentList<ListenerAndDisposable>()
init {
messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
queue.add(events)
}
})
}
override fun addListener(listener: AsyncVfsEventsListener, disposable: Disposable) {
val element = ListenerAndDisposable(listener, disposable)
Disposer.register(disposable, Disposable { listeners.remove(element) })
listeners.add(element)
}
override fun dispose() {
queue.clear()
listeners.clear()
}
@CalledInBackground
private fun processEvents(events: List<VFileEvent>) {
for ((listener, parentDisposable) in listeners) {
try {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(parentDisposable, Runnable {
listener.filesChanged(events)
})
}
catch(pce: ProcessCanceledException) {
// move to the next task
}
catch(e: Throwable) {
LOG.error(e)
}
}
}
}
| apache-2.0 | 2a68f78c519f69b3d2fd2695a99736f8 | 36.675325 | 108 | 0.767322 | 4.694175 | false | false | false | false |
HendraAnggrian/kota | kota/src/SystemServices.kt | 1 | 17167 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.accounts.AccountManager
import android.app.*
import android.app.admin.DevicePolicyManager
import android.app.job.JobScheduler
import android.app.usage.NetworkStatsManager
import android.app.usage.UsageStatsManager
import android.appwidget.AppWidgetManager
import android.bluetooth.BluetoothManager
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.*
import android.content.RestrictionsManager
import android.content.pm.LauncherApps
import android.hardware.ConsumerIrManager
import android.hardware.SensorManager
import android.hardware.display.DisplayManager
import android.hardware.fingerprint.FingerprintManager
import android.hardware.input.InputManager
import android.hardware.usb.UsbManager
import android.location.LocationManager
import android.media.AudioManager
import android.media.MediaRouter
import android.media.midi.MidiManager
import android.media.projection.MediaProjectionManager
import android.media.session.MediaSessionManager
import android.media.tv.TvInputManager
import android.net.ConnectivityManager
import android.net.nsd.NsdManager
import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pManager
import android.nfc.NfcManager
import android.os.*
import android.os.storage.StorageManager
import android.print.PrintManager
import android.support.annotation.RequiresApi
import android.telecom.TelecomManager
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import android.view.inputmethod.InputMethodManager
import android.view.textservice.TextServicesManager
@PublishedApi
internal inline fun <reified T> Context.getSystemServiceNullable(name: String): T? = getSystemService(name) as? T
inline val Context.accessibilityManager: AccessibilityManager? get() = getSystemServiceNullable(ACCESSIBILITY_SERVICE)
inline val Fragment.accessibilityManager: AccessibilityManager? get() = activity.accessibilityManager
inline val Dialog.accessibilityManager: AccessibilityManager? get() = context.accessibilityManager
inline val Context.accountManager: AccountManager? get() = getSystemServiceNullable(ACCOUNT_SERVICE)
inline val Fragment.accountManager: AccountManager? get() = activity.accountManager
inline val Dialog.accountManager: AccountManager? get() = context.accountManager
inline val Context.activityManager: ActivityManager? get() = getSystemServiceNullable(ACTIVITY_SERVICE)
inline val Fragment.activityManager: ActivityManager? get() = activity.activityManager
inline val Dialog.activityManager: ActivityManager? get() = context.activityManager
inline val Context.alarmManager: AlarmManager? get() = getSystemServiceNullable(ALARM_SERVICE)
inline val Fragment.alarmManager: AlarmManager? get() = activity.alarmManager
inline val Dialog.alarmManager: AlarmManager? get() = context.alarmManager
inline val Context.appOpsManager: AppOpsManager? @RequiresApi(19) get() = getSystemServiceNullable(APP_OPS_SERVICE)
inline val Fragment.appOpsManager: AppOpsManager? @RequiresApi(19) get() = activity.appOpsManager
inline val Dialog.appOpsManager: AppOpsManager? @RequiresApi(19) get() = context.appOpsManager
inline val Context.appWidgetManager: AppWidgetManager? @RequiresApi(21) get() = getSystemServiceNullable(APPWIDGET_SERVICE)
inline val Fragment.appWidgetManager: AppWidgetManager? @RequiresApi(21) get() = activity.appWidgetManager
inline val Dialog.appWidgetManager: AppWidgetManager? @RequiresApi(21) get() = context.appWidgetManager
inline val Context.audioManager: AudioManager? get() = getSystemServiceNullable(AUDIO_SERVICE)
inline val Fragment.audioManager: AudioManager? get() = activity.audioManager
inline val Dialog.audioManager: AudioManager? get() = context.audioManager
inline val Context.batteryManager: BatteryManager? @RequiresApi(21) get() = getSystemServiceNullable(BATTERY_SERVICE)
inline val Fragment.batteryManager: BatteryManager? @RequiresApi(21) get() = activity.batteryManager
inline val Dialog.batteryManager: BatteryManager? @RequiresApi(21) get() = context.batteryManager
inline val Context.bluetoothManager: BluetoothManager? @RequiresApi(18) get() = getSystemServiceNullable(BLUETOOTH_SERVICE)
inline val Fragment.bluetoothManager: BluetoothManager? @RequiresApi(18) get() = activity.bluetoothManager
inline val Dialog.bluetoothManager: BluetoothManager? @RequiresApi(18) get() = context.bluetoothManager
inline val Context.clipboardManager: ClipboardManager? get() = getSystemServiceNullable(CLIPBOARD_SERVICE)
inline val Fragment.clipboardManager: ClipboardManager? get() = activity.clipboardManager
inline val Dialog.clipboardManager: ClipboardManager? get() = context.clipboardManager
inline val Context.connectivityManager: ConnectivityManager? get() = getSystemServiceNullable(CONNECTIVITY_SERVICE)
inline val Fragment.connectivityManager: ConnectivityManager? get() = activity.connectivityManager
inline val Dialog.connectivityManager: ConnectivityManager? get() = context.connectivityManager
inline val Context.consumerIrManager: ConsumerIrManager? @RequiresApi(19) get() = getSystemServiceNullable(CONSUMER_IR_SERVICE)
inline val Fragment.consumerIrManager: ConsumerIrManager? @RequiresApi(19) get() = activity.consumerIrManager
inline val Dialog.consumerIrManager: ConsumerIrManager? @RequiresApi(19) get() = context.consumerIrManager
inline val Context.devicePolicyManager: DevicePolicyManager? get() = getSystemServiceNullable(DEVICE_POLICY_SERVICE)
inline val Fragment.devicePolicyManager: DevicePolicyManager? get() = activity.devicePolicyManager
inline val Dialog.devicePolicyManager: DevicePolicyManager? get() = context.devicePolicyManager
inline val Context.displayManager: DisplayManager? @RequiresApi(17) get() = getSystemServiceNullable(DISPLAY_SERVICE)
inline val Fragment.displayManager: DisplayManager? @RequiresApi(17) get() = activity.displayManager
inline val Dialog.displayManager: DisplayManager? @RequiresApi(17) get() = context.displayManager
inline val Context.downloadManager: DownloadManager? get() = getSystemServiceNullable(DOWNLOAD_SERVICE)
inline val Fragment.downloadManager: DownloadManager? get() = activity.downloadManager
inline val Dialog.downloadManager: DownloadManager? get() = context.downloadManager
inline val Context.dropBoxManager: DropBoxManager? get() = getSystemServiceNullable(DROPBOX_SERVICE)
inline val Fragment.dropBoxManager: DropBoxManager? get() = activity.dropBoxManager
inline val Dialog.dropBoxManager: DropBoxManager? get() = context.dropBoxManager
inline val Context.fingerprintManager: FingerprintManager? @RequiresApi(23) get() = getSystemServiceNullable(FINGERPRINT_SERVICE)
inline val Fragment.fingerprintManager: FingerprintManager? @RequiresApi(23) get() = activity.fingerprintManager
inline val Dialog.fingerprintManager: FingerprintManager? @RequiresApi(23) get() = context.fingerprintManager
inline val Context.inputMethodManager: InputMethodManager? get() = getSystemServiceNullable(INPUT_METHOD_SERVICE)
inline val Fragment.inputMethodManager: InputMethodManager? get() = activity.inputMethodManager
inline val Dialog.inputMethodManager: InputMethodManager? get() = context.inputMethodManager
inline val Context.inputManager: InputManager? @RequiresApi(16) get() = getSystemServiceNullable(INPUT_SERVICE)
inline val Fragment.inputManager: InputManager? @RequiresApi(16) get() = activity.inputManager
inline val Dialog.inputManager: InputManager? @RequiresApi(16) get() = context.inputManager
inline val Context.jobScheduler: JobScheduler? @RequiresApi(21) get() = getSystemServiceNullable(JOB_SCHEDULER_SERVICE)
inline val Fragment.jobScheduler: JobScheduler? @RequiresApi(21) get() = activity.jobScheduler
inline val Dialog.jobScheduler: JobScheduler? @RequiresApi(21) get() = context.jobScheduler
inline val Context.keyguardManager: KeyguardManager? get() = getSystemServiceNullable(KEYGUARD_SERVICE)
inline val Fragment.keyguardManager: KeyguardManager? get() = activity.keyguardManager
inline val Dialog.keyguardManager: KeyguardManager? get() = context.keyguardManager
inline val Context.launcherApps: LauncherApps? @RequiresApi(21) get() = getSystemServiceNullable(LAUNCHER_APPS_SERVICE)
inline val Fragment.launcherApps: LauncherApps? @RequiresApi(21) get() = activity.launcherApps
inline val Dialog.launcherApps: LauncherApps? @RequiresApi(21) get() = context.launcherApps
inline val Context.layoutInflater: LayoutInflater get() = LayoutInflater.from(this)
inline val Context.locationManager: LocationManager? get() = getSystemServiceNullable(LOCATION_SERVICE)
inline val Fragment.locationManager: LocationManager? get() = activity.locationManager
inline val Dialog.locationManager: LocationManager? get() = context.locationManager
inline val Context.mediaProjectionManager: MediaProjectionManager? @RequiresApi(21) get() = getSystemServiceNullable(MEDIA_PROJECTION_SERVICE)
inline val Fragment.mediaProjectionManager: MediaProjectionManager? @RequiresApi(21) get() = activity.mediaProjectionManager
inline val Dialog.mediaProjectionManager: MediaProjectionManager? @RequiresApi(21) get() = context.mediaProjectionManager
inline val Context.mediaRouter: MediaRouter? @RequiresApi(16) get() = getSystemServiceNullable(MEDIA_ROUTER_SERVICE)
inline val Fragment.mediaRouter: MediaRouter? @RequiresApi(16) get() = activity.mediaRouter
inline val Dialog.mediaRouter: MediaRouter? @RequiresApi(16) get() = context.mediaRouter
inline val Context.mediaSessionManager: MediaSessionManager? @RequiresApi(21) get() = getSystemServiceNullable(MEDIA_SESSION_SERVICE)
inline val Fragment.mediaSessionManager: MediaSessionManager? @RequiresApi(21) get() = activity.mediaSessionManager
inline val Dialog.mediaSessionManager: MediaSessionManager? @RequiresApi(21) get() = context.mediaSessionManager
inline val Context.midiManager: MidiManager? @RequiresApi(23) get() = getSystemServiceNullable(MIDI_SERVICE)
inline val Fragment.midiManager: MidiManager? @RequiresApi(23) get() = activity.midiManager
inline val Dialog.midiManager: MidiManager? @RequiresApi(23) get() = context.midiManager
inline val Context.networkStatsManager: NetworkStatsManager? @RequiresApi(23) get() = getSystemServiceNullable(NETWORK_STATS_SERVICE)
inline val Fragment.networkStatsManager: NetworkStatsManager? @RequiresApi(23) get() = activity.networkStatsManager
inline val Dialog.networkStatsManager: NetworkStatsManager? @RequiresApi(23) get() = context.networkStatsManager
inline val Context.nfcManager: NfcManager? get() = getSystemServiceNullable(NFC_SERVICE)
inline val Fragment.nfcManager: NfcManager? get() = activity.nfcManager
inline val Dialog.nfcManager: NfcManager? get() = context.nfcManager
inline val Context.notificationManager: NotificationManager? get() = getSystemServiceNullable(NOTIFICATION_SERVICE)
inline val Fragment.notificationManager: NotificationManager? get() = activity.notificationManager
inline val Dialog.notificationManager: NotificationManager? get() = context.notificationManager
inline val Context.nsdManager: NsdManager? @RequiresApi(16) get() = getSystemServiceNullable(NSD_SERVICE)
inline val Fragment.nsdManager: NsdManager? @RequiresApi(16) get() = activity.nsdManager
inline val Dialog.nsdManager: NsdManager? @RequiresApi(16) get() = context.nsdManager
inline val Context.powerManager: PowerManager? get() = getSystemServiceNullable(POWER_SERVICE)
inline val Fragment.powerManager: PowerManager? get() = activity.powerManager
inline val Dialog.powerManager: PowerManager? get() = context.powerManager
inline val Context.printManager: PrintManager? @RequiresApi(19) get() = getSystemServiceNullable(PRINT_SERVICE)
inline val Fragment.printManager: PrintManager? @RequiresApi(19) get() = activity.printManager
inline val Dialog.printManager: PrintManager? @RequiresApi(19) get() = context.printManager
inline val Context.restrictionsManager: RestrictionsManager? @RequiresApi(21) get() = getSystemServiceNullable(RESTRICTIONS_SERVICE)
inline val Fragment.restrictionsManager: RestrictionsManager? @RequiresApi(21) get() = activity.restrictionsManager
inline val Dialog.restrictionsManager: RestrictionsManager? @RequiresApi(21) get() = context.restrictionsManager
inline val Context.searchManager: SearchManager? get() = getSystemServiceNullable(SEARCH_SERVICE)
inline val Fragment.searchManager: SearchManager? get() = activity.searchManager
inline val Dialog.searchManager: SearchManager? get() = context.searchManager
inline val Context.sensorManager: SensorManager? get() = getSystemServiceNullable(SENSOR_SERVICE)
inline val Fragment.sensorManager: SensorManager? get() = activity.sensorManager
inline val Dialog.sensorManager: SensorManager? get() = context.sensorManager
inline val Context.storageManager: StorageManager? get() = getSystemServiceNullable(STORAGE_SERVICE)
inline val Fragment.storageManager: StorageManager? get() = activity.storageManager
inline val Dialog.storageManager: StorageManager? get() = context.storageManager
inline val Context.subscriptionManager: SubscriptionManager? @RequiresApi(22) get() = getSystemServiceNullable(TELEPHONY_SUBSCRIPTION_SERVICE)
inline val Fragment.subscriptionManager: SubscriptionManager? @RequiresApi(22) get() = activity.subscriptionManager
inline val Dialog.subscriptionManager: SubscriptionManager? @RequiresApi(22) get() = context.subscriptionManager
inline val Context.telecomManager: TelecomManager? @RequiresApi(21) get() = getSystemServiceNullable(TELECOM_SERVICE)
inline val Fragment.telecomManager: TelecomManager? @RequiresApi(21) get() = activity.telecomManager
inline val Dialog.telecomManager: TelecomManager? @RequiresApi(21) get() = context.telecomManager
inline val Context.telephonyManager: TelephonyManager? get() = getSystemServiceNullable(TELEPHONY_SERVICE)
inline val Fragment.telephonyManager: TelephonyManager? get() = activity.telephonyManager
inline val Dialog.telephonyManager: TelephonyManager? get() = context.telephonyManager
inline val Context.textServicesManager: TextServicesManager? get() = getSystemServiceNullable(TEXT_SERVICES_MANAGER_SERVICE)
inline val Fragment.textServicesManager: TextServicesManager? get() = activity.textServicesManager
inline val Dialog.textServicesManager: TextServicesManager? get() = context.textServicesManager
inline val Context.tvInputManager: TvInputManager? @RequiresApi(21) get() = getSystemServiceNullable(TV_INPUT_SERVICE)
inline val Fragment.tvInputManager: TvInputManager? @RequiresApi(21) get() = activity.tvInputManager
inline val Dialog.tvInputManager: TvInputManager? @RequiresApi(21) get() = context.tvInputManager
inline val Context.uiModeManager: UiModeManager? get() = getSystemServiceNullable(UI_MODE_SERVICE)
inline val Fragment.uiModeManager: UiModeManager? get() = activity.uiModeManager
inline val Dialog.uiModeManager: UiModeManager? get() = context.uiModeManager
inline val Context.usageStatsManager: UsageStatsManager? @RequiresApi(22) get() = getSystemServiceNullable(USAGE_STATS_SERVICE)
inline val Fragment.usageStatsManager: UsageStatsManager? @RequiresApi(22) get() = activity.usageStatsManager
inline val Dialog.usageStatsManager: UsageStatsManager? @RequiresApi(22) get() = context.usageStatsManager
inline val Context.usbManager: UsbManager? get() = getSystemServiceNullable(USB_SERVICE)
inline val Fragment.usbManager: UsbManager? get() = activity.usbManager
inline val Dialog.usbManager: UsbManager? get() = context.usbManager
inline val Context.userManager: UserManager? @RequiresApi(17) get() = getSystemServiceNullable(USER_SERVICE)
inline val Fragment.userManager: UserManager? @RequiresApi(17) get() = activity.userManager
inline val Dialog.userManager: UserManager? @RequiresApi(17) get() = context.userManager
inline val Context.vibrator: Vibrator? get() = getSystemServiceNullable(VIBRATOR_SERVICE)
inline val Fragment.vibrator: Vibrator? get() = activity.vibrator
inline val Dialog.vibrator: Vibrator? get() = context.vibrator
inline val Context.wallpaperManager: WallpaperManager? get() = getSystemServiceNullable(WALLPAPER_SERVICE)
inline val Fragment.wallpaperManager: WallpaperManager? get() = activity.wallpaperManager
inline val Dialog.wallpaperManager: WallpaperManager? get() = context.wallpaperManager
inline val Context.wifiManager: WifiManager? get() = applicationContext.getSystemServiceNullable(WIFI_SERVICE)
inline val Fragment.wifiManager: WifiManager? get() = activity.wifiManager
inline val Dialog.wifiManager: WifiManager? get() = context.wifiManager
inline val Context.wifiP2pManager: WifiP2pManager? get() = getSystemServiceNullable(WIFI_P2P_SERVICE)
inline val Fragment.wifiP2pManager: WifiP2pManager? get() = activity.wifiP2pManager
inline val Dialog.wifiP2pManager: WifiP2pManager? get() = context.wifiP2pManager
inline val Context.windowManager: WindowManager? get() = getSystemServiceNullable(WINDOW_SERVICE)
inline val Fragment.windowManager: WindowManager? get() = activity.windowManager
inline val Dialog.windowManager: WindowManager? get() = context.windowManager | apache-2.0 | 979a3c9e2837f8f6df5e64ae687503c0 | 66.0625 | 142 | 0.834217 | 4.911874 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UIPixelLine.kt | 1 | 2940 | package com.yy.codex.uikit
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.AttributeSet
import android.view.View
/**
* Created by cuiminghui on 2017/1/18.
*/
class UIPixelLine : UIView {
constructor(context: Context, view: View) : super(context, view) {}
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
}
var color = UIColor.blackColor
set(value) {
field = value
invalidate()
}
var vertical = false
set(value) {
field = value
invalidate()
}
var contentInsets: UIEdgeInsets = UIEdgeInsets.zero
set(value) {
field = value
invalidate()
}
override fun prepareProps(attrs: AttributeSet) {
super.prepareProps(attrs)
val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.UIPixelLine, 0, 0)
typedArray.getBoolean(R.styleable.UIPixelLine_pixelline_vertical, false)?.let {
initializeAttributes.put("UIPixelLine.vertical", it)
}
typedArray.getColor(R.styleable.UIPixelLine_pixelline_color, -1)?.let {
if (it != -1) {
initializeAttributes.put("UIPixelLine.color", UIColor(it))
}
}
}
override fun resetProps() {
super.resetProps()
initializeAttributes?.let {
(it["UIPixelLine.vertical"] as? Boolean)?.let {
vertical = it
}
(it["UIPixelLine.color"] as? UIColor)?.let {
color = it
}
}
}
private val paint = Paint()
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.color = color.toInt()
paint.strokeWidth = 1.0f
if (vertical) {
if (contentInsets.right > 0) {
canvas.drawLine((canvas.width - 1.0).toFloat(), 0f, (canvas.width - 1.0).toFloat(), canvas.height.toFloat(), paint)
}
else {
canvas.drawLine(0f, 0f, 0f, canvas.height.toFloat(), paint)
}
}
else {
if (contentInsets.bottom > 0) {
canvas.drawLine(0f, (canvas.height - 1.0).toFloat(), canvas.width.toFloat(), (canvas.height - 1.0).toFloat(), paint)
}
else {
canvas.drawLine(0f, 0f, canvas.width.toFloat(), 0f, paint)
}
}
}
}
| gpl-3.0 | 6e52fb8b40e779f4aef6dd69ebf20858 | 29.625 | 144 | 0.587415 | 4.248555 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UISwipeGestureRecognizer.kt | 1 | 4416 | package com.yy.codex.uikit
/**
* Created by cuiminghui on 2017/1/13.
*/
class UISwipeGestureRecognizer : UIGestureRecognizer {
enum class Direction {
Right,
Left,
Up,
Down
}
var direction = Direction.Right
private var originalPoint = CGPoint(0.0, 0.0)
private var velocityPoint = CGPoint(0.0, 0.0)
constructor(target: Any, selector: String) : super(target, selector) {}
constructor(triggerBlock: Runnable) : super(triggerBlock) {}
override fun touchesBegan(touches: List<UITouch>, event: UIEvent) {
super.touchesBegan(touches, event)
if (touches.size > 0) {
originalPoint = touches[0].absolutePoint
} else {
state = UIGestureRecognizerState.Failed
}
}
override fun touchesMoved(touches: List<UITouch>, event: UIEvent) {
if (touches.size <= 0) {
state = UIGestureRecognizerState.Failed
return
}
if (state == UIGestureRecognizerState.Possible) {
resetVelocity(touches)
}
super.touchesMoved(touches, event)
if (direction == Direction.Right) {
val distance = touches[0].absolutePoint.x - originalPoint.x
if (distance < -22.0) {
state = UIGestureRecognizerState.Failed
} else {
if (distance > 100.0 && velocityPoint.x > 1000.0) {
state = UIGestureRecognizerState.Ended
sendActions()
} else if (velocityPoint.x > 500.0) {
state = UIGestureRecognizerState.Ended
sendActions()
}
}
} else if (direction == Direction.Left) {
val distance = touches[0].absolutePoint.x - originalPoint.x
if (distance > 22.0) {
state = UIGestureRecognizerState.Failed
} else {
if (distance < -100.0 && velocityPoint.x < -1000.0) {
state = UIGestureRecognizerState.Ended
sendActions()
} else if (velocityPoint.x < -500.0) {
state = UIGestureRecognizerState.Ended
sendActions()
}
}
} else if (direction == Direction.Down) {
val distance = touches[0].absolutePoint.y - originalPoint.y
if (distance < -22.0) {
state = UIGestureRecognizerState.Failed
} else {
if (distance > 100.0 && velocityPoint.y > 1000.0) {
state = UIGestureRecognizerState.Ended
sendActions()
} else if (velocityPoint.y > 500.0) {
state = UIGestureRecognizerState.Ended
sendActions()
}
}
} else if (direction == Direction.Up) {
val distance = touches[0].absolutePoint.y - originalPoint.y
if (distance > 22.0) {
state = UIGestureRecognizerState.Failed
} else {
if (distance < -100.0 && velocityPoint.y < -1000.0) {
state = UIGestureRecognizerState.Ended
sendActions()
} else if (velocityPoint.y < -500.0) {
state = UIGestureRecognizerState.Ended
sendActions()
}
}
}
}
override fun touchesEnded(touches: List<UITouch>, event: UIEvent) {
super.touchesEnded(touches, event)
if (state != UIGestureRecognizerState.Ended) {
state = UIGestureRecognizerState.Failed
}
}
fun velocity(): CGPoint {
return velocityPoint
}
private fun resetVelocity(nextTouches: List<UITouch>) {
if (lastPoints.size > 0 && nextTouches.size > 0) {
val ts = (nextTouches[0].timestamp - lastPoints[0].timestamp) / 1000.0
if (ts == 0.0) {
} else {
val vx = (nextTouches[0].absolutePoint.x - lastPoints[0].absolutePoint.x) / ts
val vy = (nextTouches[0].absolutePoint.y - lastPoints[0].absolutePoint.y) / ts
velocityPoint = CGPoint(vx, vy)
}
}
}
override fun sendActions() {
if (state == UIGestureRecognizerState.Cancelled) {
return
}
super.sendActions()
}
}
| gpl-3.0 | 90f717aef6ac1385effd89939151d0ed | 33.5 | 94 | 0.528759 | 4.794788 | false | false | false | false |
google/ksp | integration-tests/src/test/resources/incremental-multi-chain/processors/src/main/kotlin/Aggregator.kt | 1 | 1503 | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import java.io.OutputStreamWriter
class Aggregator : SymbolProcessor {
lateinit var codeGenerator: CodeGenerator
lateinit var logger: KSPLogger
fun init(
options: Map<String, String>,
kotlinVersion: KotlinVersion,
codeGenerator: CodeGenerator,
logger: KSPLogger,
) {
this.codeGenerator = codeGenerator
this.logger = logger
}
override fun process(resolver: Resolver): List<KSAnnotated> {
val impls = resolver.getSymbolsWithAnnotation("Impl").map { it as KSDeclaration }.toList()
if (impls.isNotEmpty()) {
val names = impls.map { it.simpleName.asString() }.sorted()
OutputStreamWriter(
codeGenerator.createNewFile(
Dependencies(true), "", "AllImpls"
)
).use {
it.write("class AllImpls {\n")
it.write(" override fun toString() = \"$names\"\n")
it.write("}\n")
}
codeGenerator.associate(impls.map { it.containingFile!! }.toList(), "", "AllImpls")
}
return emptyList()
}
}
class AggregatorProvider : SymbolProcessorProvider {
override fun create(
env: SymbolProcessorEnvironment,
): SymbolProcessor {
return Aggregator().apply {
init(env.options, env.kotlinVersion, env.codeGenerator, env.logger)
}
}
}
| apache-2.0 | 714d9e4651ccf39635b618dcb7b28bd1 | 31.673913 | 98 | 0.599468 | 4.993355 | false | false | false | false |
JoosungPark/Leaning-Kotlin-Android | app/src/main/java/ma/sdop/weatherapp/data/server/ForecastServer.kt | 1 | 881 | package ma.sdop.weatherapp.data.server
import ma.sdop.weatherapp.domain.datasource.ForecastDataSource
import ma.sdop.weatherapp.data.database.ForecastDb
import ma.sdop.weatherapp.domain.model.Forecast
import ma.sdop.weatherapp.domain.model.ForecastList
/**
* Created by parkjoosung on 2017. 4. 27..
*/
class ForecastServer(val dataMapper: ServerDataMapper = ServerDataMapper(), val forecastDb: ForecastDb = ForecastDb()) : ForecastDataSource {
override fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList? {
val result = ForecastByZipCodeRequest(zipCode).execute()
val converted = dataMapper.convertToDomain(zipCode, result)
forecastDb.saveForecast(converted)
return forecastDb.requestForecastByZipCode(zipCode, date)
}
override fun requestDayForecast(id: Long): Forecast? = throw UnsupportedOperationException()
} | apache-2.0 | e6f0038423b02c9e0e457575b03123bf | 43.1 | 141 | 0.777526 | 4.235577 | false | false | false | false |
wuseal/JsonToKotlinClass | gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTaskTest.kt | 1 | 3582 | package org.jetbrains.changelog.tasks
import org.jetbrains.changelog.BaseTest
import java.io.File
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class InitializeChangelogTaskTest : BaseTest() {
@BeforeTest
fun localSetUp() {
buildFile =
"""
plugins {
id 'org.jetbrains.changelog'
}
changelog {
version = "1.0.0"
}
"""
project.evaluate()
}
@Test
fun `creates new changelog file`() {
runTask("initializeChangelog")
extension.getAll().apply {
assertEquals(1, keys.size)
assertEquals("[Unreleased]", keys.first())
assertEquals(
"""
## [Unreleased]
### Added
- Example item
### Changed
### Deprecated
### Removed
### Fixed
### Security
""".trimIndent(),
values.first().withHeader(true).toText()
)
}
assertNotNull(extension.getUnreleased())
}
@Test
fun `overrides existing changelog file`() {
changelog =
"""
# Changelog
"""
project.evaluate()
runTask("initializeChangelog")
assertEquals(
"""
## [Unreleased]
### Added
- Example item
### Changed
### Deprecated
### Removed
### Fixed
### Security
""".trimIndent(),
extension.getUnreleased().withHeader(true).toText()
)
}
@Test
fun `creates customized changelog file`() {
buildFile =
"""
plugins {
id 'org.jetbrains.changelog'
}
changelog {
version = "1.0.0"
path = "${File("${project.projectDir}/CHANGES.md").path.replace("\\", "\\\\")}"
itemPrefix = "*"
unreleasedTerm = "Upcoming version"
groups = ["Added", "Removed"]
}
"""
extension.apply {
path = File("${project.projectDir}/CHANGES.md").path
unreleasedTerm = "Upcoming version"
itemPrefix = "*"
}
project.evaluate()
runTask("initializeChangelog")
assertEquals(
"""
## Upcoming version
### Added
* Example item
### Removed
""".trimIndent(),
extension.getUnreleased().withHeader(true).toText()
)
}
@Test
fun `doesn't throw VersionNotSpecifiedException when changelog extension has no version provided`() {
buildFile =
"""
plugins {
id 'org.jetbrains.changelog'
}
changelog {
}
"""
project.evaluate()
val result = runTask("initializeChangelog")
assertFalse(result.output.contains("VersionNotSpecifiedException"))
}
@Test
fun `task loads from the configuration cache`() {
runTask("initializeChangelog", "--configuration-cache")
val result = runTask("initializeChangelog", "--configuration-cache")
assertTrue(result.output.contains("Reusing configuration cache."))
}
}
| gpl-3.0 | 041af3adbcf3739b35c42e5d76988ec6 | 22.88 | 105 | 0.487716 | 5.676704 | false | true | false | false |
camdenorrb/KPortals | src/main/kotlin/me/camdenorrb/kportals/iterator/PositionIterator.kt | 1 | 1102 | package me.camdenorrb.kportals.iterator
//import me.camdenorrb.kportals.position.Position
/**
* Created by camdenorrb on 3/20/17.
*/
// This whole thing could be a simple sequence...
/*
sequence {
for (i in 0..x)
for (i in 0..y)
yield(Pos(x, y, z))
}
*/
/*
class PositionProgression(val start: Position, val end: Position, var step: Int = 1) : Iterable<Position> {
override fun iterator() = PositionIterator(start, end, step)
class PositionIterator(val start: Position, val end: Position, var step: Int = 1) : Iterator<Position> {
private var x: Double = start.x
private var y: Double = start.y
private var z: Double = start.z
private val worldName: String = start.worldName
override fun hasNext(): Boolean = x <= end.x
override operator fun next(): Position {
val nextPos = Position(x, y, z, worldName = worldName)
if (++z <= end.z) return nextPos
z = start.z
if (++y <= end.y) return nextPos
y = start.y
x++
return nextPos
}
infix fun step(step: Int): PositionIterator {
this.step = step
return this
}
}
}*/ | mit | b9eec6d3dae2f38533b4ace0d6ef4b00 | 18.696429 | 107 | 0.647005 | 3.349544 | false | false | false | false |
nithia/xkotlin | exercises/nucleotide-count/src/test/kotlin/NucleotideTest.kt | 1 | 1962 | import org.junit.Test
import org.junit.Ignore;
import kotlin.test.assertEquals
class NucleotideTest {
@Test
fun emptyDnaStringHasNoAdenosine() {
val dna = DNA("");
assertEquals(0, dna.count('A'))
}
@Ignore
@Test
fun emptyDnaStringHasNoNucleotides() {
val dna = DNA("");
val expected = mapOf('A' to 0, 'C' to 0, 'G' to 0, 'T' to 0)
assertEquals(expected, dna.nucleotideCounts)
}
@Ignore
@Test
fun repetitiveCytidineGetsCounted() {
val dna = DNA("CCCCC");
assertEquals(5, dna.count('C'))
}
@Ignore
@Test
fun repetitiveSequenceWithOnlyGuanosine() {
val dna = DNA("GGGGGGGG");
val expected = mapOf('A' to 0, 'C' to 0, 'G' to 8, 'T' to 0)
assertEquals(expected, dna.nucleotideCounts)
}
@Ignore
@Test
fun countsOnlyThymidine() {
val dna = DNA("GGGGGTAACCCGG");
assertEquals(1, dna.count('T'))
}
@Ignore
@Test
fun countsANucleotideOnlyOnce() {
val dna = DNA("CGATTGGG");
dna.count('T')
assertEquals(2, dna.count('T'))
}
@Ignore
@Test
fun dnaCountsDoNotChangeAfterCountingAdenosine() {
val dna = DNA("GATTACA");
val expected = mapOf('A' to 3, 'C' to 1, 'G' to 1, 'T' to 2)
dna.count('A');
assertEquals(expected, dna.nucleotideCounts)
}
@Ignore
@Test(expected = IllegalArgumentException::class)
fun validatesNucleotides() {
DNA("GX")
}
@Ignore
@Test(expected = IllegalArgumentException::class)
fun validatesNucleotidesCountInput() {
DNA("GACT").count('X');
}
@Ignore
@Test
fun countsAllNucleotides() {
val dna = DNA("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC")
val expected = mapOf('A' to 20, 'C' to 12, 'G' to 17, 'T' to 21)
assertEquals(expected, dna.nucleotideCounts)
}
}
| mit | 8a02d999e73a3d7f7204f42eb41b50f1 | 21.551724 | 95 | 0.589195 | 3.205882 | false | true | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/ksp/TargetTypes.kt | 1 | 10610 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.moshi.kotlin.codegen.ksp
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getDeclaredProperties
import com.google.devtools.ksp.getVisibility
import com.google.devtools.ksp.isInternal
import com.google.devtools.ksp.isLocal
import com.google.devtools.ksp.isPublic
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.ClassKind.CLASS
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeParameter
import com.google.devtools.ksp.symbol.Modifier
import com.google.devtools.ksp.symbol.Origin
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.ksp.TypeParameterResolver
import com.squareup.kotlinpoet.ksp.toClassName
import com.squareup.kotlinpoet.ksp.toKModifier
import com.squareup.kotlinpoet.ksp.toTypeName
import com.squareup.kotlinpoet.ksp.toTypeParameterResolver
import com.squareup.kotlinpoet.ksp.toTypeVariableName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonQualifier
import com.squareup.moshi.kotlin.codegen.api.TargetConstructor
import com.squareup.moshi.kotlin.codegen.api.TargetParameter
import com.squareup.moshi.kotlin.codegen.api.TargetProperty
import com.squareup.moshi.kotlin.codegen.api.TargetType
import com.squareup.moshi.kotlin.codegen.api.unwrapTypeAlias
/** Returns a target type for [type] or null if it cannot be used with code gen. */
internal fun targetType(
type: KSDeclaration,
resolver: Resolver,
logger: KSPLogger,
): TargetType? {
if (type !is KSClassDeclaration) {
logger.error("@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must be a Kotlin class", type)
return null
}
logger.check(type.classKind != ClassKind.ENUM_CLASS, type) {
"@JsonClass with 'generateAdapter = \"true\"' can't be applied to ${type.qualifiedName?.asString()}: code gen for enums is not supported or necessary"
}
logger.check(type.classKind == CLASS && type.origin == Origin.KOTLIN, type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must be a Kotlin class"
}
logger.check(Modifier.INNER !in type.modifiers, type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must not be an inner class"
}
logger.check(Modifier.SEALED !in type.modifiers, type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must not be sealed"
}
logger.check(Modifier.ABSTRACT !in type.modifiers, type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must not be abstract"
}
logger.check(!type.isLocal(), type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must not be local"
}
logger.check(type.isPublic() || type.isInternal(), type) {
"@JsonClass can't be applied to ${type.qualifiedName?.asString()}: must be internal or public"
}
val classTypeParamsResolver = type.typeParameters.toTypeParameterResolver(
sourceTypeHint = type.qualifiedName!!.asString()
)
val typeVariables = type.typeParameters.map { it.toTypeVariableName(classTypeParamsResolver) }
val appliedType = AppliedType(type)
val constructor = primaryConstructor(resolver, type, classTypeParamsResolver, logger)
?: run {
logger.error("No primary constructor found on $type", type)
return null
}
if (constructor.visibility != KModifier.INTERNAL && constructor.visibility != KModifier.PUBLIC) {
logger.error(
"@JsonClass can't be applied to $type: " +
"primary constructor is not internal or public",
type
)
return null
}
val properties = mutableMapOf<String, TargetProperty>()
val originalType = appliedType.type
for (superclass in appliedType.superclasses(resolver)) {
val classDecl = superclass.type
if (!classDecl.isKotlinClass()) {
logger.error(
"""
@JsonClass can't be applied to $type: supertype $superclass is not a Kotlin type.
Origin=${classDecl.origin}
Annotations=${classDecl.annotations.joinToString(prefix = "[", postfix = "]") { it.shortName.getShortName() }}
""".trimIndent(),
type
)
return null
}
val supertypeProperties = declaredProperties(
constructor = constructor,
originalType = originalType,
classDecl = classDecl,
resolver = resolver,
typeParameterResolver = classDecl.typeParameters
.toTypeParameterResolver(classTypeParamsResolver)
)
for ((name, property) in supertypeProperties) {
properties.putIfAbsent(name, property)
}
}
val visibility = type.getVisibility().toKModifier() ?: KModifier.PUBLIC
// If any class in the enclosing class hierarchy is internal, they must all have internal
// generated adapters.
val resolvedVisibility = if (visibility == KModifier.INTERNAL) {
// Our nested type is already internal, no need to search
visibility
} else {
// Implicitly public, so now look up the hierarchy
val forceInternal = generateSequence<KSDeclaration>(type) { it.parentDeclaration }
.filterIsInstance<KSClassDeclaration>()
.any { it.isInternal() }
if (forceInternal) KModifier.INTERNAL else visibility
}
return TargetType(
typeName = type.toClassName().withTypeArguments(typeVariables),
constructor = constructor,
properties = properties,
typeVariables = typeVariables,
isDataClass = Modifier.DATA in type.modifiers,
visibility = resolvedVisibility,
)
}
private fun ClassName.withTypeArguments(arguments: List<TypeName>): TypeName {
return if (arguments.isEmpty()) {
this
} else {
this.parameterizedBy(arguments)
}
}
@OptIn(KspExperimental::class)
internal fun primaryConstructor(
resolver: Resolver,
targetType: KSClassDeclaration,
typeParameterResolver: TypeParameterResolver,
logger: KSPLogger
): TargetConstructor? {
val primaryConstructor = targetType.primaryConstructor ?: return null
val parameters = LinkedHashMap<String, TargetParameter>()
for ((index, parameter) in primaryConstructor.parameters.withIndex()) {
val name = parameter.name!!.getShortName()
parameters[name] = TargetParameter(
name = name,
index = index,
type = parameter.type.toTypeName(typeParameterResolver),
hasDefault = parameter.hasDefault,
qualifiers = parameter.qualifiers(resolver),
jsonName = parameter.jsonName()
)
}
val kmConstructorSignature: String = resolver.mapToJvmSignature(primaryConstructor)
?: run {
logger.error("No primary constructor found.", primaryConstructor)
return null
}
return TargetConstructor(
parameters,
primaryConstructor.getVisibility().toKModifier() ?: KModifier.PUBLIC,
kmConstructorSignature
)
}
private fun KSAnnotated?.qualifiers(resolver: Resolver): Set<AnnotationSpec> {
if (this == null) return setOf()
return annotations
.filter {
it.annotationType.resolve().declaration.isAnnotationPresent(JsonQualifier::class)
}
.mapTo(mutableSetOf()) {
it.toAnnotationSpec(resolver)
}
}
private fun KSAnnotated?.jsonName(): String? {
return this?.findAnnotationWithType<Json>()?.name?.takeUnless { it == Json.UNSET_NAME }
}
private fun KSAnnotated?.jsonIgnore(): Boolean {
return this?.findAnnotationWithType<Json>()?.ignore ?: false
}
@OptIn(KspExperimental::class)
private fun declaredProperties(
constructor: TargetConstructor,
originalType: KSClassDeclaration,
classDecl: KSClassDeclaration,
resolver: Resolver,
typeParameterResolver: TypeParameterResolver,
): Map<String, TargetProperty> {
val result = mutableMapOf<String, TargetProperty>()
for (property in classDecl.getDeclaredProperties()) {
val initialType = property.type.resolve()
val resolvedType = if (initialType.declaration is KSTypeParameter) {
property.asMemberOf(originalType.asType())
} else {
initialType
}
val propertySpec = property.toPropertySpec(resolver, resolvedType, typeParameterResolver)
val name = propertySpec.name
val parameter = constructor.parameters[name]
val isTransient = Modifier.JAVA_TRANSIENT in property.modifiers ||
property.isAnnotationPresent(Transient::class) ||
Modifier.JAVA_TRANSIENT in resolver.effectiveJavaModifiers(property)
result[name] = TargetProperty(
propertySpec = propertySpec,
parameter = parameter,
visibility = property.getVisibility().toKModifier() ?: KModifier.PUBLIC,
jsonName = parameter?.jsonName ?: property.jsonName() ?: name,
jsonIgnore = isTransient || parameter?.jsonIgnore == true || property.jsonIgnore()
)
}
return result
}
private fun KSPropertyDeclaration.toPropertySpec(
resolver: Resolver,
resolvedType: KSType,
typeParameterResolver: TypeParameterResolver
): PropertySpec {
return PropertySpec.builder(
name = simpleName.getShortName(),
type = resolvedType.toTypeName(typeParameterResolver).unwrapTypeAlias()
)
.mutable(isMutable)
.addModifiers(modifiers.map { KModifier.valueOf(it.name) })
.apply {
addAnnotations(
[email protected]
.mapNotNull {
if ((it.annotationType.resolve().unwrapTypeAlias().declaration as KSClassDeclaration).isJsonQualifier
) {
it.toAnnotationSpec(resolver)
} else {
null
}
}
.asIterable()
)
}
.build()
}
| apache-2.0 | 105fdfdc75ef440e3c5a8932e87d3d48 | 36.892857 | 154 | 0.735156 | 4.503396 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/sse/SseClient.kt | 1 | 1216 | package io.javalin.http.sse
import io.javalin.http.Context
import io.javalin.plugin.json.jsonMapper
import java.io.Closeable
import java.io.InputStream
class SseClient internal constructor(
@JvmField val ctx: Context
) : Closeable {
private val emitter = Emitter(ctx.req.asyncContext)
private var closeCallback = Runnable {}
fun onClose(closeCallback: Runnable) {
this.closeCallback = closeCallback
}
override fun close() {
ctx.req.asyncContext.complete()
closeCallback.run()
}
fun sendEvent(data: Any) = sendEvent("message", data)
@JvmOverloads
fun sendEvent(event: String, data: Any, id: String? = null) {
when (data) {
is InputStream -> emitter.emit(event, data, id)
is String -> emitter.emit(event, data.byteInputStream(), id)
else -> emitter.emit(event, ctx.jsonMapper().toJsonString(data).byteInputStream(), id)
}
if (emitter.isClosed()) { // can't detect if closed before we try emitting?
this.close()
}
}
fun sendComment(comment: String) {
emitter.emit(comment)
if (emitter.isClosed()) {
this.close()
}
}
}
| apache-2.0 | b3d9493c95fbd73ffbb6f72b3264c57d | 26.022222 | 98 | 0.628289 | 4.080537 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/ui/GesturePicker.kt | 1 | 4218 | /*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.ui
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.constraintlayout.widget.ConstraintLayout
import com.ichi2.anki.R
import com.ichi2.anki.cardviewer.Gesture
import com.ichi2.anki.cardviewer.GestureListener
import com.ichi2.utils.UiUtil.setSelectedValue
import timber.log.Timber
/** [View] which allows selection of a gesture either via taps/swipes, or via a [Spinner]
* The spinner aids discoverability of [Gesture.DOUBLE_TAP] and [Gesture.LONG_TAP]
* as they're not explained in [GestureDisplay].
*
* Current use is via [com.ichi2.anki.dialogs.GestureSelectionDialogBuilder]
*/
// This class exists as elements resized when adding in the spinner to GestureDisplay.kt
class GesturePicker
constructor(ctx: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(ctx, attributeSet, defStyleAttr) {
private val mGestureSpinner: Spinner
private val mGestureDisplay: GestureDisplay
private var mOnGestureListener: GestureListener? = null
init {
val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.gesture_picker, this)
mGestureDisplay = findViewById(R.id.gestureDisplay)
mGestureSpinner = findViewById(R.id.spinner_gesture)
mGestureDisplay.setGestureChangedListener(this::onGesture)
mGestureSpinner.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, allGestures())
mGestureSpinner.onItemSelectedListener = InnerSpinner()
}
fun getGesture() = mGestureDisplay.getGesture()
private fun onGesture(gesture: Gesture?) {
Timber.d("gesture: %s", gesture?.toDisplayString(context))
setGesture(gesture)
if (gesture == null) {
return
}
mOnGestureListener?.onGesture(gesture)
}
private fun setGesture(gesture: Gesture?) {
mGestureSpinner.setSelectedValue(GestureWrapper(gesture))
mGestureDisplay.setGesture(gesture)
}
/** Not fired if deselected */
fun setGestureChangedListener(listener: GestureListener?) {
mOnGestureListener = listener
}
fun allGestures(): List<GestureWrapper> {
return (listOf(null) + availableGestures()).map(this::GestureWrapper).toList()
}
private fun availableGestures() = mGestureDisplay.availableValues()
inner class GestureWrapper(val gesture: Gesture?) {
override fun toString(): String {
return gesture?.toDisplayString(context) ?: "None"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GestureWrapper
if (gesture != other.gesture) return false
return true
}
override fun hashCode() = gesture?.hashCode() ?: 0
}
private inner class InnerSpinner : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val wrapper = parent?.getItemAtPosition(position) as? GestureWrapper
onGesture(wrapper?.gesture)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
}
| gpl-3.0 | 434767478d8f27de9987611824915c6d | 35.051282 | 117 | 0.711 | 4.555076 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.