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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/views/AttachmentPreviewAdapterView.kt | 1 | 1841 | package com.quickblox.sample.chat.kotlin.ui.views
import android.content.Context
import android.database.DataSetObserver
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
class AttachmentPreviewAdapterView(context: Context, attrs: AttributeSet) : HorizontalScrollView(context, attrs) {
private val mainThreadHandler = Handler(Looper.getMainLooper())
private val container: LinearLayout = LinearLayout(context)
private var adapter: Adapter? = null
private val dataSetObserver: DataSetObserver
init {
container.orientation = LinearLayout.HORIZONTAL
val width = ViewGroup.LayoutParams.MATCH_PARENT
val height = ViewGroup.LayoutParams.MATCH_PARENT
val layoutParams = LayoutParams(width, height)
addView(container, layoutParams)
dataSetObserver = object : DataSetObserver() {
override fun onChanged() {
populateWithViewsFromAdapter()
}
override fun onInvalidated() {
populateWithViewsFromAdapter()
}
}
}
fun setAdapter(newAdapter: Adapter) {
adapter?.unregisterDataSetObserver(dataSetObserver)
adapter = newAdapter
adapter?.registerDataSetObserver(dataSetObserver)
populateWithViewsFromAdapter()
}
private fun populateWithViewsFromAdapter() {
mainThreadHandler.post {
container.removeAllViews()
adapter?.let {
for (index in 0 until it.count) {
val childView = it.getView(index, null, this)
container.addView(childView, index)
}
}
}
}
} | bsd-3-clause | 15a40ffe038582f23145e19a94aa5aa8 | 32.490909 | 114 | 0.67409 | 5.320809 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/searchfilesystem/SortSearchResultTask.kt | 1 | 2885 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.asynchronous.asynctasks.searchfilesystem
import com.amaze.filemanager.R
import com.amaze.filemanager.adapters.data.LayoutElementParcelable
import com.amaze.filemanager.asynchronous.asynctasks.Task
import com.amaze.filemanager.filesystem.files.FileListSorter
import com.amaze.filemanager.ui.fragments.MainFragment
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class SortSearchResultTask(
val elements: MutableList<LayoutElementParcelable>,
val sorter: FileListSorter,
val mainFragment: MainFragment,
val query: String
) : Task<Unit, SortSearchResultCallable> {
private val log: Logger = LoggerFactory.getLogger(SortSearchResultTask::class.java)
private val task = SortSearchResultCallable(elements, sorter)
override fun getTask(): SortSearchResultCallable = task
override fun onError(error: Throwable) {
log.error("Could not sort search results because of exception", error)
}
override fun onFinish(value: Unit) {
val mainFragmentViewModel = mainFragment.mainFragmentViewModel
if (mainFragmentViewModel == null) {
log.error(
"Could not show sorted search results because main fragment view model is null"
)
return
}
val mainActivity = mainFragment.mainActivity
if (mainActivity == null) {
log.error("Could not show sorted search results because main activity is null")
return
}
mainFragment.reloadListElements(
true,
true,
!mainFragmentViewModel.isList
) // TODO: 7/7/2017 this is really inneffient, use RecycleAdapter's
// createHeaders()
mainActivity.appbar.bottomBar.setPathText("")
mainActivity
.appbar
.bottomBar.fullPathText = mainActivity.getString(R.string.search_results, query)
mainFragmentViewModel.results = false
}
}
| gpl-3.0 | 27d0a6a9fa93d022a4a17a1b5c3c4efa | 35.987179 | 107 | 0.714731 | 4.616 | false | false | false | false |
natanieljr/droidmate | project/deviceComponents/deviceControlDaemon/src/androidTest/java/org/droidmate/uiautomator2daemon/UiAutomator2DaemonDriver.kt | 1 | 4327 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.uiautomator2daemon
import android.util.Log
import kotlinx.coroutines.runBlocking
import org.droidmate.deviceInterface.DeviceConstants.uiaDaemon_logcatTag
import org.droidmate.deviceInterface.communication.DeviceCommand
import org.droidmate.deviceInterface.communication.ExecuteCommand
import org.droidmate.deviceInterface.communication.StopDaemonCommand
import org.droidmate.deviceInterface.exploration.DeviceResponse
import org.droidmate.uiautomator2daemon.exploration.*
import org.droidmate.uiautomator2daemon.uiautomatorExtensions.UiAutomationEnvironment
import kotlin.math.max
/**
* Decides if UiAutomator2DaemonDriver should wait for the window to go to idle state after each click.
*/
class UiAutomator2DaemonDriver(waitForIdleTimeout: Long, waitForInteractiveTimeout: Long, imgQuality: Int,
delayedImgTransfer: Boolean,
enablePrintouts: Boolean = false) : IUiAutomator2DaemonDriver {
private val uiEnvironment: UiAutomationEnvironment = UiAutomationEnvironment(idleTimeout = waitForIdleTimeout, interactiveTimeout = waitForInteractiveTimeout, imgQuality = imgQuality, delayedImgTransfer = delayedImgTransfer, enablePrintouts = enablePrintouts)
private var nActions = 0
@Throws(DeviceDaemonException::class)
override fun executeCommand(deviceCommand: DeviceCommand): DeviceResponse = runBlocking { // right now need this since calling class is still Java, which cannot handle coroutines
Log.v(uiaDaemon_logcatTag, "Executing device command: ($nActions) $deviceCommand")
try {
when (deviceCommand) {
is ExecuteCommand ->
performAction(deviceCommand)
// The server will be closed after this response is sent, because the given deviceCommand
// will be interpreted in the caller, i.e. Uiautomator2DaemonTcpServerBase.
is StopDaemonCommand -> DeviceResponse.empty
}
} catch (e: Throwable) {
Log.e(uiaDaemon_logcatTag, "Error: " + e.message)
Log.e(uiaDaemon_logcatTag, "Printing stack trace for debug")
e.printStackTrace()
ErrorResponse(e)
}
}
private var tFetch = 0L
private var tExec = 0L
private var et = 0.0
@Throws(DeviceDaemonException::class)
private suspend fun performAction(deviceCommand: ExecuteCommand): DeviceResponse =
deviceCommand.guiAction.let { action ->
debugT(" EXECUTE-TIME avg = ${et / max(1, nActions)}", {
isWithinQueue = false
Log.v(uiaDaemon_logcatTag, "Performing GUI action $action [${action.id}]")
val result = debugT("execute action avg= ${tExec / (max(nActions, 1) * 1000000)}", {
lastId = action.id
action.execute(uiEnvironment)
}, inMillis = true, timer = {
tExec += it
})
//TODO if the previous action was not successful we should return an "ActionFailed"-DeviceResponse
if (!action.isFetch()) // only fetch once even if the action was a FetchGUI action
debugT("FETCH avg= ${tFetch / (max(nActions, 1) * 1000000)}", { fetchDeviceData(uiEnvironment, afterAction = true) }, inMillis = true, timer = {
// if (action !is DeviceLaunchApp) {
tFetch += it
// }
})
else result as DeviceResponse
}, inMillis = true, timer = {
// if (action !is DeviceLaunchApp) {
et += it / 1000000.0
nActions += 1
// }
})
}
} | gpl-3.0 | 3e16e8591796b947a779c2e47cf3d194 | 41.431373 | 260 | 0.737925 | 3.995383 | false | false | false | false |
jereksel/LibreSubstratum | libs/changelogdialog/src/main/java/com/jereksel/changelogdialog/ChangeLogDialog.kt | 1 | 2078 | package com.jereksel.changelogdialog
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import it.gmariotti.changelibs.library.internal.ChangeLogRecyclerViewAdapter
import it.gmariotti.changelibs.library.internal.ChangeLogRow
import it.gmariotti.changelibs.library.view.ChangeLogRecyclerView
import java.util.*
object ChangeLogDialog {
fun show(context: Context, changeLog: ChangeLog) {
val manager = context.packageManager
val info = manager.getPackageInfo(
context.packageName, 0)
val code = info.versionCode
val prefs = context.getSharedPreferences("ChangeLogDialog", MODE_PRIVATE)
val lastCode = prefs.getInt("LAST_CODE", -1)
if (code != lastCode) {
val layoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chgList = layoutInflater.inflate(R.layout.changelogdialog_dialog, null) as ChangeLogRecyclerView
(chgList.adapter as ChangeLogRecyclerViewAdapter).add(changeLog)
prefs.edit().putInt("LAST_CODE", code).apply()
val alert = AlertDialog.Builder(context)
alert.setTitle("Changelog")
alert.setView(chgList)
alert.setNegativeButton("Close", { dialog, _ -> dialog.dismiss() })
alert.show()
}
}
private fun ChangeLogRecyclerViewAdapter.add(changeLog: ChangeLog) {
val rows = changeLog.versions.flatMap { version ->
val header = ChangeLogRow()
header.isHeader = true
header.versionName = version.version
header.changeDate = " "
val rows = version.changes.map { change ->
val row = ChangeLogRow()
row.changeText = change
row.isBulletedList = true
row
}
listOf(header, *rows.toTypedArray())
}
add(LinkedList(rows))
}
}
| mit | e9354add68eae990f4c448c9931a6536 | 27.465753 | 112 | 0.641963 | 4.68018 | false | false | false | false |
cwoolner/flex-poker | src/test/kotlin/com/flexpoker/table/command/aggregate/singlehand/twoplayer/TwoPlayerButtonFoldsDueToTimeoutTest.kt | 1 | 4266 | package com.flexpoker.table.command.aggregate.singlehand.twoplayer
import com.flexpoker.table.command.HandDealerState
import com.flexpoker.table.command.aggregate.applyEvents
import com.flexpoker.table.command.aggregate.eventproducers.expireActionOn
import com.flexpoker.table.command.aggregate.testhelpers.createBasicTableAndStartHand
import com.flexpoker.table.command.aggregate.testhelpers.fetchIdForBigBlind
import com.flexpoker.table.command.aggregate.testhelpers.fetchIdForButton
import com.flexpoker.table.command.events.ActionOnChangedEvent
import com.flexpoker.table.command.events.CardsShuffledEvent
import com.flexpoker.table.command.events.HandCompletedEvent
import com.flexpoker.table.command.events.HandDealtEvent
import com.flexpoker.table.command.events.PlayerForceFoldedEvent
import com.flexpoker.table.command.events.PotAmountIncreasedEvent
import com.flexpoker.table.command.events.PotCreatedEvent
import com.flexpoker.table.command.events.RoundCompletedEvent
import com.flexpoker.table.command.events.TableCreatedEvent
import com.flexpoker.table.command.events.WinnersDeterminedEvent
import com.flexpoker.test.util.CommonAssertions.verifyNewEvents
import com.flexpoker.test.util.TableEventProducerApplierBuilder
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.UUID
class TwoPlayerButtonFoldsDueToTimeoutTest {
@Test
fun test() {
val tableId = UUID.randomUUID()
val events = createBasicTableAndStartHand(tableId, UUID.randomUUID(), UUID.randomUUID())
val initState = applyEvents(events)
val (_, _, handId, playerId) = events[4] as ActionOnChangedEvent
val (_, newEvents) = TableEventProducerApplierBuilder()
.initState(initState)
.andRun { expireActionOn(it, handId, playerId) }
.run()
val tableCreatedEvent = events[0] as TableCreatedEvent
val handDealtEvent = events[2] as HandDealtEvent
val (_, _, _, _, playersInvolved) = events[3] as PotCreatedEvent
val (_, _, _, _, amountIncreased) = newEvents[1] as PotAmountIncreasedEvent
val (_, _, _, _, amountIncreased1) = newEvents[2] as PotAmountIncreasedEvent
val (_, _, _, nextHandDealerState) = newEvents[3] as RoundCompletedEvent
val buttonPlayerId = fetchIdForButton(tableCreatedEvent, handDealtEvent)
val bigBlindPlayerId = fetchIdForBigBlind(tableCreatedEvent, handDealtEvent)
assertEquals(10, handDealtEvent.callAmountsMap[buttonPlayerId]!!.toInt())
assertEquals(0, handDealtEvent.callAmountsMap[bigBlindPlayerId]!!.toInt())
assertEquals(1490, handDealtEvent.chipsInBack[buttonPlayerId]!!.toInt())
assertEquals(1480, handDealtEvent.chipsInBack[bigBlindPlayerId]!!.toInt())
assertEquals(10, handDealtEvent.chipsInFrontMap[buttonPlayerId]!!.toInt())
assertEquals(20, handDealtEvent.chipsInFrontMap[bigBlindPlayerId]!!.toInt())
assertEquals(HandDealerState.POCKET_CARDS_DEALT, handDealtEvent.handDealerState)
assertEquals(2, playersInvolved.size)
assertTrue(playersInvolved.contains(buttonPlayerId))
assertTrue(playersInvolved.contains(bigBlindPlayerId))
assertEquals(20, amountIncreased)
assertEquals(10, amountIncreased1)
assertEquals(HandDealerState.COMPLETE, nextHandDealerState)
val (_, _, _, playersToShowCards, playersToChipsWonMap) = newEvents[4] as WinnersDeterminedEvent
assertNull(playersToChipsWonMap[buttonPlayerId])
assertEquals(30, playersToChipsWonMap[bigBlindPlayerId]!!.toInt())
assertTrue(playersToShowCards.isEmpty())
verifyNewEvents(tableId, events + newEvents,
TableCreatedEvent::class.java, CardsShuffledEvent::class.java,
HandDealtEvent::class.java, PotCreatedEvent::class.java,
ActionOnChangedEvent::class.java, PlayerForceFoldedEvent::class.java,
PotAmountIncreasedEvent::class.java, PotAmountIncreasedEvent::class.java,
RoundCompletedEvent::class.java, WinnersDeterminedEvent::class.java,
HandCompletedEvent::class.java
)
}
} | gpl-2.0 | 84080779a2c653787bfe24e1ba40dce2 | 53.012658 | 104 | 0.764182 | 4.547974 | false | true | false | false |
LachlanMcKee/gsonpath | compiler/standard/src/main/java/gsonpath/adapter/standard/extension/range/intrange/IntRangeExtension.kt | 1 | 4090 | package gsonpath.adapter.standard.extension.range.intrange
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import gsonpath.ProcessingException
import gsonpath.adapter.standard.extension.getAnnotationMirror
import gsonpath.adapter.standard.extension.getAnnotationValueObject
import gsonpath.adapter.standard.extension.range.handleRangeValue
import gsonpath.compiler.ExtensionFieldMetadata
import gsonpath.compiler.GsonPathExtension
import gsonpath.model.FieldType
import gsonpath.util.codeBlock
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.AnnotationMirror
/**
* A {@link GsonPathExtension} that supports the '@IntRange' annotation.
*/
class IntRangeExtension : GsonPathExtension {
private val boxedInt = ClassName.get("java.lang", "Integer")
private val boxedLong = ClassName.get("java.lang", "Long")
override val extensionName: String
get() = "'IntRange' Annotation"
override fun createCodePostReadResult(
processingEnvironment: ProcessingEnvironment,
extensionFieldMetadata: ExtensionFieldMetadata): GsonPathExtension.ExtensionResult? {
val (fieldInfo, variableName, jsonPath) = extensionFieldMetadata
val intRangeAnnotation: AnnotationMirror =
getAnnotationMirror(fieldInfo.element, "android.support.annotation", "IntRange")
?: getAnnotationMirror(fieldInfo.element, "gsonpath.extension.annotation", "IntRange")
?: return null
// Ensure that the field is either a integer, or a long.
val typeName = fieldInfo.fieldType.typeName.let {
if (fieldInfo.fieldType is FieldType.Primitive) {
it.box()
} else {
it
}
}
if (typeName != boxedInt && typeName != boxedLong) {
throw ProcessingException("Unexpected type found for field annotated with 'IntRange', only " +
"integers and longs are allowed.", fieldInfo.element)
}
val validationCodeBlock = codeBlock {
handleFrom(intRangeAnnotation, jsonPath, variableName)
handleTo(intRangeAnnotation, jsonPath, variableName)
}
if (!validationCodeBlock.isEmpty) {
return GsonPathExtension.ExtensionResult(validationCodeBlock)
}
return null
}
/**
* Adds the range 'from' validation if the fromValue does not equal the floor-value.
*
* @param intRangeAnnotationMirror the annotation to obtain the range values
* @param jsonPath the json path of the field being validated
* @param variableName the name of the variable that is assigned back to the fieldName
*/
private fun CodeBlock.Builder.handleFrom(intRangeAnnotationMirror: AnnotationMirror, jsonPath: String,
variableName: String): CodeBlock.Builder {
val fromValue: Long = getAnnotationValueObject(intRangeAnnotationMirror, "from") as Long? ?: return this
if (fromValue == java.lang.Long.MIN_VALUE) {
return this
}
return handleRangeValue(fromValue.toString(), true, true, jsonPath, variableName)
}
/**
* Adds the range 'to' validation if the toValue does not equal the ceiling-value.
*
* @param intRangeAnnotationMirror the annotation to obtain the range values
* @param jsonPath the json path of the field being validated
* @param variableName the name of the variable that is assigned back to the fieldName
*/
private fun CodeBlock.Builder.handleTo(intRangeAnnotationMirror: AnnotationMirror, jsonPath: String,
variableName: String): CodeBlock.Builder {
val toValue: Long = getAnnotationValueObject(intRangeAnnotationMirror, "to") as Long? ?: return this
if (toValue == java.lang.Long.MAX_VALUE) {
return this
}
return handleRangeValue(toValue.toString(), false, true, jsonPath, variableName)
}
}
| mit | 60ca472b7f5a86e18a6ca5dd851d82d9 | 40.734694 | 112 | 0.686064 | 5.157629 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/ui/fileactions/FileActionsViewModel.kt | 1 | 5875 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.ui.fileactions
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.logger.Logger
import com.nextcloud.utils.TimeConstants
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.files.FileMenuFilter
import com.owncloud.android.lib.resources.files.model.FileLockType
import com.owncloud.android.ui.activity.ComponentsGetter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
class FileActionsViewModel @Inject constructor(
private val currentAccountProvider: CurrentAccountProvider,
private val filterFactory: FileMenuFilter.Factory,
private val logger: Logger
) :
ViewModel() {
data class LockInfo(val lockType: FileLockType, val lockedBy: String, val lockedUntil: Long?)
sealed interface UiState {
object Loading : UiState
object Error : UiState
data class LoadedForSingleFile(
val actions: List<FileAction>,
val titleFile: OCFile?,
val lockInfo: LockInfo? = null
) : UiState
data class LoadedForMultipleFiles(val actions: List<FileAction>, val fileCount: Int) : UiState
}
private val _uiState: MutableLiveData<UiState> = MutableLiveData(UiState.Loading)
val uiState: LiveData<UiState>
get() = _uiState
private val _clickActionId: MutableLiveData<Int?> = MutableLiveData(null)
val clickActionId: LiveData<Int?>
@IdRes
get() = _clickActionId
fun load(arguments: Bundle, componentsGetter: ComponentsGetter) {
val files: List<OCFile>? = arguments.getParcelableArrayList(ARG_FILES)
val numberOfAllFiles: Int = arguments.getInt(ARG_ALL_FILES_COUNT, 1)
val isOverflow = arguments.getBoolean(ARG_IS_OVERFLOW, false)
val additionalFilter: IntArray? = arguments.getIntArray(ARG_ADDITIONAL_FILTER)
if (files.isNullOrEmpty()) {
logger.d(TAG, "No valid files argument for loading actions")
_uiState.postValue(UiState.Error)
} else {
load(componentsGetter, files.toList(), numberOfAllFiles, isOverflow, additionalFilter)
}
}
private fun load(
componentsGetter: ComponentsGetter,
files: Collection<OCFile>,
numberOfAllFiles: Int?,
isOverflow: Boolean?,
additionalFilter: IntArray?
) {
viewModelScope.launch(Dispatchers.IO) {
val toHide = getHiddenActions(componentsGetter, numberOfAllFiles, files, isOverflow)
val availableActions = getActionsToShow(additionalFilter, toHide)
updateStateLoaded(files, availableActions)
}
}
private fun getHiddenActions(
componentsGetter: ComponentsGetter,
numberOfAllFiles: Int?,
files: Collection<OCFile>,
isOverflow: Boolean?
): List<Int> {
return filterFactory.newInstance(
numberOfAllFiles ?: 1,
files.toList(),
componentsGetter,
isOverflow ?: false,
currentAccountProvider.user
)
.getToHide(false)
}
private fun getActionsToShow(
additionalFilter: IntArray?,
toHide: List<Int>
) = FileAction.SORTED_VALUES
.filter { additionalFilter == null || it.id !in additionalFilter }
.filter { it.id !in toHide }
private fun updateStateLoaded(
files: Collection<OCFile>,
availableActions: List<FileAction>
) {
val state: UiState = when (files.size) {
1 -> {
val file = files.first()
UiState.LoadedForSingleFile(availableActions, file, getLockInfo(file))
}
else -> UiState.LoadedForMultipleFiles(availableActions, files.size)
}
_uiState.postValue(state)
}
private fun getLockInfo(file: OCFile): LockInfo? {
val lockType = file.lockType
val username = file.lockOwnerDisplayName ?: file.lockOwnerId
return if (file.isLocked && lockType != null && username != null) {
LockInfo(lockType, username, getLockedUntil(file))
} else {
null
}
}
private fun getLockedUntil(file: OCFile): Long? {
return if (file.lockTimestamp == 0L || file.lockTimeout == 0L) {
null
} else {
(file.lockTimestamp + file.lockTimeout) * TimeConstants.MILLIS_PER_SECOND
}
}
fun onClick(action: FileAction) {
_clickActionId.value = action.id
}
companion object {
const val ARG_ALL_FILES_COUNT = "ALL_FILES_COUNT"
const val ARG_FILES = "FILES"
const val ARG_IS_OVERFLOW = "OVERFLOW"
const val ARG_ADDITIONAL_FILTER = "ADDITIONAL_FILTER"
private val TAG = FileActionsViewModel::class.simpleName!!
}
}
| gpl-2.0 | a7f17256a211f56a26cc4e1a12e2c7f2 | 34.167665 | 102 | 0.674442 | 4.53864 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/SmartResize.kt | 1 | 22711 | package tornadofx
import javafx.application.Platform
import javafx.beans.property.ObjectProperty
import javafx.beans.property.ReadOnlyProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.value.ChangeListener
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.scene.control.TableColumn
import javafx.scene.control.TableView
import javafx.scene.control.TreeTableColumn
import javafx.scene.control.TreeTableView
import javafx.util.Callback
import tornadofx.ResizeType.*
import tornadofx.adapters.*
import kotlin.collections.set
import kotlin.math.abs
import kotlin.reflect.KClass
//private const val SMART_RESIZE_INSTALLED = "tornadofx.smartResizeInstalled"
private const val SMART_RESIZE = "tornadofx.smartResize"
private const val IS_SMART_RESIZING = "tornadofx.isSmartResizing"
const val RESIZE_TYPE_KEY = "tornadofx.smartColumnResizeType"
private typealias GroupedColumns = Map<KClass<out ResizeType>, List<TornadoFXColumn<out Any?>>>
sealed class ResizeType(val isResizable: Boolean) {
class Pref(val width: Number) : ResizeType(true)
class Fixed(val width: Number) : ResizeType(false)
class Weight(val weight: Number, val padding: Number = 0.0, val minContentWidth: Boolean = false, var minRecorded: Boolean = false) : ResizeType(true)
class Pct(val value: Number) : ResizeType(true)
class Content(val padding: Number = 0.0, val useAsMin: Boolean = false, val useAsMax: Boolean = false, var minRecorded: Boolean = false, var maxRecorded: Boolean = false) : ResizeType(true)
class Remaining : ResizeType(true)
var delta: Double = 0.0
}
typealias TableViewResizeCallback = Callback<TableView.ResizeFeatures<out Any>, Boolean>
typealias TreeTableViewResizeCallback = Callback<TreeTableView.ResizeFeatures<out Any>, Boolean>
class SmartResize private constructor() : TableViewResizeCallback {
override fun call(param: TableView.ResizeFeatures<out Any>) = resizeCall(param.toTornadoFXFeatures()) { table ->
if (!isPolicyInstalled(table)) install(table)
}
fun requestResize(table: TableView<*>) {
Platform.runLater {
call(TableView.ResizeFeatures(table, null, 0.0))
}
}
companion object {
val POLICY = SmartResize()
val ResizeTypeKey = "tornadofx.smartColumnResizeType"
private var TableView<*>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
private val policyChangeListener = ChangeListener<Callback<TableView.ResizeFeatures<*>, Boolean>> { observable, _, newValue ->
val table = (observable as ObjectProperty<*>).bean as TableView<*>
if (newValue == POLICY) install(table) else uninstall(table)
}
private val itemsChangeListener = ChangeListener<ObservableList<*>> { observable, _, _ ->
val table = (observable as ObjectProperty<*>).bean as TableView<*>
POLICY.requestResize(table)
}
private val columnsChangeListener = ListChangeListener<TableColumn<*, *>> { s ->
while (s.next()) {
if (s.wasAdded()) s.addedSubList.forEach {
it.widthProperty().addListener(columnWidthChangeListener)
}
if (s.wasRemoved()) s.removed.forEach {
it.widthProperty().removeListener(columnWidthChangeListener)
}
}
}
@Suppress("UNCHECKED_CAST")
private val columnWidthChangeListener = ChangeListener<Number> { observable, oldValue, newValue ->
val column = (observable as ReadOnlyProperty<*>).bean as TableColumn<*, *>
val table: TableView<out Any>? = column.tableView
if (table?.isSmartResizing == false) {
val rt = column.resizeType
val diff = oldValue.toDouble() - newValue.toDouble()
rt.delta -= diff
POLICY.call(TableView.ResizeFeatures<Any>(table as TableView<Any>?, null, 0.0))
}
}
private fun isPolicyInstalled(table: TableView<*>) = table.properties[SMART_RESIZE] == true
private fun install(table: TableView<*>) {
table.columnResizePolicyProperty().addListener(policyChangeListener)
table.columns.addListener(columnsChangeListener)
table.itemsProperty().addListener(itemsChangeListener)
table.columns.forEach { it.widthProperty().addListener(columnWidthChangeListener) }
table.properties[SMART_RESIZE] = true
}
private fun uninstall(table: TableView<*>) {
table.columnResizePolicyProperty().removeListener(policyChangeListener)
table.columns.removeListener(columnsChangeListener)
table.itemsProperty().removeListener(itemsChangeListener)
table.columns.forEach { it.widthProperty().removeListener(columnWidthChangeListener) }
table.properties.remove(SMART_RESIZE)
}
}
}
class TreeTableSmartResize private constructor() : TreeTableViewResizeCallback {
override fun call(param: TreeTableView.ResizeFeatures<out Any>) = resizeCall(param.toTornadoFXResizeFeatures()) { table ->
if (!isPolicyInstalled(table)) install(table)
}
fun requestResize(table: TreeTableView<*>) {
Platform.runLater {
call(TreeTableView.ResizeFeatures(table, null, 0.0))
}
}
companion object {
val POLICY = TreeTableSmartResize()
const val ResizeTypeKey = "tornadofx.smartColumnResizeType"
internal var TreeTableView<*>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
private val policyChangeListener = ChangeListener<Callback<TreeTableView.ResizeFeatures<*>, Boolean>> { observable, oldValue, newValue ->
val table = (observable as ObjectProperty<*>).bean as TreeTableView<*>
if (newValue == POLICY) install(table) else uninstall(table)
}
private val columnsChangeListener = ListChangeListener<TreeTableColumn<*, *>> { s ->
while (s.next()) {
if (s.wasAdded()) s.addedSubList.forEach {
it.widthProperty().addListener(columnWidthChangeListener)
}
if (s.wasRemoved()) s.removed.forEach {
it.widthProperty().removeListener(columnWidthChangeListener)
}
}
}
@Suppress("UNCHECKED_CAST")
private val columnWidthChangeListener = ChangeListener<Number> { observable, oldValue, newValue ->
val column = (observable as ReadOnlyProperty<*>).bean as TreeTableColumn<*, *>
val table: TreeTableView<out Any>? = column.treeTableView
if (table != null && !table.isSmartResizing) {
val rt = column.resizeType
val diff = oldValue.toDouble() - newValue.toDouble()
rt.delta -= diff
POLICY.call(TreeTableView.ResizeFeatures<Any>(table as TreeTableView<Any>?, null, 0.0))
}
}
private fun isPolicyInstalled(table: TreeTableView<*>) = table.properties[SMART_RESIZE] == true
private fun install(table: TreeTableView<*>) {
table.columnResizePolicyProperty().addListener(policyChangeListener)
table.columns.addListener(columnsChangeListener)
table.columns.forEach { it.widthProperty().addListener(columnWidthChangeListener) }
table.properties[SMART_RESIZE] = true
}
private fun uninstall(table: TreeTableView<*>) {
table.columnResizePolicyProperty().removeListener(policyChangeListener)
table.columns.removeListener(columnsChangeListener)
table.columns.forEach { it.widthProperty().removeListener(columnWidthChangeListener) }
table.properties.remove(SMART_RESIZE)
}
}
}
fun TableView<*>.smartResize() {
columnResizePolicy = SmartResize.POLICY
}
fun TableView<*>.requestResize() {
SmartResize.POLICY.requestResize(this)
}
fun TreeTableView<*>.smartResize() {
columnResizePolicy = TreeTableSmartResize.POLICY
}
fun TreeTableView<*>.requestResize() {
TreeTableSmartResize.POLICY.requestResize(this)
}
/**
* Get the width of the area available for columns inside the TableView
*/
fun TableView<*>.getContentWidth() = TableView::class.java.getDeclaredField("contentWidth").let {
it.isAccessible = true
it.get(this@getContentWidth) as Double
}
/**
* Get the width of the area available for columns inside the TableView
*/
fun TreeTableView<*>.getContentWidth() = TreeTableView::class.java.getDeclaredField("contentWidth").let {
it.isAccessible = true
it.get(this@getContentWidth) as Double
}
val TableView<*>.contentColumns: List<TableColumn<*, *>>
get() = columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}
val TreeTableView<*>.contentColumns: List<TreeTableColumn<*, *>>
get() = columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}
internal var TableColumn<*, *>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
internal var TreeTableColumn<*, *>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
@Suppress("UNCHECKED_CAST")
internal fun TableColumn<*, *>.resizeTypeProperty() =
properties.getOrPut(SmartResize.ResizeTypeKey) { SimpleObjectProperty(Content()) } as ObjectProperty<ResizeType>
@Suppress("UNCHECKED_CAST")
internal fun TreeTableColumn<*, *>.resizeTypeProperty() =
properties.getOrPut(TreeTableSmartResize.ResizeTypeKey) { SimpleObjectProperty(Content()) } as ObjectProperty<ResizeType>
fun <S, T> TableColumn<S, T>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = Fixed(width.toDouble())
}
fun <S, T> TreeTableColumn<S, T>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = Fixed(width.toDouble())
}
fun <S, T> TableColumn<S, T>.minWidth(width: Number) = apply { minWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.minWidth(width: Number) = apply { minWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.maxWidth(width: Number) = apply { maxWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.maxWidth(width: Number) = apply { maxWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.prefWidth(width: Number) = apply { prefWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.prefWidth(width: Number) = apply { prefWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.remainingWidth() = apply { resizeType = Remaining() }
fun <S, T> TreeTableColumn<S, T>.remainingWidth() = apply { resizeType = Remaining() }
fun <S, T> TableColumn<S, T>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S, T> TreeTableColumn<S, T>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S, T> TableColumn<S, T>.pctWidth(pct: Number) = apply {
resizeType = Pct(pct.toDouble())
}
fun <S, T> TreeTableColumn<S, T>.pctWidth(pct: Number) = apply {
resizeType = Pct(pct.toDouble())
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S, T> TableColumn<S, T>.contentWidth(padding: Double = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = Content(padding, useAsMin, useAsMax)
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S, T> TreeTableColumn<S, T>.contentWidth(padding: Number = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = Content(padding, useAsMin, useAsMax)
}
internal var TornadoFXColumn<*>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
@Suppress("UNCHECKED_CAST")
internal fun TornadoFXColumn<*>.resizeTypeProperty() =
properties.getOrPut(RESIZE_TYPE_KEY) { SimpleObjectProperty(Content()) } as ObjectProperty<ResizeType>
var TornadoFXTable<*, *>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
fun <S> TornadoFXColumn<S>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = Fixed(width.toDouble())
}
fun <S> TornadoFXColumn<S>.minWidth(width: Number) = apply {
minWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.maxWidth(width: Number) = apply {
maxWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.prefWidth(width: Number) = apply {
prefWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.remainingWidth() = apply {
resizeType = Remaining()
}
fun <S> TornadoFXColumn<S>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S> TornadoFXColumn<S>.pctWidth(pct: Number) = apply {
resizeType = Pct(pct.toDouble())
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S> TornadoFXColumn<S>.contentWidth(padding: Double = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = Content(padding, useAsMin, useAsMax)
}
fun <S, T : Any> TornadoFXTable<S, T>.resizeColumnsToFitContent(resizeColumns: List<TornadoFXColumn<S>> = contentColumns, maxRows: Int = 50, afterResize: () -> Unit = {}) {
when (table) {
is TableView<*> -> (table as TableView<*>).resizeColumnsToFitContent(resizeColumns.map { it.column as TableColumn<*, *> }, maxRows, afterResize)
is TreeTableView<*> -> (table as TreeTableView<*>).resizeColumnsToFitContent(resizeColumns.map { it.column as TreeTableColumn<*, *> }, maxRows, afterResize)
else -> throw IllegalArgumentException("Unable to resize columns for unknown table type $table")
}
}
fun <TABLE : Any> resizeCall(
param: TornadoFXResizeFeatures<*, TABLE>,
installIfNeeded: (TABLE) -> Unit
): Boolean {
param.table.isSmartResizing = true
val paramColumn = param.column
try {
if (paramColumn == null) {
val contentWidth = param.table.contentWidth
if (contentWidth == 0.0) return false
installIfNeeded(param.table.table)
resizeAllColumns(param.table, contentWidth)
} else {
// Handle specific column size operation
val rt = paramColumn.resizeType
if (!rt.isResizable) return false
val targetWidth = paramColumn.width + param.delta
if (!paramColumn.isLegalWidth(targetWidth)) return false
// Prepare to adjust the right column by the same amount we subtract or add to this column
val rightColDelta = param.delta * -1.0
val colIndex = param.table.contentColumns.indexOf(paramColumn)
val rightCol = param.table.contentColumns
.filterIndexed { i, c -> i > colIndex && c.resizeType.isResizable }.firstOrNull {
val newWidth = it.width + rightColDelta
it.isLegalWidth(newWidth)
} ?: return false
// Apply negative delta and set new with for the right column
with(rightCol) {
resizeType.delta += rightColDelta
prefWidth = width + rightColDelta
}
// Apply delta and set new width for the resized column
with(paramColumn) {
rt.delta += param.delta
prefWidth = width + param.delta
}
return true
}
return true
} finally {
param.table.isSmartResizing = false
}
}
private fun <COLUMN, TABLE : Any> resizeAllColumns(table: TornadoFXTable<COLUMN, TABLE>, contentWidth: Double) {
fun <S, T : Any> List<TornadoFXColumn<S>>.adjustTo(table: TornadoFXTable<S, T>) = table.resizeColumnsToFitContent(this)
val groupedColumns = table.contentColumns.filter { it.isVisible }.groupBy { it.resizeType::class }
var remainingWidth = contentWidth -
groupedColumns.resizeFixedColumns() -
groupedColumns.resizePreferredColumns()
groupedColumns[Content::class]?.adjustTo(table)
remainingWidth -=
groupedColumns.resizeContentColumns() +
groupedColumns.resizePctColumns(contentWidth)
val totalWeight = groupedColumns.totalWeightOfWeightedColumns() + groupedColumns.countValues(Remaining::class)
val widthPerWeight = remainingWidth/totalWeight
remainingWidth -= groupedColumns.resizeWeightedColumns(widthPerWeight) +
groupedColumns.resizeRemainingColumns(widthPerWeight)
if (remainingWidth > 0.0) table.divideRemainingWith(remainingWidth)
else if (remainingWidth < 0.0) table.takeBackOverflowedWith(remainingWidth)
}
fun <K> Map<K,Collection<*>>.countValues(key: K) = this[key]?.size ?: 0
private fun GroupedColumns.totalWeightOfWeightedColumns() = this[Weight::class]?.run {
map { it.resizeType as ResizeType.Weight }.sumByDouble { it.weight as Double }
} ?: 0.0
private fun GroupedColumns.resizeWeightedColumns(widthPerWeight: Double): Double {
var spaceNeeded = 0.0
this[Weight::class]?.forEach {
val rt = it.resizeType as ResizeType.Weight
if (rt.minContentWidth && !rt.minRecorded) {
it.minWidth = it.width + rt.padding.toDouble()
rt.minRecorded = true
}
it.prefWidth = maxOf(it.minWidth, (widthPerWeight * rt.weight.toDouble()) + rt.delta + rt.padding.toDouble())
spaceNeeded += it.width
}
return spaceNeeded
}
private fun GroupedColumns.resizeRemainingColumns(widthPerWeight: Double): Double {
var spaceNeeded = 0.0
this[Remaining::class]?.withEach{
prefWidth = maxOf(minWidth, widthPerWeight + resizeType.delta)
spaceNeeded += width
}
return spaceNeeded
}
private fun <TABLE : Any> TornadoFXTable<out Any?, TABLE>.takeBackOverflowedWith(remainingWidth: Double) {
var stillToTake = remainingWidth
contentColumns.filter { it.resizeType.isResizable }.reduceSorted(
// sort the column by the largest reduction potential: the gap between size and minSize
sorter = { minWidth - width },
filter = { minWidth < width }
) {
val reduceBy = minOf(1.0, abs(stillToTake))
val toWidth = it.width - reduceBy
it.prefWidth = toWidth
stillToTake += reduceBy
stillToTake < 0.0
}
}
private fun <TABLE : Any> TornadoFXTable<out Any?, TABLE>.divideRemainingWith(remainingWidth: Double) {
// Give remaining width to the right-most resizable column
val rightMostResizable = contentColumns.lastOrNull { it.resizeType.isResizable }
rightMostResizable?.apply {
prefWidth = width + remainingWidth
}
}
private fun GroupedColumns.resizePctColumns(contentWidth: Double): Double {
var spaceNeeded = 0.0
this[Pct::class]?.also { pctColumn ->
val widthPerPct = contentWidth / 100.0
pctColumn.forEach {
val rt = it.resizeType as ResizeType.Pct
it.prefWidth = (widthPerPct * rt.value.toDouble()) + rt.delta.toDouble()
spaceNeeded += it.width
}
}
return spaceNeeded
}
private fun GroupedColumns.resizeContentColumns(): Double {
// Content columns are resized to their content and adjusted for resize-delta that affected them
var spaceNeeded = 0.0
this[Content::class]?.also { contentColumns ->
contentColumns.forEach {
val rt = it.resizeType as ResizeType.Content
it.prefWidth = it.width + rt.delta + rt.padding.toDouble()
if (rt.hasUnrecordedMin()) it.recordMinFrom(rt)
if (rt.hasUnrecordedMax()) it.recordMaxFrom(rt)
spaceNeeded += it.width
}
}
return spaceNeeded
}
private const val DEFAULT_COLUMN_WIDTH = 80.0
private fun ResizeType.Content.hasUnrecordedMin() = !minRecorded && useAsMin
private fun TornadoFXColumn<*>.recordMinFrom(content: ResizeType.Content) {
if (width != DEFAULT_COLUMN_WIDTH) {
minWidth = width
content.minRecorded = true
}
}
private fun ResizeType.Content.hasUnrecordedMax() = !maxRecorded && useAsMax
private fun TornadoFXColumn<*>.recordMaxFrom(content: ResizeType.Content) {
if (width != DEFAULT_COLUMN_WIDTH) {
maxWidth = width
content.maxRecorded = true
}
}
private fun GroupedColumns.resizePreferredColumns(): Double {
var spaceNeeded = 0.0
this[Pref::class]?.forEach {
val rt = it.resizeType as ResizeType.Pref
it.prefWidth = rt.width.toDouble() + rt.delta.toDouble()
spaceNeeded += it.width
}
return spaceNeeded
}
private fun GroupedColumns.resizeFixedColumns(): Double {
var spaceNeeded = 0.0
this[Fixed::class]?.forEach {
val rt = it.resizeType as Fixed
it.prefWidth = rt.width.toDouble()
spaceNeeded += it.width
}
return spaceNeeded
}
/**
* Removes elements from the list in a sorted way with a cycle:
*
* 1. removes elements that fail the [filter]
* 2. find the first sorted element with the [sorter]
* 3. change the state of the element with the [iteration]
* 4. if [iteration] returns true, start again.
*
* @return the reduced list
*/
private inline fun <T, R : Comparable<R>> List<T>.reduceSorted(
crossinline sorter: T.() -> R,
noinline filter: T.() -> Boolean,
iteration: (T) -> Boolean
): List<T> {
val removingList = asSequence().filter(filter).sortedBy(sorter).toMutableList()
while (removingList.any()) {
val element = removingList.first()
if (!iteration(element)) break
if (!element.filter()) removingList.remove(element)
removingList.sortBy(sorter)
}
return removingList
} | apache-2.0 | 80d01d57499b75f9be2c73671813f84b | 37.107383 | 193 | 0.671349 | 4.319323 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/test/kotlin/app/cash/sqldelight/core/queries/async/AsyncMutatorQueryTypeTest.kt | 1 | 4233 | package app.cash.sqldelight.core.queries.async
import app.cash.sqldelight.core.compiler.MutatorQueryGenerator
import app.cash.sqldelight.test.util.FixtureCompiler
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class AsyncMutatorQueryTypeTest {
@get:Rule val tempFolder = TemporaryFolder()
@Test fun `type is generated properly for no result set changes`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE data (
| id INTEGER AS kotlin.Int PRIMARY KEY,
| value TEXT AS kotlin.collections.List<kotlin.String>
|);
|
|insertData:
|INSERT INTO data
|VALUES (?, ?);
""".trimMargin(),
tempFolder,
generateAsync = true,
)
val mutator = file.namedMutators.first()
val generator = MutatorQueryGenerator(mutator)
assertThat(generator.function().toString()).isEqualTo(
"""
|public suspend fun insertData(id: kotlin.Int?, value_: kotlin.collections.List<kotlin.String>?): kotlin.Unit {
| driver.execute(${mutator.id}, ""${'"'}
| |INSERT INTO data
| |VALUES (?, ?)
| ""${'"'}.trimMargin(), 2) {
| bindLong(0, id?.let { data_Adapter.idAdapter.encode(it) })
| bindString(1, value_?.let { data_Adapter.value_Adapter.encode(it) })
| }.await()
| notifyQueries(1642410240) { emit ->
| emit("data")
| }
|}
|
""".trimMargin(),
)
}
@Test fun `type is generated properly for result set changes in same file`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE data (
| id INTEGER AS kotlin.Int PRIMARY KEY,
| value TEXT AS kotlin.collections.List<kotlin.String>
|);
|
|selectForId:
|SELECT *
|FROM data
|WHERE id = ?;
|
|insertData:
|INSERT INTO data
|VALUES (?, ?);
""".trimMargin(),
tempFolder,
fileName = "Data.sq",
generateAsync = true,
)
val mutator = file.namedMutators.first()
val generator = MutatorQueryGenerator(mutator)
assertThat(generator.function().toString()).isEqualTo(
"""
|public suspend fun insertData(id: kotlin.Int?, value_: kotlin.collections.List<kotlin.String>?): kotlin.Unit {
| driver.execute(${mutator.id}, ""${'"'}
| |INSERT INTO data
| |VALUES (?, ?)
| ""${'"'}.trimMargin(), 2) {
| bindLong(0, id?.let { data_Adapter.idAdapter.encode(it) })
| bindString(1, value_?.let { data_Adapter.value_Adapter.encode(it) })
| }.await()
| notifyQueries(${mutator.id}) { emit ->
| emit("data")
| }
|}
|
""".trimMargin(),
)
}
@Test fun `type is generated properly for result set changes in different file`() {
FixtureCompiler.writeSql(
"""
|selectForId:
|SELECT *
|FROM data
|WHERE id = ?;
""".trimMargin(),
tempFolder,
fileName = "OtherData.sq",
)
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE data (
| id INTEGER AS kotlin.Int PRIMARY KEY,
| value TEXT AS kotlin.collections.List<kotlin.String>
|);
|
|insertData:
|INSERT INTO data
|VALUES (?, ?);
""".trimMargin(),
tempFolder,
fileName = "Data.sq",
generateAsync = true,
)
val mutator = file.namedMutators.first()
val generator = MutatorQueryGenerator(mutator)
assertThat(generator.function().toString()).isEqualTo(
"""
|public suspend fun insertData(id: kotlin.Int?, value_: kotlin.collections.List<kotlin.String>?): kotlin.Unit {
| driver.execute(${mutator.id}, ""${'"'}
| |INSERT INTO data
| |VALUES (?, ?)
| ""${'"'}.trimMargin(), 2) {
| bindLong(0, id?.let { data_Adapter.idAdapter.encode(it) })
| bindString(1, value_?.let { data_Adapter.value_Adapter.encode(it) })
| }.await()
| notifyQueries(${mutator.id}) { emit ->
| emit("data")
| }
|}
|
""".trimMargin(),
)
}
}
| apache-2.0 | d4f9f07295c159d0e4ef05987fb71049 | 28.395833 | 117 | 0.564611 | 4.06238 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/KatydidHtmlElementImpl.kt | 1 | 3156 | //
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements
import o.katydid.vdom.elements.KatydidHtmlElement
import o.katydid.vdom.types.EDirection
import x.katydid.vdom.dom.Document
import x.katydid.vdom.dom.Node
//---------------------------------------------------------------------------------------------------------------------
/**
* Abstract Katydid class corresponding to a DOM HTMLElement node. Accepts the global attributes available
* to most HTML tags.
* @param Msg the type of message returned by events from this element when an Elm-like architecture is in use.
*
* @constructor Constructs a new HTML element with given attributes.
* @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class".
* @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element.
* @param accesskey a string specifying the HTML accesskey value.
* @param contenteditable whether the element has editable content.
* @param draggable controls whether or not the element is draggable.
* @param dir the left-to-right direction of text inside this element.
* @param hidden true if the element is to be hidden.
* @param lang the language of text within this element.
* @param spellcheck whether the element is subject to spell checking.
* @param style a string containing CSS for this element.
* @param tabindex the tab index for the element.
* @param title a tool tip for the element.
* @param translate whether to translate text within this element.
*/
@Suppress("unused")
internal abstract class KatydidHtmlElementImpl<Msg>(
selector: String?,
key: Any?,
accesskey: Char? = null,
contenteditable: Boolean? = null,
dir: EDirection? = null,
draggable: Boolean? = null,
hidden: Boolean? = null,
lang: String? = null,
spellcheck: Boolean? = null,
style: String? = null,
tabindex: Int? = null,
title: String? = null,
translate: Boolean? = null
) : KatydidElementImpl<Msg>(selector, key, style, tabindex), KatydidHtmlElement<Msg> {
init {
check( draggable == null || title !=null ) { "Draggable elements should have a title." }
// TODO: need to output a string with Unicode escapes for non-ASCII characters
setAttribute("accesskey", accesskey?.toString())
setTrueFalseAttribute("contenteditable", contenteditable)
setAttribute("dir", dir?.toHtmlString())
setTrueFalseAttribute("draggable", draggable)
setBooleanAttribute("hidden", hidden)
setAttribute("lang", lang)
setTrueFalseAttribute("spellcheck", spellcheck)
setAttribute("title", title)
setYesNoAttribute("translate", translate)
}
override fun createDomNode(document: Document, parentDomNode: Node, followingDomChild: Node?) {
val childElement = document.createElement(nodeName)
establish(childElement)
parentDomNode.insertBefore(childElement, followingDomChild)
}
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | b89fcedfb082d1c652fdf37e60033aa0 | 39.461538 | 119 | 0.662548 | 4.675556 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/TTS.kt | 1 | 3781 | /*
* Copyright (c) 2021 Tyler Lewis <[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/>.
*/
// This time, we're going to be doing the most that we can using ReadText.java. Rather than the reimplementation
// that happened with branch Cloze_TTS_#9590.
package com.ichi2.anki.cardviewer
import android.content.Context
import com.ichi2.anki.CardUtils
import com.ichi2.anki.R
import com.ichi2.anki.ReadText
import com.ichi2.libanki.Card
import com.ichi2.libanki.Sound.SoundSide
import com.ichi2.libanki.TTSTag
import com.ichi2.libanki.Utils
import com.ichi2.libanki.template.TemplateFilters
class TTS {
@get:JvmName("isEnabled")
var enabled: Boolean = false
private val mTTS: ReadText? = null
/**
* Returns the card ordinal for TTS language storage.
*
* The ordinal of a Cloze card denotes the cloze deletion, causing the TTS
* language to be requested and stored on every new highest cloze deletion when
* used normally.
*
* @param card The card to check the type of before determining the ordinal.
* @return The card ordinal. If it's a Cloze card, returns 0.
*/
private fun getOrdUsingCardType(card: Card): Int {
return if (card.model().isCloze) {
0
} else {
card.ord
}
}
/**
* Reads the text (using TTS) for the given side of a card.
*
* @param card The card to play TTS for
* @param cardSide The side of the current card to play TTS for
*/
fun readCardText(ttsTags: List<TTSTag>, card: Card, cardSide: SoundSide) {
ReadText.readCardSide(ttsTags, cardSide, CardUtils.getDeckIdForCard(card), getOrdUsingCardType(card))
}
/**
* Ask the user what language they want.
*
* @param card The card to read text from
* @param qa The card question or card answer
*/
fun selectTts(context: Context, card: Card, qa: SoundSide) {
val textToRead = if (qa == SoundSide.QUESTION) card.q(true) else card.pureAnswer
// get the text from the card
ReadText.selectTts(getTextForTts(context, textToRead), CardUtils.getDeckIdForCard(card), getOrdUsingCardType(card), qa)
}
fun getTextForTts(context: Context, text: String): String {
val clozeReplacement = context.getString(R.string.reviewer_tts_cloze_spoken_replacement)
val clozeReplaced = text.replace(TemplateFilters.CLOZE_DELETION_REPLACEMENT, clozeReplacement)
return Utils.stripHTML(clozeReplaced)
}
fun initialize(ctx: Context, listener: ReadText.ReadTextListener) {
if (!enabled) {
return
}
ReadText.initializeTts(ctx, listener)
}
/**
* Request that TextToSpeech is stopped and shutdown after it it no longer being used
* by the context that initialized it.
* No-op if the current instance of TextToSpeech was initialized by another Context
* @param context The context used during {@link #initializeTts(Context, ReadTextListener)}
*/
fun releaseTts(context: Context) {
if (!enabled) {
return
}
ReadText.releaseTts(context)
}
}
| gpl-3.0 | bbe2ed030a05af95d659b41794ed29e6 | 36.068627 | 127 | 0.685797 | 3.934443 | false | false | false | false |
panpf/sketch | sample/src/main/java/com/github/panpf/sketch/sample/ui/photo/pexels/PexelsPhotoListComposeFragment.kt | 1 | 4520 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.sample.ui.photo.pexels
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.github.panpf.sketch.sample.NavMainDirections
import com.github.panpf.sketch.sample.image.SettingsEventViewModel
import com.github.panpf.sketch.sample.model.ImageDetail
import com.github.panpf.sketch.sample.model.Photo
import com.github.panpf.sketch.sample.ui.base.ToolbarFragment
import com.github.panpf.sketch.sample.ui.common.menu.ToolbarMenuViewModel
import kotlinx.coroutines.launch
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class PexelsPhotoListComposeFragment : ToolbarFragment() {
private val settingsEventViewModel by viewModels<SettingsEventViewModel>()
private val pexelsPhotoListViewModel by viewModels<PexelsPhotoListViewModel>()
private val toolbarMenuViewModel by viewModels<ToolbarMenuViewModel> {
ToolbarMenuViewModel.Factory(
requireActivity().application,
showLayoutModeMenu = false,
showPlayMenu = false,
fromComposePage = true,
)
}
override fun createView(toolbar: Toolbar, inflater: LayoutInflater, parent: ViewGroup?): View {
return ComposeView(requireContext()).apply {
setContent {
PhotoListContent(
photoPagingFlow = pexelsPhotoListViewModel.pagingFlow,
restartImageFlow = settingsEventViewModel.listRestartImageFlow,
reloadFlow = settingsEventViewModel.listReloadFlow
) { items, _, index ->
startImageDetail(items, index)
}
}
}
}
override fun onViewCreated(toolbar: Toolbar, savedInstanceState: Bundle?) {
super.onViewCreated(toolbar, savedInstanceState)
toolbar.apply {
title = "Pexels Photos"
subtitle = "Compose"
viewLifecycleOwner.lifecycleScope.launch {
toolbarMenuViewModel.menuFlow.collect { list ->
menu.clear()
list.forEachIndexed { groupIndex, group ->
group.items.forEachIndexed { index, menuItemInfo ->
menu.add(groupIndex, index, index, menuItemInfo.title).apply {
menuItemInfo.iconResId?.let { iconResId ->
setIcon(iconResId)
}
setOnMenuItemClickListener {
menuItemInfo.onClick(this@PexelsPhotoListComposeFragment)
true
}
setShowAsAction(menuItemInfo.showAsAction)
}
}
}
}
}
}
}
private fun startImageDetail(items: List<Photo>, position: Int) {
val imageList = items.mapIndexedNotNull { index, photo ->
if (index >= position - 50 && index <= position + 50) {
ImageDetail(
position = index,
originUrl = photo.originalUrl,
mediumUrl = photo.detailPreviewUrl,
thumbnailUrl = photo.listThumbnailUrl,
)
} else {
null
}
}
findNavController().navigate(
NavMainDirections.actionGlobalImageViewerPagerFragment(
Json.encodeToString(imageList),
position,
),
)
}
} | apache-2.0 | 0b625e9f49d1f1cd3935c58522c71e7b | 39.72973 | 99 | 0.61792 | 5.32391 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/actions/appplay/AppPlayAction.kt | 1 | 6114 | package com.matejdro.wearmusiccenter.actions.appplay
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.PersistableBundle
import android.view.InputDevice
import android.view.KeyEvent
import androidx.appcompat.content.res.AppCompatResources
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.ActionHandler
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.actions.SelectableAction
import com.matejdro.wearmusiccenter.music.MusicService
import com.matejdro.wearmusiccenter.music.isPlaying
import kotlinx.coroutines.delay
import javax.inject.Inject
class AppPlayAction : SelectableAction {
companion object {
const val KEY_PACKAGE_NAME = "PACKAGE_NAME"
const val KEY_CLASS_NAME = "COMPONENT_NAME"
}
private lateinit var receiverComponent: ComponentName
constructor(context: Context, receiverComponent: ComponentName) : super(context) {
this.receiverComponent = receiverComponent
}
constructor(context: Context, bundle: PersistableBundle) : super(context, bundle) {
this.receiverComponent = ComponentName(
bundle.getString(KEY_PACKAGE_NAME)!!,
bundle.getString(KEY_CLASS_NAME)!!
)
}
private val lazyName by lazy {
val appName: String = try {
val appInfo = context.packageManager.getApplicationInfo(receiverComponent.packageName, 0)
context.packageManager.getApplicationLabel(appInfo).toString()
} catch (ignored: PackageManager.NameNotFoundException) {
AppCompatResources.getDrawable(context, android.R.drawable.sym_def_app_icon)
context.getString(R.string.uninstalled_app)
}
context.getString(R.string.play_app, appName)
}
override fun writeToBundle(bundle: PersistableBundle) {
super.writeToBundle(bundle)
bundle.putString(KEY_PACKAGE_NAME, receiverComponent.packageName)
bundle.putString(KEY_CLASS_NAME, receiverComponent.className)
}
override fun retrieveTitle(): String = lazyName
override val defaultIcon: Drawable
get() = try {
context.packageManager.getApplicationIcon(receiverComponent.packageName)
} catch (ignored: PackageManager.NameNotFoundException) {
AppCompatResources.getDrawable(context, android.R.drawable.sym_def_app_icon)!!
}
override fun isEqualToAction(other: PhoneAction): Boolean {
other as AppPlayAction
return super.isEqualToAction(other) && this.receiverComponent == other.receiverComponent
}
class Handler @Inject constructor(
private val service: MusicService
) : ActionHandler<AppPlayAction> {
override suspend fun handleAction(action: AppPlayAction) {
val receiverComponent = action.receiverComponent
// Some apps (Spotify for example) seems to obey commands
// sent from AVRCP device more than others. If there is AVRCP bluetooth device
// available, use it
var pickedDeviceID = -1
for (deviceId in InputDevice.getDeviceIds()) {
val device = InputDevice.getDevice(deviceId)
if (device.name == "AVRCP") {
pickedDeviceID = deviceId
}
}
val androidContext = service
dispatchUpDownEvents(pickedDeviceID, receiverComponent)
delay(2000)
if (service.currentMediaController?.packageName == receiverComponent.packageName &&
service.currentMediaController?.isPlaying() == true) {
return
}
// Media is still not playing.
// Some players do not handle background starts very well. Start their UI activity first.
val launcherActivity = androidContext.packageManager.getLaunchIntentForPackage(receiverComponent.packageName)
if (launcherActivity != null) {
androidContext.startActivity(launcherActivity)
delay(500)
if (service.currentMediaController?.packageName == receiverComponent.packageName &&
service.currentMediaController?.isPlaying() == true) {
// In the time it took for activity to launch, media has already started playing. Nothing to do.
return
}
dispatchUpDownEvents(pickedDeviceID, receiverComponent)
delay(500)
}
if (service.currentMediaController?.packageName == receiverComponent.packageName &&
service.currentMediaController?.isPlaying() == true) {
return
}
// Media is still not playing.
// Maybe UI activity took some time to restart?
// Retry sending play command one last time after 3 second delay
delay(3000)
dispatchUpDownEvents(pickedDeviceID, receiverComponent)
}
private fun dispatchUpDownEvents(
pickedDeviceID: Int,
receiverComponent: ComponentName,
eventTime: Long = System.currentTimeMillis()
) {
dispatchKeyEvent(
KeyEvent(0, eventTime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY, 0, 0, pickedDeviceID, 0),
receiverComponent
)
dispatchKeyEvent(
KeyEvent(0, eventTime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY, 0, 0, pickedDeviceID, 0),
receiverComponent
)
}
private fun dispatchKeyEvent(keyEvent: KeyEvent, receiverComponent: ComponentName) {
val intent = Intent(Intent.ACTION_MEDIA_BUTTON)
intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent)
intent.component = receiverComponent
service.sendBroadcast(intent)
}
}
}
| gpl-3.0 | 778a8441754cecc176251575ac41bf6e | 38.960784 | 121 | 0.656362 | 5.307292 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/ui/trackview/TrackViewFragment.kt | 1 | 2711 | package com.peterlaurence.trekme.ui.trackview
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.peterlaurence.trekme.R
import com.peterlaurence.trekme.core.track.TrackStatistics
import com.peterlaurence.trekme.util.UnitFormatter
import kotlinx.android.synthetic.main.fragment_track_view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* This fragment provides a view of a track's statistics.
*
* @author peterLaurence on 28/10/18
*/
class TrackViewFragment : Fragment() {
companion object {
private const val ARG_STATS = "stats"
private const val ARG_TITLE = "title"
@JvmStatic
fun newInstance(trackStats: TrackStatistics, title: String): Fragment {
val fragment = Fragment()
val args = Bundle()
args.putParcelable(ARG_STATS, trackStats)
args.putString(ARG_TITLE, title)
fragment.arguments = args
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_track_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
trackStatsTitle.text = savedInstanceState?.getString(ARG_TITLE) ?: getText(R.string.current_recording)
super.onViewCreated(view, savedInstanceState)
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
/* When the user goes back and forth or rotates the device, we should display the last values */
val event = EventBus.getDefault().getStickyEvent(TrackStatistics::class.java)
if (event != null) {
setStatistics(event)
}
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onTrackStatistics(event: TrackStatistics) {
setStatistics(event)
}
private fun setStatistics(statistics: TrackStatistics) {
trackDistanceView.setDistanceText(
UnitFormatter.formatDistance(statistics.distance))
trackElevationStackView.setElevationStack(
UnitFormatter.formatDistance(statistics.elevationUpStack),
UnitFormatter.formatDistance(statistics.elevationDownStack))
trackDurationView.setDurationText(
UnitFormatter.formationDuration(statistics.durationInSecond)
)
}
} | gpl-3.0 | 5d14c0b983bce972fe5030b48ba89904 | 32.9 | 116 | 0.697529 | 4.69844 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/notifications/ScopedExpoNotificationBuilder.kt | 2 | 3151 | package host.exp.exponent.notifications
import android.content.Context
import android.util.Log
import expo.modules.notifications.notifications.channels.managers.NotificationsChannelManager
import expo.modules.notifications.notifications.interfaces.NotificationBuilder
import expo.modules.notifications.notifications.model.Notification
import expo.modules.notifications.notifications.presentation.builders.CategoryAwareNotificationBuilder
import expo.modules.notifications.service.delegates.SharedPreferencesNotificationCategoriesStore
import expo.modules.manifests.core.Manifest
import host.exp.exponent.Constants
import host.exp.exponent.ExponentManifest
import host.exp.exponent.di.NativeModuleDepsProvider
import host.exp.exponent.kernel.ExperienceKey
import host.exp.exponent.notifications.model.ScopedNotificationRequest
import host.exp.exponent.storage.ExponentDB
import host.exp.expoview.R
import org.json.JSONException
import versioned.host.exp.exponent.modules.api.notifications.channels.ScopedNotificationsChannelManager
import versioned.host.exp.exponent.modules.api.notifications.channels.ScopedNotificationsGroupManager
import javax.inject.Inject
open class ScopedExpoNotificationBuilder(
context: Context,
store: SharedPreferencesNotificationCategoriesStore?
) : CategoryAwareNotificationBuilder(context, store!!) {
@Inject
lateinit var exponentManifest: ExponentManifest
var manifest: Manifest? = null
var experienceKey: ExperienceKey? = null
override fun setNotification(notification: Notification): NotificationBuilder {
super.setNotification(notification)
// We parse manifest here to have easy access to it from other methods.
val requester = getNotification().notificationRequest
if (requester is ScopedNotificationRequest) {
val experienceScopeKey = requester.experienceScopeKeyString
try {
val exponentDBObject = ExponentDB.experienceScopeKeyToExperienceSync(experienceScopeKey!!)
manifest = exponentDBObject!!.manifest
experienceKey = ExperienceKey.fromManifest(manifest!!)
} catch (e: JSONException) {
Log.e("notifications", "Couldn't parse manifest.", e)
e.printStackTrace()
}
}
return this
}
override fun getNotificationsChannelManager(): NotificationsChannelManager {
return if (experienceKey == null) {
super.getNotificationsChannelManager()
} else ScopedNotificationsChannelManager(
context,
experienceKey,
ScopedNotificationsGroupManager(
context,
experienceKey
)
)
}
override fun getIcon(): Int {
return if (Constants.isStandaloneApp()) R.drawable.shell_notification_icon else R.drawable.notification_icon
}
override fun getColor(): Number? {
// Try to use color defined in notification content
if (notificationContent.color != null) {
return notificationContent.color
}
return if (manifest == null) {
super.getColor()
} else NotificationHelper.getColor(null, manifest!!, exponentManifest)
}
init {
NativeModuleDepsProvider.instance.inject(ScopedExpoNotificationBuilder::class.java, this)
}
}
| bsd-3-clause | 190f294a94a83790014d671392a3aa41 | 37.426829 | 112 | 0.785148 | 5.165574 | false | false | false | false |
AndroidX/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/BloodGlucoseRecord.kt | 3 | 7307 | /*
* Copyright (C) 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.health.connect.client.records
import androidx.annotation.IntDef
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.BloodGlucoseRecord.SpecimenSource
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.BloodGlucose
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the concentration of glucose in the blood. Each record represents a single instantaneous
* blood glucose reading.
*/
public class BloodGlucoseRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/**
* Blood glucose level or concentration. Required field. Valid range: 0-50 mmol/L.
*
* @see BloodGlucose
*/
public val level: BloodGlucose,
/**
* Type of body fluid used to measure the blood glucose. Optional, enum field. Allowed values:
* [SpecimenSource].
*
* @see SpecimenSource
*/
@property:SpecimenSources public val specimenSource: Int = SPECIMEN_SOURCE_UNKNOWN,
/**
* Type of meal related to the blood glucose measurement. Optional, enum field. Allowed values:
* [MealType].
*
* @see MealType
*/
@property:MealTypes public val mealType: Int = MealType.MEAL_TYPE_UNKNOWN,
/**
* Relationship of the meal to the blood glucose measurement. Optional, enum field. Allowed
* values: [RelationToMeal].
*
* @see RelationToMeal
*/
@property:RelationToMeals public val relationToMeal: Int = RELATION_TO_MEAL_UNKNOWN,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
init {
level.requireNotLess(other = level.zero(), name = "level")
level.requireNotMore(other = MAX_BLOOD_GLUCOSE_LEVEL, name = "level")
}
/**
* List of supported blood glucose specimen sources (type of body fluid used to measure the
* blood glucose).
*/
internal object SpecimenSource {
const val INTERSTITIAL_FLUID = "interstitial_fluid"
const val CAPILLARY_BLOOD = "capillary_blood"
const val PLASMA = "plasma"
const val SERUM = "serum"
const val TEARS = "tears"
const val WHOLE_BLOOD = "whole_blood"
}
/** Temporal relationship of measurement time to a meal. */
internal object RelationToMeal {
const val GENERAL = "general"
const val FASTING = "fasting"
const val BEFORE_MEAL = "before_meal"
const val AFTER_MEAL = "after_meal"
}
companion object {
private val MAX_BLOOD_GLUCOSE_LEVEL = BloodGlucose.millimolesPerLiter(50.0)
const val RELATION_TO_MEAL_UNKNOWN = 0
const val RELATION_TO_MEAL_GENERAL = 1
const val RELATION_TO_MEAL_FASTING = 2
const val RELATION_TO_MEAL_BEFORE_MEAL = 3
const val RELATION_TO_MEAL_AFTER_MEAL = 4
const val SPECIMEN_SOURCE_UNKNOWN = 0
const val SPECIMEN_SOURCE_INTERSTITIAL_FLUID = 1
const val SPECIMEN_SOURCE_CAPILLARY_BLOOD = 2
const val SPECIMEN_SOURCE_PLASMA = 3
const val SPECIMEN_SOURCE_SERUM = 4
const val SPECIMEN_SOURCE_TEARS = 5
const val SPECIMEN_SOURCE_WHOLE_BLOOD = 6
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val RELATION_TO_MEAL_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
RelationToMeal.GENERAL to RELATION_TO_MEAL_GENERAL,
RelationToMeal.AFTER_MEAL to RELATION_TO_MEAL_AFTER_MEAL,
RelationToMeal.FASTING to RELATION_TO_MEAL_FASTING,
RelationToMeal.BEFORE_MEAL to RELATION_TO_MEAL_BEFORE_MEAL
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val RELATION_TO_MEAL_INT_TO_STRING_MAP = RELATION_TO_MEAL_STRING_TO_INT_MAP.reverse()
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val SPECIMEN_SOURCE_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
SpecimenSource.INTERSTITIAL_FLUID to SPECIMEN_SOURCE_INTERSTITIAL_FLUID,
SpecimenSource.CAPILLARY_BLOOD to SPECIMEN_SOURCE_CAPILLARY_BLOOD,
SpecimenSource.PLASMA to SPECIMEN_SOURCE_PLASMA,
SpecimenSource.TEARS to SPECIMEN_SOURCE_TEARS,
SpecimenSource.WHOLE_BLOOD to SPECIMEN_SOURCE_WHOLE_BLOOD,
SpecimenSource.SERUM to SPECIMEN_SOURCE_SERUM
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val SPECIMEN_SOURCE_INT_TO_STRING_MAP = SPECIMEN_SOURCE_STRING_TO_INT_MAP.reverse()
}
/**
* List of supported blood glucose specimen sources (type of body fluid used to measure the
* blood glucose).
*
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
SPECIMEN_SOURCE_INTERSTITIAL_FLUID,
SPECIMEN_SOURCE_CAPILLARY_BLOOD,
SPECIMEN_SOURCE_PLASMA,
SPECIMEN_SOURCE_SERUM,
SPECIMEN_SOURCE_TEARS,
SPECIMEN_SOURCE_WHOLE_BLOOD,
]
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
annotation class SpecimenSources
/**
* Temporal relationship of measurement time to a meal.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
RELATION_TO_MEAL_GENERAL,
RELATION_TO_MEAL_FASTING,
RELATION_TO_MEAL_BEFORE_MEAL,
RELATION_TO_MEAL_AFTER_MEAL,
]
)
annotation class RelationToMeals
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BloodGlucoseRecord
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (level != other.level) return false
if (specimenSource != other.specimenSource) return false
if (mealType != other.mealType) return false
if (relationToMeal != other.relationToMeal) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + level.hashCode()
result = 31 * result + specimenSource
result = 31 * result + mealType
result = 31 * result + relationToMeal
result = 31 * result + metadata.hashCode()
return result
}
}
| apache-2.0 | 0c35684bfad9b57d3064b0aaad2648d3 | 34.818627 | 100 | 0.644861 | 4.032561 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/utils/import/RsImportHelper.kt | 2 | 8328 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils.import
import org.rust.ide.settings.RsCodeInsightSettings
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsQualifiedNamedElement
import org.rust.lang.core.psi.ext.typeParameters
import org.rust.lang.core.resolve.*
import org.rust.lang.core.types.Substitution
import org.rust.lang.core.types.emptySubstitution
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.infer.substitute
import org.rust.lang.core.types.normType
import org.rust.lang.core.types.ty.*
import org.rust.stdext.intersects
object RsImportHelper {
fun importTypeReferencesFromElement(context: RsElement, element: RsElement) =
importTypeReferencesFromElements(context, listOf(element))
private fun importTypeReferencesFromElements(context: RsElement, elements: Collection<RsElement>) {
val (toImport, _) = getTypeReferencesInfoFromElements(context, elements)
importElements(context, toImport)
}
fun importTypeReferencesFromTys(
context: RsElement,
tys: Collection<Ty>,
useAliases: Boolean = true,
skipUnchangedDefaultTypeArguments: Boolean = true
) {
val (toImport, _) = getTypeReferencesInfoFromTys(
context,
*tys.toTypedArray(),
useAliases = useAliases,
skipUnchangedDefaultTypeArguments = skipUnchangedDefaultTypeArguments
)
importElements(context, toImport)
}
fun importTypeReferencesFromTy(
context: RsElement,
ty: Ty,
useAliases: Boolean = true,
skipUnchangedDefaultTypeArguments: Boolean = true
) {
importTypeReferencesFromTys(context, listOf(ty), useAliases, skipUnchangedDefaultTypeArguments)
}
fun importElement(context: RsElement, element: RsQualifiedNamedElement) =
importElements(context, setOf(element))
fun importElements(context: RsElement, elements: Set<RsQualifiedNamedElement>) {
if (!RsCodeInsightSettings.getInstance().importOutOfScopeItems) return
val importContext = ImportContext.from(context, ImportContext.Type.OTHER) ?: return
for (element in elements) {
val candidate = ImportCandidatesCollector.findImportCandidate(importContext, element)
candidate?.import(context)
}
}
// finds path to `element` from `context.containingMod`, taking into account reexports and glob imports
fun findPath(context: RsElement, element: RsQualifiedNamedElement): String? {
val importContext = ImportContext.from(context, ImportContext.Type.OTHER) ?: return null
val candidate = ImportCandidatesCollector.findImportCandidate(importContext, element)
return candidate?.info?.usePath
}
/**
* Traverses type references in `elements` and collects all items that unresolved in current context.
*/
private fun getTypeReferencesInfoFromElements(
context: RsElement,
elements: Collection<RsElement>,
): TypeReferencesInfo = getTypeReferencesInfo(context, elements) { ty, result ->
collectImportSubjectsFromTypeReferences(ty, result)
}
/**
* Traverse types in `elemTy` and collects all items that unresolved in current context.
*/
fun getTypeReferencesInfoFromTys(
context: RsElement,
vararg elemTys: Ty,
useAliases: Boolean = true,
skipUnchangedDefaultTypeArguments: Boolean = true
): TypeReferencesInfo = getTypeReferencesInfo(context, elemTys.toList()) { ty, result ->
collectImportSubjectsFromTy(ty, emptySubstitution, result, useAliases, skipUnchangedDefaultTypeArguments)
}
private fun <T> getTypeReferencesInfo(
context: RsElement,
elements: Collection<T>,
collector: (T, MutableSet<RsQualifiedNamedElement>) -> Unit
): TypeReferencesInfo {
val result = hashSetOf<RsQualifiedNamedElement>()
elements.forEach { collector(it, result) }
return processRawImportSubjects(context, result)
}
private fun collectImportSubjectsFromTypeReferences(
context: RsElement,
result: MutableSet<RsQualifiedNamedElement>,
) {
context.accept(object : RsVisitor() {
override fun visitPath(path: RsPath) {
val qualifier = path.path
if (qualifier == null) {
val item = path.reference?.resolve() as? RsQualifiedNamedElement
if (item != null) {
result += item
}
}
super.visitPath(path)
}
override fun visitElement(element: RsElement) =
element.acceptChildren(this)
})
}
private fun collectImportSubjectsFromTy(
ty: Ty,
subst: Substitution,
result: MutableSet<RsQualifiedNamedElement>,
useAliases: Boolean,
skipUnchangedDefaultTypeArguments: Boolean
) {
ty.substitute(subst).visitWith(object : TypeVisitor {
override fun visitTy(ty: Ty): Boolean {
val alias = ty.aliasedBy?.element.takeIf { useAliases } as? RsQualifiedNamedElement
if (alias != null) {
result += alias
return true
}
when (ty) {
is TyAdt -> {
result += ty.item
if (skipUnchangedDefaultTypeArguments) {
val filteredTypeArguments = ty.typeArguments
.zip(ty.item.typeParameters)
.dropLastWhile { (argumentTy, param) -> argumentTy.isEquivalentTo(param.typeReference?.normType) }
.map { (argumentTy, _) -> argumentTy }
return ty.copy(typeArguments = filteredTypeArguments).superVisitWith(this)
}
}
is TyAnon -> result += ty.traits.map { it.element }
is TyTraitObject -> result += ty.traits.map { it.element }
is TyProjection -> {
result += ty.trait.element
result += ty.target
}
}
return ty.superVisitWith(this)
}
})
}
/**
* Takes `rawImportSubjects` and filters items that are unresolved in the current `context`.
* Then splits the items into two sets:
* - Items that should be imported
* - Items that can't be imported
*/
private fun processRawImportSubjects(
context: RsElement,
rawImportSubjects: Set<RsQualifiedNamedElement>
): TypeReferencesInfo {
val subjectsWithName = rawImportSubjects.associateWithTo(hashMapOf()) { it.name }
val processor = createProcessor { entry ->
val element = entry.element ?: return@createProcessor false
if (subjectsWithName[element] == entry.name) {
subjectsWithName.remove(element)
}
subjectsWithName.isEmpty()
}
val itemsInScope = hashMapOf<String, Set<Namespace>>()
processWithShadowingAndUpdateScope(itemsInScope, TYPES_N_VALUES, processor) {
processNestedScopesUpwards(context, TYPES_N_VALUES, it)
}
val toImport = hashSetOf<RsQualifiedNamedElement>()
val toQualify = hashSetOf<RsQualifiedNamedElement>()
for ((item, name) in subjectsWithName) {
val existingNs = itemsInScope[name ?: continue]
if (existingNs != null && existingNs.intersects(item.namespaces)) {
toQualify += item
} else {
toImport += item
}
}
return TypeReferencesInfo(toImport, toQualify)
}
}
/**
* @param toImport Set of unresolved items that should be imported
* @param toQualify Set of unresolved items that can't be imported
*/
data class TypeReferencesInfo(
val toImport: Set<RsQualifiedNamedElement>,
val toQualify: Set<RsQualifiedNamedElement>
)
| mit | 69c4ba7e7692d1c92c107e7cbc993c68 | 38.283019 | 130 | 0.634606 | 4.936574 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/IntroduceLocalVariableIntention.kt | 2 | 1693 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.refactoring.introduceVariable.extractExpression
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.ancestors
import org.rust.lang.core.types.ty.TyUnit
import org.rust.lang.core.types.type
class IntroduceLocalVariableIntention : RsElementBaseIntentionAction<RsExpr>() {
override fun getText(): String = "Introduce local variable"
override fun getFamilyName(): String = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsExpr? {
val expr = element.ancestors
.takeWhile {
it !is RsBlock && it !is RsMatchExpr && it !is RsLambdaExpr
}
.find {
val parent = it.parent
parent is RsRetExpr
|| parent is RsExprStmt
|| parent is RsMatchArm && it == parent.expr
|| parent is RsLambdaExpr && it == parent.expr
} as? RsExpr
if (expr?.type is TyUnit) return null
return expr
}
override fun invoke(project: Project, editor: Editor, ctx: RsExpr) {
extractExpression(editor, ctx, postfixLet = false)
}
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo =
IntentionPreviewInfo.EMPTY
}
| mit | 63d2280c2c3502e0854dc4c4f3cf2e0a | 35.021277 | 105 | 0.679858 | 4.575676 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/person/model/Contact.kt | 1 | 913 | package de.tum.`in`.tumcampusapp.component.tumui.person.model
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import java.io.Serializable
/**
* Contact information of a TUM [Employee] or a generic [Person].
* Note: This model is based on the TUMOnline web service response format for a
* corresponding request.
*/
@Xml
data class Contact(
@PropertyElement(name = "zusatz_info")
var additionalInfo: String = "",
@PropertyElement(name = "fax")
var fax: String = "",
@PropertyElement(name = "www_homepage")
var homepage: String = "",
@PropertyElement(name = "mobiltelefon")
var mobilephone: String = "",
@PropertyElement(name = "telefon")
var telefon: String = ""
) : Serializable {
companion object {
private const val serialVersionUID = 4413581972047241018L
}
}
| gpl-3.0 | 04bbba6e612fb0ea28f2bbfbe2928710 | 29.433333 | 79 | 0.670318 | 4.09417 | false | false | false | false |
McGars/basekitk | app/src/main/java/com/mcgars/basekitkotlin/sample/ArrowToolbarViewController.kt | 1 | 1274 | package com.mcgars.basekitkotlin.sample
import android.view.MenuItem
import android.view.View
import com.mcgars.basekitk.tools.snack
import com.mcgars.basekitkotlin.R
import com.mcgars.basekitkotlin.decorator.ToolbarColorDecorator
import com.mcgars.basekitk.animatorHandlers.CircularRevealChangeHandler
import com.mcgars.basekitk.animatorHandlers.CircularRevealChangeHandlerCompat
/**
* Created by gars on 07.08.17.
*/
class ArrowToolbarViewController : EmptyViewController() {
override fun getTitleInt() = R.string.arrow
init {
setHasOptionsMenu(true)
overridePushHandler(CircularRevealChangeHandlerCompat().apply {
halfPosition = CircularRevealChangeHandler.TOP_CENTER
})
overridePopHandler(CircularRevealChangeHandlerCompat().apply {
halfPosition = CircularRevealChangeHandler.TOP_CENTER
})
addDecorator(ToolbarColorDecorator(this))
}
override fun onReady(view: View) {
super.onReady(view)
setHomeArrow(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
view?.snack("Home pressed")
return true
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | c40e6c24f80d312ff8cb79d09c65e7b4 | 30.097561 | 77 | 0.718995 | 4.701107 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/kotlin/src/main/kotlin/org/tsdes/advanced/kotlin/KotlinNull.kt | 1 | 508 | package org.tsdes.advanced.kotlin
/**
* Created by arcuri82 on 17-Aug-17.
*/
class KotlinNull {
fun bar(){
var foo = "foo"
foo = "changed"
//foo = null // doesn't compile
//note the "?" after the type
var bar : String? = "foo"
bar = null
}
// note the ?
fun startWithFoo(s: String?) : Boolean {
//doesn't compile
//return s.startsWith("foo")
//elvis operator
return s?.startsWith("foo") ?: false
}
} | lgpl-3.0 | 7ca6bfe940530505a492dbef736bf5f6 | 17.178571 | 44 | 0.517717 | 3.907692 | false | false | false | false |
androidx/androidx | constraintlayout/constraintlayout-compose/src/androidMain/kotlin/androidx/constraintlayout/compose/ChainConstrainScope.kt | 5 | 3394 | /*
* Copyright (C) 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.constraintlayout.compose
import androidx.compose.foundation.layout.LayoutScopeMarker
import androidx.compose.runtime.Stable
import androidx.constraintlayout.core.state.ConstraintReference
@LayoutScopeMarker
@Stable
class HorizontalChainScope internal constructor(internal val id: Any) {
internal val tasks = mutableListOf<(State) -> Unit>()
/**
* Reference to the [ConstraintLayout] itself, which can be used to specify constraints
* between itself and its children.
*/
val parent = ConstrainedLayoutReference(SolverState.PARENT)
/**
* The start anchor of the chain - can be constrained using [VerticalAnchorable.linkTo].
*/
val start: VerticalAnchorable = ChainVerticalAnchorable(tasks, id, -2)
/**
* The left anchor of the chain - can be constrained using [VerticalAnchorable.linkTo].
*/
val absoluteLeft: VerticalAnchorable = ChainVerticalAnchorable(tasks, id, 0)
/**
* The end anchor of the chain - can be constrained using [VerticalAnchorable.linkTo].
*/
val end: VerticalAnchorable = ChainVerticalAnchorable(tasks, id, -1)
/**
* The right anchor of the chain - can be constrained using [VerticalAnchorable.linkTo].
*/
val absoluteRight: VerticalAnchorable = ChainVerticalAnchorable(tasks, id, 1)
}
@LayoutScopeMarker
@Stable
class VerticalChainScope internal constructor(internal val id: Any) {
internal val tasks = mutableListOf<(State) -> Unit>()
/**
* Reference to the [ConstraintLayout] itself, which can be used to specify constraints
* between itself and its children.
*/
val parent = ConstrainedLayoutReference(SolverState.PARENT)
/**
* The top anchor of the chain - can be constrained using [HorizontalAnchorable.linkTo].
*/
val top: HorizontalAnchorable = ChainHorizontalAnchorable(tasks, id, 0)
/**
* The bottom anchor of the chain - can be constrained using [HorizontalAnchorable.linkTo].
*/
val bottom: HorizontalAnchorable = ChainHorizontalAnchorable(tasks, id, 1)
}
private class ChainVerticalAnchorable constructor(
tasks: MutableList<(State) -> Unit>,
private val id: Any,
index: Int
) : BaseVerticalAnchorable(tasks, index) {
override fun getConstraintReference(state: State): ConstraintReference =
state.helper(id, androidx.constraintlayout.core.state.State.Helper.HORIZONTAL_CHAIN)
}
private class ChainHorizontalAnchorable constructor(
tasks: MutableList<(State) -> Unit>,
private val id: Any,
index: Int
) : BaseHorizontalAnchorable(tasks, index) {
override fun getConstraintReference(state: State): ConstraintReference =
state.helper(id, androidx.constraintlayout.core.state.State.Helper.VERTICAL_CHAIN)
} | apache-2.0 | ebfe2747a91eca53b9cf80ac9caf3f52 | 35.505376 | 95 | 0.729817 | 4.513298 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/viewinterop/NestedScrollInterop.kt | 3 | 9315 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.viewinterop
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.demos.R
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.ViewCompat
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlin.math.roundToInt
private val ToolbarHeight = 48.dp
@SuppressLint("UnnecessaryLambdaCreation")
@Composable
private fun OuterComposeWithNestedScroll(factory: (Context) -> View) {
val toolbarHeightPx = with(LocalDensity.current) { ToolbarHeight.roundToPx().toFloat() }
val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
val newOffset = toolbarOffsetHeightPx.value + delta
toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
return Offset.Zero
}
}
}
// Compose Scrollable
Box(
Modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
TopAppBar(
modifier = Modifier
.height(ToolbarHeight)
.offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) },
title = { Text("toolbar offset is ${toolbarOffsetHeightPx.value}") }
)
// Android View
AndroidView(
factory = { context -> factory(context) },
modifier = Modifier.fillMaxWidth()
)
}
}
private fun AndroidViewWithNestedScrollEnabled(context: Context): View {
return LayoutInflater.from(context)
.inflate(R.layout.android_in_compose_nested_scroll_interop, null).apply {
with(findViewById<RecyclerView>(R.id.main_list)) {
layoutManager =
LinearLayoutManager(context, RecyclerView.VERTICAL, false)
adapter = NestedScrollInteropAdapter()
}
}.also {
ViewCompat.setNestedScrollingEnabled(it, true)
}
}
@Composable
internal fun NestedScrollInteropComposeParentWithAndroidChild() {
OuterComposeWithNestedScroll { context ->
AndroidViewWithNestedScrollEnabled(context)
}
}
@Composable
private fun LazyColumnWithNestedScrollInteropEnabled() {
LazyColumn(
modifier = Modifier.nestedScroll(
rememberNestedScrollInteropConnection()
),
contentPadding = PaddingValues(top = ToolbarHeight)
) {
item {
Text("This is a Lazy Column")
}
items(40) { item ->
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(item.toString())
}
}
}
}
@Composable
internal fun ComposeViewComposeNestedInterop() {
OuterComposeWithNestedScroll { context ->
LayoutInflater.from(context)
.inflate(R.layout.three_fold_nested_scroll_interop, null).apply {
with(findViewById<ComposeView>(R.id.compose_view)) {
setContent { LazyColumnWithNestedScrollInteropEnabled() }
}
}.also {
ViewCompat.setNestedScrollingEnabled(it, true)
}
}
}
private class NestedScrollInteropAdapter :
RecyclerView.Adapter<NestedScrollInteropAdapter.NestedScrollInteropViewHolder>() {
val items = (1..100).map { it.toString() }
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): NestedScrollInteropViewHolder {
return NestedScrollInteropViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.android_in_compose_nested_scroll_interop_list_item, parent, false)
)
}
override fun onBindViewHolder(holder: NestedScrollInteropViewHolder, position: Int) {
if (position == 0) {
holder.bind("This is a RV")
} else {
holder.bind(items[position])
}
}
override fun getItemCount(): Int = items.size
class NestedScrollInteropViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(item: String) {
itemView.findViewById<TextView>(R.id.list_item).text = item
}
}
}
internal class ComposeInAndroidCoordinatorLayout : ComponentActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.compose_in_android_coordinator_layout)
findViewById<ComposeView>(R.id.compose_view).apply {
setContent { LazyColumnWithNestedScrollInteropEnabled() }
}
}
}
internal class ViewComposeViewNestedScrollInteropDemo : ComponentActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.compose_in_android_coordinator_layout)
findViewById<ComposeView>(R.id.compose_view).apply {
setContent {
val nestedScrollInterop = rememberNestedScrollInteropConnection()
Box(modifier = Modifier.nestedScroll(nestedScrollInterop)) {
AndroidView({ context ->
AndroidViewWithNestedScrollEnabled(context)
}, modifier = Modifier.fillMaxWidth())
}
}
}
}
}
internal class BottomSheetFragmentNestedScrollInteropDemo : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.bottom_sheet_fragment_nestedscrollinterop_demo)
findViewById<Button>(R.id.button).setOnClickListener {
openFragment()
}
}
private fun openFragment() {
val addPhotoBottomDialogFragment = LazyListBottomSheetDialogFragment()
addPhotoBottomDialogFragment.show(supportFragmentManager, "tag")
}
}
internal class LazyListBottomSheetDialogFragment : BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_bottom_sheet, container)
view.findViewById<ComposeView>(R.id.compose_view).setContent {
Box(Modifier.nestedScroll(rememberNestedScrollInteropConnection())) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(100) {
Text("Item $it", Modifier.fillMaxWidth(), Color.Black)
}
}
}
}
return view
}
}
| apache-2.0 | 46cbefa8353ebc1ac959360b8f8ddaab | 35.245136 | 100 | 0.684487 | 5.101314 | false | false | false | false |
Sylvilagus/SylvaBBSClient | SylvaBBSClient/app/src/main/java/com/sylva/sylvabbsclient/view/TProgressDialogView.kt | 1 | 801 | package com.sylva.sylvabbsclient.view
import android.app.ProgressDialog
import android.view.View
import android.widget.TextView
/**
* Created by sylva on 2016/3/19.
*/
interface TProgressDialogView :IRunBackgroundView {
override fun showProgressView(message:String){
if (mPd == null) {
mPd = ProgressDialog(ctx)
mPd?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
mPd?.isIndeterminate = true
mPd?.setCancelable(false)
}
mPd?.setMessage(message)
mPd?.show()
}
override fun modifyProgressText(message:String){
mPd?.setMessage(message)
}
override fun hideProgressView(){
mPd?.dismiss()
mPd=null
}
companion object{
private var mPd: ProgressDialog?=null
}
} | apache-2.0 | 4d3524584c34dea1c455eec5d034581a | 24.870968 | 63 | 0.644195 | 4.128866 | false | false | false | false |
paulalewis/agl | src/main/kotlin/com/castlefrog/agl/domains/hex/HexState.kt | 1 | 5185 | package com.castlefrog.agl.domains.hex
import com.castlefrog.agl.State
data class HexState(
val boardSize: Int,
val bitBoards: Array<ByteArray> = Array(2) {
ByteArray((boardSize * boardSize + java.lang.Byte.SIZE - 1) / java.lang.Byte.SIZE)
},
var agentTurn: Byte = TURN_BLACK
) : State<HexState> {
companion object {
const val N_PLAYERS = 2
const val LOCATION_EMPTY = 0
const val LOCATION_BLACK = 1
const val LOCATION_WHITE = 2
const val TURN_BLACK: Byte = 0
const val TURN_WHITE: Byte = 1
}
override fun copy(): HexState {
return HexState(boardSize, bitBoards, agentTurn)
}
val locations: Array<ByteArray>
get() {
val locations = Array(boardSize) { ByteArray(boardSize) }
var i = 0
while (i < boardSize) {
var j = 0
while (j < boardSize) {
locations[i][j] = getLocation(i, j).toByte()
j += 1
}
i += 1
}
return locations
}
fun getLocation(x: Int, y: Int): Int {
checkLocationArgs(x, y)
val bitLocation = y * boardSize + x
val byteLocation = bitLocation / java.lang.Byte.SIZE
return when {
bitBoards[0][byteLocation].toInt() and (1 shl bitLocation % java.lang.Byte.SIZE) != 0 -> LOCATION_BLACK
bitBoards[1][byteLocation].toInt() and (1 shl bitLocation % java.lang.Byte.SIZE) != 0 -> LOCATION_WHITE
else -> LOCATION_EMPTY
}
}
fun isLocationEmpty(x: Int, y: Int): Boolean {
checkLocationArgs(x, y)
val bitLocation = y * boardSize + x
val byteLocation = bitLocation / java.lang.Byte.SIZE
return bitBoards[0][byteLocation].toInt() or bitBoards[1][byteLocation].toInt() and (1 shl bitLocation % java.lang.Byte.SIZE) == LOCATION_EMPTY
}
fun isLocationOnBoard(x: Int, y: Int): Boolean {
return x in 0 until boardSize && y in 0 until boardSize
}
val nPieces: Int
get() {
return (bitBoards[0].indices).sumOf {
Integer.bitCount((bitBoards[0][it].toInt() or bitBoards[1][it].toInt()) and 0xff)
}
}
fun setLocation(x: Int, y: Int, value: Int) {
checkLocationArgs(x, y)
val bitLocation = y * boardSize + x
val byteLocation = bitLocation / java.lang.Byte.SIZE
val byteShift = bitLocation % java.lang.Byte.SIZE
when (value) {
LOCATION_EMPTY -> {
bitBoards[0][byteLocation] =
(bitBoards[0][byteLocation].toInt() and (1 shl byteShift xor 0xff)).toByte()
bitBoards[1][byteLocation] =
(bitBoards[1][byteLocation].toInt() and (1 shl byteShift xor 0xff)).toByte()
}
LOCATION_BLACK -> {
bitBoards[0][byteLocation] = (bitBoards[0][byteLocation].toInt() or (1 shl byteShift)).toByte()
bitBoards[1][byteLocation] =
(bitBoards[1][byteLocation].toInt() and (1 shl byteShift xor 0xff)).toByte()
}
LOCATION_WHITE -> {
bitBoards[0][byteLocation] =
(bitBoards[0][byteLocation].toInt() and (1 shl byteShift xor 0xff)).toByte()
bitBoards[1][byteLocation] = (bitBoards[1][byteLocation].toInt() or (1 shl byteShift)).toByte()
}
}
}
private fun checkLocationArgs(x: Int, y: Int) {
if (!isLocationOnBoard(x, y))
throw IllegalArgumentException("(x=$x,y=$y) out of bounds")
}
override fun hashCode(): Int {
var hashCode = 17 + boardSize
hashCode = hashCode * 19 + bitBoards.contentHashCode()
hashCode = hashCode * 31 + agentTurn
return hashCode
}
override fun equals(other: Any?): Boolean {
if (other !is HexState) {
return false
}
if (bitBoards.size != other.bitBoards.size) {
return false
}
for (i in bitBoards.indices) {
if (bitBoards[i].size != other.bitBoards[i].size) {
return false
}
bitBoards[i].indices
.filter { other.bitBoards[i][it] != bitBoards[i][it] }
.forEach { _ -> return false }
}
return other.boardSize == boardSize && other.agentTurn == agentTurn
}
override fun toString(): String {
val output = StringBuilder()
for (i in boardSize - 1 downTo 0) {
for (j in i..boardSize - 2) {
output.append(" ")
}
for (j in 0 until boardSize) {
when (getLocation(j, i)) {
LOCATION_BLACK -> output.append("X")
LOCATION_WHITE -> output.append("O")
else -> output.append("-")
}
if (j != boardSize - 1) {
output.append(" ")
}
}
if (i != 0) {
output.append("\n")
}
}
return output.toString()
}
}
| mit | 36615332396c4de0290422c978d10d14 | 33.798658 | 151 | 0.526133 | 4.121622 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/create/CreateConferenceActivity.kt | 1 | 2011 | package me.proxer.app.chat.prv.create
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.commitNow
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.chat.prv.Participant
import me.proxer.app.util.extension.intentFor
import me.proxer.app.util.extension.startActivity
/**
* @author Ruben Gees
*/
class CreateConferenceActivity : DrawerActivity() {
companion object {
private const val IS_GROUP_EXTRA = "is_group"
private const val INITIAL_PARTICIPANT_EXTRA = "initial_participant"
fun navigateTo(context: Activity, isGroup: Boolean = false, initialParticipant: Participant? = null) {
context.startActivity<CreateConferenceActivity>(
IS_GROUP_EXTRA to isGroup,
INITIAL_PARTICIPANT_EXTRA to initialParticipant
)
}
fun getIntent(context: Activity, isGroup: Boolean = false, initialParticipant: Participant? = null): Intent {
return context.intentFor<CreateConferenceActivity>(
IS_GROUP_EXTRA to isGroup,
INITIAL_PARTICIPANT_EXTRA to initialParticipant
)
}
}
val isGroup: Boolean
get() = intent.getBooleanExtra(IS_GROUP_EXTRA, false)
val initialParticipant: Participant?
get() = intent.getParcelableExtra(INITIAL_PARTICIPANT_EXTRA)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar()
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, CreateConferenceFragment.newInstance())
}
}
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = when (isGroup) {
true -> getString(R.string.action_create_group)
false -> getString(R.string.action_create_chat)
}
}
}
| gpl-3.0 | 8b7d3a077ed09816c65d75e4fbc3884a | 31.435484 | 117 | 0.668324 | 4.754137 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/LuaFileStub.kt | 2 | 3636 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.lang.ASTNode
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiFile
import com.intellij.psi.StubBuilder
import com.intellij.psi.stubs.*
import com.intellij.psi.tree.IStubFileElementType
import com.intellij.util.io.StringRef
import com.tang.intellij.lua.lang.LuaLanguage
import com.tang.intellij.lua.lang.LuaParserDefinition
import com.tang.intellij.lua.psi.LuaPsiFile
/**
* Created by tangzx on 2016/11/27.
*/
class LuaFileElementType : IStubFileElementType<LuaFileStub>(LuaLanguage.INSTANCE) {
companion object {
val LOG = Logger.getInstance(LuaFileElementType::class.java)
}
// debug performance
override fun parseContents(chameleon: ASTNode): ASTNode? {
val psi = chameleon.psi
val t = System.currentTimeMillis()
val contents = super.parseContents(chameleon)
if (psi is LuaPsiFile) {
if (LOG.isDebugEnabled) {
val dt = System.currentTimeMillis() - t
val fileName = psi.name
println("$fileName : $dt")
LOG.debug("$fileName : $dt")
}
}
return contents
}
override fun getBuilder(): StubBuilder {
return object : DefaultStubBuilder() {
private var isTooLarger = false
override fun createStubForFile(file: PsiFile): StubElement<*> {
if (file is LuaPsiFile){
isTooLarger = file.tooLarger
return LuaFileStub(file)
}
return super.createStubForFile(file)
}
override fun skipChildProcessingWhenBuildingStubs(parent: ASTNode, node: ASTNode): Boolean {
return isTooLarger
}
}
}
override fun serialize(stub: LuaFileStub, dataStream: StubOutputStream) {
dataStream.writeName(stub.module)
dataStream.writeUTFFast(stub.uid)
if (LOG.isTraceEnabled) {
println("--------- START: ${stub.psi.name}")
println(stub.printTree())
println("--------- END: ${stub.psi.name}")
}
}
override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): LuaFileStub {
val moduleRef = dataStream.readName()
val uid = dataStream.readUTFFast()
return LuaFileStub(null, StringRef.toString(moduleRef), uid)
}
override fun getExternalId() = "lua.file"
}
class LuaFileStub : PsiFileStubImpl<LuaPsiFile> {
private var file: LuaPsiFile? = null
private var moduleName:String? = null
val uid: String
constructor(file: LuaPsiFile) : this(file, file.moduleName, file.uid)
constructor(file: LuaPsiFile?, module:String?, uid: String) : super(file) {
this.file = file
this.uid = uid
moduleName = module
}
val module: String? get() {
return moduleName
}
override fun getType(): LuaFileElementType = LuaParserDefinition.FILE
} | apache-2.0 | 533ebf09be1090dd7d731b5b2d7f4cba | 31.185841 | 104 | 0.651815 | 4.455882 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/activities/SettingsActivity.kt | 1 | 4504 | package com.habitrpg.wearos.habitica.ui.activities
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.wear.widget.WearableLinearLayoutManager
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ActivitySettingsBinding
import com.habitrpg.wearos.habitica.ui.adapters.SettingsAdapter
import com.habitrpg.wearos.habitica.ui.adapters.SettingsItem
import com.habitrpg.wearos.habitica.ui.viewmodels.SettingsViewModel
import com.habitrpg.wearos.habitica.ui.views.TextActionChipView
import com.habitrpg.wearos.habitica.util.HabiticaScrollingLayoutCallback
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class SettingsActivity: BaseActivity<ActivitySettingsBinding, SettingsViewModel>() {
override val viewModel: SettingsViewModel by viewModels()
private val adapter = SettingsAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivitySettingsBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
binding.root.apply {
layoutManager =
WearableLinearLayoutManager(this@SettingsActivity, HabiticaScrollingLayoutCallback())
adapter = [email protected]
}
adapter.data = buildSettings()
adapter.title = getString(R.string.settings)
lifecycleScope.launch {
appStateManager.isAppConnected.collect {
adapter.isDisconnected = !it
}
}
}
private fun logout() {
viewModel.logout()
try {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.build()
val client = GoogleSignIn.getClient(this, gso)
client.signOut()
} catch (e: Exception) {
}
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
private fun buildSettings(): List<SettingsItem> {
return listOf(
SettingsItem(
"sync",
getString(R.string.sync_data),
SettingsItem.Types.BUTTON,
null
) {
viewModel.resyncData()
},
SettingsItem(
"logout",
getString(R.string.logout),
SettingsItem.Types.BUTTON,
null
) {
showLogoutConfirmation()
},
SettingsItem(
"spacer",
getString(R.string.settings),
SettingsItem.Types.SPACER,
null
) {
},
SettingsItem(
"footer",
getString(R.string.version_info, versionName, versionCode),
SettingsItem.Types.FOOTER,
null
){
}
)
}
private val versionName: String by lazy {
try {
@Suppress("DEPRECATION")
packageManager?.getPackageInfo(packageName ?: "", 0)?.versionName ?: ""
} catch (e: PackageManager.NameNotFoundException) {
""
}
}
private val versionCode: Int by lazy {
try {
@Suppress("DEPRECATION")
packageManager?.getPackageInfo(packageName ?: "", 0)?.versionCode ?: 0
} catch (e: PackageManager.NameNotFoundException) {
0
}
}
private fun showLogoutConfirmation() {
val logoutDialog = Dialog(this)
val myLayout = layoutInflater.inflate(R.layout.logout_layout, null)
val positiveButton: TextActionChipView = myLayout.findViewById(R.id.logout_button)
positiveButton.setOnClickListener {
logout()
logoutDialog.dismiss()
}
val negativeButton: TextActionChipView = myLayout.findViewById(R.id.cancel_button)
negativeButton.setOnClickListener {
logoutDialog.dismiss()
}
logoutDialog.setContentView(myLayout)
logoutDialog.show()
}
} | gpl-3.0 | 5741a3f46087b3183efbd2aec66811a7 | 33.128788 | 123 | 0.633215 | 5.147429 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/activities/LoginActivity.kt | 1 | 6238 | package com.habitrpg.wearos.habitica.ui.activities
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.text.method.PasswordTransformationMethod
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ActivityLoginBinding
import com.habitrpg.common.habitica.helpers.DeviceCommunication
import com.habitrpg.wearos.habitica.ui.viewmodels.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LoginActivity: BaseActivity<ActivityLoginBinding, LoginViewModel>() {
enum class State {
INITIAL,
OTHER,
INPUT
}
override val viewModel: LoginViewModel by viewModels()
private var currentState: State = State.INITIAL
set(value) {
field = value
when(value) {
State.INITIAL -> {
binding.descriptionView.isVisible = true
binding.signInOnPhoneButton.isVisible = true
binding.otherButton.isVisible = true
binding.googleLoginButton.isVisible = false
binding.registerButton.isVisible = false
binding.usernamePasswordButton.isVisible = false
binding.usernameEditText.isVisible = false
binding.passwordEditText.isVisible = false
binding.loginButton.isVisible = false
}
State.OTHER -> {
binding.descriptionView.isVisible = false
binding.signInOnPhoneButton.isVisible = false
binding.otherButton.isVisible = false
binding.googleLoginButton.isVisible = true
binding.registerButton.isVisible = binding.registerButton.isEnabled
binding.usernamePasswordButton.isVisible = true
binding.usernameEditText.isVisible = false
binding.passwordEditText.isVisible = false
binding.loginButton.isVisible = false
}
State.INPUT -> {
binding.descriptionView.isVisible = false
binding.signInOnPhoneButton.isVisible = false
binding.otherButton.isVisible = false
binding.googleLoginButton.isVisible = false
binding.registerButton.isVisible = false
binding.usernamePasswordButton.isVisible = false
binding.usernameEditText.isVisible = true
binding.passwordEditText.isVisible = true
binding.loginButton.isVisible = true
}
}
binding.root.smoothScrollTo(0, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityLoginBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
viewModel.onLoginCompleted = {
startMainActivity()
}
binding.signInOnPhoneButton.setOnClickListener { openLoginOnPhone() }
binding.otherButton.setOnClickListener { currentState = State.OTHER }
binding.usernamePasswordButton.setOnClickListener { currentState = State.INPUT }
binding.loginButton.setOnClickListener { loginLocal() }
binding.googleLoginButton.setOnClickListener { loginGoogle() }
binding.registerButton.setOnClickListener { openRegisterOnPhone() }
binding.passwordEditText.transformationMethod = PasswordTransformationMethod()
binding.usernameEditText.doOnTextChanged { text, start, before, count ->
setLoginButtonIsEnabled()
}
binding.passwordEditText.doOnTextChanged { text, start, before, count ->
setLoginButtonIsEnabled()
}
currentState = State.INITIAL
}
private fun openRegisterOnPhone() {
openRemoteActivity(DeviceCommunication.SHOW_REGISTER, true)
}
private fun openLoginOnPhone() {
openRemoteActivity(DeviceCommunication.SHOW_LOGIN)
}
private fun loginLocal() {
val username: String = binding.usernameEditText.text.toString().trim { it <= ' ' }
val password: String = binding.passwordEditText.text.toString()
if (username.isEmpty() || password.isEmpty()) {
showValidationError(getString(R.string.login_validation_error_fieldsmissing))
return
}
viewModel.login(username, password) {
stopAnimatingProgress()
}
startAnimatingProgress()
}
private fun loginGoogle() {
viewModel.handleGoogleLogin(this, pickAccountResult)
}
private fun showValidationError(message: String) {
val alert = AlertDialog.Builder(this).create()
alert.setTitle(R.string.login_validation_error_title)
alert.setMessage(message)
alert.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok)) { thisAlert, _ ->
thisAlert.dismiss()
}
alert.show()
}
private fun setLoginButtonIsEnabled() {
binding.loginButton.isEnabled = binding.usernameEditText.text.isNotEmpty() && binding.passwordEditText.text.isNotEmpty()
}
private val pickAccountResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
viewModel.handleGoogleLoginResult(this, task, recoverFromPlayServicesErrorResult)
}
private val recoverFromPlayServicesErrorResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode != Activity.RESULT_CANCELED) {
val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
viewModel.handleGoogleLoginResult(this, task, null)
}
}
private fun startMainActivity() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
} | gpl-3.0 | 0023f4e4d1a76acea29fabffe0b0dad3 | 39.251613 | 128 | 0.681629 | 5.359107 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/core/presenters/CardPresenter.kt | 2 | 6051 | package org.stepic.droid.core.presenters
import android.os.Bundle
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import org.stepic.droid.adaptive.listeners.AdaptiveReactionListener
import org.stepic.droid.adaptive.listeners.AnswerListener
import org.stepic.droid.adaptive.model.Card
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.presenters.contracts.CardView
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.util.getStepType
import org.stepik.android.domain.submission.repository.SubmissionRepository
import org.stepik.android.model.Submission
import org.stepik.android.model.adaptive.Reaction
import retrofit2.HttpException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class CardPresenter(
val card: Card,
private val listener: AdaptiveReactionListener?,
private val answerListener: AnswerListener?
) : PresenterBase<CardView>() {
@Inject
lateinit var submissionRepository: SubmissionRepository
@Inject
@field:MainScheduler
lateinit var mainScheduler: Scheduler
@Inject
@field:BackgroundScheduler
lateinit var backgroundScheduler: Scheduler
@Inject
lateinit var analytic: Analytic
private var submission: Submission? = null
private var error: Throwable? = null
private var disposable: Disposable? = null
var isLoading = false
private set
init {
App.componentManager()
.adaptiveCourseComponent(card.courseId)
.inject(this)
}
override fun attachView(view: CardView) {
super.attachView(view)
view.setStep(card.step)
view.setTitle(card.lesson?.title)
view.setQuestion(card.step?.block?.text)
view.getQuizViewDelegate().setAttempt(card.attempt)
if (isLoading) view.onSubmissionLoading()
submission?.let { view.setSubmission(it, false) }
error?.let { onError(it) }
}
fun detachView() {
view?.let {
if (submission == null || submission?.status == Submission.Status.LOCAL) {
submission = Submission(
_reply = it.getQuizViewDelegate().createReply(),
status = Submission.Status.LOCAL) // cache current choices state
}
super.detachView(it)
}
}
fun destroy() {
App.componentManager()
.releaseAdaptiveCourseComponent(card.courseId)
card.recycle()
disposable?.dispose()
}
fun createReaction(reaction: Reaction) {
val lesson = card.lessonId
when(reaction) {
Reaction.NEVER_AGAIN -> {
if (card.correct) {
analytic.reportEventValue(Analytic.Adaptive.REACTION_EASY_AFTER_CORRECT, lesson)
}
analytic.reportEventValue(Analytic.Adaptive.REACTION_EASY, lesson)
}
Reaction.MAYBE_LATER -> {
if (card.correct) {
analytic.reportEventValue(Analytic.Adaptive.REACTION_HARD_AFTER_CORRECT, lesson)
}
analytic.reportEventValue(Analytic.Adaptive.REACTION_HARD, lesson)
}
}
listener?.createReaction(lesson, reaction)
}
fun createSubmission() {
if (disposable == null || disposable?.isDisposed != false) {
view?.onSubmissionLoading()
isLoading = true
error = null
val submission = Submission(
_reply = view?.getQuizViewDelegate()?.createReply(),
attempt = card.attempt?.id ?: 0)
disposable = submissionRepository.createSubmission(submission)
.ignoreElement()
.andThen(submissionRepository.getSubmissionsForAttempt(submission.attempt))
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe(this::onSubmissionLoaded, this::onError)
}
}
fun retrySubmission() {
submission = null
}
private fun onSubmissionLoaded(submissions: List<Submission>) {
submission = submissions.firstOrNull()
submission?.let {
if (it.status == Submission.Status.EVALUATION) {
disposable = submissionRepository.getSubmissionsForAttempt(it.attempt)
.delay(1, TimeUnit.SECONDS)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe(this::onSubmissionLoaded, this::onError)
} else {
isLoading = false
if (it.status == Submission.Status.CORRECT) {
listener?.createReaction(card.lessonId, Reaction.SOLVED)
answerListener?.onCorrectAnswer(it.id)
card.onCorrect()
}
if (it.status == Submission.Status.WRONG) {
answerListener?.onWrongAnswer(it.id)
}
analytic.reportAmplitudeEvent(AmplitudeAnalytic.Steps.SUBMISSION_MADE, mapOf(
AmplitudeAnalytic.Steps.Params.SUBMISSION to it.id,
AmplitudeAnalytic.Steps.Params.TYPE to card.step.getStepType(),
AmplitudeAnalytic.Steps.Params.STEP to (card.step?.id?.toString() ?: "0"),
AmplitudeAnalytic.Steps.Params.LOCAL to false,
AmplitudeAnalytic.Steps.Params.IS_ADAPTIVE to true
))
view?.setSubmission(it, true)
}
}
}
private fun onError(error: Throwable) {
isLoading = false
this.error = error
if (error is HttpException) {
view?.onSubmissionRequestError()
} else {
view?.onSubmissionConnectivityError()
}
}
} | apache-2.0 | 1be4c73a7cf9465f8ffd24d65e772eab | 34.391813 | 100 | 0.619402 | 5.021577 | false | false | false | false |
robfletcher/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartWaitingExecutionsHandler.kt | 3 | 3065 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CancelExecution
import com.netflix.spinnaker.orca.q.ExecutionLevel
import com.netflix.spinnaker.orca.q.RestartStage
import com.netflix.spinnaker.orca.q.StartExecution
import com.netflix.spinnaker.orca.q.StartWaitingExecutions
import com.netflix.spinnaker.orca.q.pending.PendingExecutionService
import com.netflix.spinnaker.q.Queue
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
@Component
class StartWaitingExecutionsHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
private val pendingExecutionService: PendingExecutionService
) : OrcaMessageHandler<StartWaitingExecutions> {
private val log: Logger get() = LoggerFactory.getLogger(javaClass)
override val messageType = StartWaitingExecutions::class.java
override fun handle(message: StartWaitingExecutions) {
if (message.purgeQueue) {
// when purging the queue, run the latest message and discard the rest
pendingExecutionService.popNewest(message.pipelineConfigId)
.also { _ ->
pendingExecutionService.purge(message.pipelineConfigId) { purgedMessage ->
when (purgedMessage) {
is StartExecution -> {
log.info("Dropping queued pipeline {} {}", purgedMessage.application, purgedMessage.executionId)
queue.push(CancelExecution(
source = purgedMessage,
user = "spinnaker",
reason = "This execution was queued but then canceled because a newer queued execution superceded it. This pipeline is configured to automatically cancel waiting executions."
))
}
is RestartStage -> {
log.info("Cancelling restart of {} {}", purgedMessage.application, purgedMessage.executionId)
// don't need to do anything else
}
}
}
}
} else {
// when not purging the queue, run the messages in the order they came in
pendingExecutionService.popOldest(message.pipelineConfigId)
}
?.let {
// spoiler, it always is!
if (it is ExecutionLevel) {
log.info("Starting queued pipeline {} {} {}", it.application, it.executionId)
}
queue.push(it)
}
}
}
| apache-2.0 | 339b307289009815c3ec5c65c00f3708 | 39.328947 | 193 | 0.699837 | 4.679389 | false | true | false | false |
hotmobmobile/hotmob-android-sdk | AndroidStudio/HotmobSDKShowcase/app/src/main/java/com/hotmob/sdk/hotmobsdkshowcase/DeepLinkContentFragment.kt | 1 | 1842 | package com.hotmob.sdk.hotmobsdkshowcase
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hotmob.sdk.hotmobsdkshowcase.databinding.FragmentDeepLinkContentBinding
private const val ARG_PARAM1 = "param1"
/**
* A simple [Fragment] subclass.
* Use the [DeepLinkContentFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class DeepLinkContentFragment : androidx.fragment.app.Fragment() {
private var param1: String? = null
private var _binding: FragmentDeepLinkContentBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.run {
param1 = getString(ARG_PARAM1)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentDeepLinkContentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.deepLinkAddress.text = param1
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @return A new instance of fragment DeepLinkContentFragment.
*/
@JvmStatic
fun newInstance(param1: String) =
DeepLinkContentFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
}
}
}
}
| mit | 406f1b6ba383e98d45ac607a6e386c14 | 29.196721 | 85 | 0.666124 | 4.796875 | false | false | false | false |
jriley/HackerNews | mobile/src/test/java/dev/jriley/hackernews/data/StoryRepositoryTest.kt | 1 | 6326 | package dev.jriley.hackernews.data
import com.nhaarman.mockito_kotlin.*
import dev.jriley.hackernews.services.HackerNewsService
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import io.reactivex.subjects.BehaviorSubject
import org.junit.Test
import test
import java.util.*
class StoryRepositoryTest {
private lateinit var testObject: StoryRepository
private val storyData: StoryData = mock()
private val hackerNewsService: HackerNewsService = mock()
private val ioScheduler: TestScheduler = TestScheduler()
private val random = Random()
@Test
fun isLoadedDoNotCallService() {
whenever(storyData.isLoaded()).thenReturn(Single.just(true))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.isLoaded().test()
testObserver.apply {
assertNoValues()
assertNotComplete()
assertNoErrors()
}
ioScheduler.triggerActions()
testObserver.apply {
assertValues(true)
assertComplete()
assertNoErrors()
}
verifyZeroInteractions(hackerNewsService)
}
@Test
fun loadBestStories() {
val story1 = Story.test(random.nextLong())
val expectedInsert = Story(story1, StoryTypes.BEST)
val expectedIdList = listOf(story1.id)
whenever(storyData.isLoaded(any())).thenReturn(false)
whenever(storyData.insert(expectedInsert)).thenReturn(Single.just(story1.id))
whenever(hackerNewsService.best).thenReturn(Single.just(expectedIdList))
whenever(hackerNewsService.getStory("${story1.id}")).thenReturn(Single.just(story1))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.loadBest().test()
testObserver.apply {
assertNoValues()
assertNotComplete()
assertNoErrors()
}
ioScheduler.triggerActions()
testObserver.apply {
assertValues(expectedIdList)
assertComplete()
assertNoErrors()
}
}
@Test
fun loadTopStories() {
val story1 = Story.test(random.nextLong())
val expectedInsert = Story(story1, StoryTypes.TOP)
val expectedIdList = listOf(story1.id)
whenever(storyData.isLoaded(any())).thenReturn(false)
whenever(storyData.insert(expectedInsert)).thenReturn(Single.just(story1.id))
whenever(hackerNewsService.top).thenReturn(Single.just(expectedIdList))
whenever(hackerNewsService.getStory("${story1.id}")).thenReturn(Single.just(story1))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.loadTop().test()
testObserver.apply {
assertNoValues()
assertNotComplete()
assertNoErrors()
}
ioScheduler.triggerActions()
testObserver.apply {
assertValues(expectedIdList)
assertComplete()
assertNoErrors()
}
}
@Test
fun loadNewStories() {
val expectedStoryList: List<Story> = listOf(Story.test(random.nextLong()))
val story1 = expectedStoryList.first()
val expectedIdList = listOf(story1.id)
whenever(storyData.isLoaded(any())).thenReturn(false)
whenever(storyData.insert(story1)).thenReturn(Single.just(story1.id))
whenever(hackerNewsService.new).thenReturn(Single.just(expectedIdList))
whenever(hackerNewsService.getStory("${story1.id}")).thenReturn(Single.just(story1))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.loadNew().test()
testObserver.apply {
assertNoValues()
assertNotComplete()
assertNoErrors()
}
ioScheduler.triggerActions()
testObserver.apply {
assertValues(expectedIdList)
assertComplete()
assertNoErrors()
}
}
@Test
fun doNotLoadStoriesAlreadyInDB() {
val expectedIdList = listOf(random.nextLong())
whenever(storyData.isLoaded(any())).thenReturn(true)
whenever(hackerNewsService.best).thenReturn(Single.just(expectedIdList))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.loadBest().test()
testObserver.apply {
assertNoValues()
assertNotComplete()
assertNoErrors()
}
ioScheduler.triggerActions()
testObserver.apply {
assertValues(listOf())
assertComplete()
assertNoErrors()
}
verify(storyData, never()).insert(any())
verify(hackerNewsService, never()).getStory(any())
}
@Test
fun flowFromRepo() {
val expectedStoryList = listOf(Story.test())
val behaviorSubject = BehaviorSubject.create<List<Story>>()
val flowable: Flowable<List<Story>> = behaviorSubject.toFlowable(BackpressureStrategy.BUFFER)
whenever(storyData.storyList()).thenReturn(flowable)
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
testObject.flowBest().test().apply {
assertNoErrors()
assertNotComplete()
assertNoValues()
}
behaviorSubject.onNext(expectedStoryList)
testObject.flowBest().test().apply {
assertNoErrors()
assertNotComplete()
assertValues(expectedStoryList)
}
}
@Test
fun updateStory() {
val expectedStory = Story.test()
whenever(storyData.update(expectedStory)).thenReturn(Single.just(1))
testObject = StoryRepository(storyData, hackerNewsService, ioScheduler)
val testObserver = testObject.bookmarkStory(expectedStory).test().apply {
assertNoErrors()
assertNotComplete()
assertNoValues()
}
ioScheduler.triggerActions()
testObserver.apply {
assertNoErrors()
assertComplete()
assertValue(1)
}
}
} | mpl-2.0 | fa2b251bf886c09aabc12e22b9b5f31f | 30.321782 | 101 | 0.646696 | 5.06891 | false | true | false | false |
devromik/poly | src/main/kotlin/net/devromik/poly/FFT.kt | 1 | 5000 | package net.devromik.poly
import net.devromik.poly.utils.*
import java.lang.Integer.numberOfLeadingZeros
import java.lang.Integer.reverse
/**
* @author Shulnyaev Roman
*/
private val PRINCIPAL_ROOTS_OF_UNITY_FOR_DIRECT_FFT = arrayOf(
Complex(re=-1.0, im=1.2246467991473532E-16),
Complex(re=6.123233995736766E-17, im=1.0),
Complex(re=0.7071067811865476, im=0.7071067811865475),
Complex(re=0.9238795325112867, im=0.3826834323650898),
Complex(re=0.9807852804032304, im=0.19509032201612825),
Complex(re=0.9951847266721969, im=0.0980171403295606),
Complex(re=0.9987954562051724, im=0.049067674327418015),
Complex(re=0.9996988186962042, im=0.024541228522912288),
Complex(re=0.9999247018391445, im=0.012271538285719925),
Complex(re=0.9999811752826011, im=0.006135884649154475),
Complex(re=0.9999952938095762, im=0.003067956762965976),
Complex(re=0.9999988234517019, im=0.0015339801862847655),
Complex(re=0.9999997058628822, im=7.669903187427045E-4),
Complex(re=0.9999999264657179, im=3.8349518757139556E-4),
Complex(re=0.9999999816164293, im=1.917475973107033E-4),
Complex(re=0.9999999954041073, im=9.587379909597734E-5),
Complex(re=0.9999999988510269, im=4.793689960306688E-5),
Complex(re=0.9999999997127567, im=2.396844980841822E-5),
Complex(re=0.9999999999281892, im=1.1984224905069705E-5),
Complex(re=0.9999999999820472, im=5.9921124526424275E-6),
Complex(re=0.9999999999955118, im=2.996056226334661E-6),
Complex(re=0.999999999998878, im=1.4980281131690111E-6),
Complex(re=0.9999999999997194, im=7.490140565847157E-7),
Complex(re=0.9999999999999298, im=3.7450702829238413E-7),
Complex(re=0.9999999999999825, im=1.8725351414619535E-7),
Complex(re=0.9999999999999957, im=9.362675707309808E-8),
Complex(re=0.9999999999999989, im=4.681337853654909E-8),
Complex(re=0.9999999999999998, im=2.340668926827455E-8),
Complex(re=0.9999999999999999, im=1.1703344634137277E-8)
)
private val PRINCIPAL_ROOTS_OF_UNITY_FOR_INVERSE_FFT = arrayOf(
Complex(re=-1.0, im=-1.2246467991473532E-16),
Complex(re=6.123233995736766E-17, im=-1.0),
Complex(re=0.7071067811865476, im=-0.7071067811865475),
Complex(re=0.9238795325112867, im=-0.3826834323650898),
Complex(re=0.9807852804032304, im=-0.19509032201612825),
Complex(re=0.9951847266721969, im=-0.0980171403295606),
Complex(re=0.9987954562051724, im=-0.049067674327418015),
Complex(re=0.9996988186962042, im=-0.024541228522912288),
Complex(re=0.9999247018391445, im=-0.012271538285719925),
Complex(re=0.9999811752826011, im=-0.006135884649154475),
Complex(re=0.9999952938095762, im=-0.003067956762965976),
Complex(re=0.9999988234517019, im=-0.0015339801862847655),
Complex(re=0.9999997058628822, im=-7.669903187427045E-4),
Complex(re=0.9999999264657179, im=-3.8349518757139556E-4),
Complex(re=0.9999999816164293, im=-1.917475973107033E-4),
Complex(re=0.9999999954041073, im=-9.587379909597734E-5),
Complex(re=0.9999999988510269, im=-4.793689960306688E-5),
Complex(re=0.9999999997127567, im=-2.396844980841822E-5),
Complex(re=0.9999999999281892, im=-1.1984224905069705E-5),
Complex(re=0.9999999999820472, im=-5.9921124526424275E-6),
Complex(re=0.9999999999955118, im=-2.996056226334661E-6),
Complex(re=0.999999999998878, im=-1.4980281131690111E-6),
Complex(re=0.9999999999997194, im=-7.490140565847157E-7),
Complex(re=0.9999999999999298, im=-3.7450702829238413E-7),
Complex(re=0.9999999999999825, im=-1.8725351414619535E-7),
Complex(re=0.9999999999999957, im=-9.362675707309808E-8),
Complex(re=0.9999999999999989, im=-4.681337853654909E-8),
Complex(re=0.9999999999999998, im=-2.340668926827455E-8),
Complex(re=0.9999999999999999, im=-1.1703344634137277E-8)
)
fun fft(a: Array<Complex>, inverse: Boolean) {
doBitReversalPermutationOf(a)
val principalRootsOfUnity = if (inverse) PRINCIPAL_ROOTS_OF_UNITY_FOR_INVERSE_FFT else PRINCIPAL_ROOTS_OF_UNITY_FOR_DIRECT_FFT
val n = a.size
var r = 2
var principalRootOfUnityIndex = 0
while (r <= n) {
val principalRootOfUnity = principalRootsOfUnity[principalRootOfUnityIndex]
for (i in 0..n - 1 step r) {
var w = COMPLEX_UNITY
for (j in 0..r / 2 - 1) {
val u = a[i + j]
val v = a[i + j + r / 2] * w
a[i + j] = u + v
a[i + j + r / 2] = u - v
w *= principalRootOfUnity
}
}
r = r.shl(1)
++principalRootOfUnityIndex
}
if (inverse) {
for (i in 0..n - 1) {
a[i] = a[i] / n
}
}
}
fun doBitReversalPermutationOf(a: Array<Complex>) {
val n = a.size
val shift = numberOfLeadingZeros(n) + 1
for (i in 0..n - 1) {
val p = reverse(i).ushr(shift)
if (i < p) {
val temp = a[i]
a[i] = a[p]
a[p] = temp
}
}
} | mit | 15094b785e7f9417587ca6fb89e016e3 | 39.330645 | 130 | 0.6866 | 2.520161 | false | false | false | false |
RalfBr/energy-model | src/test/kotlin/org/codefx/demo/bingen/energy_model/EnergyTest.kt | 2 | 1026 | package org.codefx.demo.bingen.energy_model
import org.junit.Test
import org.junit.Assert.assertEquals
class EnergyTest {
@Test
fun ifEnergySufficesFulfillsOrdered() {
val energy = Energy(100)
val order = EnergyOrder(20)
val produced = energy.produce(order)
assertEquals(Energy(20), produced)
}
@Test
fun ifEnergyTooSmallProducesAvailableEnergy() {
val energy = Energy(100)
val order = EnergyOrder(120)
val produced = energy.produce(order)
assertEquals(Energy(100), produced)
}
@Test
fun reduceEnergyBySmallerOrderResultsInFullReduction() {
val energy = Energy(100)
val order = Energy(20)
val reduced = energy.reduce(order)
assertEquals(Energy(80), reduced)
}
@Test
fun reduceEnergyByLargerOrderResultsInZero() {
val energy = Energy(100)
val order = Energy(200)
val reduced = energy.reduce(order)
assertEquals(Energy(0), reduced)
}
}
| cc0-1.0 | a0b8cc056d9b79961eb457cbf03e7c6d | 19.938776 | 60 | 0.639376 | 4.120482 | false | true | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/ui/activity/DashboardActivity.kt | 1 | 4825 | package net.treelzebub.zinepress.ui.activity
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.content_dashboard.*
import kotlinx.android.synthetic.main.nav_header_dashboard.*
import net.treelzebub.zinepress.R
import net.treelzebub.zinepress.db.articles.DbArticles
import net.treelzebub.zinepress.db.articles.IArticle
import net.treelzebub.zinepress.net.sync.Sync
import net.treelzebub.zinepress.ui.adapter.ArticlesAdapter
import net.treelzebub.zinepress.util.UserUtils
import net.treelzebub.zinepress.util.extensions.*
import net.treelzebub.zinepress.zine.EpubGenerator
import net.treelzebub.zinepress.zine.SelectedArticles
import rx.android.lifecycle.LifecycleObservable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_dashboard.drawer_layout as drawer
import kotlinx.android.synthetic.main.activity_dashboard.nav_view as navView
/**
* Created by Tre Murillo on 1/2/16
*/
class DashboardActivity : AuthedRxActivity(), NavigationView.OnNavigationItemSelectedListener {
private val listAdapter = ArticlesAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
setSupportActionBar(toolbar)
reload()
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
setup(savedInstanceState)
}
override fun onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.dashboard, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_refresh -> reload()
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_pocket -> {
}
R.id.nav_library -> {
}
R.id.nav_share -> {
}
R.id.nav_settings -> {
}
R.id.nav_logout -> {
UserUtils.logout(this)
finish()
startActivity(createIntent<MainActivity>())
}
}
drawer.closeDrawer(GravityCompat.START)
return true
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (SelectedArticles.articles.isNotEmpty()) {
outState.putSerializable("selected_articles", SelectedArticles.articles)
}
}
private fun setup(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
val selectedArticles = savedInstanceState.getSerializable<Set<IArticle>>("selected_articles")
SelectedArticles.articles.addAll(selectedArticles)
}
recycler.apply {
layoutManager = LinearLayoutManager(this@DashboardActivity)
adapter = listAdapter
}
fab.setOnClickListener {
if (SelectedArticles.articles.isEmpty()) {
Snackbar.make(it, "No articles selected for zine!", Snackbar.LENGTH_LONG).show()
} else {
generateBook()
}
}
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.setDrawerListener(toggle)
toggle.syncState()
navView.apply {
setNavigationItemSelectedListener(this@DashboardActivity)
onNextLayout {
username.text = UserUtils.getName()
}
}
}
private fun reload() {
LifecycleObservable.bindActivityLifecycle(lifecycle(),
Sync.requestSync(this))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
listAdapter.setList(DbArticles.all())
}, {
Log.e(TAG, it.message)
})
}
private fun handleEmpty() {
//TODO
}
private fun generateBook() {
EpubGenerator.beginBuild(SelectedArticles.articles)
}
}
| gpl-2.0 | 108839495069c32698dea80f15241e94 | 32.978873 | 105 | 0.657202 | 4.918451 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinArtifactReflection.kt | 3 | 3179 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.Task
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Exec
import org.jetbrains.kotlin.idea.gradleTooling.loadClassOrNull
import java.io.File
fun KonanArtifactReflection(konanArtifact: Any): KonanArtifactReflection = KonanArtifactReflectionImpl(konanArtifact)
interface KonanArtifactReflection {
val executableName: String?
val compilationTargetName: String?
val outputKindType: String?
val konanTargetName: String?
val outputFile: File?
val linkTaskPath: String?
val runTask: Exec?
val isTests: Boolean?
val freeCompilerArgs: Collection<String>?
val binaryOptions: Map<String, String>?
}
private class KonanArtifactReflectionImpl(private val instance: Any) : KonanArtifactReflection {
override val executableName: String? by lazy {
instance.callReflectiveGetter("getBaseName", logger)
}
private val linkTask: Task? by lazy {
instance.callReflectiveGetter("getLinkTask", logger)
}
override val linkTaskPath: String? by lazy {
linkTask?.path
}
override val runTask: Exec? by lazy {
if (instance.javaClass.classLoader.loadClassOrNull(NATIVE_EXECUTABLE_CLASS)?.isInstance(instance) == true)
instance.callReflectiveGetter("getRunTask", logger)
else null
}
override val compilationTargetName: String? by lazy {
val compilation = linkTask?.callReflectiveAnyGetter("getCompilation", logger)?.let {
when (it) {
is Provider<*> -> it.get()
else -> it
}
}
compilation?.callReflectiveAnyGetter("getTarget", logger)
?.callReflectiveGetter("getName", logger)
}
override val outputKindType: String? by lazy {
linkTask?.callReflectiveAnyGetter("getOutputKind", logger)
?.callReflectiveGetter("name", logger)
}
override val konanTargetName: String? by lazy {
linkTask?.callReflectiveGetter("getTarget", logger)
}
override val outputFile: File? by lazy {
when (val outputFile = instance.callReflective("getOutputFile", parameters(), returnType<Any>(), logger)) {
is Provider<*> -> outputFile.orNull as? File
is File -> outputFile
else -> null
}
}
override val isTests: Boolean? by lazy {
linkTask?.callReflectiveGetter("getProcessTests", logger)
}
override val freeCompilerArgs: Collection<String>? by lazy {
linkTask?.callReflectiveAnyGetter("getKotlinOptions", logger)
?.callReflectiveGetter("getFreeCompilerArgs", logger)
}
override val binaryOptions: Map<String, String>? by lazy {
linkTask?.callReflectiveGetter("getBinaryOptions", logger)
}
companion object {
private val logger: ReflectionLogger = ReflectionLogger(KonanArtifactReflection::class.java)
private const val NATIVE_EXECUTABLE_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.Executable"
}
}
| apache-2.0 | 05a010b77343134660a6981d142cfb50 | 37.768293 | 120 | 0.693614 | 4.802115 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/analysis/AbstractSet.kt | 1 | 1173 | package arcs.core.analysis
/** An abstract domain representing a set of values, where the elements are ordered by inclusion. */
data class AbstractSet<S>(
val value: BoundedAbstractElement<Set<S>>
) : AbstractValue<AbstractSet<S>> {
override val isBottom = value.isBottom
override val isTop = value.isTop
/** Returns the underling set. Returns null if this is `Top` or `Bottom`. */
val set: Set<S>?
get() = value.value
constructor(s: Set<S>) : this(BoundedAbstractElement.makeValue(s))
override infix fun isEquivalentTo(other: AbstractSet<S>) =
value.isEquivalentTo(other.value) { a, b -> a == b }
override infix fun join(other: AbstractSet<S>) = AbstractSet(
value.join(other.value) { a, b -> a union b }
)
override infix fun meet(other: AbstractSet<S>) = AbstractSet(
value.meet(other.value) { a, b -> a intersect b }
)
override fun toString() = when {
value.isTop -> "TOP"
value.isBottom -> "BOTTOM"
else -> "$set"
}
companion object {
fun <S> getBottom() = AbstractSet<S>(BoundedAbstractElement.getBottom<Set<S>>())
fun <S> getTop() = AbstractSet<S>(BoundedAbstractElement.getTop<Set<S>>())
}
}
| bsd-3-clause | 04897bcddf9204f9f3dc45b9f39ef03f | 30.702703 | 100 | 0.675192 | 3.735669 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/demo/DemoActivity.kt | 1 | 2795 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.demo
// TODO(b/170962663) Disabled due to different ordering after copybara transformations.
/* ktlint-disable import-ordering */
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import arcs.android.labs.host.AndroidManifestHostRegistry
import arcs.core.allocator.Allocator
import arcs.core.entity.ForeignReferenceCheckerImpl
import arcs.core.host.HandleManagerImpl
import arcs.core.host.HostRegistry
import arcs.core.host.SimpleSchedulerProvider
import arcs.jvm.util.JvmTime
import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager
import arcs.sdk.android.storage.service.DefaultBindHelper
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/** Entry UI to launch Arcs demo. */
@OptIn(ExperimentalCoroutinesApi::class)
class DemoActivity : AppCompatActivity() {
private val coroutineContext: CoroutineContext = Job() + Dispatchers.Main
private val scope: CoroutineScope = CoroutineScope(coroutineContext)
private val schedulerProvider = SimpleSchedulerProvider(Dispatchers.Default)
/**
* Recipe hand translated from 'person.arcs'
*/
private lateinit var allocator: Allocator
private lateinit var hostRegistry: HostRegistry
private val storageEndpointManager = AndroidStorageServiceEndpointManager(
scope,
DefaultBindHelper(this)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
scope.launch {
hostRegistry = AndroidManifestHostRegistry.create(this@DemoActivity)
allocator = Allocator.create(
hostRegistry,
HandleManagerImpl(
time = JvmTime,
scheduler = schedulerProvider("personArc"),
storageEndpointManager = storageEndpointManager,
foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap())
),
scope
)
findViewById<Button>(R.id.person_test).setOnClickListener {
testPersonRecipe()
}
}
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
private fun testPersonRecipe() {
scope.launch {
val arcId = allocator.startArcForPlan(PersonRecipePlan).id
allocator.stopArc(arcId)
}
}
}
| bsd-3-clause | b73aa31fbad288da7157fb2f5132b385 | 29.714286 | 96 | 0.763506 | 4.810671 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/OP/syntax/token/Token.kt | 1 | 1469 | package com.bajdcc.OP.syntax.token
import com.bajdcc.util.Position
import com.bajdcc.util.lexer.token.Token as LexerToken
import com.bajdcc.util.lexer.token.TokenType as LexerTokenType
/**
* 单词
*
* @author bajdcc
*/
class Token {
/**
* 单词类型
*/
var kToken = TokenType.ERROR
/**
* 数据
*/
var `object`: Any? = null
/**
* 位置
*/
var position = Position()
override fun toString(): String {
return String.format("%04d,%03d: %s %s", position.line,
position.column, kToken.desc,
if (`object` == null) "(null)" else `object`!!.toString())
}
companion object {
fun transfer(token: LexerToken): Token {
val tk = Token()
tk.`object` = token.obj
tk.position = token.position
when (token.type) {
LexerTokenType.COMMENT -> tk.kToken = TokenType.COMMENT
LexerTokenType.EOF -> tk.kToken = TokenType.EOF
LexerTokenType.ERROR -> tk.kToken = TokenType.ERROR
LexerTokenType.ID -> tk.kToken = TokenType.NONTERMINAL
LexerTokenType.OPERATOR -> tk.kToken = TokenType.OPERATOR
LexerTokenType.STRING -> tk.kToken = TokenType.TERMINAL
LexerTokenType.WHITESPACE -> tk.kToken = TokenType.WHITSPACE
else -> {
}
}
return tk
}
}
} | mit | 718b35d54e4d3ed8d99e3812a6793550 | 25.363636 | 76 | 0.549344 | 4.390909 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/ReferenceLut.kt | 1 | 1512 | /*
* Copyright (C) 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 com.google.android.renderscript_test
import com.google.android.renderscript.LookupTable
import com.google.android.renderscript.Range2d
/**
* Reference implementation of a LookUpTable operation.
*/
@ExperimentalUnsignedTypes
fun referenceLut(
inputArray: ByteArray,
sizeX: Int,
sizeY: Int,
table: LookupTable,
restriction: Range2d?
): ByteArray {
val input = Vector2dArray(inputArray.asUByteArray(), 4, sizeX, sizeY)
val output = input.createSameSized()
input.forEach(restriction) { x, y ->
val oldValue = input[x, y]
val newValue = byteArrayOf(
table.red[oldValue[0].toInt()],
table.green[oldValue[1].toInt()],
table.blue[oldValue[2].toInt()],
table.alpha[oldValue[3].toInt()]
)
output[x, y] = newValue.asUByteArray()
}
return output.values.asByteArray()
}
| apache-2.0 | c36d2dd5335099b90e0857315a5a55f7 | 30.5 | 75 | 0.690476 | 4.097561 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day18.kt | 1 | 3162 | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.Point
import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo
import java.util.*
/**
*
* @author Jelle Stege
*/
class Day18 : Day(title = "Like a GIF For Your Yard") {
private companion object Configuration {
private const val ITERATIONS = 100
}
override fun first(input: Sequence<String>) = (0 until ITERATIONS)
.transformTo(Grid.parse(input.toList())) { grid, _ ->
grid.getTogglePoints().forEach { (x, y) -> grid[x, y] = !grid[x, y] }
}
.cardinality()
override fun second(input: Sequence<String>) = (0 until ITERATIONS)
.transformTo(Grid.parse(input.toList())) { grid, _ ->
grid.getTogglePoints().asSequence()
.filterNot { (x, y) ->
(y == 0 || y == grid.height - 1) && (x == 0 || x == grid.width - 1)
}
.forEach { (x, y) -> grid[x, y] = !grid[x, y] }
}
.cardinality()
private class Grid private constructor(val grid: BitSet, val height: Int, val width: Int) {
operator fun get(x: Int, y: Int) = grid[y * width + x]
operator fun set(x: Int, y: Int, value: Boolean) = grid.set(y * width + x, value)
fun cardinality() = grid.cardinality()
fun getTogglePoints(): Set<Point> = (0 until height)
.flatMap { y ->
(0 until width).map { x ->
Point.of(x, y)
}
}
.filter { (x, y) ->
countNeighbours(x, y)
.let { (this[x, y] && !(it == 2 || it == 3)) || (!this[x, y] && it == 3) }
}
.toSet()
private fun countNeighbours(x: Int, y: Int): Int {
var n = 0
if (x > 0) {
if (y > 0) {
n += if (this[x - 1, y - 1]) 1 else 0
}
n += if (this[x - 1, y]) 1 else 0
if (y < height - 1) {
n += if (this[x - 1, y + 1]) 1 else 0
}
}
if (y > 0) {
n += if (this[x, y - 1]) 1 else 0
}
if (y < height - 1) {
n += if (this[x, y + 1]) 1 else 0
}
if (x < width - 1) {
if (y > 0) {
n += if (this[x + 1, y - 1]) 1 else 0
}
n += if (this[x + 1, y]) 1 else 0
if (y < height - 1) {
n += if (this[x + 1, y + 1]) 1 else 0
}
}
return n
}
companion object Parser {
fun parse(input: List<String>) = Grid(
input
.withIndex()
.transformTo(BitSet(input.size * input.first().length)) { bs, (i, s) ->
s.forEachIndexed { index, c -> bs[i * s.length + index] = c == '#' }
},
input.size,
input.first().length
)
}
}
}
| mit | 3768cbc405233538344ee6c5c71759d7 | 33 | 95 | 0.427894 | 3.800481 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeOverriddenMemberOpenFix.kt | 1 | 7384 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.kotlin.caches.project.CachedValue
import org.jetbrains.kotlin.caches.project.getValue
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.*
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.isOverridable
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.compilerPreferences.KotlinBaseCompilerConfigurationUiBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.util.actualsForExpected
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.lexer.KtTokens.OPEN_KEYWORD
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
private typealias DeclarationPointer = SmartPsiElementPointer<KtCallableDeclaration>
class MakeOverriddenMemberOpenFix(declaration: KtDeclaration) : KotlinQuickFixAction<KtDeclaration>(declaration) {
private val myQuickFixInfo: QuickFixInfo by CachedValue(declaration.project) {
CachedValueProvider.Result.createSingleDependency(computeInfo(), PsiModificationTracker.MODIFICATION_COUNT)
}
private val containingDeclarationsNames
get() = myQuickFixInfo.declNames
private val overriddenNonOverridableMembers
get() = myQuickFixInfo.declarations
private fun computeInfo(): QuickFixInfo {
val element = element ?: return QUICKFIX_UNAVAILABLE
val overriddenNonOverridableMembers = mutableListOf<DeclarationPointer>()
val containingDeclarationsNames = mutableListOf<String>()
val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableMemberDescriptor ?: return QUICKFIX_UNAVAILABLE
for (overriddenDescriptor in getAllDeclaredNonOverridableOverriddenDescriptors(descriptor)) {
assert(overriddenDescriptor.kind == DECLARATION) { "Can only be applied to declarations." }
val overriddenMember = DescriptorToSourceUtils.descriptorToDeclaration(overriddenDescriptor)
if (overriddenMember == null || !overriddenMember.canRefactor() || overriddenMember !is KtCallableDeclaration ||
overriddenMember.modifierList?.hasModifier(OPEN_KEYWORD) == true
) {
return QUICKFIX_UNAVAILABLE
}
overriddenDescriptor.takeIf { overriddenMember.isExpectDeclaration() }?.actualsForExpected()?.forEach {
if (it is MemberDescriptor && it.modality < Modality.OPEN) {
val member = DescriptorToSourceUtils.descriptorToDeclaration(it)
if (member == null || !member.canRefactor() || member !is KtCallableDeclaration) {
return QUICKFIX_UNAVAILABLE
}
overriddenNonOverridableMembers.add(member.createSmartPointer())
}
}
val containingDeclarationName = overriddenDescriptor.containingDeclaration.name.asString()
overriddenNonOverridableMembers.add(overriddenMember.createSmartPointer())
containingDeclarationsNames.add(containingDeclarationName)
}
return QuickFixInfo(overriddenNonOverridableMembers, containingDeclarationsNames)
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
return overriddenNonOverridableMembers.isNotEmpty()
}
override fun getText(): String {
val element = element ?: return ""
if (containingDeclarationsNames.size == 1) {
val name = containingDeclarationsNames[0] + "." + element.name
return KotlinBundle.message("make.0", "$name $OPEN_KEYWORD")
}
val sortedDeclarationNames = containingDeclarationsNames.sorted()
val declarations = sortedDeclarationNames.subList(0, sortedDeclarationNames.size - 1).joinToString(", ") +
" ${KotlinBaseCompilerConfigurationUiBundle.message("configuration.text.and")} " +
sortedDeclarationNames.last()
return KotlinBundle.message("make.0.in.1.open", element.name.toString(), declarations)
}
override fun getFamilyName(): String = KotlinBundle.message("add.modifier")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
for (overriddenMember in overriddenNonOverridableMembers) {
overriddenMember.element?.addModifier(OPEN_KEYWORD)
}
}
companion object : KotlinSingleIntentionActionFactory() {
private data class QuickFixInfo(val declarations: List<DeclarationPointer>, val declNames: List<String>)
private val QUICKFIX_UNAVAILABLE = QuickFixInfo(emptyList(), emptyList())
private fun getAllDeclaredNonOverridableOverriddenDescriptors(
callableMemberDescriptor: CallableMemberDescriptor
): Collection<CallableMemberDescriptor> {
val result = hashSetOf<CallableMemberDescriptor>()
val nonOverridableOverriddenDescriptors = retainNonOverridableMembers(callableMemberDescriptor.overriddenDescriptors)
for (overriddenDescriptor in nonOverridableOverriddenDescriptors) {
when (overriddenDescriptor.kind) {
DECLARATION ->
result.add(overriddenDescriptor)
FAKE_OVERRIDE, DELEGATION ->
result.addAll(getAllDeclaredNonOverridableOverriddenDescriptors(overriddenDescriptor))
SYNTHESIZED -> {
} /* do nothing */
else -> throw UnsupportedOperationException("Unexpected callable kind ${overriddenDescriptor.kind}")
}
}
return result
}
private fun retainNonOverridableMembers(
callableMemberDescriptors: Collection<CallableMemberDescriptor>
): Collection<CallableMemberDescriptor> {
return callableMemberDescriptors.filter { !it.isOverridable }
}
override fun createAction(diagnostic: Diagnostic): IntentionAction {
val declaration = diagnostic.psiElement.getNonStrictParentOfType<KtDeclaration>()!!
return MakeOverriddenMemberOpenFix(declaration)
}
}
}
| apache-2.0 | 624b59ecd251990356f43523d9e67f73 | 50.277778 | 158 | 0.733749 | 5.658238 | false | false | false | false |
SimpleMobileTools/Simple-Music-Player | app/src/main/kotlin/com/simplemobiletools/musicplayer/adapters/PlaylistsAdapter.kt | 1 | 6156 | package com.simplemobiletools.musicplayer.adapters
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.extensions.deleteFiles
import com.simplemobiletools.commons.extensions.getFilenameFromPath
import com.simplemobiletools.commons.extensions.highlightTextPart
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.musicplayer.R
import com.simplemobiletools.musicplayer.dialogs.NewPlaylistDialog
import com.simplemobiletools.musicplayer.dialogs.RemovePlaylistDialog
import com.simplemobiletools.musicplayer.extensions.deletePlaylists
import com.simplemobiletools.musicplayer.extensions.tracksDAO
import com.simplemobiletools.musicplayer.models.Events
import com.simplemobiletools.musicplayer.models.Playlist
import kotlinx.android.synthetic.main.item_playlist.view.*
import org.greenrobot.eventbus.EventBus
class PlaylistsAdapter(
activity: BaseSimpleActivity, var playlists: ArrayList<Playlist>, recyclerView: MyRecyclerView, itemClick: (Any) -> Unit
) : MyRecyclerViewAdapter(activity, recyclerView, itemClick), RecyclerViewFastScroller.OnPopupTextUpdate {
private var textToHighlight = ""
init {
setupDragListener(true)
}
override fun getActionMenuId() = R.menu.cab_playlists
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_playlist, parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val playlist = playlists.getOrNull(position) ?: return
holder.bindView(playlist, true, true) { itemView, layoutPosition ->
setupView(itemView, playlist)
}
bindViewHolder(holder)
}
override fun getItemCount() = playlists.size
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_rename).isVisible = isOneItemSelected()
}
}
override fun actionItemPressed(id: Int) {
when (id) {
R.id.cab_delete -> askConfirmDelete()
R.id.cab_rename -> showRenameDialog()
R.id.cab_select_all -> selectAll()
}
}
override fun getSelectableItemCount() = playlists.size
override fun getIsItemSelectable(position: Int) = true
override fun getItemSelectionKey(position: Int) = playlists.getOrNull(position)?.id
override fun getItemKeyPosition(key: Int) = playlists.indexOfFirst { it.id == key }
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
private fun askConfirmDelete() {
RemovePlaylistDialog(activity) {
val ids = selectedKeys.map { it } as ArrayList<Int>
if (it) {
ensureBackgroundThread {
deletePlaylistSongs(ids) {
removePlaylists()
}
}
} else {
removePlaylists()
}
}
}
private fun deletePlaylistSongs(ids: ArrayList<Int>, callback: () -> Unit) {
var cnt = ids.size
ids.map {
val paths = activity.tracksDAO.getTracksFromPlaylist(it).map { it.path }
val fileDirItems = paths.map { FileDirItem(it, it.getFilenameFromPath()) } as ArrayList<FileDirItem>
activity.deleteFiles(fileDirItems) {
if (--cnt <= 0) {
callback()
}
}
}
}
private fun removePlaylists() {
val playlistsToDelete = ArrayList<Playlist>(selectedKeys.size)
val positions = ArrayList<Int>()
for (key in selectedKeys) {
val playlist = getItemWithKey(key) ?: continue
val position = playlists.indexOfFirst { it.id == key }
if (position != -1) {
positions.add(position + positionOffset)
}
playlistsToDelete.add(playlist)
}
playlists.removeAll(playlistsToDelete)
ensureBackgroundThread {
activity.deletePlaylists(playlistsToDelete)
activity.runOnUiThread {
removeSelectedItems(positions)
}
if (playlists.isEmpty()) {
EventBus.getDefault().post(Events.PlaylistsUpdated())
}
}
}
private fun getItemWithKey(key: Int): Playlist? = playlists.firstOrNull { it.id == key }
fun updateItems(newItems: ArrayList<Playlist>, highlightText: String = "", forceUpdate: Boolean = false) {
if (forceUpdate || newItems.hashCode() != playlists.hashCode()) {
playlists = newItems.clone() as ArrayList<Playlist>
textToHighlight = highlightText
notifyDataSetChanged()
finishActMode()
} else if (textToHighlight != highlightText) {
textToHighlight = highlightText
notifyDataSetChanged()
}
}
private fun showRenameDialog() {
NewPlaylistDialog(activity, playlists[getItemKeyPosition(selectedKeys.first())]) {
activity.runOnUiThread {
finishActMode()
}
}
}
private fun setupView(view: View, playlist: Playlist) {
view.apply {
playlist_frame?.isSelected = selectedKeys.contains(playlist.id)
playlist_title.text = if (textToHighlight.isEmpty()) playlist.title else playlist.title.highlightTextPart(textToHighlight, properPrimaryColor)
playlist_title.setTextColor(textColor)
val tracks = resources.getQuantityString(R.plurals.tracks_plural, playlist.trackCount, playlist.trackCount)
playlist_tracks.text = tracks
playlist_tracks.setTextColor(textColor)
}
}
override fun onChange(position: Int) = playlists.getOrNull(position)?.getBubbleText() ?: ""
}
| gpl-3.0 | b6680dfe990f7a0acfc3e3c1314e3e51 | 36.536585 | 154 | 0.668941 | 5.203719 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/TooLongCharLiteralToStringFix.kt | 1 | 1936 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
class TooLongCharLiteralToStringFix(
element: KtConstantExpression
) : KotlinQuickFixAction<KtConstantExpression>(element) {
override fun getText(): String = KotlinBundle.message("convert.too.long.character.literal.to.string")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val text = element.text
if (!(text.startsWith("'") && text.endsWith("'") && text.length >= 2)) {
return
}
val newStringContent = text
.slice(1..text.length - 2)
.replace("\\\"", "\"")
.replace("\"", "\\\"")
val newElement = KtPsiFactory(element).createStringTemplate(newStringContent)
element.replace(newElement)
}
override fun getFamilyName(): String = text
companion object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtConstantExpression ?: return null
if (element.text == "'\\'") return null
if (element.text.startsWith("\"")) return null
return TooLongCharLiteralToStringFix(element = element)
}
}
} | apache-2.0 | 1de6e965b3b55287896595c12447d7a6 | 42.044444 | 158 | 0.708161 | 4.82793 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmOverloadsIntention.kt | 1 | 3762 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_OVERLOADS_FQ_NAME
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
private val annotationFqName get() = JVM_OVERLOADS_FQ_NAME
class AddJvmOverloadsIntention : SelfTargetingIntention<KtModifierListOwner>(
KtModifierListOwner::class.java,
KotlinBundle.lazyMessage("add.jvmoverloads.annotation"),
), LowPriorityAction {
override fun isApplicableTo(element: KtModifierListOwner, caretOffset: Int): Boolean {
val (targetName, parameters) = when (element) {
is KtNamedFunction -> {
val funKeyword = element.funKeyword ?: return false
val valueParameterList = element.valueParameterList ?: return false
if (caretOffset !in funKeyword.startOffset..valueParameterList.endOffset) {
return false
}
KotlinBundle.message("function.0", element.name.toString()) to valueParameterList.parameters
}
is KtSecondaryConstructor -> {
val constructorKeyword = element.getConstructorKeyword()
val valueParameterList = element.valueParameterList ?: return false
if (caretOffset !in constructorKeyword.startOffset..valueParameterList.endOffset) {
return false
}
KotlinBundle.message("text.secondary.constructor") to valueParameterList.parameters
}
is KtPrimaryConstructor -> {
if (element.parent.safeAs<KtClass>()?.isAnnotation() == true) return false
val parameters = (element.valueParameterList ?: return false).parameters
// For primary constructors with all default values, a zero-arg constructor is generated anyway. If there's only one
// parameter and it has a default value, the bytecode with and without @JvmOverloads is exactly the same.
if (parameters.singleOrNull()?.hasDefaultValue() == true) {
return false
}
KotlinBundle.message("text.primary.constructor") to parameters
}
else -> return false
}
setTextGetter(KotlinBundle.lazyMessage("add.jvmoverloads.annotation.to.0", targetName))
return element.containingKtFile.platform.isJvm()
&& parameters.any { it.hasDefaultValue() }
&& element.findAnnotation(annotationFqName) == null
}
override fun applyTo(element: KtModifierListOwner, editor: Editor?) {
if (element is KtPrimaryConstructor) {
if (element.getConstructorKeyword() == null) {
element.addBefore(KtPsiFactory(element).createConstructorKeyword(), element.valueParameterList)
}
element.addAnnotation(annotationFqName, whiteSpaceText = " ")
} else {
element.addAnnotation(annotationFqName)
}
}
}
| apache-2.0 | ebf8c9152631460bc566b98facc8a802 | 47.857143 | 158 | 0.685008 | 5.33617 | false | false | false | false |
markusressel/TutorialTooltip | library/src/main/java/de/markusressel/android/library/tutorialtooltip/TutorialTooltip.kt | 1 | 8973 | /*
* Copyright (c) 2016 Markus Ressel
*
* 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 de.markusressel.android.library.tutorialtooltip
import android.app.Dialog
import android.content.Context
import android.view.ViewGroup
import de.markusressel.android.library.tutorialtooltip.builder.TutorialTooltipBuilder
import de.markusressel.android.library.tutorialtooltip.preferences.PreferencesHandler
import de.markusressel.android.library.tutorialtooltip.view.TooltipId
import de.markusressel.android.library.tutorialtooltip.view.TutorialTooltipView
import de.markusressel.android.library.tutorialtooltip.view.ViewHelper
import java.util.*
/**
* Base TutorialTooltip class
*
*
* Contains Builder and basic construction methods
*
*
* Created by Markus on 17.11.2016.
*/
object TutorialTooltip {
/**
* Create the TutorialTooltip
* @param builder TutorialTooltipBuilder
* *
* @return TutorialTooltipView
*/
fun make(builder: TutorialTooltipBuilder): TutorialTooltipView {
if (!builder.isCompleted) {
throw IllegalStateException("Builder is not complete! Did you call build()?")
}
return TutorialTooltipView(builder)
}
/**
* Create a TutorialTooltip and show it right away
* @param builder TutorialTooltipBuilder
* *
* @return ID of TutorialTooltip
*/
fun show(builder: TutorialTooltipBuilder): TooltipId {
val tutorialTooltipView = make(builder)
return show(tutorialTooltipView)
}
/**
* Show a TutorialTooltip
* @param tutorialTooltipView TutorialTooltipView
* *
* @return ID of TutorialTooltip
*/
fun show(tutorialTooltipView: TutorialTooltipView): TooltipId {
tutorialTooltipView.show()
return tutorialTooltipView.tutorialTooltipId
}
/**
* Searches through the view tree for instances of TutorialTooltipView
*
*
* WARNING: This only works if the TutorialTooltip was attached to the Activity and NOT to the Window!
* If you attach the TutorialTooltip to the window you have to keep a reference to its view manually.
* @param context activity context
* *
* @param id id of TutorialTooltip
* *
* @return true if a TutorialTooltip with the given id exists, false otherwise
*/
fun exists(context: Context, id: TooltipId): Boolean {
val act = ViewHelper.getActivity(context)
if (act != null) {
val rootView = act.window.decorView as ViewGroup
for (i in 0 until rootView.childCount) {
val child = rootView.getChildAt(i)
if (child is TutorialTooltipView && child.tutorialTooltipId == id) {
return true
}
}
}
return false
}
/**
* Remove an existing TutorialTooltip via its ID
*
*
* WARNING: This only works if the TutorialTooltip was attached to the Activity and NOT to the Window!
* If you attach the TutorialTooltip to the window you have to keep a reference to its view manually.
* @param context activity context the specified tooltip was added to, application context will not work!
* *
* @param id id of TutorialTooltip
* *
* @param animated true fades out, false removes immediately
* *
* @return true if a TutorialTooltip was found and removed, false otherwise
*/
fun remove(context: Context, id: TooltipId, animated: Boolean): Boolean {
val activity = ViewHelper.getActivity(context)
activity?.let {
val rootView = it.window.decorView as ViewGroup
return removeChild(id, rootView, animated)
}
return false
}
/**
* Remove an existing TutorialTooltip via its ID
*
*
* WARNING: This only works if the TutorialTooltip was attached to a Dialog and NOT to the Window or Activity!
* If you attach the TutorialTooltip to the activity use `remove(Context context, TooltipId id)`
* If you attach it to the window you have to keep a reference to its view and remove it manually.
* @param dialog dialog the specified tooltip was added to
* *
* @param id id of TutorialTooltip
* *
* @param animated true fades out, false removes immediately
* *
* @return true if a TutorialTooltip was found and removed, false otherwise
*/
fun remove(dialog: Dialog?, id: TooltipId, animated: Boolean): Boolean {
dialog?.let {
val rootView = it.window!!.decorView as ViewGroup
return removeChild(id, rootView, animated)
}
return false
}
/**
* This method traverses through the view tree horizontally
* and searches for a TutorialTooltipView with the given ID
* until a matching view is found and removes it.
* @param id ID of the TutorialTooltip
* *
* @param parent parent ViewGroup
* *
* @param animated true fades out, false removes immediately
* *
* @return true if a TutorialTooltip was found and removed, false otherwise
*/
private fun removeChild(id: TooltipId, parent: ViewGroup, animated: Boolean): Boolean {
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
if (child is TutorialTooltipView && child.tutorialTooltipId == id) {
child.remove(animated)
return true
}
}
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
if (child is ViewGroup) {
if (removeChild(id, child, animated)) {
return true
}
}
}
return false
}
/**
* Remove an existing TutorialTooltip
* @param tutorialTooltipView TutorialTooltipView to remove
* *
* @param animated true fades out, false removes immediately
*/
fun remove(tutorialTooltipView: TutorialTooltipView, animated: Boolean) {
tutorialTooltipView.remove(animated)
}
/**
* Remove all existing TutorialTooltips from activity
*
*
* WARNING: This does not remove TutorialTooltips that are attached to the window!
* If you attach the TutorialTooltip to the window you have to keep a reference to its view manually.
* @param context activity context the specified tooltip was added to, application context will not work!
* *
* @param animated true fades out, false removes immediately
*/
fun removeAll(context: Context, animated: Boolean) {
val activity = ViewHelper.getActivity(context)
activity?.let {
val rootView = it.window.decorView as ViewGroup
val childrenToRemove = LinkedList<Int>()
for (i in 0 until rootView.childCount) {
val child = rootView.getChildAt(i)
if (child is TutorialTooltipView) {
val tutorialTooltipView = child
childrenToRemove.add(i)
}
}
childrenToRemove.reverse()
childrenToRemove
.map { rootView.getChildAt(it) as TutorialTooltipView }
.forEach { it.remove(animated) }
}
}
/**
* Reset the show count for a TutorialTooltip ID
* @param applicationContext application context (for access to SharedPreferences)
* *
* @param tooltipId the TutorialTooltip ID to reset the count for
*/
fun resetShowCount(applicationContext: Context,
tooltipId: TooltipId) {
val preferencesHandler = PreferencesHandler(applicationContext)
preferencesHandler.resetCount(tooltipId)
}
/**
* Reset the show count for a TutorialTooltip
* @param tutorialTooltipView the TutorialTooltip to reset the count for
*/
fun resetShowCount(tutorialTooltipView: TutorialTooltipView) {
val preferencesHandler = PreferencesHandler(tutorialTooltipView.context)
preferencesHandler.resetCount(tutorialTooltipView)
}
/**
* Reset the show count for ALL TutorialTooltips
* @param context application context
*/
fun resetAllShowCount(context: Context) {
val preferencesHandler = PreferencesHandler(context)
preferencesHandler.clearAll()
}
}
| apache-2.0 | 56a0ef14e7d3279b615291b48e5a8e0f | 32.356877 | 114 | 0.650173 | 5.043845 | false | false | false | false |
hzsweers/CatchUp | libraries/base-ui/src/main/kotlin/io/sweers/catchup/base/ui/PaletteExt.kt | 1 | 1909 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package io.sweers.catchup.base.ui
import androidx.annotation.FloatRange
import androidx.palette.graphics.Palette
import androidx.palette.graphics.Palette.Swatch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/*
* Extension functions for the Palette library.
*/
inline fun Palette.orderedSwatches(
@FloatRange(from = 0.0, to = 1.0) darkAlpha: Float,
@FloatRange(from = 0.0, to = 1.0) lightAlpha: Float
): List<Pair<Swatch, Float>> {
return listOfNotNull(
vibrantSwatch?.let { it to darkAlpha },
lightVibrantSwatch?.let { it to lightAlpha },
darkVibrantSwatch?.let { it to darkAlpha },
mutedSwatch?.let { it to darkAlpha },
lightMutedSwatch?.let { it to lightAlpha },
darkMutedSwatch?.let { it to darkAlpha }
)
}
inline fun Palette.findSwatch(predicate: (Swatch) -> Boolean): Swatch? {
return listOfNotNull(
darkVibrantSwatch,
lightMutedSwatch,
vibrantSwatch,
mutedSwatch,
lightVibrantSwatch,
darkMutedSwatch
)
.firstOrNull(predicate)
}
suspend fun Palette.Builder.generateAsync(): Palette? = withContext(Dispatchers.Default) {
generate()
}
val Swatch.hue: Float
get() = hsl[0]
val Swatch.saturation: Float
get() = hsl[1]
val Swatch.luminosity: Float
get() = hsl[2]
| apache-2.0 | 991ca8dd8a462a9d6b793935a01dd857 | 28.369231 | 90 | 0.727082 | 3.765286 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/AtTypeParameter.kt | 9 | 625 | interface Base
/**
* @param T this is docs for T
*/
class Some<<caret>T: Base>
//INFO: <div class='definition'><pre><span style=""><</span><span style="color:#20999d;">T</span><span style=""> : </span><span style="color:#000000;"><a href="psi_element://Base">Base</a></span><span style="">></span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>this is docs for T</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/classKotlin.svg"/> <a href="psi_element://Some"><code><span style="color:#000000;">Some</span></code></a><br/></div>
| apache-2.0 | 7d816788f99673b183320ff090e5c2da | 77.125 | 541 | 0.6544 | 3.205128 | false | false | false | false |
jk1/intellij-community | python/src/com/jetbrains/python/sdk/pipenv/pipenv.kt | 1 | 17722 | // 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.sdk.pipenv
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.annotations.SerializedName
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.execution.ExecutionException
import com.intellij.execution.RunCanceledByUserException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PathEnvironmentVariableUtil
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import com.jetbrains.python.inspections.PyPackageRequirementsInspection
import com.jetbrains.python.packaging.*
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import icons.PythonIcons
import org.jetbrains.annotations.SystemDependent
import java.io.File
import javax.swing.Icon
/**
* @author vlan
*/
const val PIP_FILE: String = "Pipfile"
const val PIP_FILE_LOCK: String = "Pipfile.lock"
const val PIPENV_DEFAULT_SOURCE_URL: String = "https://pypi.org/simple"
const val PIPENV_PATH_SETTING: String = "PyCharm.Pipenv.Path"
// TODO: Provide a special icon for pipenv
val PIPENV_ICON: Icon = PythonIcons.Python.PythonClosed
/**
* The Pipfile found in the main content root of the module.
*/
val Module.pipFile: VirtualFile?
get() =
baseDir?.findChild(PIP_FILE)
/**
* Tells if the SDK was added as a pipenv.
*/
var Sdk.isPipEnv: Boolean
get() = sdkAdditionalData is PyPipEnvSdkAdditionalData
set(value) {
val oldData = sdkAdditionalData
val newData = if (value) {
when (oldData) {
is PythonSdkAdditionalData -> PyPipEnvSdkAdditionalData(oldData)
else -> PyPipEnvSdkAdditionalData()
}
}
else {
when (oldData) {
is PyPipEnvSdkAdditionalData -> PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(this))
else -> oldData
}
}
val modificator = sdkModificator
modificator.sdkAdditionalData = newData
ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() }
}
/**
* The user-set persisted path to the pipenv executable.
*/
var PropertiesComponent.pipEnvPath: @SystemDependent String?
get() = getValue(PIPENV_PATH_SETTING)
set(value) {
setValue(PIPENV_PATH_SETTING, value)
}
/**
* Detects the pipenv executable in `$PATH`.
*/
fun detectPipEnvExecutable(): File? {
val name = when {
SystemInfo.isWindows -> "pipenv.exe"
else -> "pipenv"
}
return PathEnvironmentVariableUtil.findInPath(name)
}
/**
* Returns the configured pipenv executable or detects it automatically.
*/
fun getPipEnvExecutable(): File? =
PropertiesComponent.getInstance().pipEnvPath?.let { File(it) } ?: detectPipEnvExecutable()
/**
* Sets up the pipenv environment under the modal progress window.
*
* The pipenv is associated with the first valid object from this list:
*
* 1. New project specified by [newProjectPath]
* 2. Existing module specified by [module]
* 3. Existing project specified by [project]
*
* @return the SDK for pipenv, not stored in the SDK table yet.
*/
fun setupPipEnvSdkUnderProgress(project: Project?,
module: Module?,
existingSdks: List<Sdk>,
newProjectPath: String?,
python: String?,
installPackages: Boolean): Sdk? {
val projectPath = newProjectPath ?:
module?.basePath ?:
project?.basePath ?:
return null
val task = object : Task.WithResult<String, ExecutionException>(project, "Setting Up Pipenv Environment", true) {
override fun compute(indicator: ProgressIndicator): String {
indicator.isIndeterminate = true
val pipEnv = setupPipEnv(FileUtil.toSystemDependentName(projectPath), python, installPackages)
return PythonSdkType.getPythonExecutable(pipEnv) ?: FileUtil.join(pipEnv, "bin", "python")
}
}
val suggestedName = "Pipenv (${PathUtil.getFileName(projectPath)})"
return createSdkByGenerateTask(task, existingSdks, null, projectPath, suggestedName)?.apply {
isPipEnv = true
associateWithModule(module, newProjectPath)
}
}
/**
* Sets up the pipenv environment for the specified project path.
*
* @return the path to the pipenv environment.
*/
fun setupPipEnv(projectPath: @SystemDependent String, python: String?, installPackages: Boolean): @SystemDependent String {
when {
installPackages -> {
val pythonArgs = if (python != null) listOf("--python", python) else emptyList()
val command = pythonArgs + listOf("install", "--dev")
runPipEnv(projectPath, *command.toTypedArray())
}
python != null ->
runPipEnv(projectPath, "--python", python)
else ->
runPipEnv(projectPath, "run", "python", "-V")
}
return runPipEnv(projectPath, "--venv").trim()
}
/**
* Runs the configured pipenv for the specified Pipenv SDK with the associated project path.
*/
fun runPipEnv(sdk: Sdk, vararg args: String): String {
val projectPath = sdk.associatedModulePath ?:
throw PyExecutionException("Cannot find the project associated with this Pipenv environment",
"Pipenv", emptyList(), ProcessOutput())
return runPipEnv(projectPath, *args)
}
/**
* Runs the configured pipenv for the specified project path.
*/
fun runPipEnv(projectPath: @SystemDependent String, vararg args: String): String {
val executable = getPipEnvExecutable()?.path ?:
throw PyExecutionException("Cannot find Pipenv", "pipenv", emptyList(), ProcessOutput())
val command = listOf(executable) + args
val commandLine = GeneralCommandLine(command).withWorkDirectory(projectPath)
val handler = CapturingProcessHandler(commandLine)
val indicator = ProgressManager.getInstance().progressIndicator
val result = with(handler) {
when {
indicator != null -> {
addProcessListener(PyPackageManagerImpl.IndicatedProcessOutputListener(indicator))
runProcessWithProgressIndicator(indicator)
}
else ->
runProcess()
}
}
return with(result) {
when {
isCancelled ->
throw RunCanceledByUserException()
exitCode != 0 ->
throw PyExecutionException("Error Running Pipenv", executable, args.asList(),
stdout, stderr, exitCode, emptyList())
else -> stdout
}
}
}
/**
* Detects and sets up pipenv SDK for a module with Pipfile.
*/
fun detectAndSetupPipEnv(project: Project?, module: Module?, existingSdks: List<Sdk>): Sdk? {
if (module?.pipFile == null || getPipEnvExecutable() == null) {
return null
}
return setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false)
}
/**
* The URLs of package sources configured in the Pipfile.lock of the module associated with this SDK.
*/
val Sdk.pipFileLockSources: List<String>
get() = parsePipFileLock()?.meta?.sources?.mapNotNull { it.url } ?:
listOf(PIPENV_DEFAULT_SOURCE_URL)
/**
* The list of requirements defined in the Pipfile.lock of the module associated with this SDK.
*/
val Sdk.pipFileLockRequirements: List<PyRequirement>?
get() {
fun toRequirements(packages: Map<String, PipFileLockPackage>): List<PyRequirement> =
packages
.asSequence()
.filterNot { (_, pkg) -> pkg.editable ?: false }
.flatMap { (name, pkg) -> packageManager.parseRequirements("$name${pkg.version ?: ""}").asSequence() }
.toList()
val pipFileLock = parsePipFileLock() ?: return null
val packages = pipFileLock.packages?.let { toRequirements(it) } ?: emptyList()
val devPackages = pipFileLock.devPackages?.let { toRequirements(it) } ?: emptyList()
return packages + devPackages
}
/**
* A quick-fix for setting up the pipenv for the module of the current PSI element.
*/
class UsePipEnvQuickFix(sdk: Sdk?, module: Module) : LocalQuickFix {
private val quickFixName = when {
sdk != null && sdk.associatedModule != module -> "Fix Pipenv interpreter"
else -> "Use Pipenv interpreter"
}
companion object {
fun isApplicable(module: Module): Boolean = module.pipFile != null
fun setUpPipEnv(project: Project, module: Module) {
val sdksModel = ProjectSdksModel().apply {
reset(project)
}
val existingSdks = sdksModel.sdks.filter { it.sdkType is PythonSdkType }
// XXX: Should we show an error message on exceptions and on null?
val newSdk = setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false) ?: return
val existingSdk = existingSdks.find { it.isPipEnv && it.homePath == newSdk.homePath }
val sdk = existingSdk ?: newSdk
if (sdk == newSdk) {
SdkConfigurationUtil.addSdk(newSdk)
}
else {
sdk.associateWithModule(module, null)
}
project.pythonSdk = sdk
module.pythonSdk = sdk
}
}
override fun getFamilyName() = quickFixName
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
// Invoke the setup later to escape the write action of the quick fix in order to show the modal progress dialog
ApplicationManager.getApplication().invokeLater {
if (project.isDisposed || module.isDisposed) return@invokeLater
setUpPipEnv(project, module)
}
}
}
/**
* A quick-fix for installing packages specified in Pipfile.lock.
*/
class PipEnvInstallQuickFix : LocalQuickFix {
companion object {
fun pipEnvInstall(project: Project, module: Module) {
val sdk = module.pythonSdk ?: return
if (!sdk.isPipEnv) return
val listener = PyPackageRequirementsInspection.RunningPackagingTasksListener(module)
val ui = PyPackageManagerUI(project, sdk, listener)
ui.install(null, listOf("--dev"))
}
}
override fun getFamilyName() = "Install requirements from Pipfile.lock"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
pipEnvInstall(project, module)
}
}
/**
* Watches for edits in Pipfiles inside modules with a pipenv SDK set.
*/
class PipEnvPipFileWatcherComponent(val project: Project) : ProjectComponent {
override fun projectOpened() {
val editorFactoryListener = object : EditorFactoryListener {
private val changeListenerKey = Key.create<DocumentListener>("Pipfile.change.listener")
private val notificationActive = Key.create<Boolean>("Pipfile.notification.active")
override fun editorCreated(event: EditorFactoryEvent) {
if (!isPipFileEditor(event.editor)) return
val listener = object : DocumentListener {
override fun documentChanged(event: DocumentEvent?) {
val module = event?.document?.virtualFile?.getModule(project) ?: return
notifyPipFileChanged(module)
}
}
with(event.editor.document) {
addDocumentListener(listener)
putUserData(changeListenerKey, listener)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val listener = event.editor.getUserData(changeListenerKey) ?: return
event.editor.document.removeDocumentListener(listener)
}
private fun notifyPipFileChanged(module: Module) {
if (module.getUserData(notificationActive) == true) return
val what = when {
module.pipFileLock == null -> "not found"
else -> "out of date"
}
val title = "$PIP_FILE_LOCK is $what"
val content = "Run <a href='#lock'>pipenv lock</a> or <a href='#update'>pipenv update</a>"
val notification = LOCK_NOTIFICATION_GROUP.createNotification(title, null, content,
NotificationType.INFORMATION) { notification, event ->
notification.expire()
module.putUserData(notificationActive, null)
FileDocumentManager.getInstance().saveAllDocuments()
when (event.description) {
"#lock" ->
runPipEnvInBackground(module, listOf("lock"), "Locking $PIP_FILE")
"#update" ->
runPipEnvInBackground(module, listOf("update", "--dev"), "Updating Pipenv environment")
}
}
module.putUserData(notificationActive, true)
notification.whenExpired {
module.putUserData(notificationActive, null)
}
notification.notify(project)
}
private fun runPipEnvInBackground(module: Module, args: List<String>, description: String) {
val task = object : Task.Backgroundable(module.project, StringUtil.toTitleCase(description), true) {
override fun run(indicator: ProgressIndicator) {
val sdk = module.pythonSdk ?: return
indicator.text = "$description..."
try {
runPipEnv(sdk, *args.toTypedArray())
}
catch (e: RunCanceledByUserException) {}
catch (e: ExecutionException) {
runInEdt {
Messages.showErrorDialog(project, e.toString(), "Error Running Pipenv")
}
}
}
}
ProgressManager.getInstance().run(task)
}
private fun isPipFileEditor(editor: Editor): Boolean {
if (editor.project != project) return false
val file = editor.document.virtualFile ?: return false
if (file.name != PIP_FILE) return false
val module = file.getModule(project) ?: return false
if (module.pipFile != file) return false
return module.pythonSdk?.isPipEnv == true
}
}
EditorFactory.getInstance().addEditorFactoryListener(editorFactoryListener, project)
}
}
private val Document.virtualFile: VirtualFile?
get() = FileDocumentManager.getInstance().getFile(this)
private fun VirtualFile.getModule(project: Project): Module? =
ModuleUtil.findModuleForFile(this, project)
private val LOCK_NOTIFICATION_GROUP = NotificationGroup("$PIP_FILE Watcher", NotificationDisplayType.STICKY_BALLOON, false)
private val Sdk.packageManager: PyPackageManager
get() = PyPackageManagers.getInstance().forSdk(this)
private fun Sdk.parsePipFileLock(): PipFileLock? {
// TODO: Log errors if Pipfile.lock is not found
val file = pipFileLock ?: return null
val text = ReadAction.compute<String, Throwable> { FileDocumentManager.getInstance().getDocument(file)?.text }
return try {
Gson().fromJson(text, PipFileLock::class.java)
}
catch (e: JsonSyntaxException) {
// TODO: Log errors
return null
}
}
private val Sdk.pipFileLock: VirtualFile?
get() =
associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it)?.findChild(PIP_FILE_LOCK) }
private val Module.pipFileLock: VirtualFile?
get() = baseDir?.findChild(PIP_FILE_LOCK)
private data class PipFileLock(@SerializedName("_meta") var meta: PipFileLockMeta?,
@SerializedName("default") var packages: Map<String, PipFileLockPackage>?,
@SerializedName("develop") var devPackages: Map<String, PipFileLockPackage>?)
private data class PipFileLockMeta(@SerializedName("sources") var sources: List<PipFileLockSource>?)
private data class PipFileLockSource(@SerializedName("url") var url: String?)
private data class PipFileLockPackage(@SerializedName("version") var version: String?,
@SerializedName("editable") var editable: Boolean?)
| apache-2.0 | 211328e4002b4c78ab5a8e71b2b98e75 | 37.864035 | 140 | 0.702235 | 4.558128 | false | false | false | false |
jk1/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/BoxableType.kt | 2 | 881 | package org.jetbrains.protocolModelGenerator
interface BoxableType {
val defaultValue: String?
val fullText: CharSequence
fun getShortText(contextNamespace: NamePath): String
val writeMethodName: String
companion object {
val STRING: StandaloneType = StandaloneType(NamePath("String"), "writeString", "null")
val ANY_STRING: StandaloneType = StandaloneType(NamePath("String"), "writeString", "null")
val INT: StandaloneType = StandaloneType(NamePath("Int"), "writeInt", "-1")
val LONG: StandaloneType = StandaloneType(NamePath("Long"), "writeLong", "-1")
val NUMBER: StandaloneType = StandaloneType(NamePath("Double"), "writeDouble", "Double.NaN")
val BOOLEAN: StandaloneType = StandaloneType(NamePath("Boolean"), "writeBoolean", "false")
val MAP: StandaloneType = StandaloneType(NamePath("Map<String, String>"), "writeMap", "null")
}
} | apache-2.0 | ea9208528243c9d1c2ffe9dcd11b212d | 41 | 97 | 0.732123 | 4.339901 | false | true | false | false |
marklemay/IntelliJATS | src/main/kotlin/com/atslangplugin/runner/RunnerConfigurationType.kt | 1 | 1780 | package com.atslangplugin.runner
import com.atslangplugin.ATSIcons
import com.intellij.execution.configurations.ConfigurationType
class RunnerConfigurationType : ConfigurationType {
/**
* Returns the display name of the configuration type. This is used, for example, to represent the configuration type in the run
* configurations tree, and also as the name of the action used to create the configuration.
* @return the display name of the configuration type.
*/
override fun getDisplayName() = "ATS"
/**
* Returns the description of the configuration type. You may return the same text as the display name of the configuration type.
* @return the description of the configuration type.
*/
override fun getConfigurationTypeDescription() = "ATS build and run via patsopt"
/**
* Returns the 16x16 icon used to represent the configuration type.
* @return the icon
*/
//TODO: a specific ats run icon?
override fun getIcon() = ATSIcons.LOGO
/**
* Returns the ID of the configuration type. The ID is used to store run configuration settings in a project or workspace file and
* must not change between plugin versions.
* @return the configuration type ID.
*/
override fun getId() = "ATS_RUN_CONFIGURATION"
/**
* Returns the configuration factories used by this configuration type. Normally each configuration type provides just a single factory.
* You can return multiple factories if your configurations can be created in multiple variants (for example, local and remote for an
* application server).
* @return the run configuration factories.
*/
override fun getConfigurationFactories() = arrayOf(AtsRunConfigurationFactory(this))
} | gpl-3.0 | 7a5964bef55cf11365e527bd1f416402 | 36.104167 | 140 | 0.72191 | 5.028249 | false | true | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/bukkit/SpigotModuleType.kt | 1 | 1557 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel
import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object SpigotModuleType : AbstractModuleType<BukkitModule<SpigotModuleType>>("org.spigotmc", "spigot-api") {
private const val ID = "SPIGOT_MODULE_TYPE"
init {
CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS)
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.SPIGOT
override val icon = PlatformAssets.SPIGOT_ICON
override val id = ID
override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS
override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS
override val isEventGenAvailable = true
override fun generateModule(facet: MinecraftFacet): BukkitModule<SpigotModuleType> = BukkitModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass)
}
| mit | 99d5e21c072422cad49bc8c4a22a8ba9 | 36.97561 | 114 | 0.802184 | 4.325 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/opengl/OpenGLObjectState.kt | 2 | 2605 | package graphics.scenery.backends.opengl
import cleargl.GLTexture
import graphics.scenery.NodeMetadata
import graphics.scenery.utils.LazyLogger
import java.nio.ByteBuffer
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.collections.HashSet
/**
* OpenGLObjectState stores the OpenGL metadata that is needed for rendering a node
*
* @author Ulrik Günther <[email protected]>
* @constructor Creates an empty OpenGLObjectState, with [OpenGLRenderer] as
* default consumers.
*/
class OpenGLObjectState : NodeMetadata {
private val logger by LazyLogger()
/** List of consumers of this metadata, e.g. [OpenGLRenderer] */
override val consumers: MutableList<String> = ArrayList()
/** IDs of buffers that may be additionally required. */
val additionalBufferIds = Hashtable<String, Int>()
/** Hash map of GLTexture objects storing the OpenGL texture handles. */
var textures = ConcurrentHashMap<String, GLTexture>()
/** VAO storage. */
val mVertexArrayObject = IntArray(1)
/** VBO storage. */
val mVertexBuffers = IntArray(3)
/** Index buffer storage. */
val mIndexBuffer = IntArray(1)
/** Whether the object has been initialised yet. */
var initialized: Boolean = false
/** Number of stores indices. */
var mStoredIndexCount = 0
/** Number of stored vertex/normal/texcoord primitives. */
var mStoredPrimitiveCount = 0
/** OpenGL UBOs **/
var UBOs = LinkedHashMap<String, OpenGLUBO>()
/** are we missing textures? **/
var defaultTexturesFor = HashSet<String>()
/** shader to use for the program */
var shader: OpenGLShaderProgram? = null
/** instance count */
var instanceCount: Int = 1
/** buffer storage */
var vertexBuffers = HashMap<String, ByteBuffer>()
/** Hash code for the currently used material */
var materialHash: Int = -1
/** Last reload time for textures */
var texturesLastSeen = 0L
init {
consumers.add("OpenGLRenderer")
}
/**
* Returns the UBO given by [name] if it exists, otherwise null.
*/
fun getUBO(name: String): OpenGLUBO? {
return UBOs[name]
}
/**
* Returns the UBO given by [name] if it exists and has a backing buffer, otherwise null.
*/
fun getBackedUBO(name: String): Pair<OpenGLUBO, OpenGLRenderer.OpenGLBuffer>? {
val ubo = UBOs[name]
return if(ubo?.backingBuffer != null) {
ubo to ubo.backingBuffer
} else {
logger.warn("UBO for $name has no backing buffer")
null
}
}
}
| lgpl-3.0 | 918826cb0336b6e89ad411bfdef53cfa | 31.55 | 93 | 0.666283 | 4.34 | false | false | false | false |
saffih/ElmDroid | app/src/main/java/saffih/elmdroid/service/ElmService.kt | 1 | 4613 | /*
* By Saffi Hartal, 2017.
* 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 saffih.elmdroid.service
import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.widget.Toast
import saffih.elmdroid.ElmBase
/**
* Copyright Joseph Hartal (Saffi)
* Created by saffi on 7/05/17.
*/
fun Context.isServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
abstract class ElmMessengerService<M, MSG, API : MSG>(
override val me: Service,
val toMessage: (API) -> Message,
val toApi: (Message) -> API, val debug: Boolean = false) :
ElmBase<M, MSG>(me) {
fun toast(txt: String, duration: Int = Toast.LENGTH_SHORT) {
if (!debug) return
post({ Toast.makeText(me, txt, duration).show() })
}
override fun view(model: M, pre: M?) {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private var lastincomingMessage: Message? = null
protected fun dispatchReply(msg: API) {
val message = toMessage(msg)
val last = lastincomingMessage!!
val replyTo = last.replyTo
if (replyTo !== null) {
replyTo.send(message)
} else if (clientMessenger != null)
clientMessenger?.send(message)
else {
toast("no Messenger to reply ${msg}", duration = Toast.LENGTH_LONG)
}
}
private val handler = object : Handler() {
override fun handleMessage(message: Message) {
lastincomingMessage = message
val msg = toApi(message)
if (msg == null) {
super.handleMessage(message)
} else {
// any reply would use dispatchReply to return the response.
dispatch(msg)
}
}
}
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
private val mMessenger = Messenger(handler)
private var clientMessenger: Messenger? = null
/**
* When binding to the service, we return an interface to our messenger
* for sending messages to the service.
*/
fun onBind(intent: Intent?): IBinder {
setMessenger(intent)
return mMessenger.binder
}
fun onRebind(intent: Intent?) {
setMessenger(intent)
}
fun onUnbind(intent: Intent?): Boolean {
clientMessenger = null
return true
}
// for unbound service
fun onStartCommand(intent: Intent?, flags: Int, startId: Int) {
setMessenger(intent)
}
private fun setMessenger(intent: Intent?): Messenger? {
val extras = intent?.extras
clientMessenger = extras?.get("MESSENGER") as Messenger?
return clientMessenger
}
companion object {
fun startServiceIfNotRunning(context: Context, serviceClass: Class<*>,
messenger: Messenger? = null, receiver: (Intent) -> Unit = {}): Boolean {
if (!context.isServiceRunning(serviceClass)) {
val startIntent = Intent(context, serviceClass)
if (messenger != null) {
startIntent.putExtra("MESSENGER", messenger)
}
receiver(startIntent)
context.startService(startIntent)
return true
} else
return false
}
}
}
| apache-2.0 | 7ce74fb440668542dc17af1980394945 | 29.753333 | 110 | 0.629525 | 4.504883 | false | false | false | false |
subhalaxmin/Programming-Kotlin | Chapter07/src/main/kotlin/com/packt/chapter2/exceptions.kt | 4 | 553 | package com.packt.chapter2
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
class File(path: String) {
fun close(): Unit {
}
}
fun openFile(): File = File("")
fun readFromFile(file: File): Unit {
}
fun readFile(path: Path): Unit {
val input = Files.newInputStream(path)
try {
var byte = input.read()
while (byte != -1) {
println(byte)
byte = input.read()
}
} catch (e: IOException) {
println("Error reading from file. Error was ${e.message}")
} finally {
input.close()
}
} | mit | be8c5ab1088853181ee2c24ad3994e75 | 18.103448 | 62 | 0.632911 | 3.311377 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/cloudwatch/src/main/kotlin/com/kotlin/cloudwatch/DeleteSubscriptionFilter.kt | 1 | 1940 | // snippet-sourcedescription:[DeleteSubscriptionFilter.kt demonstrates how to delete Amazon CloudWatch log subscription filters.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon CloudWatch]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.cloudwatch
// snippet-start:[cloudwatch.kotlin.delete_subscription_filter.import]
import aws.sdk.kotlin.services.cloudwatchlogs.CloudWatchLogsClient
import aws.sdk.kotlin.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest
import kotlin.system.exitProcess
// snippet-end:[cloudwatch.kotlin.delete_subscription_filter.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<filter> <pattern>
Where:
filter - A filter name (for example, myfilter).
pattern - A filter pattern (for example, ERROR).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val filter = args[0]
val pattern = args[1]
deleteSubFilter(filter, pattern)
}
// snippet-start:[cloudwatch.kotlin.delete_subscription_filter.main]
suspend fun deleteSubFilter(filter: String?, logGroup: String?) {
val request = DeleteSubscriptionFilterRequest {
filterName = filter
logGroupName = logGroup
}
CloudWatchLogsClient { region = "us-west-2" }.use { logs ->
logs.deleteSubscriptionFilter(request)
println("Successfully deleted CloudWatch logs subscription filter named $filter")
}
}
// snippet-end:[cloudwatch.kotlin.delete_subscription_filter.main]
| apache-2.0 | faff106a598673e44b9b1464ecd7069f | 29.803279 | 129 | 0.703093 | 4.154176 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/images/CropImageInteractor.kt | 2 | 2464 | package co.smartreceipts.android.images
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.exifinterface.media.ExifInterface
import co.smartreceipts.android.utils.ImageUtils
import co.smartreceipts.core.di.scopes.ApplicationScope
import co.smartreceipts.analytics.log.Logger
import com.squareup.picasso.Picasso
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import javax.inject.Inject
@ApplicationScope
class CropImageInteractor(
private val subscribeOnScheduler: Scheduler = Schedulers.io(),
private val observeOnScheduler: Scheduler = AndroidSchedulers.mainThread()
) {
@Inject
constructor() : this(Schedulers.io(), AndroidSchedulers.mainThread())
fun getImage(imageFile: File): Observable<Bitmap> {
return Observable.just(imageFile)
.map { BitmapFactory.decodeFile(it.absolutePath) }
.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
}
fun updateImage(file: File, bitmap: Bitmap): Completable {
return Completable.create { emitter ->
val result= ImageUtils.writeImageToFile(bitmap, file)
Picasso.get().invalidate(file)
if (result) {
emitter.onComplete()
} else {
Logger.error(this, "Failed to save bitmap to file")
emitter.onError(Exception("Failed to save bitmap to file"))
}
}
.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
}
fun rotateImage(file: File, isRight: Boolean): Single<Bitmap> {
return Single.create<Bitmap> { emitter ->
val bitmap = ImageUtils.getImageFromFile(file)
val orientation = when {
isRight -> ExifInterface.ORIENTATION_ROTATE_90 // turn right
else -> ExifInterface.ORIENTATION_ROTATE_270 // turn left
}
when {
bitmap!= null -> emitter.onSuccess(ImageUtils.rotateBitmap(bitmap, orientation))
else -> emitter.onError(Exception("Failed to get bitmap"))
}
}
.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
}
} | agpl-3.0 | fa5859ffc164936fc6fb136425eae397 | 31.434211 | 100 | 0.662744 | 5.14405 | false | false | false | false |
taumechanica/ml | src/main/kotlin/ml/base/RandomIndicator.kt | 1 | 794 | // Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package taumechanica.ml.base
import java.util.concurrent.ThreadLocalRandom
import taumechanica.ml.BinaryClassifier
import taumechanica.ml.data.*
class RandomIndicator : BinaryClassifier {
val index: Int
val value: DoubleArray
constructor(attr: Attribute) {
if (attr !is NominalAttribute) {
throw Exception("Unexpected attribute type")
}
val domain = attr.domain
val random = ThreadLocalRandom.current()
index = attr.index
value = DoubleArray(domain.size, {
if (random.nextDouble() > 0.5) 1.0 else -1.0
})
}
override fun phi(values: DoubleArray) = value[values[index].toInt()].toInt()
}
| mit | 61c9bd9f2c228eb447b742308aa2c708 | 25.466667 | 80 | 0.664987 | 4.092784 | false | false | false | false |
paplorinc/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/StaticFileHandler.kt | 1 | 3927 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.builtInWebServer
import com.intellij.openapi.project.Project
import com.intellij.util.PathUtilRt
import io.netty.buffer.ByteBufUtf8Writer
import io.netty.channel.Channel
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpHeaders
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpUtil
import io.netty.handler.stream.ChunkedStream
import org.jetbrains.builtInWebServer.ssi.SsiExternalResolver
import org.jetbrains.builtInWebServer.ssi.SsiProcessor
import org.jetbrains.io.FileResponses
import org.jetbrains.io.addKeepAliveIfNeed
import org.jetbrains.io.flushChunkedResponse
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
private class StaticFileHandler : WebServerFileHandler() {
override val pageFileExtensions = arrayOf("html", "htm", "shtml", "stm", "shtm")
private var ssiProcessor: SsiProcessor? = null
override fun process(pathInfo: PathInfo, canonicalPath: CharSequence, project: Project, request: FullHttpRequest, channel: Channel, projectNameIfNotCustomHost: String?, extraHeaders: HttpHeaders): Boolean {
if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) {
val ioFile = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path)
val nameSequence = ioFile.fileName.toString()
//noinspection SpellCheckingInspection
if (nameSequence.endsWith(".shtml", true) || nameSequence.endsWith(".stm", true) || nameSequence.endsWith(".shtm", true)) {
processSsi(ioFile, PathUtilRt.getParentPath(canonicalPath.toString()), project, request, channel, extraHeaders)
return true
}
FileResponses.sendFile(request, channel, ioFile, extraHeaders)
return true
}
val file = pathInfo.file!!
val response = FileResponses.prepareSend(request, channel, file.timeStamp, file.name, extraHeaders) ?: return true
val isKeepAlive = response.addKeepAliveIfNeed(request)
if (request.method() != HttpMethod.HEAD) {
HttpUtil.setContentLength(response, file.length)
}
channel.write(response)
if (request.method() != HttpMethod.HEAD) {
channel.write(ChunkedStream(file.inputStream))
}
flushChunkedResponse(channel, isKeepAlive)
return true
}
private fun processSsi(file: Path, path: String, project: Project, request: FullHttpRequest, channel: Channel, extraHeaders: HttpHeaders) {
if (ssiProcessor == null) {
ssiProcessor = SsiProcessor(false)
}
val buffer = channel.alloc().ioBuffer()
val isKeepAlive: Boolean
var releaseBuffer = true
try {
val lastModified = ssiProcessor!!.process(SsiExternalResolver(project, request, path, file.parent), file, ByteBufUtf8Writer(buffer))
val response = FileResponses.prepareSend(request, channel, lastModified, file.fileName.toString(), extraHeaders) ?: return
isKeepAlive = response.addKeepAliveIfNeed(request)
if (request.method() != HttpMethod.HEAD) {
HttpUtil.setContentLength(response, buffer.readableBytes().toLong())
}
channel.write(response)
if (request.method() != HttpMethod.HEAD) {
releaseBuffer = false
channel.write(buffer)
}
}
finally {
if (releaseBuffer) {
buffer.release()
}
}
flushChunkedResponse(channel, isKeepAlive)
}
}
internal fun checkAccess(file: Path, root: Path = file.root): Boolean {
var parent = file
do {
if (!hasAccess(parent)) {
return false
}
parent = parent.parent ?: break
}
while (parent != root)
return true
}
// deny access to any dot prefixed file
internal fun hasAccess(result: Path) = Files.isReadable(result) && !(Files.isHidden(result) || result.fileName.toString().startsWith('.')) | apache-2.0 | e6267e4d7f6ca2b91ea633f8c7e01cc1 | 36.409524 | 208 | 0.727782 | 4.363333 | false | false | false | false |
google/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/legacy/GradleStandaloneScriptActions.kt | 2 | 1707 | // 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.gradleJava.scripting.legacy
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
class GradleStandaloneScriptActions(
val manager: GradleStandaloneScriptActionsManager,
val file: VirtualFile,
val isFirstLoad: Boolean,
private val doLoad: () -> Unit
) {
val project get() = manager.project
private val scriptDefinition
get() = file.findScriptDefinition(project)
val isAutoReloadAvailable: Boolean
val isAutoReloadEnabled: Boolean
init {
val scriptDefinition = scriptDefinition
if (scriptDefinition != null) {
isAutoReloadAvailable = true
isAutoReloadEnabled = KotlinScriptingSettings.getInstance(project)
.autoReloadConfigurations(scriptDefinition)
} else {
isAutoReloadAvailable = false
isAutoReloadEnabled = false
}
}
fun enableAutoReload() {
KotlinScriptingSettings.getInstance(project).setAutoReloadConfigurations(scriptDefinition!!, true)
doLoad()
updateNotification()
}
fun reload() {
doLoad()
manager.remove(file)
}
fun updateNotification() {
GradleBuildRootsManager.getInstance(project)?.updateNotifications(false) {
it == file.path
}
}
} | apache-2.0 | a634a57683852e8ac7d680c3378f7f37 | 31.846154 | 158 | 0.707674 | 5.268519 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/onboarding/ViewPagerPager.kt | 5 | 3011 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.onboarding
import android.animation.ValueAnimator
import android.view.animation.AnimationUtils
import androidx.core.animation.addListener
import androidx.viewpager.widget.ViewPager
/**
* Helper class for automatically scrolling pages of a [ViewPager] which does not allow you to
* customize the speed at which it changes page when directly setting the current page.
*/
class ViewPagerPager(private val viewPager: ViewPager) {
private val fastOutSlowIn =
AnimationUtils.loadInterpolator(viewPager.context, android.R.interpolator.fast_out_slow_in)
fun advance() {
if (viewPager.width <= 0) return
val current = viewPager.currentItem
val next = ((current + 1) % requireNotNull(viewPager.adapter).count)
val pages = next - current
val dragDistance = pages * viewPager.width
ValueAnimator.ofInt(0, dragDistance).apply {
var dragProgress = 0
var draggedPages = 0
addListener(
onStart = { viewPager.beginFakeDrag() },
onEnd = { viewPager.endFakeDrag() }
)
addUpdateListener {
if (!viewPager.isFakeDragging) {
// Sometimes onAnimationUpdate is called with initial value before
// onAnimationStart is called.
return@addUpdateListener
}
val dragPoint = (animatedValue as Int)
val dragBy = dragPoint - dragProgress
viewPager.fakeDragBy(-dragBy.toFloat())
dragProgress = dragPoint
// Fake dragging doesn't let you drag more than one page width. If we want to do
// this then need to end and start a new fake drag.
val draggedPagesProgress = dragProgress / viewPager.width
if (draggedPagesProgress != draggedPages) {
viewPager.endFakeDrag()
viewPager.beginFakeDrag()
draggedPages = draggedPagesProgress
}
}
duration = if (pages == 1) PAGE_CHANGE_DURATION else MULTI_PAGE_CHANGE_DURATION
interpolator = fastOutSlowIn
}.start()
}
companion object {
private const val PAGE_CHANGE_DURATION = 400L
private const val MULTI_PAGE_CHANGE_DURATION = 600L
}
}
| apache-2.0 | 20f9ac8d33993487b24322bd3c358356 | 37.602564 | 99 | 0.639655 | 4.985099 | false | false | false | false |
JetBrains/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/execution/build/output/GradleOutputDispatcherFactory.kt | 1 | 8436 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.build.output
import com.intellij.build.BuildProgressListener
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.DuplicateMessageAware
import com.intellij.build.events.FinishEvent
import com.intellij.build.events.StartEvent
import com.intellij.build.events.impl.OutputBuildEventImpl
import com.intellij.build.output.BuildOutputInstantReaderImpl
import com.intellij.build.output.BuildOutputParser
import com.intellij.build.output.LineProcessor
import com.intellij.openapi.externalSystem.service.execution.AbstractOutputMessageDispatcher
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputDispatcherFactory
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputMessageDispatcher
import org.apache.commons.lang.ClassUtils
import org.gradle.api.logging.LogLevel
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
class GradleOutputDispatcherFactory : ExternalSystemOutputDispatcherFactory {
override val externalSystemId = GradleConstants.SYSTEM_ID
override fun create(
buildId: Any,
buildProgressListener: BuildProgressListener,
appendOutputToMainConsole: Boolean,
parsers: List<BuildOutputParser>
): ExternalSystemOutputMessageDispatcher {
return GradleOutputMessageDispatcher(buildId, buildProgressListener, appendOutputToMainConsole, parsers)
}
private class GradleOutputMessageDispatcher(
private val buildId: Any,
private val myBuildProgressListener: BuildProgressListener,
private val appendOutputToMainConsole: Boolean,
private val parsers: List<BuildOutputParser>
) : AbstractOutputMessageDispatcher(
myBuildProgressListener) {
override var stdOut: Boolean = true
private val lineProcessor: LineProcessor
private val myRootReader: BuildOutputInstantReaderImpl
private val tasksOutputReaders: MutableMap<String, BuildOutputInstantReaderImpl> = ConcurrentHashMap()
private val tasksEventIds: MutableMap<String, Any> = ConcurrentHashMap()
private val redefinedReaders = mutableListOf<BuildOutputInstantReaderImpl>()
init {
val deferredRootEvents = mutableListOf<BuildEvent>()
myRootReader = object : BuildOutputInstantReaderImpl(buildId, buildId, BuildProgressListener { _: Any, event: BuildEvent ->
var buildEvent = event
val parentId = buildEvent.parentId
if (parentId != buildId && parentId is String) {
val taskEventId = tasksEventIds[parentId]
if (taskEventId != null) {
buildEvent = BuildEventInvocationHandler.wrap(event, taskEventId)
}
}
if (buildEvent is DuplicateMessageAware) {
deferredRootEvents += buildEvent
}
else {
myBuildProgressListener.onEvent(buildId, buildEvent)
}
}, parsers) {
override fun closeAndGetFuture(): CompletableFuture<Unit> =
super.closeAndGetFuture().whenComplete { _, _ -> deferredRootEvents.forEach { myBuildProgressListener.onEvent(buildId, it) } }
}
lineProcessor = object : LineProcessor() {
private var myCurrentReader: BuildOutputInstantReaderImpl = myRootReader
override fun process(line: String) {
val cleanLine = removeLoggerPrefix(line)
// skip Gradle test runner output
if (cleanLine.startsWith("<ijLog>")) return
if (cleanLine.startsWith("> Task :")) {
val taskName = cleanLine.removePrefix("> Task ").substringBefore(' ')
myCurrentReader = tasksOutputReaders[taskName] ?: myRootReader
}
else if (cleanLine.startsWith("> Configure") ||
cleanLine.startsWith("FAILURE: Build failed") ||
cleanLine.startsWith("CONFIGURE SUCCESSFUL") ||
cleanLine.startsWith("BUILD SUCCESSFUL")) {
myCurrentReader = myRootReader
}
myCurrentReader.appendln(cleanLine)
if (myCurrentReader != myRootReader) {
val parentEventId = myCurrentReader.parentEventId
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(parentEventId, line + '\n', stdOut)) //NON-NLS
}
}
}
}
override fun onEvent(buildId: Any, event: BuildEvent) {
super.onEvent(buildId, event)
if (event.parentId != buildId) return
if (event is StartEvent) {
val eventId = event.id
val oldValue = tasksOutputReaders.put(event.message,
BuildOutputInstantReaderImpl(buildId, eventId, myBuildProgressListener, parsers))
if (oldValue != null) { // multiple invocations of the same task during the build session
redefinedReaders.add(oldValue)
}
tasksEventIds[event.message] = eventId
}
else if (event is FinishEvent) {
// unreceived output is still possible after finish task event but w/o long pauses between chunks
// also no output expected for up-to-date tasks
tasksOutputReaders[event.message]?.disableActiveReading()
}
}
override fun closeAndGetFuture(): CompletableFuture<*> {
lineProcessor.close()
val futures = (tasksOutputReaders.values.asSequence()
+ redefinedReaders.asSequence()
+ sequenceOf(myRootReader))
.map { it.closeAndGetFuture() }
.toList()
tasksOutputReaders.clear()
redefinedReaders.clear()
return CompletableFuture.allOf(*futures.toTypedArray())
}
override fun append(csq: CharSequence): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.toString(), stdOut)) //NON-NLS
}
lineProcessor.append(csq)
return this
}
override fun append(csq: CharSequence, start: Int, end: Int): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.subSequence(start, end).toString(), stdOut)) //NON-NLS
}
lineProcessor.append(csq, start, end)
return this
}
override fun append(c: Char): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, c.toString(), stdOut))
}
lineProcessor.append(c)
return this
}
private fun removeLoggerPrefix(line: String): String {
val list = mutableListOf<String>()
list += line.split(' ', limit = 3)
if (list.size < 3) return line
if (!list[1].startsWith('[') || !list[1].endsWith(']')) return line
if (!list[2].startsWith('[')) return line
if (!list[2].endsWith(']')) {
val i = list[2].indexOf(']')
if (i == -1) return line
list[2] = list[2].substring(0, i + 1)
if (!list[2].endsWith(']')) return line
}
val logLevel = list[1].drop(1).dropLast(1)
return if (enumValues<LogLevel>().none { it.name == logLevel }) {
line
}
else {
line.drop(list.sumOf { it.length } + 2).trimStart()
}
}
private class BuildEventInvocationHandler(
private val buildEvent: BuildEvent,
private val parentEventId: Any
) : InvocationHandler {
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
if (method?.name.equals("getParentId")) return parentEventId
return method?.invoke(buildEvent, *args ?: arrayOfNulls<Any>(0))
}
companion object {
fun wrap(buildEvent: BuildEvent, parentEventId: Any): BuildEvent {
val classLoader = buildEvent.javaClass.classLoader
val interfaces = ClassUtils.getAllInterfaces(buildEvent.javaClass)
.filterIsInstance(Class::class.java)
.toTypedArray()
val invocationHandler = BuildEventInvocationHandler(buildEvent, parentEventId)
return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler) as BuildEvent
}
}
}
}
}
| apache-2.0 | 8c58b6b824ce261f2fe3b143149a91b3 | 41.18 | 140 | 0.690019 | 5.185003 | false | false | false | false |
raybritton/json-query | lib/src/main/kotlin/com/raybritton/jsonquery/tools/Rewriting.kt | 1 | 6894 | package com.raybritton.jsonquery.tools
import com.raybritton.jsonquery.RuntimeException
import com.raybritton.jsonquery.ext.copyWithoutFirst
import com.raybritton.jsonquery.ext.copyWithoutLast
import com.raybritton.jsonquery.ext.toPath
import com.raybritton.jsonquery.ext.toSegments
import com.raybritton.jsonquery.models.JsonArray
import com.raybritton.jsonquery.models.JsonObject
import com.raybritton.jsonquery.models.Query
import com.raybritton.jsonquery.models.SelectProjection
import java.util.*
/**
* Methods in this file update the object they are called instead of returning a new version
*/
internal fun Any?.rewrite(query: Query) {
if (this == null) return
if (query.select?.projection == null) return
val projection = query.select.projection
when (projection) {
is SelectProjection.SingleField -> {
if (projection.newName != null) {
update(projection.field, projection.newName)
}
}
is SelectProjection.MultipleFields -> {
projection.fields.forEach {
if (it.second != null) {
update(it.first, it.second!!)
}
}
}
}
}
private fun Any.rename(segments: List<String>, newName: String) {
val key = segments.last()
val path = segments.copyWithoutLast()
val container = this.navigateToTarget(path.joinToString("."))
when (container) {
is JsonObject -> {
container[newName] = container[key]
container.remove(key)
}
is JsonArray -> {
container.filter { it is JsonObject }
.forEach {
val element = it as JsonObject
element[newName] = element[key]
element.remove(key)
}
}
else -> throw RuntimeException("Aliasing $key to $newName is not possible as ${container.javaClass} is not in an object")
}
}
private fun Any.createPath(new: List<String>) {
if (new.isNotEmpty()) {
val segment = new[0]
when {
this is JsonObject -> {
if (this[segment] !is JsonObject) {
this[segment] = JsonObject()
}
this[segment]!!.createPath(new.copyWithoutFirst())
}
this is JsonArray -> {
forEach {
if (it is JsonObject) {
it.createPath(new.copyWithoutFirst())
}
}
}
else -> throw RuntimeException("Unable to rename to ${new.joinToString(".")}, encountered: ${this.javaClass}")
}
}
}
private fun Any.move(old: List<String>, new: List<String>) {
val key = old.last()
val oldSegments = old.copyWithoutLast()
val oldContainer = this.navigateToTarget(oldSegments.toPath())
when (oldContainer) {
is JsonObject -> {
val value = oldContainer.remove(key)
if (oldContainer.isEmpty()) {
if (oldSegments.isNotEmpty()) {
val parent = this.navigateToTarget(oldSegments.copyWithoutLast().toPath())
when (parent) {
is JsonObject -> parent.remove(oldSegments.last())
is JsonArray -> {
}
else -> throw IllegalStateException("Parent was a value: $parent (${parent.javaClass})")
}
}
}
this.createPath(new)
val newContainer = this.navigateToTarget(new.copyWithoutLast().toPath())
if (newContainer is JsonObject) {
newContainer[new.last()] = value
} else {
throw IllegalStateException("createPath() didn't force target to JsonObject")
}
this.removeEmpties()
}
is JsonArray -> {
val values = ArrayDeque(oldContainer.filter { it is JsonObject }.map { (it as JsonObject).remove(key) })
if (this is JsonArray) {
(0 until values.size).forEach {
when {
this.size < it -> this.add(JsonObject())
this[it] !is JsonObject -> this[it] = JsonObject()
}
}
this.filter { it is JsonObject }.forEach {
it!!.createPath(new)
val newContainer = it.navigateToTarget(new.copyWithoutLast().toPath())
if (newContainer is JsonObject) {
newContainer[new.last()] = values.poll()
} else {
throw IllegalStateException("createPath() didn't force target to JsonObject: ${newContainer.javaClass}")
}
}
} else if (this is JsonObject) {
this[new.last()] = JsonArray(values)
// this.createPath(new)
// (this.navigateToTarget(new.copyWithoutLast().toPath()) as JsonObject)[new.last()] = JsonArray(values)
}
this.removeEmpties()
}
else -> throw RuntimeException("Aliasing $key to ${new.last()} is not possible as ${oldContainer.javaClass} is not in an object")
}
}
private fun Any?.removeEmpties() {
val isEmpty: (Any?) -> Boolean = {
((it as? JsonArray)?.isEmpty() == true) || ((it as? JsonObject)?.isEmpty() == true)
}
when (this) {
is JsonArray -> {
val iterator = this.listIterator()
while (iterator.hasNext()) {
val element = iterator.next()
if (isEmpty(element)) {
iterator.remove()
} else {
element.removeEmpties()
if (isEmpty(element)) {
iterator.remove()
}
}
}
}
is JsonObject -> {
val iterator = this.keys.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
if (isEmpty(this[key])) {
iterator.remove() //call iterator.remove() before to stop ConcurrentModificationException
this.remove(key)
} else {
this[key].removeEmpties()
if (isEmpty(this[key])) {
iterator.remove()
this.remove(key)
}
}
}
}
}
}
private fun Any.update(field: String, newName: String) {
val currentPath = field.toSegments()
val newPath = newName.toSegments()
if (currentPath.copyWithoutLast() == newPath.copyWithoutLast()) {
rename(currentPath, newPath.last())
} else {
move(currentPath, newPath)
}
} | apache-2.0 | 07e31228f3d3cd3c3485a0ed9aa3e382 | 36.069892 | 137 | 0.524369 | 4.959712 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/jps/serialization/ExternalModuleImlFileEntitiesSerializer.kt | 1 | 8038 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtil
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.util.JpsPathUtil
internal class ExternalModuleImlFileEntitiesSerializer(modulePath: ModulePath,
fileUrl: VirtualFileUrl,
virtualFileManager: VirtualFileUrlManager,
internalEntitySource: JpsFileEntitySource,
internalModuleListSerializer: JpsModuleListSerializer)
: ModuleImlFileEntitiesSerializer(modulePath, fileUrl, internalEntitySource, virtualFileManager, internalModuleListSerializer) {
override val skipLoadingIfFileDoesNotExist: Boolean
get() = true
override fun loadEntities(builder: WorkspaceEntityStorageBuilder,
reader: JpsFileContentReader,
errorReporter: ErrorReporter,
virtualFileManager: VirtualFileUrlManager) {
}
override fun acceptsSource(entitySource: EntitySource): Boolean {
return entitySource is JpsImportedEntitySource && entitySource.storedExternally
}
override fun readExternalSystemOptions(reader: JpsFileContentReader,
moduleOptions: Map<String?, String?>): Pair<Map<String?, String?>, String?> {
val componentTag = reader.loadComponent(fileUrl.url, "ExternalSystem", getBaseDirPath()) ?: return Pair(emptyMap(), null)
val options = componentTag.attributes.associateBy({ it.name }, { it.value })
return Pair(options, options["externalSystem"])
}
override fun loadExternalSystemOptions(builder: WorkspaceEntityStorageBuilder,
module: ModuleEntity,
reader: JpsFileContentReader,
externalSystemOptions: Map<String?, String?>,
externalSystemId: String?,
entitySource: EntitySource) {
val optionsEntity = builder.getOrCreateExternalSystemModuleOptions(module, entitySource)
builder.modifyEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, optionsEntity) {
externalSystem = externalSystemId
externalSystemModuleVersion = externalSystemOptions["externalSystemModuleVersion"]
linkedProjectPath = externalSystemOptions["linkedProjectPath"]
linkedProjectId = externalSystemOptions["linkedProjectId"]
rootProjectPath = externalSystemOptions["rootProjectPath"]
externalSystemModuleGroup = externalSystemOptions["externalSystemModuleGroup"]
externalSystemModuleType = externalSystemOptions["externalSystemModuleType"]
}
}
override fun saveModuleOptions(externalSystemOptions: ExternalSystemModuleOptionsEntity?,
moduleType: String?,
customImlData: ModuleCustomImlDataEntity?,
writer: JpsFileContentWriter) {
val fileUrlString = fileUrl.url
if (FileUtil.extensionEquals(fileUrlString, "iml")) {
logger<ExternalModuleImlFileEntitiesSerializer>().error("External serializer should not write to iml files. Path:$fileUrlString")
}
if (externalSystemOptions != null) {
val componentTag = JDomSerializationUtil.createComponentElement("ExternalSystem")
fun saveOption(name: String, value: String?) {
if (value != null) {
componentTag.setAttribute(name, value)
}
}
saveOption("externalSystem", externalSystemOptions.externalSystem)
saveOption("externalSystemModuleGroup", externalSystemOptions.externalSystemModuleGroup)
saveOption("externalSystemModuleType", externalSystemOptions.externalSystemModuleType)
saveOption("externalSystemModuleVersion", externalSystemOptions.externalSystemModuleVersion)
saveOption("linkedProjectId", externalSystemOptions.linkedProjectId)
saveOption("linkedProjectPath", externalSystemOptions.linkedProjectPath)
saveOption("rootProjectPath", externalSystemOptions.rootProjectPath)
writer.saveComponent(fileUrlString, "ExternalSystem", componentTag)
}
if (moduleType != null) {
val componentTag = JDomSerializationUtil.createComponentElement(DEPRECATED_MODULE_MANAGER_COMPONENT_NAME)
componentTag.addContent(Element("option").setAttribute("key", "type").setAttribute("value", moduleType))
writer.saveComponent(fileUrlString, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, componentTag)
}
}
override fun createExternalEntitySource(externalSystemId: String) =
JpsImportedEntitySource(internalEntitySource, externalSystemId, true)
override fun createFacetSerializer(): FacetEntitiesSerializer {
return FacetEntitiesSerializer(fileUrl, internalEntitySource, "ExternalFacetManager", true)
}
override fun getBaseDirPath(): String? {
return modulePath.path
}
override fun toString(): String = "ExternalModuleImlFileEntitiesSerializer($fileUrl)"
}
internal class ExternalModuleListSerializer(private val externalStorageRoot: VirtualFileUrl,
private val virtualFileManager: VirtualFileUrlManager) :
ModuleListSerializerImpl(externalStorageRoot.append("project/modules.xml").url, virtualFileManager) {
override val isExternalStorage: Boolean
get() = true
override val componentName: String
get() = "ExternalProjectModuleManager"
override val entitySourceFilter: (EntitySource) -> Boolean
get() = { it is JpsImportedEntitySource && it.storedExternally }
override fun getSourceToSave(module: ModuleEntity): JpsFileEntitySource.FileInDirectory? {
return (module.entitySource as? JpsImportedEntitySource)?.internalFile as? JpsFileEntitySource.FileInDirectory
}
override fun getFileName(entity: ModuleEntity): String {
return "${entity.name}.xml"
}
override fun createSerializer(internalSource: JpsFileEntitySource, fileUrl: VirtualFileUrl, moduleGroup: String?): JpsFileEntitiesSerializer<ModuleEntity> {
val fileName = PathUtil.getFileName(fileUrl.url)
val actualFileUrl = if (PathUtil.getFileExtension(fileName) == "iml") {
externalStorageRoot.append("modules/${fileName.substringBeforeLast('.')}.xml")
}
else {
fileUrl
}
val filePath = JpsPathUtil.urlToPath(fileUrl.url)
return ExternalModuleImlFileEntitiesSerializer(ModulePath(filePath, moduleGroup), actualFileUrl, virtualFileManager, internalSource, this)
}
// Component DeprecatedModuleOptionManager removed by ModuleStateStorageManager.beforeElementSaved from .iml files
override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) {
super.deleteObsoleteFile(fileUrl, writer)
if (FileUtil.extensionEquals(fileUrl, "xml")) {
writer.saveComponent(fileUrl, "ExternalSystem", null)
writer.saveComponent(fileUrl, "ExternalFacetManager", null)
writer.saveComponent(fileUrl, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null)
}
}
override fun toString(): String = "ExternalModuleListSerializer($fileUrl)"
}
| apache-2.0 | 89efce304ad10e9a439b5ca867be0551 | 51.881579 | 158 | 0.728664 | 6.339117 | false | false | false | false |
allotria/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/language/java/JavaGrammarCheckingStrategy.kt | 2 | 3050 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.language.java
import com.intellij.grazie.grammar.strategy.BaseGrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain
import com.intellij.grazie.grammar.strategy.StrategyUtils
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.psi.JavaDocTokenType.*
import com.intellij.psi.JavaTokenType.C_STYLE_COMMENT
import com.intellij.psi.JavaTokenType.END_OF_LINE_COMMENT
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.impl.source.tree.JavaDocElementType.DOC_COMMENT
import com.intellij.psi.impl.source.tree.JavaElementType.LITERAL_EXPRESSION
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.impl.source.tree.PsiCommentImpl
import com.intellij.psi.javadoc.PsiDocTag
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.elementType
class JavaGrammarCheckingStrategy : BaseGrammarCheckingStrategy {
private fun isTag(token: PsiElement) = token.parent is PsiDocTag
private fun isCodeTag(token: PsiElement) = isTag(token) && ((token.parent as PsiDocTag).nameElement.text == "@code")
private fun isCommentData(token: PsiElement) = token is LeafPsiElement && token.elementType == DOC_COMMENT_DATA
override fun isMyContextRoot(element: PsiElement) = getContextRootTextDomain(element) != TextDomain.NON_TEXT
override fun getContextRootTextDomain(root: PsiElement) = when (root.elementType) {
DOC_COMMENT -> TextDomain.DOCS
C_STYLE_COMMENT, END_OF_LINE_COMMENT -> TextDomain.COMMENTS
LITERAL_EXPRESSION -> TextDomain.LITERALS
else -> TextDomain.NON_TEXT
}
override fun isAbsorb(element: PsiElement) = isTag(element) && (!isCommentData(element) || isCodeTag(element))
private val STEALTH_TYPES = setOf(DOC_COMMENT_START, DOC_COMMENT_LEADING_ASTERISKS, DOC_COMMENT_END)
override fun isStealth(element: PsiElement) = element is LeafPsiElement && element.elementType in STEALTH_TYPES
override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement) = when {
root is PsiLiteralExpression -> RuleGroup.LITERALS
isTag(child) -> RuleGroup.CASING + RuleGroup.PUNCTUATION
else -> null
}
override fun getStealthyRanges(root: PsiElement, text: CharSequence) = when (root) {
is PsiCommentImpl -> StrategyUtils.indentIndexes(text, setOf(' ', '\t', '*', '/'))
else -> StrategyUtils.indentIndexes(text, setOf(' ', '\t'))
}
private fun IElementType?.isSingleLineCommentType() = when (this) {
END_OF_LINE_COMMENT, C_STYLE_COMMENT -> true
else -> false
}
override fun getRootsChain(root: PsiElement): List<PsiElement> {
return if (root.elementType.isSingleLineCommentType()) {
StrategyUtils.getNotSoDistantSiblingsOfTypes(this, root) { type -> type.isSingleLineCommentType() }.toList()
}
else super.getRootsChain(root)
}
}
| apache-2.0 | dd05193364c7151df2838f293734a853 | 48.193548 | 140 | 0.776721 | 3.986928 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ui/tabs/layout/TabsLayoutSettingsUi.kt | 4 | 4614 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.layout
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.layout.*
import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo
import javax.swing.ComboBoxModel
import javax.swing.DefaultComboBoxModel
import javax.swing.JComboBox
import javax.swing.ListCellRenderer
import javax.swing.SwingConstants.TOP
class TabsLayoutSettingsUi {
companion object {
private val LOG = Logger.getInstance(TabsLayoutSettingsUi::class.java)
internal fun tabsLayoutComboBox(tabPlacementComboBoxModel: DefaultComboBoxModel<Int>): ComboBox<TabsLayoutInfo> {
val model = DefaultComboBoxModel<TabsLayoutInfo>(TabsLayoutSettingsHolder.instance.installedInfos.toTypedArray())
val comboBox = comboBox(model,
SimpleListCellRenderer.create<TabsLayoutInfo> { label, value, _ ->
label.text = value.name
})
comboBox.addActionListener {
val selectedInfo = getSelectedInfo(comboBox)
if (selectedInfo == null) {
tabPlacementComboBoxModel.removeAllElements()
tabPlacementComboBoxModel.addElement(TOP);
return@addActionListener
}
var availableTabsPositions: Array<Int>? = selectedInfo.getAvailableTabsPositions();
if (availableTabsPositions == null || availableTabsPositions.isEmpty()) {
tabPlacementComboBoxModel.removeAllElements()
tabPlacementComboBoxModel.addElement(TOP);
return@addActionListener
}
var needToResetSelected = true
var selectedValue: Int? = null
if (tabPlacementComboBoxModel.selectedItem is Int) {
var prevSelectedValue = tabPlacementComboBoxModel.selectedItem as Int
if (prevSelectedValue in availableTabsPositions) {
selectedValue = prevSelectedValue;
needToResetSelected = false;
}
}
if (needToResetSelected) {
selectedValue = availableTabsPositions[0];
}
tabPlacementComboBoxModel.removeAllElements();
for (value in availableTabsPositions) {
tabPlacementComboBoxModel.addElement(value);
}
tabPlacementComboBoxModel.selectedItem = selectedValue;
}
return comboBox
}
private fun <T> comboBox(model: ComboBoxModel<T>,
renderer: ListCellRenderer<T?>? = null): ComboBox<T> {
val component = ComboBox(model)
if (renderer != null) {
component.renderer = renderer
}
else {
component.renderer = SimpleListCellRenderer.create("") { it.toString() }
}
return component
}
fun prepare(builder: CellBuilder<JComboBox<TabsLayoutInfo>>,
comboBox: JComboBox<TabsLayoutInfo>) {
builder.onApply {
getSelectedInfo(comboBox)?.let{
UISettings.instance.selectedTabsLayoutInfoId = it.id
}
}
builder.onReset {
val savedSelectedInfoId = calculateSavedSelectedInfoId()
val selectedInfo = getSelectedInfo(comboBox)
val isWrongSelected = selectedInfo == null || selectedInfo.id != UISettings.instance.selectedTabsLayoutInfoId
for (info in TabsLayoutSettingsHolder.instance.installedInfos) {
if (isWrongSelected && info.id == savedSelectedInfoId) {
comboBox.selectedItem = info
}
}
}
builder.onIsModified {
val savedSelectedInfoId = calculateSavedSelectedInfoId()
val selectedInfo = getSelectedInfo(comboBox)
if (selectedInfo != null && selectedInfo.id != savedSelectedInfoId) {
return@onIsModified true
}
return@onIsModified false
}
}
private fun calculateSavedSelectedInfoId(): String? {
var savedSelectedInfoId = UISettings.instance.selectedTabsLayoutInfoId
if (StringUtil.isEmpty(savedSelectedInfoId)) {
savedSelectedInfoId = TabsLayoutSettingsHolder.instance.defaultInfo.id
}
return savedSelectedInfoId
}
fun getSelectedInfo(comboBox: JComboBox<TabsLayoutInfo>) : TabsLayoutInfo? {
val selectedInfo = comboBox.selectedItem
selectedInfo?.let {
return selectedInfo as TabsLayoutInfo
}
return null
}
}
} | apache-2.0 | f46ebd75cb7584d13f0bd8eafd5ecfd2 | 36.520325 | 140 | 0.680754 | 5.07033 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/platform/ProjectFrameAllocator.kt | 1 | 8546 | // 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.platform
import com.intellij.conversion.CannotConvertException
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.runActivity
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.idea.SplashManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.createModalTask
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.*
import com.intellij.ui.ComponentUtil
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.ScreenUtil
import com.intellij.ui.scale.ScaleContext
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAwt
import java.awt.Dimension
import java.awt.Frame
import java.awt.Image
import java.io.EOFException
import java.nio.file.Path
import kotlin.math.min
internal open class ProjectFrameAllocator {
open fun run(task: () -> Unit): Boolean {
task()
return true
}
/**
* Project is loaded and is initialized, project services and components can be accessed.
*/
open fun projectLoaded(project: Project) {}
open fun projectNotLoaded(error: CannotConvertException?) {
if (error != null) {
ProjectManagerImpl.showCannotConvertMessage(error, null)
}
}
open fun projectOpened(project: Project) {}
}
internal class ProjectUiFrameAllocator(private var options: OpenProjectTask, private val projectFile: Path) : ProjectFrameAllocator() {
// volatile not required because created in run (before executing run task)
private var frameHelper: ProjectFrameHelper? = null
private var isFrameBoundsCorrect = false
@Volatile
private var cancelled = false
override fun run(task: () -> Unit): Boolean {
var completed = false
val progressTitle = IdeUICustomization.getInstance().projectMessage("project.loading.name", options.projectName ?: projectFile.fileName)
ApplicationManager.getApplication().invokeAndWait {
val frame = createFrameIfNeeded()
val progressTask = createModalTask(progressTitle) {
if (frameHelper == null) {
ApplicationManager.getApplication().invokeLater {
if (cancelled) {
return@invokeLater
}
runActivity("project frame initialization") {
initNewFrame(frame)
}
}
}
task()
}
completed = (ProgressManager.getInstance() as CoreProgressManager).runProcessWithProgressSynchronously(progressTask, frame.rootPane)
}
return completed
}
@CalledInAwt
private fun initNewFrame(frame: IdeFrameImpl) {
if (frame.isVisible) {
val frameHelper = ProjectFrameHelper(frame, null)
frameHelper.init()
// otherwise not painted if frame already visible
frame.validate()
this.frameHelper = frameHelper
isFrameBoundsCorrect = true
return
}
if (options.frame?.bounds == null) {
val recentProjectManager = RecentProjectsManager.getInstance()
if (recentProjectManager is RecentProjectsManagerBase) {
val info = recentProjectManager.getProjectMetaInfo(projectFile)
if (info != null) {
options = options.copy(frame = info.frame, projectWorkspaceId = info.projectWorkspaceId)
}
}
}
var projectSelfie: Image? = null
if (options.projectWorkspaceId != null && Registry.`is`("ide.project.loading.show.last.state")) {
try {
projectSelfie = ProjectSelfieUtil.readProjectSelfie(options.projectWorkspaceId!!, ScaleContext.create(frame))
}
catch (e: Throwable) {
if (e.cause !is EOFException) {
logger<ProjectFrameAllocator>().warn(e)
}
}
}
val frameHelper = ProjectFrameHelper(frame, projectSelfie)
// must be after preInit (frame decorator is required to set full screen mode)
var frameInfo = options.frame
if (frameInfo?.bounds == null) {
isFrameBoundsCorrect = false
frameInfo = (WindowManager.getInstance() as WindowManagerImpl).defaultFrameInfo
}
else {
isFrameBoundsCorrect = true
}
if (frameInfo != null) {
restoreFrameState(frameHelper, frameInfo)
}
if (options.sendFrameBack && frame.isAutoRequestFocus) {
logger<ProjectFrameAllocator>().error("isAutoRequestFocus must be false")
}
frame.isVisible = true
frameHelper.init()
this.frameHelper = frameHelper
}
private fun createFrameIfNeeded(): IdeFrameImpl {
val freeRootFrame = (WindowManager.getInstance() as WindowManagerImpl).removeAndGetRootFrame()
if (freeRootFrame != null) {
isFrameBoundsCorrect = true
frameHelper = freeRootFrame
return freeRootFrame.frame
}
runActivity("create a frame", ActivityCategory.MAIN) {
var frame = SplashManager.getAndUnsetProjectFrame() as IdeFrameImpl?
if (frame == null) {
frame = createNewProjectFrame(forceDisableAutoRequestFocus = options.sendFrameBack)
}
return frame
}
}
override fun projectLoaded(project: Project) {
ApplicationManager.getApplication().invokeLater(Runnable {
val frameHelper = frameHelper ?: return@Runnable
val windowManager = WindowManager.getInstance() as WindowManagerImpl
runActivity("project frame assigning") {
val projectFrameBounds = ProjectFrameBounds.getInstance(project)
if (isFrameBoundsCorrect) {
// update to ensure that project stores correct frame bounds
projectFrameBounds.markDirty(if (FrameInfoHelper.isMaximized(frameHelper.frame.extendedState)) null else frameHelper.frame.bounds)
}
else {
val frameInfo = projectFrameBounds.getFrameInfoInDeviceSpace()
if (frameInfo?.bounds != null) {
restoreFrameState(frameHelper, frameInfo)
}
}
windowManager.assignFrame(frameHelper, project)
}
runActivity("tool window pane creation") {
(ToolWindowManager.getInstance(project) as ToolWindowManagerImpl).init(frameHelper)
}
}, project.disposed)
}
override fun projectNotLoaded(error: CannotConvertException?) {
cancelled = true
ApplicationManager.getApplication().invokeLater {
val frame = frameHelper
frameHelper = null
if (error != null) {
ProjectManagerImpl.showCannotConvertMessage(error, frame?.frame)
}
frame?.frame?.dispose()
}
}
override fun projectOpened(project: Project) {
if (options.sendFrameBack) {
frameHelper?.frame?.isAutoRequestFocus = true
}
}
}
private fun restoreFrameState(frameHelper: ProjectFrameHelper, frameInfo: FrameInfo) {
val deviceBounds = frameInfo.bounds
val bounds = if (deviceBounds == null) null else FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(deviceBounds)
val state = frameInfo.extendedState
val isMaximized = FrameInfoHelper.isMaximized(state)
val frame = frameHelper.frame
if (bounds != null && isMaximized && frame.extendedState == Frame.NORMAL) {
frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds)
}
if (bounds != null) {
frame.bounds = bounds
}
frame.extendedState = state
if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) {
frameHelper.toggleFullScreen(true)
}
}
@ApiStatus.Internal
fun createNewProjectFrame(forceDisableAutoRequestFocus: Boolean): IdeFrameImpl {
val frame = IdeFrameImpl()
SplashManager.hideBeforeShow(frame)
val size = ScreenUtil.getMainScreenBounds().size
size.width = min(1400, size.width - 20)
size.height = min(1000, size.height - 40)
frame.size = size
frame.setLocationRelativeTo(null)
if (forceDisableAutoRequestFocus || (!ApplicationManager.getApplication().isActive && ComponentUtil.isDisableAutoRequestFocus())) {
frame.isAutoRequestFocus = false
}
frame.minimumSize = Dimension(340, frame.minimumSize.height)
return frame
} | apache-2.0 | 0039d03e321edc006b0705db837d5098 | 33.603239 | 140 | 0.724549 | 4.779642 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KPascalTriangle.kt | 1 | 995 | package me.consuegra.algorithms
/**
* Given numRows, generate the first numRows of Pascal’s triangle.
* <p>
* Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
* <p>
* Example:
* <p>
* Given numRows = 5,
* <p>
* Return
* <p>
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
*/
class KPascalTriangle {
fun generate(rows: Int): Array<IntArray> {
val triangle = Array(rows, { intArrayOf() })
for (i in 0 until rows) {
triangle[i] = IntArray(i + 1)
for (j in 0..i) {
triangle[i][j] = calculateValue(triangle, i - 1, j)
}
}
return triangle
}
private fun calculateValue(triangle: Array<IntArray>, i: Int, j: Int): Int {
if (i < 0) {
return 1
}
val row = triangle[i]
if (j <= 0 || j >= row.size) {
return 1
}
return row[j] + row[j - 1]
}
}
| mit | f60eea9f8da648e428ddacf00aaa40f1 | 20.456522 | 99 | 0.484296 | 2.963964 | false | false | false | false |
smmribeiro/intellij-community | platform/indexing-impl/src/com/intellij/psi/impl/search/lowLevelSearchUtil.kt | 10 | 2760 | // 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.psi.impl.search
import com.intellij.lang.ASTNode
import com.intellij.model.search.LeafOccurrence
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.psi.PsiElement
import com.intellij.psi.util.walkUp
internal data class LeafOccurrenceData(
override val scope: PsiElement,
override val start: PsiElement,
override val offsetInStart: Int
) : LeafOccurrence
internal fun LeafOccurrence.elementsUp(): Iterator<Pair<PsiElement, Int>> = walkUp(start, offsetInStart, scope)
internal typealias OccurrenceProcessor = (occurrence: LeafOccurrence) -> Boolean
/**
* @return [OccurrenceProcessor] which runs bunch of [OccurrenceProcessor]s one by one
*/
internal fun Collection<OccurrenceProcessor>.compound(progress: ProgressIndicator): OccurrenceProcessor {
singleOrNull()?.let {
return it
}
return { occurrence: LeafOccurrence ->
[email protected](progress, occurrence)
}
}
/**
* @return runs bunch of [OccurrenceProcessor]s one by one
*/
internal fun Collection<OccurrenceProcessor>.runProcessors(progress: ProgressIndicator, occurrence: LeafOccurrence): Boolean {
for (processor in this) {
progress.checkCanceled()
if (!processor(occurrence)) {
return false
}
}
return true
}
internal fun processOffsets(scope: PsiElement,
offsetsInScope: IntArray,
patternLength: Int,
progress: ProgressIndicator,
processor: OccurrenceProcessor): Boolean {
if (offsetsInScope.isEmpty()) {
return true
}
val scopeNode = requireNotNull(scope.node) {
"Scope doesn't have node, can't scan: $scope; containingFile: ${scope.containingFile}"
}
return LowLevelSearchUtil.processOffsets(scopeNode, offsetsInScope, progress) { node, offsetInNode ->
processOffset(scopeNode, node, offsetInNode, patternLength, processor)
}
}
private fun processOffset(scopeNode: ASTNode,
node: ASTNode,
offsetInNode: Int,
patternLength: Int,
processor: OccurrenceProcessor): Boolean {
var currentNode = node
var currentOffset = offsetInNode
while (true) {
if (currentNode.textLength >= currentOffset + patternLength) {
return processor(LeafOccurrenceData(scopeNode.psi, currentNode.psi, currentOffset))
}
if (currentNode === scopeNode) {
return true
}
currentOffset += currentNode.startOffsetInParent
currentNode = currentNode.treeParent ?: return true
}
}
| apache-2.0 | aa067f1830ba6e5bbe16345e7e5aad4c | 34.384615 | 158 | 0.700725 | 4.6543 | false | false | false | false |
smmribeiro/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/state.kt | 5 | 3714 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl
import com.intellij.openapi.components.BaseState
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.XCollection
import com.intellij.xdebugger.XExpression
import com.intellij.xdebugger.impl.breakpoints.BreakpointState
import com.intellij.xdebugger.impl.breakpoints.LineBreakpointState
import com.intellij.xdebugger.impl.breakpoints.XBreakpointsDialogState
import com.intellij.xdebugger.impl.breakpoints.XExpressionState
import com.intellij.xdebugger.impl.inline.InlineWatch
import com.intellij.xdebugger.impl.pinned.items.PinnedItemInfo
@Tag("breakpoint-manager")
class BreakpointManagerState : BaseState() {
@get:XCollection(propertyElementName = "default-breakpoints")
val defaultBreakpoints by list<BreakpointState<*, *, *>>()
@get:XCollection(elementTypes = [BreakpointState::class, LineBreakpointState::class], style = XCollection.Style.v2)
val breakpoints by list<BreakpointState<*, *, *>>()
@get:XCollection(propertyElementName = "breakpoints-defaults", elementTypes = [BreakpointState::class, LineBreakpointState::class])
val breakpointsDefaults by list<BreakpointState<*, *, *>>()
@get:Tag("breakpoints-dialog")
var breakpointsDialogProperties by property<XBreakpointsDialogState>()
var defaultGroup by string()
}
@Tag("watches-manager")
class WatchesManagerState : BaseState() {
@get:Property(surroundWithTag = false)
@get:XCollection
val expressions by list<ConfigurationState>()
@get:Property(surroundWithTag = false)
@get:XCollection
val inlineExpressionStates by list<InlineWatchState>()
}
@Tag("configuration")
class ConfigurationState @JvmOverloads constructor(name: String? = null,
expressions: List<XExpression>? = null) : BaseState() {
@get:Attribute
var name by string()
@Suppress("MemberVisibilityCanPrivate")
@get:Property(surroundWithTag = false)
@get:XCollection
val expressionStates by list<WatchState>()
init {
// passed values are not default - constructor provided only for convenience
if (name != null) {
this.name = name
}
if (expressions != null) {
expressionStates.clear()
expressions.mapTo(expressionStates) { WatchState(it) }
}
}
}
@Tag("inline-watch")
class InlineWatchState @JvmOverloads constructor(expression: XExpression? = null, line: Int = -1, fileUrl: String? = null) : BaseState() {
@get:Attribute
var fileUrl by string()
@get:Attribute
var line by property(-1)
@get:Property(surroundWithTag = false)
var watchState by property<WatchState?>(null) {it == null}
init {
this.fileUrl = fileUrl
this.line = line
this.watchState = expression?.let { WatchState(it) }
}
}
@Tag("watch")
class WatchState : XExpressionState {
@Suppress("unused")
constructor() : super()
constructor(expression: XExpression) : super(expression)
}
@Tag("pin-to-top-manager")
class PinToTopManagerState : BaseState() {
@get:XCollection(propertyElementName = "pinned-members")
var pinnedMembersList by list<PinnedItemInfo>()
}
internal class XDebuggerState : BaseState() {
@get:Property(surroundWithTag = false)
var breakpointManagerState by property(BreakpointManagerState())
@get:Property(surroundWithTag = false)
var watchesManagerState by property(WatchesManagerState())
@get:Property(surroundWithTag = false)
var pinToTopManagerState by property(PinToTopManagerState())
} | apache-2.0 | 8f8b9e5738b158e7ad5ee148f1deadeb | 33.398148 | 140 | 0.750942 | 4.298611 | false | false | false | false |
mdaniel/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/ngram/ModelRunnerWithCache.kt | 9 | 1415 | // 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.completion.ml.ngram
import com.intellij.completion.ml.ngram.NGram.forgetTokens
import com.intellij.completion.ml.ngram.NGram.learnTokens
import com.intellij.completion.ml.ngram.NGram.lexPsiFile
import com.intellij.completion.ngram.slp.modeling.Model
import com.intellij.completion.ngram.slp.modeling.ngram.JMModel
import com.intellij.completion.ngram.slp.modeling.runners.ModelRunner
import com.intellij.psi.PsiFile
internal class ModelRunnerWithCache(model: Model = JMModel()) : ModelRunner(model) {
private val myCache = FilePath2Tokens(this)
internal fun processFile(psiFile: PsiFile, filePath: String) {
if (filePath in myCache) return
val tokens = lexPsiFile(psiFile, TEXT_RANGE_LIMIT)
myCache[filePath] = tokens
learnTokens(tokens)
}
private class FilePath2Tokens(private val myModelRunner: ModelRunner) : LinkedHashMap<String, List<String>>() {
override fun removeEldestEntry(eldest: Map.Entry<String?, List<String>?>): Boolean {
if (size > CACHE_SIZE) {
eldest.value?.let { myModelRunner.forgetTokens(it) }
return true
}
return false
}
}
companion object {
private const val CACHE_SIZE = 9
private const val TEXT_RANGE_LIMIT = 16 * 1024 // 32 KB of chars
}
} | apache-2.0 | b186a0c1d4099f356c1d3ca68eb4a454 | 36.263158 | 140 | 0.746996 | 3.773333 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyExplicitLambdaSignatureIntention.kt | 1 | 4473 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isError
open class SpecifyExplicitLambdaSignatureIntention : SelfTargetingOffsetIndependentIntention<KtLambdaExpression>(
KtLambdaExpression::class.java, KotlinBundle.lazyMessage("specify.explicit.lambda.signature")
), LowPriorityAction {
override fun isApplicableTo(element: KtLambdaExpression): Boolean {
if (element.functionLiteral.arrow != null && element.valueParameters.all { it.typeReference != null }) return false
val functionDescriptor = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)[BindingContext.FUNCTION, element.functionLiteral] ?: return false
return functionDescriptor.valueParameters.none { it.type.isError }
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
applyTo(element)
}
companion object {
fun applyTo(element: KtLambdaExpression) {
val functionLiteral = element.functionLiteral
val functionDescriptor = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.FUNCTION, functionLiteral]!!
applyWithParameters(element, functionDescriptor.valueParameters
.asSequence()
.mapIndexed { index, parameterDescriptor ->
parameterDescriptor.render(psiName = functionLiteral.valueParameters.getOrNull(index)?.let {
it.name ?: it.destructuringDeclaration?.text
})
}
.joinToString())
}
fun KtFunctionLiteral.setParameterListIfAny(psiFactory: KtPsiFactory, newParameterList: KtParameterList?) {
val oldParameterList = valueParameterList
if (oldParameterList != null && newParameterList != null) {
oldParameterList.replace(newParameterList)
} else {
val openBraceElement = lBrace
val nextSibling = openBraceElement.nextSibling
val addNewline = nextSibling is PsiWhiteSpace && nextSibling.text?.contains("\n") ?: false
val (whitespace, arrow) = psiFactory.createWhitespaceAndArrow()
addRangeAfter(whitespace, arrow, openBraceElement)
if (newParameterList != null) {
addAfter(newParameterList, openBraceElement)
}
if (addNewline) {
addAfter(psiFactory.createNewLine(), openBraceElement)
}
}
}
fun applyWithParameters(element: KtLambdaExpression, parameterString: String) {
val psiFactory = KtPsiFactory(element)
val functionLiteral = element.functionLiteral
val newParameterList =
(psiFactory.createExpression("{ $parameterString -> }") as KtLambdaExpression).functionLiteral.valueParameterList
runWriteActionIfPhysical(element) {
functionLiteral.setParameterListIfAny(psiFactory, newParameterList)
ShortenReferences.DEFAULT.process(element.valueParameters)
}
}
}
}
private fun ValueParameterDescriptor.render(psiName: String?): String = IdeDescriptorRenderers.SOURCE_CODE.let {
"${psiName ?: it.renderName(name, true)}: ${it.renderType(type)}"
}
| apache-2.0 | e15e3b25e3816b08f52e2627b5317e47 | 50.413793 | 160 | 0.716521 | 5.570361 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassImportAliasAllUsages.0.kt | 3 | 1077 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtImportAlias
// OPTIONS: usages, constructorUsages
package client
import server.Server as Srv<caret>
import server.Server
class Client(name: String = Server.NAME): Srv() {
var nextServer: Server? = new Server()
val name = Server.NAME
/**
* [Srv] parameter
*/
fun foo(s: Srv) {
val server: Server = s
println("Server: $server")
}
fun getNextServer(): Server? {
return nextServer
}
override fun work() {
super<Server>.work()
println("Client")
}
companion object: Server() {
}
}
object ClientObject: Server() {
}
class Servers: Iterator<Server> {
}
fun Iterator<Server>.f(p: Iterator<Server>): Iterator<Server> = this
fun Client.bar(s: Server = Server.NAME) {
foo(s)
}
fun Client.hasNextServer(): Boolean {
return getNextServer() != null
}
fun Any.asServer(): Server? {
when (this) {
is Server -> println("Server!")
}
return if (this is Server) this as Server else this as? Server
}
// DISABLE-ERRORS | apache-2.0 | 330d6747bdc24b610341dd5e329e9b80 | 17.271186 | 68 | 0.619313 | 3.650847 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt | 1 | 15682 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.completion.handlers.BaseDeclarationInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinClassifierInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionInsertHandler
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.core.completion.PackageLookupObject
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.highlighter.dsl.DslHighlighterExtension
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.awt.Font
class BasicLookupElementFactory(
private val project: Project,
val insertHandlerProvider: InsertHandlerProvider
) {
companion object {
// we skip parameter names in functional types in most of cases for shortness
val SHORT_NAMES_RENDERER = DescriptorRenderer.SHORT_NAMES_IN_TYPES.withOptions {
enhancedTypes = true
parameterNamesInFunctionalTypes = false
}
}
fun createLookupElement(
descriptor: DeclarationDescriptor,
qualifyNestedClasses: Boolean = false,
includeClassTypeArguments: Boolean = true,
parametersAndTypeGrayed: Boolean = false
): LookupElement {
return createLookupElementUnwrappedDescriptor(
descriptor.unwrapIfFakeOverride(),
qualifyNestedClasses,
includeClassTypeArguments,
parametersAndTypeGrayed
)
}
fun createLookupElementForJavaClass(
psiClass: PsiClass,
qualifyNestedClasses: Boolean = false,
includeClassTypeArguments: Boolean = true
): LookupElement {
val lookupObject = object : DeclarationLookupObjectImpl(null) {
override val psiElement: PsiElement?
get() = psiClass
override fun getIcon(flags: Int) = psiClass.getIcon(flags)
}
var element = LookupElementBuilder.create(lookupObject, psiClass.name!!).withInsertHandler(KotlinClassifierInsertHandler)
val typeParams = psiClass.typeParameters
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
element = element.appendTailText(typeParams.map { it.name }.joinToString(", ", "<", ">"), true)
}
val qualifiedName = psiClass.qualifiedName!!
var containerName = qualifiedName.substringBeforeLast('.', FqName.ROOT.toString())
if (qualifyNestedClasses) {
val nestLevel = psiClass.parents.takeWhile { it is PsiClass }.count()
if (nestLevel > 0) {
var itemText = psiClass.name
for (i in 1..nestLevel) {
val outerClassName = containerName.substringAfterLast('.')
element = element.withLookupString(outerClassName)
itemText = outerClassName + "." + itemText
containerName = containerName.substringBeforeLast('.', FqName.ROOT.toString())
}
element = element.withPresentableText(itemText!!)
}
}
element = element.appendTailText(" ($containerName)", true)
if (lookupObject.isDeprecated) {
element = element.withStrikeoutness(true)
}
return element.withIconFromLookupObject()
}
fun createLookupElementForPackage(name: FqName): LookupElement {
var element = LookupElementBuilder.create(PackageLookupObject(name), name.shortName().asString())
element = element.withInsertHandler(BaseDeclarationInsertHandler())
if (!name.parent().isRoot) {
element = element.appendTailText(" (${name.asString()})", true)
}
return element.withIconFromLookupObject()
}
private fun createLookupElementUnwrappedDescriptor(
descriptor: DeclarationDescriptor,
qualifyNestedClasses: Boolean,
includeClassTypeArguments: Boolean,
parametersAndTypeGrayed: Boolean
): LookupElement {
if (descriptor is JavaClassDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor)
if (declaration is PsiClass && declaration !is KtLightClass) {
// for java classes we create special lookup elements
// because they must be equal to ones created in TypesCompletion
// otherwise we may have duplicates
return createLookupElementForJavaClass(declaration, qualifyNestedClasses, includeClassTypeArguments)
}
}
if (descriptor is PackageViewDescriptor) {
return createLookupElementForPackage(descriptor.fqName)
}
if (descriptor is PackageFragmentDescriptor) {
return createLookupElementForPackage(descriptor.fqName)
}
val lookupObject: DeclarationLookupObject
val name: String = when (descriptor) {
is ConstructorDescriptor -> {
// for constructor use name and icon of containing class
val classifierDescriptor = descriptor.containingDeclaration
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, classifierDescriptor) }
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(classifierDescriptor, psiElement, flags)
}
classifierDescriptor.name.asString()
}
is SyntheticJavaPropertyDescriptor -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor.getMethod) }
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, null, flags)
}
descriptor.name.asString()
}
else -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy {
DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) ?: DescriptorToSourceUtilsIde.getAnyDeclaration(
project,
descriptor
)
}
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, psiElement, flags)
}
descriptor.name.asString()
}
}
var element = LookupElementBuilder.create(lookupObject, name)
val insertHandler = insertHandlerProvider.insertHandler(descriptor)
element = element.withInsertHandler(insertHandler)
when (descriptor) {
is FunctionDescriptor -> {
val returnType = descriptor.returnType
element = element.withTypeText(
if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "",
parametersAndTypeGrayed
)
val insertsLambda = (insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null
if (insertsLambda) {
element = element.appendTailText(" {...} ", parametersAndTypeGrayed)
}
element = element.appendTailText(
SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor),
parametersAndTypeGrayed || insertsLambda
)
}
is VariableDescriptor -> {
element = element.withTypeText(SHORT_NAMES_RENDERER.renderType(descriptor.type), parametersAndTypeGrayed)
}
is ClassifierDescriptorWithTypeParameters -> {
val typeParams = descriptor.declaredTypeParameters
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
element = element.appendTailText(typeParams.joinToString(", ", "<", ">") { it.name.asString() }, true)
}
var container = descriptor.containingDeclaration
if (descriptor.isArtificialImportAliasedDescriptor) {
container = descriptor.original // we show original descriptor instead of container for import aliased descriptors
} else if (qualifyNestedClasses) {
element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor))
while (container is ClassDescriptor) {
val containerName = container.name
if (!containerName.isSpecial) {
element = element.withLookupString(containerName.asString())
}
container = container.containingDeclaration
}
}
if (container is PackageFragmentDescriptor || container is ClassifierDescriptor) {
element = element.appendTailText(" (" + DescriptorUtils.getFqName(container) + ")", true)
}
if (descriptor is TypeAliasDescriptor) {
// here we render with DescriptorRenderer.SHORT_NAMES_IN_TYPES to include parameter names in functional types
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.underlyingType), false)
}
}
else -> {
element = element.withTypeText(SHORT_NAMES_RENDERER.render(descriptor), parametersAndTypeGrayed)
}
}
var isMarkedAsDsl = false
if (descriptor is CallableDescriptor) {
appendContainerAndReceiverInformation(descriptor) { element = element.appendTailText(it, true) }
val dslTextAttributes = DslHighlighterExtension.dslCustomTextStyle(descriptor)?.let {
EditorColorsManager.getInstance().globalScheme.getAttributes(it)
}
if (dslTextAttributes != null) {
isMarkedAsDsl = true
element = element.withBoldness(dslTextAttributes.fontType == Font.BOLD)
dslTextAttributes.foregroundColor?.let { element = element.withItemTextForeground(it) }
}
}
if (descriptor is PropertyDescriptor) {
val getterName = JvmAbi.getterName(name)
if (getterName != name) {
element = element.withLookupString(getterName)
}
if (descriptor.isVar) {
element = element.withLookupString(JvmAbi.setterName(name))
}
}
if (lookupObject.isDeprecated) {
element = element.withStrikeoutness(true)
}
if ((insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null) {
element.putUserData(KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE, Unit)
}
val result = element.withIconFromLookupObject()
result.isDslMember = isMarkedAsDsl
return result
}
fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullResult {
it.getContainerAndReceiverInformation(descriptor)
}
if (information != null) {
appendTailText(information)
return
}
val extensionReceiver = descriptor.original.extensionReceiverParameter
if (extensionReceiver != null) {
when (descriptor) {
is SamAdapterExtensionFunctionDescriptor -> {
// no need to show them as extensions
return
}
is SyntheticJavaPropertyDescriptor -> {
var from = descriptor.getMethod.name.asString() + "()"
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.from.0", from))
return
}
else -> {
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type)
appendTailText(KotlinIdeaCompletionBundle.message("presentation.tail.for.0", receiverPresentation))
}
}
}
val containerPresentation = containerPresentation(descriptor)
if (containerPresentation != null) {
appendTailText(" ")
appendTailText(containerPresentation)
}
}
private fun containerPresentation(descriptor: DeclarationDescriptor): String? {
when {
descriptor.isArtificialImportAliasedDescriptor -> {
return "(${DescriptorUtils.getFqName(descriptor.original)})"
}
descriptor.isExtension -> {
val containerPresentation = when (val container = descriptor.containingDeclaration) {
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
is PackageFragmentDescriptor -> container.fqName.toString()
else -> return null
}
return KotlinIdeaCompletionBundle.message("presentation.tail.in.0", containerPresentation)
}
else -> {
val container = descriptor.containingDeclaration as? PackageFragmentDescriptor
// we show container only for global functions and properties
?: return null
//TODO: it would be probably better to show it also for static declarations which are not from the current class (imported)
return "(${container.fqName})"
}
}
}
// add icon in renderElement only to pass presentation.isReal()
private fun LookupElement.withIconFromLookupObject(): LookupElement = object : LookupElementDecorator<LookupElement>(this) {
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject)
}
}
}
| apache-2.0 | 8fb47555c7549acc98f3538b73cc6015 | 44.455072 | 158 | 0.644178 | 5.974095 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/german/WieManga.kt | 1 | 4575 | /*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* TachiyomiEX 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 file incorporates work covered by the following license notice:
*
* 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 .
*/
package eu.kanade.tachiyomi.data.source.online.german
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.DE
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
class WieManga(override val source: Sources) : ParsedOnlineSource() {
override val baseUrl = "http://www.wiemanga.com"
override val lang: Language get()= DE
override fun supportsLatest() = true
override fun popularMangaInitialUrl() = "$baseUrl/list/Hot-Book/"
override fun latestUpdatesInitialUrl() = "$baseUrl/list/New-Update/"
override fun popularMangaSelector() = ".booklist td > div"
override fun popularMangaFromElement(element: Element, manga: Manga) {
val title = element.select("dd a:first-child")
manga.setUrlWithoutDomain(title.attr("href"))
manga.title = title.text()
manga.thumbnail_url = element.select("dt img").attr("src")
}
override fun popularMangaNextPageSelector() = null
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/search/?wd=$query"
override fun searchMangaSelector() = ".searchresult td > div"
override fun searchMangaFromElement(element: Element, manga: Manga) {
val title = element.select(".resultbookname")
manga.setUrlWithoutDomain(title.attr("href"))
manga.title = title.text()
manga.thumbnail_url = element.select(".resultimg img").attr("src")
}
override fun searchMangaNextPageSelector() = ".pagetor a.l"
override fun mangaDetailsParse(document: Document, manga: Manga) {
val infoElement = document.select(".bookmessgae tr > td:nth-child(2)").first()
manga.author = infoElement.select("dd:nth-of-type(2) a").first()?.text()
manga.artist = infoElement.select("dd:nth-of-type(3) a").first()?.text()
manga.description = infoElement.select("dl > dt:last-child").first()?.text()?.replaceFirst("Beschreibung", "")
manga.thumbnail_url = document.select(".bookmessgae tr > td:nth-child(1) a > img").first()?.attr("src")
if (manga.author == "RSS")
manga.author = null
if (manga.artist == "RSS")
manga.artist = null
}
override fun chapterListSelector() = ".chapterlist tr:not(:first-child)"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select(".col1 a").first()
val dateElement = element.select(".col3 a").first()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = dateElement?.text()?.let { parseChapterDate(it) } ?: 0
}
private fun parseChapterDate(date: String): Long {
return SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(date).time
}
override fun pageListParse(response: Response, pages: MutableList<Page>) {
val document = response.asJsoup()
document.select("select#page").first().select("option").forEach {
pages.add(Page(pages.size, it.attr("value")))
}
}
override fun pageListParse(document: Document, pages: MutableList<Page>) {}
override fun imageUrlParse(document: Document) = document.select("img#comicpic").first().attr("src")
}
| gpl-3.0 | 51ce87eafe05401025cfd5565812f8b5 | 39.131579 | 118 | 0.699454 | 4.159091 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/AbstractKlibLibraryInfo.kt | 3 | 1423 | // 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.klib
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.idea.caches.project.LibraryInfo
import org.jetbrains.kotlin.idea.util.IJLoggerAdapter
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.platform.TargetPlatform
abstract class AbstractKlibLibraryInfo(project: Project, library: Library, val libraryRoot: String) : LibraryInfo(project, library) {
val resolvedKotlinLibrary: KotlinLibrary = resolveSingleFileKlib(
libraryFile = File(libraryRoot),
logger = LOG,
strategy = ToolingSingleFileKlibResolveStrategy
)
val compatibilityInfo: KlibCompatibilityInfo by lazy { resolvedKotlinLibrary.getCompatibilityInfo() }
final override fun getLibraryRoots() = listOf(libraryRoot)
abstract override val platform: TargetPlatform // must override
val uniqueName: String? by lazy { resolvedKotlinLibrary.safeRead(null) { uniqueName } }
val isInterop: Boolean by lazy { resolvedKotlinLibrary.safeRead(false) { isInterop } }
companion object {
private val LOG = IJLoggerAdapter.getInstance(AbstractKlibLibraryInfo::class.java)
}
}
| apache-2.0 | ea3ae50aac3f2f852aac375ec4e85baa | 40.852941 | 158 | 0.779339 | 4.711921 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/draw/Shadow.kt | 3 | 4269 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.draw
import androidx.compose.runtime.Stable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.DefaultShadowColor
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.platform.inspectable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Creates a [graphicsLayer] that draws a shadow. The [elevation] defines the visual
* depth of the physical object. The physical object has a shape specified by [shape].
*
* If the passed [shape] is concave the shadow will not be drawn on Android versions less than 10.
*
* Note that [elevation] is only affecting the shadow size and doesn't change the drawing order.
* Use a [androidx.compose.ui.zIndex] modifier if you want to draw the elements with larger
* [elevation] after all the elements with a smaller one.
*
* Usage of this API renders this composable into a separate graphics layer
* @see graphicsLayer
*
* Example usage:
*
* @sample androidx.compose.ui.samples.ShadowSample
*
* @param elevation The elevation for the shadow in pixels
* @param shape Defines a shape of the physical object
* @param clip When active, the content drawing clips to the shape.
*/
@Deprecated(
"Replace with shadow which accepts ambientColor and spotColor parameters",
ReplaceWith(
"Modifier.shadow(elevation, shape, clip, DefaultShadowColor, DefaultShadowColor)",
"androidx.compose.ui.draw"
),
DeprecationLevel.HIDDEN
)
@Stable
fun Modifier.shadow(
elevation: Dp,
shape: Shape = RectangleShape,
clip: Boolean = elevation > 0.dp
) = shadow(
elevation,
shape,
clip,
DefaultShadowColor,
DefaultShadowColor,
)
/**
* Creates a [graphicsLayer] that draws a shadow. The [elevation] defines the visual
* depth of the physical object. The physical object has a shape specified by [shape].
*
* If the passed [shape] is concave the shadow will not be drawn on Android versions less than 10.
*
* Note that [elevation] is only affecting the shadow size and doesn't change the drawing order.
* Use a [androidx.compose.ui.zIndex] modifier if you want to draw the elements with larger
* [elevation] after all the elements with a smaller one.
*
* Usage of this API renders this composable into a separate graphics layer
* @see graphicsLayer
*
* Example usage:
*
* @sample androidx.compose.ui.samples.ShadowSample
*
* @param elevation The elevation for the shadow in pixels
* @param shape Defines a shape of the physical object
* @param clip When active, the content drawing clips to the shape.
*/
@Stable
fun Modifier.shadow(
elevation: Dp,
shape: Shape = RectangleShape,
clip: Boolean = elevation > 0.dp,
ambientColor: Color = DefaultShadowColor,
spotColor: Color = DefaultShadowColor,
) = if (elevation > 0.dp || clip) {
inspectable(
inspectorInfo = debugInspectorInfo {
name = "shadow"
properties["elevation"] = elevation
properties["shape"] = shape
properties["clip"] = clip
properties["ambientColor"] = ambientColor
properties["spotColor"] = spotColor
}
) {
graphicsLayer {
this.shadowElevation = elevation.toPx()
this.shape = shape
this.clip = clip
this.ambientShadowColor = ambientColor
this.spotShadowColor = spotColor
}
}
} else {
this
}
| apache-2.0 | 4e41f29e9bfc7181a823ac478969ffa4 | 33.991803 | 98 | 0.71703 | 4.32085 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/layout.kt | 1 | 2289 | // 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.ui.DialogPanel
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.components.DialogPanel
/**
* See [docs](http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/kotlin_ui_dsl.html).
*
* Claims all available space in the container for the columns ([LCFlags.fillX], if `constraints` is passed, `fillX` will be not applied - add it explicitly if need).
* At least one component need to have a [Row.grow] constraint for it to fill the container.
*
* Check `Tools -> Internal Actions -> UI -> UI DSL Debug Mode` to turn on debug painting.
*
* `JTextComponent`, `TextFieldWithHistory` (use [Row.textFieldWithBrowseButton]), `SeparatorComponent` and `ComponentWithBrowseButton` components automatically have [Row.growX].
*
* `ToolbarDecorator` and `JBScrollPane` (use [Row.scrollPane]) components automatically have [Row.grow] and [Row.push].
*/
@Deprecated("Use com.intellij.ui.dsl.builder.panel from Kotlin UI DSL Version 2 and kotlin documentations for related classes")
inline fun panel(vararg constraints: LCFlags, @NlsContexts.DialogTitle title: String? = null, init: LayoutBuilder.() -> Unit): DialogPanel {
val builder = createLayoutBuilder()
builder.init()
val panel = DialogPanel(title, layout = null)
val bgcolor = Registry.getColor("ui.kotlin.ui.dsl.deprecated.panel.color", null)
bgcolor?.let {
panel.background = it
}
builder.builder.build(panel, constraints)
initPanel(builder, panel)
return panel
}
@PublishedApi
internal fun initPanel(builder: LayoutBuilder, panel: DialogPanel) {
panel.preferredFocusedComponent = builder.builder.preferredFocusedComponent
panel.validateCallbacks = builder.builder.validateCallbacks
panel.componentValidateCallbacks = builder.builder.componentValidateCallbacks
panel.customValidationRequestors = builder.builder.customValidationRequestors
panel.applyCallbacks = builder.builder.applyCallbacks
panel.resetCallbacks = builder.builder.resetCallbacks
panel.isModifiedCallbacks = builder.builder.isModifiedCallbacks
} | apache-2.0 | 4cb1e8429227c812275987bae93c114f | 49.888889 | 178 | 0.782875 | 4.302632 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/orders.kt | 1 | 7790 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
/**
* This entity stores order of facets in iml file. This is needed to ensure that facet tags are saved in the same order to avoid
* unnecessary modifications of iml file.
*/
interface FacetsOrderEntity : WorkspaceEntity {
val orderOfFacets: List<String>
val moduleEntity: ModuleEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetsOrderEntity, WorkspaceEntity.Builder<FacetsOrderEntity>, ObjBuilder<FacetsOrderEntity> {
override var entitySource: EntitySource
override var orderOfFacets: MutableList<String>
override var moduleEntity: ModuleEntity
}
companion object : Type<FacetsOrderEntity, Builder>() {
operator fun invoke(orderOfFacets: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetsOrderEntity {
val builder = builder()
builder.orderOfFacets = orderOfFacets.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetsOrderEntity, modification: FacetsOrderEntity.Builder.() -> Unit) = modifyEntity(
FacetsOrderEntity.Builder::class.java, entity, modification)
//endregion
val ModuleEntity.facetOrder: @Child FacetsOrderEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in facet configuration to avoid unnecessary modifications
*/
interface FacetExternalSystemIdEntity : WorkspaceEntity {
val externalSystemId: String
val facet: FacetEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetExternalSystemIdEntity, WorkspaceEntity.Builder<FacetExternalSystemIdEntity>, ObjBuilder<FacetExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var facet: FacetEntity
}
companion object : Type<FacetExternalSystemIdEntity, Builder>() {
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): FacetExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetExternalSystemIdEntity,
modification: FacetExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
FacetExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val FacetEntity.facetExternalSystemIdEntity: @Child FacetExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in artifact configuration file to avoid unnecessary modifications
*/
interface ArtifactExternalSystemIdEntity : WorkspaceEntity {
val externalSystemId: String
val artifactEntity: ArtifactEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactExternalSystemIdEntity, WorkspaceEntity.Builder<ArtifactExternalSystemIdEntity>, ObjBuilder<ArtifactExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var artifactEntity: ArtifactEntity
}
companion object : Type<ArtifactExternalSystemIdEntity, Builder>() {
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ArtifactExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactExternalSystemIdEntity,
modification: ArtifactExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
ArtifactExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val ArtifactEntity.artifactExternalSystemIdEntity: @Child ArtifactExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in library configuration file to avoid unnecessary modifications
*/
interface LibraryExternalSystemIdEntity: WorkspaceEntity {
val externalSystemId: String
val library: LibraryEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : LibraryExternalSystemIdEntity, WorkspaceEntity.Builder<LibraryExternalSystemIdEntity>, ObjBuilder<LibraryExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var library: LibraryEntity
}
companion object : Type<LibraryExternalSystemIdEntity, Builder>() {
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): LibraryExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LibraryExternalSystemIdEntity,
modification: LibraryExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
LibraryExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val LibraryEntity.externalSystemId: @Child LibraryExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This entity stores order of artifacts in ipr file. This is needed to ensure that artifact tags are saved in the same order to avoid
* unnecessary modifications of ipr file.
*/
interface ArtifactsOrderEntity : WorkspaceEntity {
val orderOfArtifacts: List<String>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactsOrderEntity, WorkspaceEntity.Builder<ArtifactsOrderEntity>, ObjBuilder<ArtifactsOrderEntity> {
override var entitySource: EntitySource
override var orderOfArtifacts: MutableList<String>
}
companion object : Type<ArtifactsOrderEntity, Builder>() {
operator fun invoke(orderOfArtifacts: List<String>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ArtifactsOrderEntity {
val builder = builder()
builder.orderOfArtifacts = orderOfArtifacts.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactsOrderEntity, modification: ArtifactsOrderEntity.Builder.() -> Unit) = modifyEntity(
ArtifactsOrderEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | da9643bcd9dcf825f7c5207f01845b1c | 37.95 | 155 | 0.755327 | 5.715334 | false | false | false | false |
GunoH/intellij-community | platform/util/diff/src/com/intellij/diff/comparison/MergeResolveUtil.kt | 8 | 9128 | // 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.diff.comparison
import com.intellij.diff.fragments.DiffFragment
import com.intellij.diff.fragments.MergeWordFragmentImpl
import com.intellij.diff.util.*
import com.intellij.diff.util.MergeConflictType.Type
import com.intellij.diff.util.Side.LEFT
import com.intellij.diff.util.Side.RIGHT
import com.intellij.util.text.MergingCharSequence
object MergeResolveUtil {
@JvmStatic
fun tryResolve(leftText: CharSequence, baseText: CharSequence, rightText: CharSequence): CharSequence? {
try {
val resolved = trySimpleResolve(leftText, baseText, rightText, ComparisonPolicy.DEFAULT)
if (resolved != null) return resolved
return trySimpleResolve(leftText, baseText, rightText, ComparisonPolicy.IGNORE_WHITESPACES)
}
catch (e: DiffTooBigException) {
return null
}
}
/*
* Here we assume, that resolve results are explicitly verified by user and can be safely undone.
* Thus we trade higher chances of incorrect resolve for higher chances of correct resolve.
*
* We're making an assertion, that "A-X-B" and "B-X-A" conflicts should produce equal results.
* This leads us to conclusion, that insertion-insertion conflicts can't be possibly resolved (if inserted fragments are different),
* because we don't know the right order of inserted chunks (and sorting them alphabetically or by length makes no sense).
*
* deleted-inserted conflicts can be resolved by applying both of them.
* deleted-deleted conflicts can be resolved by merging deleted intervals.
* modifications can be considered as "insertion + deletion" and resolved accordingly.
*/
@JvmStatic
fun tryGreedyResolve(leftText: CharSequence, baseText: CharSequence, rightText: CharSequence): CharSequence? {
try {
val resolved = tryGreedyResolve(leftText, baseText, rightText, ComparisonPolicy.DEFAULT)
if (resolved != null) return resolved
return tryGreedyResolve(leftText, baseText, rightText, ComparisonPolicy.IGNORE_WHITESPACES)
}
catch (e: DiffTooBigException) {
return null
}
}
}
private fun trySimpleResolve(leftText: CharSequence, baseText: CharSequence, rightText: CharSequence,
policy: ComparisonPolicy): CharSequence? {
return SimpleHelper(leftText, baseText, rightText).execute(policy)
}
private fun tryGreedyResolve(leftText: CharSequence, baseText: CharSequence, rightText: CharSequence,
policy: ComparisonPolicy): CharSequence? {
return GreedyHelper(leftText, baseText, rightText).execute(policy)
}
private class SimpleHelper(val leftText: CharSequence, val baseText: CharSequence, val rightText: CharSequence) {
private val newContent = StringBuilder()
private var last1 = 0
private var last2 = 0
private var last3 = 0
private val texts = listOf(leftText, baseText, rightText)
fun execute(policy: ComparisonPolicy): CharSequence? {
val changes = ByWordRt.compare(leftText, baseText, rightText, policy, CancellationChecker.EMPTY)
for (fragment in changes) {
val baseRange = nextMergeRange(fragment.getStartOffset(ThreeSide.LEFT),
fragment.getStartOffset(ThreeSide.BASE),
fragment.getStartOffset(ThreeSide.RIGHT))
appendBase(baseRange)
val conflictRange = nextMergeRange(fragment.getEndOffset(ThreeSide.LEFT),
fragment.getEndOffset(ThreeSide.BASE),
fragment.getEndOffset(ThreeSide.RIGHT))
if (!appendConflict(conflictRange, policy)) return null
}
val trailingRange = nextMergeRange(leftText.length, baseText.length, rightText.length)
appendBase(trailingRange)
return newContent.toString()
}
private fun nextMergeRange(end1: Int, end2: Int, end3: Int): MergeRange {
val range = MergeRange(last1, end1, last2, end2, last3, end3)
last1 = end1
last2 = end2
last3 = end3
return range
}
private fun appendBase(range: MergeRange) {
if (range.isEmpty) return
val policy = ComparisonPolicy.DEFAULT
if (isUnchangedRange(range, policy)) {
append(range, ThreeSide.BASE)
}
else {
val type = getConflictType(range, policy)
if (type.isChange(Side.LEFT)) {
append(range, ThreeSide.LEFT)
}
else if (type.isChange(Side.RIGHT)) {
append(range, ThreeSide.RIGHT)
}
else {
append(range, ThreeSide.BASE)
}
}
}
private fun appendConflict(range: MergeRange, policy: ComparisonPolicy): Boolean {
val type = getConflictType(range, policy)
if (type.type == Type.CONFLICT) return false
if (type.isChange(Side.LEFT)) {
append(range, ThreeSide.LEFT)
}
else {
append(range, ThreeSide.RIGHT)
}
return true
}
private fun append(range: MergeRange, side: ThreeSide) {
when (side) {
ThreeSide.LEFT -> newContent.append(leftText, range.start1, range.end1)
ThreeSide.BASE -> newContent.append(baseText, range.start2, range.end2)
ThreeSide.RIGHT -> newContent.append(rightText, range.start3, range.end3)
}
}
private fun getConflictType(range: MergeRange, policy: ComparisonPolicy): MergeConflictType {
return MergeRangeUtil.getWordMergeType(MergeWordFragmentImpl(range), texts, policy)
}
private fun isUnchangedRange(range: MergeRange, policy: ComparisonPolicy): Boolean {
return MergeRangeUtil.compareWordMergeContents(MergeWordFragmentImpl(range), texts, policy, ThreeSide.BASE, ThreeSide.LEFT) &&
MergeRangeUtil.compareWordMergeContents(MergeWordFragmentImpl(range), texts, policy, ThreeSide.BASE, ThreeSide.RIGHT)
}
}
private class GreedyHelper(val leftText: CharSequence, val baseText: CharSequence, val rightText: CharSequence) {
private val newContent = StringBuilder()
private var lastBaseOffset = 0
private var index1 = 0
private var index2 = 0
fun execute(policy: ComparisonPolicy): CharSequence? {
val fragments1 = ByWordRt.compare(baseText, leftText, policy, CancellationChecker.EMPTY)
val fragments2 = ByWordRt.compare(baseText, rightText, policy, CancellationChecker.EMPTY)
while (true) {
val changeStart1 = fragments1.getOrNull(index1)?.startOffset1 ?: -1
val changeStart2 = fragments2.getOrNull(index2)?.startOffset1 ?: -1
if (changeStart1 == -1 && changeStart2 == -1) {
// no more changes left
appendBase(baseText.length)
break
}
// skip till the next block of changes
if (changeStart1 != -1 && changeStart2 != -1) {
appendBase(Math.min(changeStart1, changeStart2))
}
else if (changeStart1 != -1) {
appendBase(changeStart1)
}
else {
appendBase(changeStart2)
}
// collect next block of changes, that intersect one another.
var baseOffsetEnd = lastBaseOffset
var end1 = index1
var end2 = index2
while (true) {
val next1 = fragments1.getOrNull(end1)
val next2 = fragments2.getOrNull(end2)
if (next1 != null && next1.startOffset1 <= baseOffsetEnd) {
baseOffsetEnd = Math.max(baseOffsetEnd, next1.endOffset1)
end1++
continue
}
if (next2 != null && next2.startOffset1 <= baseOffsetEnd) {
baseOffsetEnd = Math.max(baseOffsetEnd, next2.endOffset1)
end2++
continue
}
break
}
assert(index1 != end1 || index2 != end2)
val inserted1 = getInsertedContent(fragments1, index1, end1, LEFT)
val inserted2 = getInsertedContent(fragments2, index2, end2, RIGHT)
index1 = end1
index2 = end2
// merge and apply deletions
lastBaseOffset = baseOffsetEnd
// merge and apply non-conflicted insertions
if (inserted1.isEmpty() && inserted2.isEmpty()) continue
if (inserted2.isEmpty()) {
newContent.append(inserted1)
continue
}
if (inserted1.isEmpty()) {
newContent.append(inserted2)
continue
}
if (ComparisonUtil.isEqualTexts(inserted1, inserted2, policy)) {
val inserted = if (inserted1.length <= inserted2.length) inserted1 else inserted2
newContent.append(inserted)
continue
}
// we faced conflicting insertions - resolve failed
return null
}
return newContent
}
private fun appendBase(endOffset: Int) {
if (lastBaseOffset == endOffset) return
newContent.append(baseText.subSequence(lastBaseOffset, endOffset))
lastBaseOffset = endOffset
}
private fun getInsertedContent(fragments: List<DiffFragment>, start: Int, end: Int, side: Side): CharSequence {
val text = side.select(leftText, rightText)!!
val empty: CharSequence = ""
return fragments.subList(start, end).fold(empty, { prefix, fragment ->
MergingCharSequence(prefix, text.subSequence(fragment.startOffset2, fragment.endOffset2))
})
}
}
| apache-2.0 | 8c5e1812ea70f327b7ddcbac322da119 | 33.97318 | 134 | 0.688103 | 4.373742 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/LinuxDistributionBuilder.kt | 1 | 20640 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.io.NioFiles
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.BundledRuntimeImpl.Companion.getProductPrefix
import org.jetbrains.intellij.build.impl.productInfo.*
import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
import org.jetbrains.intellij.build.io.*
import java.nio.file.*
import java.nio.file.attribute.PosixFilePermissions
import kotlin.time.Duration.Companion.minutes
class LinuxDistributionBuilder(override val context: BuildContext,
private val customizer: LinuxDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val iconPngPath: Path?
override val targetOs: OsFamily
get() = OsFamily.LINUX
init {
val iconPng = (if (context.applicationInfo.isEAP) customizer.iconPngPathForEAP else null) ?: customizer.iconPngPath
iconPngPath = if (iconPng.isNullOrEmpty()) null else Path.of(iconPng)
}
override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
spanBuilder("copy files for os distribution").setAttribute("os", targetOs.osName).setAttribute("arch", arch.name).useWithScope2 {
withContext(Dispatchers.IO) {
val distBinDir = targetPath.resolve("bin")
val sourceBinDir = context.paths.communityHomeDir.resolve("bin/linux")
copyFileToDir(sourceBinDir.resolve("restart.py"), distBinDir)
if (arch == JvmArchitecture.x64 || arch == JvmArchitecture.aarch64) {
@Suppress("SpellCheckingInspection")
listOf("fsnotifier", "libdbm.so").forEach {
copyFileToDir(sourceBinDir.resolve("${arch.dirName}/${it}"), distBinDir)
}
}
generateBuildTxt(context, targetPath)
copyDistFiles(context = context, newDir = targetPath, os = OsFamily.LINUX, arch = arch)
Files.copy(ideaProperties!!, distBinDir.resolve(ideaProperties.fileName), StandardCopyOption.REPLACE_EXISTING)
//todo[nik] converting line separators to unix-style make sense only when building Linux distributions under Windows on a local machine;
// for real installers we need to checkout all text files with 'lf' separators anyway
convertLineSeparators(targetPath.resolve("bin/idea.properties"), "\n")
if (iconPngPath != null) {
Files.copy(iconPngPath, distBinDir.resolve("${context.productProperties.baseFileName}.png"), StandardCopyOption.REPLACE_EXISTING)
}
generateVMOptions(distBinDir)
generateUnixScripts(distBinDir = distBinDir,
os = OsFamily.LINUX,
arch = arch,
context = context)
generateReadme(targetPath)
generateVersionMarker(targetPath, context)
RepairUtilityBuilder.bundle(context = context, os = OsFamily.LINUX, arch = arch, distributionDir = targetPath)
customizer.copyAdditionalFiles(context = context, targetDir = targetPath, arch = arch)
}
}
}
override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
copyFilesForOsDistribution(osAndArchSpecificDistPath, arch)
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
context.executeStep(spanBuilder("build linux .tar.gz").setAttribute("arch", arch.name), BuildOptions.LINUX_ARTIFACTS_STEP) {
if (customizer.buildTarGzWithoutBundledRuntime) {
context.executeStep(spanBuilder("Build Linux .tar.gz without bundled Runtime").setAttribute("arch", arch.name),
BuildOptions.LINUX_TAR_GZ_WITHOUT_BUNDLED_RUNTIME_STEP) {
val tarGzPath = buildTarGz(runtimeDir = null,
unixDistPath = osAndArchSpecificDistPath,
suffix = NO_JBR_SUFFIX + suffix,
arch = arch)
checkExecutablePermissions(tarGzPath, rootDirectoryName, includeRuntime = false)
}
}
if (customizer.buildOnlyBareTarGz) {
return@executeStep
}
val runtimeDir = context.bundledRuntime.extract(getProductPrefix(context), OsFamily.LINUX, arch)
val tarGzPath = buildTarGz(arch = arch, runtimeDir = runtimeDir, unixDistPath = osAndArchSpecificDistPath, suffix = suffix)
checkExecutablePermissions(tarGzPath, rootDirectoryName, includeRuntime = true)
if (arch == JvmArchitecture.x64) {
buildSnapPackage(runtimeDir = runtimeDir, unixDistPath = osAndArchSpecificDistPath, arch = arch)
}
else {
// TODO: Add snap for aarch64
Span.current().addEvent("skip building Snap packages for non-x64 arch")
}
if (!context.options.buildStepsToSkip.contains(BuildOptions.REPAIR_UTILITY_BUNDLE_STEP)) {
val tempTar = Files.createTempDirectory(context.paths.tempDir, "tar-")
try {
ArchiveUtils.unTar(tarGzPath, tempTar)
RepairUtilityBuilder.generateManifest(context = context,
unpackedDistribution = tempTar.resolve(rootDirectoryName),
os = OsFamily.LINUX,
arch = arch)
}
finally {
NioFiles.deleteRecursively(tempTar)
}
}
}
}
private fun generateVMOptions(distBinDir: Path) {
val fileName = "${context.productProperties.baseFileName}64.vmoptions"
@Suppress("SpellCheckingInspection")
val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties) +
listOf("-Dsun.tools.attach.tmp.only=true")
VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\n")
}
private fun generateReadme(unixDistPath: Path) {
val fullName = context.applicationInfo.productName
val sourceFile = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/linux/Install-Linux-tar.txt")
val targetFile = unixDistPath.resolve("Install-Linux-tar.txt")
substituteTemplatePlaceholders(sourceFile, targetFile, "@@", listOf(
Pair("product_full", fullName),
Pair("product", context.productProperties.baseFileName),
Pair("product_vendor", context.applicationInfo.shortCompanyName),
Pair("system_selector", context.systemSelector)
), convertToUnixLineEndings = true)
}
override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> {
var patterns = persistentListOf("bin/*.sh", "plugins/**/*.sh", "bin/*.py", "bin/fsnotifier*")
.addAll(customizer.extraExecutables)
if (includeRuntime) {
patterns = patterns.addAll(context.bundledRuntime.executableFilesPatterns(OsFamily.LINUX))
}
return patterns.addAll(context.getExtraExecutablePattern(OsFamily.LINUX))
}
private val rootDirectoryName: String
get() = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)
private fun buildTarGz(arch: JvmArchitecture, runtimeDir: Path?, unixDistPath: Path, suffix: String): Path {
val tarRoot = rootDirectoryName
val tarName = artifactName(context, suffix)
val tarPath = context.paths.artifactDir.resolve(tarName)
val paths = mutableListOf(context.paths.distAllDir, unixDistPath)
var javaExecutablePath: String? = null
if (runtimeDir != null) {
paths.add(runtimeDir)
javaExecutablePath = "jbr/bin/java"
require(Files.exists(runtimeDir.resolve(javaExecutablePath))) { "$javaExecutablePath was not found under $runtimeDir" }
}
val productJsonDir = context.paths.tempDir.resolve("linux.dist.product-info.json$suffix")
generateProductJson(targetDir = productJsonDir, arch = arch, javaExecutablePath = javaExecutablePath, context = context)
paths.add(productJsonDir)
val executableFilesPatterns = generateExecutableFilesPatterns(runtimeDir != null)
spanBuilder("build Linux tar.gz")
.setAttribute("runtimeDir", runtimeDir?.toString() ?: "")
.useWithScope {
synchronized(context.paths.distAllDir) {
// Sync to prevent concurrent context.paths.distAllDir modification and reading from two Linux builders,
// otherwise tar building may fail due to FS change (changed attributes) while reading a file
for (dir in paths) {
updateExecutablePermissions(dir, executableFilesPatterns)
}
ArchiveUtils.tar(tarPath, tarRoot, paths.map(Path::toString), context.options.buildDateInSeconds)
}
checkInArchive(tarPath, tarRoot, context)
context.notifyArtifactBuilt(tarPath)
}
return tarPath
}
private suspend fun buildSnapPackage(runtimeDir: Path, unixDistPath: Path, arch: JvmArchitecture) {
val snapName = customizer.snapName ?: return
if (!context.options.buildUnixSnaps) {
return
}
val snapDir = context.paths.buildOutputDir.resolve("dist.snap")
spanBuilder("build Linux .snap package")
.setAttribute("snapName", snapName)
.useWithScope { span ->
check(iconPngPath != null) { context.messages.error("'iconPngPath' not set") }
check(!customizer.snapDescription.isNullOrBlank()) { context.messages.error("'snapDescription' not set") }
span.addEvent("prepare files")
val unixSnapDistPath = context.paths.buildOutputDir.resolve("dist.unix.snap")
copyDir(unixDistPath, unixSnapDistPath)
val appInfo = context.applicationInfo
val productName = appInfo.productNameWithEdition
substituteTemplatePlaceholders(
inputFile = context.paths.communityHomeDir.resolve("platform/platform-resources/src/entry.desktop"),
outputFile = snapDir.resolve("$snapName.desktop"),
placeholder = "$",
values = listOf(
Pair("NAME", productName),
Pair("ICON", "\${SNAP}/bin/${context.productProperties.baseFileName}.png"),
Pair("SCRIPT", snapName),
Pair("COMMENT", appInfo.motto!!),
Pair("WM_CLASS", getLinuxFrameClass(context))
)
)
copyFile(iconPngPath, snapDir.resolve("$snapName.png"))
val snapcraftTemplate = context.paths.communityHomeDir.resolve(
"platform/build-scripts/resources/linux/snap/snapcraft-template.yaml")
val versionSuffix = appInfo.versionSuffix?.replace(' ', '-') ?: ""
val version = "${appInfo.majorVersion}.${appInfo.minorVersion}${if (versionSuffix.isEmpty()) "" else "-${versionSuffix}"}"
substituteTemplatePlaceholders(
inputFile = snapcraftTemplate,
outputFile = snapDir.resolve("snapcraft.yaml"),
placeholder = "$",
values = listOf(
Pair("NAME", snapName),
Pair("VERSION", version),
Pair("SUMMARY", productName),
Pair("DESCRIPTION", customizer.snapDescription!!),
Pair("GRADE", if (appInfo.isEAP) "devel" else "stable"),
Pair("SCRIPT", "bin/${context.productProperties.baseFileName}.sh")
)
)
FileSet(unixSnapDistPath)
.include("bin/*.sh")
.include("bin/*.py")
.include("bin/fsnotifier*")
.enumerate().forEach(::makeFileExecutable)
FileSet(runtimeDir)
.include("jbr/bin/*")
.enumerate().forEach(::makeFileExecutable)
if (!customizer.extraExecutables.isEmpty()) {
for (distPath in listOf(unixSnapDistPath, context.paths.distAllDir)) {
val fs = FileSet(distPath)
customizer.extraExecutables.forEach(fs::include)
fs.enumerateNoAssertUnusedPatterns().forEach(::makeFileExecutable)
}
}
validateProductJson(jsonText = generateProductJson(unixSnapDistPath, arch = arch, "jbr/bin/java", context),
relativePathToProductJson = "",
installationDirectories = listOf(context.paths.distAllDir, unixSnapDistPath, runtimeDir),
installationArchives = listOf(),
context = context)
val resultDir = snapDir.resolve("result")
Files.createDirectories(resultDir)
span.addEvent("build package")
val snapArtifact = snapName + "_" + version + "_amd64.snap"
runProcess(
args = listOf(
"docker", "run", "--rm", "--volume=$snapDir/snapcraft.yaml:/build/snapcraft.yaml:ro",
"--volume=$snapDir/$snapName.desktop:/build/snap/gui/$snapName.desktop:ro",
"--volume=$snapDir/$snapName.png:/build/prime/meta/gui/icon.png:ro",
"--volume=$snapDir/result:/build/result",
"--volume=${context.paths.getDistAll()}:/build/dist.all:ro",
"--volume=$unixSnapDistPath:/build/dist.unix:ro",
"--volume=$runtimeDir:/build/jre:ro",
"--workdir=/build",
context.options.snapDockerImage,
"snapcraft",
"snap", "-o", "result/$snapArtifact"
),
workingDir = snapDir,
timeout = context.options.snapDockerBuildTimeoutMin.minutes,
)
moveFileToDir(resultDir.resolve(snapArtifact), context.paths.artifactDir)
context.notifyArtifactWasBuilt(context.paths.artifactDir.resolve(snapArtifact))
}
}
}
private const val NO_JBR_SUFFIX = "-no-jbr"
private fun generateProductJson(targetDir: Path, arch: JvmArchitecture, javaExecutablePath: String?, context: BuildContext): String {
val scriptName = context.productProperties.baseFileName
val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME)
Files.createDirectories(targetDir)
val json = generateMultiPlatformProductJson(
relativePathToBin = "bin",
builtinModules = context.builtinModule,
launch = listOf(ProductInfoLaunchData(
os = OsFamily.LINUX.osName,
arch = arch.dirName,
launcherPath = "bin/$scriptName.sh",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "bin/" + scriptName + "64.vmoptions",
startupWmClass = getLinuxFrameClass(context),
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.LINUX, arch))),
context = context
)
Files.writeString(file, json)
return json
}
private fun generateVersionMarker(unixDistPath: Path, context: BuildContext) {
val targetDir = unixDistPath.resolve("lib")
Files.createDirectories(targetDir)
Files.writeString(targetDir.resolve("build-marker-" + context.fullBuildNumber), context.fullBuildNumber)
}
private fun artifactName(buildContext: BuildContext, suffix: String?): String {
val baseName = buildContext.productProperties.getBaseArtifactName(buildContext.applicationInfo, buildContext.buildNumber)
return "$baseName$suffix.tar.gz"
}
private fun makeFileExecutable(file: Path) {
Span.current().addEvent("set file permission to 0755", Attributes.of(AttributeKey.stringKey("file"), file.toString()))
@Suppress("SpellCheckingInspection")
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rwxr-xr-x"))
}
internal const val REMOTE_DEV_SCRIPT_FILE_NAME = "remote-dev-server.sh"
internal fun generateUnixScripts(distBinDir: Path,
os: OsFamily,
arch: JvmArchitecture,
context: BuildContext) {
val classPathJars = context.bootClassPathJarNames
var classPath = "CLASS_PATH=\"\$IDE_HOME/lib/${classPathJars[0]}\""
for (i in 1 until classPathJars.size) {
classPath += "\nCLASS_PATH=\"\$CLASS_PATH:\$IDE_HOME/lib/${classPathJars[i]}\""
}
val additionalJvmArguments = context.getAdditionalJvmArguments(os = os, arch = arch, isScript = true).toMutableList()
if (!context.xBootClassPathJarNames.isEmpty()) {
val bootCp = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$IDE_HOME/lib/${it}" }
additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"")
}
val additionalJvmArgs = additionalJvmArguments.joinToString(separator = " ")
val baseName = context.productProperties.baseFileName
val vmOptionsPath = when (os) {
OsFamily.LINUX -> distBinDir.resolve("${baseName}64.vmoptions")
OsFamily.MACOS -> distBinDir.resolve("${baseName}.vmoptions")
else -> throw IllegalStateException("Unknown OsFamily")
}
val defaultXmxParameter = try {
Files.readAllLines(vmOptionsPath).firstOrNull { it.startsWith("-Xmx") }
}
catch (e: NoSuchFileException) {
throw IllegalStateException("File '$vmOptionsPath' should be already generated at this point", e)
} ?: throw IllegalStateException("-Xmx was not found in '$vmOptionsPath'")
val isRemoteDevEnabled = context.productProperties.productLayout.bundledPluginModules.contains("intellij.remoteDevServer")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/linux/scripts")
when (os) {
OsFamily.LINUX -> {
val scriptName = "$baseName.sh"
Files.newDirectoryStream(sourceScriptDir).use {
for (file in it) {
val fileName = file.fileName.toString()
if (!isRemoteDevEnabled && fileName == REMOTE_DEV_SCRIPT_FILE_NAME) {
continue
}
val target = distBinDir.resolve(if (fileName == "executable-template.sh") scriptName else fileName)
copyScript(sourceFile = file,
targetFile = target,
vmOptionsFileName = baseName,
additionalJvmArgs = additionalJvmArgs,
defaultXmxParameter = defaultXmxParameter,
classPath = classPath,
scriptName = scriptName,
context = context)
}
}
copyInspectScript(context, distBinDir)
}
OsFamily.MACOS -> {
copyScript(sourceFile = sourceScriptDir.resolve(REMOTE_DEV_SCRIPT_FILE_NAME),
targetFile = distBinDir.resolve(REMOTE_DEV_SCRIPT_FILE_NAME),
vmOptionsFileName = baseName,
additionalJvmArgs = additionalJvmArgs,
defaultXmxParameter = defaultXmxParameter,
classPath = classPath,
scriptName = baseName,
context = context)
}
else -> {
throw IllegalStateException("Unsupported OsFamily: $os")
}
}
}
private fun copyScript(sourceFile: Path,
targetFile: Path,
vmOptionsFileName: String,
additionalJvmArgs: String,
defaultXmxParameter: String,
classPath: String,
scriptName: String,
context: BuildContext) {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
substituteTemplatePlaceholders(
inputFile = sourceFile,
outputFile = targetFile,
placeholder = "__",
values = listOf(
Pair("product_full", context.applicationInfo.productName),
Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)),
Pair("product_vendor", context.applicationInfo.shortCompanyName),
Pair("product_code", context.applicationInfo.productCode),
Pair("vm_options", vmOptionsFileName),
Pair("system_selector", context.systemSelector),
Pair("ide_jvm_args", additionalJvmArgs),
Pair("ide_default_xmx", defaultXmxParameter.trim()),
Pair("class_path", classPath),
Pair("script_name", scriptName),
Pair("main_class_name", context.productProperties.mainClassName),
),
mustUseAllPlaceholders = false,
convertToUnixLineEndings = true,
)
}
| apache-2.0 | 9025e403af7d5585b5d6b66b5d18797a | 46.777778 | 144 | 0.676114 | 4.879433 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/livedata/ArticleActivity.kt | 1 | 4396 | package com.zhou.android.livedata
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.zhou.android.R
import com.zhou.android.R.layout.listformat_article_item
import com.zhou.android.common.BaseActivity
import com.zhou.android.common.CommonRecyclerAdapter
import com.zhou.android.common.PaddingItemDecoration
import com.zhou.android.common.toast
import kotlinx.android.synthetic.main.activity_article.*
/**
* Created by mxz on 2020/5/22.
*/
class ArticleActivity : BaseActivity() {
private val tag = "article"
private val ArticleCode = 100
private lateinit var model: ArticleModel
private val data = ArrayList<Article>()
override fun setContentView() {
setContentView(R.layout.activity_article)
}
override fun addListener() {
}
override fun init() {
model = ViewModelProviders.of(this).get(ArticleModel::class.java)
model.liveData.observe(this, Observer {
Log.i(tag, "on change >> ${it?.size}")
if (it != null) {
data.clear()
data.addAll(it)
articleRecycler.adapter.notifyDataSetChanged()
}
})
val articleAdapter = object : CommonRecyclerAdapter<Article, CommonRecyclerAdapter.ViewHolder>(this, data) {
override fun onBind(holder: ViewHolder, item: Article, pos: Int) {
val image = holder.getView<ImageView>(R.id.imageCover)
if (item.image.isNullOrEmpty()) {
image.visibility = View.GONE
} else {
image.visibility = View.VISIBLE
Glide.with(this@ArticleActivity)
.load(item.image)
.centerCrop()
.into(image)
}
holder.getView<TextView>(R.id.tvTitle).text = item.title
holder.getView<TextView>(R.id.tvContent).text = item.content
holder.getView<View>(R.id.layout).setOnClickListener {
startActivityForResult(Intent(this@ArticleActivity, ArticleDetailActivity::class.java).apply {
putExtra("Article", item)
putExtra("index", pos)
}, ArticleCode)
}
}
override fun getViewHolder(context: Context, parent: ViewGroup, viewType: Int): ViewHolder {
val view = layoutInflater.inflate(listformat_article_item, parent, false)
return ViewHolder(view)
}
}
articleRecycler.apply {
adapter = articleAdapter
layoutManager = LinearLayoutManager(this@ArticleActivity, LinearLayoutManager.VERTICAL, false)
addItemDecoration(PaddingItemDecoration(this@ArticleActivity, 8, 8, 8, 0))
}
LiveEventBus.getChannel("test", String::class.java).observe(this, Observer { value ->
toast(value!!)
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_bluetooth, menu)
menu?.findItem(R.id.menu_status)?.title = "测试Bus"
return true
// return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_status) {
startActivity(Intent(this, LDBusActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (ArticleCode == requestCode && Activity.RESULT_OK == resultCode) {
val article = data?.getParcelableExtra<Article>("Article")
val pos = data?.getIntExtra("index", -1) ?: -1
if (pos != -1) {
model.updateArticle(article, pos)
}
} else
super.onActivityResult(requestCode, resultCode, data)
}
} | mit | 2e807c2d9b3e6084e7efd6cc93c175d7 | 35.008197 | 116 | 0.625 | 4.742981 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/text/regex/sets/AbstractSet.kt | 2 | 6632 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
/*
* 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 kotlin.text.regex
import kotlin.AssertionError
/** Basic class for sets which have no complex next node handling. */
internal abstract class SimpleSet : AbstractSet {
override var next: AbstractSet = dummyNext
constructor()
constructor(type : Int): super(type)
}
/**
* Basic class for nodes, representing given regular expression.
* Note: (Almost) All the classes representing nodes has 'set' suffix.
*/
internal abstract class AbstractSet(val type: Int = 0) {
companion object {
const val TYPE_LEAF = 1 shl 0
const val TYPE_FSET = 1 shl 1
const val TYPE_QUANT = 1 shl 3
const val TYPE_DOTSET = 0x80000000.toInt() or '.'.toInt()
val dummyNext = object : AbstractSet() {
override var next: AbstractSet
get() = throw AssertionError("This method is not expected to be called.")
@Suppress("UNUSED_PARAMETER")
set(value) {}
override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl) =
throw AssertionError("This method is not expected to be called.")
override fun hasConsumed(matchResult: MatchResultImpl): Boolean =
throw AssertionError("This method is not expected to be called.")
override fun processSecondPassInternal(): AbstractSet = this
override fun processSecondPass(): AbstractSet = this
}
}
var secondPassVisited = false
abstract var next: AbstractSet
protected open val name: String
get() = ""
/**
* Checks if this node matches in given position and recursively call
* next node matches on positive self match. Returns positive integer if
* entire match succeed, negative otherwise.
* @param startIndex - string index to start from.
* @param testString - input string.
* @param matchResult - MatchResult to sore result into.
* @return -1 if match fails or n > 0;
*/
abstract fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int
/**
* Attempts to apply pattern starting from this set/startIndex; returns
* index this search was started from, if value is negative, this means that
* this search didn't succeed, additional information could be obtained via
* matchResult.
*
* Note: this is default implementation for find method, it's based on
* matches, subclasses do not have to override find method unless
* more effective find method exists for a particular node type
* (sequence, i.e. substring, for example). Same applies for find back
* method.
*
* @param startIndex - starting index.
* @param testString - string to search in.
* @param matchResult - result of the match.
* @return last searched index.
*/
open fun find(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int
= (startIndex..testString.length).firstOrNull { index -> matches(index, testString, matchResult) >= 0 }
?: -1
/**
* @param leftLimit - an index, to finish search back (left limit, inclusive).
* @param rightLimit - an index to start search from (right limit, exclusive).
* @param testString - test string.
* @param matchResult - match result.
* @return an index to start back search next time if this search fails(new left bound);
* if this search fails the value is negative.
*/
open fun findBack(leftLimit: Int, rightLimit: Int, testString: CharSequence, matchResult: MatchResultImpl): Int
= (rightLimit downTo leftLimit).firstOrNull { index -> matches(index, testString, matchResult) >= 0 }
?: -1
/**
* Returns true, if this node has consumed any characters during
* positive match attempt, for example node representing character always
* consumes one character if it matches. If particular node matches
* empty sting this method will return false.
*
* @param matchResult - match result;
* @return true if the node consumes any character and false otherwise.
*/
abstract fun hasConsumed(matchResult: MatchResultImpl): Boolean
/**
* Returns true if the given node intersects with this one, false otherwise.
* This method is being used for quantifiers construction, lets consider the
* following regular expression (a|b)*ccc. (a|b) does not intersects with "ccc"
* and thus can be quantified greedily (w/o kickbacks), like *+ instead of *.
* @param set - A node the intersection is checked for. Usually a previous node.
* @return true if the given node intersects with this one, false otherwise.
*/
open fun first(set: AbstractSet): Boolean = true
/**
* This method is used for replacement backreferenced sets.
*
* @return null if current node need not to be replaced,
* [JointSet] which is replacement of current node otherwise.
*/
open fun processBackRefReplacement(): JointSet? {
return null
}
/**
* This method performs the second pass without checking if it's already performed or not.
*/
protected open fun processSecondPassInternal(): AbstractSet {
if (!next.secondPassVisited) {
this.next = next.processSecondPass()
}
return processBackRefReplacement() ?: this
}
/**
* This method is used for traversing nodes after the first stage of compilation.
*/
open fun processSecondPass(): AbstractSet {
secondPassVisited = true
return processSecondPassInternal()
}
} | apache-2.0 | 9d3a5c58bfb2bd327204947acc2e41a4 | 40.716981 | 115 | 0.677171 | 4.713575 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/moveConflictUtils.kt | 1 | 45351 | // 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.refactoring.move.moveDeclarations
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.module.impl.scopes.JdkScope
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.ClassInheritorsSearch.SearchParameters
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewTypeLocation
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.backend.common.serialization.findPackage
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfoByVirtualFile
import org.jetbrains.kotlin.idea.caches.project.implementedModules
import org.jetbrains.kotlin.idea.caches.resolve.*
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.hasJavaResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.javaResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.resolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.forcedTargetPlatform
import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.refactoring.getUsageContext
import org.jetbrains.kotlin.idea.refactoring.move.KotlinMoveUsage
import org.jetbrains.kotlin.idea.refactoring.pullUp.renderForConflicts
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.search.and
import org.jetbrains.kotlin.idea.search.not
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.projectStructure.getModule
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.ClassifierNamePolicy
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.descriptors.findPackageFragmentForFile
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.util.isJavaDescriptor
import org.jetbrains.kotlin.util.supertypesWithAny
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class MoveConflictChecker(
private val project: Project,
private val elementsToMove: Collection<KtElement>,
private val moveTarget: KotlinMoveTarget,
contextElement: KtElement,
doNotGoIn: Collection<KtElement> = emptySet(),
allElementsToMove: Collection<PsiElement>? = null
) {
private val doNotGoIn: Set<KtElement> by lazy { doNotGoIn.toSet() }
private val resolutionFacade = contextElement.getResolutionFacade()
private val fakeFile = KtPsiFactory(project).createFile("")
private val allElementsToMove = allElementsToMove ?: elementsToMove
private fun PackageFragmentDescriptor.withSource(sourceFile: KtFile): PackageFragmentDescriptor {
return object : PackageFragmentDescriptor by this {
override fun getOriginal() = this
override fun getSource() = KotlinSourceElement(sourceFile)
}
}
private fun getModuleDescriptor(sourceFile: VirtualFile) =
getModuleInfoByVirtualFile(
project,
sourceFile
)?.let { resolutionFacade.findModuleDescriptor(it) }
private fun KotlinMoveTarget.getContainerDescriptor(): DeclarationDescriptor? {
return when (this) {
is KotlinMoveTargetForExistingElement -> when (val targetElement = targetElement) {
is KtNamedDeclaration -> resolutionFacade.resolveToDescriptor(targetElement)
is KtFile -> {
val packageFragment =
targetElement
.findModuleDescriptor()
.findPackageFragmentForFile(targetElement)
packageFragment?.withSource(targetElement)
}
else -> null
}
is KotlinDirectoryMoveTarget, is KotlinMoveTargetForDeferredFile -> {
val packageFqName = targetContainerFqName ?: return null
val targetModuleDescriptor = targetFileOrDir?.let { getModuleDescriptor(it) ?: return null }
?: resolutionFacade.moduleDescriptor
MutablePackageFragmentDescriptor(targetModuleDescriptor, packageFqName).withSource(fakeFile)
}
else -> null
}
}
private fun DeclarationDescriptor.isVisibleIn(where: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings): Boolean {
return when {
this !is DeclarationDescriptorWithVisibility -> true
!DescriptorVisibilityUtils.isVisibleIgnoringReceiver(this, where, languageVersionSettings) -> false
this is ConstructorDescriptor -> DescriptorVisibilityUtils.isVisibleIgnoringReceiver(containingDeclaration, where, languageVersionSettings)
else -> true
}
}
private fun DeclarationDescriptor.wrap(
newContainer: DeclarationDescriptor? = null,
newVisibility: DescriptorVisibility? = null
): DeclarationDescriptor? {
if (newContainer == null && newVisibility == null) return this
return when (val wrappedDescriptor = this) {
// We rely on visibility not depending on more specific type of CallableMemberDescriptor
is CallableMemberDescriptor -> object : CallableMemberDescriptor by wrappedDescriptor {
override fun getOriginal() = this
override fun getContainingDeclaration() = newContainer ?: wrappedDescriptor.containingDeclaration
override fun getVisibility(): DescriptorVisibility = newVisibility ?: wrappedDescriptor.visibility
override fun getSource() =
newContainer?.let { SourceElement { DescriptorUtils.getContainingSourceFile(it) } } ?: wrappedDescriptor.source
}
is ClassDescriptor -> object : ClassDescriptor by wrappedDescriptor {
override fun getOriginal() = this
override fun getContainingDeclaration() = newContainer ?: wrappedDescriptor.containingDeclaration
override fun getVisibility(): DescriptorVisibility = newVisibility ?: wrappedDescriptor.visibility
override fun getSource() =
newContainer?.let { SourceElement { DescriptorUtils.getContainingSourceFile(it) } } ?: wrappedDescriptor.source
}
else -> null
}
}
private fun DeclarationDescriptor.asPredicted(
newContainer: DeclarationDescriptor,
actualVisibility: DescriptorVisibility?
): DeclarationDescriptor? {
val visibility = actualVisibility ?: (this as? DeclarationDescriptorWithVisibility)?.visibility ?: return null
val adjustedVisibility = if (visibility == DescriptorVisibilities.PROTECTED && newContainer is PackageFragmentDescriptor) {
DescriptorVisibilities.PUBLIC
} else {
visibility
}
return wrap(newContainer, adjustedVisibility)
}
private fun DeclarationDescriptor.visibilityAsViewedFromJava(): DescriptorVisibility? {
if (this !is DeclarationDescriptorWithVisibility) return null
return when (visibility) {
DescriptorVisibilities.PRIVATE -> {
if (this is ClassDescriptor && DescriptorUtils.isTopLevelDeclaration(this)) JavaDescriptorVisibilities.PACKAGE_VISIBILITY else null
}
DescriptorVisibilities.PROTECTED -> JavaDescriptorVisibilities.PROTECTED_AND_PACKAGE
else -> null
}
}
private fun render(declaration: PsiElement) = RefactoringUIUtil.getDescription(declaration, false)
private fun render(descriptor: DeclarationDescriptor) = CommonRefactoringUtil.htmlEmphasize(descriptor.renderForConflicts())
// Based on RefactoringConflictsUtil.analyzeModuleConflicts
private fun analyzeModuleConflictsInUsages(
project: Project,
usages: Collection<UsageInfo>,
targetScope: VirtualFile,
conflicts: MultiMap<PsiElement, String>
) {
val targetModule = targetScope.getModule(project) ?: return
val isInTestSources = ModuleRootManager.getInstance(targetModule).fileIndex.isInTestSourceContentKotlinAware(targetScope)
NextUsage@ for (usage in usages) {
val element = usage.element ?: continue
if (PsiTreeUtil.getParentOfType(element, PsiImportStatement::class.java, false) != null) continue
if (isToBeMoved(element)) continue@NextUsage
val resolveScope = element.resolveScope
if (resolveScope.isSearchInModuleContent(targetModule, isInTestSources)) continue
val usageModule = element.module ?: continue
val scopeDescription = RefactoringUIUtil.getDescription(element.getUsageContext(), true)
val referencedElement = (if (usage is MoveRenameUsageInfo) usage.referencedElement else usage.element) ?: error(usage)
val message = if (usageModule == targetModule && isInTestSources) {
RefactoringBundle.message(
"0.referenced.in.1.will.not.be.accessible.from.production.of.module.2",
RefactoringUIUtil.getDescription(referencedElement, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(usageModule.name)
)
} else {
RefactoringBundle.message(
"0.referenced.in.1.will.not.be.accessible.from.module.2",
RefactoringUIUtil.getDescription(referencedElement, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(usageModule.name)
)
}
conflicts.putValue(referencedElement, StringUtil.capitalize(message))
}
}
private fun checkModuleConflictsInUsages(externalUsages: MutableSet<UsageInfo>, conflicts: MultiMap<PsiElement, String>) {
val newConflicts = MultiMap<PsiElement, String>()
val targetScope = moveTarget.targetFileOrDir ?: return
analyzeModuleConflictsInUsages(project, externalUsages, targetScope, newConflicts)
if (!newConflicts.isEmpty) {
val referencedElementsToSkip = newConflicts.keySet().mapNotNullTo(HashSet()) { it.namedUnwrappedElement }
externalUsages.removeIf {
it is MoveRenameUsageInfo &&
it.referencedElement?.namedUnwrappedElement?.let { element -> element in referencedElementsToSkip } ?: false
}
conflicts.putAllValues(newConflicts)
}
}
companion object {
private val DESCRIPTOR_RENDERER_FOR_COMPARISON = DescriptorRenderer.withOptions {
withDefinedIn = true
classifierNamePolicy = ClassifierNamePolicy.FULLY_QUALIFIED
modifiers = emptySet()
withoutTypeParameters = true
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
includeAdditionalModifiers = false
renderUnabbreviatedType = false
withoutSuperTypes = true
}
}
private fun Module.getScopeWithPlatformAwareDependencies(): SearchScope {
val baseScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(this)
val targetPlatform = TargetPlatformDetector.getPlatform(this)
if (targetPlatform.isJvm()) return baseScope
return ModuleRootManager.getInstance(this)
.orderEntries
.filterIsInstance<JdkOrderEntry>()
.fold(baseScope as SearchScope) { scope, jdkEntry -> scope and !JdkScope(project, jdkEntry) }
}
@OptIn(ExperimentalMultiplatform::class)
fun checkModuleConflictsInDeclarations(
internalUsages: MutableSet<UsageInfo>,
conflicts: MultiMap<PsiElement, String>
) {
val targetScope = moveTarget.targetFileOrDir ?: return
val targetModule = targetScope.getModule(project) ?: return
val resolveScope = targetModule.getScopeWithPlatformAwareDependencies()
fun isInScope(targetElement: PsiElement, targetDescriptor: DeclarationDescriptor): Boolean {
if (targetElement in resolveScope) return true
if (targetElement.manager.isInProject(targetElement)) return false
val fqName = targetDescriptor.importableFqName ?: return true
val importableDescriptor = targetDescriptor.getImportableDescriptor()
val targetModuleInfo = getModuleInfoByVirtualFile(project, targetScope)
val dummyFile = KtPsiFactory(targetElement.project).createFile("dummy.kt", "").apply {
forcedModuleInfo = targetModuleInfo
forcedTargetPlatform = TargetPlatformDetector.getPlatform(targetModule)
}
val newTargetDescriptors = dummyFile.resolveImportReference(fqName)
if (
newTargetDescriptors.any { descriptor ->
descriptor is MemberDescriptor && descriptor.isExpect &&
descriptor.annotations.any { OptionalExpectation::class.qualifiedName!! == it.fqName?.asString() }
}
) {
return false
}
if (importableDescriptor is TypeAliasDescriptor
&& newTargetDescriptors.any {
it is ClassDescriptor && it.isExpect && it.importableFqName == importableDescriptor.importableFqName
}
) return true
val renderedImportableTarget = DESCRIPTOR_RENDERER_FOR_COMPARISON.render(importableDescriptor)
val renderedTarget by lazy { DESCRIPTOR_RENDERER_FOR_COMPARISON.render(targetDescriptor) }
return newTargetDescriptors.any { descriptor ->
if (DESCRIPTOR_RENDERER_FOR_COMPARISON.render(descriptor) != renderedImportableTarget) return@any false
if (importableDescriptor == targetDescriptor) return@any true
val candidateDescriptors: Collection<DeclarationDescriptor> = when (targetDescriptor) {
is ConstructorDescriptor -> {
(descriptor as? ClassDescriptor)?.constructors ?: emptyList()
}
is PropertyAccessorDescriptor -> {
(descriptor as? PropertyDescriptor)
?.let { if (targetDescriptor is PropertyGetterDescriptor) it.getter else it.setter }
?.let { listOf(it) }
?: emptyList()
}
else -> emptyList()
}
candidateDescriptors.any { DESCRIPTOR_RENDERER_FOR_COMPARISON.render(it) == renderedTarget }
}
}
val referencesToSkip = HashSet<KtReferenceExpression>()
for (declaration in elementsToMove - doNotGoIn) {
if (declaration.module == targetModule) continue
declaration.forEachDescendantOfType<KtReferenceExpression> { refExpr ->
// NB: for unknown reason, refExpr.resolveToCall() does not work here
val targetDescriptor =
refExpr.analyze(BodyResolveMode.PARTIAL)[BindingContext.REFERENCE_TARGET, refExpr] ?: return@forEachDescendantOfType
if (KotlinBuiltIns.isBuiltIn(targetDescriptor)) return@forEachDescendantOfType
val target = DescriptorToSourceUtilsIde.getAnyDeclaration(project, targetDescriptor) ?: return@forEachDescendantOfType
if (isToBeMoved(target)) return@forEachDescendantOfType
if (isInScope(target, targetDescriptor)) return@forEachDescendantOfType
if (target is KtTypeParameter) return@forEachDescendantOfType
val superMethods = SmartSet.create<PsiMethod>()
target.toLightMethods().forEach { superMethods += it.findDeepestSuperMethods() }
if (superMethods.any { isInScope(it, targetDescriptor) }) return@forEachDescendantOfType
val refContainer = refExpr.getStrictParentOfType<KtNamedDeclaration>() ?: return@forEachDescendantOfType
val scopeDescription = RefactoringUIUtil.getDescription(refContainer, true)
val message = RefactoringBundle.message(
"0.referenced.in.1.will.not.be.accessible.in.module.2",
RefactoringUIUtil.getDescription(target, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(targetModule.name)
)
conflicts.putValue(target, StringUtil.capitalize(message))
referencesToSkip += refExpr
}
}
internalUsages.removeIf { it.reference?.element?.let { element -> element in referencesToSkip } ?: false }
}
private fun checkVisibilityInUsages(usages: Collection<UsageInfo>, conflicts: MultiMap<PsiElement, String>) {
val declarationToContainers = HashMap<KtNamedDeclaration, MutableSet<PsiElement>>()
for (usage in usages) {
val element = usage.element
if (element == null || usage !is MoveRenameUsageInfo || usage is NonCodeUsageInfo) continue
if (isToBeMoved(element)) continue
val referencedElement = usage.referencedElement?.namedUnwrappedElement as? KtNamedDeclaration ?: continue
val referencedDescriptor = resolutionFacade.resolveToDescriptor(referencedElement)
if (referencedDescriptor is DeclarationDescriptorWithVisibility
&& referencedDescriptor.visibility == DescriptorVisibilities.PUBLIC
&& moveTarget is KotlinMoveTargetForExistingElement
&& moveTarget.targetElement.parentsWithSelf.filterIsInstance<KtClassOrObject>().all { it.isPublic }
) continue
val container = element.getUsageContext()
if (!declarationToContainers.getOrPut(referencedElement) { HashSet() }.add(container)) continue
val targetContainer = moveTarget.getContainerDescriptor() ?: continue
val referencingDescriptor = when (container) {
is KtDeclaration -> container.resolveToDescriptorIfAny()
is PsiMember -> container.getJavaMemberDescriptor()
else -> null
} ?: continue
val languageVersionSettings = referencedElement.getResolutionFacade().languageVersionSettings
val actualVisibility = if (referencingDescriptor.isJavaDescriptor) referencedDescriptor.visibilityAsViewedFromJava() else null
val originalDescriptorToCheck = referencedDescriptor.wrap(newVisibility = actualVisibility) ?: referencedDescriptor
val newDescriptorToCheck = referencedDescriptor.asPredicted(targetContainer, actualVisibility) ?: continue
if (originalDescriptorToCheck.isVisibleIn(referencingDescriptor, languageVersionSettings) && !newDescriptorToCheck.isVisibleIn(referencingDescriptor, languageVersionSettings)) {
val message = KotlinBundle.message(
"text.0.uses.1.which.will.be.inaccessible.after.move",
render(container),
render(referencedElement)
)
conflicts.putValue(element, message.capitalize())
}
}
}
fun checkVisibilityInDeclarations(conflicts: MultiMap<PsiElement, String>) {
val targetContainer = moveTarget.getContainerDescriptor() ?: return
fun DeclarationDescriptor.targetAwareContainingDescriptor(): DeclarationDescriptor? {
val defaultContainer = containingDeclaration
val psi = (this as? DeclarationDescriptorWithSource)?.source?.getPsi()
return if (psi != null && psi in allElementsToMove) targetContainer else defaultContainer
}
fun DeclarationDescriptor.targetAwareContainers(): Sequence<DeclarationDescriptor> {
return generateSequence(this) { it.targetAwareContainingDescriptor() }.drop(1)
}
fun DeclarationDescriptor.targetAwareContainingClass(): ClassDescriptor? {
return targetAwareContainers().firstIsInstanceOrNull()
}
fun DeclarationDescriptorWithVisibility.isProtectedVisible(referrerDescriptor: DeclarationDescriptor): Boolean {
val givenClassDescriptor = targetAwareContainingClass()
val referrerClassDescriptor = referrerDescriptor.targetAwareContainingClass() ?: return false
if (givenClassDescriptor != null && givenClassDescriptor.isCompanionObject) {
val companionOwner = givenClassDescriptor.targetAwareContainingClass()
if (companionOwner != null && referrerClassDescriptor.isSubclassOf(companionOwner)) return true
}
val whatDeclaration = DescriptorUtils.unwrapFakeOverrideToAnyDeclaration(this)
val classDescriptor = whatDeclaration.targetAwareContainingClass() ?: return false
if (referrerClassDescriptor.isSubclassOf(classDescriptor)) return true
return referrerDescriptor.targetAwareContainingDescriptor()?.let { isProtectedVisible(it) } ?: false
}
fun DeclarationDescriptorWithVisibility.isVisibleFrom(ref: PsiReference, languageVersionSettings: LanguageVersionSettings): Boolean {
val targetVisibility = visibility.normalize()
if (targetVisibility == DescriptorVisibilities.PUBLIC) return true
val refElement = ref.element
val referrer = refElement.getStrictParentOfType<KtNamedDeclaration>()
var referrerDescriptor = referrer?.resolveToDescriptorIfAny() ?: return true
if (referrerDescriptor is ClassDescriptor && refElement.getParentOfTypeAndBranch<KtSuperTypeListEntry> { typeReference } != null) {
referrerDescriptor.unsubstitutedPrimaryConstructor?.let { referrerDescriptor = it }
}
if (!isVisibleIn(referrerDescriptor, languageVersionSettings)) return true
return when (targetVisibility) {
DescriptorVisibilities.PROTECTED -> isProtectedVisible(referrerDescriptor)
else -> isVisibleIn(targetContainer, languageVersionSettings)
}
}
for (declaration in elementsToMove - doNotGoIn) {
val languageVersionSettings = declaration.getResolutionFacade().languageVersionSettings
declaration.forEachDescendantOfType<KtReferenceExpression> { refExpr ->
refExpr.references.forEach { ref ->
val target = ref.resolve() ?: return@forEach
if (isToBeMoved(target)) return@forEach
val targetDescriptor = when {
target is KtDeclaration -> target.resolveToDescriptorIfAny()
target is PsiMember && target.hasJavaResolutionFacade() -> target.getJavaMemberDescriptor()
else -> null
} as? DeclarationDescriptorWithVisibility ?: return@forEach
var isVisible = targetDescriptor.isVisibleFrom(ref, languageVersionSettings)
if (isVisible && targetDescriptor is ConstructorDescriptor) {
isVisible = targetDescriptor.containingDeclaration.isVisibleFrom(ref, languageVersionSettings)
}
if (!isVisible) {
val message = KotlinBundle.message(
"text.0.uses.1.which.will.be.inaccessible.after.move",
render(declaration),
render(target)
)
conflicts.putValue(refExpr, message.replaceFirstChar(Char::uppercaseChar))
}
}
}
}
}
private fun isToBeMoved(element: PsiElement): Boolean = allElementsToMove.any { it.isAncestor(element, false) }
private fun checkInternalMemberUsages(conflicts: MultiMap<PsiElement, String>) {
val targetModule = moveTarget.getTargetModule(project) ?: return
val membersToCheck = LinkedHashSet<KtDeclaration>()
val memberCollector = object : KtVisitorVoid() {
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
val declarations = classOrObject.declarations
declarations.filterTo(membersToCheck) { it.hasModifier(KtTokens.INTERNAL_KEYWORD) }
declarations.forEach { it.accept(this) }
}
}
elementsToMove.forEach { it.accept(memberCollector) }
for (memberToCheck in membersToCheck) {
for (reference in ReferencesSearch.search(memberToCheck)) {
val element = reference.element
val usageModule = ModuleUtilCore.findModuleForPsiElement(element) ?: continue
if (usageModule != targetModule && targetModule !in usageModule.implementedModules && !isToBeMoved(element)) {
val container = element.getUsageContext()
val message = KotlinBundle.message(
"text.0.uses.internal.1.which.will.be.inaccessible.after.move",
render(container),
render(memberToCheck)
)
conflicts.putValue(element, message.capitalize())
}
}
}
}
private fun checkSealedClassMove(conflicts: MultiMap<PsiElement, String>) {
val sealedInheritanceRulesRelaxed =
project.getLanguageVersionSettings().supportsFeature(LanguageFeature.AllowSealedInheritorsInDifferentFilesOfSamePackage)
if (sealedInheritanceRulesRelaxed)
checkSealedClassMoveWithinPackageAndModule(conflicts)
else
checkSealedClassMoveWithinFile(conflicts)
}
private fun checkSealedClassMoveWithinFile(conflicts: MultiMap<PsiElement, String>) {
val visited = HashSet<PsiElement>()
for (elementToMove in elementsToMove) {
if (!visited.add(elementToMove)) continue
if (elementToMove !is KtClassOrObject) continue
val rootClass: KtClass
val rootClassDescriptor: ClassDescriptor
if (elementToMove is KtClass && elementToMove.isSealed()) {
rootClass = elementToMove
rootClassDescriptor = rootClass.resolveToDescriptorIfAny() ?: return
} else {
val classDescriptor = elementToMove.resolveToDescriptorIfAny() ?: return
val superClassDescriptor = classDescriptor.getSuperClassNotAny() ?: return
if (superClassDescriptor.modality != Modality.SEALED) return
rootClassDescriptor = superClassDescriptor
rootClass = rootClassDescriptor.source.getPsi() as? KtClass ?: return
}
val subclasses = rootClassDescriptor.sealedSubclasses.mapNotNull { it.source.getPsi() }
if (subclasses.isEmpty()) continue
visited.add(rootClass)
visited.addAll(subclasses)
if (isToBeMoved(rootClass) && subclasses.all { isToBeMoved(it) }) continue
val message = if (elementToMove == rootClass) {
KotlinBundle.message("text.sealed.class.0.must.be.moved.with.all.its.subclasses", rootClass.name.toString())
} else {
val type = ElementDescriptionUtil.getElementDescription(elementToMove, UsageViewTypeLocation.INSTANCE).capitalize()
KotlinBundle.message(
"text.0.1.must.be.moved.with.sealed.parent.class.and.all.its.subclasses",
type,
rootClass.name.toString()
)
}
conflicts.putValue(elementToMove, message)
}
}
private fun checkSealedClassMoveWithinPackageAndModule(conflicts: MultiMap<PsiElement, String>) {
val hierarchyChecker = SealedHierarchyChecker()
for (elementToMove in elementsToMove) {
if (elementToMove !is KtClassOrObject) continue
hierarchyChecker.reportIfMoveIsDestructive(elementToMove)?.let { conflicts.putValue(elementToMove, it) }
}
}
private fun checkNameClashes(conflicts: MultiMap<PsiElement, String>) {
fun <T> equivalent(a: T, b: T): Boolean = when (a) {
is DeclarationDescriptor -> when (a) {
is FunctionDescriptor -> b is FunctionDescriptor
&& equivalent(a.name, b.name) && a.valueParameters.zip(b.valueParameters).all { equivalent(it.first, it.second) }
is ValueParameterDescriptor -> b is ValueParameterDescriptor
&& equivalent(a.type, b.type)
else -> b is DeclarationDescriptor && equivalent(a.name, b.name)
}
is Name -> b is Name && a.asString() == b.asString()
is FqName -> b is FqName && a.asString() == b.asString()
is KotlinType -> {
if (b !is KotlinType) false
else {
val aSupertypes = a.constructor.supertypesWithAny()
val bSupertypes = b.constructor.supertypesWithAny()
when {
a.isAnyOrNullableAny() && b.isAnyOrNullableAny() -> // a = T(?) | Any(?), b = T(?) | Any(?)
true // => 100% clash
aSupertypes.size == 1 && bSupertypes.size == 1 -> // a = T: T1, b = T: T2
equivalent(aSupertypes.first(), bSupertypes.first()) // equivalent(T1, T2) => clash
a.arguments.isNotEmpty() && b.arguments.isNotEmpty() ->
equivalent( // a = Something<....>, b = SomethingElse<....>
a.constructor.declarationDescriptor?.name, // equivalent(Something, SomethingElse) => clash
b.constructor.declarationDescriptor?.name
)
else -> a == b // common case. a == b => clash
}
}
}
else -> false
}
fun walkDeclarations(
currentScopeDeclaration: DeclarationDescriptor,
declaration: DeclarationDescriptor,
report: (DeclarationDescriptor, DeclarationDescriptor) -> Unit
) {
when (currentScopeDeclaration) {
is PackageFragmentDescriptor -> {
fun getPackage(declaration: PackageFragmentDescriptor) =
declaration.containingDeclaration.getPackage(declaration.fqName)
val packageDescriptor = getPackage(currentScopeDeclaration)
if ((declaration.containingDeclaration)?.fqNameOrNull() == currentScopeDeclaration.fqNameOrNull()) {
return
}
packageDescriptor
.memberScope
.getContributedDescriptors { it == declaration.name }
.filter { equivalent(it, declaration) }
.forEach { report(it, packageDescriptor) }
return
}
is ClassDescriptor -> {
if ((declaration.containingDeclaration)?.fqNameOrNull() != currentScopeDeclaration.fqNameOrNull()) {
currentScopeDeclaration
.unsubstitutedMemberScope
.getContributedDescriptors { it == declaration.name }
.filter { equivalent(it, declaration) }
.forEach { report(it, currentScopeDeclaration) }
}
}
}
currentScopeDeclaration.containingDeclaration?.let { walkDeclarations(it, declaration, report) }
}
(elementsToMove - doNotGoIn)
.filterIsInstance<PsiNamedElement>()
.forEach { declaration ->
val declarationDescriptor =
(declaration as KtElement).analyze().get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration)
if (declarationDescriptor is DeclarationDescriptor) {
moveTarget.getContainerDescriptor()?.let { baseDescriptor ->
walkDeclarations(baseDescriptor, declarationDescriptor) { conflictingDeclaration, conflictingScope ->
val message = KotlinBundle.message(
"text.declarations.clash.move.0.destination.1.declared.in.scope.2",
render(declarationDescriptor),
render(conflictingDeclaration),
render(conflictingScope)
)
conflicts.putValue(declaration, message)
}
}
}
}
}
fun checkAllConflicts(
externalUsages: MutableSet<UsageInfo>,
internalUsages: MutableSet<UsageInfo>,
conflicts: MultiMap<PsiElement, String>
) {
checkModuleConflictsInUsages(externalUsages, conflicts)
checkModuleConflictsInDeclarations(internalUsages, conflicts)
checkVisibilityInUsages(externalUsages, conflicts)
checkVisibilityInDeclarations(conflicts)
checkInternalMemberUsages(conflicts)
checkSealedClassMove(conflicts)
checkNameClashes(conflicts)
}
private inner class SealedHierarchyChecker {
private val visited: MutableSet<ClassDescriptor> = mutableSetOf()
@OptIn(ExperimentalStdlibApi::class)
fun reportIfMoveIsDestructive(classToMove: KtClassOrObject): String? {
val classToMoveDesc = classToMove.resolveToDescriptorIfAny() ?: return null
if (classToMoveDesc in visited) return null
val directSealedParents = classToMoveDesc.listDirectSealedParents()
// Not a part of sealed hierarchy?
if (!classToMoveDesc.isSealed() && directSealedParents.isEmpty())
return null
// Standalone sealed class: no sealed parents, no subclasses?
if (classToMoveDesc.isSealed() && directSealedParents.isEmpty() && classToMoveDesc.listAllSubclasses().isEmpty())
return null
// Ok, we're dealing with sealed hierarchy member
val otherHierarchyMembers = classToMoveDesc.listSealedHierarchyMembers().apply { remove(classToMove) }
assert(otherHierarchyMembers.isNotEmpty())
// Entire hierarchy is to be moved at once?
if (otherHierarchyMembers.all { isToBeMoved(it) })
return null
// Hierarchy might be split (broken) (members reside in different packages) and we shouldn't prevent intention to fix it.
// That is why it's ok to move the class to a package where at least one member of hierarchy resides. In case the hierarchy is
// fully correct all its members share the same package.
val targetModule = moveTarget.getTargetModule(project) ?: return null
val targetPackage = moveTarget.getTargetPackage() ?: return null
val targetDir = moveTarget.targetFileOrDir?.takeIf { it.isDirectory } ?: moveTarget.targetFileOrDir?.parent
val className = classToMove.nameAsSafeName.asString()
if (otherHierarchyMembers.none { it.residesIn(targetModule, targetPackage, targetDir) }) {
val hierarchyMembers = buildList { add(classToMove); addAll(otherHierarchyMembers) }.toNamesList()
return KotlinBundle.message(
"text.sealed.broken.hierarchy.none.in.target",
className, moveTarget.getPackageName(), targetModule.name, hierarchyMembers
)
}
// Ok, class joins at least one member of the hierarchy. But probably it leaves the package where other members still exist.
// It doesn't mean we should prevent such move, but it might be good for the user to be aware of the situation.
val moduleToMoveFrom = classToMove.module ?: return null
val packageToMoveFrom = classToMoveDesc.findPsiPackage(moduleToMoveFrom) ?: return null
val directoryToMoveFrom = classToMove.containingKtFile.containingDirectory?.virtualFile
val membersRemainingInOriginalPackage =
otherHierarchyMembers.filter { it.residesIn(moduleToMoveFrom, packageToMoveFrom, directoryToMoveFrom) && !isToBeMoved(it) }.toList()
if ((targetPackage != packageToMoveFrom || targetModule != moduleToMoveFrom) &&
membersRemainingInOriginalPackage.any { !isToBeMoved(it) }
) {
return KotlinBundle.message(
"text.sealed.broken.hierarchy.still.in.source",
className, packageToMoveFrom.getNameOrDefault(), moduleToMoveFrom.name, membersRemainingInOriginalPackage.toNamesList()
)
}
return null
}
private fun KtClassOrObject.residesIn(targetModule: Module, targetPackage: PsiPackage, targetDir: VirtualFile?): Boolean {
val myModule = module ?: return false
val myPackage = descriptor?.findPsiPackage(myModule)
val myDirectory = containingKtFile.containingDirectory?.virtualFile
return myPackage == targetPackage && myModule == targetModule && myDirectory == targetDir
}
private fun DeclarationDescriptor.findPsiPackage(module: Module): PsiPackage? {
val fqName = findPackage().fqName
return KotlinJavaPsiFacade.getInstance(project).findPackage(fqName.asString(), GlobalSearchScope.moduleScope(module))
}
private fun KotlinMoveTarget.getTargetPackage(): PsiPackage? {
fun tryGetPackageFromTargetContainer(): PsiPackage? {
val fqName = targetContainerFqName ?: return null
val module = getTargetModule(project) ?: return null
return KotlinJavaPsiFacade.getInstance(project).findPackage(fqName.asString(), GlobalSearchScope.moduleScope(module))
}
return (this as? KotlinDirectoryMoveTarget)?.targetFileOrDir?.toPsiDirectory(project)?.getPackage()
?: (this as? KotlinMoveTargetForDeferredFile)?.targetFileOrDir?.toPsiDirectory(project)?.getPackage()
?: tryGetPackageFromTargetContainer()
}
private fun KotlinMoveTarget.getPackageName(): String =
targetContainerFqName?.asString()?.takeIf { it.isNotEmpty() } ?: "default" // PsiPackage might not exist by this moment
private fun PsiPackage?.getNameOrDefault(): String = this?.qualifiedName?.takeIf { it.isNotEmpty() } ?: "default"
@OptIn(ExperimentalStdlibApi::class)
private fun ClassDescriptor.listDirectSealedParents(): List<ClassDescriptor> = buildList {
getSuperClassNotAny()?.takeIf { it.isSealed() }?.let { this.add(it) }
getSuperInterfaces().filter { it.isSealed() }.let { this.addAll(it) }
}
private fun ClassDescriptor.listAllSubclasses(): List<ClassDescriptor> {
val sealedKtClass = findPsi() as? KtClassOrObject ?: return emptyList()
val lightClass = sealedKtClass.toLightClass() ?: return emptyList()
val searchScope = GlobalSearchScope.projectScope(sealedKtClass.project)
val searchParameters = SearchParameters(lightClass, searchScope, false, true, false)
return ClassInheritorsSearch.search(searchParameters)
.map mapper@{
val resolutionFacade = it.javaResolutionFacade() ?: return@mapper null
it.resolveToDescriptor(resolutionFacade)
}.filterNotNull()
.sortedBy(ClassDescriptor::getName)
}
private fun ClassDescriptor.listSealedHierarchyMembers(): MutableList<KtClassOrObject> {
fun ClassDescriptor.listMembersInternal(members: MutableList<ClassDescriptor>) {
val alreadyVisited = !visited.add(this)
if (alreadyVisited) return
if (isSealed()) {
members.add(this)
listDirectSealedParents().forEach { it.listMembersInternal(members) }
listAllSubclasses().forEach { it.listMembersInternal(members) }
} else {
val directSuperSealed = listDirectSealedParents()
if (directSuperSealed.isNotEmpty()) {
members.add(this)
directSuperSealed.forEach { it.listMembersInternal(members) }
}
}
}
val members = mutableListOf<ClassDescriptor>()
listMembersInternal(members)
return members.mapNotNull { it.findPsi() as? KtClassOrObject }.toMutableList()
}
private fun List<PsiElement>.toNamesList(): List<String> = mapNotNull { el -> el.getKotlinFqName()?.asString() }.toList()
}
}
fun analyzeConflictsInFile(
file: KtFile,
usages: Collection<UsageInfo>,
moveTarget: KotlinMoveTarget,
allElementsToMove: Collection<PsiElement>,
conflicts: MultiMap<PsiElement, String>,
onUsageUpdate: (List<UsageInfo>) -> Unit
) {
val elementsToMove = file.declarations
if (elementsToMove.isEmpty()) return
val (internalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val internalUsageSet = internalUsages.toMutableSet()
val externalUsageSet = externalUsages.toMutableSet()
val conflictChecker = MoveConflictChecker(
file.project,
elementsToMove,
moveTarget,
elementsToMove.first(),
allElementsToMove = allElementsToMove
)
conflictChecker.checkAllConflicts(externalUsageSet, internalUsageSet, conflicts)
if (externalUsageSet.size != externalUsages.size || internalUsageSet.size != internalUsages.size) {
onUsageUpdate((externalUsageSet + internalUsageSet).toList())
}
}
| apache-2.0 | 49040c22848014ee3ef12be93447158a | 50.18623 | 189 | 0.661749 | 5.908155 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainBuilderBase.kt | 6 | 3353 | // 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.sequence.psi.impl
import com.intellij.debugger.streams.psi.ChainTransformer
import com.intellij.debugger.streams.psi.PsiUtil
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.StreamChainBuilder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.psi.*
abstract class KotlinChainBuilderBase(private val transformer: ChainTransformer<KtCallExpression>) : StreamChainBuilder {
protected abstract val existenceChecker: ExistenceChecker
override fun isChainExists(startElement: PsiElement): Boolean {
val start = if (startElement is PsiWhiteSpace) PsiUtil.ignoreWhiteSpaces(startElement) else startElement
var element = getLatestElementInScope(start)
existenceChecker.reset()
while (element != null && !existenceChecker.isFound()) {
existenceChecker.reset()
element.accept(existenceChecker)
element = toUpperLevel(element)
}
return existenceChecker.isFound()
}
override fun build(startElement: PsiElement): List<StreamChain> {
val visitor = createChainsBuilder()
val start = if (startElement is PsiWhiteSpace) PsiUtil.ignoreWhiteSpaces(startElement) else startElement
var element = getLatestElementInScope(start)
while (element != null) {
element.accept(visitor)
element = toUpperLevel(element)
}
return visitor.chains().map { transformer.transform(it, startElement) }
}
private fun toUpperLevel(element: PsiElement): PsiElement? {
var current = element.parent
while (current != null && !(current is KtLambdaExpression || current is KtAnonymousInitializer || current is KtObjectDeclaration)) {
current = current.parent
}
return getLatestElementInScope(current)
}
protected abstract fun createChainsBuilder(): ChainBuilder
private fun getLatestElementInScope(element: PsiElement?): PsiElement? {
var current = element
while (current != null) {
if (current is KtNamedFunction && current.hasInitializer()) {
break
}
val parent = current.parent
if (parent is KtBlockExpression || parent is KtLambdaExpression) {
break
}
current = parent
}
return current
}
protected abstract class ExistenceChecker : MyTreeVisitor() {
private var myIsFound: Boolean = false
fun isFound(): Boolean = myIsFound
fun reset() = setFound(false)
protected fun fireElementFound() = setFound(true)
private fun setFound(value: Boolean) {
myIsFound = value
}
}
protected abstract class ChainBuilder : MyTreeVisitor() {
abstract fun chains(): List<List<KtCallExpression>>
}
protected abstract class MyTreeVisitor : KtTreeVisitorVoid() {
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {}
override fun visitBlockExpression(expression: KtBlockExpression) {}
}
} | apache-2.0 | 00266400bc70cf54c4364ffb0fc51488 | 35.857143 | 158 | 0.687146 | 5.18238 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/FileAttributeService.kt | 2 | 1275 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches
import com.intellij.openapi.vfs.VirtualFile
import java.io.DataInput
import java.io.DataOutput
data class CachedAttributeData<out T>(val value: T, val timeStamp: Long)
interface FileAttributeService {
fun register(id: String, version: Int, fixedSize: Boolean = true) {}
fun <T : Enum<T>> writeEnumAttribute(id: String, file: VirtualFile, value: T): CachedAttributeData<T> =
CachedAttributeData(value, timeStamp = file.timeStamp)
fun <T : Enum<T>> readEnumAttribute(id: String, file: VirtualFile, klass: Class<T>): CachedAttributeData<T>? = null
fun writeBooleanAttribute(id: String, file: VirtualFile, value: Boolean): CachedAttributeData<Boolean> =
CachedAttributeData(value, timeStamp = file.timeStamp)
fun readBooleanAttribute(id: String, file: VirtualFile): CachedAttributeData<Boolean>? = null
fun <T> write(file: VirtualFile, id: String, value: T, writeValueFun: (DataOutput, T) -> Unit): CachedAttributeData<T>
fun <T> read(file: VirtualFile, id: String, readValueFun: (DataInput) -> T): CachedAttributeData<T>?
}
| apache-2.0 | d62845518a8d0c9abf29f1ab65b2c0b9 | 46.222222 | 158 | 0.741961 | 3.87538 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/_custom/recycleview/LoadingMoreFooter.kt | 1 | 2013 | package com.zwq65.unity.ui._custom.recycleview
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.zwq65.unity.R
import com.zwq65.unity.ui._custom.view.LoadingView
class LoadingMoreFooter : LinearLayout {
private var mText: TextView? = null
private var mLoadingView: LoadingView? = null
constructor(context: Context) : super(context) {
initView(context)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initView(context)
}
fun initView(context: Context) {
LayoutInflater.from(context).inflate(R.layout.layout_load_footer, this)
mText = findViewById(R.id.tv_msg)
mLoadingView = findViewById(R.id.loadingView)
mLoadingView!!.setSize(SizeUtils.dp2px(14f))
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
fun setState(state: Int) {
when (state) {
STATE_LOADING -> {
mText!!.text = context.getText(R.string.listview_loading)
mLoadingView!!.visibility = View.VISIBLE
visibility = View.VISIBLE
}
STATE_COMPLETE -> {
mText!!.text = context.getText(R.string.listview_loading)
visibility = View.GONE
}
STATE_NOMORE -> {
mText!!.text = context.getText(R.string.nomore_loading)
mLoadingView!!.visibility = View.GONE
visibility = View.VISIBLE
}
else -> {
}
}
}
fun reSet() {
this.visibility = View.GONE
}
companion object {
const val STATE_LOADING = 0
const val STATE_COMPLETE = 1
const val STATE_NOMORE = 2
}
}
| apache-2.0 | 9853f0571d797139d373ae3ac88b9a03 | 29.5 | 122 | 0.629906 | 4.357143 | false | false | false | false |
h0tk3y/better-parse | src/jvmMain/kotlin/com/github/h0tk3y/betterParse/lexer/RegexToken.kt | 1 | 2052 | package com.github.h0tk3y.betterParse.lexer
import java.util.*
import java.util.regex.Matcher
public actual class RegexToken private constructor(
name: String?,
ignored: Boolean,
private val pattern: String,
private val regex: Regex
) : Token(name, ignored) {
private val threadLocalMatcher = object : ThreadLocal<Matcher>() {
override fun initialValue() = regex.toPattern().matcher("")
}
private val matcher: Matcher get() = threadLocalMatcher.get()
private companion object {
private const val inputStartPrefix = "\\A"
private fun prependPatternWithInputStart(patternString: String, options: Set<RegexOption>) =
if (patternString.startsWith(Companion.inputStartPrefix))
patternString.toRegex(options)
else {
val newlineAfterComments = if (RegexOption.COMMENTS in options) "\n" else ""
val patternToEmbed = if (RegexOption.LITERAL in options) Regex.escape(patternString) else patternString
("${inputStartPrefix}(?:$patternToEmbed$newlineAfterComments)").toRegex(options - RegexOption.LITERAL)
}
}
public actual constructor(
name: String?,
@Language("RegExp", "", "") patternString: String,
ignored: Boolean
) : this(
name,
ignored,
patternString,
prependPatternWithInputStart(patternString, emptySet())
)
public actual constructor(
name: String?,
regex: Regex,
ignored: Boolean
) : this(
name,
ignored,
regex.pattern,
prependPatternWithInputStart(regex.pattern, regex.options)
)
override fun match(input: CharSequence, fromIndex: Int): Int {
matcher.reset(input).region(fromIndex, input.length)
if (!matcher.find()) {
return 0
}
val end = matcher.end()
return end - fromIndex
}
override fun toString(): String = "${name ?: ""} [$pattern]" + if (ignored) " [ignorable]" else ""
} | apache-2.0 | cf5d7a401f2df74899ee4ad962c3914d | 29.641791 | 119 | 0.626706 | 4.717241 | false | false | false | false |
zhlsky/kotlin-koans | src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt | 1 | 945 | package i_introduction._3_Default_Arguments
import util.TODO
import util.doc2
fun todoTask3(): Nothing = TODO(
"""
Task 3.
Several overloads of 'JavaCode3.foo()' can be replaced with one function in Kotlin.
Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile.
You have to add parameters and replace 'todoTask3()' with a real body.
Uncomment the commented code and make it compile.
""",
documentation = doc2(),
references = { name: String -> JavaCode3().foo(name); foo(name) })
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String {
val upCaseName = if (toUpperCase) name.toUpperCase() else name
return upCaseName + number
}
fun task3(): String {
return (foo("a") +
foo("b", number = 1) +
foo("c", toUpperCase = true) +
foo(name = "d", number = 2, toUpperCase = true))
}
| mit | 88bcae3a333b6f7fd51f5fcfef7bf499 | 34 | 102 | 0.632804 | 3.970588 | false | false | false | false |
timrijckaert/BetterBottomBar | library/src/main/kotlin/be/rijckaert/tim/library/BetterBottomBar.kt | 1 | 9398 | package be.rijckaert.tim.library
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Rect
import android.os.Build
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.os.Bundle
import android.os.Parcelable
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
import android.support.design.widget.CoordinatorLayout.DefaultBehavior
import android.support.v7.widget.TintTypedArray
import android.util.AttributeSet
import android.view.MenuItem
import android.view.View
import android.view.ViewAnimationUtils.createCircularReveal
import android.view.ViewGroup
import be.rijckaert.tim.library.AnimatorListenerAdapter.Companion.withCircularRevealListener
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.dip
@DefaultBehavior(BetterBottomBarDefaultBehavior::class)
class BetterBottomBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
: BottomNavigationView(context, attrs, defStyle) {
private val BOTTOM_BAR_HEIGHT_DP = 56
private val ANIMATION_DURATION = 300L
private val START_RADIUS = 0F
private val ACCESSIBILITY_VIEW = "mItemData"
private val INVALID_REFERENCE = 0
private val SELECTED_TAB_INDEX = "be.rijckaert.tim.library.BetterBottomBar.SELECTED_TAB_INDEX"
var textColors = emptyArray<ColorStateList>()
var iconColors = emptyArray<ColorStateList>()
var colors = emptyArray<Int>()
var contentDescriptionTitles = emptyArray<String>()
var betterBottomBarClickListener: ((BetterBottomBar, MenuItem) -> Unit)? = null
private val navigationMenu by lazy { getChildAt(0) as BottomNavigationMenuView }
private var overlayView: View? = null
get() {
if (field != null) {
return field
}
field = View(context).apply {
backgroundColor = currentBackgroundColor
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip(BOTTOM_BAR_HEIGHT_DP).toInt())
}
addView(field, INVALID_REFERENCE)
return field
}
var selectedTab = 0
private set
private val currentBackgroundColor
get() = colors.takeIf { it.isNotEmpty() }?.get(selectedTab) ?: (background as android.graphics.drawable.ColorDrawable).color
private val SELECTED_ACC_TEXT by lazy { context.getString(R.string.acc_was_selected) }
private val TAB_ACC_TEXT by lazy { context.getString(R.string.acc_tab) }
private val OF_ACC_TEXT by lazy { context.getString(R.string.acc_of) }
init {
val styledAttributes = TintTypedArray.obtainStyledAttributes(context, attrs, R.styleable.BetterBottomBar, 0, 0)
initializeTextColors(styledAttributes)
initializeIconColors(styledAttributes)
initializeColors(styledAttributes)
initializeAccessibilityTextTitles(styledAttributes)
styledAttributes.recycle()
setTextColors()
setIconColors()
setWillNotDraw(true)
prepareBottomNavigationItems()
}
//<editor-fold desc="View State">
override fun onSaveInstanceState(): Parcelable {
super.onSaveInstanceState()
return Bundle().apply { putInt(SELECTED_TAB_INDEX, selectedTab) }
}
override fun onRestoreInstanceState(state: Parcelable?) {
super.onRestoreInstanceState(null)
selectedTab = (state as Bundle).getInt(SELECTED_TAB_INDEX)
menu.getItem(selectedTab).isChecked = true
prepareBottomNavigationItems()
setBackgroundColor()
setIconColors()
setTextColors()
}
//</editor-fold>
//<editor-fold desc="Styling">
private fun initializeTextColors(styledAttributes: TintTypedArray) {
val textColorRes = arrayListOf(
R.styleable.BetterBottomBar_firstTabTextColors,
R.styleable.BetterBottomBar_secondTabTextColors,
R.styleable.BetterBottomBar_thirdTabTextColors,
R.styleable.BetterBottomBar_fourthTabTextColors,
R.styleable.BetterBottomBar_fifthTabTextColors
)
textColors = textColorRes
.map { styledAttributes.getColorStateList(it) }
.toTypedArray()
}
private fun initializeIconColors(styledAttributes: TintTypedArray) {
val iconColorRes = arrayListOf(
R.styleable.BetterBottomBar_firstTabIconColors,
R.styleable.BetterBottomBar_secondTabIconColors,
R.styleable.BetterBottomBar_thirdTabIconColors,
R.styleable.BetterBottomBar_fourthTabIconColors,
R.styleable.BetterBottomBar_fifthTabIconColors
)
iconColors = iconColorRes
.map { styledAttributes.getColorStateList(it) }
.toTypedArray()
}
private fun initializeAccessibilityTextTitles(styledAttributes: TintTypedArray) {
val titles = styledAttributes.getResourceId(R.styleable.BetterBottomBar_contentDescriptionTitles, INVALID_REFERENCE)
if (titles != INVALID_REFERENCE) {
contentDescriptionTitles = resources.getStringArray(titles)
}
}
private fun initializeColors(styledAttributes: TintTypedArray) {
val colors = styledAttributes.getResourceId(R.styleable.BetterBottomBar_colors, INVALID_REFERENCE)
if (colors != INVALID_REFERENCE) {
this.colors = resources.getIntArray(colors).toTypedArray()
}
}
//</editor-fold>
//<editor-fold desc="View Modification">
private fun setIconColors() {
iconColors.getOrNull(selectedTab)?.let {
navigationMenu.iconTintList = it
}
}
private fun setTextColors() {
textColors.getOrNull(selectedTab)?.let {
navigationMenu.itemTextColor = it
}
}
private fun setBackgroundColor() {
backgroundColor = currentBackgroundColor
}
//</editor-fold>
private fun prepareBottomNavigationItems() {
val navigationItemViews =
getAllViewGroups()
.filter { it is BottomNavigationItemView }
.filterNotNull()
setContentDescriptions(navigationItemViews)
navigationItemViews.getOrNull(selectedTab)?.isSelected = true
navigationItemViews.forEach { btmNavItem ->
btmNavItem.setOnClickListener {
val clickedBtmNavItem = btmNavItem as BottomNavigationItemView
selectedTab = clickedBtmNavItem.itemPosition
menu.getItem(selectedTab).isChecked = true
betterBottomBarClickListener?.invoke(this, menu.getItem(selectedTab))
setContentDescriptions(navigationItemViews)
announceForAccessibility(it.contentDescription)
setTextColors()
setIconColors()
if (Build.VERSION.SDK_INT >= LOLLIPOP) {
with(createRevealAnimator(it)) {
start()
addListener(
withCircularRevealListener(
onTerminate = {
removeOverlay()
setBackgroundColor()
})
)
}
} else {
setBackgroundColor()
}
}
}
}
private fun removeOverlay() {
removeView(overlayView)
overlayView = null
}
@SuppressLint("NewApi")
private fun createRevealAnimator(clickedView: View): Animator {
val clickedViewRectXPos = Rect()
clickedView.getGlobalVisibleRect(clickedViewRectXPos)
val xPosClickedView = clickedViewRectXPos.left
val xPos = xPosClickedView + (clickedView.width / 2)
val remainingWidth = (width - xPos)
return createCircularReveal(
overlayView,
xPos,
height / 2,
START_RADIUS,
xPos.coerceAtLeast(remainingWidth).toFloat()
).apply { duration = ANIMATION_DURATION }
}
private fun setContentDescriptions(navigationItemViews: List<ViewGroup>) {
navigationItemViews.forEach { viewGroup ->
val btmNavItem = viewGroup as BottomNavigationItemView
val title = getAccessibilityTitle(btmNavItem)
val isSelectedText = if (btmNavItem.isSelected || btmNavItem.itemPosition == selectedTab) SELECTED_ACC_TEXT else ""
btmNavItem.contentDescription = "$title $TAB_ACC_TEXT ${btmNavItem.itemPosition + 1} $OF_ACC_TEXT ${navigationItemViews.size} $isSelectedText"
}
}
private fun getAccessibilityTitle(btmNavItem: BottomNavigationItemView): String =
if (contentDescriptionTitles.isNotEmpty()) {
contentDescriptionTitles[btmNavItem.itemPosition]
} else {
btmNavItem.javaClass.getDeclaredField(ACCESSIBILITY_VIEW).isAccessible = true
btmNavItem.itemData.title.toString()
}
} | mit | 6abbacfbc1ed38124b9ad36833724758 | 37.838843 | 154 | 0.657374 | 5.264986 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttGroupAction.kt | 1 | 1405 | package com.softmotions.ncms.mtt.http
import com.google.inject.Singleton
import org.slf4j.LoggerFactory
import javax.annotation.concurrent.ThreadSafe
import javax.servlet.http.HttpServletResponse
/**
*
* @author Adamansky Anton ([email protected])
*/
@Singleton
@ThreadSafe
open class MttGroupAction : MttActionHandler {
private val log = LoggerFactory.getLogger(javaClass)
override val type: String = "group"
override fun execute(ctx: MttActionHandlerContext,
rmc: MttRequestModificationContext,
resp: HttpServletResponse): Boolean {
val glist = ctx.findGroupActions();
if (log.isDebugEnabled) {
log.debug("Groups={}",
glist.map { it.action }
)
}
var sum = 0.0
for (ac in glist) {
sum += ac.action.groupWeight
}
if (sum == 0.0) { // zero width
return false
}
val p = Math.random() * sum
var cp = 0.0
if (log.isDebugEnabled) {
log.debug("P=${p}")
}
for (ac in glist) {
cp += ac.action.groupWeight
if (p <= cp) {
if (log.isDebugEnabled) {
log.debug("Executing: ${cp}")
}
return ac.execute(rmc, resp)
}
}
return false
}
} | apache-2.0 | 6339b162f2cee2f8f8b79c30b0170992 | 26.038462 | 62 | 0.537367 | 4.390625 | false | false | false | false |
breadwallet/breadwallet-android | ui/ui-common/src/main/java/com/breadwallet/ui/BaseMobiusController.kt | 1 | 13296 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 8/13/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui
import android.os.Bundle
import android.view.View
import com.breadwallet.ext.throttleFirst
import com.breadwallet.mobius.ConsumerDelegate
import com.breadwallet.mobius.QueuedConsumer
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.Navigator
import com.breadwallet.util.errorHandler
import com.spotify.mobius.Connectable
import com.spotify.mobius.Connection
import com.spotify.mobius.EventSource
import com.spotify.mobius.First
import com.spotify.mobius.Init
import com.spotify.mobius.Mobius
import com.spotify.mobius.MobiusLoop
import com.spotify.mobius.Update
import com.spotify.mobius.android.AndroidLogger
import com.spotify.mobius.android.runners.MainThreadWorkRunner
import com.spotify.mobius.disposables.Disposable
import com.spotify.mobius.functions.Consumer
import drewcarlson.mobius.flow.DispatcherWorkRunner
import drewcarlson.mobius.flow.FlowTransformer
import drewcarlson.mobius.flow.asConnectable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart.ATOMIC
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.Unconfined
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
import org.kodein.di.Kodein
import org.kodein.di.erased.instance
import java.util.concurrent.atomic.AtomicBoolean
private const val MAX_QUEUED_VIEW_EFFECTS = 100
@Suppress("TooManyFunctions")
abstract class BaseMobiusController<M, E, F>(
args: Bundle? = null
) : BaseController(args),
EventSource<E> {
override val kodein by Kodein.lazy {
extend(super.kodein)
}
protected val uiBindScope = CoroutineScope(
SupervisorJob() + Dispatchers.Main + errorHandler("uiBindScope")
)
private val navigator by instance<Navigator>()
private val viewEffectChannel = Channel<ViewEffect>(MAX_QUEUED_VIEW_EFFECTS)
/** The default model used to construct [loopController]. */
abstract val defaultModel: M
/** The update function used to construct [loopFactory]. */
abstract val update: Update<M, E, F>
/** The init function used to construct [loopFactory]. */
open val init: Init<M, F> = Init { First.first(it) }
/** The effect handler used to construct [loopFactory]. */
open val effectHandler: Connectable<F, E>? = null
// TODO: Make abstract and non-nullable when children only implement flowEffectHandler
/** The effect handler used to construct [loopFactory]. */
open val flowEffectHandler: FlowTransformer<F, E>? = null
private var loop: MobiusLoop<M, E, F>? = null
private val isLoopActive = AtomicBoolean(false)
private val logger = AndroidLogger.tag<M, E, F>(this::class.java.simpleName)
private val loopFactory by lazy {
val loopConnection = Connectable<F, E> { output ->
val handler = checkNotNull(effectHandler ?: flowEffectHandler?.asConnectable()) {
"effectHandler or flowEffectHandler must be implemented."
}
val connection = handler.connect(output)
object : Connection<F> {
override fun accept(value: F) {
if (value is ViewEffect) {
check(viewEffectChannel.offer(value)) {
"ViewEffect queue capacity exceeded."
}
} else {
connection.accept(value)
}
}
override fun dispose() {
connection.dispose()
// Dispose any queued effects
viewEffectChannel.receiveAsFlow()
.launchIn(GlobalScope)
}
}
}
Mobius.loop(update, loopConnection)
.eventRunner { DispatcherWorkRunner(Dispatchers.Default) }
.effectRunner { DispatcherWorkRunner(Dispatchers.Default) }
.logger(logger)
.eventSource(this)
}
private var disposeConnection: (() -> Unit)? = null
private val eventConsumerDelegate = ConsumerDelegate<E>(QueuedConsumer())
private val modelChannel = BroadcastChannel<M>(Channel.CONFLATED)
/**
* An entrypoint for adding platform events into a [MobiusLoop].
*
* When the loop has not been started, a [QueuedConsumer] is used
* and all events will be dispatched when the loop is started.
* Events dispatched from [onActivityResult] are one example of
* of this use-case.
*/
val eventConsumer: Consumer<E> = eventConsumerDelegate
/** The currently rendered model. */
val currentModel: M
get() = loop?.mostRecentModel ?: defaultModel
/** The previously rendered model or null */
var previousModel: M? = null
private set
/** Called when [view] can attach listeners to dispatch events via [output]. */
open fun bindView(output: Consumer<E>): Disposable = Disposable { }
/** Called when the model is updated or additional rendering is required. */
open fun M.render() = Unit
/**
* Called when instances of model [M] can be collected
* from [modelFlow].
*
* The returned [Flow] will be collected while the loop
* is running to dispatch each event [E].
*/
open fun bindView(modelFlow: Flow<M>): Flow<E> = emptyFlow()
open fun handleViewEffect(effect: ViewEffect) = Unit
override fun onAttach(view: View) {
super.onAttach(view)
collectViewEffects()
if (loop == null) {
createLoop()
connectView(checkNotNull(loop))
} else {
previousModel = null
connectView(checkNotNull(loop))
currentModel.render()
}
}
override fun onDetach(view: View) {
disconnectView()
super.onDetach(view)
}
override fun onDestroy() {
disposeLoop()
super.onDestroy()
}
override fun subscribe(newConsumer: Consumer<E>): Disposable {
(eventConsumerDelegate.consumer as? QueuedConsumer)?.dequeueAll(newConsumer)
eventConsumerDelegate.consumer = newConsumer
return Disposable {
eventConsumerDelegate.consumer = QueuedConsumer()
}
}
private fun createLoop() {
logger.beforeInit(currentModel)
val first = init.init(currentModel)
logger.afterInit(currentModel, first)
val workRunner = MainThreadWorkRunner.create()
loop = loopFactory.startFrom(first.model(), first.effects()).apply {
observe { model ->
modelChannel.offer(model)
workRunner.post {
if (isAttached) model.render()
previousModel = model
}
}
}
isLoopActive.set(true)
}
private fun disposeLoop() {
isLoopActive.set(false)
disposeConnection = null
loop?.dispose()
loop = null
}
private fun connectView(loop: MobiusLoop<M, E, F>) {
val legacyDispose = bindView(Consumer { event ->
if (isLoopActive.get()) {
loop.dispatchEvent(event)
}
})
val job = SupervisorJob()
val scope = CoroutineScope(job + Dispatchers.Main + errorHandler("modelConsumer"))
scope.launch(Unconfined) {
bindView(modelChannel.asFlow()).collect { event ->
ensureActive()
if (isLoopActive.get()) {
loop.dispatchEvent(event)
}
}
}
disposeConnection = {
legacyDispose.dispose()
// Ensure the view binding flow is fully cancelled before
// the view is detached.
// Unconfined: Immediately execute to first suspension point.
// Atomic: Immediately execute coroutine in launched context.
scope.launch(Unconfined, ATOMIC) {
job.cancelAndJoin()
}
}
}
private fun disconnectView() {
disposeConnection?.invoke()
disposeConnection = null
}
private fun collectViewEffects() {
viewEffectChannel.receiveAsFlow()
.transform { effect ->
if (effect is NavigationEffect) {
emit(effect)
} else {
handleViewEffect(effect)
}
}
.filterIsInstance<NavigationEffect>()
.throttleFirst(500L)
.onEach { effect ->
navigator.navigateTo(effect.navigationTarget)
}
.flowOn(Dispatchers.Main)
.launchIn(viewAttachScope)
}
inline fun <T, reified M2 : M> extractOrUnit(
model: M?,
crossinline extract: (M2) -> T
): Any? {
return if (model is M2) model.run(extract) else Unit
}
/**
* Invokes [block] only when the result of [extract] on
* [this] is not equal to [extract] on [previousModel].
*
* [block] supplies the value extracted from [currentModel].
*/
inline fun <T, reified M2 : M> M2.ifChanged(
crossinline extract: (M2) -> T,
crossinline block: (@ParameterName("value") T) -> Unit
) {
val currentValue = extract(this)
val previousValue = extractOrUnit(previousModel, extract)
if (currentValue != previousValue) {
block(currentValue)
}
}
/**
* Invokes [block] if the result of any extract functions on
* [this] are not equal to the same function on the [previousModel].
*/
inline fun <T1, T2, reified M2 : M> M2.ifChanged(
crossinline extract1: (M2) -> T1,
crossinline extract2: (M2) -> T2,
crossinline block: () -> Unit
) {
if (
extract1(this) != extractOrUnit(previousModel, extract1) ||
extract2(this) != extractOrUnit(previousModel, extract2)
) {
block()
}
}
/**
* Invokes [block] if the result of any extract functions on
* [this] are not equal to the same function on the [previousModel].
*/
inline fun <T1, T2, T3, reified M2 : M> M2.ifChanged(
crossinline extract1: (M2) -> T1,
crossinline extract2: (M2) -> T2,
crossinline extract3: (M2) -> T3,
crossinline block: () -> Unit
) {
if (
extract1(this) != extractOrUnit(previousModel, extract1) ||
extract2(this) != extractOrUnit(previousModel, extract2) ||
extract3(this) != extractOrUnit(previousModel, extract3)
) {
block()
}
}
/**
* Invokes [block] if the result of any extract functions on
* [this] are not equal to the same function on the [previousModel].
*/
@Suppress("ComplexCondition")
inline fun <T1, T2, T3, T4, reified M2 : M> M2.ifChanged(
crossinline extract1: (M2) -> T1,
crossinline extract2: (M2) -> T2,
crossinline extract3: (M2) -> T3,
crossinline extract4: (M2) -> T4,
crossinline block: () -> Unit
) {
if (
extract1(this) != extractOrUnit(previousModel, extract1) ||
extract2(this) != extractOrUnit(previousModel, extract2) ||
extract3(this) != extractOrUnit(previousModel, extract3) ||
extract4(this) != extractOrUnit(previousModel, extract4)
) {
block()
}
}
}
| mit | d8d75809ae52d79b5e8280b0b9b7d9e8 | 34.267905 | 93 | 0.638764 | 4.570643 | false | false | false | false |
AVnetWS/Hentoid | app/src/main/java/me/devsaki/hentoid/fragments/intro/ThemeIntroFragment.kt | 1 | 1357 | package me.devsaki.hentoid.fragments.intro
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import me.devsaki.hentoid.R
import me.devsaki.hentoid.activities.IntroActivity
import me.devsaki.hentoid.databinding.IntroSlide05Binding
import me.devsaki.hentoid.util.Preferences
class ThemeIntroFragment : Fragment(R.layout.intro_slide_05) {
private var _binding: IntroSlide05Binding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = IntroSlide05Binding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val parentActivity = context as IntroActivity
binding.intro5Light.setOnClickListener { parentActivity.setThemePrefs(Preferences.Constant.COLOR_THEME_LIGHT) }
binding.intro5Dark.setOnClickListener { parentActivity.setThemePrefs(Preferences.Constant.COLOR_THEME_DARK) }
binding.intro5Black.setOnClickListener { parentActivity.setThemePrefs(Preferences.Constant.COLOR_THEME_BLACK) }
}
}
| apache-2.0 | 290fd002ff0f396ebe60940f3e3b38fa | 38.911765 | 119 | 0.768607 | 4.523333 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/character/RPKCharacterProviderImpl.kt | 1 | 9266 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.characters.bukkit.character
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.database.table.RPKCharacterTable
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterCreateEvent
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterDeleteEvent
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterSwitchEvent
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterUpdateEvent
import com.rpkit.players.bukkit.player.RPKPlayer
import com.rpkit.players.bukkit.player.RPKPlayerProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.attribute.Attribute
/**
* Character provider implementation.
*/
class RPKCharacterProviderImpl(private val plugin: RPKCharactersBukkit) : RPKCharacterProvider {
override fun getCharacter(id: Int): RPKCharacter? {
return plugin.core.database.getTable(RPKCharacterTable::class)[id]
}
override fun getActiveCharacter(player: RPKPlayer): RPKCharacter? {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val offlineBukkitPlayer = player.bukkitPlayer
if (offlineBukkitPlayer != null) {
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(offlineBukkitPlayer)
if (minecraftProfile != null) {
return getActiveCharacter(minecraftProfile)
}
}
val characterTable = plugin.core.database.getTable(RPKCharacterTable::class)
return characterTable.getActive(player)
}
override fun getActiveCharacter(minecraftProfile: RPKMinecraftProfile): RPKCharacter? {
var character = plugin.core.database.getTable(RPKCharacterTable::class).get(minecraftProfile)
if (character != null) {
return character
} else {
val playerProvider = plugin.core.serviceManager.getServiceProvider(RPKPlayerProvider::class)
val player = playerProvider.getPlayer(plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID))
val characterTable = plugin.core.database.getTable(RPKCharacterTable::class)
character = characterTable.getActive(player)
if (character != null) {
setActiveCharacter(minecraftProfile, character)
return character
}
}
return null
}
override fun setActiveCharacter(player: RPKPlayer, character: RPKCharacter?) {
val offlineBukkitPlayer = player.bukkitPlayer
if (offlineBukkitPlayer != null) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(offlineBukkitPlayer)
if (minecraftProfile != null) {
setActiveCharacter(minecraftProfile, character)
}
}
}
override fun setActiveCharacter(minecraftProfile: RPKMinecraftProfile, character: RPKCharacter?) {
var oldCharacter = getActiveCharacter(minecraftProfile)
val event = RPKBukkitCharacterSwitchEvent(minecraftProfile, oldCharacter, character)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
oldCharacter = event.fromCharacter
val newCharacter = event.character
if (oldCharacter != null) {
oldCharacter.minecraftProfile = null
val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID)
val bukkitPlayer = offlineBukkitPlayer.player
if (bukkitPlayer != null) {
oldCharacter.inventoryContents = bukkitPlayer.inventory.contents
oldCharacter.helmet = bukkitPlayer.inventory.helmet
oldCharacter.chestplate = bukkitPlayer.inventory.chestplate
oldCharacter.leggings = bukkitPlayer.inventory.leggings
oldCharacter.boots = bukkitPlayer.inventory.boots
oldCharacter.location = bukkitPlayer.location
oldCharacter.health = bukkitPlayer.health
oldCharacter.foodLevel = bukkitPlayer.foodLevel
}
updateCharacter(oldCharacter)
}
if (newCharacter != null) {
val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID)
val bukkitPlayer = offlineBukkitPlayer.player
if (bukkitPlayer != null) {
bukkitPlayer.inventory.contents = newCharacter.inventoryContents
bukkitPlayer.inventory.helmet = newCharacter.helmet
bukkitPlayer.inventory.chestplate = newCharacter.chestplate
bukkitPlayer.inventory.leggings = newCharacter.leggings
bukkitPlayer.inventory.boots = newCharacter.boots
bukkitPlayer.teleport(newCharacter.location)
bukkitPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.baseValue = newCharacter.maxHealth
bukkitPlayer.health = newCharacter.health
bukkitPlayer.foodLevel = newCharacter.foodLevel
if (plugin.config.getBoolean("characters.set-player-display-name")) {
bukkitPlayer.setDisplayName(newCharacter.name)
}
}
newCharacter.minecraftProfile = minecraftProfile
updateCharacter(newCharacter)
}
}
override fun getCharacters(player: RPKPlayer): Collection<RPKCharacter> {
val offlineBukkitPlayer = player.bukkitPlayer
if (offlineBukkitPlayer != null) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(offlineBukkitPlayer)
if (minecraftProfile != null) {
val profile = minecraftProfile.profile
if (profile is RPKProfile) {
val characters = getCharacters(profile).toMutableList()
val characterTable = plugin.core.database.getTable(RPKCharacterTable::class)
val oldCharacters = characterTable.get(player)
oldCharacters.forEach { oldCharacter ->
oldCharacter.profile = profile
updateCharacter(oldCharacter)
}
characters.addAll(oldCharacters)
if (characters.isNotEmpty()) {
return characters.distinct()
}
}
}
}
val characterTable = plugin.core.database.getTable(RPKCharacterTable::class)
return characterTable.get(player)
}
override fun getCharacters(profile: RPKProfile): List<RPKCharacter> {
return plugin.core.database.getTable(RPKCharacterTable::class).get(profile)
}
override fun getCharacters(name: String): List<RPKCharacter> {
return plugin.core.database.getTable(RPKCharacterTable::class).get(name)
}
override fun addCharacter(character: RPKCharacter) {
val event = RPKBukkitCharacterCreateEvent(character)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
plugin.core.database.getTable(RPKCharacterTable::class).insert(event.character)
}
override fun removeCharacter(character: RPKCharacter) {
val event = RPKBukkitCharacterDeleteEvent(character)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
val minecraftProfile = event.character.minecraftProfile
if (minecraftProfile != null) {
if (getActiveCharacter(minecraftProfile) == event.character) {
setActiveCharacter(minecraftProfile, null)
}
}
plugin.core.database.getTable(RPKCharacterTable::class).delete(event.character)
}
override fun updateCharacter(character: RPKCharacter) {
if (plugin.config.getBoolean("characters.delete-character-on-death") && character.isDead) {
removeCharacter(character)
} else {
val event = RPKBukkitCharacterUpdateEvent(character)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
plugin.core.database.getTable(RPKCharacterTable::class).update(event.character)
}
}
}
| apache-2.0 | 53758b68391eac60190257051cf593df | 47.010363 | 124 | 0.68897 | 5.437793 | false | false | false | false |
fuzhouch/qbranch | core/src/test/kotlin/net/dummydigit/qbranch/ut/mocks/SkipFields.kt | 1 | 1190 | // Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.ut.mocks
import net.dummydigit.qbranch.QBranchSerializable
import net.dummydigit.qbranch.annotations.FieldId
import net.dummydigit.qbranch.annotations.QBranchGeneratedCode
import net.dummydigit.qbranch.generic.StructT
/*
namespace qbranch.ut
struct StructToSkip
{
0: int32 skippedValue;
}
struct TestStructVersion1
{
0: int32 int32Value; <<< let's decode with this struct.
}
struct TestStructVersion2
{
0: int32 int32Value;
1: string stringValue;
2: StructToSkip structValue;
}
*/
@QBranchGeneratedCode("gbc", "version.mock")
open class SkipFields : QBranchSerializable {
@FieldId(0) var int32Value : Int = 0
companion object QTypeDef {
class SkipFieldsT : StructT<SkipFields>() {
override val baseClassT = null
override fun newInstance() = SkipFields()
private val refObj = newInstance()
override fun getGenericType() = refObj.javaClass
}
@JvmStatic
fun asQTypeArg() : SkipFieldsT {
return SkipFieldsT()
}
}
} | mit | efe9c025d46251a0025b59e34db2a373 | 21.903846 | 71 | 0.695798 | 4.02027 | false | false | false | false |
ibinti/intellij-community | python/src/com/jetbrains/reflection/ReflectionUtils.kt | 3 | 6401 | /*
* 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.jetbrains.reflection
import com.intellij.util.containers.HashMap
import com.intellij.util.containers.SoftHashMap
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.lang.ref.SoftReference
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaType
import kotlin.reflect.memberProperties
/**
* Tools to fetch properties both from Java and Kotlin code and to copy them from one object to another.
* To be a property container class should have kotlin properties, java bean properties or implement [SimplePropertiesProvider].
*
* Properties should be writable except [DelegationProperty]
* @author Ilya.Kazakevich
*/
interface Property {
fun getName(): String
fun getType(): java.lang.reflect.Type
fun get(): Any?
fun set(value: Any?)
}
private class KotlinProperty(val property: KMutableProperty<*>, val instance: Any?) : Property {
override fun getName() = property.name
override fun getType() = property.returnType.javaType
override fun get() = property.getter.call(instance)
override fun set(value: Any?) = property.setter.call(instance, value)
}
private class JavaProperty(val property: PropertyDescriptor, val instance: Any?) : Property {
override fun getName() = property.name!!
override fun getType() = property.propertyType!!
override fun get() = property.readMethod.invoke(instance)!!
override fun set(value: Any?) {
property.writeMethod.invoke(instance, value)
}
}
private class SimpleProperty(private val propertyName: String,
private val provider: SimplePropertiesProvider) : Property {
override fun getName() = propertyName
override fun getType() = String::class.java
override fun get() = provider.getPropertyValue(propertyName)
override fun set(value: Any?) = provider.setPropertyValue(propertyName, value?.toString())
}
/**
* Implement to handle properties manually
*/
interface SimplePropertiesProvider {
val propertyNames: List<String>
fun setPropertyValue(propertyName: String, propertyValue: String?)
fun getPropertyValue(propertyName: String): String?
}
class Properties(val properties: List<Property>, val instance: Any) {
val propertiesMap: MutableMap<String, Property> = HashMap(properties.map { Pair(it.getName(), it) }.toMap())
init {
if (instance is SimplePropertiesProvider) {
instance.propertyNames.forEach { propertiesMap.put(it, SimpleProperty(it, instance)) }
}
}
fun copyTo(dst: Properties) {
propertiesMap.values.forEach {
val dstProperty = dst.propertiesMap[it.getName()]
if (dstProperty != null) {
val value = it.get()
dstProperty.set(value)
}
}
}
}
private fun KProperty<*>.isAnnotated(annotation: KClass<*>): Boolean {
return this.annotations.find { annotation.java.isAssignableFrom(it.javaClass) } != null
}
private val membersCache: MutableMap<KClass<*>, SoftReference<Collection<KProperty<*>>>> = SoftHashMap()
private fun KClass<*>.memberPropertiesCached(): Collection<KProperty<*>> {
synchronized(membersCache) {
val cache = membersCache[this]?.get()
if (cache != null) {
return cache
}
val memberProperties = this.memberProperties
membersCache.put(this, SoftReference(memberProperties))
return memberProperties
}
}
/**
* @param instance object with properties (see module doc)
* @param annotationToFilterByClass optional annotation class to fetch only kotlin properties annotated with it. Only supported in Kotlin
* @param usePojoProperties search for java-style properties (kotlin otherwise)
* @return properties of some object
*/
fun getProperties(instance: Any, annotationToFilterByClass: Class<*>? = null, usePojoProperties: Boolean = false): Properties {
val annotationToFilterBy = annotationToFilterByClass?.kotlin
if (usePojoProperties) {
// Java props
val javaProperties = Introspector.getBeanInfo(instance.javaClass).propertyDescriptors
assert(annotationToFilterBy == null, { "Filtering java properties is not supported" })
return Properties(javaProperties.map { JavaProperty(it, instance) }, instance)
}
else {
// Kotlin props
val klass = instance.javaClass.kotlin
val allKotlinProperties = LinkedHashSet(klass.memberPropertiesCached().filterIsInstance(KProperty::class.java))
val delegatedProperties = ArrayList<Property>() // See DelegationProperty doc
allKotlinProperties.filter { it.isAnnotated(DelegationProperty::class) }.forEach {
val delegatedInstance = it.getter.call(instance)
if (delegatedInstance != null) {
delegatedProperties.addAll(getProperties(delegatedInstance, annotationToFilterBy?.java, false).properties)
allKotlinProperties.remove(it)
}
}
val firstLevelProperties = allKotlinProperties.filterIsInstance(KMutableProperty::class.java)
if (annotationToFilterBy == null) {
return Properties(firstLevelProperties.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
return Properties(
firstLevelProperties.filter { it.isAnnotated(annotationToFilterBy) }.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Property marked with it is not considered to be [Property] by itself, but class with properties instead.
* Following structure is example:
* class User:
* +familyName: String
* +lastName: String
* +credentials: Credentials
*
* class Credentials:
* +login: String
* +password: String
*
* Property credentials here is [DelegationProperty]. It can be val, but all other properties should be var
*/
annotation class DelegationProperty | apache-2.0 | 7773631f4887f9bfcab4537d0a5cb623 | 36.00578 | 144 | 0.745509 | 4.526874 | false | false | false | false |
holgerbrandl/kscript | src/main/kotlin/kscript/app/resolver/DependencyResolver.kt | 1 | 3193 | package kscript.app.resolver
import kotlinx.coroutines.runBlocking
import kscript.app.model.Dependency
import kscript.app.model.Repository
import kscript.app.util.Logger.devMsg
import kscript.app.util.Logger.infoMsg
import kscript.app.shell.OsPath
import kscript.app.shell.extension
import kscript.app.shell.toOsPath
import kotlin.collections.set
import kotlin.script.experimental.api.valueOr
import kotlin.script.experimental.dependencies.CompoundDependenciesResolver
import kotlin.script.experimental.dependencies.FileSystemDependenciesResolver
import kotlin.script.experimental.dependencies.RepositoryCoordinates
import kotlin.script.experimental.dependencies.impl.makeExternalDependenciesResolverOptions
import kotlin.script.experimental.dependencies.maven.MavenDependenciesResolver
class DependencyResolver(private val customRepos: Set<Repository>) {
private val mvnResolver = MavenDependenciesResolver().apply {
addRepository(RepositoryCoordinates("https://repo.maven.apache.org/maven2"))
customRepos.map {
val options = mutableMapOf<String, String>()
if (it.password.isNotBlank() && it.user.isNotBlank()) {
options["username"] = it.user
options["password"] = it.password
}
infoMsg("Adding repository: $it")
//Adding custom repository removes MavenCentral, so it must be re-added below
addRepository(RepositoryCoordinates(it.url), makeExternalDependenciesResolverOptions(options))
}
}
private val resolver =
CompoundDependenciesResolver(FileSystemDependenciesResolver(), MavenDependenciesResolver(), mvnResolver)
fun resolve(depIds: Set<Dependency>): Set<OsPath> {
val resolvedDependencies = runBlocking {
depIds.map {
infoMsg("Resolving ${it.value}...")
val start = System.currentTimeMillis()
val resolved = resolver.resolve(it.value)
devMsg("Resolved in: ${System.currentTimeMillis() - start}")
resolved
}
}.asSequence().map { result ->
result.valueOr { failure ->
val details = failure.reports.joinToString("\n") { scriptDiagnostic ->
scriptDiagnostic.exception?.stackTraceToString() ?: scriptDiagnostic.message
}
val firstException =
failure.reports.find { scriptDiagnostic -> scriptDiagnostic.exception != null }?.exception
throw IllegalStateException(exceptionMessage + "\n" + details, firstException)
}
}.flatten().map {
it.toOsPath()
}.filter {
it.extension == "jar"
}.toSet()
return resolvedDependencies
}
companion object {
//@formatter:off
private const val exceptionMessage =
"Failed while connecting to the server. Check the connection (http/https, port, proxy, credentials, etc.)" +
"of your maven dependency locators. If you suspect this is a bug, " +
"you can create an issue on https://github.com/holgerbrandl/kscript"
//@formatter:on
}
}
| mit | 8cc1b4ad7eb3e302d1f6428b051201fe | 39.935897 | 117 | 0.672095 | 5.092504 | false | false | false | false |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/ui/search/SearchFragment.kt | 1 | 7449 | package ru.ustimov.weather.ui.search
import android.os.Bundle
import android.support.annotation.Size
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.globusltd.recyclerview.datasource.ListDatasource
import com.globusltd.recyclerview.view.ItemClickHelper
import kotlinx.android.extensions.CacheImplementation
import kotlinx.android.extensions.ContainerOptions
import kotlinx.android.synthetic.main.fragment_search.*
import ru.ustimov.weather.R
import ru.ustimov.weather.appState
import ru.ustimov.weather.content.ImageLoaderFactory
import ru.ustimov.weather.content.data.City
import ru.ustimov.weather.content.data.Favorite
import ru.ustimov.weather.content.data.SearchResult
import ru.ustimov.weather.content.data.Suggestion
import ru.ustimov.weather.rx.RxLifecycleFragment
import ru.ustimov.weather.rx.RxSearchView
import ru.ustimov.weather.ui.EmptyViewInfoFactory
@ContainerOptions(CacheImplementation.SPARSE_ARRAY)
class SearchFragment : RxLifecycleFragment(), SearchView {
companion object Factory {
fun create(): SearchFragment = SearchFragment()
}
@InjectPresenter
lateinit var presenter: SearchPresenter
private lateinit var suggestionsDatasource: ListDatasource<Suggestion>
private lateinit var suggestionsAdapter: SuggestionsAdapter
private lateinit var searchResultsDatasource: ListDatasource<SearchResult>
private lateinit var searchResultsAdapter: SearchResultsAdapter
private val actions = EmptyViewInfoFactory.Actions(
doOnDatabaseException = this::onDatabaseExceptionTryAgainClick,
doOnNetworkException = this::onNetworkExceptionTryAgainClick,
doOnUnknownException = this::onUnknownExceptionTryAgainClick
)
@ProvidePresenter
fun provideSearchPresenter(): SearchPresenter {
val appState = context.appState()
return SearchPresenter(appState)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View =
inflater!!.inflate(R.layout.fragment_search, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
suggestionsDatasource = ListDatasource()
suggestionsAdapter = SuggestionsAdapter(suggestionsDatasource)
searchView.shouldShowProgress = false
searchView.adapter = suggestionsAdapter
searchView.setSearchItemAnimator(DefaultItemAnimator())
val suggestionsRecyclerView = searchView.findViewById<RecyclerView>(R.id.search_recyclerView)
val suggestionsItemClickHelper = ItemClickHelper<Suggestion>(suggestionsAdapter)
suggestionsItemClickHelper.setOnItemClickListener({ _, item, _ -> onSuggestionClick(item) })
suggestionsItemClickHelper.setRecyclerView(suggestionsRecyclerView)
val imageLoader = ImageLoaderFactory.create(this)
searchResultsDatasource = ListDatasource()
searchResultsAdapter = SearchResultsAdapter(searchResultsDatasource, imageLoader)
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.addItemDecoration(SearchResultsItemDecoration(context))
recyclerView.adapter = searchResultsAdapter
val searchResultsItemClickHelper = ItemClickHelper<SearchResult>(searchResultsAdapter)
searchResultsItemClickHelper.setOnItemClickListener({ v, item, _ -> onSearchResultClick(v, item) })
searchResultsItemClickHelper.setRecyclerView(recyclerView)
}
private fun onSuggestionClick(item: Suggestion): Boolean {
searchView.setQuery(item.text(), true)
searchView.hideKeyboard()
return true
}
private fun onSearchResultClick(view: View?, item: SearchResult): Boolean =
when (view?.id) {
R.id.actionToggleFavoritesView -> onActionToggleFavoritesClick(item.city)
else -> false
}
private fun onActionToggleFavoritesClick(city: City) =
if (searchResultsAdapter.isFavorite(city)) {
presenter.removeFromFavorites(city)
} else {
presenter.addToFavorites(city)
}
override fun onResume() {
super.onResume()
RxSearchView.onQueryTextChanged(searchView)
.doOnNext({ if (it.submit) searchView.hideKeyboard() })
.doOnNext({ presenter.onQueryChanged(it.query, it.submit) })
.compose(bindUntil(Event.PAUSE))
.subscribeOn(context.appState().schedulers.mainThread())
.subscribe()
}
override fun onFavoritesLoaded(favorites: List<Favorite>) {
searchResultsAdapter.favorites = favorites
}
override fun showSuggestions(query: String, suggestions: List<Suggestion>) {
suggestionsAdapter.query = query
suggestionsDatasource.clear()
suggestionsDatasource.addAll(suggestions)
searchView.showSuggestions()
searchView.setShadow(suggestions.isNotEmpty())
}
override fun hideSuggestions() {
suggestionsAdapter.query = ""
searchView.setShadow(false)
searchView.hideSuggestions()
suggestionsDatasource.clear()
}
override fun showLoading() = searchView.showProgress()
override fun showEmpty(query: String) {
searchResultsDatasource.clear()
val placeholder = context.getText(R.string.empty_search_results_for_query_x) as String
val source = String.format(placeholder, query)
emptyView.text = Html.fromHtml(source)
emptyView.action = context.getString(R.string.action_try_again)
emptyView.onActionButtonClickListener = this::onTryAgainClick
recyclerView.visibility = View.GONE
emptyView.visibility = View.VISIBLE
}
private fun onTryAgainClick() {
emptyView.visibility = View.GONE
searchView.showKeyboard()
searchView.setQuery("", false)
}
override fun showSearchResults(@Size(min = 1) searchResults: List<SearchResult>) {
searchResultsDatasource.clear()
searchResultsDatasource.addAll(searchResults)
emptyView.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
}
override fun showError(throwable: Throwable) {
val info = EmptyViewInfoFactory.fromThrowable(context, throwable, actions)
info.apply(emptyView)
recyclerView.visibility = View.GONE
emptyView.visibility = View.VISIBLE
}
private fun onDatabaseExceptionTryAgainClick() {
emptyView.visibility = View.GONE
searchView.setQuery(searchView.query, false)
}
private fun onNetworkExceptionTryAgainClick() {
emptyView.visibility = View.GONE
searchView.setQuery(searchView.query, true)
}
private fun onUnknownExceptionTryAgainClick() {
emptyView.visibility = View.GONE
searchView.setQuery(searchView.query, false)
}
override fun hideLoading() = searchView.hideProgress()
} | apache-2.0 | 6b9a0b2adb6fdc5308b386786d3db879 | 37.402062 | 107 | 0.728017 | 5.253173 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/io/ByteWriter.kt | 1 | 3236 | package asmble.io
import asmble.util.unsignedToSignedInt
import asmble.util.unsignedToSignedLong
import java.io.ByteArrayOutputStream
import java.math.BigInteger
abstract class ByteWriter {
abstract val written: Int
// Parameter will have been created via createTemp
abstract fun write(v: ByteWriter)
abstract fun writeByte(v: Byte)
abstract fun writeBytes(v: ByteArray)
abstract fun createTemp(): ByteWriter
fun writeUInt32(v: Long) {
v.unsignedToSignedInt().also {
writeByte(it.toByte())
writeByte((it shr 8).toByte())
writeByte((it shr 16).toByte())
writeByte((it shr 24).toByte())
}
}
fun writeUInt64(v: BigInteger) {
v.unsignedToSignedLong().also {
writeByte(it.toByte())
writeByte((it shr 8).toByte())
writeByte((it shr 16).toByte())
writeByte((it shr 24).toByte())
writeByte((it shr 32).toByte())
writeByte((it shr 40).toByte())
writeByte((it shr 48).toByte())
writeByte((it shr 56).toByte())
}
}
fun writeVarInt7(v: Byte) {
writeSignedLeb128(v.toLong())
}
fun writeVarInt32(v: Int) {
writeSignedLeb128(v.toLong())
}
fun writeVarInt64(v: Long) {
writeSignedLeb128(v)
}
fun writeVarUInt1(v: Boolean) {
writeUnsignedLeb128(if (v) 1 else 0)
}
fun writeVarUInt7(v: Short) {
writeUnsignedLeb128(v.toLong().unsignedToSignedInt())
}
fun writeVarUInt32(v: Long) {
writeUnsignedLeb128(v.unsignedToSignedInt())
}
protected fun writeUnsignedLeb128(v: Int) {
// Taken from Android source, Apache licensed
var v = v
var remaining = v ushr 7
while (remaining != 0) {
val byte = (v and 0x7f) or 0x80
writeByte(byte.toByte())
v = remaining
remaining = remaining ushr 7
}
val byte = v and 0x7f
writeByte(byte.toByte())
}
protected fun writeSignedLeb128(v: Long) {
// Taken from Android source, Apache licensed
var v = v
var remaining = v shr 7
var hasMore = true
val end = if (v and Long.MIN_VALUE == 0L) 0L else -1L
while (hasMore) {
hasMore = remaining != end || remaining and 1 != (v shr 6) and 1
val byte = ((v and 0x7f) or if (hasMore) 0x80 else 0).toInt()
writeByte(byte.toByte())
v = remaining
remaining = remaining shr 7
}
}
class OutputStream(val os: java.io.OutputStream) : ByteWriter() {
override var written = 0; private set
override fun write(v: ByteWriter) {
if (v !is OutputStream || v.os !is ByteArrayOutputStream) error("Writer not created from createTemp")
v.os.writeTo(os)
written += v.os.size()
}
override fun writeByte(v: Byte) {
os.write(v.toInt())
written++
}
override fun writeBytes(v: ByteArray) {
os.write(v)
written += v.size
}
override fun createTemp() = OutputStream(ByteArrayOutputStream())
}
} | mit | 7fd2d614e5aae908fb2651b917286158 | 27.646018 | 113 | 0.57293 | 4.154044 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.