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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
charlesmadere/smash-ranks-android
|
smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/DeleteFavoritePlayersPreferenceView.kt
|
1
|
1803
|
package com.garpr.android.features.settings
import android.content.Context
import android.content.DialogInterface
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.garpr.android.R
import com.garpr.android.features.common.views.SimplePreferenceView
import java.text.NumberFormat
class DeleteFavoritePlayersPreferenceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SimplePreferenceView(context, attrs), DialogInterface.OnClickListener, View.OnClickListener {
var listener: Listener? = null
interface Listener {
fun onDeleteFavoritePlayersClick(v: DeleteFavoritePlayersPreferenceView)
}
companion object {
private val NUMBER_FORMAT = NumberFormat.getIntegerInstance()
}
init {
setLoading()
setOnClickListener(this)
}
override fun onClick(dialog: DialogInterface, which: Int) {
listener?.onDeleteFavoritePlayersClick(this)
}
override fun onClick(v: View) {
AlertDialog.Builder(context)
.setMessage(R.string.are_you_sure_you_want_to_delete_all_of_your_favorite_players)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.yes, this)
.show()
}
fun setContent(size: Int) {
isEnabled = size >= 1
titleText = resources.getText(R.string.delete_all_favorite_players)
descriptionText = resources.getQuantityString(R.plurals.x_favorites, size,
NUMBER_FORMAT.format(size))
}
fun setLoading() {
isEnabled = false
titleText = resources.getText(R.string.loading_favorite_players_)
descriptionText = resources.getText(R.string.please_wait_)
}
}
|
unlicense
|
1ec0a5ea9cff596fd0d6007e42d404e4
| 30.631579 | 98 | 0.697726 | 4.623077 | false | false | false | false |
blackbbc/Tucao
|
app/src/main/kotlin/me/sweetll/tucao/business/video/viewmodel/VideoViewModel.kt
|
1
|
6288
|
package me.sweetll.tucao.business.video.viewmodel
import android.annotation.SuppressLint
import androidx.databinding.ObservableField
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.sweetll.tucao.AppApplication
import me.sweetll.tucao.base.BaseViewModel
import me.sweetll.tucao.model.json.Part
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.business.video.VideoActivity
import me.sweetll.tucao.di.service.ApiConfig
import me.sweetll.tucao.extension.*
import me.sweetll.tucao.model.xml.Durl
import me.sweetll.tucao.rxdownload.entity.DownloadStatus
import java.io.File
import java.io.FileOutputStream
class VideoViewModel(val activity: VideoActivity): BaseViewModel() {
val video = ObservableField<Video>()
var playUrlDisposable: Disposable? = null
var danmuDisposable: Disposable? = null
var currentPlayerId: String? = null
constructor(activity: VideoActivity, video: Video) : this(activity) {
this.video.set(video)
}
@SuppressLint("CheckResult")
fun queryVideo(hid: String) {
jsonApiService.view(hid)
.bindToLifecycle(activity)
.sanitizeJson()
.subscribe({
video ->
this.video.set(video)
activity.loadVideo(video)
}, {
error ->
error.printStackTrace()
activity.binding.player.loadText?.let {
it.text = it.text.replace("获取视频信息...".toRegex(), "获取视频信息...[失败]")
}
})
}
fun queryPlayUrls(hid: String, part: Part) {
if (playUrlDisposable != null && !playUrlDisposable!!.isDisposed) {
playUrlDisposable!!.dispose()
}
if (danmuDisposable != null && !danmuDisposable!!.isDisposed) {
danmuDisposable!!.dispose()
}
if (part.flag == DownloadStatus.COMPLETED) {
activity.loadDurls(part.durls)
} else if (part.file.isNotEmpty()) {
if ("clicli" !in part.file) {
// 这个视频是直传的
activity.loadDurls(mutableListOf(Durl(url = part.file)))
} else {
// 这个视频来自clicli
playUrlDisposable = jsonApiService.clicli(part.file)
.bindToLifecycle(activity)
.subscribeOn(Schedulers.io())
.flatMap {
clicli ->
if (clicli.code == 0) {
Observable.just(clicli.url)
} else {
Observable.error(Throwable("请求视频接口出错"))
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
url ->
activity.loadDurls(mutableListOf(Durl(url=url)))
}, {
error ->
error.printStackTrace()
activity.binding.player.loadText?.let {
it.text = it.text.replace("解析视频地址...".toRegex(), "解析视频地址...[失败]")
}
})
}
} else {
playUrlDisposable = xmlApiService.playUrl(part.type, part.vid, System.currentTimeMillis() / 1000)
.bindToLifecycle(activity)
.subscribeOn(Schedulers.io())
.flatMap {
response ->
if (response.durls.isNotEmpty()) {
Observable.just(response.durls)
} else {
Observable.error(Throwable("请求视频接口出错"))
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
duals ->
activity.loadDurls(duals)
}, {
error ->
error.printStackTrace()
activity.binding.player.loadText?.let {
it.text = it.text.replace("解析视频地址...".toRegex(), "解析视频地址...[失败]")
}
})
}
currentPlayerId = ApiConfig.generatePlayerId(hid, part.order)
danmuDisposable = rawApiService.danmu(currentPlayerId!!, System.currentTimeMillis() / 1000)
.bindToLifecycle(activity)
.subscribeOn(Schedulers.io())
.map {
responseBody ->
val outputFile = File.createTempFile("tucao", ".xml", AppApplication.get().cacheDir)
val outputStream = FileOutputStream(outputFile)
outputStream.write(responseBody.bytes())
outputStream.flush()
outputStream.close()
outputFile.absolutePath
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
uri ->
activity.loadDanmuUri(uri)
}, {
error ->
error.printStackTrace()
activity.binding.player.loadText?.let {
it.text = it.text.replace("全舰弹幕装填...".toRegex(), "全舰弹幕装填...[失败]")
}
})
}
fun sendDanmu(stime: Float, message: String) {
currentPlayerId?.let {
rawApiService.sendDanmu(it, it, stime, message)
.bindToLifecycle(activity)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
// 发送成功
}, Throwable::printStackTrace)
}
}
}
|
mit
|
e122adc3ab922171e9c2b327d70d4553
| 38.406452 | 109 | 0.501637 | 5.265517 | false | false | false | false |
msebire/intellij-community
|
plugins/git4idea/src/git4idea/branch/DeepComparator.kt
|
1
|
13624
|
// 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 git4idea.branch
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.JBPoint
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.ui.AbstractVcsLogUi
import com.intellij.vcs.log.ui.highlighters.MergeCommitsHighlighter
import com.intellij.vcs.log.ui.highlighters.VcsLogHighlighterFactory
import com.intellij.vcs.log.util.*
import com.intellij.vcs.log.visible.VisiblePack
import git4idea.GitBranch
import git4idea.GitUtil
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import gnu.trove.TIntHashSet
import org.jetbrains.annotations.CalledInAwt
class DeepComparator(private val project: Project,
private val repositoryManager: GitRepositoryManager,
private val vcsLogData: VcsLogData,
private val ui: VcsLogUi,
parent: Disposable) : VcsLogHighlighter, Disposable {
private val storage
get() = vcsLogData.storage
private var progressIndicator: ProgressIndicator? = null
private var comparedBranch: String? = null
private var repositoriesWithCurrentBranches: Map<GitRepository, GitBranch>? = null
private var nonPickedCommits: TIntHashSet? = null
init {
Disposer.register(parent, this)
}
override fun getStyle(commitId: Int, commitDetails: VcsShortCommitDetails, isSelected: Boolean): VcsLogHighlighter.VcsCommitStyle {
if (nonPickedCommits == null || nonPickedCommits!!.contains(commitId)) return VcsLogHighlighter.VcsCommitStyle.DEFAULT
else return VcsCommitStyleFactory.foreground(MergeCommitsHighlighter.MERGE_COMMIT_FOREGROUND)
}
override fun update(dataPack: VcsLogDataPack, refreshHappened: Boolean) {
if (comparedBranch == null) { // no branch is selected => not interested in refresh events
return
}
val singleFilteredBranch = VcsLogUtil.getSingleFilteredBranch(dataPack.filters, dataPack.refs)
if (comparedBranch != singleFilteredBranch) {
LOG.debug("Branch filter changed. Compared branch: $comparedBranch, filtered branch: $singleFilteredBranch")
stopTaskAndUnhighlight()
notifyUnhighlight()
return
}
if (refreshHappened) {
stopTask()
// highlight again
val repositories = getRepositories(dataPack.logProviders, comparedBranch!!)
if (repositories == repositoriesWithCurrentBranches) {
// but not if current branch changed
startTask(dataPack)
}
else {
LOG.debug("Repositories with current branches changed. Actual:\n$repositories\nExpected:\n$repositoriesWithCurrentBranches")
unhighlight()
}
}
}
@CalledInAwt
fun startTask(dataPack: VcsLogDataPack, branchToCompare: String) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (comparedBranch != null) {
LOG.error("Already comparing with branch $comparedBranch")
return
}
val repositories = getRepositories(ui.dataPack.logProviders, branchToCompare)
if (repositories.isEmpty()) {
LOG.debug("Could not find suitable repositories for selected branch $comparedBranch")
return
}
comparedBranch = branchToCompare
repositoriesWithCurrentBranches = repositories
startTask(dataPack)
}
@CalledInAwt
fun stopTaskAndUnhighlight() {
ApplicationManager.getApplication().assertIsDispatchThread()
stopTask()
unhighlight()
}
@CalledInAwt
fun hasHighlightingOrInProgress(): Boolean {
ApplicationManager.getApplication().assertIsDispatchThread()
return comparedBranch != null
}
private fun startTask(dataPack: VcsLogDataPack) {
LOG.debug("Highlighting requested for $repositoriesWithCurrentBranches")
val task = MyTask(repositoriesWithCurrentBranches!!, dataPack, comparedBranch!!)
progressIndicator = BackgroundableProcessIndicator(task)
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, progressIndicator!!)
}
private fun stopTask() {
if (progressIndicator != null) {
progressIndicator!!.cancel()
progressIndicator = null
}
}
private fun unhighlight() {
nonPickedCommits = null
comparedBranch = null
repositoriesWithCurrentBranches = null
}
private fun getRepositories(providers: Map<VirtualFile, VcsLogProvider>,
branchToCompare: String): Map<GitRepository, GitBranch> {
return providers.keys.mapNotNull { repositoryManager.getRepositoryForRoot(it) }.filter { repository ->
repository.currentBranch != null &&
repository.branches.findBranchByName(branchToCompare) != null
}.associate { Pair(it, it.currentBranch!!) }
}
private fun notifyUnhighlight() {
if (ui is AbstractVcsLogUi) {
val balloon = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(HIGHLIGHTING_CANCELLED, null, MessageType.INFO.popupBackground, null)
.setFadeoutTime(5000)
.createBalloon()
val component = ui.table
balloon.show(RelativePoint(component, JBPoint(component.width / 2, component.visibleRect.y)), Balloon.Position.below)
Disposer.register(this, balloon)
}
}
override fun dispose() {
stopTaskAndUnhighlight()
}
private inner class MyTask(private val repositoriesWithCurrentBranches: Map<GitRepository, GitBranch>,
vcsLogDataPack: VcsLogDataPack,
private val comparedBranch: String) :
Task.Backgroundable(project, "Comparing Branches...") {
private val dataPack = (vcsLogDataPack as? VisiblePack)?.dataPack as? DataPack
private val collectedNonPickedCommits = TIntHashSet()
private var exception: VcsException? = null
override fun run(indicator: ProgressIndicator) {
try {
repositoriesWithCurrentBranches.forEach { repo, currentBranch ->
val commits = if (Registry.`is`("git.log.use.index.for.picked.commits.highlighting")) {
if (Registry.`is`("git.log.fast.picked.commits.highlighting")) {
getCommitsByIndexFast(repo.root, comparedBranch) ?: getCommitsByIndexReliable(repo.root, comparedBranch, currentBranch.name)
}
else {
getCommitsByIndexReliable(repo.root, comparedBranch, currentBranch.name)
}
}
else {
getCommitsByPatch(repo.root, comparedBranch, currentBranch.name)
}
TroveUtil.addAll(collectedNonPickedCommits, commits)
}
}
catch (e: VcsException) {
LOG.warn(e)
exception = e
}
}
override fun onFinished() {
progressIndicator = null
}
override fun onSuccess() {
if (exception != null) {
nonPickedCommits = null
VcsNotifier.getInstance(project).notifyError("Couldn't compare with branch $comparedBranch", exception!!.message)
return
}
nonPickedCommits = collectedNonPickedCommits
}
private fun getCommitsByPatch(root: VirtualFile,
targetBranch: String,
sourceBranch: String): TIntHashSet {
return measureTimeMillis(root, "Getting non picked commits with git") {
getCommitsFromGit(root, targetBranch, sourceBranch)
}
}
private fun getCommitsByIndexReliable(root: VirtualFile, sourceBranch: String, targetBranch: String): TIntHashSet {
val resultFromGit = getCommitsByPatch(root, targetBranch, sourceBranch)
val resultFromIndex = measureTimeMillis(root, "Getting non picked commits with index reliable") {
val sourceBranchRef = dataPack?.refsModel?.findBranch(sourceBranch, root) ?: return resultFromGit
val targetBranchRef = dataPack.refsModel.findBranch(GitUtil.HEAD, root) ?: return resultFromGit
getCommitsFromIndex(dataPack, root, sourceBranchRef, targetBranchRef, resultFromGit, true)
}
return resultFromIndex ?: resultFromGit
}
private fun getCommitsByIndexFast(root: VirtualFile, sourceBranch: String): TIntHashSet? {
if (!vcsLogData.index.isIndexed(root)) return null
return measureTimeMillis(root, "Getting non picked commits with index fast") {
val sourceBranchRef = dataPack?.refsModel?.findBranch(sourceBranch, root) ?: return null
val targetBranchRef = dataPack.refsModel.findBranch(GitUtil.HEAD, root) ?: return null
val sourceBranchCommits = dataPack.subgraphDifference(sourceBranchRef, targetBranchRef, storage) ?: return null
getCommitsFromIndex(dataPack, root, sourceBranchRef, targetBranchRef, sourceBranchCommits, false)
}
}
@Throws(VcsException::class)
private fun getCommitsFromGit(root: VirtualFile,
currentBranch: String,
comparedBranch: String): TIntHashSet {
val handler = GitLineHandler(project, root, GitCommand.CHERRY)
handler.addParameters(currentBranch, comparedBranch) // upstream - current branch; head - compared branch
val pickedCommits = TIntHashSet()
handler.addLineListener { l, _ ->
var line = l
// + 645caac042ff7fb1a5e3f7d348f00e9ceea5c317
// - c3b9b90f6c26affd7e597ebf65db96de8f7e5860
if (line.startsWith("+")) {
try {
line = line.substring(2).trim { it <= ' ' }
val firstSpace = line.indexOf(' ')
if (firstSpace > 0) {
line = line.substring(0, firstSpace) // safety-check: take just the first word for sure
}
pickedCommits.add(storage.getCommitIndex(HashImpl.build(line), root))
}
catch (e: Exception) {
LOG.error("Couldn't parse line [$line]")
}
}
}
Git.getInstance().runCommandWithoutCollectingOutput(handler)
return pickedCommits
}
private fun getCommitsFromIndex(dataPack: DataPack?, root: VirtualFile,
sourceBranchRef: VcsRef, targetBranchRef: VcsRef,
sourceBranchCommits: TIntHashSet, reliable: Boolean): TIntHashSet? {
if (dataPack == null) return null
if (sourceBranchCommits.isEmpty) return sourceBranchCommits
if (!vcsLogData.index.isIndexed(root)) return null
val dataGetter = vcsLogData.index.dataGetter ?: return null
val targetBranchCommits = dataPack.subgraphDifference(targetBranchRef, sourceBranchRef, storage) ?: return null
if (targetBranchCommits.isEmpty) return sourceBranchCommits
val match = dataGetter.match(root, sourceBranchCommits, targetBranchCommits, reliable)
TroveUtil.removeAll(sourceBranchCommits, match)
if (!match.isEmpty) {
LOG.debug("Using index, detected ${match.size()} commits in ${sourceBranchRef.name}#${root.name}" +
" that were picked to the current branch" +
(if (reliable) " with different patch id but matching cherry-picked suffix"
else " with matching author, author time and message"))
}
return sourceBranchCommits
}
override fun toString(): String {
return "Task for '$comparedBranch' in $repositoriesWithCurrentBranches"
}
}
class Factory : VcsLogHighlighterFactory {
override fun createHighlighter(logDataManager: VcsLogData, logUi: VcsLogUi): VcsLogHighlighter {
return getInstance(logDataManager.project, logDataManager, logUi)
}
override fun getId(): String {
return "CHERRY_PICKED_COMMITS"
}
override fun getTitle(): String {
return "Cherry Picked Commits"
}
override fun showMenuItem(): Boolean {
return false
}
}
companion object {
private val LOG = Logger.getInstance(DeepComparator::class.java)
private const val HIGHLIGHTING_CANCELLED = "Highlighting of non-picked commits has been cancelled"
@JvmStatic
fun getInstance(project: Project, dataProvider: VcsLogData, logUi: VcsLogUi): DeepComparator {
return ServiceManager.getService(project, DeepComparatorHolder::class.java).getInstance(dataProvider, logUi)
}
}
private inline fun <R> measureTimeMillis(root: VirtualFile, actionName: String, block: () -> R): R {
val start = System.currentTimeMillis()
val result = block()
if (result != null) {
LOG.debug("$actionName took ${StopWatch.formatTime(System.currentTimeMillis() - start)} for ${root.name}")
}
return result
}
}
|
apache-2.0
|
a0440700bc7f963ef6f7e1f10e6ae75c
| 38.956012 | 140 | 0.706474 | 4.814134 | false | false | false | false |
msebire/intellij-community
|
platform/credential-store/src/NativeCredentialStoreWrapper.kt
|
1
|
4609
|
// 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.credentialStore
import com.google.common.cache.CacheBuilder
import com.intellij.credentialStore.keePass.InMemoryCredentialStore
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.util.containers.ContainerUtil
import java.util.concurrent.TimeUnit
internal val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup("Password Safe", NotificationDisplayType.STICKY_BALLOON, true), NotificationType.ERROR)
}
// used only for native keychains, not for KeePass, so, postponedCredentials and other is not overhead if KeePass is used
private class NativeCredentialStoreWrapper(private val store: CredentialStore) : CredentialStore {
private val fallbackStore = lazy { InMemoryCredentialStore() }
private val queueProcessor = QueueProcessor<() -> Unit> { it() }
private val postponedCredentials = InMemoryCredentialStore()
private val postponedRemovedCredentials = ContainerUtil.newConcurrentSet<CredentialAttributes>()
private val deniedItems = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<CredentialAttributes, Boolean>()
override fun get(attributes: CredentialAttributes): Credentials? {
if (postponedRemovedCredentials.contains(attributes)) {
return null
}
postponedCredentials.get(attributes)?.let {
return it
}
if (deniedItems.getIfPresent(attributes) != null) {
LOG.warn("User denied access to $attributes")
return null
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
val value = store.get(attributes)
if (value === ACCESS_TO_KEY_CHAIN_DENIED) {
deniedItems.put(attributes, true)
}
return value
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
return
}
if (credentials == null) {
postponedRemovedCredentials.add(attributes)
}
else {
postponedCredentials.set(attributes, credentials)
}
queueProcessor.add {
try {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
}
catch (e: ProcessCanceledException) {
throw e
}
finally {
if (!postponedRemovedCredentials.remove(attributes)) {
postponedCredentials.set(attributes, null)
}
}
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = "Credentials are remembered until ${ApplicationNamesInfo.getInstance().fullProductName} is closed."
if (SystemInfo.isLinux) {
message += "\nPlease install required package libsecret-1-0: sudo apt-get install libsecret-1-0 gnome-keyring"
}
NOTIFICATION_MANAGER.notify("Cannot Access Native Keychain", message)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (isMacOsCredentialStoreSupported) {
return NativeCredentialStoreWrapper(KeyChainCredentialStore())
}
return null
}
}
private class LinuxSecretCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (SystemInfo.isLinux) {
return NativeCredentialStoreWrapper(SecretCredentialStore("com.intellij.credentialStore.Credential"))
}
return null
}
}
|
apache-2.0
|
3f15d1c11eda1fdb14d56da94152a403
| 34.461538 | 140 | 0.731829 | 4.771222 | false | false | false | false |
langara/USpek
|
ktjsreactsample/src/jsMain/kotlin/playground/Playground.kt
|
1
|
1789
|
package playground
import csstype.*
import react.*
import react.dom.*
import kotlinx.coroutines.*
import painting.clearCanvas
import painting.paintSomething
import painting.pickColor
import pl.mareklangiewicz.uspek.*
import react.dom.html.ReactHTML.canvas
import react.dom.html.ReactHTML.div
external interface PlaygroundProps : Props { var speed: Int }
val Playground = FC<PlaygroundProps> { props ->
var tree by useState(GlobalUSpekContext.root)
useEffect {
uspekLog = {
println(it.status)
// we don't need any setState here because tree is useState hook delegate property
tree = GlobalUSpekContext.root.copy() // FIXME: is copy needed? check (and debug!) how react compares states
paintSomething()
if (it.finished) clearCanvas()
}
// FIXME: We should have scope cancelling when leaving playground
MainScope().launch {
delay(500) // temporary delay for experiments
example()
paintSomething()
}
}
div {
className = ClassName("playground")
div { className = ClassName("tests-side"); rtree(tree) }
div {
className = ClassName("canvas-side")
div {
className = ClassName("canvas")
canvas {
onClick = {
val event = it.asDynamic()
val color = pickColor(event.clientX - event.target.offsetLeft, event.clientY - event.target.offsetTop)
// TODO: check what clientX/Y is
println(color)
}
}
}
}
}
}
fun RBuilder.playground(speed: Int = 400) = child(Playground) { attrs.speed = speed }
|
apache-2.0
|
20a92a13b88eaf3bb74f305a83235a20
| 31.527273 | 126 | 0.585802 | 4.683246 | false | false | false | false |
krischik/Fit-Import
|
app/src/androidTest/kotlin/com.krischik/package.kt
|
1
|
1507
|
/********************************************************** {{{1 ***********
* Copyright © 2015 … 2016 "Martin Krischik" «[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/
********************************************************** }}}1 **********/
package com.krischik
/**
* make sleep command more readable
* @param Second time in seconds
* @return time in milli seconds
*/
fun Second (Second: Float): Int = (Second * 1000).toInt()
/**
* make sleep command more readable
* @param Minutes time in minutes
* @return time in milli seconds
*/
fun Minutes (Minutes: Float) :Int = (Minutes * 1000 * 60).toInt()
// vim: set nowrap tabstop=8 shiftwidth=3 softtabstop=3 expandtab textwidth=96 :
// vim: set fileencoding=utf-8 filetype=kotlin foldmethod=marker spell spelllang=en_gb :
|
gpl-3.0
|
3a30cf03269e516de659b668561ed087
| 43.176471 | 88 | 0.61984 | 4.207283 | false | false | false | false |
kohesive/kovert
|
vertx-example/src/main/kotlin/uy/kohesive/kovert/vertx/sample/web/PublicWebController.kt
|
1
|
1002
|
package uy.kohesive.kovert.vertx.sample.web
import uy.kohesive.kovert.core.HttpRedirect
import uy.kohesive.kovert.core.Rendered
class PublicWebController {
@Rendered("login.html.ftl")
val viewLogin = fun PublicAccess.(): EmptyModel {
if (user != null) {
throw HttpRedirect("/app") // TODO: replace with looking up HREF from a controller
}
return EmptyModel()
}
@Rendered("login.html.ftl")
val index = viewLogin
// TODO: problem here with return type of Unit, should be allowed. ALso for rendered as EmptyModel
// TODO: move EmptyModel into Kovert core
val doLogout = fun PublicAccess.(): String {
try {
if (user != null) upgradeToSecured().logout()
} catch (ex: Throwable) {
// eat exceptions during logout, why let it fail?!?
} finally {
throw HttpRedirect("/login") // TODO: change to use a reference lookup to the public web controller login page
}
}
}
|
mit
|
b6e7efbeb8a2c79fde2354789db8c1bd
| 32.4 | 122 | 0.636727 | 4.26383 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp
|
app/src/main/java/co/timetableapp/model/Assignment.kt
|
1
|
6841
|
/*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.model
import android.app.Activity
import android.content.Context
import android.database.Cursor
import android.os.Parcel
import android.os.Parcelable
import co.timetableapp.R
import co.timetableapp.data.TimetableDbHelper
import co.timetableapp.data.handler.DataNotFoundException
import co.timetableapp.data.schema.AssignmentsSchema
import co.timetableapp.model.agenda.AgendaItem
import co.timetableapp.model.home.HomeItem
import co.timetableapp.model.home.HomeItemProperties
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
/**
* Represents an assignment the user may have been given.
*
* @property classId the identifier of the [Class] this assignment is associated with
* @property title the name of the assignment
* @property detail optional, additional notes the user may enter for the assignment
* @property dueDate the date the assignment must be handed in
* @property completionProgress an integer from 0-100 (like a percentage) indicating how complete
* the assignment is (100 indicating fully complete)
*/
data class Assignment(
override val id: Int,
override val timetableId: Int,
val classId: Int,
val title: String,
val detail: String,
val dueDate: LocalDate,
var completionProgress: Int
) : TimetableItem, AgendaItem, HomeItem {
init {
if (completionProgress !in 0..100) {
throw IllegalArgumentException("the completion progress must be between 0 and 100")
}
}
companion object {
/**
* Constructs an [Assignment] using column values from the cursor provided
*
* @param cursor a query of the assignments table
* @see [AssignmentsSchema]
*/
@JvmStatic
fun from(cursor: Cursor): Assignment {
val dueDate = LocalDate.of(
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_DUE_DATE_YEAR)),
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_DUE_DATE_MONTH)),
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_DUE_DATE_DAY_OF_MONTH)))
return Assignment(
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema._ID)),
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_TIMETABLE_ID)),
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_CLASS_ID)),
cursor.getString(cursor.getColumnIndex(AssignmentsSchema.COL_TITLE)),
cursor.getString(cursor.getColumnIndex(AssignmentsSchema.COL_DETAIL)),
dueDate,
cursor.getInt(cursor.getColumnIndex(AssignmentsSchema.COL_COMPLETION_PROGRESS)))
}
/**
* Creates an [Assignment] from the [assignmentId] and corresponding data in the database.
*
* @throws DataNotFoundException if the database query returns no results
* @see from
*/
@JvmStatic
@Throws(DataNotFoundException::class)
fun create(context: Context, assignmentId: Int): Assignment {
val db = TimetableDbHelper.getInstance(context).readableDatabase
val cursor = db.query(
AssignmentsSchema.TABLE_NAME,
null,
"${AssignmentsSchema._ID}=?",
arrayOf(assignmentId.toString()),
null, null, null)
if (cursor.count == 0) {
cursor.close()
throw DataNotFoundException(this::class.java, assignmentId)
}
cursor.moveToFirst()
val assignment = Assignment.from(cursor)
cursor.close()
return assignment
}
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<Assignment> = object : Parcelable.Creator<Assignment> {
override fun createFromParcel(source: Parcel): Assignment = Assignment(source)
override fun newArray(size: Int): Array<Assignment?> = arrayOfNulls(size)
}
}
private constructor(source: Parcel) : this(
source.readInt(),
source.readInt(),
source.readInt(),
source.readString(),
source.readString(),
source.readSerializable() as LocalDate,
source.readInt()
)
fun hasDetail() = detail.trim().isNotEmpty()
fun isComplete() = completionProgress == 100
fun isOverdue() = !isComplete() && isInPast()
fun isPastAndDone() = isInPast() && isComplete()
override fun getTypeNameRes() = R.string.assignment
override fun getDisplayedTitle() = title
override fun getRelatedSubject(context: Context): Subject? {
val cls = Class.create(context, classId)
return Subject.create(context, cls.subjectId)
}
override fun getDateTime() = LocalDateTime.of(dueDate, LocalTime.MIDNIGHT)!!
override fun isInPast() = dueDate.isBefore(LocalDate.now())
override fun occursOnDate(date: LocalDate) = dueDate == date
override fun getHomeItemProperties(activity: Activity) = HomeAssignmentProperties(activity, this)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeInt(id)
dest?.writeInt(timetableId)
dest?.writeInt(classId)
dest?.writeString(title)
dest?.writeString(detail)
dest?.writeSerializable(dueDate)
dest?.writeInt(completionProgress)
}
class HomeAssignmentProperties(context: Context, assignment: Assignment) : HomeItemProperties {
private val mSubject: Subject
init {
val cls = Class.create(context, assignment.classId)
mSubject = Subject.create(context, cls.subjectId)
}
override val title = assignment.title
override val subtitle = mSubject.name
override val time = "" // TODO something better here
override val extraText = null
override val color = Color(mSubject.colorId)
}
}
|
apache-2.0
|
212446cf35909c817309c59b7d8673db
| 35.195767 | 102 | 0.65049 | 4.942919 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/user/PhysicsWorldView.kt
|
1
|
3895
|
package de.westnordost.streetcomplete.user
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.core.view.isInvisible
import androidx.core.view.updateLayoutParams
import org.jbox2d.collision.AABB
import org.jbox2d.common.Transform
import org.jbox2d.dynamics.Body
/** Draws its contained views that are connected each with a physics body at the configured
* scale and location */
class PhysicsWorldView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var offsetInMetersX = 0f
set(value) {
field = value
invalidate()
}
var offsetInMetersY = 0f
set(value) {
field = value
invalidate()
}
var pixelsPerMeter = 1f
set(value) {
field = value
invalidate()
}
private val bodies = mutableMapOf<View, Body>()
private val hasBeenSized = mutableSetOf<View>()
// reused structs to avoid new object construction in loops
private val identity = Transform()
private val aabb = AABB()
init {
setWillNotDraw(false)
}
fun addView(view: View, body: Body) {
bodies[view] = body
view.isInvisible = true
addView(view, WRAP_CONTENT, WRAP_CONTENT)
}
override fun removeView(view: View) {
bodies.remove(view)
hasBeenSized.remove(view)
super.removeView(view)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for ((view, body) in bodies.entries) {
val pixelWidth = view.width
val pixelHeight = view.height
if (pixelWidth == 0 || pixelHeight == 0) continue
val bbox = body.computeBoundingBox() ?: continue
val widthInMeters = bbox.upperBound.x - bbox.lowerBound.x
val heightInMeters = bbox.upperBound.y - bbox.lowerBound.y
val desiredPixelWidth = (widthInMeters * pixelsPerMeter).toInt()
val desiredPixelHeight = (heightInMeters * pixelsPerMeter).toInt()
if (desiredPixelHeight != pixelHeight || desiredPixelWidth != pixelWidth) {
view.updateLayoutParams {
width = desiredPixelWidth
height = desiredPixelHeight
}
}
val centerInMeters = body.position
view.x = +(centerInMeters.x - offsetInMetersX) * pixelsPerMeter - pixelWidth / 2f
// ui coordinate system: +y = down, physics coordinate system: +y = up
view.y = -(centerInMeters.y - offsetInMetersY) * pixelsPerMeter - pixelHeight / 2f + height
view.rotation = -body.angle * 180f / Math.PI.toFloat()
if (!hasBeenSized.contains(view))
hasBeenSized.add(view)
else
view.isInvisible = false
}
}
private fun Body.computeBoundingBox(): AABB? {
// this function is less computational effort than it looks: No new objects are created
// and for most bodies, it is just one fixture with one shape.
var result: AABB? = null
val identity = identity
var fixture = fixtureList
// fixtureList is an old-school C-like linked list, hence the odd iteration
while (fixture != null) {
val shape = fixture.shape
for (i in 0 until shape.childCount) {
val boundingBox = aabb
shape.computeAABB(boundingBox, identity, i)
if (result == null) result = boundingBox else result.combine(boundingBox)
}
fixture = fixture.next
}
return result
}
}
|
gpl-3.0
|
8af0dd5f1b377ac7d7376b5ec4dcb9d9
| 32.869565 | 103 | 0.618228 | 4.659091 | false | false | false | false |
androidx/androidx-ci-action
|
AndroidXCI/lib/src/test/kotlin/dev/androidx/ci/fake/FakeToolsResultApi.kt
|
1
|
1738
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.androidx.ci.fake
import com.google.common.truth.Truth.assertThat
import dev.androidx.ci.firebase.ToolsResultApi
import dev.androidx.ci.generated.testResults.History
import dev.androidx.ci.generated.testResults.ListHistoriesResponse
import java.util.UUID
internal class FakeToolsResultApi : ToolsResultApi {
private val histories = mutableListOf<History>()
override suspend fun getHistories(projectId: String, name: String?, pageSize: Int): ListHistoriesResponse {
return ListHistoriesResponse(
nextPageToken = null,
histories = histories.filter {
name == null || it.name == name
}
)
}
override suspend fun create(projectId: String, requestId: String?, history: History): History {
assertThat(
getHistories(
projectId = "",
name = history.name
).histories
).isEmpty()
val created = history.copy(
historyId = UUID.randomUUID().toString()
)
histories.add(
created
)
return created
}
}
|
apache-2.0
|
5e206f96a1d14d21da03db196c067885
| 33.078431 | 111 | 0.669735 | 4.537859 | false | false | false | false |
ursjoss/scipamato
|
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/codeclass/CodeClassListPageTest.kt
|
1
|
4566
|
package ch.difty.scipamato.core.web.codeclass
import ch.difty.scipamato.core.entity.codeclass.CodeClassDefinition
import ch.difty.scipamato.core.entity.codeclass.CodeClassTranslation
import ch.difty.scipamato.core.web.common.BasePageTest
import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.verify
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.link.Link
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
@Suppress("PrivatePropertyName", "VariableNaming")
internal class CodeClassListPageTest : BasePageTest<CodeClassListPage>() {
private val cct1_de = CodeClassTranslation(1, "de", "Name1", "a description", 1)
private val cct1_en = CodeClassTranslation(2, "en", "name1", null, 1)
private val cct1_fr = CodeClassTranslation(3, "fr", "nom1", null, 1)
private val ccd1 = CodeClassDefinition(1, "de", 1, cct1_de, cct1_en, cct1_fr)
private val cct2_en = CodeClassTranslation(5, "en", "name2", null, 1)
private val cct2_fr = CodeClassTranslation(6, "fr", "nom2", null, 1)
private val cct2_de = CodeClassTranslation(4, "de", "Name2", null, 1)
private val ccd2 = CodeClassDefinition(2, "de", 1, cct2_de, cct2_en, cct2_fr)
private val results = listOf(ccd1, ccd2)
@Suppress("LocalVariableName")
override fun setUpHook() {
every { codeClassServiceMock.countByFilter(any()) } returns results.size
every { codeClassServiceMock.findPageOfEntityDefinitions(any(), any()) } returns results.iterator()
}
@AfterEach
fun tearDown() {
confirmVerified(codeClassServiceMock)
}
override fun makePage(): CodeClassListPage = CodeClassListPage(null)
override val pageClass: Class<CodeClassListPage>
get() = CodeClassListPage::class.java
override fun assertSpecificComponents() {
assertFilterForm("filterPanel:filterForm")
val headers = arrayOf("Id", "Translations")
val values = arrayOf("1", "DE: 'Name1'; EN: 'name1'; FR: 'nom1'".replace("'", "'"))
assertResultTable("resultPanel:results", headers, values)
verify { codeClassServiceMock.countByFilter(any()) }
verify { codeClassServiceMock.findPageOfEntityDefinitions(any(), any()) }
}
@Suppress("SameParameterValue")
private fun assertFilterForm(b: String) {
tester.assertComponent(b, Form::class.java)
assertLabeledTextField(b, "name")
assertLabeledTextField(b, "description")
}
@Suppress("SameParameterValue")
private fun assertResultTable(b: String, labels: Array<String>, values: Array<String>) {
tester.assertComponent(b, BootstrapDefaultDataTable::class.java)
assertHeaderColumns(b, labels)
assertTableValuesOfRow(b, 1, COLUMN_ID_WITH_LINK, values)
}
private fun assertHeaderColumns(b: String, labels: Array<String>) {
var idx = 0
labels.forEach { label ->
tester.assertLabel(
"$b:topToolbars:toolbars:2:headers:${++idx}:header:orderByLink:header_body:label", label
)
}
}
@Suppress("SameParameterValue")
private fun assertTableValuesOfRow(b: String, rowIdx: Int, colIdxAsLink: Int?, values: Array<String>) {
if (colIdxAsLink != null)
tester.assertComponent("$b:body:rows:$rowIdx:cells:$colIdxAsLink:cell:link", Link::class.java)
var colIdx = 1
for (value in values) {
val p = "$b:body:rows:$rowIdx:cells:$colIdx:cell${if (colIdxAsLink != null && colIdx++ == colIdxAsLink) ":link:label" else ""}"
tester.assertLabel(p, value)
}
}
@Test
fun clickingOnCodeTitle_forwardsToCodeEditPage_withModelLoaded() {
tester.startPage(pageClass)
tester.clickLink("resultPanel:results:body:rows:1:cells:$COLUMN_ID_WITH_LINK:cell:link")
tester.assertRenderedPage(CodeClassEditPage::class.java)
// verify the codes were loaded into the target page
tester.assertModelValue("form:translationsPanel:translations:1:name", "Name1")
tester.assertModelValue("form:translationsPanel:translations:2:name", "name1")
tester.assertModelValue("form:translationsPanel:translations:3:name", "nom1")
verify { codeClassServiceMock.countByFilter(any()) }
verify { codeClassServiceMock.findPageOfEntityDefinitions(any(), any()) }
}
companion object {
private const val COLUMN_ID_WITH_LINK = 2
}
}
|
bsd-3-clause
|
84d1cbce0e35dca0d05301eef9a02051
| 42.485714 | 139 | 0.693605 | 3.869492 | false | true | false | false |
WindSekirun/RichUtilsKt
|
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RDeviceId.kt
|
1
|
1554
|
@file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
/**
* get androidId of device
*
* @return androidId of device
*/
@SuppressLint("HardwareIds")
fun Context.getAndroidId(): String = Settings.Secure.getString(this.contentResolver, Settings.Secure.ANDROID_ID) ?: ""
/**
* get IMEI of device
*
* this methods will grant READ_PHONE_STATE automatically if your application target SDK 23 and above.
* @return IMEI of device
*/
@SuppressLint("HardwareIds", "MissingPermission")
fun Context.getIMEI(): String {
var imei = ""
val arrays: Array<String> = arrayOf(Manifest.permission.READ_PHONE_STATE)
RPermission.instance.checkPermission(this, array = arrays, callback = { _: Int, _: List<String> ->
imei = telephonyManager.deviceId.isEmptyOrReturn()
})
return imei
}
/**
* get Line1Number (as know as PhoneNumber) of device
*
* this methods will grant READ_PHONE_STATE automatically if your application target SDK 23 and above.
* @return Line1Number of device
*/
@SuppressLint("HardwareIds", "MissingPermission")
fun Context.getLine1Number(): String {
var number = ""
val arrays: Array<String> = arrayOf(Manifest.permission.READ_PHONE_STATE)
RPermission.instance.checkPermission(this, array = arrays, callback = { _: Int, _: List<String> ->
number = telephonyManager.line1Number.isEmptyOrReturn()
})
return number
}
|
apache-2.0
|
55268abada35704ea8c63d542d85cbd7
| 28.903846 | 118 | 0.72973 | 4.025907 | false | false | false | false |
KotlinKit/Reactant
|
Core/src/main/kotlin/org/brightify/reactant/core/ControllerBase.kt
|
1
|
3086
|
package org.brightify.reactant.core
import android.content.Context
import android.view.View
import io.reactivex.Observable
import io.reactivex.rxkotlin.addTo
import org.brightify.reactant.controller.ViewController
import org.brightify.reactant.core.component.Component
import org.brightify.reactant.core.component.ComponentDelegate
import org.brightify.reactant.core.component.ComponentWithDelegate
/**
* @author <a href="mailto:[email protected]">Filip Dolnik</a>
*/
open class ControllerBase<STATE, ROOT, ROOT_ACTION>(initialState: STATE, private val rootViewFactory: (Context) -> ROOT)
: ViewController(), ComponentWithDelegate<STATE, Unit> where ROOT: View, ROOT: Component<*, ROOT_ACTION> {
final override val componentDelegate = ComponentDelegate<STATE, Unit>(initialState)
final override val action: Observable<Unit> = Observable.empty()
final override val actions: List<Observable<Unit>> = emptyList()
@Suppress("UNCHECKED_CAST")
open val rootView: ROOT
get() = view as ROOT
private val castRootView: RootView?
get() = rootView as? RootView
private var rootViewState: StateWrapper = StateWrapper.NoState
sealed class StateWrapper {
class HasState(val state: Any?): StateWrapper()
object NoState: StateWrapper()
}
init {
componentDelegate.ownerComponent = this
}
override fun needsUpdate(): Boolean = true
override fun update(previousComponentState: STATE?) {
}
override fun loadView() {
super.loadView()
val newRootView = rootViewFactory(activity)
(rootViewState as? StateWrapper.HasState)?.let { rootViewState ->
if (newRootView.componentState != rootViewState.state) {
@Suppress("UNCHECKED_CAST")
(newRootView as Component<Any?, *>).componentState = rootViewState.state
}
}
(newRootView as? ComponentView)?.init()
newRootView.observableState.subscribe { rootViewState = StateWrapper.HasState(it) }.addTo(viewLifetimeDisposeBag)
newRootView.action.subscribe { act(it) }.addTo(viewLifetimeDisposeBag)
view = newRootView
componentDelegate.needsUpdate = true
}
override fun viewWillAppear() {
super.viewWillAppear()
castRootView?.viewWillAppear()
}
override fun viewDidAppear() {
super.viewDidAppear()
componentDelegate.canUpdate = true
castRootView?.viewDidAppear()
}
override fun viewWillDisappear() {
super.viewWillDisappear()
componentDelegate.canUpdate = false
castRootView?.viewWillDisappear()
}
override fun viewDidDisappear() {
super.viewDidDisappear()
castRootView?.viewDidDisappear()
}
override fun viewDestroyed() {
super.viewDestroyed()
stateDisposeBag.clear()
(rootView as? ComponentView)?.destroy()
}
open fun act(action: ROOT_ACTION) {
}
final override fun perform(action: Unit) {
}
final override fun resetActions() {
}
}
|
mit
|
661b9c7c2b97957ec75a9059da753720
| 26.5625 | 121 | 0.683085 | 4.592262 | false | false | false | false |
chandilsachin/DietTracker
|
app/src/main/java/com/chandilsachin/diettracker/adapters/FoodListAdapter.kt
|
1
|
2787
|
package com.chandilsachin.diettracker.adapters
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.chandilsachin.diettracker.R
import com.chandilsachin.diettracker.database.DietFood
import com.chandilsachin.diettracker.database.Food
import java.util.ArrayList
/**
* Created by Sachin Chandil on 29/04/2017.
*/
class FoodListAdapter(context: Context, var onItemClick:(Long)-> Unit) :
RecyclerView.Adapter<FoodListAdapter.ViewHolder>(), Filterable {
var foodList: List<Food> = emptyList()
private var displayFoodList: ArrayList<Food> = arrayListOf()
private val inflater: LayoutInflater = LayoutInflater.from(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val holder = ViewHolder(inflater.inflate(R.layout.layout_food_list_item, parent, false))
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(displayFoodList[position])
override fun getItemCount(): Int {
return displayFoodList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textViewFoodName = itemView.findViewById(R.id.textViewFoodName) as TextView
var textViewFoodDesc = itemView.findViewById(R.id.textViewFoodDesc) as TextView
fun bind(item:Food){
textViewFoodName.text = item.foodName
textViewFoodDesc.text = item.foodDesc
itemView.setOnClickListener { onItemClick(item.id) }
}
}
override fun getFilter(): Filter {
return dietFilter;
}
val dietFilter = object : Filter() {
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
displayFoodList = results?.values as ArrayList<Food>
notifyDataSetChanged()
}
override fun performFiltering(constraint: CharSequence?): FilterResults {
displayFoodList.clear()
if (constraint == null || constraint.isEmpty()) {
displayFoodList.addAll(foodList)
} else {
for (item in foodList) {
if (item.foodName.toLowerCase().contains(constraint.toString().toLowerCase()))
displayFoodList.add(item)
}
}
var results = FilterResults()
results.values = displayFoodList
results.count = displayFoodList.size
return results
}
}
}
|
gpl-3.0
|
1cd66c41766007017efe511723a38974
| 32.8375 | 109 | 0.660567 | 4.838542 | false | false | false | false |
FHannes/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/values/UCallResultValue.kt
|
3
|
1272
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.values
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UResolvable
// Value of something resolvable (e.g. call or property access)
// that we cannot or do not want to evaluate
class UCallResultValue(val resolvable: UResolvable, val arguments: List<UValue>) : UValueBase(), UDependency {
override fun equals(other: Any?) = other is UCallResultValue && resolvable == other.resolvable && arguments == other.arguments
override fun hashCode() = resolvable.hashCode()
override fun toString(): String {
return "external ${(resolvable as? UElement)?.asRenderString() ?: "???"}(${arguments.joinToString()})"
}
}
|
apache-2.0
|
f0b7b1d5b4b632598374e5897d01b908
| 40.032258 | 130 | 0.733491 | 4.211921 | false | false | false | false |
googlesamples/mlkit
|
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/posedetector/PoseDetectorProcessor.kt
|
1
|
4336
|
/*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.vision.demo.kotlin.posedetector
import android.content.Context
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.android.odml.image.MlImage
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.demo.GraphicOverlay
import com.google.mlkit.vision.demo.java.posedetector.classification.PoseClassifierProcessor
import com.google.mlkit.vision.demo.kotlin.VisionProcessorBase
import com.google.mlkit.vision.pose.Pose
import com.google.mlkit.vision.pose.PoseDetection
import com.google.mlkit.vision.pose.PoseDetector
import com.google.mlkit.vision.pose.PoseDetectorOptionsBase
import java.util.ArrayList
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/** A processor to run pose detector. */
class PoseDetectorProcessor(
private val context: Context,
options: PoseDetectorOptionsBase,
private val showInFrameLikelihood: Boolean,
private val visualizeZ: Boolean,
private val rescaleZForVisualization: Boolean,
private val runClassification: Boolean,
private val isStreamMode: Boolean
) : VisionProcessorBase<PoseDetectorProcessor.PoseWithClassification>(context) {
private val detector: PoseDetector
private val classificationExecutor: Executor
private var poseClassifierProcessor: PoseClassifierProcessor? = null
/** Internal class to hold Pose and classification results. */
class PoseWithClassification(val pose: Pose, val classificationResult: List<String>)
init {
detector = PoseDetection.getClient(options)
classificationExecutor = Executors.newSingleThreadExecutor()
}
override fun stop() {
super.stop()
detector.close()
}
override fun detectInImage(image: InputImage): Task<PoseWithClassification> {
return detector
.process(image)
.continueWith(
classificationExecutor,
{ task ->
val pose = task.getResult()
var classificationResult: List<String> = ArrayList()
if (runClassification) {
if (poseClassifierProcessor == null) {
poseClassifierProcessor = PoseClassifierProcessor(context, isStreamMode)
}
classificationResult = poseClassifierProcessor!!.getPoseResult(pose)
}
PoseWithClassification(pose, classificationResult)
}
)
}
override fun detectInImage(image: MlImage): Task<PoseWithClassification> {
return detector
.process(image)
.continueWith(
classificationExecutor,
{ task ->
val pose = task.getResult()
var classificationResult: List<String> = ArrayList()
if (runClassification) {
if (poseClassifierProcessor == null) {
poseClassifierProcessor = PoseClassifierProcessor(context, isStreamMode)
}
classificationResult = poseClassifierProcessor!!.getPoseResult(pose)
}
PoseWithClassification(pose, classificationResult)
}
)
}
override fun onSuccess(
poseWithClassification: PoseWithClassification,
graphicOverlay: GraphicOverlay
) {
graphicOverlay.add(
PoseGraphic(
graphicOverlay,
poseWithClassification.pose,
showInFrameLikelihood,
visualizeZ,
rescaleZForVisualization,
poseWithClassification.classificationResult
)
)
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Pose detection failed!", e)
}
override fun isMlImageEnabled(context: Context?): Boolean {
// Use MlImage in Pose Detection by default, change it to OFF to switch to InputImage.
return true
}
companion object {
private val TAG = "PoseDetectorProcessor"
}
}
|
apache-2.0
|
24430a6845653e0a05821e00f3817b4e
| 32.353846 | 92 | 0.723478 | 4.58836 | false | false | false | false |
gotev/android-upload-service
|
uploadservice/src/main/java/net/gotev/uploadservice/data/HttpUploadTaskParameters.kt
|
2
|
2058
|
package net.gotev.uploadservice.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import net.gotev.uploadservice.persistence.Persistable
import net.gotev.uploadservice.persistence.PersistableData
import java.util.ArrayList
/**
* Class which contains specific parameters for HTTP uploads.
*/
@Parcelize
data class HttpUploadTaskParameters(
var method: String = "POST",
var usesFixedLengthStreamingMode: Boolean = true,
val requestHeaders: ArrayList<NameValue> = ArrayList(5),
val requestParameters: ArrayList<NameValue> = ArrayList(5)
) : Parcelable, Persistable {
companion object : Persistable.Creator<HttpUploadTaskParameters> {
private object CodingKeys {
const val method = "method"
const val fixedLength = "fixedLength"
const val headers = "headers"
const val parameters = "params"
}
private fun List<PersistableData>.toNameValueArrayList() =
ArrayList(map { NameValue.createFromPersistableData(it) })
override fun createFromPersistableData(data: PersistableData) = HttpUploadTaskParameters(
method = data.getString(CodingKeys.method),
usesFixedLengthStreamingMode = data.getBoolean(CodingKeys.fixedLength),
requestHeaders = try {
data.getArrayData(CodingKeys.headers).toNameValueArrayList()
} catch (exc: Throwable) {
ArrayList()
},
requestParameters = try {
data.getArrayData(CodingKeys.parameters).toNameValueArrayList()
} catch (exc: Throwable) {
ArrayList()
}
)
}
override fun toPersistableData() = PersistableData().apply {
putString(CodingKeys.method, method)
putBoolean(CodingKeys.fixedLength, usesFixedLengthStreamingMode)
putArrayData(CodingKeys.headers, requestHeaders.map { it.toPersistableData() })
putArrayData(CodingKeys.parameters, requestParameters.map { it.toPersistableData() })
}
}
|
apache-2.0
|
9115591120fb71cb9f8d64668e02350c
| 37.830189 | 97 | 0.681244 | 4.995146 | false | false | false | false |
cmelchior/realmfieldnameshelper
|
library/src/main/kotlin/dk/ilios/realmfieldnames/FileGenerator.kt
|
1
|
3076
|
package dk.ilios.realmfieldnames
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import java.io.IOException
import javax.annotation.processing.Filer
import javax.lang.model.element.Modifier
/**
* Class responsible for creating the final output files.
*/
class FileGenerator(private val filer: Filer) {
private val formatter: FieldNameFormatter
init {
this.formatter = FieldNameFormatter()
}
/**
* Generates all the "<class>Fields" fields with field name references.
* @param fileData Files to create.
* *
* @return `true` if the files where generated, `false` if not.
*/
fun generate(fileData: Set<ClassData>): Boolean {
return fileData
.filter { !it.libraryClass }
.all { generateFile(it, fileData) }
}
private fun generateFile(classData: ClassData, classPool: Set<ClassData>): Boolean {
val fileBuilder = TypeSpec.classBuilder(classData.simpleClassName + "Fields")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addJavadoc("This class enumerate all queryable fields in {@link \$L.\$L}\n",
classData.packageName, classData.simpleClassName)
// Add a static field reference to each queryable field in the Realm model class
classData.fields.forEach { fieldName, value ->
if (value != null) {
// Add linked field names (only up to depth 1)
for (data in classPool) {
if (data.qualifiedClassName == value) {
val linkedTypeSpec = TypeSpec.classBuilder(formatter.format(fieldName))
.addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
val linkedClassFields = data.fields
addField(linkedTypeSpec, "$", fieldName)
for (linkedFieldName in linkedClassFields.keys) {
addField(linkedTypeSpec, linkedFieldName, fieldName + "." + linkedFieldName)
}
fileBuilder.addType(linkedTypeSpec.build())
}
}
} else {
// Add normal field name
addField(fileBuilder, fieldName, fieldName)
}
}
val javaFile = JavaFile.builder(classData.packageName, fileBuilder.build()).build()
try {
javaFile.writeTo(filer)
return true
} catch (e: IOException) {
e.printStackTrace()
return false
}
}
private fun addField(fileBuilder: TypeSpec.Builder, fieldName: String, fieldNameValue: String) {
val field = FieldSpec.builder(String::class.java, formatter.format(fieldName))
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("\$S", fieldNameValue)
.build()
fileBuilder.addField(field)
}
}
|
apache-2.0
|
b2425f332431b61876a8d65deb14b054
| 36.512195 | 104 | 0.595904 | 5.059211 | false | false | false | false |
AoEiuV020/PaNovel
|
app/src/main/java/cc/aoeiuv020/panovel/detail/NovelDetailPresenter.kt
|
1
|
3602
|
package cc.aoeiuv020.panovel.detail
import cc.aoeiuv020.panovel.Presenter
import cc.aoeiuv020.panovel.data.DataManager
import cc.aoeiuv020.panovel.data.NovelManager
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.qrcode.QrCodeManager
import cc.aoeiuv020.panovel.report.Reporter
import org.jetbrains.anko.*
/**
*
* Created by AoEiuV020 on 2017.10.03-18:10:45.
*/
class NovelDetailPresenter(
id: Long
) : Presenter<NovelDetailActivity>(), AnkoLogger {
// 第一次使用要在异步线程,
private val novelManager: NovelManager by lazy {
DataManager.getNovelManager(id)
}
private val novel: Novel get() = novelManager.novel
fun start() {
requestDetail(false)
}
fun refresh() {
requestDetail(true)
}
private fun requestDetail(refresh: Boolean) {
view?.doAsync({ e ->
val message = "获取小说<${novel.bookId}>详情失败,"
Reporter.post(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
// 这里初始化novelManager,有数据库查询所以必须异步,
val novelManager = novelManager
if (!refresh) {
// 打开首次加载时先展示本地数据,
uiThread {
view?.showNovelDetail(novelManager.novel)
}
}
novelManager.requestDetail(refresh)
uiThread {
view?.showNovelDetail(novelManager.novel)
}
}
}
fun share() {
view?.doAsync({ e ->
val message = "获取小说<${novel.bookId}>详情页地址失败,"
// 按理说每个网站的extra都是设计好的,可以得到完整地址的,
// 本地小说就file协议的地址,打不开拉倒,
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val url = novelManager.getDetailUrl()
// 简单拼接,这步不可能不问题,
val qrCode = QrCodeManager.generate(url)
uiThread {
view?.showSharedUrl(url, qrCode)
}
}
}
fun browse() {
try {
val url = novelManager.getDetailUrl()
// 只支持打开网络地址,本地小说不支持调用其他app打开,
url.takeIf { it.startsWith("http") }
?.also { view?.browse(it) }
?: view?.showError("本地小说不支持外部打开,")
} catch (e: Exception) {
val message = "获取小说《${novel.name}》<${novel.site}, ${novel.detail}>详情页地址失败,"
// 按理说每个网站的extra都是设计好的,可以得到完整地址的,
Reporter.post(message, e)
error(message, e)
view?.showError(message, e)
}
}
fun updateBookshelf(checked: Boolean) {
view?.doAsync({ e ->
val message = "${if (novel.bookshelf) "添加" else "删除"}书架《${novel.name}》失败,"
// 这应该是数据库操作出问题,正常情况不会出现才对,
// 未知异常统一上报,
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
novelManager.updateBookshelf(checked)
}
}
}
|
gpl-3.0
|
e7525289624966a0b2c96fd88ad1fe2f
| 28.704762 | 87 | 0.538486 | 3.854141 | false | false | false | false |
andrei-heidelbacher/metanalysis
|
chronolens-core/src/main/kotlin/org/chronolens/core/model/QualifiedId.kt
|
1
|
7592
|
/*
* Copyright 2021 Andrei Heidelbacher <[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 org.chronolens.core.model
import org.chronolens.core.model.SourceNode.Companion.CONTAINER_SEPARATOR
import org.chronolens.core.model.SourceNode.Companion.MEMBER_SEPARATOR
import org.chronolens.core.model.SourceNodeKind.FUNCTION
import org.chronolens.core.model.SourceNodeKind.SOURCE_FILE
import org.chronolens.core.model.SourceNodeKind.TYPE
import org.chronolens.core.model.SourceNodeKind.VARIABLE
/** A unique identifier of a [SourceNode] within a [SourceTree]. */
public data class QualifiedId(
val parent: QualifiedId?,
val id: SourceNodeId,
val kind: SourceNodeKind,
) {
init {
validateKindAndIdPair(parent, id, kind)
if (parent == null) {
require(kind == SOURCE_FILE && id is SourcePath) {
"Top level qualified id '$id' must be a source path!"
}
} else {
require(parent.kind != FUNCTION) {
"Parent '$parent' of qualified id '$id' must not be a function!"
}
require(kind != SOURCE_FILE) {
"Qualified id '$id' with parent '$parent' must not be a file!"
}
}
}
override fun toString(): String {
if (parent == null) return id.toString()
val builder = StringBuilder()
fun appendParentId(parentId: QualifiedId) {
if (parentId.parent != null) {
appendParentId(parentId.parent)
builder.append(':')
}
builder.append(parentId.id)
}
appendParentId(parent)
builder.append(if (kind == TYPE) ':' else '#')
builder.append(id)
return builder.toString()
}
}
private fun validateKindAndIdPair(
parent: QualifiedId?,
id: SourceNodeId,
kind: SourceNodeKind,
) {
val lazyMessage = {
"Source node id '$id' with parent '$parent' mismatches kind '$kind'!"
}
when (kind) {
SOURCE_FILE -> require(id is SourcePath, lazyMessage)
TYPE, VARIABLE -> require(id is Identifier, lazyMessage)
FUNCTION -> require(id is Signature, lazyMessage)
}
}
/** Creates a new [SourceFile] qualified id from the given [path]. */
public fun qualifiedPathOf(path: SourcePath): QualifiedId =
QualifiedId(null, path, SOURCE_FILE)
/** Utility method. */
public fun qualifiedPathOf(path: String): QualifiedId =
qualifiedPathOf(SourcePath(path))
/**
* Creates a new [Type] qualified id using [this] id as a parent and the given
* [identifier] as the type name.
*
* @throws IllegalStateException if [this] id qualifies a [Function]
*/
public fun QualifiedId.appendType(identifier: Identifier): QualifiedId {
check(kind != FUNCTION) { "'$this' cannot be parent of '$identifier'!" }
return QualifiedId(this, identifier, TYPE)
}
/** Utility method. */
public fun QualifiedId.appendType(identifier: String): QualifiedId =
appendType(Identifier(identifier))
/**
* Creates a new [Function] qualified id using [this] id as a parent and the
* given [signature].
*
* @throws IllegalStateException if [this] id qualifies a [Function]
*/
public fun QualifiedId.appendFunction(signature: Signature): QualifiedId {
check(kind != FUNCTION) { "'$this' cannot be parent of '$signature'!" }
return QualifiedId(this, signature, FUNCTION)
}
/** Utility method. */
public fun QualifiedId.appendFunction(signature: String): QualifiedId =
appendFunction(Signature(signature))
/**
* Creates a new [Variable] qualified id using [this] id as a parent and the
* given [identifier] as the variable name.
*
* @throws IllegalStateException if [this] id qualifies a [Function]
*/
public fun QualifiedId.appendVariable(identifier: Identifier): QualifiedId {
check(kind != FUNCTION) { "'$this' cannot be parent of '$identifier'!" }
return QualifiedId(this, identifier, VARIABLE)
}
/** Utility method. */
public fun QualifiedId.appendVariable(identifier: String): QualifiedId =
appendVariable(Identifier(identifier))
/**
* The path of the [SourceFile] that contains the [SourceNode] denoted by [this]
* qualified id.
*/
public val QualifiedId.sourcePath: SourcePath
get() = parent?.sourcePath ?: (id as SourcePath)
/**
* Parses the given [rawQualifiedId].
*
* @throws IllegalArgumentException if the given [rawQualifiedId] is invalid
*/
public fun parseQualifiedIdFromString(rawQualifiedId: String): QualifiedId {
validateMemberSeparators(rawQualifiedId)
val tokens = rawQualifiedId.split(*SEPARATORS)
require(tokens.isNotEmpty() && tokens.all(String::isNotBlank)) {
"Invalid qualified id '$rawQualifiedId'!"
}
// First token is always the source file path.
var qualifiedId = qualifiedPathOf(tokens.first())
// Stop if there is just one token.
if (tokens.size == 1) return qualifiedId
// Middle tokens are always type names.
for (token in tokens.subList(1, tokens.size - 1)) {
qualifiedId = qualifiedId.appendType(token)
}
// There are at least two tokens, so the separator exists.
val separator = rawQualifiedId[rawQualifiedId.lastIndexOfAny(SEPARATORS)]
val lastId = tokens.last()
val isSignature = '(' in lastId && lastId.endsWith(')')
return when {
separator == ':' -> qualifiedId.appendType(lastId)
separator == '#' && isSignature -> qualifiedId.appendFunction(lastId)
separator == '#' && !isSignature -> qualifiedId.appendVariable(lastId)
else -> error("Invalid separator '$separator' in '$rawQualifiedId'!!")
}
}
private fun validateMemberSeparators(rawQualifiedId: String) {
val memberIndex = rawQualifiedId.indexOf('#')
val nextIndex = rawQualifiedId.indexOfAny(SEPARATORS, memberIndex + 1)
require(memberIndex == -1 || nextIndex == -1) {
"Invalid qualified id '$rawQualifiedId'!"
}
}
private val SEPARATORS = charArrayOf(':', '#')
private val separators = charArrayOf(CONTAINER_SEPARATOR, MEMBER_SEPARATOR)
public val String.sourcePath: String
get() {
val where = indexOfAny(separators)
return if (where == -1) this else substring(0, where)
}
/** The path of the [SourceFile] which contains [this] node. */
public val SourceTreeNode<*>.sourcePath: String get() = qualifiedId.sourcePath
/**
* The path of the [SourceFile] which contains the node affected by [this] edit.
*/
public val SourceTreeEdit.sourcePath: String get() = id.sourcePath
/**
* The qualified id of the parent node of the source note denoted by [this]
* qualified id, or `null` if this id denotes a [SourceFile].
*/
public val String.parentId: String?
get() {
val where = lastIndexOfAny(separators)
return if (where == -1) null else substring(0, where)
}
/** The qualified id of the parent node of [this] source tree node. */
public val SourceTreeNode<out SourceEntity>.parentId: String
get() = qualifiedId.parentId
?: error("Source entity '$qualifiedId' must have a parent!")
|
apache-2.0
|
5bb61301e9f16368c97dc5d5e5a6a5be
| 33.825688 | 80 | 0.681639 | 4.176018 | false | false | false | false |
arturbosch/detekt
|
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/runners/ElementPrinter.kt
|
1
|
1877
|
package io.gitlab.arturbosch.detekt.cli.runners
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import org.jetbrains.kotlin.diagnostics.PsiDiagnosticUtils
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtDeclarationContainer
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtStatementExpression
class ElementPrinter : DetektVisitor() {
private val sb = StringBuilder()
private val indentation
get() = (0..indent).joinToString("") { " " }
private val KtElement.line
get() = PsiDiagnosticUtils.offsetToLineAndColumn(
containingFile.viewProvider.document,
textRange.startOffset
).line
private val KtElement.dump
get() = indentation + line + ": " + javaClass.simpleName
private var indent: Int = 0
private var lastLine = 0
override fun visitKtElement(element: KtElement) {
val currentLine = element.line
if (element.isContainer()) {
indent++
sb.appendLine(element.dump)
} else {
if (lastLine == currentLine) {
indent++
sb.appendLine(element.dump)
indent--
} else {
sb.appendLine(element.dump)
}
}
lastLine = currentLine
super.visitKtElement(element)
if (element.isContainer()) {
indent--
}
}
private fun KtElement.isContainer() =
this is KtStatementExpression ||
this is KtDeclarationContainer ||
this is KtContainerNode
companion object {
fun dump(file: KtFile): String = ElementPrinter().run {
sb.appendLine("0: " + file.javaClass.simpleName)
visitKtFile(file)
sb.toString()
}
}
}
|
apache-2.0
|
f9b197159655f44031407270537fa557
| 28.793651 | 64 | 0.620671 | 4.875325 | false | false | false | false |
hypercube1024/firefly
|
firefly-net/src/main/kotlin/com/fireflysource/net/websocket/client/impl/AsyncWebSocketClientConnectionManager.kt
|
1
|
2449
|
package com.fireflysource.net.websocket.client.impl
import com.fireflysource.common.`object`.Assert
import com.fireflysource.common.lifecycle.AbstractLifeCycle
import com.fireflysource.net.http.client.impl.Http1ClientConnection
import com.fireflysource.net.http.common.HttpConfig
import com.fireflysource.net.http.common.model.HttpURI
import com.fireflysource.net.tcp.TcpClientConnectionFactory
import com.fireflysource.net.tcp.aio.ApplicationProtocol.HTTP1
import com.fireflysource.net.websocket.client.WebSocketClientConnectionManager
import com.fireflysource.net.websocket.client.WebSocketClientRequest
import com.fireflysource.net.websocket.common.WebSocketConnection
import com.fireflysource.net.websocket.common.exception.WebSocketException
import com.fireflysource.net.websocket.common.model.WebSocketBehavior
import java.net.InetSocketAddress
import java.util.concurrent.CompletableFuture
/**
* @author Pengtao Qiu
*/
class AsyncWebSocketClientConnectionManager(
private val config: HttpConfig,
private val connectionFactory: TcpClientConnectionFactory
) : WebSocketClientConnectionManager, AbstractLifeCycle() {
init {
start()
}
override fun connect(request: WebSocketClientRequest): CompletableFuture<WebSocketConnection> {
Assert.hasText(request.url, "The websocket url must be not blank")
Assert.notNull(request.policy, "The websocket policy must be not null")
Assert.notNull(request.handler, "The websocket message handler must be not null")
Assert.isTrue(request.policy.behavior == WebSocketBehavior.CLIENT, "The websocket behavior must be client")
val uri = HttpURI(request.url)
val inetSocketAddress = InetSocketAddress(uri.host, uri.port)
val tcpConnection = when (uri.scheme) {
"ws" -> connectionFactory.connect(inetSocketAddress, false)
"wss" -> connectionFactory.connect(inetSocketAddress, true, listOf(HTTP1.value))
else -> throw WebSocketException("The websocket scheme error. scheme: ${uri.scheme}")
}
return tcpConnection
.thenCompose { connection -> connection.beginHandshake().thenApply { connection } }
.thenApply { Http1ClientConnection(config, it) }
.thenCompose { it.upgradeWebSocket(request) }
}
override fun init() {
connectionFactory.start()
}
override fun destroy() {
connectionFactory.stop()
}
}
|
apache-2.0
|
80582d33fa629a8c6d8f2b17bfcecea8
| 41.241379 | 115 | 0.754185 | 4.691571 | false | true | false | false |
Karumi/Shot
|
shot-consumer/app/src/androidTest/java/com/karumi/ui/view/SuperHeroViewHolderTest.kt
|
1
|
3915
|
package com.karumi.ui.view
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.karumi.R
import com.karumi.domain.model.SuperHero
import com.karumi.ui.presenter.SuperHeroesPresenter
import com.karumi.ui.view.adapter.SuperHeroViewHolder
import org.junit.Test
import org.mockito.Mockito.mock
import com.karumi.shot.ScreenshotTest
class SuperHeroViewHolderTest : ScreenshotTest {
@Test
fun showsAnySuperHero() {
val superHero = givenASuperHero()
val holder = givenASuperHeroViewHolder()
holder.render(superHero)
compareScreenshot(holder)
}
@Test
fun showsSuperHeroesWithLongNames() {
val superHero = givenASuperHeroWithALongName()
val holder = givenASuperHeroViewHolder()
holder.render(superHero)
compareScreenshot(holder)
}
@Test
fun showsSuperHeroesWithLongDescriptions() {
val superHero = givenASuperHeroWithALongDescription()
val holder = givenASuperHeroViewHolder()
holder.render(superHero)
compareScreenshot(holder)
}
@Test
fun showsAvengersBadge() {
val superHero = givenASuperHero(isAvenger = true)
val holder = givenASuperHeroViewHolder()
holder.render(superHero)
compareScreenshot(holder)
}
private fun compareScreenshot(holder: RecyclerView.ViewHolder) {
compareScreenshot(view = holder.itemView, heightInPx = holder.itemView.resources.getDimensionPixelSize(R.dimen.super_hero_row_height).toInt())
}
private fun givenASuperHeroViewHolder(): SuperHeroViewHolder {
val context = getInstrumentation().targetContext
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.super_hero_row, null, false)
return SuperHeroViewHolder(
view,
mock<SuperHeroesPresenter>(SuperHeroesPresenter::class.java)
)
}
private fun givenASuperHeroWithALongDescription(): SuperHero {
val superHeroName = "Super Hero Name"
val superHeroDescription = """
|Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
|incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
|ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
|voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
|proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|""".trimMargin()
val isAvenger = false
return givenASuperHero(superHeroName, superHeroDescription, isAvenger)
}
private fun givenASuperHeroWithALongName(): SuperHero {
val superHeroName = """
|Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
|incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
|ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
|voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
|proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|""".trimMargin()
val superHeroDescription = "Description Super Hero"
val isAvenger = false
return givenASuperHero(superHeroName, superHeroDescription, isAvenger)
}
private fun givenASuperHero(
superHeroName: String = "Super Hero Name",
superHeroDescription: String = "Super Hero Description",
isAvenger: Boolean = false
): SuperHero = SuperHero(superHeroName, null, isAvenger, superHeroDescription)
}
|
apache-2.0
|
e6a62375e25aa64c93f2d96ae501b999
| 37.772277 | 150 | 0.709834 | 4.086639 | false | true | false | false |
martin-nordberg/KatyDOM
|
Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/api/ExperimentationTests.kt
|
1
|
4348
|
//
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.vdom.api
import o.katydid.vdom.application.katydid
import o.katydid.vdom.types.EAnchorHtmlLinkType.next
import o.katydid.vdom.types.EAnchorHtmlLinkType.noreferrer
import org.junit.jupiter.api.Test
//---------------------------------------------------------------------------------------------------------------------
/**
* Tests for quick trials of Katydid DSL.
*/
@Suppress("RemoveRedundantBackticks")
class ExperimentationTests {
@Test
fun `Sample 1 of Katydid-VDOM DSL should produce correct HTML`() {
val vdomNode = katydid<Unit> {
div("#myDiv.my-class", style = "color:red") {
div {
text("a sample")
ul("#a-list") {
li(key = 1) { text("item 1") }
li(key = 2) { text("item 2") }
li(key = 3) {
text("item 3")
div {}
}
}
}
div(".some-class", key = 2) {
classes("big" to true, "small" to false, "smelly" to true)
attribute("class", "very-classy")
attributes("a1" to "v1", "a2" to "v2")
}
p {
text("example")
}
br {}
hr {
attribute("id", "me")
}
}
}
val html = """<div class="my-class" id="myDiv" style="color:red">
| <div>
| a sample
| <ul id="a-list">
| <li>
| item 1
| </li>
| <li>
| item 2
| </li>
| <li>
| item 3
| <div></div>
| </li>
| </ul>
| </div>
| <div a1="v1" a2="v2" class="big smelly some-class very-classy"></div>
| <p>
| example
| </p>
| <br>
| <hr id="me">
|</div>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `Sample 2 of Katydid-VDOM DSL should produce correct HTML`() {
val vdomNode = katydid<Unit> {
div("#myDiv.my-class", style = "color:red") {
div(hidden = true) {
text("a sample")
}
div(".some-class", key = "x", title = "A Title") {
classes("big" to true, "small" to false, "smelly" to true)
attribute("class", "very-classy")
attributes("a1" to "v1", "a2" to "v2")
}
}
}
val html = """<div class="my-class" id="myDiv" style="color:red">
| <div hidden="">
| a sample
| </div>
| <div a1="v1" a2="v2" class="big smelly some-class very-classy" title="A Title"></div>
|</div>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `Sample 3 of Katydid-VDOM DSL should produce correct HTML`() {
val vdomNode = katydid<Unit> {
div("#myDiv.my-class", "div1") {
span(".mottled") {
a(href = "#somewhere", rel = listOf(next, noreferrer)) {
text("Go Somewhere")
}
}
}
}
val html = """<div class="my-class" id="myDiv">
| <span class="mottled">
| <a href="#somewhere" rel="next noreferrer">
| Go Somewhere
| </a>
| </span>
|</div>""".trimMargin()
checkBuild(html, vdomNode)
}
}
//---------------------------------------------------------------------------------------------------------------------
|
apache-2.0
|
fce648734f5d8038dc88ed4a6f988ece
| 27.418301 | 119 | 0.346596 | 4.670247 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/functions/LambdaExpression.kt
|
2
|
5237
|
package me.ztiany.functions
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
/** 高阶函数:高阶函数是将函数用作参数或返回值的函数。 */
private fun <T> lock(lock: Lock, body: () -> T): T {
lock.lock()
try {
return body.invoke()
} finally {
lock.unlock()
}
}
private fun testLock() {
val lock = ReentrantLock()
//调用lock
lock(lock, { println("abc") })
//在 Kotlin 中有一个约定,如果函数的最后一个参数是一个函数,并且你传递一个 lambda 表达式作为相应的参数,可以在圆括号之外指定它
lock(lock) { println("abc") }
}
/**
* Lambda 表达式:
* 1,lambda 表达式总是被大括号括着,
* 2,其参数(如果有的话)在 -> 之前声明(参数类型可以省略),
* 3,函数体(如果存在的话)在 -> 后面。
* 4,如果 lambda 是该调用的是唯一参数,则调用中的圆括号可以完全省略。
* 5,如果函数字面值只有一个参数, 那么它的声明可以省略(连同 ->),其名称是 it。
*/
//给List添加map操作
private fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
val result = arrayListOf<R>()
for (item in this) {
result.add(transform(item))
}
return result
}
private fun testMap() {
val list = listOf(1, 2, 3)
list.map {
{
it.toString()
}
}.forEach {
println(it)
}
}
//可以直接声明Lambda类型
private val toStr: (num: Int) -> String = { it.toString() }
// 函数类型:对于接受另一个函数作为参数的函数,我们必须为该参数指定函数类型。
// max函数中必须指定less的类型,其类型为(T, T) -> Boolean) 接收两个类型,返回一个Boolean
private fun <T> max(collection: Collection<T>, less: (T, T) -> Boolean): T? {
var max: T? = null
for (item in collection) {
if (max == null || less(max, item)) {
max = item
}
}
return max
}
private fun lambdaReturn() {
val ints = listOf(1, 2, 3, 4, 5, 6, 7)
//下面两个表达式等价
ints.filter {
val shouldFilter = it > 0
shouldFilter
}
ints.filter {
val shouldFilter = it > 0
return@filter shouldFilter
}
}
/**
* 匿名函数:上面提供的 lambda 表达式语法缺少的一个东西是指定函数的返回类型的能力。在大多数情况下,这是不必要的。
* 因为返回类型可以自动推断出来。然而,如果确实需要显式指定,可以使用另一种语法: 匿名函数
*
* 1,匿名函数的返回类型推断机制与正常函数一样:对于具有表达式函数体的匿名函数将自动 推断返回类型,
* 而具有代码块函数体的返回类型必须显式 指定(或者已假定为 Unit)。
* 2,匿名函数参数总是在括号内传递。 允许将函数留在圆括号外的简写语法仅适用于 lambda 表达式。
* 3,Lambda表达式和匿名函数之间的另一个区别是 非局部返回的行为。一个不带标签的 return 语句 总是在用 fun 关键字声明的函数中返回。
* 这意味着 lambda 表达式中的 return 将从包含它的函数返回,而匿名函数中的 return 将从匿名函数自身返回。
*
*/
private fun anonymityFunction() {
val ints = listOf(1, 2, 3, 4, 5, 6, 7)
ints.filter(fun(item): Boolean = item > 0)//指定返回类型
ints.filter(fun(item) = item > 0)//不指定返回类型
}
/**
* Lambda 表达式或者匿名函数(以及局部函数和对象表达式)可以访问其闭包 ,即在外部作用域中声明的变量。
*/
private fun testClosure() {
val ints = listOf(1, 2, 3, 4, 5, 6, 7)
var sum = 0
ints.filter { it > 0 }
.map { it * it }
.forEach { sum += it }
print(sum)
}
//自执行闭包:自执行闭包就是在定义闭包的同时直接执行闭包,一般用于初始化上下文环境。
fun autoExecute() {
{ x: Int, y: Int ->
println("${x + y}")
}(1, 3)
}
/**
* 带接收者的函数字面值:
*
* Kotlin 提供了一种能力, 调用一个函数字面值时, 可以指定一个 接收者对象(receiver object).
* 在这个函数字面值的函数体内部, 你可以调用接收者对象的方法, 而不必指定任何限定符. 这种能力与扩展函数很类似,
* 在扩展函数的函数体中, 你也可以访问接收者对象的成员
*/
private fun testExtend() {
//当接收者类型可以从上下文推断时,lambda 表达式可以用作带接收者的函数字面值。
class HTML {
fun body() {
}
}
//接收者是HTML
fun html(init: HTML.() -> Unit): HTML {
val html = HTML() // 创建接收者对象
html.init() // 将该接收者对象传给该 lambda
return html
}
//此时可以推断出接收者是HTML
html {
// 带接收者的 lambda 由此开始
body() // 省略HTML直接调用该接收者对象的一个方法
}
}
|
apache-2.0
|
c04589a98844402fc9fb4d230adad985
| 21.121795 | 82 | 0.588525 | 2.558191 | false | false | false | false |
SapuSeven/BetterUntis
|
app/src/main/java/com/sapuseven/untis/activities/ScanCodeActivity.kt
|
1
|
1471
|
package com.sapuseven.untis.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.budiyev.android.codescanner.*
import com.google.zxing.BarcodeFormat
import com.sapuseven.untis.R
class ScanCodeActivity : BaseActivity() {
private lateinit var codeScanner: CodeScanner
companion object {
const val EXTRA_STRING_SCAN_RESULT = "com.sapuseven.untis.activities.scancode"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scancode)
val scannerView = findViewById<CodeScannerView>(R.id.codescannerview_scancode)
codeScanner = CodeScanner(this, scannerView)
codeScanner.camera = CodeScanner.CAMERA_BACK
codeScanner.formats = listOf(BarcodeFormat.QR_CODE)
codeScanner.autoFocusMode = AutoFocusMode.SAFE
codeScanner.scanMode = ScanMode.SINGLE
codeScanner.isAutoFocusEnabled = true
codeScanner.isFlashEnabled = false
codeScanner.decodeCallback = DecodeCallback {
val scanResult = Intent()
scanResult.putExtra(EXTRA_STRING_SCAN_RESULT, it.text)
setResult(Activity.RESULT_OK, scanResult)
finish()
}
codeScanner.errorCallback = ErrorCallback {
//setResult()
finish()
}
scannerView.setOnClickListener {
codeScanner.startPreview()
}
}
override fun onResume() {
super.onResume()
codeScanner.startPreview()
}
override fun onPause() {
codeScanner.releaseResources()
super.onPause()
}
}
|
gpl-3.0
|
7d5ee179d8d465221e50be5746bd00b5
| 25.285714 | 80 | 0.775663 | 3.668329 | false | false | false | false |
deeplearning4j/deeplearning4j
|
codegen/op-codegen/src/test/kotlin/org/nd4j/codegen/dsl/OpBuilderTest.kt
|
1
|
6714
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.codegen.dsl
import org.apache.commons.io.FileUtils
import org.junit.jupiter.api.Test
import org.nd4j.codegen.api.AtLeast
import org.nd4j.codegen.api.AtMost
import org.nd4j.codegen.api.DataType.*
import org.nd4j.codegen.api.Exactly
import org.nd4j.codegen.api.Language
import org.nd4j.codegen.api.doc.DocScope
import org.nd4j.codegen.impl.java.JavaPoetGenerator
import java.io.File
import java.nio.charset.StandardCharsets
import kotlin.test.assertTrue
class OpBuilderTest {
private var testDir = createTempDir()
@Test
fun opBuilderTest() {
val outDir = testDir
val mathNs = Namespace("math") {
val config = Config("bla"){
val a = Input(NUMERIC, "a") { description = "This is A!"}
Input(NUMERIC, "c") { count = AtLeast(1); description = "This is C!"}
Input(NUMERIC, "e") { defaultValue = a}
val b = Arg(NUMERIC, "b") { description = "This is B!"}
Arg(NUMERIC, "d") { count = AtMost(7); description = "This is D!"}
Arg(NUMERIC, "f") { defaultValue = 12}
Constraint("Some constraint"){
a.isScalar()
}
Constraint("Some different constraint"){
b eq 7
}
Doc(Language.JAVA, DocScope.ALL){
"This is some config documentation"
}
}
Op("add") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic"
val x = Input(NUMERIC, "x") { description = "First input to add" }
Input(NUMERIC,"y") { count = AtLeast(1); description = "Second input to add"; defaultValue = x }
Arg(INT,"shape") { count = AtLeast(1); description = "shape"; defaultValue = intArrayOf(1,2,3) }
Output(NUMERIC, "z") { description = "Output (x+y)" }
Doc(Language.ANY, DocScope.ALL) {
"""
(From AddOp) Add op doc text that will appear everywhere - classes, constructors, op creators
""".trimIndent()
}
Doc(Language.ANY, DocScope.CLASS_DOC_ONLY) {
"Add op doc text that will appear in all class docs (javadoc etc)"
}
Doc(Language.ANY, DocScope.CONSTRUCTORS_ONLY) {
"Add op doc text for constructors only"
}
}
val baseArithmeticOp = Mixin("BaseArithmeticOp") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic"
Input(NUMERIC,"x") { count = Exactly(1); description = "First operand to %OPNAME%" }
Input(NUMERIC,"y") { count = Exactly(1); description = "Second operand" }
Output(NUMERIC,"z") { description = "Output" }
Doc(Language.ANY, DocScope.ALL) {
"(From BaseArithmeticOp) op doc text that will appear everywhere - classes, constructors, op creators"
}
Doc(Language.ANY, DocScope.CLASS_DOC_ONLY) {
"op doc text that will appear in all class docs (javadoc etc)"
}
Doc(Language.ANY, DocScope.CONSTRUCTORS_ONLY) {
"op doc text for constructors only"
}
}
Op("sub", extends = baseArithmeticOp)
Op("mul", extends = baseArithmeticOp)
Op("rsub", extends = baseArithmeticOp) {
isAbstract = false
javaPackage = "org.nd4j.some.other.package"
Doc(Language.ANY, DocScope.CREATORS_ONLY) {
"(From rsub) This doc section will appear only in creator method for %OPNAME%"
}
}
Op("div"){
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic"
val x = Input(NUMERIC,"x") { description = "First operand to div" }
val y = Input(NUMERIC,"y") { description = "Second operand to div" }
val idx = Arg(INT, "idx") { description = "Some kind of Index" }
Constraint("Compatible Rank"){
x.rank() eq idx
}
Constraint("Compatible Shapes"){
sameShape(x,y)
}
Output(NUMERIC,"z") { description = "Output" }
Doc(Language.ANY, DocScope.ALL) {
"op doc text that will appear everywhere - classes, constructors, op creators"
}
}
Op("zfoo"){
javaPackage = "bar"
javaOpClass = "FooBarOp"
val x = Input(NUMERIC,"x") { description = "First operand to %OPNAME% (%INPUT_TYPE%)" }
val y = Input(NUMERIC,"y") { description = "Second operand to div" }
val z = Arg(ENUM, "fooMode"){ description = "Something or other"; possibleValues = listOf("SOME", "value", "Spam", "eGGs")}
val bla = useConfig(config)
Constraint("foo bar"){
x.sizeAt(7) eq 7 and y.isScalar()
}
Doc(Language.ANY, DocScope.ALL) {
"op doc text that will appear everywhere - classes, constructors, op creators"
}
Signature(x, y, z, bla)
}
}
val generator = JavaPoetGenerator()
generator.generateNamespaceNd4j(mathNs, null, outDir, "Nd4jMath")
val exp = File(outDir, "org/nd4j/linalg/factory/ops/Nd4jMath.java")
assertTrue(exp.isFile)
println(FileUtils.readFileToString(exp, StandardCharsets.UTF_8))
}
}
|
apache-2.0
|
32be716e99827b83eef213456e30c41a
| 38.269006 | 139 | 0.53664 | 4.388235 | false | false | false | false |
Dmedina88/SSB
|
example/app/src/main/kotlin/com/grayherring/devtalks/ui/home/DetailViewFragment.kt
|
1
|
1577
|
package com.grayherring.devtalks.ui.home
import android.view.View.GONE
import android.view.View.VISIBLE
import com.grayherring.devtalks.base.util.applyThrottle
import com.grayherring.devtalks.base.util.plusAssign
import com.grayherring.devtalks.base.util.tentativelyUpdate
import com.grayherring.devtalks.ui.home.events.EditClicked
import com.jakewharton.rxbinding2.view.clicks
import kotlinx.android.synthetic.main.fragment_detail_view.*
class DetailViewFragment : com.grayherring.devtalks.base.ui.BaseFragment<HomeState, HomeViewModel>() {
override fun viewModelClass() = HomeViewModel::class.java
override fun viewLayout() = com.grayherring.devtalks.R.layout.fragment_detail_view
override fun bindView(state: HomeState) {
state.selectedTalk.let {
presenter.tentativelyUpdate(it.presenter)
title.tentativelyUpdate(it.title)
platform.tentativelyUpdate(it.platform)
description.tentativelyUpdate(it.description)
date.tentativelyUpdate(it.date)
email.tentativelyUpdate(it.email)
slides.tentativelyUpdate(it.slides)
streams.tentativelyUpdate(it.stream)
edit.visibility = if (it.id == null) GONE else VISIBLE
}
}
override fun setUpEventStream() {
disposable += edit
.clicks()
.applyThrottle()
.map { EditClicked() }
.subscribe { viewModel.addEvent(it) }
}
companion object {
fun newInstance(): com.grayherring.devtalks.ui.home.DetailViewFragment {
val fragment = com.grayherring.devtalks.ui.home.DetailViewFragment()
return fragment
}
}
}
|
apache-2.0
|
abe37c40eeb7145f96227fa1ed6ddc98
| 33.282609 | 102 | 0.747622 | 4.053985 | false | false | false | false |
exponent/exponent
|
packages/expo-image/android/src/main/java/expo/modules/image/ExpoImageView.kt
|
2
|
8660
|
package expo.modules.image
import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.graphics.Shader
import android.graphics.drawable.Drawable
import android.net.Uri
import androidx.appcompat.widget.AppCompatImageView
import com.bumptech.glide.RequestManager
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.integration.webp.decoder.WebpDrawableTransformation
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.bumptech.glide.request.RequestOptions
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.modules.i18nmanager.I18nUtil
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.events.RCTEventEmitter
import expo.modules.image.drawing.BorderDrawable
import expo.modules.image.drawing.OutlineProvider
import expo.modules.image.enums.ImageResizeMode
import expo.modules.image.events.ImageLoadEventsManager
import expo.modules.image.okhttp.OkHttpClientProgressInterceptor
import jp.wasabeef.glide.transformations.BlurTransformation
private const val SOURCE_URI_KEY = "uri"
private const val SOURCE_WIDTH_KEY = "width"
private const val SOURCE_HEIGHT_KEY = "height"
private const val SOURCE_SCALE_KEY = "scale"
@SuppressLint("ViewConstructor")
class ExpoImageView(
context: ReactContext,
private val requestManager: RequestManager,
private val progressInterceptor: OkHttpClientProgressInterceptor
) : AppCompatImageView(context) {
private val eventEmitter = context.getJSModule(RCTEventEmitter::class.java)
private val outlineProvider = OutlineProvider(context)
private var propsChanged = false
private var loadedSource: GlideUrl? = null
private val borderDrawable = lazy {
BorderDrawable(context).apply {
callback = this@ExpoImageView
outlineProvider.borderRadiiConfig
.map { it.ifYogaDefinedUse(PixelUtil::toPixelFromDIP) }
.withIndex()
.forEach { (i, radius) ->
if (i == 0) {
setRadius(radius)
} else {
setRadius(radius, i - 1)
}
}
}
}
init {
clipToOutline = true
super.setOutlineProvider(outlineProvider)
}
// region Component Props
internal var sourceMap: ReadableMap? = null
internal var defaultSourceMap: ReadableMap? = null
internal var blurRadius: Int? = null
set(value) {
field = value?.takeIf { it > 0 }
propsChanged = true
}
internal var fadeDuration: Int? = null
set(value) {
field = value?.takeIf { it > 0 }
propsChanged = true
}
internal var resizeMode = ImageResizeMode.COVER.also { scaleType = it.scaleType }
set(value) {
field = value
scaleType = value.scaleType
}
internal fun setBorderRadius(position: Int, borderRadius: Float) {
var radius = borderRadius
val isInvalidated = outlineProvider.setBorderRadius(radius, position)
if (isInvalidated) {
invalidateOutline()
if (!outlineProvider.hasEqualCorners()) {
invalidate()
}
}
// Setting the border-radius doesn't necessarily mean that a border
// should to be drawn. Only update the border-drawable when needed.
if (borderDrawable.isInitialized()) {
radius = radius.ifYogaDefinedUse(PixelUtil::toPixelFromDIP)
borderDrawable.value.apply {
if (position == 0) {
setRadius(radius)
} else {
setRadius(radius, position - 1)
}
}
}
}
internal fun setBorderWidth(position: Int, width: Float) {
borderDrawable.value.setBorderWidth(position, width)
}
internal fun setBorderColor(position: Int, rgb: Float, alpha: Float) {
borderDrawable.value.setBorderColor(position, rgb, alpha)
}
internal fun setBorderStyle(style: String?) {
borderDrawable.value.setBorderStyle(style)
}
internal fun setTintColor(color: Int?) {
color?.let { setColorFilter(it, PorterDuff.Mode.SRC_IN) } ?: clearColorFilter()
}
// endregion
// region ViewManager Lifecycle methods
internal fun onAfterUpdateTransaction() {
val sourceToLoad = createUrlFromSourceMap(sourceMap)
val defaultSourceToLoad = createUrlFromSourceMap(defaultSourceMap)
if (sourceToLoad == null) {
requestManager.clear(this)
setImageDrawable(null)
loadedSource = null
} else if (sourceToLoad != loadedSource || propsChanged) {
propsChanged = false
loadedSource = sourceToLoad
val options = createOptionsFromSourceMap(sourceMap)
val propOptions = createPropOptions()
val eventsManager = ImageLoadEventsManager(id, eventEmitter)
progressInterceptor.registerProgressListener(sourceToLoad.toStringUrl(), eventsManager)
eventsManager.onLoadStarted()
requestManager
.asDrawable()
.load(sourceToLoad)
.apply { if (defaultSourceToLoad != null) thumbnail(requestManager.load(defaultSourceToLoad)) }
.apply(options)
.addListener(eventsManager)
.run {
val fitCenter = FitCenter()
this
.optionalTransform(fitCenter)
.optionalTransform(WebpDrawable::class.java, WebpDrawableTransformation(fitCenter))
}
.apply(propOptions)
.into(this)
requestManager
.`as`(BitmapFactory.Options::class.java)
// Remove any default listeners from this request
// (an example would be an SVGSoftwareLayerSetter
// added in ExpoImageViewManager).
// This request won't load the image, only the size.
.listener(null)
.load(sourceToLoad)
.into(eventsManager)
}
}
internal fun onDrop() {
requestManager.clear(this)
}
// endregion
// region Helper methods
private fun createUrlFromSourceMap(sourceMap: ReadableMap?): GlideUrl? {
val uriKey = sourceMap?.getString(SOURCE_URI_KEY)
return uriKey?.let { GlideUrl(uriKey) }
}
private fun createOptionsFromSourceMap(sourceMap: ReadableMap?): RequestOptions {
return RequestOptions()
.apply {
// Override the size for local assets. This ensures that
// resizeMode "center" displays the image in the correct size.
if (sourceMap != null &&
sourceMap.hasKey(SOURCE_WIDTH_KEY) &&
sourceMap.hasKey(SOURCE_HEIGHT_KEY) &&
sourceMap.hasKey(SOURCE_SCALE_KEY)
) {
val scale = sourceMap.getDouble(SOURCE_SCALE_KEY)
val width = sourceMap.getInt(SOURCE_WIDTH_KEY)
val height = sourceMap.getInt(SOURCE_HEIGHT_KEY)
override((width * scale).toInt(), (height * scale).toInt())
}
}
}
private fun createPropOptions(): RequestOptions {
return RequestOptions()
.apply {
blurRadius?.let {
transform(BlurTransformation(it + 1, 4))
}
fadeDuration?.let {
alpha = 0f
animate().alpha(1f).duration = it.toLong()
}
}
}
// endregion
// region Drawing overrides
override fun invalidateDrawable(drawable: Drawable) {
super.invalidateDrawable(drawable)
if (borderDrawable.isInitialized() && drawable === borderDrawable.value) {
invalidate()
}
}
override fun draw(canvas: Canvas) {
// When the border-radii are not all the same, a convex-path
// is used for the Outline. Unfortunately clipping is not supported
// for convex-paths and we fallback to Canvas clipping.
outlineProvider.clipCanvasIfNeeded(canvas, this)
super.draw(canvas)
}
public override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Draw borders on top of the background and image
if (borderDrawable.isInitialized()) {
borderDrawable.value.apply {
val layoutDirection = if (I18nUtil.getInstance().isRTL(context)) LAYOUT_DIRECTION_RTL else LAYOUT_DIRECTION_LTR
setResolvedLayoutDirection(layoutDirection)
setBounds(0, 0, width, height)
draw(canvas)
}
}
}
/**
* Called when Glide "injects" drawable into the view.
* When `resizeMode = REPEAT`, we need to update
* received drawable (unless null) and set correct tiling.
*/
override fun setImageDrawable(drawable: Drawable?) {
val maybeUpdatedDrawable = drawable
?.takeIf { resizeMode == ImageResizeMode.REPEAT }
?.toBitmapDrawable(resources)
?.apply {
setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
}
super.setImageDrawable(maybeUpdatedDrawable ?: drawable)
}
// endregion
}
|
bsd-3-clause
|
b71cdc1af7a50a3151e1e409a160784c
| 32.565891 | 119 | 0.696305 | 4.477766 | false | false | false | false |
MeilCli/Twitter4HK
|
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/data/RateLimit.kt
|
1
|
1499
|
package com.twitter.meil_mitu.twitter4hk.data
import com.squareup.okhttp.Response
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getInt
import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getLong
import org.json.JSONObject
class RateLimit {
val limit: Int
val remaining: Int
val reset: Long
constructor(res: Response) {
limit = Integer.parseInt(res.header("X-Rate-Limit-Limit", "0"))
remaining = Integer.parseInt(res.header("X-Rate-Limit-Remaining", "0"))
reset = java.lang.Long.parseLong(res.header("X-Rate-Limit-Reset", "-1"))
}
@Throws(Twitter4HKException::class)
constructor(obj: JSONObject) {
limit = getInt(obj, "limit")
remaining = getInt(obj, "remaining")
reset = getLong(obj, "reset")
}
override fun toString(): String {
return "RateLimit{Limit=$limit, Remaining=$remaining, Reset=$reset}"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RateLimit) return false
if (limit != other.limit) return false
if (remaining != other.remaining) return false
if (reset != other.reset) return false
return true
}
override fun hashCode(): Int {
var result = limit
result = 31 * result + remaining
result = 31 * result + (reset xor (reset.ushr(32))).toInt()
return result
}
}
|
mit
|
1a8c3a0d89ff81a6e2973f064ed1c852
| 28.98 | 80 | 0.651101 | 3.944737 | false | false | false | false |
lnds/9d9l
|
desafio4/kotlin2/src/main/kotlin/huffman/HuffTree.kt
|
1
|
3598
|
package huffman
/**
* Build HuffmanTree from frequency table of symbols
* Created by ediaz on 5/21/17.
*/
fun Char.index() = this.toInt() and 0xFFFF
fun Byte.index() = this.toInt() and 0xFFFF
abstract class HuffTree(val frequency : Int) {
abstract fun writeTo(output: BitOutputStream)
abstract fun dumpCodes(codes: Array<String>, prefix : StringBuffer)
abstract fun readChar(input: BitInputStream) : Char
}
class HuffLeaf(frequency: Int, private val symbol: Char) : HuffTree(frequency) {
fun symbolIndex(): Int = symbol.index()
override fun writeTo(output: BitOutputStream){
output.write(true)
output.write(symbol)
}
override fun dumpCodes(codes: Array<String>, prefix : StringBuffer) {
codes[symbolIndex()] = prefix.toString()
}
override fun readChar(input: BitInputStream) : Char {
return this.symbol
}
}
class HuffNode(private val left: HuffTree, private val right: HuffTree) : HuffTree(left.frequency + right.frequency) {
override fun writeTo(output: BitOutputStream){
output.write(false)
left.writeTo(output)
right.writeTo(output)
}
override fun dumpCodes(codes: Array<String>, prefix : StringBuffer) {
prefix.append('0')
left.dumpCodes(codes, prefix)
prefix.deleteCharAt(prefix.lastIndex)
prefix.append('1')
right.dumpCodes(codes, prefix)
prefix.deleteCharAt(prefix.lastIndex)
}
override fun readChar(input: BitInputStream) : Char {
val bit = input.readBoolean()
return if (bit) right.readChar(input) else left.readChar(input)
}
}
val maxSymbols = 256
class HuffHeap {
var heap = arrayOfNulls<HuffTree>(maxSymbols+1)
var last = 0
fun insert(tree:HuffTree) {
if (full()) {
throw ArrayIndexOutOfBoundsException()
}
last++
heap[last] = tree
var j = last
while (j > 1){
if (heap[j]!!.frequency < heap[j/2]!!.frequency) {
val tmp = heap[j]!!
heap[j] = heap[j / 2]!!
heap[j / 2] = tmp
}
j /= 2
}
}
fun full() = last == maxSymbols
fun empty() = last == 0
fun size() = last
fun extract() : HuffTree {
if (empty()) {
throw ArrayIndexOutOfBoundsException()
}
val min = heap[1]!!
heap[1] = heap[last]
last--
var j = 1
while (2*j <= last) {
var k = 2*j
if (k+1 <= last && heap[k+1]!!.frequency < heap[k]!!.frequency) {
k++
}
if (heap[j]!!.frequency < heap[k]!!.frequency) {
break
}
val tmp = heap[j]!!
heap[j] = heap[k]
heap[k] = tmp
j = k
}
return min
}
}
fun buildTree(freqs : IntArray) : HuffTree {
val heap = HuffHeap()
freqs.forEachIndexed { sym, freq ->
if (freq > 0) {
heap.insert(HuffLeaf(freq, sym.toChar()))
}
}
while (heap.size() > 1) {
val a = heap.extract()
val b = heap.extract()
heap.insert(HuffNode(a, b))
}
return heap.extract()
}
fun readTree(input : BitInputStream) : HuffTree =
if (input.readBoolean())
HuffLeaf(-1, input.readChar())
else
HuffNode(readTree(input), readTree(input))
fun buildCodes(tree: HuffTree) : Array<String> {
val prefix = StringBuffer()
val codes = Array(maxSymbols, {""})
tree.dumpCodes(codes, prefix)
return codes
}
|
mit
|
22efa3e9c295fcc0d88dfd2b64e86bc1
| 23.986111 | 118 | 0.563646 | 3.82766 | false | false | false | false |
google/ide-perf
|
src/main/java/com/google/idea/perf/cvtracer/CachedValueEventConsumer.kt
|
1
|
3115
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.idea.perf.cvtracer
import com.intellij.psi.util.CachedValueProfiler
import com.intellij.psi.util.CachedValueProfiler.EventPlace
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
// This class depends on CachedValueProfiler, which is an *unstable* IntelliJ API.
// Ideally a CachedValue tracer should be implemented upstream instead, and then this
// code could be removed. See https://youtrack.jetbrains.com/issue/IDEA-261466.
@Suppress("UnstableApiUsage")
class CachedValueEventConsumer : CachedValueProfiler.EventConsumer {
// TODO: Audit the overhead of (1) lock contention and (2) EventPlace.stackFrame computation.
private val lock = ReentrantLock()
private val data = mutableMapOf<StackTraceElement, RawCachedValueStats>()
data class RawCachedValueStats(
val location: StackTraceElement,
var computeTimeNs: Long = 0,
var computeCount: Long = 0,
var useCount: Long = 0,
) {
val hits: Long get() = maxOf(0L, useCount - computeCount)
}
fun install() {
CachedValueProfiler.setEventConsumer(this)
}
fun uninstall() {
CachedValueProfiler.setEventConsumer(null)
}
fun getSnapshot(): List<RawCachedValueStats> {
lock.withLock {
return data.values.map { it.copy() }
}
}
fun clear() {
lock.withLock(data::clear)
}
override fun onValueComputed(frameId: Long, place: EventPlace, start: Long, time: Long) {
val location = place.stackFrame ?: return
val elapsedNs = time - start
lock.withLock {
val stats = data.getOrPut(location) { RawCachedValueStats(location) }
stats.computeTimeNs += elapsedNs
stats.computeCount++
}
}
override fun onValueUsed(frameId: Long, place: EventPlace, computed: Long, time: Long) {
val location = place.stackFrame ?: return
lock.withLock {
val stats = data.getOrPut(location) { RawCachedValueStats(location) }
stats.useCount++
}
}
override fun onFrameEnter(frameId: Long, place: EventPlace, parentId: Long, time: Long) {}
override fun onFrameExit(frameId: Long, start: Long, computed: Long, time: Long) {}
override fun onValueInvalidated(frameId: Long, place: EventPlace, used: Long, time: Long) {}
override fun onValueRejected(frameId: Long, place: EventPlace,
start: Long, computed: Long, time: Long) {}
}
|
apache-2.0
|
3ecfeafae71fbf93f650db3021dad5e6
| 36.542169 | 97 | 0.685072 | 4.326389 | false | false | false | false |
google/ide-perf
|
src/main/java/com/google/idea/perf/AgentLoader.kt
|
1
|
5148
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.idea.perf
import com.google.idea.perf.AgentLoader.ensureTracerHooksInstalled
import com.google.idea.perf.AgentLoader.instrumentation
import com.google.idea.perf.agent.AgentMain
import com.google.idea.perf.tracer.TracerClassFileTransformer
import com.google.idea.perf.tracer.TracerHookImpl
import com.google.idea.perf.agent.TracerTrampoline
import com.intellij.execution.process.OSProcessUtil
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.io.isFile
import com.sun.tools.attach.VirtualMachine
import java.lang.instrument.Instrumentation
import kotlin.system.measureTimeMillis
// Things to improve:
// - Fail gracefully upon SOE caused by instrumenting code used by TracerMethodListener.
/**
* Loads and initializes the instrumentation agent with [VirtualMachine.loadAgent].
*
* See [instrumentation] for the global [java.lang.instrument.Instrumentation] instance.
* See [ensureTracerHooksInstalled] for installing tracer hooks.
*
* Note: the agent must be loaded here before any of its classes are referenced, otherwise
* [NoClassDefFoundError] is thrown. So, for safety, all direct references to agent
* classes should ideally be encapsulated in [AgentLoader].
*/
object AgentLoader {
private val LOG = Logger.getInstance(AgentLoader::class.java)
val instrumentation: Instrumentation?
get() = if (ensureJavaAgentLoaded) AgentMain.savedInstrumentationInstance else null
val ensureJavaAgentLoaded: Boolean by lazy { doLoadJavaAgent() }
val ensureTracerHooksInstalled: Boolean by lazy { doInstallTracerHooks() }
// Note: this method can take around 200 ms or so.
private fun doLoadJavaAgent(): Boolean {
val agentLoadedAtStartup = try {
// Until the agent is loaded, we cannot trigger symbol resolution for its
// classes---otherwise NoClassDefFoundError is imminent. So we use reflection.
Class.forName("com.google.idea.perf.agent.AgentMain", false, null)
true
}
catch (e: ClassNotFoundException) {
false
}
if (agentLoadedAtStartup) {
LOG.info("Java agent was loaded at startup")
}
else {
try {
val overhead = measureTimeMillis { tryLoadAgentAfterStartup() }
LOG.info("Java agent was loaded on demand in $overhead ms")
}
catch (e: Throwable) {
val msg = """
[Tracer] Failed to attach the instrumentation agent after startup.
On JDK 9+, make sure jdk.attach.allowAttachSelf is set to true.
Alternatively, you can attach the agent at startup via the -javaagent flag.
""".trimIndent()
Notification("Tracer", "", msg, NotificationType.ERROR).notify(null)
LOG.warn(e)
return false
}
}
// Disable tracing entirely if class retransformation is not supported.
val instrumentation = checkNotNull(AgentMain.savedInstrumentationInstance)
if (!instrumentation.isRetransformClassesSupported) {
val msg = "[Tracer] The current JVM configuration does not allow class retransformation"
Notification("Tracer", "", msg, NotificationType.ERROR).notify(null)
LOG.warn(msg)
return false
}
return true
}
// Note: this method can throw a variety of exceptions.
private fun tryLoadAgentAfterStartup() {
val plugin = PluginManagerCore.getPlugin(PluginId.getId("com.google.ide-perf"))
?: error("Failed to find our own plugin")
val agentDir = plugin.pluginPath.resolve("agent")
val javaAgent = agentDir.resolve("agent.jar")
check(javaAgent.isFile()) { "Could not find agent.jar at $javaAgent" }
val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid())
try {
vm.loadAgent(javaAgent.toAbsolutePath().toString())
}
finally {
vm.detach()
}
}
private fun doInstallTracerHooks(): Boolean {
val instrumentation = instrumentation ?: return false
TracerTrampoline.installHook(TracerHookImpl())
instrumentation.addTransformer(TracerClassFileTransformer(), true)
return true
}
}
|
apache-2.0
|
d04cc85e1cc03220a25d0945574eead3
| 39.535433 | 100 | 0.690365 | 4.688525 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/net/social/ConnectionTwitterGnuSocial.kt
|
1
|
13278
|
/*
* Copyright (C) 2013 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.net.social
import android.net.Uri
import io.vavr.control.Try
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.TextMediaType
import org.andstatus.app.net.http.ConnectionException
import org.andstatus.app.net.http.HttpConnectionInterface
import org.andstatus.app.net.http.HttpReadResult
import org.andstatus.app.net.http.HttpRequest
import org.andstatus.app.origin.OriginConfig
import org.andstatus.app.util.JsonUtils
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.TryUtils
import org.andstatus.app.util.UriUtils
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.regex.Pattern
/**
* Specific implementation of the Twitter API in GNU Social
* @author [email protected]
*/
class ConnectionTwitterGnuSocial : ConnectionTwitterLike() {
override fun getApiPathFromOrigin(routine: ApiRoutineEnum): String {
val url: String = when (routine) {
ApiRoutineEnum.GET_CONFIG -> "statusnet/config.json"
ApiRoutineEnum.GET_CONVERSATION -> "statusnet/conversation/%noteId%.json"
ApiRoutineEnum.GET_OPEN_INSTANCES -> "http://gstools.org/api/get_open_instances"
ApiRoutineEnum.PUBLIC_TIMELINE -> "statuses/public_timeline.json"
ApiRoutineEnum.SEARCH_NOTES -> "search.json"
else -> ""
}
return if (url.isEmpty()) {
super.getApiPathFromOrigin(routine)
} else partialPathToApiPath(url)
}
override fun getFriendsOrFollowersIds(apiRoutine: ApiRoutineEnum, actorOid: String): Try<List<String>> {
return getApiPath(apiRoutine)
.map { obj: Uri -> obj.buildUpon() }
.map { builder: Uri.Builder -> builder.appendQueryParameter("user_id", actorOid) }
.map { it.build() }
.map { uri: Uri -> HttpRequest.of(apiRoutine, uri) }
.flatMap(::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonArray() }
.flatMap { jsonArray: JSONArray? ->
val list: MutableList<String> = ArrayList()
try {
var index = 0
while (jsonArray != null && index < jsonArray.length()) {
list.add(jsonArray.getString(index))
index++
}
Try.success(list)
} catch (e: JSONException) {
Try.failure(ConnectionException.loggedJsonException(this, apiRoutine.name, e, jsonArray))
}
}
}
override fun rateLimitStatus(): Try<RateLimitStatus> {
val apiRoutine = ApiRoutineEnum.ACCOUNT_RATE_LIMIT_STATUS
return getApiPath(apiRoutine)
.map { uri: Uri -> HttpRequest.of(apiRoutine, uri) }
.flatMap(::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonObject() }
.flatMap { result: JSONObject? ->
val status = RateLimitStatus()
if (result != null) {
status.remaining = result.optInt("remaining_hits")
status.limit = result.optInt("hourly_limit")
}
Try.success(status)
}
}
override fun updateNote2(note: Note): Try<AActivity> {
val formParams = JSONObject()
try {
super.updateNoteSetFields(note, formParams)
// This parameter was removed from Twitter API, but it still is in GNUsocial
formParams.put("source", HttpConnectionInterface.USER_AGENT)
} catch (e: JSONException) {
return Try.failure(e)
}
return tryApiPath(data.getAccountActor(), ApiRoutineEnum.UPDATE_NOTE)
.map { uri: Uri ->
HttpRequest.of(ApiRoutineEnum.UPDATE_NOTE, uri)
.withPostParams(formParams)
.withMediaPartName("media")
.withAttachmentToPost(note.attachments.firstToUpload)
}
.flatMap(::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonObject() }
.map { jso: JSONObject? -> activityFromJson(jso) }
}
override fun getConfig(): Try<OriginConfig> {
val apiRoutine = ApiRoutineEnum.GET_CONFIG
return getApiPath(apiRoutine)
.map { uri: Uri -> HttpRequest.of(apiRoutine, uri) }
.flatMap(::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonObject() }
.map { result: JSONObject? ->
var config: OriginConfig = OriginConfig.getEmpty()
if (result != null) {
val site = result.optJSONObject("site")
if (site != null) {
val textLimit = site.optInt("textlimit")
var uploadLimit = 0
val attachments = site.optJSONObject("attachments")
if (attachments != null && site.optBoolean("uploads")) {
uploadLimit = site.optInt("file_quota")
}
config = OriginConfig.fromTextLimit(textLimit, uploadLimit.toLong())
// "shorturllength" is not used
}
}
config
}
}
override fun getConversation(conversationOid: String): Try<List<AActivity>> {
if (UriUtils.nonRealOid(conversationOid)) return TryUtils.emptyList()
val apiRoutine = ApiRoutineEnum.GET_CONVERSATION
return getApiPathWithNoteId(apiRoutine, conversationOid)
.map { uri: Uri -> HttpRequest.of(apiRoutine, uri) }
.flatMap(::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonArray() }
.flatMap { jsonArray: JSONArray? -> jArrToTimeline(jsonArray, apiRoutine) }
}
override fun setNoteBodyFromJson(note: Note, jso: JSONObject) {
if (data.getOrigin().isHtmlContentAllowed() && !jso.isNull(HTML_BODY_FIELD_NAME)) {
note.setContent(jso.getString(HTML_BODY_FIELD_NAME), TextMediaType.HTML)
} else if (jso.has("text")) {
note.setContent(jso.getString("text"), TextMediaType.PLAIN)
}
}
override fun activityFromJson2(jso: JSONObject?): AActivity {
if (jso == null) return AActivity.EMPTY
val method = "activityFromJson2"
val activity = super.activityFromJson2(jso)
val note = activity.getNote()
note.url = JsonUtils.optString(jso, "external_url")
note.setConversationOid(JsonUtils.optString(jso, CONVERSATION_ID_FIELD_NAME))
if (!jso.isNull(ATTACHMENTS_FIELD_NAME)) {
try {
val jArr = jso.getJSONArray(ATTACHMENTS_FIELD_NAME)
for (ind in 0 until jArr.length()) {
val jsonAttachment = jArr[ind] as JSONObject
val uri = UriUtils.fromAlternativeTags(jsonAttachment, "url", "thumb_url")
val attachment: Attachment = Attachment.fromUriAndMimeType(uri, JsonUtils.optString(jsonAttachment, "mimetype"))
if (attachment.isValid()) {
activity.addAttachment(attachment)
} else {
MyLog.d(this, "$method; invalid attachment #$ind; $jArr")
}
}
} catch (e: JSONException) {
MyLog.d(this, method, e)
}
}
return createLikeActivity(activity)
}
override fun actorBuilderFromJson(jso: JSONObject?): Actor {
return if (jso == null) Actor.EMPTY else super.actorBuilderFromJson(jso)
.setProfileUrl(JsonUtils.optString(jso, "statusnet_profile_url"))
}
override fun getOpenInstances(): Try<List<Server>> {
val apiRoutine = ApiRoutineEnum.GET_OPEN_INSTANCES
return getApiPath(apiRoutine)
.map { path: Uri ->
HttpRequest.of(apiRoutine, path)
.withAuthenticate(false)
}
.flatMap(http::execute)
.flatMap { obj: HttpReadResult -> obj.getJsonObject() }
.map { result: JSONObject? ->
val origins: MutableList<Server> = ArrayList()
val logMessage = StringBuilder(apiRoutine.toString())
var error = false
if (result == null) {
MyStringBuilder.appendWithSpace(logMessage, "Response is null JSON")
error = true
} else if (!error && JsonUtils.optString(result, "status") != "OK") {
MyStringBuilder.appendWithSpace(
logMessage, "gtools service returned the error: '" +
JsonUtils.optString(result, "error") + "'"
)
error = true
}
if (!error && result != null) {
val data = result.optJSONObject("data")
if (data != null) {
try {
val iterator = data.keys()
while (iterator.hasNext()) {
val key = iterator.next()
val instance = data.getJSONObject(key)
origins.add(
Server(
JsonUtils.optString(instance, "instance_name"),
JsonUtils.optString(instance, "instance_address"),
instance.optLong("users_count"),
instance.optLong("notices_count")
)
)
}
} catch (e: JSONException) {
throw ConnectionException.loggedJsonException(this, logMessage.toString(), e, data)
}
}
}
if (error) {
throw ConnectionException(logMessage.toString())
}
origins
}
}
companion object {
private val ATTACHMENTS_FIELD_NAME: String = "attachments"
private val CONVERSATION_ID_FIELD_NAME: String = "statusnet_conversation_id"
private val HTML_BODY_FIELD_NAME: String = "statusnet_html"
private val GNU_SOCIAL_FAVORITED_SOMETHING_BY_PATTERN = Pattern.compile(
"(?s)([^ ]+) favorited something by [^ ]+ (.+)")
private val GNU_SOCIAL_FAVOURITED_A_STATUS_BY_PATTERN = Pattern.compile(
"(?s)([^ ]+) favourited (a status by [^ ]+)")
fun createLikeActivity(activityIn: AActivity): AActivity {
val noteIn = activityIn.getNote()
var matcher = GNU_SOCIAL_FAVORITED_SOMETHING_BY_PATTERN.matcher(noteIn.content)
if (!matcher.matches()) {
matcher = GNU_SOCIAL_FAVOURITED_A_STATUS_BY_PATTERN.matcher(noteIn.content)
}
if (!matcher.matches()) return activityIn
val inReplyTo = noteIn.inReplyTo
val favoritedActivity: AActivity
if (UriUtils.isRealOid(inReplyTo.getNote().oid)) {
favoritedActivity = inReplyTo
} else {
favoritedActivity = AActivity.from(activityIn.accountActor, ActivityType.UPDATE)
favoritedActivity.setActor(activityIn.getActor())
favoritedActivity.setNote(noteIn)
}
favoritedActivity.setUpdatedDate(RelativeTime.SOME_TIME_AGO)
val note = favoritedActivity.getNote()
note.setContent(matcher.replaceFirst("$2"), TextMediaType.HTML)
note.updatedDate = RelativeTime.SOME_TIME_AGO
note.setStatus(DownloadStatus.LOADED) // TODO: Maybe we need to invent some other status for partially loaded...
note.setInReplyTo(AActivity.EMPTY)
val activity: AActivity = AActivity.from(activityIn.accountActor, ActivityType.LIKE)
activity.setOid(activityIn.getOid())
activity.setActor(activityIn.getActor())
activity.setUpdatedDate(activityIn.getUpdatedDate())
activity.setActivity(favoritedActivity)
return activity
}
}
}
|
apache-2.0
|
dcb30729041627eda29a3955d6dba390
| 45.753521 | 132 | 0.565522 | 4.842451 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/util/reference/ClassNameReferenceProvider.kt
|
1
|
3844
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util.reference
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.mapToArray
import com.demonwav.mcdev.util.packageName
import com.intellij.codeInsight.completion.JavaClassNameCompletionContributor
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiPackage
import com.intellij.psi.ResolveResult
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PackageScope
import com.intellij.util.ArrayUtil
import com.intellij.util.PlatformIcons
abstract class ClassNameReferenceProvider : PackageNameReferenceProvider() {
override val description: String
get() = "class/package '%s'"
protected abstract fun findClasses(element: PsiElement, scope: GlobalSearchScope): List<PsiClass>
override fun canBindTo(element: PsiElement) = super.canBindTo(element) || element is PsiClass
override fun resolve(qualifiedName: String, element: PsiElement, facade: JavaPsiFacade): Array<ResolveResult> {
val actualName = qualifiedName.replace('$', '.')
val classes = facade.findClasses(actualName, element.resolveScope)
if (classes.isNotEmpty()) {
return classes.mapToArray(::PsiElementResolveResult)
}
return super.resolve(actualName, element, facade)
}
override fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> {
return if (context != null) {
if (context is PsiPackage) {
collectSubpackages(element, context)
} else {
ArrayUtil.EMPTY_OBJECT_ARRAY // TODO: Add proper support for inner classes
}
} else {
collectClasses(element)
}
}
private fun collectClasses(element: PsiElement): Array<Any> {
val classes = findClasses(element, element.resolveScope).ifEmpty { return ArrayUtil.EMPTY_OBJECT_ARRAY }
val list = ArrayList<Any>()
val packages = HashSet<String>()
val basePackage = getBasePackage(element)
for (psiClass in classes) {
list.add(JavaClassNameCompletionContributor.createClassLookupItem(psiClass, false))
val topLevelPackage = getTopLevelPackageName(psiClass, basePackage) ?: continue
if (packages.add(topLevelPackage)) {
list.add(LookupElementBuilder.create(topLevelPackage).withIcon(PlatformIcons.PACKAGE_ICON))
}
}
return list.toArray()
}
private fun getTopLevelPackageName(psiClass: PsiClass, basePackage: String?): String? {
val packageName = psiClass.packageName ?: return null
val start = if (basePackage != null && packageName.startsWith(basePackage)) {
if (packageName.length == basePackage.length) {
// packageName == basePackage
return null
}
basePackage.length + 1
} else 0
val end = packageName.indexOf('.', start)
return if (end == -1) {
packageName.substring(start)
} else {
packageName.substring(start, end)
}
}
private fun collectSubpackages(element: PsiElement, context: PsiPackage): Array<Any> {
val classes = findClasses(element, PackageScope(context, true, true).intersectWith(element.resolveScope))
.ifEmpty { return ArrayUtil.EMPTY_OBJECT_ARRAY }
return collectPackageChildren(context, classes) {
JavaClassNameCompletionContributor.createClassLookupItem(it, false)
}
}
}
|
mit
|
da20595c538b09e739469acd7f3cf2e1
| 35.264151 | 115 | 0.684183 | 4.953608 | false | false | false | false |
lrannn/EasyView
|
app/src/main/java/com/mass/view/MainActivity.kt
|
1
|
4683
|
/*
Copyright 2017 by lrannn
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.mass.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.util.TypedValue
import android.widget.TextView
import com.mass.view.ui.article.ArticleFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val mArticleFragment: ArticleFragment = ArticleFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar.setTitleTextColor(Color.WHITE)
setSupportActionBar(toolbar)
navigation.disableAnimation()
supportFragmentManager.beginTransaction().add(R.id.main_container, mArticleFragment).commit()
}
/**
* Disable the shift mode and anim
*/
@SuppressLint("RestrictedApi")
fun BottomNavigationView.disableAnimation() {
val mMenuView = getChildAt(0) as BottomNavigationMenuView
try {
// 得到属性
val field = mMenuView.javaClass.getDeclaredField("mShiftingMode")
field.isAccessible = true
field.setBoolean(mMenuView, false)
field.isAccessible = false
val count = mMenuView.childCount
for (i in 0.rangeTo(count - 1)) {
val itemView = mMenuView.getChildAt(i) as BottomNavigationItemView
itemView.setShiftingMode(false)
itemView.setChecked(itemView.itemData.isChecked)
val mLargeLabel = getField(itemView.javaClass, itemView, "mLargeLabel") as TextView
val mSmallLabel = getField(itemView.javaClass, itemView, "mSmallLabel") as TextView
var mSmallLabelSize = mSmallLabel.textSize
setField(itemView.javaClass, itemView, "mShiftAmount", 0)
setField(itemView.javaClass, itemView, "mScaleUpFactor", 1)
setField(itemView.javaClass, itemView, "mScaleDownFactor", 1)
// let the mLargeLabel font size equal to mSmallLabel
mLargeLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX, mSmallLabelSize)
}
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
mMenuView.updateMenuView()
}
/**
* get private filed in this specific object
* @param targetClass
* *
* @param instance the filed owner
* *
* @param fieldName
* *
* @param <T>
* *
* @return field if success, null otherwise.
</T> */
private fun <T> getField(targetClass: Class<T>, instance: Any, fieldName: String): T? {
try {
val field = targetClass.getDeclaredField(fieldName)
field.isAccessible = true
return field.get(instance) as T
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
return null
}
/**
* change the field value
* @param targetClass
* *
* @param instance the filed owner
* *
* @param fieldName
* *
* @param value
*/
private fun setField(targetClass: Class<*>, instance: Any, fieldName: String, value: Any) {
try {
val field = targetClass.getDeclaredField(fieldName)
field.isAccessible = true
field.set(instance, value)
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
fun Context.logd(tag: String = "lrannn", msg: Any) {
Log.d(tag, msg.toString())
}
}
|
apache-2.0
|
38de46f7b8c6d5458a629d0cda68ee06
| 30.375839 | 101 | 0.649626 | 4.741379 | false | false | false | false |
jonashao/next-kotlin
|
app/src/main/java/com/junnanhao/next/data/SongsRepository.kt
|
1
|
5088
|
package com.junnanhao.next.data
import android.Manifest
import android.app.Application
import android.content.pm.PackageManager
import android.database.Cursor
import android.provider.MediaStore
import android.support.v4.content.ContentResolverCompat
import android.support.v4.content.ContextCompat
import android.support.v4.os.CancellationSignal
import com.github.ajalt.timberkt.wtf
import com.junnanhao.next.App
import com.junnanhao.next.data.model.Song
import io.objectbox.Box
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
/**
* Created by Jonas on 2017/5/29.
* songs repository
*/
class SongsRepository constructor(private var context: Application) : SongsDataSource {
private val songBox: Box<Song> = (context as App).boxStore.boxFor(Song::class.java)
override fun isInitialized(): Boolean {
return songBox.count() > 0
}
companion object {
private val MEDIA_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
private val WHERE = MediaStore.Audio.Media.IS_MUSIC + "=1 AND " + MediaStore.Audio.Media.SIZE + ">0"
private val ORDER_BY = MediaStore.Audio.Media.DISPLAY_NAME + " ASC"
private val PROJECTIONS = arrayOf(MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.IS_RINGTONE, MediaStore.Audio.Media.IS_MUSIC, MediaStore.Audio.Media.IS_NOTIFICATION, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID)
private val ALBUM_URI = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI
private val WHERE_ALBUM = MediaStore.Audio.Albums._ID + " = ?"
private val PROJECTIONS_ALBUM = arrayOf(MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_KEY, MediaStore.Audio.Albums.ALBUM_ART)
}
private var cancellationSignal: CancellationSignal? = null
override fun scanMusic(): Observable<List<Song>> {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
return Observable.fromArray()
}
cancellationSignal = CancellationSignal()
val cursor: Cursor = ContentResolverCompat.query(
context.contentResolver,
MEDIA_URI,
PROJECTIONS,
WHERE,
null,
ORDER_BY, cancellationSignal)
wtf { "scan music, cursor: $cursor, count = ${cursor.count}" }
return Observable.just(cursor)
.filter{c:Cursor?->
wtf { "cursor = $c, count =${c?.count}" }
return@filter c!=null
}
.subscribeOn(Schedulers.io())
.map { c: Cursor? ->
wtf { "cursor = $c, count =${c?.count}" }
val songs: MutableList<Song> = ArrayList()
if (c != null && c.count > 0) {
c.moveToFirst()
do {
val song = Song.fromCursor(c)
wtf { "song: $song" }
if (song != null && song.isSongValid())
songs.add(song)
} while (c.moveToNext())
}
songs.toList()
}
.doOnNext { songs: List<Song>? ->
songs?.forEach { song: Song? ->
val cursor1: Cursor = ContentResolverCompat.query(
context.contentResolver,
ALBUM_URI,
PROJECTIONS_ALBUM,
WHERE_ALBUM,
arrayOf(song?.albumId.toString()), null, null)
if (cursor1.count > 0) {
if (cursor1.moveToFirst()) {
song?.art = cursor1.getString(cursor1.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART))
wtf { "song.art: ${song?.art}" }
}
}
cursor1.close()
}
wtf { "songs: $songs" }
songBox.put(songs)
}
.doOnComplete { cursor.close() }
.doOnError { t: Throwable? ->
cursor.close()
t?.printStackTrace()
}
}
override fun getSongs(): List<Song> {
return songBox.all
}
override fun getSong(songId: Long): Observable<Song> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun saveSong(song: Song): Observable<Song> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
|
apache-2.0
|
e1517fd8104b9ab8647a8ea4d4d3c588
| 40.713115 | 464 | 0.565252 | 4.711111 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/road_name/data/RoadNamesTable.kt
|
1
|
972
|
package de.westnordost.streetcomplete.quests.road_name.data
object RoadNamesTable {
const val NAME = "road_names"
object Columns {
const val WAY_ID = "way_id"
const val NAMES = "names"
const val GEOMETRY = "geometry"
const val MIN_LATITUDE = "min_latitude"
const val MIN_LONGITUDE = "min_longitude"
const val MAX_LATITUDE = "max_latitude"
const val MAX_LONGITUDE = "max_longitude"
const val LAST_UPDATE = "last_update"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.WAY_ID} int PRIMARY KEY,
${Columns.NAMES} blob NOT NULL,
${Columns.GEOMETRY} blob NOT NULL,
${Columns.MIN_LATITUDE} double NOT NULL,
${Columns.MIN_LONGITUDE} double NOT NULL,
${Columns.MAX_LATITUDE} double NOT NULL,
${Columns.MAX_LONGITUDE} double NOT NULL,
${Columns.LAST_UPDATE} int NOT NULL
);"""
}
|
gpl-3.0
|
0f08dcf12f6eb11d4b0e06d11e9b41a0
| 33.714286 | 59 | 0.590535 | 4.171674 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/parking_access/AddParkingAccess.kt
|
1
|
1472
|
package de.westnordost.streetcomplete.quests.parking_access
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
class AddParkingAccess : OsmFilterQuestType<ParkingAccess>() {
// Exclude parking=street_side lacking any access tags, because most of
// these are found alongside public access roads, and likely will be
// access=yes by default. Leaving these in makes this quest repetitive and
// leads to users adding lots of redundant access=yes tags to satisfy the
// quest. parking=street_side with access=unknown seems like a valid target
// though.
//
// Cf. #2408: Parking access might omit parking=street_side
override val elementFilter = """
nodes, ways, relations with amenity = parking
and (
access = unknown
or (!access and parking !~ street_side|lane)
)
"""
override val commitMessage = "Add type of parking access"
override val wikiLink = "Tag:amenity=parking"
override val icon = R.drawable.ic_quest_parking_access
override fun getTitle(tags: Map<String, String>) = R.string.quest_parking_access_title
override fun createForm() = AddParkingAccessForm()
override fun applyAnswerTo(answer: ParkingAccess, changes: StringMapChangesBuilder) {
changes.addOrModify("access", answer.osmValue)
}
}
|
gpl-3.0
|
d2a0dcc95b7515837f1b6d00474c25ee
| 39.888889 | 90 | 0.725543 | 4.673016 | false | false | false | false |
westnordost/osmagent
|
app/src/main/java/de/westnordost/streetcomplete/quests/powerpoles_material/AddPowerPolesMaterial.kt
|
1
|
890
|
package de.westnordost.streetcomplete.quests.powerpoles_material
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddPowerPolesMaterial(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters = "nodes with power=pole and !material"
override val commitMessage = "Add powerpoles material type"
override val icon = R.drawable.ic_quest_power
override fun getTitle(tags: Map<String, String>) = R.string.quest_powerPolesMaterial_title
override fun createForm() = AddPowerPolesMaterialForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("material", answer)
}
}
|
gpl-3.0
|
5823a5b5b7f4ea3f78840af65ab82817
| 41.380952 | 94 | 0.797753 | 4.427861 | false | false | false | false |
fhanik/spring-security
|
config/src/test/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDslTests.kt
|
1
|
17151
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.security.config.web.servlet
import org.junit.Rule
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.test.SpringTestRule
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
import org.springframework.security.web.util.matcher.RegexRequestMatcher
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.put
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
/**
* Tests for [AuthorizeRequestsDsl]
*
* @author Eleftheria Stein
*/
class AuthorizeRequestsDslTests {
@Rule
@JvmField
val spring = SpringTestRule()
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `request when secured by regex matcher then responds with forbidden`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by regex matcher then responds with ok`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
}
@Test
fun `request when allowed by regex matcher with http method then responds based on method`() {
this.spring.register(AuthorizeRequestsByRegexConfig::class.java).autowire()
this.mockMvc.post("/onlyPostPermitted") { with(csrf()) }
.andExpect {
status { isOk() }
}
this.mockMvc.get("/onlyPostPermitted")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
open class AuthorizeRequestsByRegexConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(RegexRequestMatcher("/path", null), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "POST"), permitAll)
authorize(RegexRequestMatcher("/onlyPostPermitted", "GET"), denyAll)
authorize(RegexRequestMatcher(".*", null), authenticated)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
@RequestMapping("/onlyPostPermitted")
fun onlyPostPermitted() {
}
}
}
@Test
fun `request when secured by mvc then responds with forbidden`() {
this.spring.register(AuthorizeRequestsByMvcConfig::class.java).autowire()
this.mockMvc.get("/private")
.andExpect {
status { isForbidden() }
}
}
@Test
fun `request when allowed by mvc then responds with OK`() {
this.spring.register(AuthorizeRequestsByMvcConfig::class.java, LegacyMvcMatchingConfig::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path.html")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/path/")
.andExpect {
status { isOk() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeRequestsByMvcConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/path", permitAll)
authorize("/**", authenticated)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Configuration
open class LegacyMvcMatchingConfig : WebMvcConfigurer {
override fun configurePathMatch(configurer: PathMatchConfigurer) {
configurer.setUseSuffixPatternMatch(true)
}
}
@Test
fun `request when secured by mvc path variables then responds based on path variable value`() {
this.spring.register(MvcMatcherPathVariablesConfig::class.java).autowire()
this.mockMvc.get("/user/user")
.andExpect {
status { isOk() }
}
this.mockMvc.get("/user/deny")
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherPathVariablesConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/user/{userName}", "#userName == 'user'")
}
}
}
@RestController
internal class PathController {
@RequestMapping("/user/{user}")
fun path(@PathVariable user: String) {
}
}
}
@Test
fun `request when user has allowed role then responds with OK`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have allowed role then responds with forbidden`() {
this.spring.register(HasRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasRoleConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasRole("ADMIN"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val adminDetails = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
return InMemoryUserDetailsManager(userDetails, adminDetails)
}
}
@Test
fun `request when user has some allowed roles then responds with OK`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed roles then responds with forbidden`() {
this.spring.register(HasAnyRoleConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyRoleConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasAnyRole("ADMIN", "USER"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.roles("OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when user has some allowed authorities then responds with OK`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("user", "password"))
}.andExpect {
status { isOk() }
}
this.mockMvc.get("/") {
with(httpBasic("admin", "password"))
}.andExpect {
status { isOk() }
}
}
@Test
fun `request when user does not have any allowed authorities then responds with forbidden`() {
this.spring.register(HasAnyAuthorityConfig::class.java).autowire()
this.mockMvc.get("/") {
with(httpBasic("other", "password"))
}.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class HasAnyAuthorityConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/**", hasAnyAuthority("ROLE_ADMIN", "ROLE_USER"))
}
httpBasic { }
}
}
@RestController
internal class PathController {
@GetMapping("/")
fun index() {
}
}
@Bean
override fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.authorities("ROLE_USER")
.build()
val admin1Details = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.authorities("ROLE_ADMIN")
.build()
val admin2Details = User.withDefaultPasswordEncoder()
.username("other")
.password("password")
.authorities("ROLE_OTHER")
.build()
return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details)
}
}
@Test
fun `request when secured by mvc with servlet path then responds based on servlet path`() {
this.spring.register(MvcMatcherServletPathConfig::class.java).autowire()
this.mockMvc.perform(MockMvcRequestBuilders.get("/spring/path")
.with { request ->
request.servletPath = "/spring"
request
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.get("/other/path")
.with { request ->
request.servletPath = "/other"
request
})
.andExpect(status().isOk)
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize("/path",
"/spring",
denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@EnableWebSecurity
@EnableWebMvc
open class AuthorizeRequestsByMvcConfigWithHttpMethod : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(HttpMethod.GET, "/path", permitAll)
authorize(HttpMethod.PUT, "/path", denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with http method then responds based on http method`() {
this.spring.register(AuthorizeRequestsByMvcConfigWithHttpMethod::class.java).autowire()
this.mockMvc.get("/path")
.andExpect {
status { isOk() }
}
this.mockMvc.put("/path") { with(csrf()) }
.andExpect {
status { isForbidden() }
}
}
@EnableWebSecurity
@EnableWebMvc
open class MvcMatcherServletPathHttpMethodConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(HttpMethod.GET, "/path", "/spring", denyAll)
authorize(HttpMethod.PUT, "/path", "/spring", denyAll)
}
}
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
@Test
fun `request when secured by mvc with servlet path and http method then responds based on path and method`() {
this.spring.register(MvcMatcherServletPathConfig::class.java).autowire()
this.mockMvc.perform(MockMvcRequestBuilders.get("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.put("/spring/path")
.with { request ->
request.apply {
servletPath = "/spring"
csrf()
}
})
.andExpect(status().isForbidden)
this.mockMvc.perform(MockMvcRequestBuilders.get("/other/path")
.with { request ->
request.apply {
servletPath = "/other"
}
})
.andExpect(status().isOk)
}
}
|
apache-2.0
|
0d7009652b898b650a37be4ce6e4dbb9
| 31.238722 | 118 | 0.56574 | 5.555879 | false | true | false | false |
mgramin/sql-boot
|
src/main/kotlin/com/github/mgramin/sqlboot/rest/controllers/ApiController.kt
|
1
|
5794
|
/*
* The MIT License (MIT)
* <p>
* Copyright (c) 2016-2019 Maksim Gramin
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* <p>
* 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 NON-INFRINGEMENT. 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.github.mgramin.sqlboot.rest.controllers
import com.github.mgramin.sqlboot.exceptions.BootException
import com.github.mgramin.sqlboot.model.connection.DbConnectionList
import com.github.mgramin.sqlboot.model.resourcetype.Metadata
import com.github.mgramin.sqlboot.model.resourcetype.ResourceType
import com.github.mgramin.sqlboot.model.resourcetype.impl.composite.FsResourceTypes
import com.github.mgramin.sqlboot.model.uri.Uri
import com.github.mgramin.sqlboot.model.uri.impl.DbUri
import com.github.mgramin.sqlboot.model.uri.impl.FakeUri
import com.github.mgramin.sqlboot.model.uri.wrappers.SqlPlaceholdersWrapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod.GET
import org.springframework.web.bind.annotation.RequestMethod.POST
import org.springframework.web.bind.annotation.RestController
import java.util.ArrayList
import javax.servlet.http.HttpServletRequest
/**
* @author Maksim Gramin ([email protected])
* @version $Id: 69e9609bd238163b6b97346900c17bb6efd0c037 $
* @since 0.1
*/
@RestController
@ComponentScan(basePackages = ["com.github.mgramin.sqlboot"])
@EnableAutoConfiguration
@CrossOrigin
class ApiController {
@Autowired
private lateinit var dbConnectionList: DbConnectionList
@RequestMapping(value = ["/api/{connectionName}/types"])
fun types(@PathVariable connectionName: String): List<ResourceType>? {
return FsResourceTypes(dbConnectionList.getConnectionsByMask(connectionName), FakeUri()).resourceTypes()
}
@RequestMapping(value = ["/api/{connectionName}/**"], method = [GET, POST])
fun getResourcesHeadersJson(
request: HttpServletRequest,
@PathVariable connectionName: String
): ResponseEntity<List<Map<String, Any>>> {
return getListResponseEntityHeaders(SqlPlaceholdersWrapper(DbUri(parseUri(request, "api/headers"))))
}
@RequestMapping(value = ["/api/meta/{connectionName}/**"], method = [GET, POST])
fun getResourceMetadata(
request: HttpServletRequest,
@PathVariable connectionName: String
): ResponseEntity<List<Metadata>> {
return responseEntity(SqlPlaceholdersWrapper(DbUri(parseUri(request, "api/meta"))))
}
private fun getListResponseEntityHeaders(uri: Uri): ResponseEntity<List<Map<String, Any>>> {
val connections = dbConnectionList.getConnectionsByMask(uri.connection())
try {
val headers = FsResourceTypes(connections, uri)
.read(uri)
.map { it.headers() }
.collectList()
.block()
return if (headers.isEmpty()) {
ResponseEntity(headers, HttpStatus.NO_CONTENT)
} else {
ResponseEntity(headers, HttpStatus.OK)
}
} catch (e: BootException) {
if (e.errorCode == 404) {
return ResponseEntity(emptyList(), HttpStatus.NOT_FOUND)
}
return ResponseEntity(emptyList(), HttpStatus.INTERNAL_SERVER_ERROR)
}
}
private fun responseEntity(uri: Uri): ResponseEntity<List<Metadata>> {
val fsResourceTypes = FsResourceTypes(
listOf(dbConnectionList.getConnectionByName(uri.connection())), uri)
val resourceType = fsResourceTypes
.resourceTypes()
.stream()
.filter { v -> v.name().equals(uri.type(), ignoreCase = true) }
.findAny()
.orElse(null) ?: return ResponseEntity(ArrayList(), HttpStatus.NO_CONTENT)
return ResponseEntity(resourceType.metaData(uri), HttpStatus.OK)
}
private fun parseUri(request: HttpServletRequest, basePath: String): String {
val path = request.servletPath
.split("/")
.asSequence()
.filter { it.isNotEmpty() }
.filter { !basePath.split("/").contains(it) }
.joinToString(separator = "/") { it }
return if (request.queryString == null || request.queryString.isEmpty()) {
path
} else {
path + "?" + request.queryString
}
}
}
|
mit
|
ea342ac26e1e53bb6b491e5963211747
| 40.985507 | 112 | 0.699862 | 4.501943 | false | false | false | false |
android/performance-samples
|
MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/recyclerview/ChildItem.kt
|
1
|
1672
|
/*
* 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 com.example.macrobenchmark.target.recyclerview
import androidx.recyclerview.widget.DiffUtil
data class ChildItem(
val id: String,
val parentId: String,
val title: String,
val subtitle: String,
val description: String,
val color: Int,
val inWishlist: Boolean = false,
val likeState: LikeState = LikeState.UNKNOWN,
)
enum class LikeState {
LIKED,
DISLIKED,
UNKNOWN
}
object ChildItemDiffCallback : DiffUtil.ItemCallback<ChildItem>() {
override fun areItemsTheSame(oldItem: ChildItem, newItem: ChildItem): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: ChildItem, newItem: ChildItem): Boolean = when {
oldItem.color != newItem.color -> false
oldItem.title != newItem.title -> false
oldItem.subtitle != newItem.subtitle -> false
oldItem.description != newItem.description -> false
oldItem.inWishlist != newItem.inWishlist -> false
oldItem.likeState != newItem.likeState -> false
else -> true
}
}
|
apache-2.0
|
72875428a73f6ec975db129ad61e171b
| 31.153846 | 93 | 0.706938 | 4.320413 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/presentation/updates/UpdatesScreen.kt
|
1
|
10916
|
package eu.kanade.presentation.updates
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FlipToBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.stringResource
import eu.kanade.presentation.components.AppBar
import eu.kanade.presentation.components.ChapterDownloadAction
import eu.kanade.presentation.components.EmptyScreen
import eu.kanade.presentation.components.LazyColumn
import eu.kanade.presentation.components.LoadingScreen
import eu.kanade.presentation.components.MangaBottomActionMenu
import eu.kanade.presentation.components.Scaffold
import eu.kanade.presentation.components.SwipeRefresh
import eu.kanade.presentation.components.VerticalFastScroller
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesItem
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesPresenter
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesPresenter.Dialog
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesPresenter.Event
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.widget.TachiyomiBottomNavigationView
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.util.Date
import kotlin.time.Duration.Companion.seconds
@Composable
fun UpdateScreen(
presenter: UpdatesPresenter,
onClickCover: (UpdatesItem) -> Unit,
onBackClicked: () -> Unit,
) {
val internalOnBackPressed = {
if (presenter.selectionMode) {
presenter.toggleAllSelection(false)
} else {
onBackClicked()
}
}
BackHandler(onBack = internalOnBackPressed)
val context = LocalContext.current
val onUpdateLibrary = {
val started = LibraryUpdateService.start(context)
context.toast(if (started) R.string.updating_library else R.string.update_already_running)
started
}
Scaffold(
topBar = { scrollBehavior ->
UpdatesAppBar(
incognitoMode = presenter.isIncognitoMode,
downloadedOnlyMode = presenter.isDownloadOnly,
onUpdateLibrary = { onUpdateLibrary() },
actionModeCounter = presenter.selected.size,
onSelectAll = { presenter.toggleAllSelection(true) },
onInvertSelection = { presenter.invertSelection() },
onCancelActionMode = { presenter.toggleAllSelection(false) },
scrollBehavior = scrollBehavior,
)
},
bottomBar = {
UpdatesBottomBar(
selected = presenter.selected,
onDownloadChapter = presenter::downloadChapters,
onMultiBookmarkClicked = presenter::bookmarkUpdates,
onMultiMarkAsReadClicked = presenter::markUpdatesRead,
onMultiDeleteClicked = {
presenter.dialog = Dialog.DeleteConfirmation(it)
},
)
},
) { contentPadding ->
val contentPaddingWithNavBar = TachiyomiBottomNavigationView.withBottomNavPadding(contentPadding)
when {
presenter.isLoading -> LoadingScreen()
presenter.uiModels.isEmpty() -> EmptyScreen(
textResource = R.string.information_no_recent,
modifier = Modifier.padding(contentPaddingWithNavBar),
)
else -> {
UpdateScreenContent(
presenter = presenter,
contentPadding = contentPaddingWithNavBar,
onUpdateLibrary = onUpdateLibrary,
onClickCover = onClickCover,
)
}
}
}
}
@Composable
private fun UpdateScreenContent(
presenter: UpdatesPresenter,
contentPadding: PaddingValues,
onUpdateLibrary: () -> Boolean,
onClickCover: (UpdatesItem) -> Unit,
) {
val context = LocalContext.current
val updatesListState = rememberLazyListState()
val scope = rememberCoroutineScope()
var isRefreshing by remember { mutableStateOf(false) }
SwipeRefresh(
refreshing = isRefreshing,
onRefresh = {
val started = onUpdateLibrary()
if (!started) return@SwipeRefresh
scope.launch {
// Fake refresh status but hide it after a second as it's a long running task
isRefreshing = true
delay(1.seconds)
isRefreshing = false
}
},
enabled = presenter.selectionMode.not(),
indicatorPadding = contentPadding,
) {
VerticalFastScroller(
listState = updatesListState,
topContentPadding = contentPadding.calculateTopPadding(),
endContentPadding = contentPadding.calculateEndPadding(LocalLayoutDirection.current),
) {
LazyColumn(
modifier = Modifier.fillMaxHeight(),
state = updatesListState,
contentPadding = contentPadding,
) {
if (presenter.lastUpdated > 0L) {
updatesLastUpdatedItem(presenter.lastUpdated)
}
updatesUiItems(
uiModels = presenter.uiModels,
selectionMode = presenter.selectionMode,
onUpdateSelected = presenter::toggleSelection,
onClickCover = onClickCover,
onClickUpdate = {
val intent = ReaderActivity.newIntent(context, it.update.mangaId, it.update.chapterId)
context.startActivity(intent)
},
onDownloadChapter = presenter::downloadChapters,
relativeTime = presenter.relativeTime,
dateFormat = presenter.dateFormat,
)
}
}
}
val onDismissDialog = { presenter.dialog = null }
when (val dialog = presenter.dialog) {
is Dialog.DeleteConfirmation -> {
UpdatesDeleteConfirmationDialog(
onDismissRequest = onDismissDialog,
onConfirm = {
presenter.toggleAllSelection(false)
presenter.deleteChapters(dialog.toDelete)
},
)
}
null -> {}
}
LaunchedEffect(Unit) {
presenter.events.collectLatest { event ->
when (event) {
Event.InternalError -> context.toast(R.string.internal_error)
}
}
}
}
@Composable
private fun UpdatesAppBar(
modifier: Modifier = Modifier,
incognitoMode: Boolean,
downloadedOnlyMode: Boolean,
onUpdateLibrary: () -> Unit,
// For action mode
actionModeCounter: Int,
onSelectAll: () -> Unit,
onInvertSelection: () -> Unit,
onCancelActionMode: () -> Unit,
scrollBehavior: TopAppBarScrollBehavior,
) {
AppBar(
modifier = modifier,
title = stringResource(R.string.label_recent_updates),
actions = {
IconButton(onClick = onUpdateLibrary) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = stringResource(R.string.action_update_library),
)
}
},
actionModeCounter = actionModeCounter,
onCancelActionMode = onCancelActionMode,
actionModeActions = {
IconButton(onClick = onSelectAll) {
Icon(
imageVector = Icons.Default.SelectAll,
contentDescription = stringResource(R.string.action_select_all),
)
}
IconButton(onClick = onInvertSelection) {
Icon(
imageVector = Icons.Default.FlipToBack,
contentDescription = stringResource(R.string.action_select_inverse),
)
}
},
downloadedOnlyMode = downloadedOnlyMode,
incognitoMode = incognitoMode,
scrollBehavior = scrollBehavior,
)
}
@Composable
private fun UpdatesBottomBar(
selected: List<UpdatesItem>,
onDownloadChapter: (List<UpdatesItem>, ChapterDownloadAction) -> Unit,
onMultiBookmarkClicked: (List<UpdatesItem>, bookmark: Boolean) -> Unit,
onMultiMarkAsReadClicked: (List<UpdatesItem>, read: Boolean) -> Unit,
onMultiDeleteClicked: (List<UpdatesItem>) -> Unit,
) {
MangaBottomActionMenu(
visible = selected.isNotEmpty(),
modifier = Modifier.fillMaxWidth(),
onBookmarkClicked = {
onMultiBookmarkClicked.invoke(selected, true)
}.takeIf { selected.any { !it.update.bookmark } },
onRemoveBookmarkClicked = {
onMultiBookmarkClicked.invoke(selected, false)
}.takeIf { selected.all { it.update.bookmark } },
onMarkAsReadClicked = {
onMultiMarkAsReadClicked(selected, true)
}.takeIf { selected.any { !it.update.read } },
onMarkAsUnreadClicked = {
onMultiMarkAsReadClicked(selected, false)
}.takeIf { selected.any { it.update.read } },
onDownloadClicked = {
onDownloadChapter(selected, ChapterDownloadAction.START)
}.takeIf {
selected.any { it.downloadStateProvider() != Download.State.DOWNLOADED }
},
onDeleteClicked = {
onMultiDeleteClicked(selected)
}.takeIf { selected.any { it.downloadStateProvider() == Download.State.DOWNLOADED } },
)
}
sealed class UpdatesUiModel {
data class Header(val date: Date) : UpdatesUiModel()
data class Item(val item: UpdatesItem) : UpdatesUiModel()
}
|
apache-2.0
|
9cd267909a1e9eec15812590563c4bbd
| 37.70922 | 110 | 0.650879 | 5.230474 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt
|
1
|
13942
|
package eu.kanade.tachiyomi.extension
import android.content.Context
import android.graphics.drawable.Drawable
import eu.kanade.domain.source.model.SourceData
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi
import eu.kanade.tachiyomi.extension.model.AvailableSources
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.InstallStep
import eu.kanade.tachiyomi.extension.model.LoadResult
import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver
import eu.kanade.tachiyomi.extension.util.ExtensionInstaller
import eu.kanade.tachiyomi.extension.util.ExtensionLoader
import eu.kanade.tachiyomi.util.lang.launchNow
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.preference.plusAssign
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import logcat.LogPriority
import rx.Observable
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Locale
/**
* The manager of extensions installed as another apk which extend the available sources. It handles
* the retrieval of remotely available extensions as well as installing, updating and removing them.
* To avoid malicious distribution, every extension must be signed and it will only be loaded if its
* signature is trusted, otherwise the user will be prompted with a warning to trust it before being
* loaded.
*
* @param context The application context.
* @param preferences The application preferences.
*/
class ExtensionManager(
private val context: Context,
private val preferences: SourcePreferences = Injekt.get(),
) {
var isInitialized = false
private set
/**
* API where all the available extensions can be found.
*/
private val api = ExtensionGithubApi()
/**
* The installer which installs, updates and uninstalls the extensions.
*/
private val installer by lazy { ExtensionInstaller(context) }
private val iconMap = mutableMapOf<String, Drawable>()
private val _installedExtensionsFlow = MutableStateFlow(emptyList<Extension.Installed>())
val installedExtensionsFlow = _installedExtensionsFlow.asStateFlow()
private var subLanguagesEnabledOnFirstRun = preferences.enabledLanguages().isSet()
fun getAppIconForSource(sourceId: Long): Drawable? {
val pkgName = _installedExtensionsFlow.value.find { ext -> ext.sources.any { it.id == sourceId } }?.pkgName
if (pkgName != null) {
return iconMap[pkgName] ?: iconMap.getOrPut(pkgName) { context.packageManager.getApplicationIcon(pkgName) }
}
return null
}
private val _availableExtensionsFlow = MutableStateFlow(emptyList<Extension.Available>())
val availableExtensionsFlow = _availableExtensionsFlow.asStateFlow()
private var availableExtensionsSourcesData: Map<Long, SourceData> = mapOf()
private fun setupAvailableExtensionsSourcesDataMap(extensions: List<Extension.Available>) {
if (extensions.isEmpty()) return
availableExtensionsSourcesData = extensions
.flatMap { ext -> ext.sources.map { it.toSourceData() } }
.associateBy { it.id }
}
fun getSourceData(id: Long) = availableExtensionsSourcesData[id]
private val _untrustedExtensionsFlow = MutableStateFlow(emptyList<Extension.Untrusted>())
val untrustedExtensionsFlow = _untrustedExtensionsFlow.asStateFlow()
init {
initExtensions()
ExtensionInstallReceiver(InstallationListener()).register(context)
}
/**
* Loads and registers the installed extensions.
*/
private fun initExtensions() {
val extensions = ExtensionLoader.loadExtensions(context)
_installedExtensionsFlow.value = extensions
.filterIsInstance<LoadResult.Success>()
.map { it.extension }
_untrustedExtensionsFlow.value = extensions
.filterIsInstance<LoadResult.Untrusted>()
.map { it.extension }
isInitialized = true
}
/**
* Finds the available extensions in the [api] and updates [availableExtensions].
*/
suspend fun findAvailableExtensions() {
val extensions: List<Extension.Available> = try {
api.findExtensions()
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
withUIContext { context.toast(R.string.extension_api_error) }
emptyList()
}
enableAdditionalSubLanguages(extensions)
_availableExtensionsFlow.value = extensions
updatedInstalledExtensionsStatuses(extensions)
setupAvailableExtensionsSourcesDataMap(extensions)
}
/**
* Enables the additional sub-languages in the app first run. This addresses
* the issue where users still need to enable some specific languages even when
* the device language is inside that major group. As an example, if a user
* has a zh device language, the app will also enable zh-Hans and zh-Hant.
*
* If the user have already changed the enabledLanguages preference value once,
* the new languages will not be added to respect the user enabled choices.
*/
private fun enableAdditionalSubLanguages(extensions: List<Extension.Available>) {
if (subLanguagesEnabledOnFirstRun || extensions.isEmpty()) {
return
}
// Use the source lang as some aren't present on the extension level.
val availableLanguages = extensions
.flatMap(Extension.Available::sources)
.distinctBy(AvailableSources::lang)
.map(AvailableSources::lang)
val deviceLanguage = Locale.getDefault().language
val defaultLanguages = preferences.enabledLanguages().defaultValue()
val languagesToEnable = availableLanguages.filter {
it != deviceLanguage && it.startsWith(deviceLanguage)
}
preferences.enabledLanguages().set(defaultLanguages + languagesToEnable)
subLanguagesEnabledOnFirstRun = true
}
/**
* Sets the update field of the installed extensions with the given [availableExtensions].
*
* @param availableExtensions The list of extensions given by the [api].
*/
private fun updatedInstalledExtensionsStatuses(availableExtensions: List<Extension.Available>) {
if (availableExtensions.isEmpty()) {
preferences.extensionUpdatesCount().set(0)
return
}
val mutInstalledExtensions = _installedExtensionsFlow.value.toMutableList()
var changed = false
for ((index, installedExt) in mutInstalledExtensions.withIndex()) {
val pkgName = installedExt.pkgName
val availableExt = availableExtensions.find { it.pkgName == pkgName }
if (!installedExt.isUnofficial && availableExt == null && !installedExt.isObsolete) {
mutInstalledExtensions[index] = installedExt.copy(isObsolete = true)
changed = true
} else if (availableExt != null) {
val hasUpdate = !installedExt.isUnofficial &&
availableExt.versionCode > installedExt.versionCode
if (installedExt.hasUpdate != hasUpdate) {
mutInstalledExtensions[index] = installedExt.copy(hasUpdate = hasUpdate)
changed = true
}
}
}
if (changed) {
_installedExtensionsFlow.value = mutInstalledExtensions
}
updatePendingUpdatesCount()
}
/**
* Returns an observable of the installation process for the given extension. It will complete
* once the extension is installed or throws an error. The process will be canceled if
* unsubscribed before its completion.
*
* @param extension The extension to be installed.
*/
fun installExtension(extension: Extension.Available): Observable<InstallStep> {
return installer.downloadAndInstall(api.getApkUrl(extension), extension)
}
/**
* Returns an observable of the installation process for the given extension. It will complete
* once the extension is updated or throws an error. The process will be canceled if
* unsubscribed before its completion.
*
* @param extension The extension to be updated.
*/
fun updateExtension(extension: Extension.Installed): Observable<InstallStep> {
val availableExt = _availableExtensionsFlow.value.find { it.pkgName == extension.pkgName }
?: return Observable.empty()
return installExtension(availableExt)
}
fun cancelInstallUpdateExtension(extension: Extension) {
installer.cancelInstall(extension.pkgName)
}
/**
* Sets to "installing" status of an extension installation.
*
* @param downloadId The id of the download.
*/
fun setInstalling(downloadId: Long) {
installer.updateInstallStep(downloadId, InstallStep.Installing)
}
fun updateInstallStep(downloadId: Long, step: InstallStep) {
installer.updateInstallStep(downloadId, step)
}
/**
* Uninstalls the extension that matches the given package name.
*
* @param pkgName The package name of the application to uninstall.
*/
fun uninstallExtension(pkgName: String) {
installer.uninstallApk(pkgName)
}
/**
* Adds the given signature to the list of trusted signatures. It also loads in background the
* extensions that match this signature.
*
* @param signature The signature to whitelist.
*/
fun trustSignature(signature: String) {
val untrustedSignatures = _untrustedExtensionsFlow.value.map { it.signatureHash }.toSet()
if (signature !in untrustedSignatures) return
ExtensionLoader.trustedSignatures += signature
preferences.trustedSignatures() += signature
val nowTrustedExtensions = _untrustedExtensionsFlow.value.filter { it.signatureHash == signature }
_untrustedExtensionsFlow.value -= nowTrustedExtensions
val ctx = context
launchNow {
nowTrustedExtensions
.map { extension ->
async { ExtensionLoader.loadExtensionFromPkgName(ctx, extension.pkgName) }
}
.map { it.await() }
.forEach { result ->
if (result is LoadResult.Success) {
registerNewExtension(result.extension)
}
}
}
}
/**
* Registers the given extension in this and the source managers.
*
* @param extension The extension to be registered.
*/
private fun registerNewExtension(extension: Extension.Installed) {
_installedExtensionsFlow.value += extension
}
/**
* Registers the given updated extension in this and the source managers previously removing
* the outdated ones.
*
* @param extension The extension to be registered.
*/
private fun registerUpdatedExtension(extension: Extension.Installed) {
val mutInstalledExtensions = _installedExtensionsFlow.value.toMutableList()
val oldExtension = mutInstalledExtensions.find { it.pkgName == extension.pkgName }
if (oldExtension != null) {
mutInstalledExtensions -= oldExtension
}
mutInstalledExtensions += extension
_installedExtensionsFlow.value = mutInstalledExtensions
}
/**
* Unregisters the extension in this and the source managers given its package name. Note this
* method is called for every uninstalled application in the system.
*
* @param pkgName The package name of the uninstalled application.
*/
private fun unregisterExtension(pkgName: String) {
val installedExtension = _installedExtensionsFlow.value.find { it.pkgName == pkgName }
if (installedExtension != null) {
_installedExtensionsFlow.value -= installedExtension
}
val untrustedExtension = _untrustedExtensionsFlow.value.find { it.pkgName == pkgName }
if (untrustedExtension != null) {
_untrustedExtensionsFlow.value -= untrustedExtension
}
}
/**
* Listener which receives events of the extensions being installed, updated or removed.
*/
private inner class InstallationListener : ExtensionInstallReceiver.Listener {
override fun onExtensionInstalled(extension: Extension.Installed) {
registerNewExtension(extension.withUpdateCheck())
updatePendingUpdatesCount()
}
override fun onExtensionUpdated(extension: Extension.Installed) {
registerUpdatedExtension(extension.withUpdateCheck())
updatePendingUpdatesCount()
}
override fun onExtensionUntrusted(extension: Extension.Untrusted) {
_untrustedExtensionsFlow.value += extension
}
override fun onPackageUninstalled(pkgName: String) {
unregisterExtension(pkgName)
updatePendingUpdatesCount()
}
}
/**
* Extension method to set the update field of an installed extension.
*/
private fun Extension.Installed.withUpdateCheck(): Extension.Installed {
val availableExt = _availableExtensionsFlow.value.find { it.pkgName == pkgName }
if (!isUnofficial && availableExt != null && availableExt.versionCode > versionCode) {
return copy(hasUpdate = true)
}
return this
}
private fun updatePendingUpdatesCount() {
preferences.extensionUpdatesCount().set(_installedExtensionsFlow.value.count { it.hasUpdate })
}
}
|
apache-2.0
|
ecf431cfe409624388c1c0c7d7730903
| 37.727778 | 119 | 0.6862 | 5.073508 | false | false | false | false |
bajdcc/jMiniLang
|
src/main/kotlin/com/bajdcc/LALR1/interpret/module/std/ModuleStdShell.kt
|
1
|
1000
|
package com.bajdcc.LALR1.interpret.module.std
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.interpret.module.IInterpreterModule
import com.bajdcc.util.ResourceLoader
/**
* 【模块】命令行
*
* @author bajdcc
*/
class ModuleStdShell : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "std.shell"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
runtimeCodePage = page
return page
}
companion object {
val instance = ModuleStdShell()
}
}
|
mit
|
e4b881ff9e083b4dcf353658bac43144
| 23.073171 | 59 | 0.655172 | 4.522936 | false | false | false | false |
Maccimo/intellij-community
|
platform/build-scripts/groovy/org/jetbrains/intellij/build/http.kt
|
3
|
1770
|
// 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.intellij.build
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
internal val MEDIA_TYPE_BINARY = "application/octet-stream".toMediaType()
internal fun OkHttpClient.head(url: String): Response {
return newCall(Request.Builder().url(url).head().build()).execute()
}
internal fun OkHttpClient.get(url: String): Response {
return newCall(Request.Builder().url(url).build()).execute()
}
internal inline fun <T> Response.useSuccessful(task: (Response) -> T): T {
return use { response ->
if (response.isSuccessful) {
task(response)
}
else {
throw IOException("Unexpected code $response")
}
}
}
internal val httpClient by lazy {
OkHttpClient.Builder()
.addInterceptor { chain ->
chain.proceed(chain.request()
.newBuilder()
.header("User-Agent", "IJ Builder")
.build())
}
.addInterceptor { chain ->
val request = chain.request()
var response = chain.proceed(request)
var tryCount = 0
while (response.code >= 500 && tryCount < 3) {
response.close()
tryCount++
response = chain.proceed(request)
}
response
}
.followRedirects(true)
.build()
}
@Suppress("HttpUrlsUsage")
internal fun toUrlWithTrailingSlash(serverUrl: String): String {
var result = serverUrl
if (!result.startsWith("http://") && !result.startsWith("https://")) {
result = "http://$result"
}
if (!result.endsWith('/')) {
result += '/'
}
return result
}
|
apache-2.0
|
cc39392c45fcd0a808602e535c6ce55c
| 26.671875 | 120 | 0.648588 | 4.15493 | false | false | false | false |
Maccimo/intellij-community
|
platform/build-scripts/groovy/org/jetbrains/intellij/build/ProductProperties.kt
|
1
|
11541
|
// 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.intellij.build
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentMapOf
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.intellij.build.impl.productInfo.CustomProperty
import org.jetbrains.jps.model.module.JpsModule
import java.nio.file.Path
import java.util.*
import java.util.function.BiPredicate
/**
* Describes distribution of an IntelliJ-based IDE. Override this class and build distribution of your product.
*/
abstract class ProductProperties {
/**
* Base name for script files (*.bat, *.sh, *.exe), usually a shortened product name in lower case (e.g. 'idea' for IntelliJ IDEA, 'datagrip' for DataGrip)
*/
lateinit var baseFileName: String
/**
* @deprecated specify product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file instead (see its schema for details);
* if you need to get the product code in the build scripts, use {@link ApplicationInfoProperties#productCode} instead;
* if you need to override product code value from *ApplicationInfo.xml - {@link org.jetbrains.intellij.build.ProductProperties#customProductCode} can be used.
*/
var productCode: String? = null
/**
* This value overrides specified product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file
*/
var customProductCode: String? = null
/**
* Value of 'idea.platform.prefix' property. It's also used as prefix for 'ApplicationInfo.xml' product descriptor.
*/
var platformPrefix: String? = null
/**
* Name of the module containing ${platformPrefix}ApplicationInfo.xml product descriptor in 'idea' package
*/
lateinit var applicationInfoModule: String
/**
* Paths to directories containing images specified by 'logo/@url' and 'icon/@ico' attributes in ApplicationInfo.xml file
* <br>
* todo[nik] get rid of this and make sure that these resources are located in {@link #applicationInfoModule} instead
*/
var brandingResourcePaths: List<Path> = emptyList()
/**
* Name of the command which runs IDE in 'offline inspections' mode (returned by 'getCommandName' in com.intellij.openapi.application.ApplicationStarter).
* This property will be also used to name sh/bat scripts which execute this command.
*/
var inspectCommandName = "inspect"
/**
* {@code true} if tools.jar from JDK must be added to IDE classpath
*/
var toolsJarRequired = false
var isAntRequired = false
/**
* Whether to use splash for application start-up.
*/
var useSplash = false
/**
* Class-loader that product application should use by default.
* <p/>
* `com.intellij.util.lang.PathClassLoader` is used by default as
* it unifies class-loading logic of an application and allows to avoid double-loading of bootstrap classes.
*/
var classLoader: String? = "com.intellij.util.lang.PathClassLoader"
/**
* Additional arguments which will be added to JVM command line in IDE launchers for all operating systems
*/
var additionalIdeJvmArguments: MutableList<String> = mutableListOf()
/**
* The specified options will be used instead of/in addition to the default JVM memory options for all operating systems.
*/
var customJvmMemoryOptions: MutableMap<String, String> = mutableMapOf()
/**
* An identifier which will be used to form names for directories where configuration and caches will be stored, usually a product name
* without spaces with added version ('IntelliJIdea2016.1' for IntelliJ IDEA 2016.1)
*/
open fun getSystemSelector(appInfo: ApplicationInfoProperties, buildNumber: String): String {
return "${appInfo.productName}${appInfo.majorVersion}.${appInfo.minorVersionMainPart}"
}
/**
* If {@code true} Alt+Button1 shortcut will be removed from 'Quick Evaluate Expression' action and assigned to 'Add/Remove Caret' action
* (instead of Alt+Shift+Button1) in the default keymap
*/
var reassignAltClickToMultipleCarets = false
/**
* Now file containing information about third-party libraries is bundled and shown inside IDE.
* If {@code true} html & json files of third-party libraries will be placed alongside with build artifacts.
*/
var generateLibrariesLicensesTable = true
/**
* List of licenses information about all libraries which can be used in the product modules
*/
var allLibraryLicenses: List<LibraryLicense> = CommunityLibraryLicenses.LICENSES_LIST
/**
* If {@code true} the main product JAR file will be scrambled using {@link ProprietaryBuildTools#scrambleTool}
*/
var scrambleMainJar = false
@ApiStatus.Experimental
var useProductJar = true
/**
* If {@code false} names of private fields won't be scrambled (to avoid problems with serialization). This field is ignored if
* {@link #scrambleMainJar} is {@code false}.
*/
var scramblePrivateFields = true
/**
* Path to an alternative scramble script which will should be used for a product
*/
var alternativeScrambleStubPath: Path? = null
/**
* Describes which modules should be included into the product's platform and which plugins should be bundled with the product
*/
val productLayout = ProductModulesLayout()
/**
* If true cross-platform ZIP archive containing binaries for all OS will be built. The archive will be generated in [BuildPaths.artifactDir]
* directory and have ".portable" suffix by default, override [getCrossPlatformZipFileName] to change the file name.
* Cross-platform distribution is required for [plugins development](https://github.com/JetBrains/gradle-intellij-plugin).
*/
var buildCrossPlatformDistribution = false
/**
* Specifies name of cross-platform ZIP archive if {@link #buildCrossPlatformDistribution} is set to {@code true}
*/
open fun getCrossPlatformZipFileName(applicationInfo: ApplicationInfoProperties, buildNumber: String): String =
getBaseArtifactName(applicationInfo, buildNumber) + ".portable.zip"
/**
* A {@link org.jetbrains.intellij.build.impl.ClassVersionChecker class version checker} config map
* when .class file version verification inside {@link #buildCrossPlatformDistribution cross-platform distribution} is needed.
*/
var versionCheckerConfig: PersistentMap<String, String> = persistentMapOf()
/**
* Paths to properties files the content of which should be appended to idea.properties file
*/
var additionalIDEPropertiesFilePaths: List<Path> = emptyList()
/**
* Paths to directories the content of which should be added to 'license' directory of IDE distribution
*/
var additionalDirectoriesWithLicenses: List<Path> = emptyList()
/**
* Base file name (without extension) for product archives and installers (*.exe, *.tar.gz, *.dmg)
*/
abstract fun getBaseArtifactName(appInfo: ApplicationInfoProperties, buildNumber: String): String
/**
* @return instance of the class containing properties specific for Windows distribution or {@code null} if the product doesn't have Windows distribution
*/
abstract fun createWindowsCustomizer(projectHome: String): WindowsDistributionCustomizer?
/**
* @return instance of the class containing properties specific for Linux distribution or {@code null} if the product doesn't have Linux distribution
*/
abstract fun createLinuxCustomizer(projectHome: String): LinuxDistributionCustomizer?
/**
* @return instance of the class containing properties specific for macOS distribution or {@code null} if the product doesn't have macOS distribution
*/
abstract fun createMacCustomizer(projectHome: String): MacDistributionCustomizer?
/**
* If {@code true} a zip archive containing sources of modules included into the product will be produced.
*/
var buildSourcesArchive = false
/**
* Determines sources of which modules should be included into the sources archive if {@link #buildSourcesArchive} is {@code true}
*/
var includeIntoSourcesArchiveFilter: BiPredicate<JpsModule, BuildContext> = BiPredicate { _, _ -> true }
/**
* Specifies how Maven artifacts for IDE modules should be generated, by default no artifacts are generated.
*/
val mavenArtifacts = MavenArtifactsProperties()
/**
* Specified additional modules (not included into the product layout) which need to be compiled when product is built.
* todo[nik] get rid of this
*/
var additionalModulesToCompile: List<String> = emptyList()
/**
* Specified modules which tests need to be compiled when product is built.
* todo[nik] get rid of this
*/
var modulesToCompileTests: List<String> = emptyList()
var runtimeDistribution: JetBrainsRuntimeDistribution = JetBrainsRuntimeDistribution.JCEF
/**
* Prefix for names of environment variables used by Windows and Linux distributions to allow users customize location of the product JDK
* (<PRODUCT>_JDK variable), *.vmoptions file (<PRODUCT>_VM_OPTIONS variable), idea.properties file (<PRODUCT>_PROPERTIES variable)
*/
open fun getEnvironmentVariableBaseName(applicationInfo: ApplicationInfoProperties) = applicationInfo.upperCaseProductName
/**
* Override this method to copy additional files to distributions of all operating systems.
*/
open fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) {
}
/**
* Override this method if the product has several editions to ensure that their artifacts won't be mixed up.
* @return name of subdirectory under projectHome/out where build artifacts will be placed, must be unique among all products built from
* the same sources
*/
open fun getOutputDirectoryName(appInfo: ApplicationInfoProperties) = appInfo.productName.lowercase(Locale.ROOT)
/**
* Paths to externally built plugins to be included into the IDE. They will be copied into the build, as well as included into
* the IDE classpath when launching it to build search index, jar order, etc
*/
open fun getAdditionalPluginPaths(context: BuildContext): List<Path> = emptyList()
/**
* @return custom properties for {@link org.jetbrains.intellij.build.impl.productInfo.ProductInfoData}
*/
open fun generateCustomPropertiesForProductInfo(): List<CustomProperty> = emptyList()
/**
* If {@code true} a distribution contains libraries and launcher script for running IDE in Remote Development mode.
*/
@ApiStatus.Internal
open fun addRemoteDevelopmentLibraries(): Boolean =
productLayout.bundledPluginModules.contains("intellij.remoteDevServer")
/**
* Build steps which are always skipped for this product. Can be extended via {@link org.jetbrains.intellij.build.BuildOptions#buildStepsToSkip} but not overridden.
*/
var incompatibleBuildSteps: List<String> = emptyList()
/**
* Names of JARs inside IDE_HOME/lib directory which need to be added to the Xbootclasspath to start the IDE
*/
var xBootClassPathJarNames: List<String> = emptyList()
/**
* Customize PRODUCT_CODE-builtinModules.json which contains information about product modules,
* bundled plugins, and file extensions. builtinModules.json is used to populate marketplace settings
* for the product.
* <p>
* It's particularly useful when you want to limit modules used to calculate compatible plugins on marketplace.
*/
open fun customizeBuiltinModules(context: BuildContext, builtinModulesFile: Path) {
}
}
|
apache-2.0
|
99a2f5d1c9f65e28789207d7669efd08
| 41.744444 | 166 | 0.748289 | 4.759175 | false | false | false | false |
Maccimo/intellij-community
|
platform/platform-tests/testSrc/com/intellij/configurationStore/LoadInvalidProjectTest.kt
|
2
|
5511
|
// 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.configurationStore
import com.intellij.ide.impl.TrustedPaths
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.module.ConfigurationErrorDescription
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.IoTestUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.util.io.assertMatches
import com.intellij.util.io.directoryContentOf
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths
class LoadInvalidProjectTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
private val testDataRoot: Path
get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("platform/platform-tests/testData/configurationStore/invalid")
}
@JvmField
@Rule
val tempDirectory = TemporaryDirectory()
@JvmField
@Rule
val disposable = DisposableRule()
private val errors = ArrayList<ConfigurationErrorDescription>()
@Before
fun setUp() {
ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(disposable.disposable, errors::add)
}
@Test
fun `load empty iml`() {
loadProjectAndCheckResults("empty-iml-file") { project ->
assertThat(ModuleManager.getInstance(project).modules).hasSize(1)
assertThat(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).single().name).isEqualTo("foo")
assertThat(errors.single().description).contains("foo.iml")
}
}
@Test
fun `malformed xml in iml`() {
loadProjectAndCheckResults("malformed-xml-in-iml") { project ->
assertThat(ModuleManager.getInstance(project).modules).hasSize(1)
assertThat(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).single().name).isEqualTo("foo")
assertThat(errors.single().description).contains("foo.iml")
}
}
@Test
fun `unknown classpath provider in iml`() {
loadProjectAndCheckResults("unknown-classpath-provider-in-iml") { project ->
assertThat(ModuleManager.getInstance(project).modules).hasSize(1)
assertThat(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).single().name).isEqualTo("foo")
assertThat(errors.single().description).contains("foo.iml")
}
}
@Test
fun `no iml file`() {
loadProjectAndCheckResults("no-iml-file") { project ->
//this repeats behavior in the old model: if iml files doesn't exist we create a module with empty configuration and report no errors
assertThat(ModuleManager.getInstance(project).modules.single().name).isEqualTo("foo")
assertThat(errors).isEmpty()
}
}
@Test
fun `empty library xml`() {
loadProjectAndCheckResults("empty-library-xml") { project ->
//this repeats behavior in the old model: if library configuration file cannot be parsed it's silently ignored
assertThat(LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries).isEmpty()
assertThat(errors).isEmpty()
}
}
@Test
fun `duplicating libraries`() {
loadProjectAndCheckResults("duplicating-libraries") { project ->
assertThat(LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single().name).isEqualTo("foo")
assertThat(errors).isEmpty()
project.stateStore.save()
val expected = directoryContentOf(testDataRoot.resolve("duplicating-libraries-fixed"))
.mergeWith(directoryContentOf(testDataRoot.resolve ("common")))
val projectDir = project.stateStore.directoryStorePath!!.parent
projectDir.assertMatches(expected)
}
}
@Test
fun `remote iml paths must not be loaded in untrusted projects`() {
IoTestUtil.assumeWindows()
fun createUntrustedProject(targetDir: VirtualFile): Path {
val projectDir = VfsUtil.virtualToIoFile(targetDir)
FileUtil.copyDir(testDataRoot.resolve("remote-iml-path").toFile(), projectDir)
VfsUtil.markDirtyAndRefresh(false, true, true, targetDir)
val projectDirPath = projectDir.toPath()
TrustedPaths.getInstance().setProjectPathTrusted(projectDirPath, false)
return projectDirPath
}
runBlocking {
createOrLoadProject(tempDirectory, ::createUntrustedProject, loadComponentState = true, useDefaultProjectSettings = false) {
assertThat(errors).hasSize(1)
assertThat(errors.single().description).contains("remote locations")
}
}
}
private fun loadProjectAndCheckResults(testDataDirName: String, checkProject: suspend (Project) -> Unit) {
return loadProjectAndCheckResults(listOf(testDataRoot.resolve("common"), testDataRoot.resolve(testDataDirName)), tempDirectory, checkProject)
}
}
|
apache-2.0
|
a7c2d5d091e871c3ffcea0636cfea7de
| 39.822222 | 145 | 0.760842 | 4.754961 | false | true | false | false |
mdaniel/intellij-community
|
platform/core-api/src/com/intellij/openapi/application/coroutines.kt
|
1
|
5320
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.application
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import kotlin.coroutines.CoroutineContext
/**
* Suspends until it's possible to obtain the read lock and then
* runs the [action] holding the lock **without** preventing write actions.
* See [constrainedReadAction] for semantic details.
*
* @see readActionBlocking
*/
suspend fun <T> readAction(action: () -> T): T {
return constrainedReadAction(action = action)
}
/**
* Suspends until it's possible to obtain the read lock in smart mode and then
* runs the [action] holding the lock **without** preventing write actions.
* See [constrainedReadAction] for semantic details.
*
* @see smartReadActionBlocking
*/
suspend fun <T> smartReadAction(project: Project, action: () -> T): T {
return constrainedReadAction(ReadConstraint.inSmartMode(project), action = action)
}
/**
* Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction]
* **without** preventing write actions.
*
* The function suspends if at the moment of calling it's not possible to acquire the read lock,
* or if [constraints] are not [satisfied][ReadConstraint.isSatisfied].
* If the write action happens while the [action] is running, then the [action] is canceled,
* and the function suspends until its possible to acquire the read lock, and then the [action] is tried again.
*
* Since the [action] might me executed several times, it must be idempotent.
* The function returns when given [action] was completed fully.
* To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled].
*
* @see constrainedReadActionBlocking
*/
suspend fun <T> constrainedReadAction(vararg constraints: ReadConstraint, action: () -> T): T {
return readActionSupport().executeReadAction(constraints.toList(), blocking = false, action)
}
/**
* Suspends until it's possible to obtain the read lock and then
* runs the [action] holding the lock and **preventing** write actions.
* See [constrainedReadActionBlocking] for semantic details.
*
* @see readAction
*/
suspend fun <T> readActionBlocking(action: () -> T): T {
return constrainedReadActionBlocking(action = action)
}
/**
* Suspends until it's possible to obtain the read lock in smart mode and then
* runs the [action] holding the lock and **preventing** write actions.
* See [constrainedReadActionBlocking] for semantic details.
*
* @see smartReadAction
*/
suspend fun <T> smartReadActionBlocking(project: Project, action: () -> T): T {
return constrainedReadActionBlocking(ReadConstraint.inSmartMode(project), action = action)
}
/**
* Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction]
* **preventing** write actions.
*
* The function suspends if at the moment of calling it's not possible to acquire the read lock,
* or if [constraints] are not [satisfied][ReadConstraint.isSatisfied].
* If the write action happens while the [action] is running, then the [action] is **not** canceled,
* meaning the [action] will block pending write actions until finished.
*
* The function returns when given [action] was completed fully.
* To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled].
*
* @see constrainedReadAction
*/
suspend fun <T> constrainedReadActionBlocking(vararg constraints: ReadConstraint, action: () -> T): T {
return readActionSupport().executeReadAction(constraints.toList(), blocking = true, action)
}
private fun readActionSupport() = ApplicationManager.getApplication().getService(ReadActionSupport::class.java)
/**
* The code within [ModalityState.any] context modality state must only perform pure UI operations,
* it must not access any PSI, VFS, project model, or indexes. It also must not show any modal dialogs.
*/
fun ModalityState.asContextElement(): CoroutineContext = coroutineSupport().asContextElement(this)
/**
* UI dispatcher which dispatches onto Swing event dispatching thread within the [context modality state][asContextElement].
* If no context modality state is specified, then the coroutine is dispatched within [ModalityState.NON_MODAL] modality state.
*
* This dispatcher is also installed as [Dispatchers.Main].
* Use [Dispatchers.EDT] when in doubt, use [Dispatchers.Main] if the coroutine doesn't care about IJ model,
* e.g. when it is also able to be executed outside of IJ process.
*/
@Suppress("UnusedReceiverParameter")
val Dispatchers.EDT: CoroutineContext get() = coroutineSupport().edtDispatcher()
private fun coroutineSupport() = ApplicationManager.getApplication().getService(CoroutineSupport::class.java)
@ApiStatus.Internal
@ApiStatus.Experimental
fun createSupervisorCoroutineScope(parentScope: CoroutineScope, dispatcher: CoroutineDispatcher? = null): CoroutineScope {
val parentContext = parentScope.coroutineContext
var context = parentContext + SupervisorJob(parent = parentContext.job)
if (dispatcher != null) {
context += dispatcher
}
return CoroutineScope(context)
}
|
apache-2.0
|
13283d4a2f66d789c691711b9e07008d
| 43.341667 | 127 | 0.763534 | 4.481887 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddValVarToConstructorParameterAction.kt
|
1
|
4258
|
// 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.intentions
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.refactoring.ValVarExpression
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.idea.util.mustHaveValOrVar
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
interface AddValVarToConstructorParameterAction {
fun canInvoke(element: KtParameter): Boolean =
element.valOrVarKeyword == null && ((element.parent as? KtParameterList)?.parent as? KtPrimaryConstructor)?.takeIf { it.mustHaveValOrVar() || !it.isExpectDeclaration() } != null
operator fun invoke(element: KtParameter, editor: Editor?) {
val project = element.project
element.addBefore(KtPsiFactory(project).createValKeyword(), element.nameIdentifier)
if (element.containingClass()?.isInline() == true || editor == null) return
val parameter = element.createSmartPointer().let {
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
it.element
} ?: return
editor.caretModel.moveToOffset(parameter.startOffset)
TemplateBuilderImpl(parameter)
.apply { replaceElement(parameter.valOrVarKeyword ?: return@apply, ValVarExpression) }
.buildInlineTemplate()
.let { TemplateManager.getInstance(project).startTemplate(editor, it) }
}
class Intention : SelfTargetingRangeIntention<KtParameter>(
KtParameter::class.java,
KotlinBundle.lazyMessage("add.val.var.to.primary.constructor.parameter")
), AddValVarToConstructorParameterAction {
override fun applicabilityRange(element: KtParameter): TextRange? {
if (!canInvoke(element)) return null
val containingClass = element.getStrictParentOfType<KtClass>()
if (containingClass?.isData() == true || containingClass?.isInline() == true) return null
setTextGetter(KotlinBundle.lazyMessage("add.val.var.to.parameter.0", element.name ?: ""))
return element.nameIdentifier?.textRange
}
override fun applyTo(element: KtParameter, editor: Editor?) = invoke(element, editor)
}
class QuickFix(parameter: KtParameter) :
KotlinQuickFixAction<KtParameter>(parameter),
AddValVarToConstructorParameterAction {
override fun getText(): String {
val element = this.element ?: return ""
val key = when {
element.getStrictParentOfType<KtClass>()?.isInline() == true -> "add.val.to.parameter.0"
else -> "add.val.var.to.parameter.0"
}
return KotlinBundle.message(key, element.name ?: "")
}
override fun getFamilyName() = KotlinBundle.message("add.val.var.to.primary.constructor.parameter")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
invoke(element ?: return, editor)
}
}
object DataClassVsPropertyQuickFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = QuickFix(Errors.DATA_CLASS_NOT_PROPERTY_PARAMETER.cast(diagnostic).psiElement)
}
}
|
apache-2.0
|
b58adea0198e70670b34757aba55ef31
| 46.853933 | 185 | 0.736261 | 4.980117 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/PrivateToThis/PrivateToThis.kt
|
15
|
288
|
package p
class PrivateToThis<in I> {
private val foo: I = null!!
private var bar: I = null!!
private val val_with_accessors: I
get() = null!!
private var var_with_accessors: I
get() = null!!
set(value: I) {}
private fun bas(): I = null!!
}
|
apache-2.0
|
01e7b792c52c3b9de1b7115b5c959f9e
| 18.266667 | 37 | 0.555556 | 3.555556 | false | false | false | false |
WhisperSystems/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/emoji/EmojiRemote.kt
|
2
|
2347
|
package org.thoughtcrime.securesms.emoji
import okhttp3.Request
import okhttp3.Response
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import java.io.IOException
private const val VERSION_URL = "https://updates.signal.org/dynamic/android/emoji/version.txt"
private const val BASE_STATIC_BUCKET_URL = "https://updates.signal.org/static/android/emoji"
/**
* Responsible for communicating with S3 to download Emoji related objects.
*/
object EmojiRemote {
private const val TAG = "EmojiRemote"
private val okHttpClient = ApplicationDependencies.getOkHttpClient()
@JvmStatic
@Throws(IOException::class)
fun getVersion(): Int {
val request = Request.Builder()
.get()
.url(VERSION_URL)
.build()
try {
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException()
}
return response.body()?.bytes()?.let { String(it).trim().toIntOrNull() } ?: throw IOException()
}
} catch (e: IOException) {
throw e
}
}
/**
* Downloads and returns the MD5 hash stored in an S3 object's ETag
*/
@JvmStatic
fun getMd5(emojiRequest: EmojiRequest): ByteArray? {
val request = Request.Builder()
.head()
.url(emojiRequest.url)
.build()
try {
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException()
}
return response.header("ETag")?.toByteArray()
}
} catch (e: IOException) {
Log.w(TAG, "Could not retrieve md5", e)
return null
}
}
/**
* Downloads an object for the specified name.
*/
@JvmStatic
fun getObject(emojiRequest: EmojiRequest): Response {
val request = Request.Builder()
.get()
.url(emojiRequest.url)
.build()
return okHttpClient.newCall(request).execute()
}
}
interface EmojiRequest {
val url: String
}
class EmojiJsonRequest(version: Int) : EmojiRequest {
override val url: String = "$BASE_STATIC_BUCKET_URL/$version/emoji_data.json"
}
class EmojiImageRequest(
version: Int,
density: String,
name: String,
format: String
) : EmojiRequest {
override val url: String = "$BASE_STATIC_BUCKET_URL/$version/$density/$name.$format"
}
|
gpl-3.0
|
22d3a8677d2fe4668cba8c295557ab68
| 23.705263 | 103 | 0.66553 | 4.032646 | false | false | false | false |
madisp/agp-tweeter
|
src/main/java/pink/madis/agptweeter/store/migrate.kt
|
1
|
2510
|
package pink.madis.agptweeter.store
import com.squareup.moshi.Moshi
import pink.madis.agptweeter.ArtifactConfig
import java.lang.IllegalStateException
import java.time.Instant
const val DB_VERSION: Int = 2
private var Store.version: Int
get() = Integer.parseInt(read("db_version") ?: "1")
set(value) = write("db_version", value.toString())
private var Store.keys: Set<String>
// we either have the keys or we have to guess...
get() = read("db_keys")?.split(',')?.toSet() ?: ArtifactConfig.values().map { it.key }.toSet() + "key" /* tests */
set(value) = write("db_keys", value.joinToString(separator = ","))
fun migrate(store: Store, moshi: Moshi): MigratedStore {
println("Checking $store for migration...")
val version = store.version
if (version == DB_VERSION) {
println("Nothing to migrate")
return MigratedStore(store)
}
val keys = store.keys
for (v in version until DB_VERSION) {
upgrade(store, v, moshi, keys)
}
println("Migration of $store completed")
return MigratedStore(store)
}
/**
* Upgrade the db schema by 1
*/
private fun upgrade(store: Store, currentVersion: Int, moshi: Moshi, keys: Collection<String>) {
println("Upgrading schema of $store: $currentVersion -> ${currentVersion+1}")
when (currentVersion) {
0 -> { /* initial version, nothing to do */ }
1 -> {
// store keys
store.keys = keys.toSet()
// add the pending field to keys
val v1Adapter = moshi.adapter(Version1::class.java)
val v2Adapter = moshi.adapter(Version2::class.java)
keys.asSequence()
.map { it to store.read(it)?.let(v1Adapter::fromJson) }
.map { (k, v) -> if (v == null) null else (k to v) }
.filterNotNull()
.forEach { (k, value) -> store.write(k, v2Adapter.toJson(Version2(value))) }
}
else -> { throw IllegalStateException("Don't know how to migrate $store from $currentVersion") }
}
store.version = currentVersion + 1
}
class MigratedStore internal constructor(private val store: Store): Store by store {
override fun write(key: String, value: String) {
store.write(key, value)
if (key != "db_keys") {
store.keys = store.keys + key
}
}
}
private data class Version1(val versions: List<String>)
private data class PendingVersion2(val version: String, val seenAt: Instant)
private data class Version2(val versions: List<String>, val pending: List<PendingVersion2>) {
constructor(v: Version1) : this(v.versions, emptyList())
}
|
mit
|
f5ae6a1795783313d333e041f943983f
| 32.932432 | 121 | 0.665737 | 3.621934 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vswin/utilities/registryUtils/impl/RegistryRoot.kt
|
2
|
2519
|
package com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.impl
import com.intellij.openapi.diagnostic.logger
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.throwIfNotAlive
import com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.IRegistryKey
import com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.IRegistryRoot
import com.sun.jna.platform.win32.Advapi32
import com.sun.jna.platform.win32.Advapi32Util
import com.sun.jna.platform.win32.WinReg
typealias WinRegAction<T> = (WinReg.HKEY) -> T
private val logger = logger<RegistryKey>()
class RegistryKey internal constructor(val key: String, private val registryRoot: RegistryRoot): IRegistryKey {
override fun withSuffix(suffix: String): IRegistryKey {
return RegistryKey("$key$suffix", registryRoot)
}
override fun inChild(child: String): IRegistryKey {
return RegistryKey("$key\\$child", registryRoot)
}
override fun getStringValue(value: String) = tryExecuteWithHKEY(key, value) {
if (!Advapi32Util.registryKeyExists(it, key)) {
return@tryExecuteWithHKEY null
}
return@tryExecuteWithHKEY Advapi32Util.registryGetStringValue(it, key, value)
}
override fun getKeys() = tryExecuteWithHKEY(key) { Advapi32Util.registryGetKeys(it, key) }?.toList()
override fun getValues() = tryExecuteWithHKEY(key) { Advapi32Util.registryGetValues(it, key) }
private fun <T> tryExecuteWithHKEY(vararg args: String, action: WinRegAction<T>): T? {
return registryRoot.executeWithHKEY {
try {
return@executeWithHKEY action(it)
}
catch (t: com.sun.jna.platform.win32.Win32Exception) {
logger.info("registry arguments: ${args.joinToString()}")
logger.warn("Failed to work with registry", t)
return@executeWithHKEY null
}
}
}
}
open class RegistryRoot(private val hKey: WinReg.HKEY, private val lifetime: Lifetime) : IRegistryRoot {
init {
lifetime.onTermination {
closeRoot()
}
}
fun <T> executeWithHKEY(action: WinRegAction<T>): T {
lifetime.throwIfNotAlive()
return action(hKey)
}
override fun fromKey(key: String): IRegistryKey {
return RegistryKey(key, this)
}
protected open fun closeRoot() {
Advapi32.INSTANCE.RegCloseKey(hKey)
}
}
|
apache-2.0
|
1c5268c2b50fab32bd21aa262ce93b54
| 37.181818 | 111 | 0.701072 | 3.911491 | false | false | false | false |
GunoH/intellij-community
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/BuildDependenciesOpenTelemetryTracer.kt
|
7
|
2548
|
// 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.intellij.build.impl
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.StatusCode
import org.jetbrains.intellij.build.TraceManager
import org.jetbrains.intellij.build.dependencies.telemetry.BuildDependenciesSpan
import org.jetbrains.intellij.build.dependencies.telemetry.BuildDependenciesTraceEventAttributes
import org.jetbrains.intellij.build.dependencies.telemetry.BuildDependenciesTracer
class BuildDependenciesOpenTelemetryTracer private constructor() : BuildDependenciesTracer {
companion object {
@JvmField
val INSTANCE: BuildDependenciesTracer = BuildDependenciesOpenTelemetryTracer()
}
override fun createAttributes(): BuildDependenciesTraceEventAttributes = BuildDependenciesOpenTelemetryAttributes()
override fun startSpan(name: String, attributes: BuildDependenciesTraceEventAttributes): BuildDependenciesSpan {
return BuildDependenciesOpenTelemetrySpan(name, attributes)
}
}
private class BuildDependenciesOpenTelemetrySpan(name: String, attributes: BuildDependenciesTraceEventAttributes) : BuildDependenciesSpan {
private val span: Span
init {
val spanBuilder = TraceManager.spanBuilder(name)
spanBuilder.setAllAttributes((attributes as BuildDependenciesOpenTelemetryAttributes).getAttributes())
span = spanBuilder.startSpan()
}
override fun addEvent(name: String, attributes: BuildDependenciesTraceEventAttributes) {
span.addEvent(name, (attributes as BuildDependenciesOpenTelemetryAttributes).getAttributes())
}
override fun recordException(throwable: Throwable) {
span.recordException(throwable)
}
override fun setStatus(status: BuildDependenciesSpan.SpanStatus) {
val statusCode = when (status) {
BuildDependenciesSpan.SpanStatus.UNSET -> StatusCode.UNSET
BuildDependenciesSpan.SpanStatus.OK -> StatusCode.OK
BuildDependenciesSpan.SpanStatus.ERROR -> StatusCode.ERROR
else -> throw IllegalArgumentException("Unsupported span status: $status")
}
span.setStatus(statusCode)
}
override fun close() {
span.end()
}
}
private class BuildDependenciesOpenTelemetryAttributes : BuildDependenciesTraceEventAttributes {
private val builder = Attributes.builder()
fun getAttributes(): Attributes = builder.build()
override fun setAttribute(name: String, value: String) {
builder.put(name, value)
}
}
|
apache-2.0
|
732bf8814f8c18078f1de4ee7634b09d
| 37.606061 | 139 | 0.80102 | 5.189409 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/FloatingToolbarComponentImpl.kt
|
5
|
1980
|
// 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.openapi.editor.toolbar.floating
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.observable.util.whenKeyPressed
import com.intellij.openapi.util.Disposer
import org.jetbrains.annotations.ApiStatus
import java.awt.Point
import java.awt.Rectangle
import java.awt.event.KeyEvent
import javax.swing.SwingUtilities
@ApiStatus.Internal
class FloatingToolbarComponentImpl(
editor: EditorEx,
provider: FloatingToolbarProvider,
parentDisposable: Disposable
) : AbstractFloatingToolbarComponent(provider.actionGroup, provider.autoHideable) {
init {
init(editor.contentComponent)
if (provider.autoHideable) {
initAutoHideableListeners(editor)
}
provider.register(editor.dataContext, this, this)
Disposer.register(parentDisposable, this)
}
private fun initAutoHideableListeners(editor: EditorEx) {
var ignoreMouseMotionRectangle: Rectangle? = null
editor.addEditorMouseMotionListener(object : EditorMouseMotionListener {
override fun mouseMoved(e: EditorMouseEvent) {
ignoreMouseMotionRectangle?.let {
if (!it.contains(e.mouseEvent.locationOnScreen)) {
ignoreMouseMotionRectangle = null
}
}
if (ignoreMouseMotionRectangle == null) {
scheduleShow()
}
}
}, this)
editor.contentComponent.whenKeyPressed(this) {
if (it.keyCode == KeyEvent.VK_ESCAPE) {
if (isVisible) {
val location = Point()
SwingUtilities.convertPointToScreen(location, this)
ignoreMouseMotionRectangle = Rectangle(location, size)
}
hideImmediately()
}
}
}
}
|
apache-2.0
|
5dfee82cd8d4e507e27ab48f676735d4
| 32.576271 | 140 | 0.734848 | 4.541284 | false | false | false | false |
waynepiekarski/XPlaneMonitor
|
app/src/main/java/net/waynepiekarski/xplanemonitor/TCPClient.kt
|
1
|
5810
|
// ---------------------------------------------------------------------
//
// XPlaneMonitor
//
// Copyright (C) 2017-2018 Wayne Piekarski
// [email protected] http://tinmith.net/wayne
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ---------------------------------------------------------------------
package net.waynepiekarski.xplanemonitor
import android.util.Log
import java.net.*
import kotlin.concurrent.thread
import java.io.*
class TCPClient (private var address: InetAddress, private var port: Int, private var callback: OnTCPEvent) {
private lateinit var socket: Socket
@Volatile private var cancelled = false
private lateinit var bufferedWriter: BufferedWriter
private lateinit var bufferedReader: BufferedReader
private lateinit var inputStreamReader: InputStreamReader
private lateinit var outputStreamWriter: OutputStreamWriter
interface OnTCPEvent {
fun onReceiveTCP(line: String, tcpRef: TCPClient)
fun onConnectTCP(tcpRef: TCPClient)
fun onDisconnectTCP(tcpRef: TCPClient)
}
fun stopListener() {
// Stop the loop from running any more
cancelled = true
// Call close on the top level buffers to cause any pending read to fail, ending the loop
closeBuffers()
// The socketThread loop will now clean up everything
}
fun writeln(str: String) {
if (cancelled) {
Log.d(Const.TAG, "Skipping write to cancelled socket: [$str]")
return
}
Log.d(Const.TAG, "Writing to TCP socket: [$str]")
try {
bufferedWriter.write(str + "\n")
bufferedWriter.flush()
} catch (e: IOException) {
Log.d(Const.TAG, "Failed to write [$str] to TCP socket with exception $e")
stopListener()
}
}
private fun closeBuffers() {
// Call close on the top level buffers which will propagate to the original socket
// and cause any pending reads and writes to fail
if (::bufferedWriter.isInitialized) {
try {
Log.d(Const.TAG, "Closing bufferedWriter")
bufferedWriter.close()
} catch (e: IOException) {
Log.d(Const.TAG, "Closing bufferedWriter in stopListener caused IOException, this is probably ok")
}
}
if (::bufferedReader.isInitialized) {
try {
Log.d(Const.TAG, "Closing bufferedReader")
bufferedReader.close()
} catch (e: IOException) {
Log.d(Const.TAG, "Closing bufferedReader in stopListener caused IOException, this is probably ok")
}
}
}
// In a separate function so we can "return" any time to bail out
private fun socketThread() {
try {
socket = Socket(address, port)
} catch (e: Exception) {
Log.e(Const.TAG, "Failed to connect to $address:$port with exception $e")
Thread.sleep(Const.ERROR_NETWORK_SLEEP)
MainActivity.doUiThread { callback.onDisconnectTCP(this) }
return
}
// Wrap the socket up so we can work with it - no exceptions should be thrown here
try {
inputStreamReader = InputStreamReader(socket.getInputStream())
bufferedReader = BufferedReader(inputStreamReader)
outputStreamWriter = OutputStreamWriter(socket.getOutputStream())
bufferedWriter = BufferedWriter(outputStreamWriter)
} catch (e: IOException) {
Log.e(Const.TAG, "Exception while opening socket buffers $e")
closeBuffers()
Thread.sleep(Const.ERROR_NETWORK_SLEEP)
MainActivity.doUiThread { callback.onDisconnectTCP(this) }
return
}
// Connection should be established, everything is ready to read and write
MainActivity.doUiThread { callback.onConnectTCP(this) }
// Start reading from the socket, any writes happen from another thread
while (!cancelled) {
var line: String?
try {
line = bufferedReader.readLine()
} catch (e: IOException) {
Log.d(Const.TAG, "Exception during socket readLine $e")
line = null
}
if (line == null) {
Log.d(Const.TAG, "readLine returned null, connection has failed")
cancelled = true
} else {
// Log.d(Const.TAG, "TCP returned line [$line]")
MainActivity.doUiThread { callback.onReceiveTCP(line, this) }
}
}
// Close any outer buffers we own, which will propagate to the original socket
closeBuffers()
// The connection is gone, tell the listener in case they need to update the UI
Thread.sleep(Const.ERROR_NETWORK_SLEEP)
MainActivity.doUiThread { callback.onDisconnectTCP(this) }
}
// Constructor starts a new thread to handle the blocking outbound connection
init {
Log.d(Const.TAG, "Created thread to connect to $address:$port")
thread(start = true) {
socketThread()
}
}
}
|
gpl-3.0
|
2b069ce91ec4301bcbddb4a3525d715b
| 36.973856 | 114 | 0.609639 | 4.785832 | false | false | false | false |
himikof/intellij-rust
|
src/main/kotlin/org/rust/lang/core/types/ty/TyArray.kt
|
1
|
575
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.resolve.ImplLookup
class TyArray(val base: Ty, val size: Int) : Ty {
override fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult =
if (other is TyArray && size == other.size) base.unifyWith(other.base, lookup) else UnifyResult.fail
override fun substitute(subst: Substitution): Ty =
TyArray(base.substitute(subst), size)
override fun toString() = "[$base; $size]"
}
|
mit
|
9dbd485450781d62597227d83f5ecd21
| 30.944444 | 108 | 0.697391 | 3.639241 | false | false | false | false |
codebutler/farebot
|
farebot-app/src/main/java/com/codebutler/farebot/app/core/kotlin/Optional.kt
|
1
|
1360
|
/*
* Optional.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.core.kotlin
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
fun <T> Observable<Optional<T>>.filterAndGetOptional(): Observable<T> = this
.filter { it.isPresent }
.map { it.get }
fun <T> Single<Optional<T>>.filterAndGetOptional(): Maybe<T> = this
.filter { it.isPresent }
.map { it.get }
data class Optional<out T>(val value: T?) {
val isPresent: Boolean
get() = value != null
val get: T
get() = value!!
}
|
gpl-3.0
|
12dfc961312753d34f4b459da8c666d7
| 30.627907 | 76 | 0.695588 | 3.788301 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt
|
2
|
10934
|
package eu.kanade.tachiyomi.ui.library
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import dev.chrisbanes.insetter.applyInsetter
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.SelectableAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.databinding.LibraryCategoryBinding
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.util.lang.plusAssign
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.util.view.inflate
import eu.kanade.tachiyomi.util.view.onAnimationsFinished
import eu.kanade.tachiyomi.widget.AutofitRecyclerView
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import reactivecircus.flowbinding.recyclerview.scrollStateChanges
import reactivecircus.flowbinding.swiperefreshlayout.refreshes
import rx.subscriptions.CompositeSubscription
import java.util.ArrayDeque
/**
* Fragment containing the library manga for a certain category.
*/
class LibraryCategoryView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
FrameLayout(context, attrs),
FlexibleAdapter.OnItemClickListener,
FlexibleAdapter.OnItemLongClickListener {
private val scope = MainScope()
/**
* The fragment containing this view.
*/
private lateinit var controller: LibraryController
/**
* Category for this view.
*/
lateinit var category: Category
private set
/**
* Recycler view of the list of manga.
*/
private lateinit var recycler: AutofitRecyclerView
/**
* Adapter to hold the manga in this category.
*/
private lateinit var adapter: LibraryCategoryAdapter
/**
* Subscriptions while the view is bound.
*/
private var subscriptions = CompositeSubscription()
private var lastClickPositionStack = ArrayDeque(listOf(-1))
fun onCreate(controller: LibraryController, binding: LibraryCategoryBinding, viewType: Int) {
this.controller = controller
recycler = if (viewType == LibraryAdapter.LIST_DISPLAY_MODE) {
(binding.swipeRefresh.inflate(R.layout.library_list_recycler) as AutofitRecyclerView).apply {
spanCount = 1
}
} else {
(binding.swipeRefresh.inflate(R.layout.library_grid_recycler) as AutofitRecyclerView).apply {
spanCount = controller.mangaPerRow
}
}
recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
adapter = LibraryCategoryAdapter(this)
recycler.setHasFixedSize(true)
recycler.adapter = adapter
binding.swipeRefresh.addView(recycler)
adapter.fastScroller = binding.fastScroller
recycler.scrollStateChanges()
.onEach {
// Disable swipe refresh when view is not at the top
val firstPos = (recycler.layoutManager as LinearLayoutManager)
.findFirstCompletelyVisibleItemPosition()
binding.swipeRefresh.isEnabled = firstPos <= 0
}
.launchIn(scope)
recycler.onAnimationsFinished {
(controller.activity as? MainActivity)?.ready = true
}
// Double the distance required to trigger sync
binding.swipeRefresh.setDistanceToTriggerSync((2 * 64 * resources.displayMetrics.density).toInt())
binding.swipeRefresh.refreshes()
.onEach {
if (LibraryUpdateService.start(context, category)) {
context.toast(R.string.updating_category)
}
// It can be a very long operation, so we disable swipe refresh and show a toast.
binding.swipeRefresh.isRefreshing = false
}
.launchIn(scope)
}
fun onBind(category: Category) {
this.category = category
adapter.mode = if (controller.selectedMangas.isNotEmpty()) {
SelectableAdapter.Mode.MULTI
} else {
SelectableAdapter.Mode.SINGLE
}
subscriptions += controller.searchRelay
.doOnNext { adapter.setFilter(it) }
.skip(1)
.subscribe { adapter.performFilter() }
subscriptions += controller.libraryMangaRelay
.subscribe { onNextLibraryManga(it) }
subscriptions += controller.selectionRelay
.subscribe { onSelectionChanged(it) }
subscriptions += controller.selectAllRelay
.filter { it == category.id }
.subscribe {
adapter.currentItems.forEach { item ->
controller.setSelection(item.manga, true)
}
controller.invalidateActionMode()
}
subscriptions += controller.selectInverseRelay
.filter { it == category.id }
.subscribe {
adapter.currentItems.forEach { item ->
controller.toggleSelection(item.manga)
}
controller.invalidateActionMode()
}
}
fun onRecycle() {
adapter.setItems(emptyList())
adapter.clearSelection()
unsubscribe()
}
fun onDestroy() {
unsubscribe()
scope.cancel()
}
private fun unsubscribe() {
subscriptions.clear()
}
/**
* Subscribe to [LibraryMangaEvent]. When an event is received, it updates the content of the
* adapter.
*
* @param event the event received.
*/
private fun onNextLibraryManga(event: LibraryMangaEvent) {
// Get the manga list for this category.
val mangaForCategory = event.getMangaForCategory(category).orEmpty()
// Update the category with its manga.
adapter.setItems(mangaForCategory)
if (adapter.mode == SelectableAdapter.Mode.MULTI) {
controller.selectedMangas.forEach { manga ->
val position = adapter.indexOf(manga)
if (position != -1 && !adapter.isSelected(position)) {
adapter.toggleSelection(position)
(recycler.findViewHolderForItemId(manga.id!!) as? LibraryHolder<*>)?.toggleActivation()
}
}
}
}
/**
* Subscribe to [LibrarySelectionEvent]. When an event is received, it updates the selection
* depending on the type of event received.
*
* @param event the selection event received.
*/
private fun onSelectionChanged(event: LibrarySelectionEvent) {
when (event) {
is LibrarySelectionEvent.Selected -> {
if (adapter.mode != SelectableAdapter.Mode.MULTI) {
adapter.mode = SelectableAdapter.Mode.MULTI
}
findAndToggleSelection(event.manga)
}
is LibrarySelectionEvent.Unselected -> {
findAndToggleSelection(event.manga)
with(adapter.indexOf(event.manga)) {
if (this != -1) lastClickPositionStack.remove(this)
}
if (controller.selectedMangas.isEmpty()) {
adapter.mode = SelectableAdapter.Mode.SINGLE
}
}
is LibrarySelectionEvent.Cleared -> {
adapter.mode = SelectableAdapter.Mode.SINGLE
adapter.clearSelection()
lastClickPositionStack.clear()
lastClickPositionStack.push(-1)
}
}
}
/**
* Toggles the selection for the given manga and updates the view if needed.
*
* @param manga the manga to toggle.
*/
private fun findAndToggleSelection(manga: Manga) {
val position = adapter.indexOf(manga)
if (position != -1) {
adapter.toggleSelection(position)
(recycler.findViewHolderForItemId(manga.id!!) as? LibraryHolder<*>)?.toggleActivation()
}
}
/**
* Called when a manga is clicked.
*
* @param position the position of the element clicked.
* @return true if the item should be selected, false otherwise.
*/
override fun onItemClick(view: View?, position: Int): Boolean {
// If the action mode is created and the position is valid, toggle the selection.
val item = adapter.getItem(position) ?: return false
return if (adapter.mode == SelectableAdapter.Mode.MULTI) {
if (adapter.isSelected(position)) {
lastClickPositionStack.remove(position)
} else {
lastClickPositionStack.push(position)
}
toggleSelection(position)
true
} else {
openManga(item.manga)
false
}
}
/**
* Called when a manga is long clicked.
*
* @param position the position of the element clicked.
*/
override fun onItemLongClick(position: Int) {
controller.createActionModeIfNeeded()
val lastClickPosition = lastClickPositionStack.peek()!!
when {
lastClickPosition == -1 -> setSelection(position)
lastClickPosition > position ->
for (i in position until lastClickPosition)
setSelection(i)
lastClickPosition < position ->
for (i in lastClickPosition + 1..position)
setSelection(i)
else -> setSelection(position)
}
if (lastClickPosition != position) {
lastClickPositionStack.remove(position)
lastClickPositionStack.push(position)
}
}
/**
* Opens a manga.
*
* @param manga the manga to open.
*/
private fun openManga(manga: Manga) {
controller.openManga(manga)
}
/**
* Tells the presenter to toggle the selection for the given position.
*
* @param position the position to toggle.
*/
private fun toggleSelection(position: Int) {
val item = adapter.getItem(position) ?: return
controller.setSelection(item.manga, !adapter.isSelected(position))
controller.invalidateActionMode()
}
/**
* Tells the presenter to set the selection for the given position.
*
* @param position the position to toggle.
*/
private fun setSelection(position: Int) {
val item = adapter.getItem(position) ?: return
controller.setSelection(item.manga, true)
controller.invalidateActionMode()
}
}
|
apache-2.0
|
2a50e104cd3c79f2523c704e23fd3335
| 32.437309 | 107 | 0.62356 | 5.162417 | false | false | false | false |
mdanielwork/intellij-community
|
java/execution/impl/src/com/intellij/execution/application/JvmMainMethodRunConfigurationOptions.kt
|
4
|
2295
|
// 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.execution.application
import com.intellij.configurationStore.Property
import com.intellij.execution.InputRedirectAware
import com.intellij.execution.JvmConfigurationOptions
import com.intellij.execution.ShortenCommandLine
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.XMap
import java.util.*
open class JvmMainMethodRunConfigurationOptions : JvmConfigurationOptions() {
@get:OptionTag("PROGRAM_PARAMETERS")
open var programParameters by string()
@get:OptionTag("WORKING_DIRECTORY")
open var workingDirectory by string()
@get:OptionTag("INCLUDE_PROVIDED_SCOPE")
var isIncludeProvidedScope by property(false)
@get:OptionTag("ENABLE_SWING_INSPECTOR")
var isSwingInspectorEnabled by property(false)
@get:OptionTag("PASS_PARENT_ENVS")
var isPassParentEnv by property(true)
@Property(description = "Environment variables")
@get:XMap(propertyElementName = "envs", entryTagName = "env", keyAttributeName = "name")
var env: MutableMap<String, String> by property(LinkedHashMap())
// see ConfigurationWithCommandLineShortener - "null if option was not selected explicitly, legacy user-local options to be used"
// so, we cannot use NONE as default value
@get:OptionTag(nameAttribute = "", valueAttribute = "name")
var shortenClasspath by enum<ShortenCommandLine>()
@get:OptionTag(InputRedirectAware.InputRedirectOptionsImpl.REDIRECT_INPUT)
var isRedirectInput by property(false)
@get:OptionTag(InputRedirectAware.InputRedirectOptionsImpl.INPUT_FILE)
var redirectInputPath by string()
@Transient
val redirectOptions = object : InputRedirectAware.InputRedirectOptions {
override fun isRedirectInput() = [email protected]
override fun setRedirectInput(value: Boolean) {
[email protected] = value
}
override fun getRedirectInputPath() = [email protected]
override fun setRedirectInputPath(value: String?) {
[email protected] = value
}
}
}
|
apache-2.0
|
0e97faf88a48a271f11c7dab6871e6c6
| 40 | 140 | 0.796514 | 4.741736 | false | true | false | false |
dhis2/dhis2-android-sdk
|
core/src/test/java/org/hisp/dhis/android/core/trackedentity/search/TrackedEntityInstanceQueryErrorCatcherShould.kt
|
1
|
4037
|
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.search
import com.google.common.truth.Truth.assertThat
import javax.net.ssl.HttpsURLConnection
import okhttp3.ResponseBody
import org.hisp.dhis.android.core.maintenance.D2ErrorCode
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import retrofit2.Response
@RunWith(JUnit4::class)
class TrackedEntityInstanceQueryErrorCatcherShould {
private val catcher: TrackedEntityInstanceQueryErrorCatcher = TrackedEntityInstanceQueryErrorCatcher()
@Test
fun return_too_many_orgunits() {
val response =
Response.error<Any>(HttpsURLConnection.HTTP_REQ_TOO_LONG, ResponseBody.create(null, ""))
assertThat(catcher.catchError(response, response.errorBody()!!.string()))
.isEqualTo(D2ErrorCode.TOO_MANY_ORG_UNITS)
}
@Test
fun return_max_tei_reached() {
val responseError =
"""{
"httpStatus": "Conflict",
"httpStatusCode": 409,
"status": "ERROR",
"message": "maxteicountreached"
}"""
val response = Response.error<Any>(409, ResponseBody.create(null, responseError))
assertThat(catcher.catchError(response, response.errorBody()!!.string()))
.isEqualTo(D2ErrorCode.MAX_TEI_COUNT_REACHED)
}
@Test
fun return_orgunit_not_in_search_scope() {
val responseError =
"""{
"httpStatus": "Conflict",
"httpStatusCode": 409,
"status": "ERROR",
"message": "Organisation unit is not part of the search scope: O6uvpzGd5pu"
}"""
val response = Response.error<Any>(409, ResponseBody.create(null, responseError))
assertThat(catcher.catchError(response, response.errorBody()!!.string()))
.isEqualTo(D2ErrorCode.ORGUNIT_NOT_IN_SEARCH_SCOPE)
}
@Test
fun return_min_search_attributes_required() {
val responseError =
"""{
"httpStatus": "Conflict",
"httpStatusCode": 409,
"status": "ERROR",
"message": "At least 1 attributes should be mentioned in the search criteria."
}"""
val response = Response.error<Any>(409, ResponseBody.create(null, responseError))
assertThat(catcher.catchError(response, response.errorBody()!!.string()))
.isEqualTo(D2ErrorCode.MIN_SEARCH_ATTRIBUTES_REQUIRED)
}
}
|
bsd-3-clause
|
457c57d07637d762e56f14f96ddda092
| 41.052083 | 106 | 0.693337 | 4.490545 | false | true | false | false |
TheMrMilchmann/lwjgl3
|
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/AMD_debug_output.kt
|
1
|
15137
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val AMD_debug_output = "AMDDebugOutput".nativeClassGL("AMD_debug_output", postfix = AMD) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows the GL to notify applications when various debug events occur in contexts that have been created with the debug flag, as provided
by ${WGL_ARB_create_context.link} and ${GLX_ARB_create_context.link}.
These events are represented in the form of enumerable messages with an included human-readable translation. Examples of debug events include incorrect
use of the GL, warnings of undefined behavior, and performance warnings.
A message is uniquely identified by a category and an implementation-dependent ID within that category. Message categories are general and are used to
organize large groups of similar messages together. Examples of categories include GL errors, performance warnings, and deprecated functionality
warnings. Each message is also assigned a severity level that denotes roughly how "important" that message is in comparison to other messages across all
categories. For example, notification of a GL error would have a higher severity than a performance warning due to redundant state changes.
Messages are communicated to the application through an application-defined callback function that is called by the GL implementation on each debug
message. The motivation for the callback routine is to free application developers from actively having to query whether any GL error or other
debuggable event has happened after each call to a GL function. With a callback, developers can keep their code free of debug checks, and only have to
react to messages as they occur. In order to support indirect rendering, a message log is also provided that stores copies of recent messages until they
are actively queried.
To control the volume of debug output, messages can be disabled either individually by ID, or entire groups of messages can be turned off based on
category or severity.
The only requirement on the minimum quantity and type of messages that implementations of this extension must support is that a message must be sent
notifying the application whenever any GL error occurs. Any further messages are left to the implementation. Implementations do not have to output
messages from all categories listed by this extension in order to support this extension, and new categories can be added by other extensions.
This extension places no restrictions or requirements on any additional functionality provided by the debug context flag through other extensions.
Requires ${WGL_ARB_create_context.link} or ${GLX_ARB_create_context.link}.
"""
IntConstant(
"Tokens accepted by GetIntegerv.",
"MAX_DEBUG_MESSAGE_LENGTH_AMD"..0x9143,
"MAX_DEBUG_LOGGED_MESSAGES_AMD"..0x9144,
"DEBUG_LOGGED_MESSAGES_AMD"..0x9145
)
val Severities = IntConstant(
"Tokens accepted by DebugMessageEnableAMD, GetDebugMessageLogAMD, DebugMessageInsertAMD, and DEBUGPROCAMD callback function for {@code severity}.",
"DEBUG_SEVERITY_HIGH_AMD"..0x9146,
"DEBUG_SEVERITY_MEDIUM_AMD"..0x9147,
"DEBUG_SEVERITY_LOW_AMD"..0x9148
).javaDocLinks
val Categories = IntConstant(
"Tokens accepted by DebugMessageEnableAMD, GetDebugMessageLogAMD, and DEBUGPROCAMD callback function for {@code category}.",
"DEBUG_CATEGORY_API_ERROR_AMD"..0x9149,
"DEBUG_CATEGORY_WINDOW_SYSTEM_AMD"..0x914A,
"DEBUG_CATEGORY_DEPRECATION_AMD"..0x914B,
"DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD"..0x914C,
"DEBUG_CATEGORY_PERFORMANCE_AMD"..0x914D,
"DEBUG_CATEGORY_SHADER_COMPILER_AMD"..0x914E,
"DEBUG_CATEGORY_APPLICATION_AMD"..0x914F,
"DEBUG_CATEGORY_OTHER_AMD"..0x9150
).javaDocLinks
void(
"DebugMessageEnableAMD",
"""
Allows disabling or enabling generation of subsets of messages. If {@code enabled} is #TRUE, the referenced subset of messages is enabled. If
#FALSE, then those messages are disabled. This command can reference different subsets of messages by varying its parameter values in the following
ways:
${ol(
"To reference all messages, let {@code category}, {@code severity}, and {@code count} all be zero. The value of {@code ids} is ignored in this case.",
"""
To reference all messages across all categories with a specific severity level, let {@code category} and {@code count} be zero and let
{@code severity} identify the severity level. The value of {@code ids} is ignored in this case.
""",
"""
To reference all messages within a single category, let {@code category} identify the referenced category and let {@code severity} and {@code count}
be zero. The value of {@code ids} is ignored in this case.
""",
"""
To reference all messages within a single category and at a specific severity level, let {@code category} identify the category and {@code severity}
identify the severity level, and let {@code count} be zero. The value of {@code ids} is ignored in this case.
""",
"""
To reference specific messages by ID within a single category, let {@code category} identify the category, let {@code severity} be zero, let
{@code count} be greater than zero and let {@code ids} identify the IDs of {@code count} messages within the identified category. Operations on
message IDs that are not valid within the category are silently ignored.
"""
)}
In all of the above cases, if {@code category} is non-zero and specifies an invalid category, the error #INVALID_ENUM is generated. Similarly if
{@code severity} is non-zero and is an invalid severity level, the error #INVALID_ENUM is generated. If {@code count} is less than zero, the error
#INVALID_VALUE is generated. If the parameters do not fall into one of the cases defined above, the error #INVALID_VALUE is generated. The error
#INVALID_OPERATION is generated if this command is called in a non-debug context.
Although messages are grouped into categories and severities, and entire groups of messages can be turned off with a single call, there is no explicit
per-category or per-severity enabled state. Instead the enabled state is stored individually for each message. There is no difference between disabling
a category of messages with a single call, and enumerating all messages of that category and individually disabling each of them by their ID.
All messages of severity level #DEBUG_SEVERITY_MEDIUM_AMD and #DEBUG_SEVERITY_HIGH_AMD in all categories are initially enabled, and all messages at
#DEBUG_SEVERITY_LOW_AMD are initially disabled.
""",
GLenum("category", "the message category", Categories),
GLenum("severity", "the message severity", Severities),
AutoSize("ids")..GLsizei("count", "the number of values in the {@code ids} array"),
SingleValue("id")..nullable..GLuint.const.p("ids", "an array of message ids"),
GLboolean("enabled", "whether to enable or disable the referenced subset of messages")
)
void(
"DebugMessageInsertAMD",
"""
Injects an application-supplied message into the debug message stream.
The value of {@code id} specifies the ID for the message and {@code severity} indicates its severity level as defined by the application. If
{@code severity} is not a valid severity level, the error #INVALID_ENUM will be generated. The value of {@code category} must be
#DEBUG_CATEGORY_APPLICATION_AMD, or the error #INVALID_ENUM will be generated. The string {@code buf} contains the string representation of the
message. The parameter {@code length} contains the size of the message's string representation, excluding the null-terminator. If {@code length} is
zero, then its value is derived from the string-length of {@code buf} and {@code buf} must contain a null-terminated string. The error
#INVALID_VALUE will be generated if {@code length} is less than zero or its derived value is larger than or equal to #MAX_DEBUG_MESSAGE_LENGTH_AMD.
The error #INVALID_OPERATION will be generated if this function is called in a non-debug context.
""",
GLenum("category", "the message category", "#DEBUG_CATEGORY_APPLICATION_AMD"),
GLenum("severity", "the message severity", Severities),
GLuint("id", "the message id"),
AutoSize("buf")..GLsizei("length", "the number of character in the message"),
GLcharUTF8.const.p("buf", "the message characters")
)
void(
"DebugMessageCallbackAMD",
"""
Specifies a callback to receive debugging messages from the GL.
With {@code callback} storing the address of the callback function. This function's signature must follow the type definition of DEBUGPROCAMD, and its
calling convention must be the same as the calling convention of GL functions. Anything else will result in undefined behavior. Only one debug callback
can be specified for the current context, and further calls overwrite the previous callback. Specifying zero as the value of {@code callback} clears the
current callback and disables message output through callbacks. Applications can specify user-specified data through the pointer {@code userParam}. The
context will store this pointer and will include it as one of the parameters of each call to the callback function. The error #INVALID_OPERATION
will be generated if this function is called for contexts created without the debug flag.
If the application has specified a callback function in a debug context, the implementation will call that function whenever any unfiltered message is
generated. The ID, category, and severity of the message are specified by the callback parameters {@code id}, {@code category} and {@code severity},
respectively. The string representation of the message is stored in {@code message} and its length (excluding the null-terminator) is stored in
{@code length}. The parameter {@code userParam} is the user-specified value that was passed when calling DebugMessageCallbackAMD. The memory for
{@code message} is allocated, owned and released by the implementation, and should only be considered valid for the duration of the callback function
call. While it is allowed to concurrently use multiple debug contexts with the same debug callback function, note that it is the application's
responsibility to ensure that any work that occurs inside the debug callback function is thread-safe. Furthermore, calling any GL or window layer
function from within the callback function results in undefined behavior.
If no callback is set, then messages are instead stored in an internal message log up to some maximum number of strings as defined by the
implementation-dependent constant #MAX_DEBUG_LOGGED_MESSAGES_AMD. Each context stores its own message log and will only store messages generated by
commands operating in that context. If the message log is full, then the oldest messages will be removed from the log to make room for newer ones. The
application can query the number of messages currently in the log by obtaining the value of #DEBUG_LOGGED_MESSAGES_AMD.
""",
nullable..GLDEBUGPROCAMD("callback", "a callback function that will be called when a debug message is generated"),
nullable..opaque_p(
"userParam",
"a user supplied pointer that will be passed on each invocation of {@code callback}"
)
)
GLuint(
"GetDebugMessageLogAMD",
"""
Retrieves messages from the debug message log.
This function will fetch as many messages as possible from the message log up to {@code count} in order from oldest to newest, and will return the
number of messages fetched. Those messages that were fetched will be removed from the log. The value of {@code count} must be greater than zero and less
than #MAX_DEBUG_LOGGED_MESSAGES_AMD or otherwise the error #INVALID_VALUE will be generated. The value of {@code count} can be larger than the
actual number of messages currently in the log. If {@code messageLog} is not a null pointer, then the string representations of all fetched messages
will be stored in the buffer {@code messageLog} and will be separated by null-terminators. The maximum size of the buffer (including all
null-terminators) is denoted by {@code bufSize}, and strings of messages within {@code count} that do not fit in the buffer will not be fetched. If
{@code bufSize} is less than zero, the error #INVALID_VALUE will be generated. If {@code messageLog} is a null pointer, then the value of
{@code bufSize} is ignored. The categories, severity levels, IDs, and string representation lengths of all (up to {@code count}) removed messages will
be stored in the arrays {@code categories}, {@code severities}, {@code ids}, and {@code lengths}, respectively. The counts stored in the array
{@code lengths} include the null-terminator of each string. Any and all of the output arrays, including {@code messageLog}, are optional, and no data is
returned for those arrays that are specified with a null pointer. To simply delete up to {@code count} messages from the message log and ignoring, the
application can call the function with null pointers for all output arrays. The error #INVALID_OPERATION will be generated by GetDebugMessageLogAMD
if it is called in a non-debug context.
""",
GLuint("count", "the number of debug messages to retrieve from the log"),
AutoSize("messageLog")..GLsizei("bufsize", "the maximum number of characters that can be written in the {@code message} array"),
Check("count")..nullable..GLenum.p("categories", "an array of variables to receive the categories of the retrieved messages"),
Check("count")..nullable..GLuint.p("severities", "an array of variables to receive the severities of the retrieved messages"),
Check("count")..nullable..GLuint.p("ids", "an array of variables to receive the ids of the retrieved messages"),
Check("count")..nullable..GLsizei.p("lengths", "an array of variables to receive the lengths of the retrieved messages"),
nullable..GLcharUTF8.p("messageLog", "an array of characters that will receive the messages")
)
}
|
bsd-3-clause
|
f0749560d85fda6ca4818e9a7463bbf2
| 73.940594 | 162 | 0.717712 | 4.913015 | false | false | false | false |
lisuperhong/ModularityApp
|
KaiyanModule/src/main/java/com/lisuperhong/openeye/http/OpenEyeRetrofit.kt
|
1
|
3677
|
package com.lisuperhong.openeye.http
import com.company.commonbusiness.http.RetrofitManager
import com.lisuperhong.openeye.OpenEyeApplication
import com.lisuperhong.openeye.utils.CommonUtil
import com.lisuperhong.openeye.utils.Constant
import com.lisuperhong.openeye.utils.NetworkUtil
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Retrofit
class OpenEyeRetrofit private constructor() {
private val retrofit: Retrofit
init {
val builder: OkHttpClient.Builder = RetrofitManager.instance.getClientBuilder()
builder.addInterceptor(addQueryParameterInterceptor())
RetrofitManager.instance.customClient(builder.build())
retrofit = RetrofitManager.instance.moduleRetrofit(Constant.HOST)
}
companion object {
val INSTANCE: OpenEyeRetrofit by lazy { OpenEyeRetrofit() }
}
/**
* 返回模块定义的接口Service
* @param service 接口服务
* @return <T> service实例
*/
fun <T> initService(service: Class<T>?): T {
if (service == null) {
throw RuntimeException("Api service is null!")
}
return retrofit.create(service)
}
/**
* 设置公共参数
*/
private fun addQueryParameterInterceptor(): Interceptor {
return Interceptor { chain ->
val originalRequest = chain.request()
val request: Request
val modifiedUrl = originalRequest.url().newBuilder()
.addQueryParameter("udid", "525fe2e3c24149e69947443589b7a9b137a01aaf")
.addQueryParameter("vc", "403")
.addQueryParameter("vn", CommonUtil.getVersionName())
.addQueryParameter("deviceModel", CommonUtil.getDeviceModel())
.addQueryParameter("first_channel", "eyepetizer_zhihuiyun_market")
.addQueryParameter("last_channel", "eyepetizer_zhihuiyun_market")
.addQueryParameter("system_version_code", CommonUtil.getSystemVersion().toString())
.build()
request = originalRequest.newBuilder().url(modifiedUrl).build()
chain.proceed(request)
}
}
/**
* 设置缓存
*/
// private fun addCacheInterceptor(): Interceptor {
// return Interceptor { chain ->
// var request = chain.request()
// if (!NetworkUtil.isNetworkAvailable(OpenEyeApplication.context)) {
// request = request.newBuilder()
// .cacheControl(CacheControl.FORCE_CACHE)
// .build()
// }
// val response = chain.proceed(request)
// if (NetworkUtil.isNetworkAvailable(OpenEyeApplication.context)) {
// val maxAge = 0
// // 有网络时 设置缓存超时时间0个小时 ,意思就是不读取缓存数据,只对get有用,post没有缓冲
// response.newBuilder()
// .header("Cache-Control", "public, max-age=" + maxAge)
// .removeHeader("Retrofit")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
// .build()
// } else {
// // 无网络时,设置超时为4周 只对get有用,post没有缓冲
// val maxStale = 60 * 60 * 24 * 28
// response.newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
// .removeHeader("nyn")
// .build()
// }
// response
// }
// }
}
|
apache-2.0
|
3747c5f8e17be45c543264a1a19ff3fb
| 36.096774 | 99 | 0.600464 | 4.354798 | false | false | false | false |
StephaneBg/ScoreIt
|
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/belote/BeloteEditionBonusFragment.kt
|
1
|
3189
|
/*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.edition.belote
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sbgapps.scoreit.app.R
import com.sbgapps.scoreit.app.databinding.FragmentEditionBeloteBonusBinding
import com.sbgapps.scoreit.data.model.BeloteBonusValue
import com.sbgapps.scoreit.data.model.PlayerPosition
import io.uniflow.androidx.flow.onStates
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
class BeloteEditionBonusFragment : BottomSheetDialogFragment() {
private val viewModel by sharedViewModel<BeloteEditionViewModel>()
private var beloteBonus: BeloteBonusValue = BeloteBonusValue.BELOTE
private lateinit var binding: FragmentEditionBeloteBonusBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentEditionBeloteBonusBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
onStates(viewModel) { state ->
if (state is BeloteEditionState.Content) {
binding.teamOne.text = state.players[PlayerPosition.ONE.index].name
binding.teamTwo.text = state.players[PlayerPosition.TWO.index].name
beloteBonus = state.availableBonuses.first()
binding.bonus.text = getString(beloteBonus.resId)
binding.bonus.setOnClickListener {
MaterialAlertDialogBuilder(requireContext())
.setSingleChoiceItems(
state.availableBonuses.map { getString(it.resId) }.toTypedArray(),
state.availableBonuses.indexOf(beloteBonus)
) { dialog, which ->
beloteBonus = state.availableBonuses[which]
binding.bonus.text = getString(beloteBonus.resId)
dialog.dismiss()
}
.show()
}
binding.addBonus.setOnClickListener {
viewModel.addBonus(getTeam() to beloteBonus)
dismiss()
}
}
}
}
private fun getTeam(): PlayerPosition =
if (R.id.teamOne == binding.teamGroup.checkedButtonId) PlayerPosition.ONE else PlayerPosition.TWO
}
|
apache-2.0
|
1572a2a11d1f008534a795b3cb5a4dfc
| 42.081081 | 116 | 0.679109 | 4.81571 | false | false | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/os/SystemRuntimeCollector.kt
|
2
|
6750
|
// 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.internal.statistic.collectors.fus.os
import com.intellij.internal.DebugAttachDetector
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventId1
import com.intellij.internal.statistic.eventLog.events.EventId2
import com.intellij.internal.statistic.eventLog.events.EventId3
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.internal.statistic.utils.StatisticsUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.Version
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.lang.JavaVersion
import com.intellij.util.system.CpuArch
import com.sun.management.OperatingSystemMXBean
import java.lang.management.ManagementFactory
import java.util.*
import kotlin.math.min
import kotlin.math.roundToInt
class SystemRuntimeCollector : ApplicationUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): Set<MetricEvent> {
val result = HashSet<MetricEvent>()
result.add(CORES.metric(StatisticsUtil.getUpperBound(Runtime.getRuntime().availableProcessors(),
intArrayOf(1, 2, 4, 6, 8, 12, 16, 20, 24, 32, 64))))
val osMxBean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean
val totalPhysicalMemory = StatisticsUtil.getUpperBound((osMxBean.totalPhysicalMemorySize.toDouble() / (1 shl 30)).roundToInt(),
intArrayOf(1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128, 256))
result.add(MEMORY_SIZE.metric(totalPhysicalMemory))
var totalSwapSize = (osMxBean.totalSwapSpaceSize.toDouble() / (1 shl 30)).roundToInt()
totalSwapSize = min(totalSwapSize, totalPhysicalMemory)
result.add(SWAP_SIZE.metric(if (totalSwapSize > 0) StatisticsUtil.getNextPowerOfTwo(totalSwapSize) else 0))
for (gc in ManagementFactory.getGarbageCollectorMXBeans()) {
result.add(GC.metric(gc.name))
}
result.add(JVM.metric(
Version(1, JavaVersion.current().feature, 0),
CpuArch.CURRENT.name.toLowerCase(Locale.ENGLISH),
getJavaVendor())
)
val options: HashMap<String, Long> = collectJvmOptions()
for (option in options) {
result.add(JVM_OPTION.metric(option.key, option.value))
}
result.add(DEBUG_AGENT.metric(DebugAttachDetector.isDebugEnabled()))
return result
}
private fun collectJvmOptions(): HashMap<String, Long> {
val options: HashMap<String, Long> = hashMapOf()
for (argument in ManagementFactory.getRuntimeMXBean().inputArguments) {
val data = convertOptionToData(argument)
if (data != null) {
options[data.first] = data.second
}
}
return options
}
private fun getJavaVendor() : String {
return when {
SystemInfo.isJetBrainsJvm -> "JetBrains"
SystemInfo.isOracleJvm -> "Oracle"
SystemInfo.isIbmJvm -> "IBM"
SystemInfo.isAzulJvm -> "Azul"
else -> "Other"
}
}
companion object {
private val knownOptions = ContainerUtil.newHashSet(
"-Xms", "-Xmx", "-XX:SoftRefLRUPolicyMSPerMB", "-XX:ReservedCodeCacheSize"
)
private val GROUP: EventLogGroup = EventLogGroup("system.runtime", 9)
private val DEBUG_AGENT: EventId1<Boolean> = GROUP.registerEvent("debug.agent", EventFields.Enabled)
private val CORES: EventId1<Int> = GROUP.registerEvent("cores", EventFields.Int("value"))
private val MEMORY_SIZE: EventId1<Int> = GROUP.registerEvent("memory.size", EventFields.Int("gigabytes"))
private val SWAP_SIZE: EventId1<Int> = GROUP.registerEvent("swap.size", EventFields.Int("gigabytes"))
private val GC: EventId1<String?> = GROUP.registerEvent("garbage.collector",
EventFields.String(
"name",
arrayListOf("Shenandoah", "G1_Young_Generation", "G1_Old_Generation", "Copy",
"MarkSweepCompact", "PS_MarkSweep", "PS_Scavenge", "ParNew", "ConcurrentMarkSweep")
)
)
private val JVM: EventId3<Version?, String?, String?> = GROUP.registerEvent("jvm",
EventFields.VersionByObject,
EventFields.String("arch", arrayListOf("x86", "x86_64", "arm64", "other", "unknown")),
EventFields.String("vendor", arrayListOf( "JetBrains", "Apple", "Oracle", "Sun", "IBM", "Azul", "Other"))
)
private val JVM_OPTION: EventId2<String?, Long> = GROUP.registerEvent("jvm.option",
EventFields.String("name", arrayListOf("Xmx", "Xms", "SoftRefLRUPolicyMSPerMB", "ReservedCodeCacheSize")),
EventFields.Long("value")
)
fun convertOptionToData(arg: String): Pair<String, Long>? {
val value = getMegabytes(arg).toLong()
if (value < 0) return null
when {
arg.startsWith("-Xmx") -> {
return "Xmx" to roundDown(value, 512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000)
}
arg.startsWith("-Xms") -> {
return "Xms" to roundDown(value, 64, 128, 256, 512)
}
arg.startsWith("-XX:SoftRefLRUPolicyMSPerMB") -> {
return "SoftRefLRUPolicyMSPerMB" to roundDown(value, 50, 100)
}
arg.startsWith("-XX:ReservedCodeCacheSize") -> {
return "ReservedCodeCacheSize" to roundDown(value, 240, 300, 400, 500)
}
else -> {
return null
}
}
}
private fun getMegabytes(s: String): Int {
var num = knownOptions.firstOrNull { s.startsWith(it) }
?.let { s.substring(it.length).toUpperCase().trim() }
if (num == null) return -1
if (num.startsWith("=")) num = num.substring(1)
if (num.last().isDigit()) {
return try {
Integer.parseInt(num)
}
catch (e: Exception) {
-1
}
}
try {
val size = Integer.parseInt(num.substring(0, num.length - 1))
when (num.last()) {
'B' -> return size / (1024 * 1024)
'K' -> return size / 1024
'M' -> return size
'G' -> return size * 1024
}
}
catch (e: Exception) {
return -1
}
return -1
}
fun roundDown(value: Long, vararg steps: Long): Long {
val length = steps.size
if (length == 0 || steps[0] < 0) return -1
var ind = 0
while (ind < length && value >= steps[ind]) {
ind++
}
return if (ind == 0) 0 else steps[ind - 1]
}
}
}
|
apache-2.0
|
ae521a294ded44b77b04e58f8ff35532
| 38.017341 | 140 | 0.657778 | 4.115854 | false | false | false | false |
allotria/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRTemplateLoader.kt
|
2
|
1512
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.TimeoutUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import org.jetbrains.plugins.github.util.submitIOTask
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
object GHPRTemplateLoader {
private val LOG = logger<GHPRTemplateLoader>()
private val paths = listOf(
".github/pull_request_template.md",
"pull_request_template.md",
"docs/pull_request_template.md"
)
fun readTemplate(project: Project): CompletableFuture<String?> {
return ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) {
doLoad(project)
}
}
@RequiresBackgroundThread
private fun doLoad(project: Project): String? {
val basePath = project.basePath ?: return null
try {
val files = paths.map { Paths.get(basePath, it) }
val fileContent = files.find(Files::exists)?.let(Files::readString)
if (fileContent != null) return fileContent
}
catch (e: Exception) {
LOG.warn("Failed to read PR template", e)
}
return null
}
}
|
apache-2.0
|
e2ad60ab62d100a04661d54cbcf38e73
| 33.386364 | 140 | 0.753307 | 4.247191 | false | false | false | false |
allotria/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageExtensions.kt
|
2
|
8124
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.workspaceModel.storage.WorkspaceEntity
// ------------------------- Updating references ------------------------
internal fun <Child : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToManyChildrenOfParent(connectionId: ConnectionId,
parentId: EntityId,
children: Sequence<Child>) {
refs.updateOneToManyChildrenOfParent(connectionId, parentId.arrayId, children)
}
internal fun <Child : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: EntityId,
children: Sequence<Child>) {
refs.updateOneToAbstractManyChildrenOfParent(connectionId, parentId, children)
}
internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToAbstractOneParentOfChild(connectionId: ConnectionId,
childId: EntityId,
parent: Parent) {
refs.updateOneToAbstractOneParentOfChild(connectionId, childId, parent)
}
internal fun <Child : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToOneChildOfParent(connectionId: ConnectionId,
parentId: EntityId,
child: Child?) {
if (child != null) {
refs.updateOneToOneChildOfParent(connectionId, parentId.arrayId, child)
}
else {
refs.removeOneToOneRefByParent(connectionId, parentId.arrayId)
}
}
internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToManyParentOfChild(connectionId: ConnectionId,
childId: EntityId,
parent: Parent?) {
if (parent != null) {
refs.updateOneToManyParentOfChild(connectionId, childId.arrayId, parent)
}
else {
refs.removeOneToManyRefsByChild(connectionId, childId.arrayId)
}
}
internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToOneParentOfChild(connectionId: ConnectionId,
childId: EntityId,
parent: Parent?) {
if (parent != null) {
refs.updateOneToOneParentOfChild(connectionId, childId.arrayId, parent)
}
else {
refs.removeOneToOneRefByChild(connectionId, childId.arrayId)
}
}
// ------------------------- Extracting references references ------------------------
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToManyChildren(connectionId: ConnectionId,
parentId: EntityId): Sequence<Child> {
val entitiesList = entitiesByType[connectionId.childClass] ?: return emptySequence()
return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map {
val entityData = entitiesList[it]
if (entityData == null) {
if (!brokenConsistency) {
thisLogger().error(
"""Cannot resolve entity.
|Connection id: $connectionId
|Unresolved array id: $it
|All child array ids: ${refs.getOneToManyChildren(connectionId, parentId.arrayId)?.toArray()}
""".trimMargin()
)
}
null
} else entityData.createEntity(this)
}?.filterNotNull() as? Sequence<Child> ?: emptySequence()
}
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId,
parentId: EntityId): Sequence<Child> {
return refs.getOneToAbstractManyChildren(connectionId, parentId)?.asSequence()?.map { pid ->
entityDataByIdOrDie(pid).createEntity(this)
} as? Sequence<Child> ?: emptySequence()
}
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractAbstractOneToOneChildren(connectionId: ConnectionId,
parentId: EntityId): Sequence<Child> {
return refs.getAbstractOneToOneChildren(connectionId, parentId)?.let { pid ->
sequenceOf(entityDataByIdOrDie(pid).createEntity(this))
} as? Sequence<Child> ?: emptySequence()
}
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractOneParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
return refs.getOneToAbstractOneParent(connectionId, childId)?.let { entityDataByIdOrDie(it).createEntity(this) as Parent }
}
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parentId: EntityId): Child? {
val entitiesList = entitiesByType[connectionId.childClass] ?: return null
return refs.getOneToOneChild(connectionId, parentId.arrayId) {
val childEntityData = entitiesList[it]
if (childEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a child in one to one connection.
Connection id: $connectionId
Parent id: $parentId
Child array id: $it
""".trimIndent())
}
null
}
else childEntityData.createEntity(this) as Child
}
}
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToOneParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToOneParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a parent in one to one connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToManyParent(connectionId: ConnectionId, childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToManyParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a parent in one to many connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
|
apache-2.0
|
69025d0d0334c76be81eb06ea51e0186
| 49.459627 | 144 | 0.582349 | 6.4992 | false | false | false | false |
allotria/intellij-community
|
platform/execution-impl/src/com/intellij/execution/ui/RunContentManagerImpl.kt
|
2
|
26828
|
// 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.execution.ui
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.Executor
import com.intellij.execution.KillableProcess
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.layout.impl.DockableGridContainerFactory
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.AppUIUtil
import com.intellij.ui.content.*
import com.intellij.ui.docking.DockManager
import com.intellij.util.ObjectUtils
import com.intellij.util.SmartList
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Predicate
import javax.swing.Icon
private val EXECUTOR_KEY: Key<Executor> = Key.create("Executor")
private val CLOSE_LISTENER_KEY: Key<ContentManagerListener> = Key.create("CloseListener")
class RunContentManagerImpl(private val project: Project) : RunContentManager {
private val toolWindowIdToBaseIcon: MutableMap<String, Icon> = HashMap()
private val toolWindowIdZBuffer = ConcurrentLinkedDeque<String>()
init {
val containerFactory = DockableGridContainerFactory()
DockManager.getInstance(project).register(DockableGridContainerFactory.TYPE, containerFactory, project)
AppUIExecutor.onUiThread().expireWith(project).submit { init() }
}
companion object {
@JvmField
val ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create<Boolean>("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY")
@ApiStatus.Internal
@JvmField
val TEMPORARY_CONFIGURATION_KEY = Key.create<RunnerAndConfigurationSettings>("TemporaryConfiguration")
@JvmStatic
fun copyContentAndBehavior(descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
if (contentToReuse != null) {
val attachedContent = contentToReuse.attachedContent
if (attachedContent != null && attachedContent.isValid) {
descriptor.setAttachedContent(attachedContent)
}
if (contentToReuse.isReuseToolWindowActivation) {
descriptor.isActivateToolWindowWhenAdded = contentToReuse.isActivateToolWindowWhenAdded
}
descriptor.contentToolWindowId = contentToReuse.contentToolWindowId
descriptor.isSelectContentWhenAdded = contentToReuse.isSelectContentWhenAdded
}
}
@JvmStatic
fun isTerminated(content: Content): Boolean {
val processHandler = getRunContentDescriptorByContent(content)?.processHandler ?: return true
return processHandler.isProcessTerminated
}
@JvmStatic
fun getRunContentDescriptorByContent(content: Content): RunContentDescriptor? {
return content.getUserData(RunContentDescriptor.DESCRIPTOR_KEY)
}
@JvmStatic
fun getExecutorByContent(content: Content): Executor? = content.getUserData(EXECUTOR_KEY)
}
// must be called on EDT
private fun init() {
val messageBusConnection = project.messageBus.connect()
messageBusConnection.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
toolWindowIdZBuffer.retainAll(toolWindowManager.toolWindowIdSet)
val activeToolWindowId = toolWindowManager.activeToolWindowId
if (activeToolWindowId != null && toolWindowIdZBuffer.remove(activeToolWindowId)) {
toolWindowIdZBuffer.addFirst(activeToolWindowId)
}
}
})
messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
processToolWindowContentManagers { _, contentManager ->
val contents = contentManager.contents
for (content in contents) {
val runContentDescriptor = getRunContentDescriptorByContent(content) ?: continue
if (runContentDescriptor.processHandler?.isProcessTerminated == true) {
contentManager.removeContent(content, true)
}
}
}
}
})
}
@ApiStatus.Internal
fun registerToolWindow(executor: Executor): ContentManager {
val toolWindowManager = getToolWindowManager()
val toolWindowId = executor.toolWindowId
var toolWindow = toolWindowManager.getToolWindow(toolWindowId)
if (toolWindow != null) {
return toolWindow.contentManager
}
toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask(
id = toolWindowId, icon = executor.toolWindowIcon, stripeTitle = executor::getActionName))
val contentManager = toolWindow.contentManager
contentManager.addDataProvider(object : DataProvider {
override fun getData(dataId: String): Any? {
if (PlatformDataKeys.HELP_ID.`is`(dataId)) return executor.helpId
return null
}
})
ContentManagerWatcher.watchContentManager(toolWindow, contentManager)
initToolWindow(executor, toolWindowId, executor.toolWindowIcon, contentManager)
return contentManager
}
private fun initToolWindow(executor: Executor?, toolWindowId: String, toolWindowIcon: Icon, contentManager: ContentManager) {
toolWindowIdToBaseIcon.put(toolWindowId, toolWindowIcon)
contentManager.addContentManagerListener(object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) {
if (event.operation != ContentManagerEvent.ContentOperation.add) {
return
}
val content = event.content
// Content manager contains contents related with different executors.
// Try to get executor from content.
// Must contain this user data since all content is added by this class.
val contentExecutor = executor ?: getExecutorByContent(content)!!
syncPublisher.contentSelected(getRunContentDescriptorByContent(content), contentExecutor)
content.helpId = contentExecutor.helpId
}
})
Disposer.register(contentManager, Disposable {
contentManager.removeAllContents(true)
toolWindowIdZBuffer.remove(toolWindowId)
toolWindowIdToBaseIcon.remove(toolWindowId)
})
toolWindowIdZBuffer.addLast(toolWindowId)
}
private val syncPublisher: RunContentWithExecutorListener
get() = project.messageBus.syncPublisher(RunContentManager.TOPIC)
override fun toFrontRunContent(requestor: Executor, handler: ProcessHandler) {
val descriptor = getDescriptorBy(handler, requestor) ?: return
toFrontRunContent(requestor, descriptor)
}
override fun toFrontRunContent(requestor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val contentManager = getContentManagerForRunner(requestor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
if (content != null) {
contentManager.setSelectedContent(content)
getToolWindowManager().getToolWindow(getToolWindowIdForRunner(requestor, descriptor))!!.show(null)
}
}, project.disposed)
}
override fun hideRunContent(executor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val toolWindow = getToolWindowManager().getToolWindow(getToolWindowIdForRunner(executor, descriptor))
toolWindow?.hide(null)
}, project.disposed)
}
override fun getSelectedContent(): RunContentDescriptor? {
for (activeWindow in toolWindowIdZBuffer) {
val contentManager = getContentManagerByToolWindowId(activeWindow) ?: continue
val selectedContent = contentManager.selectedContent
?: if (contentManager.contentCount == 0) {
// continue to the next window if the content manager is empty
continue
}
else {
// stop iteration over windows because there is some content in the window and the window is the last used one
break
}
// here we have selected content
return getRunContentDescriptorByContent(selectedContent)
}
return null
}
override fun removeRunContent(executor: Executor, descriptor: RunContentDescriptor): Boolean {
val contentManager = getContentManagerForRunner(executor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
return content != null && contentManager.removeContent(content, true)
}
override fun showRunContent(executor: Executor, descriptor: RunContentDescriptor) {
showRunContent(executor, descriptor, descriptor.executionId)
}
private fun showRunContent(executor: Executor, descriptor: RunContentDescriptor, executionId: Long) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val contentManager = getContentManagerForRunner(executor, descriptor)
val toolWindowId = getToolWindowIdForRunner(executor, descriptor)
val oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.displayName, getReuseCondition(toolWindowId))
val content: Content?
if (oldDescriptor == null) {
content = createNewContent(descriptor, executor)
}
else {
content = oldDescriptor.attachedContent!!
syncPublisher.contentRemoved(oldDescriptor, executor)
Disposer.dispose(oldDescriptor) // is of the same category, can be reused
}
content.executionId = executionId
content.component = descriptor.component
content.setPreferredFocusedComponent(descriptor.preferredFocusComputable)
content.putUserData(RunContentDescriptor.DESCRIPTOR_KEY, descriptor)
content.putUserData(EXECUTOR_KEY, executor)
content.displayName = descriptor.displayName
descriptor.setAttachedContent(content)
val toolWindow = getToolWindowManager().getToolWindow(toolWindowId)
val processHandler = descriptor.processHandler
if (processHandler != null) {
val processAdapter = object : ProcessAdapter() {
override fun startNotified(event: ProcessEvent) {
UIUtil.invokeLaterIfNeeded {
content.icon = ExecutionUtil.getLiveIndicator(descriptor.icon)
toolWindow!!.setIcon(ExecutionUtil.getLiveIndicator(toolWindowIdToBaseIcon[toolWindowId]))
}
}
override fun processTerminated(event: ProcessEvent) {
AppUIUtil.invokeLaterIfProjectAlive(project) {
val manager = getContentManagerByToolWindowId(toolWindowId) ?: return@invokeLaterIfProjectAlive
val alive = isAlive(manager)
setToolWindowIcon(alive, toolWindow!!)
val icon = descriptor.icon
content.icon = if (icon == null) executor.disabledIcon else IconLoader.getTransparentIcon(icon)
}
}
}
processHandler.addProcessListener(processAdapter)
val disposer = content.disposer
if (disposer != null) {
Disposer.register(disposer, Disposable { processHandler.removeProcessListener(processAdapter) })
}
}
if (oldDescriptor == null) {
contentManager.addContent(content)
content.putUserData(CLOSE_LISTENER_KEY, CloseListener(content, executor))
}
if (descriptor.isSelectContentWhenAdded /* also update selection when reused content is already selected */
|| oldDescriptor != null && contentManager.isSelected(content)) {
content.manager!!.setSelectedContent(content)
}
if (!descriptor.isActivateToolWindowWhenAdded) {
return
}
ApplicationManager.getApplication().invokeLater(Runnable {
// let's activate tool window, but don't move focus
//
// window.show() isn't valid here, because it will not
// mark the window as "last activated" windows and thus
// some action like navigation up/down in stacktrace wont
// work correctly
getToolWindowManager().getToolWindow(toolWindowId)!!.activate(
descriptor.activationCallback,
descriptor.isAutoFocusContent,
descriptor.isAutoFocusContent)
}, project.disposed)
}
private fun getContentManagerByToolWindowId(toolWindowId: String): ContentManager? {
project.serviceIfCreated<RunDashboardManager>()?.let {
if (it.toolWindowId == toolWindowId) {
return if (toolWindowIdToBaseIcon.contains(toolWindowId)) it.dashboardContentManager else null
}
}
return getToolWindowManager().getToolWindow(toolWindowId)?.contentManagerIfCreated
}
override fun getReuseContent(executionEnvironment: ExecutionEnvironment): RunContentDescriptor? {
if (ApplicationManager.getApplication().isUnitTestMode) {
return null
}
val contentToReuse = executionEnvironment.contentToReuse
if (contentToReuse != null) {
return contentToReuse
}
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
val reuseCondition: Predicate<Content>?
val contentManager: ContentManager
if (toolWindowId == null) {
contentManager = getContentManagerForRunner(executionEnvironment.executor, null)
reuseCondition = null
}
else {
contentManager = getOrCreateContentManagerForToolWindow(toolWindowId, executionEnvironment.executor)
reuseCondition = getReuseCondition(toolWindowId)
}
return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.executionId, executionEnvironment.toString(), reuseCondition)
}
private fun getReuseCondition(toolWindowId: String): Predicate<Content>? {
val runDashboardManager = RunDashboardManager.getInstance(project)
return if (runDashboardManager.toolWindowId == toolWindowId) runDashboardManager.reuseCondition else null
}
override fun findContentDescriptor(requestor: Executor, handler: ProcessHandler): RunContentDescriptor? {
return getDescriptorBy(handler, requestor)
}
override fun showRunContent(info: Executor, descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
copyContentAndBehavior(descriptor, contentToReuse)
showRunContent(info, descriptor, descriptor.executionId)
}
private fun getContentManagerForRunner(executor: Executor, descriptor: RunContentDescriptor?): ContentManager {
return getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor)
}
private fun getOrCreateContentManagerForToolWindow(id: String, executor: Executor): ContentManager {
val contentManager = getContentManagerByToolWindowId(id)
if (contentManager != null) {
return contentManager
}
val dashboardManager = RunDashboardManager.getInstance(project)
if (dashboardManager.toolWindowId == id) {
initToolWindow(null, dashboardManager.toolWindowId, dashboardManager.toolWindowIcon, dashboardManager.dashboardContentManager)
return dashboardManager.dashboardContentManager
}
else {
return registerToolWindow(executor)
}
}
override fun getToolWindowByDescriptor(descriptor: RunContentDescriptor): ToolWindow? {
descriptor.contentToolWindowId?.let {
return getToolWindowManager().getToolWindow(it)
}
processToolWindowContentManagers { toolWindow, contentManager ->
if (getRunContentByDescriptor(contentManager, descriptor) != null) {
return toolWindow
}
}
return null
}
private inline fun processToolWindowContentManagers(processor: (ToolWindow, ContentManager) -> Unit) {
val toolWindowManager = getToolWindowManager()
for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) {
val toolWindow = toolWindowManager.getToolWindow(executor.id) ?: continue
processor(toolWindow, toolWindow.contentManagerIfCreated ?: continue)
}
project.serviceIfCreated<RunDashboardManager>()?.let {
val toolWindowId = it.toolWindowId
if (toolWindowIdToBaseIcon.contains(toolWindowId)) {
processor(toolWindowManager.getToolWindow(toolWindowId) ?: return, it.dashboardContentManager)
}
}
}
override fun getAllDescriptors(): List<RunContentDescriptor> {
val descriptors: MutableList<RunContentDescriptor> = SmartList()
processToolWindowContentManagers { _, contentManager ->
for (content in contentManager.contents) {
getRunContentDescriptorByContent(content)?.let {
descriptors.add(it)
}
}
}
return descriptors
}
override fun selectRunContent(descriptor: RunContentDescriptor) {
processToolWindowContentManagers { _, contentManager ->
val content = getRunContentByDescriptor(contentManager, descriptor) ?: return@processToolWindowContentManagers
contentManager.setSelectedContent(content)
return
}
}
private fun getToolWindowManager() = ToolWindowManager.getInstance(project)
override fun getContentDescriptorToolWindowId(configuration: RunConfiguration?): String? {
if (configuration != null) {
val runDashboardManager = RunDashboardManager.getInstance(project)
if (runDashboardManager.isShowInDashboard(configuration)) {
return runDashboardManager.toolWindowId
}
}
return null
}
override fun getToolWindowIdByEnvironment(executionEnvironment: ExecutionEnvironment): String {
// Also there are some places where ToolWindowId.RUN or ToolWindowId.DEBUG are used directly.
// For example, HotSwapProgressImpl.NOTIFICATION_GROUP. All notifications for this group is shown in Debug tool window,
// however such notifications should be shown in Run Dashboard tool window, if run content is redirected to Run Dashboard tool window.
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
return toolWindowId ?: executionEnvironment.executor.toolWindowId
}
private fun getDescriptorBy(handler: ProcessHandler, runnerInfo: Executor): RunContentDescriptor? {
fun find(contents: Array<Content>): RunContentDescriptor? {
for (content in contents) {
val runContentDescriptor = getRunContentDescriptorByContent(content)
if (runContentDescriptor?.processHandler === handler) {
return runContentDescriptor
}
}
return null
}
find(getContentManagerForRunner(runnerInfo, null).contents)?.let {
return it
}
find(getContentManagerByToolWindowId(project.serviceIfCreated<RunDashboardManager>()?.toolWindowId ?: return null)?.contents ?: return null)?.let {
return it
}
return null
}
fun moveContent(executor: Executor, descriptor: RunContentDescriptor) {
val content = descriptor.attachedContent ?: return
val oldContentManager = content.manager
val newContentManager = getContentManagerForRunner(executor, descriptor)
if (oldContentManager == null || oldContentManager === newContentManager) return
val listener = content.getUserData(CLOSE_LISTENER_KEY)
if (listener != null) {
oldContentManager.removeContentManagerListener(listener)
}
oldContentManager.removeContent(content, false)
if (isAlive(descriptor)) {
if (!isAlive(oldContentManager)) {
updateToolWindowIcon(oldContentManager, false)
}
if (!isAlive(newContentManager)) {
updateToolWindowIcon(newContentManager, true)
}
}
newContentManager.addContent(content)
if (listener != null) {
newContentManager.addContentManagerListener(listener)
}
}
private fun updateToolWindowIcon(contentManagerToUpdate: ContentManager, alive: Boolean) {
processToolWindowContentManagers { toolWindow, contentManager ->
if (contentManagerToUpdate == contentManager) {
setToolWindowIcon(alive, toolWindow)
return
}
}
}
private fun setToolWindowIcon(alive: Boolean, toolWindow: ToolWindow) {
val base = toolWindowIdToBaseIcon.get(toolWindow.id)
toolWindow.setIcon(if (alive) ExecutionUtil.getLiveIndicator(base) else ObjectUtils.notNull(base, EmptyIcon.ICON_13))
}
private inner class CloseListener(content: Content, private val myExecutor: Executor) : BaseContentCloseListener(content, project) {
override fun disposeContent(content: Content) {
try {
val descriptor = getRunContentDescriptorByContent(content)
syncPublisher.contentRemoved(descriptor, myExecutor)
if (descriptor != null) {
Disposer.dispose(descriptor)
}
}
finally {
content.release()
}
}
override fun closeQuery(content: Content, projectClosing: Boolean): Boolean {
val descriptor = getRunContentDescriptorByContent(content) ?: return true
val processHandler = descriptor.processHandler
if (processHandler == null || processHandler.isProcessTerminated) {
return true
}
val sessionName = descriptor.displayName
val killable = processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess()
val task = object : WaitForProcessTask(processHandler, sessionName, projectClosing, project) {
override fun onCancel() {
if (killable && !processHandler.isProcessTerminated) {
(processHandler as KillableProcess).killProcess()
}
}
}
if (killable) {
val cancelText = ExecutionBundle.message("terminating.process.progress.kill")
task.cancelText = cancelText
task.cancelTooltipText = cancelText
}
return askUserAndWait(processHandler, sessionName, task)
}
}
}
private fun chooseReuseContentForDescriptor(contentManager: ContentManager,
descriptor: RunContentDescriptor?,
executionId: Long,
preferredName: String?,
reuseCondition: Predicate<in Content>?): RunContentDescriptor? {
var content: Content? = null
if (descriptor != null) {
//Stage one: some specific descriptors (like AnalyzeStacktrace) cannot be reused at all
if (descriptor.isContentReuseProhibited) {
return null
}
// stage two: try to get content from descriptor itself
val attachedContent = descriptor.attachedContent
if (attachedContent != null && attachedContent.isValid
&& contentManager.getIndexOfContent(attachedContent) != -1 && (descriptor.displayName == attachedContent.displayName || !attachedContent.isPinned)) {
content = attachedContent
}
}
// stage three: choose the content with name we prefer
if (content == null) {
content = getContentFromManager(contentManager, preferredName, executionId, reuseCondition)
}
if (content == null || !RunContentManagerImpl.isTerminated(content) || content.executionId == executionId && executionId != 0L) {
return null
}
val oldDescriptor = RunContentManagerImpl.getRunContentDescriptorByContent(content) ?: return null
if (oldDescriptor.isContentReuseProhibited) {
return null
}
if (descriptor == null || oldDescriptor.reusePolicy.canBeReusedBy(descriptor)) {
return oldDescriptor
}
return null
}
private fun getContentFromManager(contentManager: ContentManager,
preferredName: String?,
executionId: Long,
reuseCondition: Predicate<in Content>?): Content? {
val contents = contentManager.contents.toMutableList()
val first = contentManager.selectedContent
if (first != null && contents.remove(first)) {
//selected content should be checked first
contents.add(0, first)
}
if (preferredName != null) {
// try to match content with specified preferred name
for (c in contents) {
if (canReuseContent(c, executionId) && preferredName == c.displayName) {
return c
}
}
}
// return first "good" content
return contents.firstOrNull {
canReuseContent(it, executionId) && (reuseCondition == null || reuseCondition.test(it))
}
}
private fun canReuseContent(c: Content, executionId: Long): Boolean {
return !c.isPinned && RunContentManagerImpl.isTerminated(c) && !(c.executionId == executionId && executionId != 0L)
}
private fun getToolWindowIdForRunner(executor: Executor, descriptor: RunContentDescriptor?): String {
return descriptor?.contentToolWindowId ?: executor.toolWindowId
}
private fun createNewContent(descriptor: RunContentDescriptor, executor: Executor): Content {
val content = ContentFactory.SERVICE.getInstance().createContent(descriptor.component, descriptor.displayName, true)
content.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE)
content.icon = descriptor.icon ?: executor.toolWindowIcon
return content
}
private fun getRunContentByDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor): Content? {
return contentManager.contents.firstOrNull {
descriptor == RunContentManagerImpl.getRunContentDescriptorByContent(it)
}
}
private fun isAlive(contentManager: ContentManager): Boolean {
return contentManager.contents.any {
val descriptor = RunContentManagerImpl.getRunContentDescriptorByContent(it)
descriptor != null && isAlive(descriptor)
}
}
private fun isAlive(descriptor: RunContentDescriptor): Boolean {
val handler = descriptor.processHandler
return handler != null && !handler.isProcessTerminated
}
|
apache-2.0
|
5d05f8303c2750d43ecd89e24f3c6135
| 41.585714 | 157 | 0.736991 | 5.373122 | false | false | false | false |
allotria/intellij-community
|
platform/credential-store/src/keePass/KeePassFileManager.kt
|
3
|
10135
|
// 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.credentialStore.keePass
import com.intellij.credentialStore.*
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.kdbx.KdbxPassword
import com.intellij.credentialStore.kdbx.KdbxPassword.Companion.createAndClear
import com.intellij.credentialStore.kdbx.KeePassDatabase
import com.intellij.credentialStore.kdbx.loadKdbx
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts.DialogMessage
import com.intellij.openapi.util.NlsContexts.DialogTitle
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.Nls.Capitalization.Sentence
import java.awt.Component
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.security.SecureRandom
import javax.swing.JPasswordField
internal open class KeePassFileManager(private val file: Path,
masterKeyFile: Path,
private val masterKeyEncryptionSpec: EncryptionSpec,
private val secureRandom: Lazy<SecureRandom>) {
private val masterKeyFileStorage = MasterKeyFileStorage(masterKeyFile)
fun clear() {
if (!file.exists()) {
return
}
try {
// don't create with preloaded empty db because "clear" action should remove only IntelliJ group from database,
// but don't remove other groups
val masterPassword = masterKeyFileStorage.load()
if (masterPassword != null) {
val db = loadKdbx(file, KdbxPassword.createAndClear(masterPassword))
val store = KeePassCredentialStore(file, masterKeyFileStorage, db)
store.clear()
store.save(masterKeyEncryptionSpec)
return
}
}
catch (e: Exception) {
// ok, just remove file
if (e !is IncorrectMasterPasswordException && ApplicationManager.getApplication()?.isUnitTestMode == false) {
LOG.error(e)
}
}
file.delete()
}
fun import(fromFile: Path, event: AnActionEvent?) {
if (file == fromFile) {
return
}
try {
doImportOrUseExisting(fromFile, event)
}
catch (e: IncorrectMasterPasswordException) {
throw e
}
catch (e: Exception) {
LOG.warn(e)
Messages.showMessageDialog(event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)!!,
CredentialStoreBundle.message("kee.pass.dialog.message"),
CredentialStoreBundle.message("kee.pass.dialog.title.cannot.import"), Messages.getErrorIcon())
}
}
// throws IncorrectMasterPasswordException if user cancelled ask master password dialog
@Throws(IncorrectMasterPasswordException::class)
fun useExisting() {
if (file.exists()) {
if (!doImportOrUseExisting(file, event = null)) {
throw IncorrectMasterPasswordException()
}
}
else {
saveDatabase(file, KeePassDatabase(), generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom.value), masterKeyFileStorage, secureRandom.value)
}
}
private fun doImportOrUseExisting(file: Path, event: AnActionEvent?): Boolean {
val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)
// check master key file in parent dir of imported file
val possibleMasterKeyFile = file.parent.resolve(MASTER_KEY_FILE_NAME)
var masterPassword = MasterKeyFileStorage(possibleMasterKeyFile).load()
if (masterPassword != null) {
try {
loadKdbx(file, KdbxPassword(masterPassword))
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn("On import \"$file\" found existing master key file \"$possibleMasterKeyFile\" but key is not correct")
masterPassword = null
}
}
if (masterPassword == null && !requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.request.master.title"), contextComponent = contextComponent) {
try {
loadKdbx(file, KdbxPassword(it))
masterPassword = it
null
}
catch (e: IncorrectMasterPasswordException) {
CredentialStoreBundle.message("dialog.message.master.password.not.correct")
}
}) {
return false
}
if (file !== this.file) {
Files.copy(file, this.file, StandardCopyOption.REPLACE_EXISTING)
}
masterKeyFileStorage.save(createMasterKey(masterPassword!!))
return true
}
fun askAndSetMasterKey(event: AnActionEvent?, @Nls(capitalization = Sentence) topNote: String? = null): Boolean {
val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)
// to open old database, key can be required, so, to avoid showing 2 dialogs, check it before
val db = try {
if (file.exists()) loadKdbx(file, KdbxPassword(this.masterKeyFileStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true))) else KeePassDatabase()
}
catch (e: IncorrectMasterPasswordException) {
// ok, old key is required
return requestCurrentAndNewKeys(contextComponent)
}
return requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.title.set.master.password"), topNote = topNote, contextComponent = contextComponent) {
saveDatabase(file, db, createMasterKey(it), masterKeyFileStorage, secureRandom.value)
null
}
}
protected open fun requestCurrentAndNewKeys(contextComponent: Component?): Boolean {
val currentPasswordField = JPasswordField()
val newPasswordField = JPasswordField()
val panel = panel {
row(CredentialStoreBundle.message("kee.pass.row.current.password")) { currentPasswordField().focused() }
row(CredentialStoreBundle.message("kee.pass.row.new.password")) { newPasswordField() }
commentRow(CredentialStoreBundle.message("kee.pass.row.comment"))
}
return dialog(title = CredentialStoreBundle.message("kee.pass.dialog.default.title"), panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val current = checkIsEmpty(currentPasswordField, errors)
val new = checkIsEmpty(newPasswordField, errors)
if (errors.isEmpty()) {
try {
if (doSetNewMasterPassword(current!!, new!!)) {
return@dialog errors
}
}
catch (e: IncorrectMasterPasswordException) {
errors.add(ValidationInfo(CredentialStoreBundle.message("kee.pass.validation.info.current.password.incorrect"), currentPasswordField))
new?.fill(0.toChar())
}
}
else {
current?.fill(0.toChar())
new?.fill(0.toChar())
}
errors
}.showAndGet()
}
@Suppress("MemberVisibilityCanBePrivate")
protected fun doSetNewMasterPassword(current: CharArray, new: CharArray): Boolean {
val db = loadKdbx(file, createAndClear(current.toByteArrayAndClear()))
saveDatabase(file, db, createMasterKey(new), masterKeyFileStorage, secureRandom.value)
return false
}
private fun createMasterKey(value: CharArray) = createMasterKey(value.toByteArrayAndClear())
private fun createMasterKey(value: ByteArray, isAutoGenerated: Boolean = false) = MasterKey(value, isAutoGenerated, masterKeyEncryptionSpec)
private fun checkIsEmpty(field: JPasswordField, errors: MutableList<ValidationInfo>): CharArray? {
val chars = field.getTrimmedChars()
if (chars == null) {
errors.add(ValidationInfo(CredentialStoreBundle.message("kee.pass.validation.info.current.password.incorrect.current.empty"), field))
}
return chars
}
protected open fun requestMasterPassword(@DialogTitle title: String,
@Nls(capitalization = Sentence) topNote: String? = null,
contextComponent: Component? = null,
@DialogMessage ok: (value: ByteArray) -> String?): Boolean {
val passwordField = JPasswordField()
val panel = panel {
topNote?.let {
noteRow(it)
}
row(CredentialStoreBundle.message("kee.pass.row.master.password")) { passwordField().focused() }
}
return dialog(title = title, panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val value = checkIsEmpty(passwordField, errors)
if (errors.isEmpty()) {
val result = value!!.toByteArrayAndClear()
ok(result)?.let {
errors.add(ValidationInfo(it, passwordField))
}
if (!errors.isEmpty()) {
result.fill(0)
}
}
errors
}
.showAndGet()
}
fun saveMasterKeyToApplyNewEncryptionSpec() {
// if null, master key file doesn't exist now, it will be saved later somehow, no need to re-save with a new encryption spec
val existing = masterKeyFileStorage.load() ?: return
// no need to re-save db file because master password is not changed, only master key encryption spec changed
masterKeyFileStorage.save(createMasterKey(existing, isAutoGenerated = masterKeyFileStorage.isAutoGenerated()))
}
fun setCustomMasterPasswordIfNeeded(defaultDbFile: Path) {
// https://youtrack.jetbrains.com/issue/IDEA-174581#focus=streamItem-27-3081868-0-0
// for custom location require to set custom master password to make sure that user will be able to reuse file on another machine
if (file == defaultDbFile) {
return
}
if (!masterKeyFileStorage.isAutoGenerated()) {
return
}
askAndSetMasterKey(null, topNote = CredentialStoreBundle.message("kee.pass.top.note"))
}
}
|
apache-2.0
|
878f51ddf0b83638e1a3477bc2c4a273
| 39.063241 | 173 | 0.696991 | 4.90087 | false | false | false | false |
stevesea/RPGpad
|
app/src/main/kotlin/org/stevesea/adventuresmith/AboutActivity.kt
|
2
|
3300
|
/*
* Copyright (c) 2017 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.StaggeredGridLayoutManager
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter
import com.mikepenz.materialize.MaterializeBuilder
import kotlinx.android.synthetic.main.activity_about.recycler_about
import kotlinx.android.synthetic.main.activity_about.toolbar
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.debug
class AboutActivity : AppCompatActivity(), AnkoLogger {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
var versionName = ""
var versionCode = -1L
try {
val packageInfo = packageManager.getPackageInfo(packageName, 0)
versionName = packageInfo.versionName
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
versionCode = packageInfo.longVersionCode
} else {
versionCode = packageInfo.versionCode.toLong()
}
} catch (e: PackageManager.NameNotFoundException) {
debug("Ignored exception. ${e.message}")
}
setSupportActionBar(toolbar)
supportActionBar?.setTitle(R.string.nav_about)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
MaterializeBuilder()
.withActivity(this)
.withFullscreen(false)
.withStatusBarPadding(true)
.build()
val itemAdapter : FastItemAdapter<ResultItem> = FastItemAdapter<ResultItem>()
.withSelectable(false)
.withMultiSelect(false)
.withPositionBasedStateManagement(false)
as FastItemAdapter<ResultItem>
val resultsGridLayoutMgr = StaggeredGridLayoutManager(
resources.getInteger(R.integer.resultCols),
StaggeredGridLayoutManager.VERTICAL)
recycler_about.layoutManager = resultsGridLayoutMgr
recycler_about.itemAnimator = DefaultItemAnimator()
recycler_about.adapter = itemAdapter
itemAdapter.add(ResultItem(String.format(getString(R.string.about_app), versionName, versionCode)))
itemAdapter.add(ResultItem(getString(R.string.about_help)))
itemAdapter.add(ResultItem(getString(R.string.about_thirdparty)))
}
}
|
gpl-3.0
|
66a4da0262406efa698b5d43c032fb5b
| 37.823529 | 107 | 0.705758 | 4.78955 | false | false | false | false |
leafclick/intellij-community
|
python/src/com/jetbrains/python/codeInsight/intentions/PyConvertImportIntentionAction.kt
|
1
|
1690
|
// 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.jetbrains.python.codeInsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFromImportStatement
import com.jetbrains.python.psi.PyStatement
import org.jetbrains.annotations.PropertyKey
abstract class PyConvertImportIntentionAction(@PropertyKey(resourceBundle = PyBundle.BUNDLE) intentionText: String) : PyBaseIntentionAction() {
init {
text = PyBundle.message(intentionText)
}
override fun getFamilyName(): String = text
fun replaceImportStatement(statement: PyFromImportStatement, file: PsiFile, path: String) {
val imported = statement.importElements.joinToString(", ") { it.text }
val generator = PyElementGenerator.getInstance(file.project)
val languageLevel = LanguageLevel.forElement(file)
val generatedStatement = generator.createFromImportStatement(languageLevel, path, imported, null)
val formattedStatement = CodeStyleManager.getInstance(file.project).reformat(generatedStatement)
statement.replace(formattedStatement)
}
fun findStatement(file: PsiFile, editor: Editor): PyFromImportStatement? {
val position = file.findElementAt(editor.caretModel.offset)
return PsiTreeUtil.getParentOfType(position, PyFromImportStatement::class.java, true, PyStatement::class.java)
}
}
|
apache-2.0
|
2a8a3a742176aaf084622b75c6fbf82c
| 43.473684 | 143 | 0.805917 | 4.642857 | false | false | false | false |
leafclick/intellij-community
|
plugins/laf/win10/src/com/intellij/laf/win10/WinIntelliJLaf.kt
|
1
|
1067
|
package com.intellij.laf.win10
import com.intellij.ide.ui.laf.IntelliJLaf
import com.intellij.ide.ui.laf.MenuArrowIcon
import com.intellij.util.ui.UIUtil
import javax.swing.UIDefaults
class WinIntelliJLaf : IntelliJLaf() {
init {
putUserData(UIUtil.PLUGGABLE_LAF_KEY, name)
}
override fun getName(): String {
return WinLafProvider.LAF_NAME
}
override fun getPrefix(): String {
return "win10intellijlaf"
}
override fun getSystemPrefix(): String? {
return null
}
override fun loadDefaults(defaults: UIDefaults) {
super.loadDefaults(defaults)
defaults["ClassLoader"] = javaClass.classLoader
defaults["Menu.arrowIcon"] = Win10MenuArrowIcon()
}
private class Win10MenuArrowIcon :
MenuArrowIcon(WinIconLookup.getIcon(name = MENU_TRIANGLE_ICON_NAME),
WinIconLookup.getIcon(name = MENU_TRIANGLE_ICON_NAME, selected = true),
WinIconLookup.getIcon(name = MENU_TRIANGLE_ICON_NAME, enabled = false))
companion object {
const val MENU_TRIANGLE_ICON_NAME = "menuTriangle"
}
}
|
apache-2.0
|
0b8ac5a1b67bbf7b87aa7903625160db
| 26.384615 | 89 | 0.716026 | 3.865942 | false | false | false | false |
zdary/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrAttributeExpressionReference.kt
|
16
|
1605
|
// 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 org.jetbrains.plugins.groovy.lang.resolve.references
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference
import org.jetbrains.plugins.groovy.lang.resolve.initialState
import org.jetbrains.plugins.groovy.lang.resolve.processReceiverType
import org.jetbrains.plugins.groovy.lang.resolve.processSpread
import org.jetbrains.plugins.groovy.lang.resolve.processors.FirstFieldProcessor
class GrAttributeExpressionReference(element: GrReferenceExpression) : GroovyCachingReference<GrReferenceExpression>(element) {
init {
require(element.hasAt())
require(element.isQualified)
}
override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> {
val expression = element
val attributeName = expression.referenceName ?: return emptyList()
val receiver = requireNotNull(expression.qualifier).type ?: return emptyList()
val processor = FirstFieldProcessor(attributeName, expression)
val state = initialState(false)
if (expression.dotTokenType == GroovyElementTypes.T_SPREAD_DOT) {
receiver.processSpread(processor, state, expression)
}
else {
receiver.processReceiverType(processor, state, expression)
}
return processor.results
}
}
|
apache-2.0
|
bfdbd978631a2cdbeddb8f8b360c80eb
| 46.205882 | 140 | 0.800623 | 4.495798 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Conv.kt
|
1
|
16339
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.apache.commons.lang3.StringUtils
import org.nd4j.autodiff.samediff.SDIndex
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.common.util.ArrayUtil
import org.nd4j.enums.Mode
import org.nd4j.enums.WeightsFormat
import org.nd4j.linalg.api.buffer.DataType
import org.nd4j.linalg.api.ops.impl.layers.convolution.config.Conv1DConfig
import org.nd4j.linalg.api.ops.impl.layers.convolution.config.Conv2DConfig
import org.nd4j.linalg.api.ops.impl.layers.convolution.config.Conv3DConfig
import org.nd4j.linalg.api.ops.impl.layers.convolution.config.PaddingMode
import org.nd4j.linalg.factory.Nd4j
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.ImportUtils
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* A port of cast.py from onnx tensorflow for samediff:
* https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/cast.py
*
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["Conv"],frameworkName = "onnx")
class Conv : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val inWeights = sd.getVariable(op.inputsToOp[1])
val weightsRank = inWeights.shape.size
var inputVariable = sd.getVariable(op.inputsToOp[0])
val rank = weightsRank
val xShape = inputVariable.shape
val spatialSize = rank - 2
val storageComputeFormat = ImportUtils.getDataFormat(rank)
val computeIndex = storageComputeFormat.second.indexOf('C')
val spatialFormat = StringUtils.join(storageComputeFormat.second.filter { input -> input == 'C' || input == 'W' })
val perm = (2 to weightsRank - 1).toList() + listOf(1,0)
val kernelShape = if(attributes.containsKey("kernel_shape")) {
val kernelShapeList = attributes["kernel_shape"] as List<Int>
kernelShapeList.map { input -> input }.toIntArray()
} else {
val weightsShape = inWeights.shape
weightsShape.map { input -> input.toInt() }.toIntArray()
}
var weights = sd.permute(inWeights,*perm.toIntArray())
var inWeightsShape = ArrayUtil.permute(ArrayUtil.copy(inWeights.shape),perm.toIntArray())
val dilations = if(attributes.containsKey("dilations")) {
val dilationsList = attributes["dilations"] as List<Int>
val dilationsArr = dilationsList
dilationsList.map { input -> input.toLong() }
} else {
List<Long>(spatialSize) { _ -> 1}
}
val spatialSizeConst = sd.constant(spatialSize)
val strides = if(attributes.containsKey("strides")) {
val stridesList = attributes["strides"] as List<Int>
val stridesArr = stridesList
stridesArr.map { input -> input.toLong() }
} else {
List<Long>(spatialSize) { _ -> 1}
}
val pads = if(attributes.containsKey("pads")) {
val padsList = attributes["pads"] as List<Int>
padsList.map { input -> input.toLong() }
} else {
val newPadsList = mutableListOf<Long>(0,0)
for(i in 0 until spatialSize) {
newPadsList.add(0)
}
newPadsList
}
val defaultPads2 = defaultPads(spatialSize)
var padMode = attributes["auto_pad"] as String?
if(!attributes.containsKey("auto_pad") || attributes["auto_pad"] == "NOTSET") {
if(pads != defaultPads2) {
inputVariable = paddingOp(sd,inputVariable,pads)
//note our padding is not quite the same is onnx
//our valid is equivalent to NOTSET and paddings should not be modified
padMode = "NOTSET"
}
} else if(padMode == "SAME_UPPER") {
padMode = "SAME"
} else if(padMode == "VALID") {
padMode = "VALID"
} else if(padMode == "SAME_LOWER") {
throw IllegalArgumentException("Unable to convert model running SAME_LOWER")
}
var groups = attributes.getOrDefault("group",1) as Number
groups = groups.toLong()
var depthWise = (rank == 4 && weightsRank == 4 && groups.toInt() != 1)
if(depthWise && xShape != null && xShape[1].toInt() != -1) {
depthWise = depthWise && groups == xShape[1]
}
/* if depthwise and x.get_shape().as_list()[1] != None:
depthwise = bool(group == x.get_shape().as_list()[1])
* */
var xs = mutableListOf<SDVariable>()
var weightGroupsList = mutableListOf<SDVariable>()
if(depthWise) {
val depthWiseFilterShape = mutableListOf<Int>()
for(i in 0 until 2) depthWiseFilterShape.add(inWeightsShape[i].toInt())
depthWiseFilterShape.add(-1)
depthWiseFilterShape.add(Math.floorDiv(weights.shape[3].toInt(),groups.toInt()))
weights = weights.reshape(*depthWiseFilterShape.toIntArray())
inputVariable = sd.permute(inputVariable,*ImportUtils.getPermFromFormats(storageComputeFormat.first,storageComputeFormat.second))
xs.add(inputVariable)
weightGroupsList.add(weights)
} else {
val weightGroups = sd.split(weights,groups.toInt(),-1)
val permuteFormat = ImportUtils.getPermFromFormats(storageComputeFormat.first,storageComputeFormat.second)
inputVariable = sd.permute(inputVariable,*permuteFormat)
if(groups.toInt() == 1)
xs.add(inputVariable)
else {
xs.addAll(sd.split(inputVariable,groups.toInt(),-1))
}
weightGroupsList.addAll(weightGroups)
}
val convolvedList = mutableListOf<SDVariable>()
var stridesList = mutableListOf<Long>()
if(depthWise) {
if(storageComputeFormat.second == "NHWC") {
stridesList.add(1)
stridesList.addAll(strides)
stridesList.add(1)
} else {
stridesList.add(1)
stridesList.add(1)
stridesList.addAll(strides)
}
val convConfig = Conv2DConfig.builder()
.kH(kernelShape[0].toLong())
.kW(kernelShape[1].toLong())
.sH(strides[0])
.sW(strides[1])
.dH(dilations[0])
.dW(dilations[1])
.dataFormat("NWHC")
.weightsFormat(WeightsFormat.YXIO)
.paddingMode(padModeForName(padMode!!))
.build()
for(i in 0 until xs.size) {
var depthWiseConv2d = sd.cnn().depthWiseConv2d(xs[i.toInt()], weightGroupsList[i.toInt()], convConfig)
convolvedList.add(depthWiseConv2d)
}
} else {
for(i in 0 until groups) {
if(rank == 3) {
//notset => valid
//valid => valid + pads zeroed
var totalPad = if(padMode == "NOTSET") {
0
} else {
pads[0]
}
val oneDConfig = Conv1DConfig.builder()
.k(kernelShape[0].toLong())
.dataFormat("NWC")
.d(dilations[0])
.p(totalPad)
.s(strides[0])
.paddingMode(PaddingMode.valueOf(padMode!!))
.build()
var convolved = sd.cnn().conv1d(xs[i.toInt()],weightGroupsList[i.toInt()], oneDConfig)
if(pads[0] > 0) {
convolved = convolved.get(*indicesForPads("NWC",pads).toTypedArray())
}
convolvedList.add(convolved)
} else if(rank == 4) {
//notset => valid
//valid => valid + pads zeroed
var totalPadHeight = if(padMode == "NOTSET") {
0
} else {
pads[1]
}
var totalPadWidth = if(padMode == "NOTSET") {
0
} else {
pads[2]
}
val convConfig = Conv2DConfig.builder()
.kH(kernelShape[0].toLong())
.kW(kernelShape[1].toLong())
.sH(strides[0])
.sW(strides[1])
.pH(totalPadHeight)
.pW(totalPadWidth)
.dH(dilations[0])
.dW(dilations[1])
.dataFormat("NHWC")
.weightsFormat(WeightsFormat.YXIO)
.paddingMode(padModeForName(padMode!!))
.build()
var conv2d = sd.cnn().conv2d(xs[i.toInt()], weightGroupsList[i.toInt()], convConfig)
convolvedList.add(conv2d)
} else if(rank == 5) {
var totalPadHeight = if(padMode == "NOTSET") {
0
} else {
pads[1]
}
var totalPadWidth = if(padMode == "NOTSET") {
0
} else {
pads[2]
}
var totalPadDepth = if(padMode == "NOTSET") {
0
} else {
pads[2]
}
val threeDConfig = Conv3DConfig.builder()
.kD(kernelShape[0].toLong())
.kH(kernelShape[1].toLong())
.kW(kernelShape[2].toLong())
.dD(dilations[0])
.dH(dilations[1])
.dW(dilations[2])
.pD(totalPadDepth).pH(totalPadHeight)
.pW(totalPadWidth)
.biasUsed(false)
.dataFormat("NWHDC")
.paddingMode(padModeForName(padMode!!))
.build()
var conv3d = sd.cnn().conv3d(xs[i.toInt()],weightGroupsList[i.toInt()], threeDConfig)
convolvedList.add(conv3d)
}
}
}
//grouped convolutions need to handle bias differently
if(op.inputsToOp.size > 2) {
val bias = sd.getVariable(op.inputsToOp[2])
var output = sd.concat(-1,*convolvedList.toTypedArray())
output = output.add(bias)
output = sd.permute(outputNames[0],output,*ImportUtils.getPermFromFormats(storageComputeFormat.second,storageComputeFormat.first))
return mapOf(output.name() to listOf(output))
} else {
var output = sd.concat(-1,*convolvedList.toTypedArray())
val newPermute = ImportUtils.getPermFromFormats(storageComputeFormat.second,storageComputeFormat.first)
output = sd.permute(outputNames[0],output,*newPermute)
return mapOf(output.name() to listOf(output))
}
}
fun padModeForName(name: String): PaddingMode {
return when(name) {
"VALID" -> PaddingMode.VALID
"SAME" -> PaddingMode.SAME
"NOTSET" -> PaddingMode.VALID
else -> PaddingMode.CAUSAL
}
}
fun indicesForPads(dataFormat: String,pads: List<Long>): List<SDIndex> {
val ret = ArrayList<SDIndex>()
val rank = dataFormat.length
when(pads.size) {
//1D cnn
3 -> {
val widthIdx = dataFormat.indexOf("W")
for(i in 0 until rank) {
if(i == widthIdx) {
ret.add(SDIndex.interval(pads[i], - pads[i] - 1))
} else {
ret.add(SDIndex.all())
}
}
}
//2d CNN
4 -> {
val widthIdx = dataFormat.indexOf("W")
val heightIdx = dataFormat.indexOf("H")
for(i in 0 until rank) {
if(i == widthIdx) {
ret.add(SDIndex.interval(pads[i], - pads[i] - 1))
} else if(i == heightIdx) {
ret.add(SDIndex.interval(pads[i],- pads[i] - 1))
} else {
ret.add(SDIndex.all())
}
}
}
//3D CNN
5 -> {
val widthIdx = dataFormat.indexOf("W")
val heightIdx = dataFormat.indexOf("H")
val depthIdx = dataFormat.indexOf("D")
for(i in 0 until rank) {
if(i == widthIdx) {
ret.add(SDIndex.interval(pads[i], - pads[i] - 1))
} else if(i == heightIdx) {
ret.add(SDIndex.interval(pads[i], - pads[i] - 1))
} else if(i == depthIdx) {
ret.add(SDIndex.interval(pads[i], - pads[i] - 1))
} else {
ret.add(SDIndex.all())
}
}
}
}
return ret
}
fun adaptPads(inputPads: List<Long>): List<Long> {
if(inputPads.size == 4) {
return listOf(inputPads[0], inputPads[2], inputPads[1], inputPads[3])
}
return inputPads
}
fun defaultPads(spatialSize : Int): List<Int> {
val newPadsList = mutableListOf(0,0)
for(i in 0 until spatialSize) {
newPadsList.add(0)
}
return newPadsList
}
fun paddingOp(sd: SameDiff,x: SDVariable,pads: List<Long>): SDVariable {
val adaptedPads = adaptPads(pads)
val numDim = adaptedPads.size / 2
val newPads = Nd4j.create(Nd4j.createBuffer(adaptedPads.toLongArray())).transpose().reshape('c',2,numDim)
val newPads2 = Nd4j.concat(0,Nd4j.create(Nd4j.createBuffer(longArrayOf(0,0,0,0))).reshape(4),newPads.ravel().reshape(newPads.length()))
val inputPadding = sd.constant(newPads2.reshape('c',numDim + 2,2).castTo(DataType.INT32))
return sd.image().pad(x,inputPadding,Mode.CONSTANT,0.0)
}
}
|
apache-2.0
|
b7903757d96693b28cd7984b9d15d1dc
| 39.952381 | 184 | 0.5351 | 4.165987 | false | false | false | false |
smmribeiro/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/hints/settings/InlayHintsPanel.kt
|
11
|
3313
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.settings
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.hints.InlayHintsSettings
import com.intellij.codeInsight.hints.ParameterHintsPassFactory
import com.intellij.lang.Language
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import javax.swing.*
import javax.swing.border.EmptyBorder
class InlayHintsPanel(languages: Iterable<Language>) : JPanel() {
private val hintsEnabledGlobally = JCheckBox(CodeInsightBundle.message("inlay.hints.show.hints.for"), true)
private val languagePanels = languages.map { LanguagePanel(it) }
init {
layout = BorderLayout()
val label = JLabel(CodeInsightBundle.message("inlay.hints.language.list.description"))
add(label, BorderLayout.NORTH)
add(createListPanel(), BorderLayout.WEST)
reset()
}
private fun createListPanel(): JPanel {
val panel = JPanel()
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
panel.border = JBUI.Borders.empty(0, 10, 0, 0)
panel.add(Box.createRigidArea(JBUI.size(0, 10)))
val toggleGloballyCheckBox = hintsEnabledGlobally
toggleGloballyCheckBox.addActionListener {
val selected = toggleGloballyCheckBox.isSelected
for (languagePanel in languagePanels) {
languagePanel.setCheckBoxEnabled(selected)
}
}
panel.add(toggleGloballyCheckBox)
for (languagePanel in languagePanels) {
languagePanel.alignmentX = 0f
languagePanel.border = EmptyBorder(1, 17, 3, 1)
panel.add(languagePanel)
}
return panel
}
fun isModified() : Boolean {
val settings = InlayHintsSettings.instance()
if (hintsEnabledGlobally.isSelected != settings.hintsEnabledGlobally()) {
return true
}
for ((index, panel) in languagePanels.withIndex()) {
val checkboxSelected = languagePanels[index].selected()
val inSettingsEnabled = settings.hintsEnabled(panel.language)
if (checkboxSelected != inSettingsEnabled) return true
}
return false
}
fun apply() {
val settings = InlayHintsSettings.instance()
settings.setEnabledGlobally(hintsEnabledGlobally.isSelected)
for ((index, panel) in languagePanels.withIndex()) {
settings.setHintsEnabledForLanguage(panel.language, languagePanels[index].selected())
}
ParameterHintsPassFactory.forceHintsUpdateOnNextPass()
}
fun reset() {
val settings = InlayHintsSettings.instance()
hintsEnabledGlobally.isSelected = settings.hintsEnabledGlobally()
for ((index, panel) in languagePanels.withIndex()) {
val languagePanel = languagePanels[index]
languagePanel.select(settings.hintsEnabled(panel.language))
languagePanel.setCheckBoxEnabled(settings.hintsEnabledGlobally())
}
}
}
private class LanguagePanel(val language: Language) : JPanel() {
val checkBox = JCheckBox(language.displayName)
init {
layout = BoxLayout(this, BoxLayout.X_AXIS)
add(checkBox)
}
fun selected() :Boolean {
return checkBox.isSelected
}
fun select(value: Boolean) {
checkBox.isSelected = value
}
fun setCheckBoxEnabled(value: Boolean) {
checkBox.isEnabled = value
}
}
|
apache-2.0
|
1474d91f7279f979857c32dfba24189a
| 32.816327 | 140 | 0.735285 | 4.388079 | false | false | false | false |
smmribeiro/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaULambdaExpression.kt
|
2
|
3057
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
@ApiStatus.Internal
class JavaULambdaExpression(
override val sourcePsi: PsiLambdaExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), ULambdaExpression {
override val functionalInterfaceType: PsiType?
get() = sourcePsi.functionalInterfaceType
override val valueParameters: List<UParameter> by lz {
sourcePsi.parameterList.parameters.map { JavaUParameter(it, this) }
}
override val body: UExpression by lz {
val b = sourcePsi.body
when (b) {
is PsiCodeBlock -> JavaConverter.convertBlock(b, this)
is PsiExpression -> wrapLambdaBody(this, b)
else -> UastEmptyExpression(this)
}
}
}
private fun wrapLambdaBody(parent: JavaULambdaExpression, b: PsiExpression): UBlockExpression =
JavaImplicitUBlockExpression(parent).apply {
expressions = listOf(JavaImplicitUReturnExpression(this).apply {
returnExpression = JavaConverter.convertOrEmpty(b, this)
})
}
private class JavaImplicitUReturnExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UReturnExpression {
override val label: String?
get() = null
override val jumpTarget: UElement? =
getParentOfType(ULambdaExpression::class.java, strict = true)
override val sourcePsi: PsiElement?
get() = null
override val psi: PsiElement?
get() = null
override lateinit var returnExpression: UExpression
internal set
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as JavaImplicitUReturnExpression
val b = returnExpression != other.returnExpression
if (b) return false
return true
}
override fun hashCode(): Int = 31 + returnExpression.hashCode()
}
private class JavaImplicitUBlockExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UBlockExpression {
override val sourcePsi: PsiElement?
get() = null
override lateinit var expressions: List<UExpression>
internal set
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as JavaImplicitUBlockExpression
if (expressions != other.expressions) return false
return true
}
override fun hashCode(): Int = 31 + expressions.hashCode()
}
|
apache-2.0
|
d40395388866f33199d6cdbd73826b55
| 30.515464 | 127 | 0.739614 | 4.710324 | false | false | false | false |
Flank/flank
|
test_runner/src/main/kotlin/ftl/presentation/cli/AuthCommand.kt
|
1
|
389
|
package ftl.presentation.cli
import ftl.presentation.cli.auth.LoginCommand
import ftl.util.PrintHelpCommand
import picocli.CommandLine.Command
@Command(
name = "auth",
synopsisHeading = "%n",
header = ["Manage oauth2 credentials for Google Cloud"],
subcommands = [
LoginCommand::class
],
usageHelpAutoWidth = true
)
class AuthCommand : PrintHelpCommand()
|
apache-2.0
|
fa657ad55aae4c4d168c9f93d747a09c
| 23.3125 | 60 | 0.722365 | 4.138298 | false | false | false | false |
macoscope/KetchupLunch
|
app/src/main/java/com/macoscope/ketchuplunch/presenter/LoginPresenter.kt
|
1
|
3873
|
package com.macoscope.ketchuplunch.presenter
import android.accounts.AccountManager
import android.app.Activity
import android.content.Intent
import com.macoscope.ketchuplunch.model.GooglePlayServices
import com.macoscope.ketchuplunch.model.NetworkAvailability
import com.macoscope.ketchuplunch.model.login.AccountRepository
import com.macoscope.ketchuplunch.model.login.GoogleCredentialWrapper
import com.macoscope.ketchuplunch.view.login.LoginView
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.lang.kotlin.deferredObservable
import rx.schedulers.Schedulers
class LoginPresenter(val loginView: LoginView,
val accountRepository: AccountRepository,
val googlePlayServices: GooglePlayServices,
val networkAvailability: NetworkAvailability,
val googleCredentialsWrapper: GoogleCredentialWrapper) {
private val REQUEST_ACCOUNT_PICKER = 1000
private val REQUEST_AUTHORIZATION = 1001
private val REQUEST_GOOGLE_PLAY_SERVICES = 1002
fun onCreate() {
deferredObservable {
Observable.just(isGooglePlayServicesAvailable())
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
when {
!it -> acquireGooglePlayServices()
!accountRepository.isAccountNameDefined() -> chooseAccount()
!isDeviceOnline() -> displayNoNetworkMessage()
else -> openMealsScreen()
}
}
}
private fun displayNoNetworkMessage() {
loginView.showNoNetworkMessage()
}
private fun openMealsScreen() {
loginView.startLunchActivity()
}
private fun chooseAccount() {
if (loginView.hasAccountPermissions()) {
permissionGranted()
} else {
loginView.requestAccountPermissions()
}
}
private fun isGooglePlayServicesAvailable(): Boolean = googlePlayServices.isAvailable()
private fun acquireGooglePlayServices() {
val (isAvailable, connectionStatusCode) = googlePlayServices.acquireServices()
if (!isAvailable) {
loginView.showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode, REQUEST_GOOGLE_PLAY_SERVICES)
}
}
private fun isDeviceOnline(): Boolean = networkAvailability.isDeviceOnline()
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_GOOGLE_PLAY_SERVICES -> resultGooglePlayServicesRequest(resultCode)
REQUEST_ACCOUNT_PICKER -> storeAccountName(resultCode, data)
REQUEST_AUTHORIZATION -> {
if (resultCode == Activity.RESULT_OK) {
openMealsScreen()
}
}
}
}
private fun storeAccountName(resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK
&& data != null
&& data.extras != null) {
val accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
if (accountName != null) {
accountRepository.setAccountName(accountName)
openMealsScreen()
}
}
}
private fun resultGooglePlayServicesRequest(resultCode: Int) {
if (resultCode != Activity.RESULT_OK) {
loginView.showNoGooglePlayServices()
} else {
openMealsScreen()
}
}
fun permissionDenied() {
//We display choose account dialog until user grants permission
chooseAccount()
}
fun permissionGranted() {
loginView.openSelectAccountDialog(googleCredentialsWrapper.userCredential, REQUEST_ACCOUNT_PICKER)
}
}
|
apache-2.0
|
5f2fd0ec8c852198cfb724ec3a940e0d
| 33.891892 | 119 | 0.646527 | 5.524964 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt
|
1
|
2300
|
package info.nightscout.androidaps.plugins.source
import android.content.Intent
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TomatoPlugin @Inject constructor(
injector: HasAndroidInjector,
resourceHelper: ResourceHelper,
aapsLogger: AAPSLogger,
private val sp: SP,
private val nsUpload: NSUpload
) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginIcon(R.drawable.ic_sensor)
.pluginName(R.string.tomato)
.preferencesId(R.xml.pref_bgsource)
.shortName(R.string.tomato_short)
.description(R.string.description_source_tomato),
aapsLogger, resourceHelper, injector
), BgSourceInterface {
override fun advancedFilteringSupported(): Boolean {
return false
}
override fun handleNewData(intent: Intent) {
if (!isEnabled(PluginType.BGSOURCE)) return
val bundle = intent.extras ?: return
val bgReading = BgReading()
aapsLogger.debug(LTag.BGSOURCE, "Received Tomato Data")
bgReading.value = bundle.getDouble("com.fanqies.tomatofn.Extras.BgEstimate")
bgReading.date = bundle.getLong("com.fanqies.tomatofn.Extras.Time")
val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Tomato")
if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
nsUpload.uploadBg(bgReading, "AndroidAPS-Tomato")
}
if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
nsUpload.sendToXdrip(bgReading)
}
}
}
|
agpl-3.0
|
d0bf772ade5a83f6f9547579b3d16d5b
| 39.368421 | 84 | 0.762174 | 4.204753 | false | false | false | false |
stepstone-tech/android-material-app-rating
|
app-rating/src/main/java/com/stepstone/apprating/common/Preconditions.kt
|
1
|
16285
|
package com.stepstone.apprating.common
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.*
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
* Note that the sense of the expression is inverted; with `Preconditions`
* you declare what you expect to be *true*, just as you do with an
* [
* `assert`](http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html) or a JUnit `assertTrue` call.
*
* **Warning:** only the `"%s"` specifier is recognized as a
* placeholder in these messages, not the full range of [ ][String.format] specifiers.
*
* Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* [IndexOutOfBoundsException], [NoSuchElementException], [ ] and others -- are used to signal that the
* *calling method* has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps ever. Postcondition or other invariant failures should not throw
* these types of exceptions.
* @author Kevin Bourrillion
*/
object Preconditions {
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
* @param expression a boolean expression
* *
* @throws IllegalArgumentException if `expression` is false
*/
fun checkArgument(expression: Boolean) {
if (!expression) {
throw IllegalArgumentException()
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
* @param expression a boolean expression
* *
* @param errorMessage the exception message to use if the check fails; will
* * be converted to a string using [String.valueOf]
* *
* @throws IllegalArgumentException if `expression` is false
*/
fun checkArgument(expression: Boolean, errorMessage: Any) {
if (!expression) {
throw IllegalArgumentException(errorMessage.toString())
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
* @param expression a boolean expression
* *
* @param errorMessageTemplate a template for the exception message should the
* * check fail. The message is formed by replacing each `%s`
* * placeholder in the template with an argument. These are matched by
* * position - the first `%s` gets `errorMessageArgs[0]`, etc.
* * Unmatched arguments will be appended to the formatted message in square
* * braces. Unmatched placeholders will be left as-is.
* *
* @param errorMessageArgs the arguments to be substituted into the message
* * template. Arguments are converted to strings using
* * [String.valueOf].
* *
* @throws IllegalArgumentException if `expression` is false
* *
* @throws NullPointerException if the check fails and either `errorMessageTemplate` or `errorMessageArgs` is null (don't let
* * this happen)
*/
fun checkArgument(expression: Boolean,
errorMessageTemplate: String, vararg errorMessageArgs: Any) {
if (!expression) {
throw IllegalArgumentException(
format(errorMessageTemplate, *errorMessageArgs))
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
* @param expression a boolean expression
* *
* @throws IllegalStateException if `expression` is false
*/
fun checkState(expression: Boolean) {
if (!expression) {
throw IllegalStateException()
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
* @param expression a boolean expression
* *
* @param errorMessage the exception message to use if the check fails; will
* * be converted to a string using [String.valueOf]
* *
* @throws IllegalStateException if `expression` is false
*/
fun checkState(expression: Boolean, errorMessage: Any) {
if (!expression) {
throw IllegalStateException(errorMessage.toString())
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
* @param expression a boolean expression
* *
* @param errorMessageTemplate a template for the exception message should the
* * check fail. The message is formed by replacing each `%s`
* * placeholder in the template with an argument. These are matched by
* * position - the first `%s` gets `errorMessageArgs[0]`, etc.
* * Unmatched arguments will be appended to the formatted message in square
* * braces. Unmatched placeholders will be left as-is.
* *
* @param errorMessageArgs the arguments to be substituted into the message
* * template. Arguments are converted to strings using
* * [String.valueOf].
* *
* @throws IllegalStateException if `expression` is false
* *
* @throws NullPointerException if the check fails and either `errorMessageTemplate` or `errorMessageArgs` is null (don't let
* * this happen)
*/
fun checkState(expression: Boolean,
errorMessageTemplate: String, vararg errorMessageArgs: Any) {
if (!expression) {
throw IllegalStateException(
format(errorMessageTemplate, *errorMessageArgs))
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
* @param reference an object reference
* *
* @return the non-null reference that was validated
* *
* @throws NullPointerException if `reference` is null
*/
fun <T> checkNotNull(reference: T?): T {
if (reference == null) {
throw NullPointerException()
}
return reference
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
* @param reference an object reference
* *
* @param errorMessage the exception message to use if the check fails; will
* * be converted to a string using [String.valueOf]
* *
* @return the non-null reference that was validated
* *
* @throws NullPointerException if `reference` is null
*/
fun <T> checkNotNull(reference: T?, errorMessage: Any): T {
if (reference == null) {
throw NullPointerException(errorMessage.toString())
}
return reference
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
* @param reference an object reference
* *
* @param errorMessageTemplate a template for the exception message should the
* * check fail. The message is formed by replacing each `%s`
* * placeholder in the template with an argument. These are matched by
* * position - the first `%s` gets `errorMessageArgs[0]`, etc.
* * Unmatched arguments will be appended to the formatted message in square
* * braces. Unmatched placeholders will be left as-is.
* *
* @param errorMessageArgs the arguments to be substituted into the message
* * template. Arguments are converted to strings using
* * [String.valueOf].
* *
* @return the non-null reference that was validated
* *
* @throws NullPointerException if `reference` is null
*/
fun <T> checkNotNull(reference: T?, errorMessageTemplate: String,
vararg errorMessageArgs: Any): T {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw NullPointerException(
format(errorMessageTemplate, *errorMessageArgs))
}
return reference
}
/**
* Ensures that `index` specifies a valid *element* in an array,
* list or string of size `size`. An element index may range from zero,
* inclusive, to `size`, exclusive.
* @param index a user-supplied index identifying an element of an array, list
* * or string
* *
* @param size the size of that array, list or string
* *
* @param desc the text to use to describe this index in an error message
* *
* @return the value of `index`
* *
* @throws IndexOutOfBoundsException if `index` is negative or is not
* * less than `size`
* *
* @throws IllegalArgumentException if `size` is negative
*/
@JvmOverloads
fun checkElementIndex(index: Int, size: Int, desc: String = "index"): Int {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw IndexOutOfBoundsException(badElementIndex(index, size, desc))
}
return index
}
private fun badElementIndex(index: Int, size: Int, desc: String): String {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index)
} else if (size < 0) {
throw IllegalArgumentException("negative size: " + size)
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size)
}
}
/**
* Ensures that `index` specifies a valid *position* in an array,
* list or string of size `size`. A position index may range from zero
* to `size`, inclusive.
* @param index a user-supplied index identifying a position in an array, list
* * or string
* *
* @param size the size of that array, list or string
* *
* @param desc the text to use to describe this index in an error message
* *
* @return the value of `index`
* *
* @throws IndexOutOfBoundsException if `index` is negative or is
* * greater than `size`
* *
* @throws IllegalArgumentException if `size` is negative
*/
@JvmOverloads
fun checkPositionIndex(index: Int, size: Int, desc: String = "index"): Int {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw IndexOutOfBoundsException(badPositionIndex(index, size, desc))
}
return index
}
private fun badPositionIndex(index: Int, size: Int, desc: String): String {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index)
} else if (size < 0) {
throw IllegalArgumentException("negative size: " + size)
} else { // index > size
return format("%s (%s) must not be greater than size (%s)",
desc, index, size)
}
}
/**
* Ensures that `start` and `end` specify a valid *positions*
* in an array, list or string of size `size`, and are in order. A
* position index may range from zero to `size`, inclusive.
* @param start a user-supplied index identifying a starting position in an
* * array, list or string
* *
* @param end a user-supplied index identifying a ending position in an array,
* * list or string
* *
* @param size the size of that array, list or string
* *
* @throws IndexOutOfBoundsException if either index is negative or is
* * greater than `size`, or if `end` is less than `start`
* *
* @throws IllegalArgumentException if `size` is negative
*/
fun checkPositionIndexes(start: Int, end: Int, size: Int) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw IndexOutOfBoundsException(badPositionIndexes(start, end, size))
}
}
private fun badPositionIndexes(start: Int, end: Int, size: Int): String {
if (start < 0 || start > size) {
return badPositionIndex(start, size, "start index")
}
if (end < 0 || end > size) {
return badPositionIndex(end, size, "end index")
}
// end < start
return format("end index (%s) must not be less than start index (%s)",
end, start)
}
/**
* Substitutes each `%s` in `template` with an argument. These
* are matched by position - the first `%s` gets `args[0]`, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
* @param template a non-null string containing 0 or more `%s`
* * placeholders.
* *
* @param args the arguments to be substituted into the message
* * template. Arguments are converted to strings using
* * [String.valueOf]. Arguments can be null.
*/
internal fun format(template: String, vararg args: Any): String {
// start substituting the arguments into the '%s' placeholders
val builder = StringBuilder(
template.length + 16 * args.size)
var templateStart = 0
var i = 0
while (i < args.size) {
val placeholderStart = template.indexOf("%s", templateStart)
if (placeholderStart == -1) {
break
}
builder.append(template.substring(templateStart, placeholderStart))
builder.append(args[i++])
templateStart = placeholderStart + 2
}
builder.append(template.substring(templateStart))
// if we run out of placeholders, append the extra args in square braces
if (i < args.size) {
builder.append(" [")
builder.append(args[i++])
while (i < args.size) {
builder.append(", ")
builder.append(args[i++])
}
builder.append("]")
}
return builder.toString()
}
}
/**
* Ensures that `index` specifies a valid *element* in an array,
* list or string of size `size`. An element index may range from zero,
* inclusive, to `size`, exclusive.
* @param index a user-supplied index identifying an element of an array, list
* * or string
* *
* @param size the size of that array, list or string
* *
* @return the value of `index`
* *
* @throws IndexOutOfBoundsException if `index` is negative or is not
* * less than `size`
* *
* @throws IllegalArgumentException if `size` is negative
*/
/**
* Ensures that `index` specifies a valid *position* in an array,
* list or string of size `size`. A position index may range from zero
* to `size`, inclusive.
* @param index a user-supplied index identifying a position in an array, list
* * or string
* *
* @param size the size of that array, list or string
* *
* @return the value of `index`
* *
* @throws IndexOutOfBoundsException if `index` is negative or is
* * greater than `size`
* *
* @throws IllegalArgumentException if `size` is negative
*/
|
apache-2.0
|
7e6bb81c39879ac08c0755c170e84f12
| 36.350917 | 129 | 0.629291 | 4.509831 | false | false | false | false |
zsmb13/MaterialDrawerKt
|
library/src/main/java/co/zsmb/materialdrawerkt/draweritems/toggleable/AbstractToggleableDrawerItemKt.kt
|
1
|
3868
|
@file:Suppress("RedundantVisibilityModifier")
package co.zsmb.materialdrawerkt.draweritems.toggleable
import android.widget.CompoundButton
import co.zsmb.materialdrawerkt.draweritems.base.BaseDescribeableDrawerItemKt
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener
import com.mikepenz.materialdrawer.model.AbstractToggleableDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
@Suppress("FINITE_BOUNDS_VIOLATION_IN_JAVA")
public abstract class AbstractToggleableDrawerItemKt<out T : AbstractToggleableDrawerItem<*>>(item: T) :
BaseDescribeableDrawerItemKt<T>(item) {
/**
* Whether the drawer item's toggle is currently in its "on" state.
* Default value is false.
*
* Wraps the [AbstractToggleableDrawerItem.isChecked] property.
*/
public var checked: Boolean
get() = item.isChecked
set(value) {
item.isChecked = value
}
/**
* Adds an event [handler] to the drawer item that's called when the toggle's state is changed.
*
* Wraps the [AbstractToggleableDrawerItem.withOnCheckedChangeListener] method.
*
* @param drawerItem The drawer item itself
* @param buttonView The CompoundButton View whose state has changed
* @param isChecked True if the toggle is now in an "on" state
*/
@Deprecated(level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("onToggledChanged(handler)"),
message = "Use onToggledChanged instead.")
public fun onCheckedChange(handler: (drawerItem: IDrawerItem<*>, buttonView: CompoundButton, isChecked: Boolean) -> Unit) {
item.withOnCheckedChangeListener(object : OnCheckedChangeListener {
override fun onCheckedChanged(drawerItem: IDrawerItem<*>, buttonView: CompoundButton, isChecked: Boolean) {
handler(drawerItem, buttonView, isChecked)
}
})
}
/**
* Adds an event [handler] to the drawer item that's called when the toggle's state is changed.
*
* Replacement for [onCheckedChange]. Wraps the [AbstractToggleableDrawerItem.withOnCheckedChangeListener] method.
*
* @param drawerItem The drawer item itself
* @param buttonView The CompoundButton View whose state has changed
* @param isChecked True if the toggle is now in an "on" state
*/
public fun onToggleChanged(handler: (drawerItem: IDrawerItem<*>, buttonView: CompoundButton, isEnabled: Boolean) -> Unit) {
item.withOnCheckedChangeListener(object : OnCheckedChangeListener {
override fun onCheckedChanged(drawerItem: IDrawerItem<*>, buttonView: CompoundButton, isChecked: Boolean) {
handler(drawerItem, buttonView, isChecked)
}
})
}
/**
* Adds an event [handler] to the drawer item that's called when the toggle's state is changed.
*
* Alternative to the three parameter [onToggleChanged] method, to be used when you don't need all its parameters.
*
* Wraps the [AbstractToggleableDrawerItem.withOnCheckedChangeListener] method.
*
* @param isChecked True if the toggle is now in an "on" state
*/
public fun onToggled(handler: (isEnabled: Boolean) -> Unit) {
item.withOnCheckedChangeListener(object : OnCheckedChangeListener {
override fun onCheckedChanged(drawerItem: IDrawerItem<*>, buttonView: CompoundButton, isChecked: Boolean) {
handler(isChecked)
}
})
}
/**
* Whether the drawer item's toggle can be toggled by the user.
* Default value is true.
*
* Wraps the [AbstractToggleableDrawerItem.isToggleEnabled] property.
*/
public var toggleEnabled: Boolean
get() = item.isToggleEnabled
set(value) {
item.isToggleEnabled = value
}
}
|
apache-2.0
|
785015ec61dca25bccd97e78e4a16a38
| 40.591398 | 127 | 0.689504 | 5.129973 | false | false | false | false |
siosio/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerExImpl.kt
|
1
|
19075
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.openapi.project.impl
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.runActivity
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.setTrusted
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.ComponentManagerEx
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.getProjectDataPathRoot
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.project.ProjectStoreOwner
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.ui.IdeUICustomization
import com.intellij.util.ModalityUiUtil
import com.intellij.util.io.delete
import org.jetbrains.annotations.ApiStatus
import java.awt.event.InvocationEvent
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.BiFunction
@ApiStatus.Internal
open class ProjectManagerExImpl : ProjectManagerImpl() {
final override fun createProject(name: String?, path: String): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, runConfigurators = false, projectName = name))
}
final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectAsTemplate,
projectName = projectName))
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return openProjectAsync(projectStoreBaseDir, options).get(30, TimeUnit.MINUTES)
}
final override fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): CompletableFuture<Project?> {
if (LOG.isDebugEnabled && !ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project)) {
return CompletableFuture.completedFuture(null)
}
val activity = StartUpMeasurer.startActivity("project opening preparation")
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects.last()
}
}
// this null assertion is required to overcome bug in new version of KT compiler: KT-40034
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectStoreBaseDir, options.projectName, this)) {
return CompletableFuture.completedFuture(null)
}
}
}
return doOpenAsync(options, projectStoreBaseDir, activity)
}
private fun doOpenAsync(options: OpenProjectTask,
projectStoreBaseDir: Path,
activity: Activity): CompletableFuture<Project?> {
val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) ProjectFrameAllocator(options)
else ProjectUiFrameAllocator(options, projectStoreBaseDir)
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
return frameAllocator.run { indicator ->
activity.end()
val result: PrepareProjectResult
if (options.project == null) {
result = prepareProject(options, projectStoreBaseDir) ?: return@run null
}
else {
result = PrepareProjectResult(options.project, null)
}
val project = result.project
if (!addToOpened(project)) {
return@run null
}
frameAllocator.projectLoaded(project)
try {
openProject(project, indicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
ApplicationManager.getApplication().invokeAndWait {
closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false)
}
ApplicationManager.getApplication().messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
return@run null
}
frameAllocator.projectOpened(project)
result
}
.handle(BiFunction { result, error ->
disableAutoSaveToken.finish()
if (error != null) {
throw error
}
if (result == null) {
frameAllocator.projectNotLoaded(error = null)
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
return@BiFunction null
}
val project = result.project
if (options.callback != null) {
options.callback!!.projectOpened(project, result.module ?: ModuleManager.getInstance(project).modules[0])
}
project
})
}
override fun openProject(project: Project): Boolean {
val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null
if (store != null) {
val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath
for (p in openProjects) {
if (ProjectUtil.isSameProject(projectFilePath, p)) {
ModalityUiUtil.invokeLaterIfNeeded({ ProjectUtil.focusProjectWindow(p, false) },
ModalityState.NON_MODAL)
return false
}
}
}
if (!addToOpened(project)) {
return false
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread) {
LOG.warn("Do not open project in EDT")
}
try {
openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) }
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
if (!app.isUnitTestMode) {
WelcomeFrame.showIfNoProjectOpened()
}
return false
}
return true
}
override fun newProject(projectFile: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(projectFile)
val project = instantiateProject(projectFile, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectFile, project, options.isRefreshVfsNeeded, options.preloadServices, template,
ProgressManager.getInstance().progressIndicator)
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startActivity("project instantiation")
val project = ProjectExImpl(projectStoreBaseDir, options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path): PrepareProjectResult? {
val project: Project?
val indicator = ProgressManager.getInstance().progressIndicator
if (options.isNewProject) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
project = instantiateProject(projectStoreBaseDir, options)
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, template, indicator)
}
else {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
indicator?.text = IdeUICustomization.getInstance().projectMessage("progress.text.project.checking.configuration")
conversionResult = runActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
return null
}
indicator?.text = ""
}
}
project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, null, indicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
}
project.putUserData(PlatformProjectOpenProcessor.PROJECT_NEWLY_OPENED, options.isNewProject)
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (options.beforeOpen != null && !options.beforeOpen!!(project)) {
return null
}
if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty())) {
val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project,
options.isProjectCreatedWithWizard)
options.preparedToOpen?.invoke(module)
return PrepareProjectResult(project, module)
}
else {
return PrepareProjectResult(project, module = null)
}
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
}
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
val causeMessage = message(e.cause ?: return message)
return "$message (cause: $causeMessage)"
}
private fun checkExistingProjectOnOpen(projectToClose: Project,
callback: ProjectOpenedCallback?,
projectDir: Path?,
projectName: String?,
projectManager: ProjectManagerExImpl): Boolean {
val settings = GeneralSettings.getInstance()
val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir)
var result = false
// modality per thread, it means that we cannot use invokeLater, because after getting result from EDT, we MUST continue execution
// in ORIGINAL thread
ApplicationManager.getApplication().invokeAndWait task@{
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || settings.confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
val exitCode = ProjectUtil.confirmOpenOrAttachProject()
if (exitCode == -1) {
result = true
return@task
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result = true
return@task
}
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result = true
return@task
}
}
// process all pending events that can interrupt focus flow
// todo this can be removed after taming the focus beast
IdeEventQueue.getInstance().flushQueue()
}
else {
val mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (projectDir != null && PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result = true
return@task
}
}
val projectNameValue = projectName ?: projectDir?.fileName?.toString() ?: projectDir?.toString()
val exitCode = ProjectUtil.confirmOpenNewProject(false, projectNameValue)
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result = true
return@task
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
result = true
return@task
}
}
result = false
}
return result
}
private fun openProject(project: Project, indicator: ProgressIndicator?, runStartUpActivities: Boolean): CompletableFuture<*> {
val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue")
if (indicator != null) {
indicator.text = if (ApplicationManager.getApplication().isInternal) "Waiting on event queue..." // NON-NLS (internal mode)
else ProjectBundle.message("project.preparing.workspace")
indicator.isIndeterminate = true
}
// invokeLater cannot be used for now
ApplicationManager.getApplication().invokeAndWait {
waitEdtActivity.end()
if (indicator != null && ApplicationManager.getApplication().isInternal) {
indicator.text = "Running project opened tasks..." // NON-NLS (internal mode)
}
ProjectManagerImpl.LOG.debug("projectOpened")
LifecycleUsageTriggerCollector.onProjectOpened(project)
val activity = StartUpMeasurer.startActivity("project opened callbacks")
runActivity("projectOpened event executing") {
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
}
@Suppress("DEPRECATION")
(project as ComponentManagerEx)
.processInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java) { component, pluginDescriptor ->
ProgressManager.checkCanceled()
try {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER,
pluginDescriptor.pluginId.idString)
component.projectOpened()
componentActivity.end()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
ProjectManagerImpl.LOG.error(e)
}
}
activity.end()
ProjectImpl.ourClassesAreLoaded = true
}
if (runStartUpActivities) {
(StartupManager.getInstance(project) as StartupManagerImpl).projectOpened(indicator)
}
return CompletableFuture.completedFuture(null)
}
// allow `invokeAndWait` inside startup activities
internal fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
val eventQueue = IdeEventQueue.getInstance()
while (true) {
// getNextEvent() will block until an event has been posted by another thread, so,
// peekEvent() is used to check that there is already some event in the queue
if (eventQueue.peekEvent() == null) {
if (startupManager.postStartupActivityPassed()) {
break
}
else {
continue
}
}
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
}
}
private data class PrepareProjectResult(val project: Project, val module: Module?)
private fun toCanonicalName(filePath: String): Path {
val file = Paths.get(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (e: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
|
apache-2.0
|
f0126c7027c0447e82e1cb68ba20c71a
| 38.168378 | 140 | 0.706999 | 5.310412 | false | false | false | false |
MichaelRocks/grip
|
library/src/test/java/io/michaelrocks/grip/ElementMatchersTest.kt
|
1
|
5003
|
/*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.mirrors.Element
import io.michaelrocks.mockito.RETURNS_MOCKS
import io.michaelrocks.mockito.given
import io.michaelrocks.mockito.mock
import org.junit.Test
import org.objectweb.asm.Opcodes.ACC_ABSTRACT
import org.objectweb.asm.Opcodes.ACC_ANNOTATION
import org.objectweb.asm.Opcodes.ACC_ENUM
import org.objectweb.asm.Opcodes.ACC_FINAL
import org.objectweb.asm.Opcodes.ACC_INTERFACE
import org.objectweb.asm.Opcodes.ACC_PRIVATE
import org.objectweb.asm.Opcodes.ACC_PROTECTED
import org.objectweb.asm.Opcodes.ACC_PUBLIC
import org.objectweb.asm.Opcodes.ACC_STATIC
import org.objectweb.asm.Opcodes.ACC_SUPER
class ElementMatchersTest {
private val finalClass = mock<Element<*>>(RETURNS_MOCKS).apply {
given(access).thenReturn(ACC_PRIVATE or ACC_STATIC or ACC_FINAL or ACC_SUPER)
given(name).thenReturn("FinalClass")
}
private val abstractClass = mock<Element<*>>(RETURNS_MOCKS).apply {
given(access).thenReturn(ACC_ABSTRACT or ACC_SUPER)
given(name).thenReturn("AbstractClass")
}
private val enum = mock<Element<*>>(RETURNS_MOCKS).apply {
given(access).thenReturn(ACC_PROTECTED or ACC_FINAL or ACC_ENUM or ACC_SUPER)
given(name).thenReturn("Enum")
}
private val annotation = mock<Element<*>>(RETURNS_MOCKS).apply {
given(access).thenReturn(ACC_PUBLIC or ACC_ANNOTATION or ACC_INTERFACE)
given(name).thenReturn("Annotation")
}
@Test
fun testAccessEqualsTrue() = abstractClass.testAccess(true) { access(ACC_ABSTRACT or ACC_SUPER) }
@Test
fun testAccessEqualsFalse() = finalClass.testAccess(false) { access(ACC_ABSTRACT or ACC_SUPER) }
@Test
fun testAccessHasAllOfTrue() = abstractClass.testAccess(true) { accessHasAllOf(ACC_ABSTRACT or ACC_SUPER) }
@Test
fun testAccessHasAllOfFalse() = abstractClass.testAccess(false) { accessHasAllOf(ACC_ABSTRACT or ACC_STATIC) }
@Test
fun testAccessHasAnyOfTrue() = abstractClass.testAccess(true) { accessHasAnyOf(ACC_ABSTRACT or ACC_STATIC) }
@Test
fun testAccessHasAnyOfFalse() = abstractClass.testAccess(false) { accessHasAnyOf(ACC_STATIC or ACC_FINAL) }
@Test
fun testAccessHasNoneOfTrue() = abstractClass.testAccess(true) { accessHasNoneOf(ACC_STATIC or ACC_FINAL) }
@Test
fun testAccessHasNoneOfFalse() = abstractClass.testAccess(false) { accessHasNoneOf(ACC_ABSTRACT or ACC_STATIC) }
@Test
fun testIsPublicTrue() = annotation.testAccess(true) { isPublic() }
@Test
fun testIsPublicFalse() = enum.testAccess(false) { isPublic() }
@Test
fun testIsProtectedTrue() = enum.testAccess(true) { isProtected() }
@Test
fun testIsProtectedFalse() = annotation.testAccess(false) { isProtected() }
@Test
fun testIsPrivateTrue() = finalClass.testAccess(true) { isPrivate() }
@Test
fun testIsPrivateFalse() = abstractClass.testAccess(false) { isPrivate() }
@Test
fun testIsPackagePrivateTrue() = abstractClass.testAccess(true) { isPackagePrivate() }
@Test
fun testIsPackagePrivateFalse() = finalClass.testAccess(false) { isPackagePrivate() }
@Test
fun testIsStaticTrue() = finalClass.testAccess(true) { isStatic() }
@Test
fun testIsStaticFalse() = abstractClass.testAccess(false) { isStatic() }
@Test
fun testIsFinalTrue() = finalClass.testAccess(true) { isFinal() }
@Test
fun testIsFinalFalse() = abstractClass.testAccess(false) { isFinal() }
@Test
fun testIsInterfaceTrue() = annotation.testAccess(true) { isInterface() }
@Test
fun testIsInterfaceFalse() = enum.testAccess(false) { isInterface() }
@Test
fun testIsAbstractTrue() = abstractClass.testAccess(true) { isAbstract() }
@Test
fun testIsAbstractFalse() = finalClass.testAccess(false) { isAbstract() }
@Test
fun testIsAnnotationTrue() = annotation.testAccess(true) { isAnnotation() }
@Test
fun testIsAnnotationFalse() = enum.testAccess(false) { isAnnotation() }
@Test
fun testIsEnumTrue() = enum.testAccess(true) { isEnum() }
@Test
fun testIsEnumFalse() = annotation.testAccess(false) { isEnum() }
@Test
fun testNameTrue() = finalClass.assertAndVerify(true, { name { _, _ -> true } }, { name })
@Test
fun testNameFalse() = finalClass.assertAndVerify(false, { name { _, _ -> false } }, { name })
private inline fun Element<*>.testAccess(condition: Boolean, body: () -> ((Grip, Element<*>) -> Boolean)) =
assertAndVerify(condition, body) { access }
}
|
apache-2.0
|
01ef4ae816617bd257519076f26f9aac
| 32.804054 | 114 | 0.735958 | 3.773002 | false | true | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt
|
1
|
39877
|
// 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.changeSignature
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.rename.ResolveSnapshotProvider
import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.javaResolutionFacade
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.*
import org.jetbrains.kotlin.idea.refactoring.createJavaMethod
import org.jetbrains.kotlin.idea.refactoring.isTrueJavaMethod
import org.jetbrains.kotlin.idea.references.KtArrayAccessReference
import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.codeUsageScopeRestrictedToKotlinSources
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.usagesSearch.processDelegationCallConstructorUsages
import org.jetbrains.kotlin.idea.search.useScope
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.psiUtil.getValueParameters
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor {
// This is special 'PsiElement' whose purpose is to wrap JetMethodDescriptor so that it can be kept in the usage list
private class OriginalJavaMethodDescriptorWrapper(element: PsiElement) : UsageInfo(element) {
var originalJavaMethodDescriptor: KotlinMethodDescriptor? = null
}
private class DummyKotlinChangeInfo(
method: PsiElement,
methodDescriptor: KotlinMethodDescriptor
) : KotlinChangeInfo(
methodDescriptor = methodDescriptor,
name = "",
newReturnTypeInfo = KotlinTypeInfo(true),
newVisibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
parameterInfos = emptyList(),
receiver = null,
context = method
)
// It's here to prevent O(usage_count^2) performance
private var initializedOriginalDescriptor: Boolean = false
override fun findUsages(info: ChangeInfo): Array<UsageInfo> {
if (!canHandle(info)) return UsageInfo.EMPTY_ARRAY
initializedOriginalDescriptor = false
val result = hashSetOf<UsageInfo>()
result.add(OriginalJavaMethodDescriptorWrapper(info.method))
val kotlinChangeInfo = info.asKotlinChangeInfo
if (kotlinChangeInfo != null) {
findAllMethodUsages(kotlinChangeInfo, result)
} else {
findSAMUsages(info, result)
//findConstructorDelegationUsages(info, result)
findKotlinOverrides(info, result)
if (info is JavaChangeInfo) {
findKotlinCallers(info, result)
}
}
return result.toTypedArray()
}
private fun canHandle(changeInfo: ChangeInfo) = changeInfo.asKotlinChangeInfo is KotlinChangeInfo || changeInfo is JavaChangeInfo
private fun findAllMethodUsages(changeInfo: KotlinChangeInfo, result: MutableSet<UsageInfo>) {
loop@ for (functionUsageInfo in changeInfo.getAffectedCallables()) {
when (functionUsageInfo) {
is KotlinCallableDefinitionUsage<*> -> findOneMethodUsages(functionUsageInfo, changeInfo, result)
is KotlinCallerUsage -> findCallerUsages(functionUsageInfo, changeInfo, result)
else -> {
result.add(functionUsageInfo)
val callee = functionUsageInfo.element ?: continue@loop
val propagationTarget = functionUsageInfo is CallerUsageInfo ||
(functionUsageInfo is OverriderUsageInfo && !functionUsageInfo.isOriginalOverrider)
for (reference in ReferencesSearch.search(callee, callee.codeUsageScopeRestrictedToKotlinSources())) {
val callElement = reference.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } ?: continue
val usage = if (propagationTarget) {
KotlinCallerCallUsage(callElement)
} else {
KotlinFunctionCallUsage(callElement, changeInfo.methodDescriptor.originalPrimaryCallable)
}
result.add(usage)
}
}
}
}
}
private fun findCallerUsages(callerUsage: KotlinCallerUsage, changeInfo: KotlinChangeInfo, result: MutableSet<UsageInfo>) {
result.add(callerUsage)
val element = callerUsage.element ?: return
for (ref in ReferencesSearch.search(element, element.useScope())) {
val callElement = ref.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } ?: continue
result.add(KotlinCallerCallUsage(callElement))
}
val body = element.getDeclarationBody() ?: return
val callerDescriptor = element.resolveToDescriptorIfAny() ?: return
val context = body.analyze()
val newParameterNames = changeInfo.getNonReceiverParameters().mapTo(hashSetOf()) { it.name }
body.accept(
object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val currentName = expression.getReferencedName()
if (currentName !in newParameterNames) return
val resolvedCall = expression.getResolvedCall(context) ?: return
if (resolvedCall.explicitReceiverKind != ExplicitReceiverKind.NO_EXPLICIT_RECEIVER) return
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor !is VariableDescriptor) return
// Do not report usages of duplicated parameter
if (resultingDescriptor is ValueParameterDescriptor && resultingDescriptor.containingDeclaration === callerDescriptor) return
val callElement = resolvedCall.call.callElement
var receiver = resolvedCall.extensionReceiver
if (receiver !is ImplicitReceiver) {
receiver = resolvedCall.dispatchReceiver
}
if (receiver is ImplicitReceiver) {
result.add(KotlinImplicitThisUsage(callElement, receiver.declarationDescriptor))
} else if (receiver == null) {
result.add(
object : UnresolvableCollisionUsageInfo(callElement, null) {
override fun getDescription(): String {
val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(callerDescriptor)
return KotlinBundle.message(
"text.there.is.already.a.variable.0.in.1.it.will.conflict.with.the.new.parameter",
currentName,
signature
)
}
}
)
}
}
})
}
private fun findReferences(functionPsi: PsiElement): Set<PsiReference> {
val result = LinkedHashSet<PsiReference>()
val searchScope = functionPsi.useScope()
val options = KotlinReferencesSearchOptions(
acceptCallableOverrides = true,
acceptOverloads = false,
acceptExtensionsOfDeclarationClass = false,
acceptCompanionObjectMembers = false
)
val parameters = KotlinReferencesSearchParameters(functionPsi, searchScope, false, null, options)
result.addAll(ReferencesSearch.search(parameters).findAll())
if (functionPsi is KtProperty || functionPsi is KtParameter) {
functionPsi.toLightMethods().flatMapTo(result) { MethodReferencesSearch.search(it, searchScope, true).findAll() }
}
return result
}
private fun findOneMethodUsages(
functionUsageInfo: KotlinCallableDefinitionUsage<*>,
changeInfo: KotlinChangeInfo,
result: MutableSet<UsageInfo>
) {
if (functionUsageInfo.isInherited) {
result.add(functionUsageInfo)
}
val functionPsi = functionUsageInfo.element ?: return
for (reference in findReferences(functionPsi)) {
val element = reference.element
when {
reference is KtInvokeFunctionReference || reference is KtArrayAccessReference -> {
result.add(KotlinByConventionCallUsage(element as KtExpression, functionUsageInfo))
}
element is KtReferenceExpression -> {
val parent = element.parent
when {
parent is KtCallExpression -> result.add(KotlinFunctionCallUsage(parent, functionUsageInfo))
parent is KtUserType && parent.parent is KtTypeReference ->
parent.parent.parent.safeAs<KtConstructorCalleeExpression>()
?.parent?.safeAs<KtCallElement>()
?.let {
result.add(KotlinFunctionCallUsage(it, functionUsageInfo))
}
element is KtSimpleNameExpression && (functionPsi is KtProperty || functionPsi is KtParameter) ->
result.add(KotlinPropertyCallUsage(element))
}
}
}
}
val searchScope = PsiSearchHelper.getInstance(functionPsi.project).getUseScope(functionPsi)
changeInfo.oldName?.let { oldName ->
TextOccurrencesUtil.findNonCodeUsages(
functionPsi,
searchScope,
oldName,
/* searchInStringsAndComments = */true,
/* searchInNonJavaFiles = */true,
changeInfo.newName,
result
)
}
val oldParameters = (functionPsi as KtNamedDeclaration).getValueParameters()
val newReceiverInfo = changeInfo.receiverParameterInfo
val isDataClass = functionPsi is KtPrimaryConstructor && (functionPsi.getContainingClassOrObject() as? KtClass)?.isData() ?: false
for ((i, parameterInfo) in changeInfo.newParameters.withIndex()) {
if (parameterInfo.oldIndex >= 0 && parameterInfo.oldIndex < oldParameters.size) {
val oldParam = oldParameters[parameterInfo.oldIndex]
val oldParamName = oldParam.name
if (parameterInfo == newReceiverInfo || (oldParamName != null && oldParamName != parameterInfo.name) || isDataClass && i != parameterInfo.oldIndex) {
for (reference in ReferencesSearch.search(oldParam, oldParam.useScope())) {
val element = reference.element
if (isDataClass &&
element is KtSimpleNameExpression &&
(element.parent as? KtCallExpression)?.calleeExpression == element &&
element.getReferencedName() != parameterInfo.name &&
OperatorNameConventions.COMPONENT_REGEX.matches(element.getReferencedName())
) {
result.add(KotlinDataClassComponentUsage(element, "component${i + 1}"))
}
// Usages in named arguments of the calls usage will be changed when the function call is changed
else if ((element is KtSimpleNameExpression || element is KDocName) && element.parent !is KtValueArgumentName) {
result.add(KotlinParameterUsage(element as KtElement, parameterInfo, functionUsageInfo))
}
}
}
}
}
if (isDataClass && !changeInfo.hasAppendedParametersOnly()) {
(functionPsi as KtPrimaryConstructor).valueParameters.firstOrNull()?.let {
ReferencesSearch.search(it).mapNotNullTo(result) { reference ->
val destructuringEntry = reference.element as? KtDestructuringDeclarationEntry ?: return@mapNotNullTo null
KotlinComponentUsageInDestructuring(destructuringEntry)
}
}
}
if (functionPsi is KtFunction && newReceiverInfo != changeInfo.methodDescriptor.receiver) {
findOriginalReceiversUsages(functionUsageInfo, result, changeInfo)
}
if (functionPsi is KtClass && functionPsi.isEnum()) {
for (declaration in functionPsi.declarations) {
if (declaration is KtEnumEntry && declaration.superTypeListEntries.isEmpty()) {
result.add(KotlinEnumEntryWithoutSuperCallUsage(declaration))
}
}
}
functionPsi.processDelegationCallConstructorUsages(functionPsi.useScope()) {
when (it) {
is KtConstructorDelegationCall -> result.add(KotlinConstructorDelegationCallUsage(it, changeInfo))
is KtSuperTypeCallEntry -> result.add(KotlinFunctionCallUsage(it, functionUsageInfo))
}
true
}
}
private fun processInternalReferences(functionUsageInfo: KotlinCallableDefinitionUsage<*>, visitor: KtTreeVisitor<BindingContext>) {
val ktFunction = functionUsageInfo.declaration as KtFunction
val body = ktFunction.bodyExpression
body?.accept(visitor, body.analyze(BodyResolveMode.FULL))
for (parameter in ktFunction.valueParameters) {
val defaultValue = parameter.defaultValue
defaultValue?.accept(visitor, defaultValue.analyze(BodyResolveMode.FULL))
}
}
private fun findOriginalReceiversUsages(
functionUsageInfo: KotlinCallableDefinitionUsage<*>,
result: MutableSet<UsageInfo>,
changeInfo: KotlinChangeInfo
) {
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
val callableDescriptor = functionUsageInfo.originalCallableDescriptor
processInternalReferences(
functionUsageInfo,
object : KtTreeVisitor<BindingContext>() {
private fun processExplicitThis(
expression: KtSimpleNameExpression,
receiverDescriptor: ReceiverParameterDescriptor
) {
if (originalReceiverInfo != null && !changeInfo.hasParameter(originalReceiverInfo)) return
if (expression.parent !is KtThisExpression) return
if (receiverDescriptor === callableDescriptor.extensionReceiverParameter) {
assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text }
result.add(KotlinParameterUsage(expression, originalReceiverInfo!!, functionUsageInfo))
} else {
if (receiverDescriptor.value is ExtensionReceiver) return
val targetDescriptor = receiverDescriptor.type.constructor.declarationDescriptor
assert(targetDescriptor != null) { "Receiver type has no descriptor: " + functionUsageInfo.declaration.text }
if (DescriptorUtils.isAnonymousObject(targetDescriptor!!)) return
result.add(KotlinNonQualifiedOuterThisUsage(expression.parent as KtThisExpression, targetDescriptor))
}
}
private fun processImplicitThis(
callElement: KtElement,
implicitReceiver: ImplicitReceiver
) {
val targetDescriptor = implicitReceiver.declarationDescriptor
if (compareDescriptors(callElement.project, targetDescriptor, callableDescriptor)) {
assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text }
if (originalReceiverInfo in changeInfo.getNonReceiverParameters()) {
result.add(KotlinImplicitThisToParameterUsage(callElement, originalReceiverInfo!!, functionUsageInfo))
}
} else {
result.add(KotlinImplicitThisUsage(callElement, targetDescriptor))
}
}
private fun processThisCall(
expression: KtSimpleNameExpression,
context: BindingContext,
extensionReceiver: ReceiverValue?,
dispatchReceiver: ReceiverValue?
) {
val thisExpression = expression.parent as? KtThisExpression ?: return
val thisCallExpression = thisExpression.parent as? KtCallExpression ?: return
val usageInfo = when (callableDescriptor) {
dispatchReceiver.getReceiverTargetDescriptor(context) -> {
val extensionReceiverTargetDescriptor = extensionReceiver.getReceiverTargetDescriptor(context)
if (extensionReceiverTargetDescriptor != null) {
KotlinNonQualifiedOuterThisCallUsage(
thisCallExpression, originalReceiverInfo!!, functionUsageInfo, extensionReceiverTargetDescriptor
)
} else {
KotlinParameterUsage(expression, originalReceiverInfo!!, functionUsageInfo)
}
}
extensionReceiver.getReceiverTargetDescriptor(context) -> {
KotlinParameterUsage(expression, originalReceiverInfo!!, functionUsageInfo)
}
else -> null
}
result.addIfNotNull(usageInfo)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, context: BindingContext): Void? {
val resolvedCall = expression.getResolvedCall(context) ?: return null
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor is ReceiverParameterDescriptor) {
processExplicitThis(expression, resultingDescriptor)
return null
}
val (extensionReceiver, dispatchReceiver) = resolvedCall
.let { (it as? VariableAsFunctionResolvedCall)?.variableCall ?: it }
.let { (it.extensionReceiver to it.dispatchReceiver) }
if (extensionReceiver != null || dispatchReceiver != null) {
val receiverValue = extensionReceiver ?: dispatchReceiver
if (receiverValue is ImplicitReceiver) {
processImplicitThis(resolvedCall.call.callElement, receiverValue)
} else {
processThisCall(expression, context, extensionReceiver, dispatchReceiver)
}
}
return null
}
})
}
private fun findSAMUsages(changeInfo: ChangeInfo, result: MutableSet<UsageInfo>) {
val method = changeInfo.method
if (!method.isTrueJavaMethod()) return
method as PsiMethod
if (method.containingClass == null) return
val containingDescriptor = method.getJavaMethodDescriptor()?.containingDeclaration as? JavaClassDescriptor ?: return
if (containingDescriptor.defaultFunctionTypeForSamInterface == null) return
val samClass = method.containingClass ?: return
for (ref in ReferencesSearch.search(samClass)) {
if (ref !is KtSimpleNameReference) continue
val callee = ref.expression
val callExpression = callee.getNonStrictParentOfType<KtCallExpression>() ?: continue
if (callExpression.calleeExpression !== callee) continue
val arguments = callExpression.valueArguments
if (arguments.size != 1) continue
val argExpression = arguments[0].getArgumentExpression()
if (argExpression !is KtLambdaExpression) continue
val context = callExpression.analyze(BodyResolveMode.FULL)
val functionLiteral = argExpression.functionLiteral
val functionDescriptor = context.get(BindingContext.FUNCTION, functionLiteral)
assert(functionDescriptor != null) { "No descriptor for " + functionLiteral.text }
val samCallType = context.getType(callExpression) ?: continue
result.add(DeferredJavaMethodOverrideOrSAMUsage(functionLiteral, functionDescriptor!!, samCallType))
}
}
private fun findKotlinOverrides(changeInfo: ChangeInfo, result: MutableSet<UsageInfo>) {
val method = changeInfo.method as? PsiMethod ?: return
val methodDescriptor = method.getJavaMethodDescriptor() ?: return
val baseFunctionInfo = KotlinCallableDefinitionUsage<PsiElement>(method, methodDescriptor, null, null)
for (overridingMethod in OverridingMethodsSearch.search(method)) {
val unwrappedElement = overridingMethod.namedUnwrappedElement as? KtNamedFunction ?: continue
val functionDescriptor = unwrappedElement.resolveToDescriptorIfAny() ?: continue
result.add(DeferredJavaMethodOverrideOrSAMUsage(unwrappedElement, functionDescriptor, null))
findDeferredUsagesOfParameters(changeInfo, result, unwrappedElement, functionDescriptor, baseFunctionInfo)
}
}
private fun findKotlinCallers(changeInfo: JavaChangeInfo, result: MutableSet<UsageInfo>) {
val method = changeInfo.method
if (!method.isTrueJavaMethod()) return
for (primaryCaller in changeInfo.methodsToPropagateParameters) {
addDeferredCallerIfPossible(result, primaryCaller)
for (overridingCaller in OverridingMethodsSearch.search(primaryCaller)) {
addDeferredCallerIfPossible(result, overridingCaller)
}
}
}
private fun addDeferredCallerIfPossible(result: MutableSet<UsageInfo>, overridingCaller: PsiMethod) {
val unwrappedElement = overridingCaller.namedUnwrappedElement
if (unwrappedElement is KtFunction || unwrappedElement is KtClass) {
result.add(DeferredJavaMethodKotlinCallerUsage(unwrappedElement as KtNamedDeclaration))
}
}
private fun findDeferredUsagesOfParameters(
changeInfo: ChangeInfo,
result: MutableSet<UsageInfo>,
function: KtNamedFunction,
functionDescriptor: FunctionDescriptor,
baseFunctionInfo: KotlinCallableDefinitionUsage<PsiElement>
) {
val functionInfoForParameters = KotlinCallableDefinitionUsage<PsiElement>(function, functionDescriptor, baseFunctionInfo, null)
val oldParameters = function.valueParameters
val parameters = changeInfo.newParameters
for ((paramIndex, parameterInfo) in parameters.withIndex()) {
if (!(parameterInfo.oldIndex >= 0 && parameterInfo.oldIndex < oldParameters.size)) continue
val oldParam = oldParameters[parameterInfo.oldIndex]
val oldParamName = oldParam.name
if (!(oldParamName != null && oldParamName != parameterInfo.name)) continue
for (reference in ReferencesSearch.search(oldParam, oldParam.useScope())) {
val element = reference.element
// Usages in named arguments of the calls usage will be changed when the function call is changed
if (!((element is KtSimpleNameExpression || element is KDocName) && element.parent !is KtValueArgumentName)) continue
result.add(
object : JavaMethodDeferredKotlinUsage<KtElement>(element as KtElement) {
override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate<KtElement> {
return object : JavaMethodKotlinUsageWithDelegate<KtElement>(element as KtElement, javaMethodChangeInfo) {
override val delegateUsage: KotlinUsageInfo<KtElement>
get() = KotlinParameterUsage(
element as KtElement,
this.javaMethodChangeInfo.newParameters[paramIndex],
functionInfoForParameters
)
}
}
}
)
}
}
}
override fun findConflicts(info: ChangeInfo, refUsages: Ref<Array<UsageInfo>>): MultiMap<PsiElement, String> {
return KotlinChangeSignatureConflictSearcher(info, refUsages).findConflicts()
}
private fun isJavaMethodUsage(usageInfo: UsageInfo): Boolean {
// MoveRenameUsageInfo corresponds to non-Java usage of Java method
return usageInfo is JavaMethodDeferredKotlinUsage<*> || usageInfo is MoveRenameUsageInfo
}
private fun createReplacementUsage(
originalUsageInfo: UsageInfo,
javaMethodChangeInfo: KotlinChangeInfo,
allUsages: Array<UsageInfo>
): UsageInfo? {
if (originalUsageInfo is JavaMethodDeferredKotlinUsage<*>) return originalUsageInfo.resolve(javaMethodChangeInfo)
val callElement = PsiTreeUtil.getParentOfType(originalUsageInfo.element, KtCallElement::class.java) ?: return null
val refTarget = originalUsageInfo.reference?.resolve()
return JavaMethodKotlinCallUsage(callElement, javaMethodChangeInfo, refTarget != null && refTarget.isCaller(allUsages))
}
private class NullabilityPropagator(baseMethod: PsiMethod) {
private val nullManager: NullableNotNullManager
private val javaPsiFacade: JavaPsiFacade
private val javaCodeStyleManager: JavaCodeStyleManager
private val methodAnnotation: PsiAnnotation?
private val parameterAnnotations: Array<PsiAnnotation?>
init {
val project = baseMethod.project
this.nullManager = NullableNotNullManager.getInstance(project)
this.javaPsiFacade = JavaPsiFacade.getInstance(project)
this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project)
this.methodAnnotation = getNullabilityAnnotation(baseMethod)
this.parameterAnnotations = baseMethod.parameterList.parameters.map { getNullabilityAnnotation(it) }.toTypedArray()
}
private fun getNullabilityAnnotation(element: PsiModifierListOwner): PsiAnnotation? {
val nullAnnotation = nullManager.getNullableAnnotation(element, false)
val notNullAnnotation = nullManager.getNotNullAnnotation(element, false)
if ((nullAnnotation == null) == (notNullAnnotation == null)) return null
return nullAnnotation ?: notNullAnnotation
}
private fun addNullabilityAnnotationIfApplicable(element: PsiModifierListOwner, annotation: PsiAnnotation?) {
val nullableAnnotation = nullManager.getNullableAnnotation(element, false)
val notNullAnnotation = nullManager.getNotNullAnnotation(element, false)
if (notNullAnnotation != null && nullableAnnotation == null && element is PsiMethod) return
val annotationQualifiedName = annotation?.qualifiedName
if (annotationQualifiedName != null && javaPsiFacade.findClass(annotationQualifiedName, element.resolveScope) == null) return
notNullAnnotation?.delete()
nullableAnnotation?.delete()
if (annotationQualifiedName == null) return
val modifierList = element.modifierList
if (modifierList != null) {
modifierList.addAnnotation(annotationQualifiedName)
javaCodeStyleManager.shortenClassReferences(element)
}
}
fun processMethod(currentMethod: PsiMethod) {
val currentParameters = currentMethod.parameterList.parameters
addNullabilityAnnotationIfApplicable(currentMethod, methodAnnotation)
for (i in parameterAnnotations.indices) {
addNullabilityAnnotationIfApplicable(currentParameters[i], parameterAnnotations[i])
}
}
}
private fun isOverriderOrCaller(usage: UsageInfo) = usage is OverriderUsageInfo || usage is CallerUsageInfo
override fun processUsage(
changeInfo: ChangeInfo,
usageInfo: UsageInfo,
beforeMethodChange: Boolean,
usages: Array<UsageInfo>,
): Boolean {
if (usageInfo is KotlinWrapperForPropertyInheritorsUsage) return processUsage(
usageInfo.propertyChangeInfo,
usageInfo.originalUsageInfo,
beforeMethodChange,
usages,
)
if (usageInfo is KotlinWrapperForJavaUsageInfos) {
val kotlinChangeInfo = usageInfo.kotlinChangeInfo
val javaChangeInfos = kotlinChangeInfo.getOrCreateJavaChangeInfos() ?: return true
javaChangeInfos.firstOrNull {
kotlinChangeInfo.originalToCurrentMethods[usageInfo.javaChangeInfo.method] == it.method
}?.let { javaChangeInfo ->
val nullabilityPropagator = NullabilityPropagator(javaChangeInfo.method)
val javaUsageInfos = usageInfo.javaUsageInfos
val processors = ChangeSignatureUsageProcessor.EP_NAME.extensions
for (usage in javaUsageInfos) {
if (isOverriderOrCaller(usage) && beforeMethodChange) continue
for (processor in processors) {
if (processor is KotlinChangeSignatureUsageProcessor) continue
if (isOverriderOrCaller(usage)) {
processor.processUsage(javaChangeInfo, usage, true, javaUsageInfos)
}
if (processor.processUsage(javaChangeInfo, usage, beforeMethodChange, javaUsageInfos)) break
}
if (usage is OverriderUsageInfo && usage.isOriginalOverrider) {
val overridingMethod = usage.overridingMethod
if (overridingMethod != null && overridingMethod !is KtLightMethod) {
nullabilityPropagator.processMethod(overridingMethod)
}
}
}
}
}
val method = changeInfo.method
if (beforeMethodChange) {
if (usageInfo is KotlinUsageInfo<*>) {
usageInfo.preprocessUsage()
}
if (method !is PsiMethod || initializedOriginalDescriptor) return false
val descriptorWrapper = usages.firstIsInstanceOrNull<OriginalJavaMethodDescriptorWrapper>()
if (descriptorWrapper == null || descriptorWrapper.originalJavaMethodDescriptor != null) return true
val baseDeclaration = method.unwrapped ?: return false
val baseDeclarationDescriptor = method.getJavaOrKotlinMemberDescriptor()?.createDeepCopy() as CallableDescriptor?
?: return false
descriptorWrapper.originalJavaMethodDescriptor = KotlinChangeSignatureData(
baseDeclarationDescriptor,
baseDeclaration,
listOf(baseDeclarationDescriptor)
)
// This change info is used as a placeholder before primary method update
// It gets replaced with real change info afterwards
val dummyChangeInfo = DummyKotlinChangeInfo(changeInfo.method, descriptorWrapper.originalJavaMethodDescriptor!!)
for (i in usages.indices) {
val oldUsageInfo = usages[i]
if (!isJavaMethodUsage(oldUsageInfo)) continue
val newUsageInfo = createReplacementUsage(oldUsageInfo, dummyChangeInfo, usages)
if (newUsageInfo != null) {
usages[i] = newUsageInfo
}
}
initializedOriginalDescriptor = true
return true
}
val element = usageInfo.element ?: return false
if (usageInfo is JavaMethodKotlinUsageWithDelegate<*>) {
// Do not call getOriginalJavaMethodDescriptorWrapper() on each usage to avoid O(usage_count^2) performance
if (usageInfo.javaMethodChangeInfo is DummyKotlinChangeInfo) {
val descriptorWrapper = usages.firstIsInstanceOrNull<OriginalJavaMethodDescriptorWrapper>()
val methodDescriptor = descriptorWrapper?.originalJavaMethodDescriptor ?: return true
val resolutionFacade = (methodDescriptor.method as? PsiMethod)?.javaResolutionFacade() ?: return false
val javaMethodChangeInfo = changeInfo.toJetChangeInfo(methodDescriptor, resolutionFacade)
for (info in usages) {
(info as? JavaMethodKotlinUsageWithDelegate<*>)?.javaMethodChangeInfo = javaMethodChangeInfo
}
}
return usageInfo.processUsage(usages)
}
if (usageInfo is MoveRenameUsageInfo && isJavaMethodUsage(usageInfo)) {
val callee = PsiTreeUtil.getParentOfType(usageInfo.element, KtSimpleNameExpression::class.java, false)
val ref = callee?.mainReference
if (ref is KtSimpleNameReference) {
ref.handleElementRename((method as PsiMethod).name)
return true
}
return false
}
@Suppress("UNCHECKED_CAST")
val kotlinUsageInfo = usageInfo as? KotlinUsageInfo<PsiElement>
val ktChangeInfo = changeInfo.asKotlinChangeInfo
return ktChangeInfo != null && kotlinUsageInfo != null && kotlinUsageInfo.processUsage(
ktChangeInfo,
element,
usages,
)
}
override fun processPrimaryMethod(changeInfo: ChangeInfo): Boolean {
val ktChangeInfo = if (changeInfo is JavaChangeInfo) {
val method = changeInfo.method as? KtLightMethod ?: return false
var baseFunction = method.kotlinOrigin ?: return false
if (baseFunction is KtClass) {
baseFunction = baseFunction.createPrimaryConstructorIfAbsent()
}
val resolutionFacade = baseFunction.getResolutionFacade()
val baseCallableDescriptor = baseFunction.unsafeResolveToDescriptor() as CallableDescriptor
if (baseCallableDescriptor !is FunctionDescriptor) {
return false
}
val methodDescriptor = KotlinChangeSignatureData(baseCallableDescriptor, baseFunction, listOf(baseCallableDescriptor))
val dummyClass = JavaPsiFacade.getElementFactory(method.project).createClass("Dummy")
val dummyMethod = createJavaMethod(method, dummyClass)
dummyMethod.containingFile.forcedModuleInfo = baseFunction.getModuleInfo()
try {
changeInfo.updateMethod(dummyMethod)
JavaChangeSignatureUsageProcessor.processPrimaryMethod(changeInfo, changeInfo.method, null, true)
changeInfo.toJetChangeInfo(methodDescriptor, resolutionFacade)
} finally {
changeInfo.updateMethod(method)
}
} else {
changeInfo.asKotlinChangeInfo ?: return false
}
for (primaryFunction in ktChangeInfo.methodDescriptor.primaryCallables) {
primaryFunction.processUsage(ktChangeInfo, primaryFunction.declaration, UsageInfo.EMPTY_ARRAY)
}
ktChangeInfo.primaryMethodUpdated()
return true
}
override fun shouldPreviewUsages(changeInfo: ChangeInfo, usages: Array<UsageInfo>) = false
override fun setupDefaultValues(changeInfo: ChangeInfo, refUsages: Ref<Array<UsageInfo>>, project: Project) = true
override fun registerConflictResolvers(
snapshots: MutableList<in ResolveSnapshotProvider.ResolveSnapshot>,
resolveSnapshotProvider: ResolveSnapshotProvider,
usages: Array<UsageInfo>, changeInfo: ChangeInfo
) {
}
}
|
apache-2.0
|
4a3f7d4e40348046828490b49fcbbb93
| 48.721945 | 165 | 0.652557 | 6.280832 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ift/KotlinLearningCourse.kt
|
4
|
3652
|
// 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.training.ift
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.training.ift.lesson.basic.KotlinBasicCompletionLesson
import org.jetbrains.kotlin.training.ift.lesson.basic.KotlinContextActionsLesson
import org.jetbrains.kotlin.training.ift.lesson.basic.KotlinSelectLesson
import org.jetbrains.kotlin.training.ift.lesson.basic.KotlinSurroundAndUnwrapLesson
import org.jetbrains.kotlin.training.ift.lesson.navigation.KotlinFileStructureLesson
import org.jetbrains.kotlin.training.ift.lesson.navigation.KotlinSearchEverywhereLesson
import training.dsl.LessonUtil
import training.learn.LessonsBundle
import training.learn.course.LearningCourseBase
import training.learn.course.LearningModule
import training.learn.course.LessonType
import training.learn.lesson.general.*
class KotlinLearningCourse : LearningCourseBase(KotlinLanguage.INSTANCE.id) {
override fun modules() = stableModules()
private fun stableModules() = listOf(
LearningModule(
id = "Kotlin.Essential",
name = LessonsBundle.message("essential.module.name"),
description = LessonsBundle.message("essential.module.description", LessonUtil.productName),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR // todo: change to SCRATCH when KTIJ-20742 will be resolved
) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
KotlinContextActionsLesson(),
GotoActionLesson(ls("Actions.kt.sample"), firstLesson = false),
KotlinSearchEverywhereLesson(),
KotlinBasicCompletionLesson(),
)
},
LearningModule(
id = "Kotlin.EditorBasics",
name = LessonsBundle.message("editor.basics.module.name"),
description = LessonsBundle.message("editor.basics.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH
) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
KotlinSelectLesson(),
CommentUncommentLesson(ls("Comment.kt.sample"), blockCommentsAvailable = true),
DuplicateLesson(ls("Duplicate.kt.sample")),
MoveLesson("run()", ls("Move.kt.sample")),
CollapseLesson(ls("Collapse.kt.sample")),
KotlinSurroundAndUnwrapLesson(),
MultipleSelectionHtmlLesson(),
)
},
LearningModule(
id = "Kotlin.CodeCompletion",
name = LessonsBundle.message("code.completion.module.name"),
description = LessonsBundle.message("code.completion.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR // todo: change to SCRATCH when KTIJ-20742 will be resolved
) {
listOf(KotlinBasicCompletionLesson())
},
LearningModule(
id = "Kotlin.Navigation",
name = LessonsBundle.message("navigation.module.name"),
description = LessonsBundle.message("navigation.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.PROJECT
) {
listOf(
KotlinSearchEverywhereLesson(),
KotlinFileStructureLesson(),
)
}
)
}
|
apache-2.0
|
55e12ac517b9c2051479a2097f5e213a
| 46.441558 | 158 | 0.66621 | 5.262248 | false | false | false | false |
scenerygraphics/scenery
|
src/main/kotlin/graphics/scenery/controls/TrackedStereoGlasses.kt
|
1
|
9689
|
package graphics.scenery.controls
import graphics.scenery.*
import graphics.scenery.backends.Display
import graphics.scenery.backends.vulkan.VulkanDevice
import graphics.scenery.Mesh
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.extensions.plus
import org.joml.*
import org.lwjgl.vulkan.VkInstance
import org.lwjgl.vulkan.VkPhysicalDevice
import org.lwjgl.vulkan.VkQueue
/**
* Display/TrackerInput implementation for stereoscopic displays and tracked shutter glasses
*
* @author Ulrik Günther <[email protected]>
*/
class TrackedStereoGlasses(var address: String = "device@localhost:5500", var screenConfig: String = "CAVEExample.yml") : Display, TrackerInput, Hubable {
private val logger by LazyLogger()
override var hub: Hub? = null
var tracker = initializeTracker(address)
var currentOrientation = Matrix4f()
var ipd = 0.062f
var config: ScreenConfig.Config = ScreenConfig.loadFromFile(screenConfig)
var screen: ScreenConfig.SingleScreenConfig? = null
private var rotation: Quaternionf
private var fakeTrackerInput = false
override var events = TrackerInputEventHandlers()
init {
logger.info("My screen is ${ScreenConfig.getScreen(config)}")
screen = ScreenConfig.getScreen(config)
rotation = Quaternionf()
screen?.let {
rotation = Quaternionf().setFromUnnormalized(Matrix4f(it.getTransform()).transpose()).normalize()
}
}
private fun initializeTracker(address: String): TrackerInput {
return when {
address.startsWith("fake:") -> {
fakeTrackerInput = true
VRPNTrackerInput()
}
address.startsWith("DTrack:") -> {
val host = address.substringAfter("@").substringBeforeLast(":")
val device = address.substringAfter("DTrack:").substringBefore("@")
val port = address.substringAfterLast(":").toIntOrNull() ?: 5000
DTrackTrackerInput(host, port, device)
}
address.startsWith("VRPN:") -> {
VRPNTrackerInput(address.substringAfter("VRPN:"))
}
else -> {
VRPNTrackerInput(address)
}
}
}
/**
* Returns the per-eye projection matrix
*
* @param[eye] The index of the eye
* @return Matrix4f containing the per-eye projection matrix
*/
override fun getEyeProjection(eye: Int, nearPlane: Float, farPlane: Float): Matrix4f {
screen?.let { screen ->
val eyeShift = if (eye == 0) {
-ipd / 2.0f
} else {
ipd / 2.0f
}
val position = getPosition() + Vector3f(eyeShift, 0.0f, 0.0f)
val position4 = Vector4f(position.x(), position.y(), position.z(), 1.0f)
val result = screen.getTransform().transform(position4)
val left = -result.x()
val right = screen.width - result.x()
val bottom = -result.y()
val top = screen.height - result.y()
var near = -result.z()
if(near < 0.0001f) {
near = 0.0001f
}
val scaledNear = nearPlane / maxOf(near, 0.001f)
//logger.info(eye.toString() + ", " + screen.width + "/" + screen.height + " => " + near + " -> " + left + "/" + right + "/" + bottom + "/" + top + ", s=" + scaledNear)
val projection = Matrix4f().frustum(left * scaledNear, right * scaledNear, bottom * scaledNear, top * scaledNear, near * scaledNear, farPlane)
projection.mul(Matrix4f().set(rotation))
return projection
}
logger.warn("No screen configuration found, ")
return Matrix4f().identity()
}
/**
* Returns the inter-pupillary distance (IPD)
*
* @return IPD as Float
*/
override fun getIPD(): Float {
return ipd
}
/**
* Query the HMD whether a compositor is used or the renderer should take
* care of displaying on the HMD on its own.
*
* @return True if the HMD has a compositor
*/
override fun hasCompositor(): Boolean {
return false
}
/**
* Submit OpenGL texture IDs to the compositor. The texture is assumed to have the left eye in the
* left half, right eye in the right half.
*
* @param[textureId] OpenGL Texture ID of the left eye texture
*/
override fun submitToCompositor(textureId: Int) {
}
/**
* Returns the orientation of the HMD
*
* @returns Matrix4f with orientation
*/
override fun getOrientation(): Quaternionf = tracker.getOrientation()
/**
* Submit a Vulkan texture handle to the compositor
*
* @param[width] Texture width
* @param[height] Texture height
* @param[format] Vulkan texture format
* @param[instance] Vulkan Instance
* @param[device] Vulkan device
* @param[queue] Vulkan queue
* @param[queueFamilyIndex] Queue family index
* @param[image] The Vulkan texture image to be presented to the compositor
*/
override fun submitToCompositorVulkan(width: Int, height: Int, format: Int, instance: VkInstance, device: VulkanDevice, queue: VkQueue, image: Long) {
logger.error("This Display implementation does not have a compositor. Incorrect configuration?")
}
/**
* Returns the orientation of the given device, or a unit quaternion if the device is not found.
*
* @returns Matrix4f with orientation
*/
override fun getOrientation(id: String): Quaternionf = tracker.getOrientation()
/**
* Returns the absolute position as Vector3f
*
* @return HMD position as Vector3f
*/
override fun getPosition(): Vector3f {
if(fakeTrackerInput) {
// val pos = Vector3f(
// 1.92f * Math.sin(System.nanoTime()/10e9 % (2.0*Math.PI)).toFloat(),
// 1.5f,
// -1.92f * Math.cos(System.nanoTime()/10e9 % (2.0*Math.PI)).toFloat())
val pos = Vector3f(0.0f, 1.7f, 0.0f)
return pos
}
return tracker.getPosition()
}
/**
* Returns the optimal render target size for the HMD as 2D vector
*
* @return Render target size as 2D vector
*/
override fun getRenderTargetSize(): Vector2i {
return Vector2i(config.screenWidth * 2, config.screenHeight * 1)
}
/**
* Returns the HMD pose
*
* @return HMD pose as Matrix4f
*/
override fun getPose(): Matrix4f {
@Suppress("UNUSED_VARIABLE")
val trackerOrientation = tracker.getOrientation()
val trackerPos = tracker.getPosition()
currentOrientation.identity()
currentOrientation.translate(-trackerPos.x(), -trackerPos.y(), trackerPos.z())
return currentOrientation
}
/**
* Returns the HMD pose per eye
*
* @return HMD pose as Matrix4f
*/
override fun getPoseForEye(eye: Int): Matrix4f {
val p = Matrix4f(this.getPose())
p.mul(getHeadToEyeTransform(eye))
return p
}
/**
* Returns a list of poses for the devices [type] given.
*
* @return Pose as Matrix4f
*/
override fun getPose(type: TrackedDeviceType): List<TrackedDevice> {
return listOf(TrackedDevice(TrackedDeviceType.HMD, "StereoGlasses", getPose(), System.nanoTime()))
}
/**
* Check whether the HMD is initialized and working
*
* @return True if HMD is initialised correctly and working properly
*/
override fun initializedAndWorking(): Boolean {
if(fakeTrackerInput) {
return true
}
return tracker.initializedAndWorking()
}
/**
* update state
*/
override fun update() {
tracker.update()
}
override fun getVulkanInstanceExtensions(): List<String> = emptyList()
override fun getWorkingTracker(): TrackerInput? {
if(initializedAndWorking()) {
return this
} else {
return null
}
}
override fun getVulkanDeviceExtensions(physicalDevice: VkPhysicalDevice): List<String> = emptyList()
override fun getWorkingDisplay(): Display? {
if(initializedAndWorking()) {
return this
} else {
return null
}
}
/**
* Returns the per-eye transform that moves from head to eye
*
* @param[eye] The eye index
* @return Matrix4f containing the transform
*/
override fun getHeadToEyeTransform(eye: Int): Matrix4f {
val shift = Matrix4f().identity()
if(eye == 0) {
shift.translate(ipd/2.0f, 0.0f, 0.0f)
} else {
shift.translate(-ipd/2.0f, 0.0f, 0.0f)
}
return shift
}
override fun fadeToColor(color: Vector4f, seconds: Float) {
TODO("Not yet implemented")
// Ulrik: this could be easily implemented with a cam-attached plane that fades, and is removed after the fade 👍
}
override fun loadModelForMesh(type: TrackedDeviceType, mesh: Mesh): Mesh {
TODO("not implemented")
}
override fun loadModelForMesh(device: TrackedDevice, mesh: Mesh): Mesh {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun attachToNode(device: TrackedDevice, node: Node, camera: Camera?) {
TODO("not implemented")
}
override fun getTrackedDevices(ofType: TrackedDeviceType): Map<String, TrackedDevice> {
TODO("Not implemented yet")
}
}
|
lgpl-3.0
|
933dbe2c28cd1c253010393645b00cf7
| 29.843949 | 180 | 0.609602 | 4.380371 | false | true | false | false |
tommykw/Musical
|
app/src/main/java/com/github/tommykw/musical/di/AppModule.kt
|
1
|
1989
|
package com.github.tommykw.musical.di
import android.app.Application
import com.github.tommykw.musical.data.local.MusicalDatabase
import com.github.tommykw.musical.data.network.MusicalRemoteDataSource
import com.github.tommykw.musical.data.network.MusicalService
import dagger.Module
import dagger.Provides
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module(includes = [ViewModelModule::class, NetworkModule::class])
class AppModule {
@Singleton
@Provides
fun provideMusicalService(okhttpClient: OkHttpClient,
converterFactory: GsonConverterFactory
) = provideService(okhttpClient, converterFactory, MusicalService::class.java)
@Singleton
@Provides
fun provideMusicalRemoteDataSource(musicalService: MusicalService)
= MusicalRemoteDataSource(musicalService)
@Singleton
@Provides
fun provideCoroutineDispatcher() = Dispatchers.Default
@Singleton
@Provides
fun provideDb(app: Application) = MusicalDatabase.getInstance(app)
@Singleton
@Provides
fun provideMusicalDao(db: MusicalDatabase) = db.musicalDao()
@CoroutineScopeIO
@Provides
fun provideCoroutineScopeIO() = CoroutineScope(Dispatchers.IO)
private fun <T> provideService(okhttpClient: OkHttpClient,
converterFactory: GsonConverterFactory, clazz: Class<T>): T {
return createRetrofit(okhttpClient, converterFactory).create(clazz)
}
private fun createRetrofit(
okhttpClient: OkHttpClient,
converterFactory: GsonConverterFactory
): Retrofit {
return Retrofit.Builder()
.baseUrl(MusicalService.BASE_URL)
.client(okhttpClient)
.addConverterFactory(converterFactory)
.build()
}
}
|
mit
|
b03a7801bee633f972b21efb657b3495
| 31.096774 | 96 | 0.724485 | 4.984962 | false | false | false | false |
androidx/androidx
|
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/BloodPressureRecord.kt
|
3
|
10811
|
/*
* 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.aggregate.AggregateMetric
import androidx.health.connect.client.records.BloodPressureRecord.MeasurementLocation
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Pressure
import androidx.health.connect.client.units.millimetersOfMercury
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the blood pressure of a user. Each record represents a single instantaneous blood
* pressure reading.
*/
public class BloodPressureRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/**
* Systolic blood pressure measurement, in [Pressure] unit. Required field. Valid range: 20-200
* mmHg.
*/
public val systolic: Pressure,
/**
* Diastolic blood pressure measurement, in [Pressure] unit. Required field. Valid range: 10-180
* mmHg.
*/
public val diastolic: Pressure,
/**
* The user's body position when the measurement was taken. Optional field. Allowed values:
* [BodyPosition].
*
* @see BodyPosition
*/
@property:BodyPositions public val bodyPosition: Int = BODY_POSITION_UNKNOWN,
/**
* The arm and part of the arm where the measurement was taken. Optional field. Allowed values:
* [MeasurementLocation].
*
* @see MeasurementLocation
*/
@property:MeasurementLocations
public val measurementLocation: Int = MEASUREMENT_LOCATION_UNKNOWN,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
init {
systolic.requireNotLess(other = MIN_SYSTOLIC, name = "systolic")
systolic.requireNotMore(other = MAX_SYSTOLIC, name = "systolic")
diastolic.requireNotLess(other = MIN_DIASTOLIC, name = "diastolic")
diastolic.requireNotMore(other = MAX_DIASTOLIC, name = "diastolic")
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BloodPressureRecord) return false
if (systolic != other.systolic) return false
if (diastolic != other.diastolic) return false
if (bodyPosition != other.bodyPosition) return false
if (measurementLocation != other.measurementLocation) return false
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = systolic.hashCode()
result = 31 * result + diastolic.hashCode()
result = 31 * result + bodyPosition
result = 31 * result + measurementLocation
result = 31 * result + time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
/** The arm and part of the arm where a blood pressure measurement was taken. */
internal object MeasurementLocation {
const val LEFT_WRIST = "left_wrist"
const val RIGHT_WRIST = "right_wrist"
const val LEFT_UPPER_ARM = "left_upper_arm"
const val RIGHT_UPPER_ARM = "right_upper_arm"
}
/**
* The user's body position when a health measurement is taken.
* @suppress
*/
internal object BodyPosition {
const val STANDING_UP = "standing_up"
const val SITTING_DOWN = "sitting_down"
const val LYING_DOWN = "lying_down"
const val RECLINING = "reclining"
}
/**
* The arm and part of the arm where a blood pressure measurement was taken.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
MEASUREMENT_LOCATION_UNKNOWN,
MEASUREMENT_LOCATION_LEFT_WRIST,
MEASUREMENT_LOCATION_RIGHT_WRIST,
MEASUREMENT_LOCATION_LEFT_UPPER_ARM,
MEASUREMENT_LOCATION_RIGHT_UPPER_ARM
]
)
annotation class MeasurementLocations
/**
* The user's body position when a health measurement is taken.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
BODY_POSITION_UNKNOWN,
BODY_POSITION_STANDING_UP,
BODY_POSITION_SITTING_DOWN,
BODY_POSITION_LYING_DOWN,
BODY_POSITION_RECLINING
]
)
annotation class BodyPositions
companion object {
const val MEASUREMENT_LOCATION_UNKNOWN = 0
const val MEASUREMENT_LOCATION_LEFT_WRIST = 1
const val MEASUREMENT_LOCATION_RIGHT_WRIST = 2
const val MEASUREMENT_LOCATION_LEFT_UPPER_ARM = 3
const val MEASUREMENT_LOCATION_RIGHT_UPPER_ARM = 4
const val BODY_POSITION_UNKNOWN = 0
const val BODY_POSITION_STANDING_UP = 1
const val BODY_POSITION_SITTING_DOWN = 2
const val BODY_POSITION_LYING_DOWN = 3
const val BODY_POSITION_RECLINING = 4
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val MEASUREMENT_LOCATION_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
MeasurementLocation.LEFT_UPPER_ARM to MEASUREMENT_LOCATION_LEFT_UPPER_ARM,
MeasurementLocation.LEFT_WRIST to MEASUREMENT_LOCATION_LEFT_WRIST,
MeasurementLocation.RIGHT_UPPER_ARM to MEASUREMENT_LOCATION_RIGHT_UPPER_ARM,
MeasurementLocation.RIGHT_WRIST to MEASUREMENT_LOCATION_RIGHT_WRIST
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val MEASUREMENT_LOCATION_INT_TO_STRING_MAP =
MEASUREMENT_LOCATION_STRING_TO_INT_MAP.reverse()
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val BODY_POSITION_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
BodyPosition.LYING_DOWN to BODY_POSITION_LYING_DOWN,
BodyPosition.RECLINING to BODY_POSITION_RECLINING,
BodyPosition.SITTING_DOWN to BODY_POSITION_SITTING_DOWN,
BodyPosition.STANDING_UP to BODY_POSITION_STANDING_UP
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val BODY_POSITION_INT_TO_STRING_MAP = BODY_POSITION_STRING_TO_INT_MAP.reverse()
private const val BLOOD_PRESSURE_NAME = "BloodPressure"
private const val SYSTOLIC_FIELD_NAME = "systolic"
private const val DIASTOLIC_FIELD_NAME = "diastolic"
private val MIN_SYSTOLIC = 10.millimetersOfMercury
private val MAX_SYSTOLIC = 200.millimetersOfMercury
private val MIN_DIASTOLIC = 10.millimetersOfMercury
private val MAX_DIASTOLIC = 180.millimetersOfMercury
/**
* Metric identifier to retrieve average systolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SYSTOLIC_AVG: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.AVERAGE,
fieldName = SYSTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
/**
* Metric identifier to retrieve minimum systolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SYSTOLIC_MIN: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.MINIMUM,
fieldName = SYSTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
/**
* Metric identifier to retrieve maximum systolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SYSTOLIC_MAX: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.MAXIMUM,
fieldName = SYSTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
/**
* Metric identifier to retrieve average diastolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val DIASTOLIC_AVG: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.AVERAGE,
fieldName = DIASTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
/**
* Metric identifier to retrieve minimum diastolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val DIASTOLIC_MIN: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.MINIMUM,
fieldName = DIASTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
/**
* Metric identifier to retrieve maximum diastolic from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val DIASTOLIC_MAX: AggregateMetric<Pressure> =
AggregateMetric.doubleMetric(
dataTypeName = BLOOD_PRESSURE_NAME,
aggregationType = AggregateMetric.AggregationType.MAXIMUM,
fieldName = DIASTOLIC_FIELD_NAME,
mapper = Pressure::millimetersOfMercury,
)
}
}
|
apache-2.0
|
efc91e35370da7b6f3f77af974e6d58c
| 37.066901 | 100 | 0.639164 | 4.340024 | false | false | false | false |
nebula-plugins/lock-experimental
|
src/main/kotlin/com/netflix/nebula/lock/NebulaLockPlugin.kt
|
1
|
1911
|
/*
* Copyright 2016-2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nebula.lock
import com.netflix.nebula.lock.groovy.GroovyLockExtensions
import com.netflix.nebula.lock.groovy.NebulaLockExtension
import com.netflix.nebula.lock.task.ConvertLegacyLockTask
import com.netflix.nebula.lock.task.PrepareForLocksTask
import com.netflix.nebula.lock.task.StripLocksTask
import com.netflix.nebula.lock.task.UpdateLockTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.util.*
class NebulaLockPlugin: Plugin<Project> {
override fun apply(project: Project) {
val locksInEffect = ArrayList<Locked>()
val lockService = LockService(project, locksInEffect)
val prepareForLocks = project.tasks.create("prepareForLocks", PrepareForLocksTask::class.java) { it.lockService = lockService }
project.tasks.create("updateLocks", UpdateLockTask::class.java) { it.lockService = lockService }.dependsOn(prepareForLocks)
project.tasks.create("convertLegacyLocks", ConvertLegacyLockTask::class.java) { it.lockService = lockService }
project.tasks.create("stripLocks", StripLocksTask::class.java) { it.lockService = lockService }
project.extensions.create("nebulaDependencyLock", NebulaLockExtension::class.java)
GroovyLockExtensions.enhanceDependencySyntax(project, locksInEffect)
}
}
|
apache-2.0
|
f62db7f233b9ea6bb5c21ff9afe6a0a7
| 44.52381 | 135 | 0.767138 | 3.98125 | false | false | false | false |
davidcrotty/Hercules
|
app/src/main/java/net/davidcrotty/hercules/view/PlanFragment.kt
|
1
|
2526
|
package net.davidcrotty.hercules.view
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_dashboard.*
import net.davidcrotty.hercules.ExerciseActivity
import net.davidcrotty.hercules.R
import net.davidcrotty.hercules.adapter.PlanCardAdapter
import net.davidcrotty.hercules.adapter.RecyclerListener
import net.davidcrotty.hercules.domain.DataSource
import net.davidcrotty.hercules.model.Plan
import net.davidcrotty.hercules.model.Set
import net.davidcrotty.progressview.SetState
/**
* Created by David Crotty on 17/09/2017.
*
* Copyright © 2017 David Crotty - All Rights Reserved
*/
class PlanFragment : Fragment(), RecyclerListener {
companion object {
val DAY_INDEX_KEY = "DAY_INDEX_KEY"
fun newInstance(index: Int) : PlanFragment {
val fragment = PlanFragment()
val bundle = Bundle()
bundle.putInt(DAY_INDEX_KEY, index)
fragment.arguments = bundle
return fragment
}
}
private var adapter: PlanCardAdapter? = null
private var dataSet: ArrayList<Plan>? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_dashboard, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val dataSource = DataSource()
val index = arguments.getInt(DAY_INDEX_KEY, - 1)
if(index >= 0) {
val dataSet = dataSource.planForDay(index)
val adapter = PlanCardAdapter(dataSet, activity, this)
this.dataSet = dataSet
this.adapter = adapter
plan_list.layoutManager = LinearLayoutManager(activity)
plan_list.adapter = adapter
}
}
override fun onClick(view: View, position: Int) {
val intent = Intent(activity, ExerciseActivity::class.java)
val plan = dataSet?.get(position) ?: return
val converted = plan.setList.map {
item -> Set(item.name, item.repititions, item.timeSeconds, SetState.PENDING)
} as ArrayList<Set>
intent.putParcelableArrayListExtra(ExerciseActivity.SET_KEY, converted)
startActivity(intent)
}
}
|
mit
|
1ff309ba0944e64b03a9e88d655f5308
| 35.085714 | 117 | 0.702574 | 4.492883 | false | false | false | false |
GunoH/intellij-community
|
python/python-features-trainer/src/com/jetbrains/python/ift/PythonLangSupport.kt
|
8
|
1082
|
// 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.jetbrains.python.ift
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import training.project.ProjectUtils
import training.project.ReadMeCreator
import training.util.getFeedbackLink
class PythonLangSupport : PythonBasedLangSupport() {
override val contentRootDirectoryName = "PyCharmLearningProject"
override val primaryLanguage = "Python"
override val defaultProductName: String = "PyCharm"
private val sourcesDirectoryName: String = "src"
override val scratchFileName: String = "Learning.py"
override val langCourseFeedback get() = getFeedbackLink(this, false)
override val readMeCreator = ReadMeCreator()
override fun applyToProjectAfterConfigure(): (Project) -> Unit = { project ->
ProjectUtils.markDirectoryAsSourcesRoot(project, sourcesDirectoryName)
}
override fun blockProjectFileModification(project: Project, file: VirtualFile): Boolean = true
}
|
apache-2.0
|
2f796f7c444131c776081c55124724e7
| 35.066667 | 140 | 0.796673 | 4.565401 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.kt
|
2
|
28426
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.*
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.notification.EventLog
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.FusAwareAction
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.ui.Divider
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.util.*
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi
import com.intellij.toolWindow.FocusTask
import com.intellij.toolWindow.InternalDecoratorImpl
import com.intellij.toolWindow.ToolWindowEventSource
import com.intellij.toolWindow.ToolWindowProperty
import com.intellij.ui.ClientProperty
import com.intellij.ui.LayeredIcon
import com.intellij.ui.UIBundle
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.ui.content.impl.ContentImpl
import com.intellij.ui.content.impl.ContentManagerImpl
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Consumer
import com.intellij.util.ModalityUiUtil
import com.intellij.util.SingleAlarm
import com.intellij.util.ui.*
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jetbrains.annotations.ApiStatus
import java.awt.AWTEvent
import java.awt.Color
import java.awt.Component
import java.awt.Rectangle
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.InputEvent
import java.util.*
import javax.swing.*
import kotlin.math.abs
internal class ToolWindowImpl(val toolWindowManager: ToolWindowManagerImpl,
private val id: String,
private val canCloseContent: Boolean,
private val dumbAware: Boolean,
component: JComponent?,
private val parentDisposable: Disposable,
windowInfo: WindowInfo,
private var contentFactory: ToolWindowFactory?,
private var isAvailable: Boolean = true,
@NlsContexts.TabTitle private var stripeTitle: String) : ToolWindowEx {
var windowInfoDuringInit: WindowInfoImpl? = null
private val focusTask by lazy { FocusTask(this) }
val focusAlarm by lazy { SingleAlarm(focusTask, 0, disposable) }
override fun getId() = id
override fun getProject() = toolWindowManager.project
override fun getDecoration(): ToolWindowEx.ToolWindowDecoration {
return ToolWindowEx.ToolWindowDecoration(icon, additionalGearActions)
}
var windowInfo: WindowInfo = windowInfo
private set
private var contentUi: ToolWindowContentUi? = null
internal var decorator: InternalDecoratorImpl? = null
private set
private var hideOnEmptyContent = false
var isPlaceholderMode = false
private var pendingContentManagerListeners: MutableList<ContentManagerListener>? = null
private val showing = object : BusyObject.Impl() {
override fun isReady(): Boolean {
return getComponentIfInitialized()?.isShowing ?: false
}
}
private var toolWindowFocusWatcher: ToolWindowFocusWatcher? = null
private var additionalGearActions: ActionGroup? = null
private var helpId: String? = null
internal var icon: ToolWindowIcon? = null
private val contentManager = lazy {
val result = createContentManager()
if (toolWindowManager.isNewUi) {
result.addContentManagerListener(UpdateBackgroundContentManager(decorator))
}
result
}
private val moveOrResizeAlarm = SingleAlarm(Runnable {
val decorator = [email protected]
if (decorator != null) {
toolWindowManager.movedOrResized(decorator)
}
[email protected] = toolWindowManager.getLayout().getInfo(getId()) as WindowInfo
}, 100, disposable)
init {
if (component != null) {
val content = ContentImpl(component, "", false)
val contentManager = contentManager.value
contentManager.addContent(content)
contentManager.setSelectedContent(content, false)
}
}
private class UpdateBackgroundContentManager(private val decorator: InternalDecoratorImpl?) : ContentManagerListener {
override fun contentAdded(event: ContentManagerEvent) {
setBackgroundRecursively(event.content.component, JBUI.CurrentTheme.ToolWindow.background())
addAdjustListener(decorator, event.content.component)
}
}
internal fun getOrCreateDecoratorComponent(): InternalDecoratorImpl {
ensureContentManagerInitialized()
return decorator!!
}
fun createCellDecorator() : InternalDecoratorImpl {
val cellContentManager = ContentManagerImpl(canCloseContent, toolWindowManager.project, parentDisposable, ContentManagerImpl.ContentUiProducer { contentManager, componentGetter ->
ToolWindowContentUi(this, contentManager, componentGetter.get())
})
return InternalDecoratorImpl(this, cellContentManager.ui as ToolWindowContentUi, cellContentManager.component)
}
private fun createContentManager(): ContentManagerImpl {
val contentManager = ContentManagerImpl(canCloseContent, toolWindowManager.project, parentDisposable,
ContentManagerImpl.ContentUiProducer { contentManager, componentGetter ->
val result = ToolWindowContentUi(this, contentManager, componentGetter.get())
contentUi = result
result
})
addContentNotInHierarchyComponents(contentUi!!)
val contentComponent = contentManager.component
InternalDecoratorImpl.installFocusTraversalPolicy(contentComponent, LayoutFocusTraversalPolicy())
Disposer.register(parentDisposable, UiNotifyConnector(contentComponent, object : Activatable {
override fun showNotify() {
showing.onReady()
}
}))
var decoratorChild = contentManager.component
if (!dumbAware) {
decoratorChild = DumbService.getInstance(toolWindowManager.project).wrapGently(decoratorChild, parentDisposable)
}
val decorator = InternalDecoratorImpl(this, contentUi!!, decoratorChild)
this.decorator = decorator
decorator.applyWindowInfo(windowInfo)
decorator.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
onMovedOrResized()
}
})
toolWindowFocusWatcher = ToolWindowFocusWatcher(toolWindow = this, component = decorator)
contentManager.addContentManagerListener(object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) {
[email protected]?.headerToolbar?.updateActionsImmediately()
}
})
// after init, as it was before contentManager creation was changed to be lazy
pendingContentManagerListeners?.let { list ->
pendingContentManagerListeners = null
for (listener in list) {
contentManager.addContentManagerListener(listener)
}
}
return contentManager
}
fun onMovedOrResized() {
moveOrResizeAlarm.cancelAndRequest()
}
internal fun setWindowInfoSilently(info: WindowInfo) {
windowInfo = info
}
internal fun applyWindowInfo(info: WindowInfo) {
windowInfo = info
contentUi?.setType(info.contentUiType)
val decorator = decorator
if (decorator != null) {
decorator.applyWindowInfo(info)
decorator.validate()
decorator.repaint()
}
}
val decoratorComponent: JComponent?
get() = decorator
val hasFocus: Boolean
get() = decorator?.hasFocus() ?: false
fun setFocusedComponent(component: Component) {
toolWindowFocusWatcher?.setFocusedComponentImpl(component)
}
fun getLastFocusedContent() : Content? {
val lastFocusedComponent = toolWindowFocusWatcher?.focusedComponent
if (lastFocusedComponent is JComponent) {
if (!lastFocusedComponent.isShowing) return null
val nearestDecorator = InternalDecoratorImpl.findNearestDecorator(lastFocusedComponent)
val content = nearestDecorator?.contentManager?.getContent(lastFocusedComponent)
if (content != null && content.isSelected) return content
}
return null
}
override fun getDisposable() = parentDisposable
override fun remove() {
@Suppress("DEPRECATION")
toolWindowManager.unregisterToolWindow(id)
}
override fun activate(runnable: Runnable?, autoFocusContents: Boolean, forced: Boolean) {
toolWindowManager.activateToolWindow(id, runnable, autoFocusContents)
}
override fun isActive(): Boolean {
return windowInfo.isVisible && decorator != null && toolWindowManager.activeToolWindowId == id
}
override fun getReady(requestor: Any): ActionCallback {
val result = ActionCallback()
showing.getReady(this)
.doWhenDone {
toolWindowManager.focusManager.doWhenFocusSettlesDown {
if (contentManager.isInitialized() && contentManager.value.isDisposed) {
return@doWhenFocusSettlesDown
}
contentManager.value.getReady(requestor).notify(result)
}
}
return result
}
override fun show(runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.showToolWindow(id)
callLater(runnable)
}
override fun hide(runnable: Runnable?) {
toolWindowManager.hideToolWindow(id)
callLater(runnable)
}
override fun isVisible() = windowInfo.isVisible
override fun getAnchor() = windowInfo.anchor
override fun setAnchor(anchor: ToolWindowAnchor, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setToolWindowAnchor(id, anchor)
callLater(runnable)
}
override fun isSplitMode() = windowInfo.isSplit
override fun setContentUiType(type: ToolWindowContentUiType, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setContentUiType(id, type)
callLater(runnable)
}
override fun setDefaultContentUiType(type: ToolWindowContentUiType) {
toolWindowManager.setDefaultContentUiType(this, type)
}
override fun getContentUiType() = windowInfo.contentUiType
override fun setSplitMode(isSideTool: Boolean, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setSideTool(id, isSideTool)
callLater(runnable)
}
override fun setAutoHide(value: Boolean) {
toolWindowManager.setToolWindowAutoHide(id, value)
}
override fun isAutoHide() = windowInfo.isAutoHide
override fun getType() = windowInfo.type
override fun setType(type: ToolWindowType, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setToolWindowType(id, type)
callLater(runnable)
}
override fun getInternalType() = windowInfo.internalType
override fun stretchWidth(value: Int) {
toolWindowManager.stretchWidth(this, value)
}
override fun stretchHeight(value: Int) {
toolWindowManager.stretchHeight(this, value)
}
override fun getDecorator(): InternalDecoratorImpl = decorator!!
override fun setAdditionalGearActions(value: ActionGroup?) {
additionalGearActions = value
}
override fun setTitleActions(actions: List<AnAction>) {
ensureContentManagerInitialized()
decorator!!.setTitleActions(actions)
}
override fun setTabActions(vararg actions: AnAction) {
createContentIfNeeded()
decorator!!.setTabActions(actions.toList())
}
override fun setTabDoubleClickActions(actions: List<AnAction>) {
contentUi?.setTabDoubleClickActions(actions)
}
override fun setAvailable(value: Boolean) {
if (isAvailable == value) {
return
}
if (windowInfoDuringInit != null) {
throw IllegalStateException("Do not use toolWindow.setAvailable() as part of ToolWindowFactory.init().\n" +
"Use ToolWindowFactory.shouldBeAvailable() instead.")
}
toolWindowManager.assertIsEdt()
isAvailable = value
if (value) {
toolWindowManager.toolWindowAvailable(this)
}
else {
toolWindowManager.toolWindowUnavailable(this)
contentUi?.dropCaches()
}
}
override fun setAvailable(value: Boolean, runnable: Runnable?) {
setAvailable(value)
callLater(runnable)
}
private fun callLater(runnable: Runnable?) {
if (runnable != null) {
toolWindowManager.invokeLater(runnable)
}
}
override fun installWatcher(contentManager: ContentManager) {
ContentManagerWatcher.watchContentManager(this, contentManager)
}
override fun isAvailable() = isAvailable
override fun getComponent(): JComponent {
if (toolWindowManager.project.isDisposed) {
// nullable because of TeamCity plugin
@Suppress("HardCodedStringLiteral")
return JLabel("Do not call getComponent() on dispose")
}
return contentManager.value.component
}
fun getComponentIfInitialized(): JComponent? {
return if (contentManager.isInitialized()) contentManager.value.component else null
}
override fun getContentManagerIfCreated(): ContentManager? {
return if (contentManager.isInitialized()) contentManager.value else null
}
override fun getContentManager(): ContentManager {
createContentIfNeeded()
return contentManager.value
}
override fun addContentManagerListener(listener: ContentManagerListener) {
if (contentManager.isInitialized()) {
contentManager.value.addContentManagerListener(listener)
}
else {
if (pendingContentManagerListeners == null) {
pendingContentManagerListeners = mutableListOf()
}
pendingContentManagerListeners!!.add(listener)
}
}
override fun canCloseContents() = canCloseContent
override fun getIcon() = icon
override fun getTitle(): String? = contentManager.value.selectedContent?.displayName
override fun getStripeTitle() = stripeTitle
override fun setIcon(newIcon: Icon) {
EDT.assertIsEdt()
if (newIcon !== icon?.retrieveIcon()) {
doSetIcon(newIcon)
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.ICON)
}
}
internal fun doSetIcon(newIcon: Icon) {
val oldIcon = icon
if (EventLog.LOG_TOOL_WINDOW_ID != id && oldIcon !== newIcon &&
newIcon !is LayeredIcon &&
!toolWindowManager.isNewUi &&
(abs(newIcon.iconHeight - JBUIScale.scale(13f)) >= 1 || abs(newIcon.iconWidth - JBUIScale.scale(13f)) >= 1)) {
logger<ToolWindowImpl>().warn("ToolWindow icons should be 13x13. Please fix ToolWindow (ID: $id) or icon $newIcon")
}
icon = ToolWindowIcon(newIcon, id)
}
override fun setTitle(title: String) {
EDT.assertIsEdt()
contentManager.value.selectedContent?.displayName = title
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.TITLE)
}
override fun setStripeTitle(value: String) {
if (value == stripeTitle) {
return
}
stripeTitle = value
contentUi?.update()
if (windowInfoDuringInit == null) {
EDT.assertIsEdt()
toolWindowManager.toolWindowPropertyChanged(toolWindow = this, property = ToolWindowProperty.STRIPE_TITLE)
}
}
fun fireActivated(source: ToolWindowEventSource) {
toolWindowManager.activated(this, source)
}
fun fireHidden(source: ToolWindowEventSource?) {
toolWindowManager.hideToolWindow(id = id, source = source)
}
fun fireHiddenSide(source: ToolWindowEventSource?) {
toolWindowManager.hideToolWindow(id = id, hideSide = true, source = source)
}
override fun setDefaultState(anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) {
toolWindowManager.setDefaultState(this, anchor, type, floatingBounds)
}
override fun setToHideOnEmptyContent(value: Boolean) {
hideOnEmptyContent = value
}
fun isToHideOnEmptyContent() = hideOnEmptyContent
override fun setShowStripeButton(value: Boolean) {
val windowInfoDuringInit = windowInfoDuringInit
if (windowInfoDuringInit == null) {
toolWindowManager.setShowStripeButton(id, value)
}
else {
windowInfoDuringInit.isShowStripeButton = value
}
}
override fun isShowStripeButton() = windowInfo.isShowStripeButton
override fun isDisposed() = contentManager.isInitialized() && contentManager.value.isDisposed
private fun ensureContentManagerInitialized() {
contentManager.value
}
internal fun scheduleContentInitializationIfNeeded() {
if (contentFactory != null) {
// todo use lazy loading (e.g. JBLoadingPanel)
createContentIfNeeded()
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Do not use. Tool window content will be initialized automatically.", level = DeprecationLevel.ERROR)
@ApiStatus.ScheduledForRemoval
fun ensureContentInitialized() {
createContentIfNeeded()
}
internal fun createContentIfNeeded() {
val currentContentFactory = contentFactory ?: return
// clear it first to avoid SOE
this.contentFactory = null
if (contentManager.isInitialized()) {
contentManager.value.removeAllContents(false)
}
else {
ensureContentManagerInitialized()
}
currentContentFactory.createToolWindowContent(toolWindowManager.project, this)
if (toolWindowManager.isNewUi) {
setBackgroundRecursively(contentManager.value.component, JBUI.CurrentTheme.ToolWindow.background())
addAdjustListener(decorator, contentManager.value.component)
}
}
override fun getHelpId() = helpId
override fun setHelpId(value: String) {
helpId = value
}
override fun showContentPopup(inputEvent: InputEvent) {
// called only when tool window is already opened, so, content should be already created
ToolWindowContentUi.toggleContentPopup(contentUi!!, contentManager.value)
}
@JvmOverloads
fun createPopupGroup(skipHideAction: Boolean = false): ActionGroup {
val group = GearActionGroup(this)
if (!skipHideAction) {
group.addSeparator()
group.add(HideAction())
}
group.addSeparator()
group.add(object : ContextHelpAction() {
override fun getHelpId(dataContext: DataContext): String? {
val content = contentManagerIfCreated?.selectedContent
if (content != null) {
val helpId = content.helpId
if (helpId != null) {
return helpId
}
}
val id = getHelpId()
if (id != null) {
return id
}
val context = if (content == null) dataContext else DataManager.getInstance().getDataContext(content.component)
return super.getHelpId(context)
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = getHelpId(e.dataContext) != null
}
})
return group
}
override fun getEmptyText(): StatusText = (contentManager.value.component as ComponentWithEmptyText).emptyText
fun setEmptyStateBackground(color: Color) {
decorator?.background = color
}
private inner class GearActionGroup(toolWindow: ToolWindowImpl) : DefaultActionGroup(), DumbAware {
init {
templatePresentation.icon = AllIcons.General.GearPlain
if (toolWindowManager.isNewUi) {
templatePresentation.icon = AllIcons.Actions.More
}
templatePresentation.text = IdeBundle.message("show.options.menu")
val additionalGearActions = additionalGearActions
if (additionalGearActions != null) {
if (additionalGearActions.isPopup && !additionalGearActions.templatePresentation.text.isNullOrEmpty()) {
add(additionalGearActions)
}
else {
addSorted(this, additionalGearActions)
}
addSeparator()
}
val toggleToolbarGroup = ToggleToolbarAction.createToggleToolbarGroup(toolWindowManager.project, this@ToolWindowImpl)
if (ToolWindowId.PREVIEW != id) {
toggleToolbarGroup.addAction(ToggleContentUiTypeAction())
}
addAction(toggleToolbarGroup).setAsSecondary(true)
add(ActionManager.getInstance().getAction("TW.ViewModeGroup"))
if (toolWindowManager.isNewUi) {
add(SquareStripeButton.createMoveGroup(toolWindow))
}
else {
add(ToolWindowMoveAction.Group())
}
add(ResizeActionGroup())
addSeparator()
add(RemoveStripeButtonAction())
}
}
private inner class HideAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindowManager.hideToolWindow(id, false)
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
presentation.isEnabled = isVisible
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
init {
ActionUtil.copyFrom(this, InternalDecoratorImpl.HIDE_ACTIVE_WINDOW_ACTION_ID)
templatePresentation.text = UIBundle.message("tool.window.hide.action.name")
}
}
private inner class ResizeActionGroup : ActionGroup(ActionsBundle.groupText("ResizeToolWindowGroup"), true), DumbAware {
private val children by lazy<Array<AnAction>> {
// force creation
createContentIfNeeded()
val component = decorator
val toolWindow = this@ToolWindowImpl
arrayOf(
ResizeToolWindowAction.Left(toolWindow, component),
ResizeToolWindowAction.Right(toolWindow, component),
ResizeToolWindowAction.Up(toolWindow, component),
ResizeToolWindowAction.Down(toolWindow, component),
ActionManager.getInstance().getAction("MaximizeToolWindow")
)
}
override fun getChildren(e: AnActionEvent?) = children
override fun isDumbAware() = true
}
private inner class RemoveStripeButtonAction :
AnAction(ActionsBundle.messagePointer("action.RemoveStripeButton.text"),
ActionsBundle.messagePointer("action.RemoveStripeButton.description"),
null), DumbAware, FusAwareAction {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isShowStripeButton
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(e: AnActionEvent) {
toolWindowManager.hideToolWindow(id, removeFromStripe = true, source = ToolWindowEventSource.RemoveStripeButtonAction)
}
override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> {
return listOf(ToolwindowFusEventFields.TOOLWINDOW with id)
}
}
private inner class ToggleContentUiTypeAction : ToggleAction(), DumbAware, FusAwareAction {
private var hadSeveralContents = false
init {
ActionUtil.copyFrom(this, "ToggleContentUiTypeMode")
}
override fun update(e: AnActionEvent) {
hadSeveralContents = hadSeveralContents || (contentManager.isInitialized() && contentManager.value.contentCount > 1)
super.update(e)
e.presentation.isVisible = hadSeveralContents
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun isSelected(e: AnActionEvent): Boolean {
return windowInfo.contentUiType === ToolWindowContentUiType.COMBO
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
toolWindowManager.setContentUiType(id, if (state) ToolWindowContentUiType.COMBO else ToolWindowContentUiType.TABBED)
}
override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> {
return listOf(ToolwindowFusEventFields.TOOLWINDOW with id)
}
}
fun requestFocusInToolWindow() {
focusTask.resetStartTime()
focusAlarm.cancelAllRequests()
focusTask.run()
}
}
private fun addSorted(main: DefaultActionGroup, group: ActionGroup) {
val children = group.getChildren(null)
var hadSecondary = false
for (action in children) {
if (group.isPrimary(action)) {
main.add(action)
}
else {
hadSecondary = true
}
}
if (hadSecondary) {
main.addSeparator()
for (action in children) {
if (!group.isPrimary(action)) {
main.addAction(action).setAsSecondary(true)
}
}
}
val separatorText = group.templatePresentation.text
if (children.isNotEmpty() && !separatorText.isNullOrEmpty()) {
main.addAction(Separator(separatorText), Constraints.FIRST)
}
}
private fun addContentNotInHierarchyComponents(contentUi: ToolWindowContentUi) {
contentUi.component.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, NotInHierarchyComponents(contentUi))
}
private class NotInHierarchyComponents(val contentUi: ToolWindowContentUi) : Iterable<Component> {
private val oldProperty = ClientProperty.get(contentUi.component, UIUtil.NOT_IN_HIERARCHY_COMPONENTS)
override fun iterator(): Iterator<Component> {
var result = emptySequence<Component>()
if (oldProperty != null) {
result += oldProperty.asSequence()
}
val contentManager = contentUi.contentManager
if (contentManager.contentCount != 0) {
result += contentManager.contents
.asSequence()
.mapNotNull { content: Content ->
var last: JComponent? = null
var parent: Component? = content.component
while (parent != null) {
if (parent === contentUi.component || parent !is JComponent) {
return@mapNotNull null
}
last = parent
parent = parent.getParent()
}
last
}
}
return result.iterator()
}
}
/**
* Notifies window manager about focus traversal in a tool window
*/
private class ToolWindowFocusWatcher(private val toolWindow: ToolWindowImpl, component: JComponent) : FocusWatcher() {
private val id = toolWindow.id
init {
install(component)
Disposer.register(toolWindow.disposable, Disposable { deinstall(component) })
}
override fun isFocusedComponentChangeValid(component: Component?, cause: AWTEvent?) = component != null
override fun focusedComponentChanged(component: Component?, cause: AWTEvent?) {
if (component == null || !toolWindow.isActive) {
return
}
val toolWindowManager = toolWindow.toolWindowManager
toolWindowManager.focusManager
.doWhenFocusSettlesDown(ExpirableRunnable.forProject(toolWindowManager.project) {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.defaultModalityState(), toolWindowManager.project.disposed) {
val entry = toolWindowManager.getEntry(id) ?: return@invokeLaterIfNeeded
val windowInfo = entry.readOnlyWindowInfo
if (!windowInfo.isVisible) {
return@invokeLaterIfNeeded
}
toolWindowManager.activateToolWindow(entry = entry,
info = toolWindowManager.getRegisteredMutableInfoOrLogError(entry.id),
autoFocusContents = false)
}
})
}
}
private fun setBackgroundRecursively(component: Component, bg: Color) {
UIUtil.forEachComponentInHierarchy(component, Consumer { c ->
if (c !is ActionButton && c !is Divider) {
c.background = bg
}
})
}
private fun addAdjustListener(decorator: InternalDecoratorImpl?, component: JComponent) {
UIUtil.findComponentOfType(component, JScrollPane::class.java)?.verticalScrollBar?.addAdjustmentListener { event ->
decorator?.let {
ClientProperty.put(it, SimpleToolWindowPanel.SCROLLED_STATE, event.adjustable?.value != 0)
it.header.repaint()
}
}
}
|
apache-2.0
|
7211b922193da92d445b6bdca3ef77f8
| 32.443529 | 183 | 0.718603 | 5.11351 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinFormatterUsageCollector.kt
|
2
|
5246
|
// 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.formatter
import com.intellij.application.options.CodeStyle
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.idea.base.util.containsNonScriptKotlinFile
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.formatter.KotlinFormatterUsageCollector.KotlinFormatterKind.*
class KotlinFormatterUsageCollector : ProjectUsagesCollector() {
override fun requiresReadAccess() = true
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(project: Project): Set<MetricEvent> {
if (KotlinPlatformUtils.isAndroidStudio || project.runReadActionInSmartMode { !project.containsNonScriptKotlinFile() }) {
return emptySet()
}
return setOf(
settingsEvent.metric(
value1 = getKotlinFormatterKind(project),
value2 = getPluginInfoById(KotlinIdePlugin.id),
)
)
}
companion object {
private val GROUP = EventLogGroup("kotlin.ide.formatter", 4)
private val settingsEvent = GROUP.registerEvent(
eventId = "settings",
eventField1 = EventFields.Enum("kind", KotlinFormatterKind::class.java),
eventField2 = EventFields.PluginInfo,
)
private val KOTLIN_OFFICIAL_CODE_STYLE: CodeStyleSettings by lazy {
CodeStyleSettingsManager.getInstance().cloneSettings(CodeStyle.getDefaultSettings()).also(KotlinStyleGuideCodeStyle::apply)
}
private val KOTLIN_OBSOLETE_CODE_STYLE: CodeStyleSettings by lazy {
CodeStyleSettingsManager.getInstance().cloneSettings(CodeStyle.getDefaultSettings()).also(KotlinObsoleteCodeStyle::apply)
}
private fun codeStylesIsEquals(lhs: CodeStyleSettings, rhs: CodeStyleSettings): Boolean =
lhs.kotlinCustomSettings == rhs.kotlinCustomSettings && lhs.kotlinCommonSettings == rhs.kotlinCommonSettings
fun getKotlinFormatterKind(project: Project): KotlinFormatterKind {
val isProject = CodeStyle.usesOwnSettings(project)
val currentSettings = CodeStyle.getSettings(project)
val codeStyleDefaults = currentSettings.kotlinCodeStyleDefaults()
return when (val supposedCodeStyleDefaults = currentSettings.supposedKotlinCodeStyleDefaults()) {
KotlinStyleGuideCodeStyle.CODE_STYLE_ID -> when {
supposedCodeStyleDefaults != codeStyleDefaults -> paired(IDEA_WITH_BROKEN_OFFICIAL_KOTLIN, isProject)
codeStylesIsEquals(currentSettings, KOTLIN_OFFICIAL_CODE_STYLE) -> paired(IDEA_OFFICIAL_KOTLIN, isProject)
else -> paired(IDEA_OFFICIAL_KOTLIN_WITH_CUSTOM, isProject)
}
KotlinObsoleteCodeStyle.CODE_STYLE_ID -> when {
supposedCodeStyleDefaults != codeStyleDefaults -> paired(IDEA_WITH_BROKEN_OBSOLETE_KOTLIN, isProject)
codeStylesIsEquals(currentSettings, KOTLIN_OBSOLETE_CODE_STYLE) -> paired(IDEA_OBSOLETE_KOTLIN, isProject)
else -> paired(IDEA_OBSOLETE_KOTLIN_WITH_CUSTOM, isProject)
}
else -> paired(IDEA_CUSTOM, isProject)
}
}
private fun paired(kind: KotlinFormatterKind, isProject: Boolean): KotlinFormatterKind {
if (!isProject) return kind
return when (kind) {
IDEA_CUSTOM -> PROJECT_CUSTOM
IDEA_OFFICIAL_KOTLIN -> PROJECT_OFFICIAL_KOTLIN
IDEA_OFFICIAL_KOTLIN_WITH_CUSTOM -> PROJECT_OFFICIAL_KOTLIN_WITH_CUSTOM
IDEA_WITH_BROKEN_OFFICIAL_KOTLIN -> PROJECT_WITH_BROKEN_OFFICIAL_KOTLIN
IDEA_OBSOLETE_KOTLIN -> PROJECT_OBSOLETE_KOTLIN
IDEA_OBSOLETE_KOTLIN_WITH_CUSTOM -> PROJECT_OBSOLETE_KOTLIN_WITH_CUSTOM
IDEA_WITH_BROKEN_OBSOLETE_KOTLIN -> PROJECT_WITH_BROKEN_OBSOLETE_KOTLIN
else -> kind
}
}
}
enum class KotlinFormatterKind {
IDEA_CUSTOM, PROJECT_CUSTOM,
IDEA_OFFICIAL_KOTLIN, PROJECT_OFFICIAL_KOTLIN,
IDEA_OFFICIAL_KOTLIN_WITH_CUSTOM, PROJECT_OFFICIAL_KOTLIN_WITH_CUSTOM,
IDEA_WITH_BROKEN_OFFICIAL_KOTLIN, PROJECT_WITH_BROKEN_OFFICIAL_KOTLIN,
IDEA_OBSOLETE_KOTLIN, PROJECT_OBSOLETE_KOTLIN,
IDEA_OBSOLETE_KOTLIN_WITH_CUSTOM, PROJECT_OBSOLETE_KOTLIN_WITH_CUSTOM,
IDEA_WITH_BROKEN_OBSOLETE_KOTLIN, PROJECT_WITH_BROKEN_OBSOLETE_KOTLIN,
}
}
|
apache-2.0
|
9eb36bfedf1c0ed8882e5851d262c591
| 47.137615 | 135 | 0.703202 | 4.817264 | false | false | false | false |
GunoH/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/sealed.kt
|
8
|
2887
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("SealedUtil")
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.util.SmartList
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil
import org.jetbrains.plugins.groovy.lang.psi.util.SealedHelper.inferReferencedClass
internal fun getAllSealedElements(typeDef : GrTypeDefinition) : List<PsiElement> {
val modifier = typeDef.modifierList?.getModifier(GrModifier.SEALED)
val annotation = typeDef.modifierList?.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_SEALED)
return listOf(modifier, annotation).filterNotNullTo(SmartList())
}
fun GrTypeDefinition.getSealedElement() : PsiElement? = getAllSealedElements(this).firstOrNull()
fun getAllPermittedClassElements(typeDef : GrTypeDefinition) : List<PsiElement> {
var isTypeDefSealed = false
if (typeDef.hasModifierProperty(GrModifier.SEALED)) {
isTypeDefSealed = true
if (typeDef.permitsClause?.keyword != null) {
return typeDef.permitsClause?.referenceElementsGroovy?.toList() ?: emptyList()
}
}
else {
val annotation = typeDef.modifierList?.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_SEALED) as? GrAnnotation
val declaredAttribute = annotation?.findDeclaredAttributeValue("permittedSubclasses")
if (annotation != null) {
isTypeDefSealed = true
if (declaredAttribute != null) {
return AnnotationUtil.arrayAttributeValues(declaredAttribute)
}
}
}
if (isTypeDefSealed) {
return (typeDef.containingFile as? GroovyFile)?.classes?.filter { typeDef in (it.extendsListTypes + it.implementsListTypes).mapNotNull(PsiClassType::resolve) }
?: emptyList()
}
return emptyList()
}
// reduce visibility of this function to avoid misuse
object SealedHelper {
fun inferReferencedClass(element : PsiElement) : PsiClass? = when (element) {
is GrCodeReferenceElement -> element.resolve() as? PsiClass
is PsiAnnotationMemberValue -> GrAnnotationUtil.getPsiClass(element)
is PsiClass -> element
else -> null
}
}
fun getAllPermittedClasses(typeDef: GrTypeDefinition): List<PsiClass> =
getAllPermittedClassElements(typeDef).mapNotNull(::inferReferencedClass)
|
apache-2.0
|
b7b7986b6a6fde096ea562e637bc90f1
| 44.84127 | 163 | 0.789401 | 4.532182 | false | false | false | false |
GunoH/intellij-community
|
plugins/gradle/java/src/service/completion/GradleLookupWeigher.kt
|
2
|
2308
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.completion
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementWeigher
import com.intellij.codeInsight.lookup.WeighingContext
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiMember
import com.intellij.util.asSafely
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.gradle.service.resolve.DECLARATION_ALTERNATIVES
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
class GradleLookupWeigher : LookupElementWeigher("gradleWeigher", true, false) {
override fun weigh(element: LookupElement, context: WeighingContext): Comparable<*> {
val completionElement = element.`object`
val holder =
completionElement.asSafely<UserDataHolder>()
?: completionElement.asSafely<GroovyResolveResult>()?.element
?: return 0
val comparable: Int = element.getUserData(COMPLETION_PRIORITY) ?: holder.getUserData(COMPLETION_PRIORITY) ?: getFallbackCompletionPriority(holder)
val deprecationMultiplier = if (element.psiElement?.getUserData(DECLARATION_ALTERNATIVES) != null) 0.9 else 1.0
return (comparable.toDouble() * deprecationMultiplier).toInt()
}
private fun getFallbackCompletionPriority(holder: UserDataHolder): Int {
if (holder !is PsiMember) {
return 0
}
val containingFile = holder.containingFile ?: holder.asSafely<PsiMember>()?.containingClass?.containingFile
if (containingFile is PsiJavaFile && containingFile.packageName.startsWith("org.gradle")) {
return DEFAULT_COMPLETION_PRIORITY
}
return 0
}
companion object {
@JvmStatic
fun setGradleCompletionPriority(element: UserDataHolder, priority: Int) {
element.putUserData(COMPLETION_PRIORITY, priority)
}
const val DEFAULT_COMPLETION_PRIORITY : Int = 100
private val COMPLETION_PRIORITY: Key<Int> = Key.create("grouping priority for gradle completion results")
@TestOnly
fun getGradleCompletionPriority(element: UserDataHolder) : Int? = element.getUserData(COMPLETION_PRIORITY)
}
}
|
apache-2.0
|
4ec93bf537c33faf792fb8a8bf5df1d0
| 41.759259 | 150 | 0.776863 | 4.643863 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/DebugLabelPropertyDescriptorProvider.kt
|
4
|
9164
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate.compilation
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.impl.DebuggerUtilsImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.ui.tree.ValueMarkup
import com.sun.jdi.*
import org.jetbrains.kotlin.backend.common.SimpleMemberScope
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.DeclarationDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl
import org.jetbrains.kotlin.idea.core.util.externalDescriptors
import org.jetbrains.kotlin.idea.debugger.evaluate.getClassDescriptor
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import com.sun.jdi.Type as JdiType
import org.jetbrains.org.objectweb.asm.Type as AsmType
class DebugLabelPropertyDescriptorProvider(val codeFragment: KtCodeFragment, val debugProcess: DebugProcessImpl) {
companion object {
fun getMarkupMap(debugProcess: DebugProcessImpl) = doGetMarkupMap(debugProcess) ?: emptyMap()
private fun doGetMarkupMap(debugProcess: DebugProcessImpl): Map<out Value?, ValueMarkup>? {
if (isUnitTestMode()) {
return DebuggerUtilsImpl.getValueMarkers(debugProcess)?.allMarkers as Map<ObjectReference, ValueMarkup>?
}
val debugSession = debugProcess.session.xDebugSession as? XDebugSessionImpl
@Suppress("UNCHECKED_CAST")
return debugSession?.valueMarkers?.allMarkers?.filterKeys { it is Value? } as Map<out Value?, ValueMarkup>?
}
}
private val moduleDescriptor = DebugLabelModuleDescriptor
fun supplyDebugLabels() {
val packageFragment = object : PackageFragmentDescriptorImpl(moduleDescriptor, FqName.ROOT) {
val properties = createDebugLabelDescriptors(this)
override fun getMemberScope() = SimpleMemberScope(properties)
}
codeFragment.externalDescriptors = packageFragment.properties
}
private fun createDebugLabelDescriptors(containingDeclaration: PackageFragmentDescriptor): List<PropertyDescriptor> {
val markupMap = getMarkupMap(debugProcess)
val result = ArrayList<PropertyDescriptor>(markupMap.size)
nextValue@ for ((value, markup) in markupMap) {
val labelName = markup.text
val kotlinType = value?.type()?.let { convertType(it) } ?: moduleDescriptor.builtIns.nullableAnyType
result += createDebugLabelDescriptor(labelName, kotlinType, containingDeclaration)
}
return result
}
private fun createDebugLabelDescriptor(
labelName: String,
type: KotlinType,
containingDeclaration: PackageFragmentDescriptor
): PropertyDescriptor {
val propertyDescriptor = DebugLabelPropertyDescriptor(containingDeclaration, labelName)
propertyDescriptor.setType(type, emptyList(), null, null, emptyList())
val getterDescriptor = PropertyGetterDescriptorImpl(
propertyDescriptor,
Annotations.EMPTY,
Modality.FINAL,
DescriptorVisibilities.PUBLIC,
/* isDefault = */ false,
/* isExternal = */ false,
/* isInline = */ false,
CallableMemberDescriptor.Kind.SYNTHESIZED,
/* original = */ null,
SourceElement.NO_SOURCE
).apply { initialize(type) }
propertyDescriptor.initialize(getterDescriptor, null)
return propertyDescriptor
}
private fun convertType(type: JdiType): KotlinType {
val builtIns = moduleDescriptor.builtIns
return when (type) {
is VoidType -> builtIns.unitType
is LongType -> builtIns.longType
is DoubleType -> builtIns.doubleType
is CharType -> builtIns.charType
is FloatType -> builtIns.floatType
is ByteType -> builtIns.byteType
is IntegerType -> builtIns.intType
is BooleanType -> builtIns.booleanType
is ShortType -> builtIns.shortType
is ArrayType -> {
when (val componentType = type.componentType()) {
is VoidType -> builtIns.getArrayType(Variance.INVARIANT, builtIns.unitType)
is LongType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.LONG)
is DoubleType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.DOUBLE)
is CharType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.CHAR)
is FloatType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.FLOAT)
is ByteType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.BYTE)
is IntegerType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.INT)
is BooleanType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.BOOLEAN)
is ShortType -> builtIns.getPrimitiveArrayKotlinType(PrimitiveType.SHORT)
else -> builtIns.getArrayType(Variance.INVARIANT, convertReferenceType(componentType))
}
}
is ReferenceType -> convertReferenceType(type)
else -> builtIns.anyType
}
}
private fun convertReferenceType(type: JdiType): KotlinType {
require(type is ClassType || type is InterfaceType)
val asmType = AsmType.getType(type.signature())
val project = codeFragment.project
val classDescriptor = asmType.getClassDescriptor(GlobalSearchScope.allScope(project), mapBuiltIns = false)
?: return moduleDescriptor.builtIns.nullableAnyType
return classDescriptor.defaultType
}
}
private object DebugLabelModuleDescriptor : DeclarationDescriptorImpl(Annotations.EMPTY, Name.identifier("DebugLabelExtensions")),
ModuleDescriptor {
override val builtIns: KotlinBuiltIns
get() = DefaultBuiltIns.Instance
override val stableName: Name
get() = name
override fun shouldSeeInternalsOf(targetModule: ModuleDescriptor) = false
override fun getPackage(fqName: FqName): PackageViewDescriptor {
return object : PackageViewDescriptor, DeclarationDescriptorImpl(Annotations.EMPTY, FqName.ROOT.shortNameOrSpecial()) {
override fun getContainingDeclaration(): PackageViewDescriptor? = null
override val fqName: FqName
get() = FqName.ROOT
override val memberScope: MemberScope
get() = MemberScope.Empty
override val module: ModuleDescriptor
get() = this@DebugLabelModuleDescriptor
override val fragments: List<PackageFragmentDescriptor>
get() = emptyList()
override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R {
return visitor.visitPackageViewDescriptor(this, data)
}
}
}
override val platform: TargetPlatform
get() = JvmPlatforms.unspecifiedJvmPlatform
override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection<FqName> {
return emptyList()
}
override val allDependencyModules: List<ModuleDescriptor>
get() = emptyList()
override val expectedByModules: List<ModuleDescriptor>
get() = emptyList()
override val allExpectedByModules: Set<ModuleDescriptor>
get() = emptySet()
override fun <T> getCapability(capability: ModuleCapability<T>): T? = null
override val isValid: Boolean
get() = true
override fun assertValid() {}
}
internal class DebugLabelPropertyDescriptor(
containingDeclaration: DeclarationDescriptor,
val labelName: String
) : PropertyDescriptorImpl(
containingDeclaration,
null,
Annotations.EMPTY,
Modality.FINAL,
DescriptorVisibilities.PUBLIC,
/*isVar = */false,
Name.identifier(labelName + "_DebugLabel"),
CallableMemberDescriptor.Kind.SYNTHESIZED,
SourceElement.NO_SOURCE,
/*lateInit = */false,
/*isConst = */false,
/*isExpect = */false,
/*isActual = */false,
/*isExternal = */false,
/*isDelegated = */false
)
|
apache-2.0
|
44591f1e97915b3977b6ee3423515ca1
| 40.844749 | 130 | 0.704168 | 5.471045 | false | false | false | false |
JetBrains/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/BridgesBuilding.kt
|
1
|
12633
|
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.ClassLoweringPass
import org.jetbrains.kotlin.backend.common.DeclarationContainerLoweringPass
import org.jetbrains.kotlin.backend.common.ir.simpleFunctions
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlockBody
import org.jetbrains.kotlin.backend.common.lower.irIfThen
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.isNullableAny
import org.jetbrains.kotlin.ir.util.transformFlat
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature
import org.jetbrains.kotlin.load.java.SpecialGenericSignatures
internal class WorkersBridgesBuilding(val context: Context) : DeclarationContainerLoweringPass, IrElementTransformerVoid() {
val symbols = context.ir.symbols
lateinit var runtimeJobFunction: IrSimpleFunction
override fun lower(irDeclarationContainer: IrDeclarationContainer) {
irDeclarationContainer.declarations.transformFlat {
listOf(it) + buildWorkerBridges(it).also { bridges ->
// `buildWorkerBridges` builds bridges for all declarations inside `it` and nested declarations,
// so some bridges get incorrect parent. Fix it:
bridges.forEach { bridge -> bridge.parent = irDeclarationContainer }
}
}
}
private fun buildWorkerBridges(declaration: IrDeclaration): List<IrFunction> {
val bridges = mutableListOf<IrFunction>()
declaration.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitClass(declaration: IrClass): IrStatement {
// Skip nested.
return declaration
}
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
if (expression.symbol != symbols.executeImpl)
return expression
val job = expression.getValueArgument(3) as IrFunctionReference
val jobFunction = (job.symbol as IrSimpleFunctionSymbol).owner
if (!::runtimeJobFunction.isInitialized) {
val arg = jobFunction.valueParameters[0]
val startOffset = jobFunction.startOffset
val endOffset = jobFunction.endOffset
runtimeJobFunction =
IrFunctionImpl(
startOffset, endOffset,
IrDeclarationOrigin.DEFINED,
IrSimpleFunctionSymbolImpl(),
jobFunction.name,
jobFunction.visibility,
jobFunction.modality,
isInline = false,
isExternal = false,
isTailrec = false,
isSuspend = false,
returnType = context.irBuiltIns.anyNType,
isExpect = false,
isFakeOverride = false,
isOperator = false,
isInfix = false
)
runtimeJobFunction.valueParameters +=
IrValueParameterImpl(
startOffset, endOffset,
IrDeclarationOrigin.DEFINED,
IrValueParameterSymbolImpl(),
arg.name,
arg.index,
type = context.irBuiltIns.anyNType,
varargElementType = null,
isCrossinline = arg.isCrossinline,
isNoinline = arg.isNoinline,
isHidden = arg.isHidden,
isAssignable = arg.isAssignable
)
}
val overriddenJobDescriptor = OverriddenFunctionInfo(jobFunction, runtimeJobFunction)
if (!overriddenJobDescriptor.needBridge) return expression
val bridge = context.buildBridge(
startOffset = job.startOffset,
endOffset = job.endOffset,
overriddenFunction = overriddenJobDescriptor,
targetSymbol = jobFunction.symbol)
bridges += bridge
expression.putValueArgument(3, IrFunctionReferenceImpl.fromSymbolDescriptor(
startOffset = job.startOffset,
endOffset = job.endOffset,
type = job.type,
symbol = bridge.symbol,
typeArgumentsCount = 0,
reflectionTarget = null)
)
return expression
}
})
return bridges
}
}
internal class BridgesBuilding(val context: Context) : ClassLoweringPass {
override fun lower(irClass: IrClass) {
val builtBridges = mutableSetOf<IrSimpleFunction>()
for (function in irClass.simpleFunctions()) {
val set = mutableSetOf<BridgeDirections>()
for (overriddenFunction in function.allOverriddenFunctions) {
val overriddenFunctionInfo = OverriddenFunctionInfo(function, overriddenFunction)
val bridgeDirections = overriddenFunctionInfo.bridgeDirections
if (!bridgeDirections.allNotNeeded() && overriddenFunctionInfo.canBeCalledVirtually
&& !overriddenFunctionInfo.inheritsBridge && set.add(bridgeDirections)) {
buildBridge(overriddenFunctionInfo, irClass)
builtBridges += function
}
}
}
irClass.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitClass(declaration: IrClass): IrStatement {
// Skip nested.
return declaration
}
override fun visitFunction(declaration: IrFunction): IrStatement {
declaration.transformChildrenVoid(this)
val body = declaration.body ?: return declaration
val descriptor = declaration.descriptor
val typeSafeBarrierDescription = BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(descriptor)
if (typeSafeBarrierDescription == null || builtBridges.contains(declaration))
return declaration
val irBuilder = context.createIrBuilder(declaration.symbol, declaration.startOffset, declaration.endOffset)
declaration.body = irBuilder.irBlockBody(declaration) {
buildTypeSafeBarrier(declaration, declaration, typeSafeBarrierDescription)
(body as IrBlockBody).statements.forEach { +it }
}
return declaration
}
})
}
private fun buildBridge(overriddenFunction: OverriddenFunctionInfo, irClass: IrClass) {
irClass.declarations.add(context.buildBridge(
startOffset = irClass.startOffset,
endOffset = irClass.endOffset,
overriddenFunction = overriddenFunction,
targetSymbol = overriddenFunction.function.symbol,
superQualifierSymbol = irClass.symbol)
)
}
}
internal class DECLARATION_ORIGIN_BRIDGE_METHOD(val bridgeTarget: IrFunction) : IrDeclarationOrigin {
override fun toString(): String {
return "BRIDGE_METHOD(target=${bridgeTarget.descriptor})"
}
}
internal val IrFunction.bridgeTarget: IrFunction?
get() = (origin as? DECLARATION_ORIGIN_BRIDGE_METHOD)?.bridgeTarget
private fun IrBuilderWithScope.returnIfBadType(value: IrExpression,
type: IrType,
returnValueOnFail: IrExpression)
= irIfThen(irNotIs(value, type), irReturn(returnValueOnFail))
private fun IrBuilderWithScope.irConst(value: Any?) = when (value) {
null -> irNull()
is Int -> irInt(value)
is Boolean -> if (value) irTrue() else irFalse()
else -> TODO()
}
private fun IrBlockBodyBuilder.buildTypeSafeBarrier(function: IrFunction,
originalFunction: IrFunction,
typeSafeBarrierDescription: SpecialGenericSignatures.TypeSafeBarrierDescription) {
val valueParameters = function.valueParameters
val originalValueParameters = originalFunction.valueParameters
for (i in valueParameters.indices) {
if (!typeSafeBarrierDescription.checkParameter(i))
continue
val type = originalValueParameters[i].type.erasureForTypeOperation()
// Note: erasing to single type is not entirely correct if type parameter has multiple upper bounds.
// In this case the compiler could generate multiple type checks, one for each upper bound.
// But let's keep it simple here for now; JVM backend doesn't do this anyway.
if (!type.isNullableAny()) {
+returnIfBadType(irGet(valueParameters[i]), type,
if (typeSafeBarrierDescription == SpecialGenericSignatures.TypeSafeBarrierDescription.MAP_GET_OR_DEFAULT)
irGet(valueParameters[2])
else irConst(typeSafeBarrierDescription.defaultValue)
)
}
}
}
private fun Context.buildBridge(startOffset: Int, endOffset: Int,
overriddenFunction: OverriddenFunctionInfo, targetSymbol: IrSimpleFunctionSymbol,
superQualifierSymbol: IrClassSymbol? = null): IrFunction {
val bridge = specialDeclarationsFactory.getBridge(overriddenFunction)
if (bridge.modality == Modality.ABSTRACT) {
return bridge
}
val irBuilder = createIrBuilder(bridge.symbol, startOffset, endOffset)
bridge.body = irBuilder.irBlockBody(bridge) {
val typeSafeBarrierDescription = BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(overriddenFunction.overriddenFunction.descriptor)
typeSafeBarrierDescription?.let { buildTypeSafeBarrier(bridge, overriddenFunction.function, it) }
val delegatingCall = IrCallImpl.fromSymbolDescriptor(
startOffset,
endOffset,
targetSymbol.owner.returnType,
targetSymbol,
typeArgumentsCount = targetSymbol.owner.typeParameters.size,
valueArgumentsCount = targetSymbol.owner.valueParameters.size,
superQualifierSymbol = superQualifierSymbol /* Call non-virtually */
).apply {
bridge.dispatchReceiverParameter?.let {
dispatchReceiver = irGet(it)
}
bridge.extensionReceiverParameter?.let {
extensionReceiver = irGet(it)
}
bridge.valueParameters.forEachIndexed { index, parameter ->
this.putValueArgument(index, irGet(parameter))
}
}
+irReturn(delegatingCall)
}
return bridge
}
|
apache-2.0
|
21b46abc347de6c73079d33c926dac19
| 46.318352 | 176 | 0.619251 | 5.85132 | false | false | false | false |
SimpleMobileTools/Simple-Calendar
|
app/src/main/kotlin/com/simplemobiletools/calendar/pro/activities/MainActivity.kt
|
1
|
55739
|
package com.simplemobiletools.calendar.pro.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.app.SearchManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Icon
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.ContactsContract.CommonDataKinds
import android.provider.ContactsContract.Contacts
import android.provider.ContactsContract.Data
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.core.view.MenuItemCompat
import com.simplemobiletools.calendar.pro.BuildConfig
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.adapters.EventListAdapter
import com.simplemobiletools.calendar.pro.adapters.QuickFilterEventTypeAdapter
import com.simplemobiletools.calendar.pro.databases.EventsDatabase
import com.simplemobiletools.calendar.pro.dialogs.ExportEventsDialog
import com.simplemobiletools.calendar.pro.dialogs.FilterEventTypesDialog
import com.simplemobiletools.calendar.pro.dialogs.ImportEventsDialog
import com.simplemobiletools.calendar.pro.dialogs.SetRemindersDialog
import com.simplemobiletools.calendar.pro.extensions.*
import com.simplemobiletools.calendar.pro.fragments.*
import com.simplemobiletools.calendar.pro.helpers.*
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.helpers.IcsExporter.ExportResult
import com.simplemobiletools.calendar.pro.helpers.IcsImporter.ImportResult
import com.simplemobiletools.calendar.pro.jobs.CalDAVUpdateListener
import com.simplemobiletools.calendar.pro.models.Event
import com.simplemobiletools.calendar.pro.models.ListEvent
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.Release
import com.simplemobiletools.commons.models.SimpleContact
import kotlinx.android.synthetic.main.activity_main.*
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.io.FileOutputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : SimpleActivity(), RefreshRecyclerViewListener {
private val PICK_IMPORT_SOURCE_INTENT = 1
private val PICK_EXPORT_FILE_INTENT = 2
private var showCalDAVRefreshToast = false
private var mShouldFilterBeVisible = false
private var mIsSearchOpen = false
private var mLatestSearchQuery = ""
private var mSearchMenuItem: MenuItem? = null
private var shouldGoToTodayBeVisible = false
private var goToTodayButton: MenuItem? = null
private var currentFragments = ArrayList<MyFragmentHolder>()
private var eventTypesToExport = ArrayList<Long>()
private var mStoredTextColor = 0
private var mStoredBackgroundColor = 0
private var mStoredPrimaryColor = 0
private var mStoredDayCode = ""
private var mStoredIsSundayFirst = false
private var mStoredMidnightSpan = true
private var mStoredUse24HourFormat = false
private var mStoredDimPastEvents = true
private var mStoredDimCompletedTasks = true
private var mStoredHighlightWeekends = false
private var mStoredStartWeekWithCurrentDay = false
private var mStoredHighlightWeekendsColor = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appLaunched(BuildConfig.APPLICATION_ID)
setupOptionsMenu()
refreshMenuItems()
checkWhatsNewDialog()
calendar_fab.beVisibleIf(config.storedView != YEARLY_VIEW && config.storedView != WEEKLY_VIEW)
calendar_fab.setOnClickListener {
if (config.allowCreatingTasks) {
if (fab_extended_overlay.isVisible()) {
openNewEvent()
Handler().postDelayed({
hideExtendedFab()
}, 300)
} else {
showExtendedFab()
}
} else {
openNewEvent()
}
}
fab_event_label.setOnClickListener { openNewEvent() }
fab_task_label.setOnClickListener { openNewTask() }
fab_extended_overlay.setOnClickListener {
hideExtendedFab()
}
fab_task_icon.setOnClickListener {
openNewTask()
Handler().postDelayed({
hideExtendedFab()
}, 300)
}
storeStateVariables()
if (!hasPermission(PERMISSION_WRITE_CALENDAR) || !hasPermission(PERMISSION_READ_CALENDAR)) {
config.caldavSync = false
}
if (config.caldavSync) {
refreshCalDAVCalendars(false)
}
swipe_refresh_layout.setOnRefreshListener {
refreshCalDAVCalendars(true)
}
checkIsViewIntent()
if (!checkIsOpenIntent()) {
updateViewPager()
}
checkAppOnSDCard()
if (savedInstanceState == null) {
checkCalDAVUpdateListener()
}
addBirthdaysAnniversariesAtStart()
if (!config.wasUpgradedFromFreeShown && isPackageInstalled("com.simplemobiletools.calendar")) {
ConfirmationDialog(this, "", R.string.upgraded_from_free, R.string.ok, 0, false) {}
config.wasUpgradedFromFreeShown = true
}
}
override fun onResume() {
super.onResume()
if (mStoredTextColor != getProperTextColor() || mStoredBackgroundColor != getProperBackgroundColor() || mStoredPrimaryColor != getProperPrimaryColor()
|| mStoredDayCode != Formatter.getTodayCode() || mStoredDimPastEvents != config.dimPastEvents || mStoredDimCompletedTasks != config.dimCompletedTasks
|| mStoredHighlightWeekends != config.highlightWeekends || mStoredHighlightWeekendsColor != config.highlightWeekendsColor
) {
updateViewPager()
}
eventsHelper.getEventTypes(this, false) {
val newShouldFilterBeVisible = it.size > 1 || config.displayEventTypes.isEmpty()
if (newShouldFilterBeVisible != mShouldFilterBeVisible) {
mShouldFilterBeVisible = newShouldFilterBeVisible
refreshMenuItems()
}
}
if (config.storedView == WEEKLY_VIEW) {
if (mStoredIsSundayFirst != config.isSundayFirst || mStoredUse24HourFormat != config.use24HourFormat
|| mStoredMidnightSpan != config.showMidnightSpanningEventsAtTop || mStoredStartWeekWithCurrentDay != config.startWeekWithCurrentDay
) {
updateViewPager()
}
}
storeStateVariables()
updateWidgets()
updateTextColors(calendar_coordinator)
fab_extended_overlay.background = ColorDrawable(getProperBackgroundColor().adjustAlpha(0.8f))
fab_event_label.setTextColor(getProperTextColor())
fab_task_label.setTextColor(getProperTextColor())
fab_task_icon.drawable.applyColorFilter(mStoredPrimaryColor.getContrastColor())
fab_task_icon.background.applyColorFilter(mStoredPrimaryColor)
search_holder.background = ColorDrawable(getProperBackgroundColor())
checkSwipeRefreshAvailability()
checkShortcuts()
setupToolbar(main_toolbar, searchMenuItem = mSearchMenuItem)
if (!mIsSearchOpen) {
refreshMenuItems()
}
setupQuickFilter()
main_toolbar.setNavigationOnClickListener {
onBackPressed()
}
if (config.caldavSync) {
updateCalDAVEvents()
}
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
EventsDatabase.destroyInstance()
stopCalDAVUpdateListener()
}
}
fun refreshMenuItems() {
if (fab_extended_overlay.isVisible()) {
hideExtendedFab()
}
shouldGoToTodayBeVisible = currentFragments.lastOrNull()?.shouldGoToTodayBeVisible() ?: false
main_toolbar.menu.apply {
goToTodayButton = findItem(R.id.go_to_today)
findItem(R.id.print).isVisible = config.storedView != MONTHLY_DAILY_VIEW
findItem(R.id.filter).isVisible = mShouldFilterBeVisible
findItem(R.id.go_to_today).isVisible = shouldGoToTodayBeVisible && !mIsSearchOpen
findItem(R.id.go_to_date).isVisible = config.storedView != EVENTS_LIST_VIEW
findItem(R.id.refresh_caldav_calendars).isVisible = config.caldavSync
findItem(R.id.more_apps_from_us).isVisible = !resources.getBoolean(R.bool.hide_google_relations)
}
}
private fun setupOptionsMenu() {
setupSearch(main_toolbar.menu)
main_toolbar.setOnMenuItemClickListener { menuItem ->
if (fab_extended_overlay.isVisible()) {
hideExtendedFab()
}
when (menuItem.itemId) {
R.id.change_view -> showViewDialog()
R.id.go_to_today -> goToToday()
R.id.go_to_date -> showGoToDateDialog()
R.id.print -> printView()
R.id.filter -> showFilterDialog()
R.id.refresh_caldav_calendars -> refreshCalDAVCalendars(true)
R.id.add_holidays -> addHolidays()
R.id.add_birthdays -> tryAddBirthdays()
R.id.add_anniversaries -> tryAddAnniversaries()
R.id.import_events -> tryImportEvents()
R.id.export_events -> tryExportEvents()
R.id.more_apps_from_us -> launchMoreAppsFromUsIntent()
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
override fun onBackPressed() {
if (mIsSearchOpen) {
closeSearch()
} else {
swipe_refresh_layout.isRefreshing = false
checkSwipeRefreshAvailability()
when {
fab_extended_overlay.isVisible() -> hideExtendedFab()
currentFragments.size > 1 -> removeTopFragment()
else -> super.onBackPressed()
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
checkIsOpenIntent()
checkIsViewIntent()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (requestCode == PICK_IMPORT_SOURCE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
tryImportEventsFromFile(resultData.data!!)
} else if (requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportEventsTo(eventTypesToExport, outputStream)
}
}
private fun storeStateVariables() {
mStoredTextColor = getProperTextColor()
mStoredPrimaryColor = getProperPrimaryColor()
mStoredBackgroundColor = getProperBackgroundColor()
config.apply {
mStoredIsSundayFirst = isSundayFirst
mStoredUse24HourFormat = use24HourFormat
mStoredDimPastEvents = dimPastEvents
mStoredDimCompletedTasks = dimCompletedTasks
mStoredHighlightWeekends = highlightWeekends
mStoredHighlightWeekendsColor = highlightWeekendsColor
mStoredMidnightSpan = showMidnightSpanningEventsAtTop
mStoredStartWeekWithCurrentDay = startWeekWithCurrentDay
}
mStoredDayCode = Formatter.getTodayCode()
}
private fun setupSearch(menu: Menu) {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
mSearchMenuItem = menu.findItem(R.id.search)
(mSearchMenuItem!!.actionView as SearchView).apply {
setSearchableInfo(searchManager.getSearchableInfo(componentName))
isSubmitButtonEnabled = false
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String) = false
override fun onQueryTextChange(newText: String): Boolean {
if (mIsSearchOpen) {
searchQueryChanged(newText)
}
return true
}
})
}
MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, object : MenuItemCompat.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
mIsSearchOpen = true
search_holder.beVisible()
calendar_fab.beGone()
searchQueryChanged("")
refreshMenuItems()
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
mIsSearchOpen = false
search_holder.beGone()
calendar_fab.beVisibleIf(currentFragments.last() !is YearFragmentsHolder && currentFragments.last() !is WeekFragmentsHolder)
refreshMenuItems()
return true
}
})
}
private fun setupQuickFilter() {
eventsHelper.getEventTypes(this, false) {
val quickFilterEventTypes = config.quickFilterEventTypes
quick_event_type_filter.adapter = QuickFilterEventTypeAdapter(this, it, quickFilterEventTypes) {
refreshViewPager()
updateWidgets()
}
}
}
private fun closeSearch() {
mSearchMenuItem?.collapseActionView()
}
private fun checkCalDAVUpdateListener() {
if (isNougatPlus()) {
val updateListener = CalDAVUpdateListener()
if (config.caldavSync) {
if (!updateListener.isScheduled(applicationContext)) {
updateListener.scheduleJob(applicationContext)
}
} else {
updateListener.cancelJob(applicationContext)
}
}
}
private fun stopCalDAVUpdateListener() {
if (isNougatPlus()) {
if (!config.caldavSync) {
val updateListener = CalDAVUpdateListener()
updateListener.cancelJob(applicationContext)
}
}
}
@SuppressLint("NewApi")
private fun checkShortcuts() {
val appIconColor = config.appIconColor
if (isNougatMR1Plus() && config.lastHandledShortcutColor != appIconColor) {
val newEvent = getNewEventShortcut(appIconColor)
val shortcuts = arrayListOf(newEvent)
if (config.allowCreatingTasks) {
shortcuts.add(getNewTaskShortcut(appIconColor))
}
try {
shortcutManager.dynamicShortcuts = shortcuts
config.lastHandledShortcutColor = appIconColor
} catch (ignored: Exception) {
}
}
}
@SuppressLint("NewApi")
private fun getNewEventShortcut(appIconColor: Int): ShortcutInfo {
val newEvent = getString(R.string.new_event)
val newEventDrawable = resources.getDrawable(R.drawable.shortcut_event, theme)
(newEventDrawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_event_background).applyColorFilter(appIconColor)
val newEventBitmap = newEventDrawable.convertToBitmap()
val newEventIntent = Intent(this, SplashActivity::class.java)
newEventIntent.action = SHORTCUT_NEW_EVENT
return ShortcutInfo.Builder(this, "new_event")
.setShortLabel(newEvent)
.setLongLabel(newEvent)
.setIcon(Icon.createWithBitmap(newEventBitmap))
.setIntent(newEventIntent)
.build()
}
@SuppressLint("NewApi")
private fun getNewTaskShortcut(appIconColor: Int): ShortcutInfo {
val newTask = getString(R.string.new_task)
val newTaskDrawable = resources.getDrawable(R.drawable.shortcut_task, theme)
(newTaskDrawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_task_background).applyColorFilter(appIconColor)
val newTaskBitmap = newTaskDrawable.convertToBitmap()
val newTaskIntent = Intent(this, SplashActivity::class.java)
newTaskIntent.action = SHORTCUT_NEW_TASK
return ShortcutInfo.Builder(this, "new_task")
.setShortLabel(newTask)
.setLongLabel(newTask)
.setIcon(Icon.createWithBitmap(newTaskBitmap))
.setIntent(newTaskIntent)
.build()
}
private fun checkIsOpenIntent(): Boolean {
val dayCodeToOpen = intent.getStringExtra(DAY_CODE) ?: ""
val viewToOpen = intent.getIntExtra(VIEW_TO_OPEN, DAILY_VIEW)
intent.removeExtra(VIEW_TO_OPEN)
intent.removeExtra(DAY_CODE)
if (dayCodeToOpen.isNotEmpty()) {
calendar_fab.beVisible()
if (viewToOpen != LAST_VIEW) {
config.storedView = viewToOpen
}
updateViewPager(dayCodeToOpen)
return true
}
val eventIdToOpen = intent.getLongExtra(EVENT_ID, 0L)
val eventOccurrenceToOpen = intent.getLongExtra(EVENT_OCCURRENCE_TS, 0L)
intent.removeExtra(EVENT_ID)
intent.removeExtra(EVENT_OCCURRENCE_TS)
if (eventIdToOpen != 0L && eventOccurrenceToOpen != 0L) {
hideKeyboard()
Intent(this, EventActivity::class.java).apply {
putExtra(EVENT_ID, eventIdToOpen)
putExtra(EVENT_OCCURRENCE_TS, eventOccurrenceToOpen)
startActivity(this)
}
}
return false
}
private fun checkIsViewIntent() {
if (intent?.action == Intent.ACTION_VIEW && intent.data != null) {
val uri = intent.data
if (uri?.authority?.equals("com.android.calendar") == true || uri?.authority?.substringAfter("@") == "com.android.calendar") {
if (uri.path!!.startsWith("/events")) {
ensureBackgroundThread {
// intents like content://com.android.calendar/events/1756
val eventId = uri.lastPathSegment
val id = eventsDB.getEventIdWithLastImportId("%-$eventId")
if (id != null) {
hideKeyboard()
Intent(this, EventActivity::class.java).apply {
putExtra(EVENT_ID, id)
startActivity(this)
}
} else {
toast(R.string.caldav_event_not_found, Toast.LENGTH_LONG)
}
}
} else if (uri.path!!.startsWith("/time") || intent?.extras?.getBoolean("DETAIL_VIEW", false) == true) {
// clicking date on a third party widget: content://com.android.calendar/time/1507309245683
// or content://[email protected]/time/1584958526435
val timestamp = uri.pathSegments.last()
if (timestamp.areDigitsOnly()) {
openDayAt(timestamp.toLong())
return
}
}
} else {
tryImportEventsFromFile(uri!!)
}
}
}
private fun showViewDialog() {
val items = arrayListOf(
RadioItem(DAILY_VIEW, getString(R.string.daily_view)),
RadioItem(WEEKLY_VIEW, getString(R.string.weekly_view)),
RadioItem(MONTHLY_VIEW, getString(R.string.monthly_view)),
RadioItem(MONTHLY_DAILY_VIEW, getString(R.string.monthly_daily_view)),
RadioItem(YEARLY_VIEW, getString(R.string.yearly_view)),
RadioItem(EVENTS_LIST_VIEW, getString(R.string.simple_event_list))
)
RadioGroupDialog(this, items, config.storedView) {
resetActionBarTitle()
closeSearch()
updateView(it as Int)
shouldGoToTodayBeVisible = false
refreshMenuItems()
}
}
private fun goToToday() {
currentFragments.last().goToToday()
}
fun showGoToDateDialog() {
currentFragments.last().showGoToDateDialog()
}
private fun printView() {
currentFragments.last().printView()
}
private fun resetActionBarTitle() {
main_toolbar.title = getString(R.string.app_launcher_name)
main_toolbar.subtitle = ""
}
fun updateTitle(text: String) {
main_toolbar.title = text
}
fun updateSubtitle(text: String) {
main_toolbar.subtitle = text
}
private fun showFilterDialog() {
FilterEventTypesDialog(this) {
refreshViewPager()
setupQuickFilter()
updateWidgets()
}
}
fun toggleGoToTodayVisibility(beVisible: Boolean) {
shouldGoToTodayBeVisible = beVisible
if (goToTodayButton?.isVisible != beVisible) {
refreshMenuItems()
}
}
private fun updateCalDAVEvents() {
ensureBackgroundThread {
calDAVHelper.refreshCalendars(showToasts = false, scheduleNextSync = true) {
refreshViewPager()
}
}
}
private fun refreshCalDAVCalendars(showRefreshToast: Boolean) {
showCalDAVRefreshToast = showRefreshToast
if (showRefreshToast) {
toast(R.string.refreshing)
}
updateCalDAVEvents()
syncCalDAVCalendars {
calDAVHelper.refreshCalendars(showToasts = true, scheduleNextSync = true) {
calDAVChanged()
}
}
}
private fun calDAVChanged() {
refreshViewPager()
if (showCalDAVRefreshToast) {
toast(R.string.refreshing_complete)
}
runOnUiThread {
swipe_refresh_layout.isRefreshing = false
}
}
private fun addHolidays() {
val items = getHolidayRadioItems()
RadioGroupDialog(this, items) { selectedHoliday ->
SetRemindersDialog(this, OTHER_EVENT) {
val reminders = it
toast(R.string.importing)
ensureBackgroundThread {
val holidays = getString(R.string.holidays)
var eventTypeId = eventsHelper.getEventTypeIdWithClass(HOLIDAY_EVENT)
if (eventTypeId == -1L) {
eventTypeId = eventsHelper.createPredefinedEventType(holidays, R.color.default_holidays_color, HOLIDAY_EVENT, true)
}
val result = IcsImporter(this).importEvents(selectedHoliday as String, eventTypeId, 0, false, reminders)
handleParseResult(result)
if (result != ImportResult.IMPORT_FAIL) {
runOnUiThread {
updateViewPager()
setupQuickFilter()
}
}
}
}
}
}
private fun tryAddBirthdays() {
handlePermission(PERMISSION_READ_CONTACTS) {
if (it) {
SetRemindersDialog(this, BIRTHDAY_EVENT) {
val reminders = it
val privateCursor = getMyContactsCursor(false, false)
ensureBackgroundThread {
val privateContacts = MyContactsContentProvider.getSimpleContacts(this, privateCursor)
addPrivateEvents(true, privateContacts, reminders) { eventsFound, eventsAdded ->
addContactEvents(true, reminders, eventsFound, eventsAdded) {
when {
it > 0 -> {
toast(R.string.birthdays_added)
updateViewPager()
setupQuickFilter()
}
it == -1 -> toast(R.string.no_new_birthdays)
else -> toast(R.string.no_birthdays)
}
}
}
}
}
} else {
toast(R.string.no_contacts_permission)
}
}
}
private fun tryAddAnniversaries() {
handlePermission(PERMISSION_READ_CONTACTS) {
if (it) {
SetRemindersDialog(this, ANNIVERSARY_EVENT) {
val reminders = it
val privateCursor = getMyContactsCursor(false, false)
ensureBackgroundThread {
val privateContacts = MyContactsContentProvider.getSimpleContacts(this, privateCursor)
addPrivateEvents(false, privateContacts, reminders) { eventsFound, eventsAdded ->
addContactEvents(false, reminders, eventsFound, eventsAdded) {
when {
it > 0 -> {
toast(R.string.anniversaries_added)
updateViewPager()
setupQuickFilter()
}
it == -1 -> toast(R.string.no_new_anniversaries)
else -> toast(R.string.no_anniversaries)
}
}
}
}
}
} else {
toast(R.string.no_contacts_permission)
}
}
}
private fun addBirthdaysAnniversariesAtStart() {
if ((!config.addBirthdaysAutomatically && !config.addAnniversariesAutomatically) || !hasPermission(PERMISSION_READ_CONTACTS)) {
return
}
val privateCursor = getMyContactsCursor(false, false)
ensureBackgroundThread {
val privateContacts = MyContactsContentProvider.getSimpleContacts(this, privateCursor)
if (config.addBirthdaysAutomatically) {
addPrivateEvents(true, privateContacts, config.birthdayReminders) { eventsFound, eventsAdded ->
addContactEvents(true, config.birthdayReminders, eventsFound, eventsAdded) {
if (it > 0) {
toast(R.string.birthdays_added)
updateViewPager()
setupQuickFilter()
}
}
}
}
if (config.addAnniversariesAutomatically) {
addPrivateEvents(false, privateContacts, config.anniversaryReminders) { eventsFound, eventsAdded ->
addContactEvents(false, config.anniversaryReminders, eventsFound, eventsAdded) {
if (it > 0) {
toast(R.string.anniversaries_added)
updateViewPager()
setupQuickFilter()
}
}
}
}
}
}
private fun handleParseResult(result: ImportResult) {
toast(
when (result) {
ImportResult.IMPORT_NOTHING_NEW -> R.string.no_new_items
ImportResult.IMPORT_OK -> R.string.holidays_imported_successfully
ImportResult.IMPORT_PARTIAL -> R.string.importing_some_holidays_failed
else -> R.string.importing_holidays_failed
}, Toast.LENGTH_LONG
)
}
private fun addContactEvents(birthdays: Boolean, reminders: ArrayList<Int>, initEventsFound: Int, initEventsAdded: Int, callback: (Int) -> Unit) {
var eventsFound = initEventsFound
var eventsAdded = initEventsAdded
val uri = Data.CONTENT_URI
val projection = arrayOf(
Contacts.DISPLAY_NAME,
CommonDataKinds.Event.CONTACT_ID,
CommonDataKinds.Event.CONTACT_LAST_UPDATED_TIMESTAMP,
CommonDataKinds.Event.START_DATE
)
val selection = "${Data.MIMETYPE} = ? AND ${CommonDataKinds.Event.TYPE} = ?"
val type = if (birthdays) CommonDataKinds.Event.TYPE_BIRTHDAY else CommonDataKinds.Event.TYPE_ANNIVERSARY
val selectionArgs = arrayOf(CommonDataKinds.Event.CONTENT_ITEM_TYPE, type.toString())
val dateFormats = getDateFormats()
val yearDateFormats = getDateFormatsWithYear()
val existingEvents = if (birthdays) eventsDB.getBirthdays() else eventsDB.getAnniversaries()
val importIDs = HashMap<String, Long>()
existingEvents.forEach {
importIDs[it.importId] = it.startTS
}
val eventTypeId = if (birthdays) eventsHelper.getLocalBirthdaysEventTypeId() else eventsHelper.getAnniversariesEventTypeId()
val source = if (birthdays) SOURCE_CONTACT_BIRTHDAY else SOURCE_CONTACT_ANNIVERSARY
queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val contactId = cursor.getIntValue(CommonDataKinds.Event.CONTACT_ID).toString()
val name = cursor.getStringValue(Contacts.DISPLAY_NAME)
val startDate = cursor.getStringValue(CommonDataKinds.Event.START_DATE)
for (format in dateFormats) {
try {
val formatter = SimpleDateFormat(format, Locale.getDefault())
val date = formatter.parse(startDate)
val flags = if (format in yearDateFormats) {
FLAG_ALL_DAY
} else {
FLAG_ALL_DAY or FLAG_MISSING_YEAR
}
val timestamp = date.time / 1000L
val lastUpdated = cursor.getLongValue(CommonDataKinds.Event.CONTACT_LAST_UPDATED_TIMESTAMP)
val event = Event(
null, timestamp, timestamp, name, reminder1Minutes = reminders[0], reminder2Minutes = reminders[1],
reminder3Minutes = reminders[2], importId = contactId, timeZone = DateTimeZone.getDefault().id, flags = flags,
repeatInterval = YEAR, repeatRule = REPEAT_SAME_DAY, eventType = eventTypeId, source = source, lastUpdated = lastUpdated
)
val importIDsToDelete = ArrayList<String>()
for ((key, value) in importIDs) {
if (key == contactId && value != timestamp) {
val deleted = eventsDB.deleteBirthdayAnniversary(source, key)
if (deleted == 1) {
importIDsToDelete.add(key)
}
}
}
importIDsToDelete.forEach {
importIDs.remove(it)
}
eventsFound++
if (!importIDs.containsKey(contactId)) {
eventsHelper.insertEvent(event, false, false) {
eventsAdded++
}
}
break
} catch (e: Exception) {
}
}
}
runOnUiThread {
callback(if (eventsAdded == 0 && eventsFound > 0) -1 else eventsAdded)
}
}
private fun addPrivateEvents(
birthdays: Boolean,
contacts: ArrayList<SimpleContact>,
reminders: ArrayList<Int>,
callback: (eventsFound: Int, eventsAdded: Int) -> Unit
) {
var eventsAdded = 0
var eventsFound = 0
if (contacts.isEmpty()) {
callback(0, 0)
return
}
try {
val eventTypeId = if (birthdays) eventsHelper.getLocalBirthdaysEventTypeId() else eventsHelper.getAnniversariesEventTypeId()
val source = if (birthdays) SOURCE_CONTACT_BIRTHDAY else SOURCE_CONTACT_ANNIVERSARY
val existingEvents = if (birthdays) eventsDB.getBirthdays() else eventsDB.getAnniversaries()
val importIDs = HashMap<String, Long>()
existingEvents.forEach {
importIDs[it.importId] = it.startTS
}
contacts.forEach { contact ->
val events = if (birthdays) contact.birthdays else contact.anniversaries
events.forEach { birthdayAnniversary ->
// private contacts are created in Simple Contacts Pro, so we can guarantee that they exist only in these 2 formats
val format = if (birthdayAnniversary.startsWith("--")) {
"--MM-dd"
} else {
"yyyy-MM-dd"
}
val formatter = SimpleDateFormat(format, Locale.getDefault())
val date = formatter.parse(birthdayAnniversary)
if (date.year < 70) {
date.year = 70
}
val timestamp = date.time / 1000L
val lastUpdated = System.currentTimeMillis()
val event = Event(
null, timestamp, timestamp, contact.name, reminder1Minutes = reminders[0], reminder2Minutes = reminders[1],
reminder3Minutes = reminders[2], importId = contact.contactId.toString(), timeZone = DateTimeZone.getDefault().id, flags = FLAG_ALL_DAY,
repeatInterval = YEAR, repeatRule = REPEAT_SAME_DAY, eventType = eventTypeId, source = source, lastUpdated = lastUpdated
)
val importIDsToDelete = ArrayList<String>()
for ((key, value) in importIDs) {
if (key == contact.contactId.toString() && value != timestamp) {
val deleted = eventsDB.deleteBirthdayAnniversary(source, key)
if (deleted == 1) {
importIDsToDelete.add(key)
}
}
}
importIDsToDelete.forEach {
importIDs.remove(it)
}
eventsFound++
if (!importIDs.containsKey(contact.contactId.toString())) {
eventsHelper.insertEvent(event, false, false) {
eventsAdded++
}
}
}
}
} catch (e: Exception) {
showErrorToast(e)
}
callback(eventsFound, eventsAdded)
}
private fun updateView(view: Int) {
calendar_fab.beVisibleIf(view != YEARLY_VIEW && view != WEEKLY_VIEW)
val dateCode = getDateCodeToDisplay(view)
config.storedView = view
checkSwipeRefreshAvailability()
updateViewPager(dateCode)
if (goToTodayButton?.isVisible == true) {
shouldGoToTodayBeVisible = false
refreshMenuItems()
}
}
private fun getDateCodeToDisplay(newView: Int): String? {
val fragment = currentFragments.last()
val currentView = fragment.viewType
if (newView == EVENTS_LIST_VIEW || currentView == EVENTS_LIST_VIEW) {
return null
}
val fragmentDate = fragment.getCurrentDate()
val viewOrder = arrayListOf(DAILY_VIEW, WEEKLY_VIEW, MONTHLY_VIEW, YEARLY_VIEW)
val currentViewIndex = viewOrder.indexOf(if (currentView == MONTHLY_DAILY_VIEW) MONTHLY_VIEW else currentView)
val newViewIndex = viewOrder.indexOf(if (newView == MONTHLY_DAILY_VIEW) MONTHLY_VIEW else newView)
return if (fragmentDate != null && currentViewIndex <= newViewIndex) {
getDateCodeFormatForView(newView, fragmentDate)
} else {
getDateCodeFormatForView(newView, DateTime())
}
}
private fun getDateCodeFormatForView(view: Int, date: DateTime): String {
return when (view) {
WEEKLY_VIEW -> getDatesWeekDateTime(date)
YEARLY_VIEW -> date.toString()
else -> Formatter.getDayCodeFromDateTime(date)
}
}
private fun updateViewPager(dayCode: String? = null) {
val fragment = getFragmentsHolder()
currentFragments.forEach {
try {
supportFragmentManager.beginTransaction().remove(it).commitNow()
} catch (ignored: Exception) {
return
}
}
currentFragments.clear()
currentFragments.add(fragment)
val bundle = Bundle()
val fixedDayCode = fixDayCode(dayCode)
when (config.storedView) {
DAILY_VIEW -> bundle.putString(DAY_CODE, fixedDayCode ?: Formatter.getTodayCode())
WEEKLY_VIEW -> bundle.putString(WEEK_START_DATE_TIME, fixedDayCode ?: getDatesWeekDateTime(DateTime()))
MONTHLY_VIEW, MONTHLY_DAILY_VIEW -> bundle.putString(DAY_CODE, fixedDayCode ?: Formatter.getTodayCode())
YEARLY_VIEW -> bundle.putString(YEAR_TO_OPEN, fixedDayCode)
}
fragment.arguments = bundle
supportFragmentManager.beginTransaction().add(R.id.fragments_holder, fragment).commitNow()
main_toolbar.navigationIcon = null
}
private fun fixDayCode(dayCode: String? = null): String? = when {
config.storedView == WEEKLY_VIEW && (dayCode?.length == Formatter.DAYCODE_PATTERN.length) -> getDatesWeekDateTime(Formatter.getDateTimeFromCode(dayCode))
config.storedView == YEARLY_VIEW && (dayCode?.length == Formatter.DAYCODE_PATTERN.length) -> Formatter.getYearFromDayCode(dayCode)
else -> dayCode
}
private fun showExtendedFab() {
animateFabIcon(false)
arrayOf(fab_event_label, fab_extended_overlay, fab_task_icon, fab_task_label).forEach {
it.fadeIn()
}
}
private fun hideExtendedFab() {
animateFabIcon(true)
arrayOf(fab_event_label, fab_extended_overlay, fab_task_icon, fab_task_label).forEach {
it.fadeOut()
}
}
private fun animateFabIcon(showPlus: Boolean) {
val newDrawableId = if (showPlus) {
R.drawable.ic_plus_vector
} else {
R.drawable.ic_today_vector
}
val newDrawable = resources.getColoredDrawableWithColor(newDrawableId, getProperPrimaryColor())
calendar_fab.setImageDrawable(newDrawable)
}
private fun openNewEvent() {
hideKeyboard()
val lastFragment = currentFragments.last()
val allowChangingDay = lastFragment !is DayFragmentsHolder && lastFragment !is MonthDayFragmentsHolder
launchNewEventIntent(lastFragment.getNewEventDayCode(), allowChangingDay)
}
private fun openNewTask() {
hideKeyboard()
val lastFragment = currentFragments.last()
val allowChangingDay = lastFragment !is DayFragmentsHolder && lastFragment !is MonthDayFragmentsHolder
launchNewTaskIntent(lastFragment.getNewEventDayCode(), allowChangingDay)
}
fun openMonthFromYearly(dateTime: DateTime) {
if (currentFragments.last() is MonthFragmentsHolder) {
return
}
val fragment = MonthFragmentsHolder()
currentFragments.add(fragment)
val bundle = Bundle()
bundle.putString(DAY_CODE, Formatter.getDayCodeFromDateTime(dateTime))
fragment.arguments = bundle
supportFragmentManager.beginTransaction().add(R.id.fragments_holder, fragment).commitNow()
resetActionBarTitle()
calendar_fab.beVisible()
showBackNavigationArrow()
}
fun openDayFromMonthly(dateTime: DateTime) {
if (currentFragments.last() is DayFragmentsHolder) {
return
}
val fragment = DayFragmentsHolder()
currentFragments.add(fragment)
val bundle = Bundle()
bundle.putString(DAY_CODE, Formatter.getDayCodeFromDateTime(dateTime))
fragment.arguments = bundle
try {
supportFragmentManager.beginTransaction().add(R.id.fragments_holder, fragment).commitNow()
showBackNavigationArrow()
} catch (e: Exception) {
}
}
private fun getFragmentsHolder() = when (config.storedView) {
DAILY_VIEW -> DayFragmentsHolder()
MONTHLY_VIEW -> MonthFragmentsHolder()
MONTHLY_DAILY_VIEW -> MonthDayFragmentsHolder()
YEARLY_VIEW -> YearFragmentsHolder()
EVENTS_LIST_VIEW -> EventListFragment()
else -> WeekFragmentsHolder()
}
private fun removeTopFragment() {
supportFragmentManager.beginTransaction().remove(currentFragments.last()).commit()
currentFragments.removeAt(currentFragments.size - 1)
toggleGoToTodayVisibility(currentFragments.last().shouldGoToTodayBeVisible())
currentFragments.last().apply {
refreshEvents()
updateActionBarTitle()
}
calendar_fab.beGoneIf(currentFragments.size == 1 && config.storedView == YEARLY_VIEW)
if (currentFragments.size > 1) {
showBackNavigationArrow()
} else {
main_toolbar.navigationIcon = null
}
}
private fun showBackNavigationArrow() {
main_toolbar.navigationIcon = resources.getColoredDrawableWithColor(R.drawable.ic_arrow_left_vector, getProperStatusBarColor().getContrastColor())
}
private fun refreshViewPager() {
runOnUiThread {
if (!isDestroyed) {
currentFragments.last().refreshEvents()
}
}
}
private fun tryImportEvents() {
if (isQPlus()) {
handleNotificationPermission { granted ->
if (granted) {
hideKeyboard()
Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "text/calendar"
try {
startActivityForResult(this, PICK_IMPORT_SOURCE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
toast(R.string.no_post_notifications_permissions)
}
}
} else {
handlePermission(PERMISSION_READ_STORAGE) {
if (it) {
importEvents()
}
}
}
}
private fun importEvents() {
FilePickerDialog(this) {
showImportEventsDialog(it)
}
}
private fun tryImportEventsFromFile(uri: Uri) {
when {
uri.scheme == "file" -> showImportEventsDialog(uri.path!!)
uri.scheme == "content" -> {
val tempFile = getTempFile()
if (tempFile == null) {
toast(R.string.unknown_error_occurred)
return
}
try {
val inputStream = contentResolver.openInputStream(uri)
val out = FileOutputStream(tempFile)
inputStream!!.copyTo(out)
showImportEventsDialog(tempFile.absolutePath)
} catch (e: Exception) {
showErrorToast(e)
}
}
else -> toast(R.string.invalid_file_format)
}
}
private fun showImportEventsDialog(path: String) {
ImportEventsDialog(this, path) {
if (it) {
runOnUiThread {
updateViewPager()
setupQuickFilter()
}
}
}
}
private fun tryExportEvents() {
if (isQPlus()) {
ExportEventsDialog(this, config.lastExportPath, true) { file, eventTypes ->
eventTypesToExport = eventTypes
hideKeyboard()
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/calendar"
putExtra(Intent.EXTRA_TITLE, file.name)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, PICK_EXPORT_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
ExportEventsDialog(this, config.lastExportPath, false) { file, eventTypes ->
getFileOutputStream(file.toFileDirItem(this), true) {
exportEventsTo(eventTypes, it)
}
}
}
}
}
}
private fun exportEventsTo(eventTypes: ArrayList<Long>, outputStream: OutputStream?) {
ensureBackgroundThread {
val events = eventsHelper.getEventsToExport(eventTypes)
if (events.isEmpty()) {
toast(R.string.no_entries_for_exporting)
} else {
IcsExporter().exportEvents(this, outputStream, events, true) {
toast(
when (it) {
ExportResult.EXPORT_OK -> R.string.exporting_successful
ExportResult.EXPORT_PARTIAL -> R.string.exporting_some_entries_failed
else -> R.string.exporting_failed
}
)
}
}
}
}
private fun launchSettings() {
hideKeyboard()
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
private fun launchAbout() {
val licenses = LICENSE_JODA
val faqItems = arrayListOf(
FAQItem("${getString(R.string.faq_2_title)} ${getString(R.string.faq_2_title_extra)}", R.string.faq_2_text),
FAQItem(R.string.faq_5_title, R.string.faq_5_text),
FAQItem(R.string.faq_3_title, R.string.faq_3_text),
FAQItem(R.string.faq_6_title, R.string.faq_6_text),
FAQItem(R.string.faq_1_title, R.string.faq_1_text),
FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons),
FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons),
FAQItem(R.string.faq_4_title, R.string.faq_4_text)
)
if (!resources.getBoolean(R.bool.hide_google_relations)) {
faqItems.add(FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons))
faqItems.add(FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons))
faqItems.add(FAQItem(R.string.faq_7_title_commons, R.string.faq_7_text_commons))
}
startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true)
}
private fun searchQueryChanged(text: String) {
mLatestSearchQuery = text
search_placeholder_2.beGoneIf(text.length >= 2)
if (text.length >= 2) {
eventsHelper.getEventsWithSearchQuery(text, this) { searchedText, events ->
if (searchedText == mLatestSearchQuery) {
search_results_list.beVisibleIf(events.isNotEmpty())
search_placeholder.beVisibleIf(events.isEmpty())
val listItems = getEventListItems(events)
val eventsAdapter = EventListAdapter(this, listItems, true, this, search_results_list) {
hideKeyboard()
if (it is ListEvent) {
Intent(applicationContext, getActivityToOpen(it.isTask)).apply {
putExtra(EVENT_ID, it.id)
startActivity(this)
}
}
}
search_results_list.adapter = eventsAdapter
}
}
} else {
search_placeholder.beVisible()
search_results_list.beGone()
}
}
private fun checkSwipeRefreshAvailability() {
swipe_refresh_layout.isEnabled = config.caldavSync && config.pullToRefresh && config.storedView != WEEKLY_VIEW
if (!swipe_refresh_layout.isEnabled) {
swipe_refresh_layout.isRefreshing = false
}
}
// only used at active search
override fun refreshItems() {
searchQueryChanged(mLatestSearchQuery)
refreshViewPager()
}
private fun openDayAt(timestamp: Long) {
val dayCode = Formatter.getDayCodeFromTS(timestamp / 1000L)
calendar_fab.beVisible()
config.storedView = DAILY_VIEW
updateViewPager(dayCode)
}
// events fetched from Thunderbird, https://www.thunderbird.net/en-US/calendar/holidays and
// https://holidays.kayaposoft.com/public_holidays.php?year=2021
private fun getHolidayRadioItems(): ArrayList<RadioItem> {
val items = ArrayList<RadioItem>()
LinkedHashMap<String, String>().apply {
put("Algeria", "algeria.ics")
put("Argentina", "argentina.ics")
put("Australia", "australia.ics")
put("België", "belgium.ics")
put("Bolivia", "bolivia.ics")
put("Brasil", "brazil.ics")
put("България", "bulgaria.ics")
put("Canada", "canada.ics")
put("China", "china.ics")
put("Colombia", "colombia.ics")
put("Česká republika", "czech.ics")
put("Danmark", "denmark.ics")
put("Deutschland", "germany.ics")
put("Eesti", "estonia.ics")
put("España", "spain.ics")
put("Éire", "ireland.ics")
put("France", "france.ics")
put("Fürstentum Liechtenstein", "liechtenstein.ics")
put("Hellas", "greece.ics")
put("Hrvatska", "croatia.ics")
put("India", "india.ics")
put("Indonesia", "indonesia.ics")
put("Ísland", "iceland.ics")
put("Israel", "israel.ics")
put("Italia", "italy.ics")
put("Қазақстан Республикасы", "kazakhstan.ics")
put("المملكة المغربية", "morocco.ics")
put("Latvija", "latvia.ics")
put("Lietuva", "lithuania.ics")
put("Luxemburg", "luxembourg.ics")
put("Makedonija", "macedonia.ics")
put("Malaysia", "malaysia.ics")
put("Magyarország", "hungary.ics")
put("México", "mexico.ics")
put("Nederland", "netherlands.ics")
put("República de Nicaragua", "nicaragua.ics")
put("日本", "japan.ics")
put("Nigeria", "nigeria.ics")
put("Norge", "norway.ics")
put("Österreich", "austria.ics")
put("Pākistān", "pakistan.ics")
put("Polska", "poland.ics")
put("Portugal", "portugal.ics")
put("Россия", "russia.ics")
put("República de Costa Rica", "costarica.ics")
put("República Oriental del Uruguay", "uruguay.ics")
put("République d'Haïti", "haiti.ics")
put("România", "romania.ics")
put("Schweiz", "switzerland.ics")
put("Singapore", "singapore.ics")
put("한국", "southkorea.ics")
put("Srbija", "serbia.ics")
put("Slovenija", "slovenia.ics")
put("Slovensko", "slovakia.ics")
put("South Africa", "southafrica.ics")
put("Sri Lanka", "srilanka.ics")
put("Suomi", "finland.ics")
put("Sverige", "sweden.ics")
put("Taiwan", "taiwan.ics")
put("ราชอาณาจักรไทย", "thailand.ics")
put("Türkiye Cumhuriyeti", "turkey.ics")
put("Ukraine", "ukraine.ics")
put("United Kingdom", "unitedkingdom.ics")
put("United States", "unitedstates.ics")
var i = 0
for ((country, file) in this) {
items.add(RadioItem(i++, country, file))
}
}
return items
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().apply {
add(Release(39, R.string.release_39))
add(Release(40, R.string.release_40))
add(Release(42, R.string.release_42))
add(Release(44, R.string.release_44))
add(Release(46, R.string.release_46))
add(Release(48, R.string.release_48))
add(Release(49, R.string.release_49))
add(Release(51, R.string.release_51))
add(Release(52, R.string.release_52))
add(Release(54, R.string.release_54))
add(Release(57, R.string.release_57))
add(Release(59, R.string.release_59))
add(Release(60, R.string.release_60))
add(Release(62, R.string.release_62))
add(Release(67, R.string.release_67))
add(Release(69, R.string.release_69))
add(Release(71, R.string.release_71))
add(Release(73, R.string.release_73))
add(Release(76, R.string.release_76))
add(Release(77, R.string.release_77))
add(Release(80, R.string.release_80))
add(Release(84, R.string.release_84))
add(Release(86, R.string.release_86))
add(Release(88, R.string.release_88))
add(Release(98, R.string.release_98))
add(Release(117, R.string.release_117))
add(Release(119, R.string.release_119))
add(Release(129, R.string.release_129))
add(Release(143, R.string.release_143))
add(Release(155, R.string.release_155))
add(Release(167, R.string.release_167))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
}
|
gpl-3.0
|
a0a260ccbb417b92e0b4b0419eedb6c3
| 39.227043 | 161 | 0.581012 | 4.825989 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.