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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mike-neck/kuickcheck
|
core/src/main/kotlin/org/mikeneck/kuickcheck/generator/ByteGenerator.kt
|
1
|
1620
|
/*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.generator
import org.mikeneck.kuickcheck.Generator
import org.mikeneck.kuickcheck.random.RandomSource
internal class ByteGenerator(val min: Byte = Byte.MIN_VALUE, val max: Byte = Byte.MAX_VALUE) : Generator<Byte> {
init {
if (max < min) throw IllegalArgumentException("Max should be larger than min.[max: $max, min: $min]")
}
override fun invoke(): Byte = RandomSource.nextByte(min, max)
}
internal class IntBasedByteGenerator(val min: Int = MIN, val max: Int = MAX) : Generator<Byte> {
init {
if (max < min) throw IllegalArgumentException("Max should be larger than min. [max: $max, min: $min]")
if (min < MIN) throw IllegalArgumentException("Min should be larger than 0. [min: $min]")
if (max > MAX) throw IllegalArgumentException("Max should be smaller than 128. [max: $max]")
}
override fun invoke(): Byte = RandomSource.nextInt(min, max).toByte()
companion object {
val MIN: Int = 0
val MAX: Int = 255
}
}
|
apache-2.0
|
94b81f4042a2ec3f690161b98e044298
| 35.818182 | 112 | 0.701852 | 3.980344 | false | false | false | false |
GLodi/GitNav
|
app/src/main/java/giuliolodi/gitnav/data/api/ApiHelperImpl.kt
|
1
|
20880
|
/*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.data.api
import android.content.Context
import android.os.Build
import android.os.StrictMode
import android.util.Base64
import giuliolodi.gitnav.data.model.RequestAccessTokenResponse
import giuliolodi.gitnav.di.scope.AppContext
import giuliolodi.gitnav.di.scope.UrlInfo
import io.reactivex.BackpressureStrategy
import io.reactivex.Completable
import io.reactivex.Flowable
import org.eclipse.egit.github.core.*
import org.eclipse.egit.github.core.event.Event
import org.eclipse.egit.github.core.service.*
import javax.inject.Inject
import java.io.IOException
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import retrofit2.Retrofit
import java.io.UnsupportedEncodingException
/**
* Created by giulio on 12/05/2017.
*/
class ApiHelperImpl : ApiHelper {
private val mContext: Context
private val mUrlMap: Map<String,String>
private val mRetrofit: Retrofit
@Inject
constructor(@AppContext context: Context, @UrlInfo urlMap: Map<String,String>, retrofit: Retrofit) {
mContext = context
mUrlMap = urlMap
mRetrofit = retrofit
}
override fun apiAuthToGitHub(username: String, password: String): String {
val oAuthService: OAuthService = OAuthService()
oAuthService.client.setCredentials(username, password)
// This will set the token parameters and its permissions
var auth = Authorization()
auth.scopes = arrayListOf("repo", "gist", "user")
val description = "GitNav - " + Build.MANUFACTURER + " " + Build.MODEL
auth.note = description
// Required for some reason
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
// Check if token already exists and deletes it.
try {
for (authorization in oAuthService.authorizations) {
if (authorization.note == description) {
oAuthService.deleteAuthorization(authorization.id)
}
}
} catch (e: IOException) {
e.printStackTrace()
throw e
}
// Create authorization
try {
auth = oAuthService.createAuthorization(auth)
return auth.token
} catch (e: IOException) {
e.printStackTrace()
throw e
}
}
override fun apiGetUser(token: String, username: String): Flowable<User> {
return Flowable.defer {
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
Flowable.just(userService.getUser(username))
}
}
override fun apiPageEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> {
return Flowable.defer {
val eventService: EventService = EventService()
eventService.client.setOAuth2Token(token)
Flowable.just(ArrayList(eventService.pageUserReceivedEvents(username, false, pageN, itemsPerPage).next()))
}
}
override fun apiPageUserEvents(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Event>> {
return Flowable.defer {
val eventService: EventService = EventService()
eventService.client.setOAuth2Token(token)
Flowable.just(ArrayList(eventService.pageUserEvents(username, false, pageN, itemsPerPage).next()))
}
}
override fun apiGetTrending(token: String, period: String): Flowable<Repository> {
return Flowable.create({ emitter ->
var URL: String = ""
val ownerRepoList: MutableList<String> = mutableListOf()
when (period) {
"daily" -> URL = mUrlMap["base"] + mUrlMap["daily"]
"weekly" -> URL = mUrlMap["base"] + mUrlMap["weekly"]
"monthly" -> URL = mUrlMap["base"] + mUrlMap["monthly"]
}
try {
val document = Jsoup.connect(URL).get()
val repoList = document.getElementsByTag("ol")[0].getElementsByTag("li")
if (repoList != null && !repoList.isEmpty()) {
var string: Element
var ss: String
for (i in 0..repoList.size - 1) {
string = repoList[i].getElementsByTag("div")[0].getElementsByTag("h3")[0].getElementsByTag("a")[0]
ss = string.children()[0].ownText() + string.ownText()
val t = ss.split("/")
val a = t[0].replace(" ", "")
val b = t[1]
ownerRepoList.add(a)
ownerRepoList.add(b)
}
val repositoryService: RepositoryService = RepositoryService()
repositoryService.client.setOAuth2Token(token)
for (i in 0..ownerRepoList.size - 1 step 2) {
emitter.onNext(repositoryService.getRepository(ownerRepoList[i], ownerRepoList[i+1]))
}
emitter.onComplete()
}
} catch (e: Exception) {
if (!emitter.isCancelled)
emitter.onError(e)
}
}, BackpressureStrategy.BUFFER)
}
override fun apiPageRepos(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> {
return Flowable.defer {
val repositoryService: RepositoryService = RepositoryService()
repositoryService.client.setOAuth2Token(token)
when (filter?.get("sort")) {
"stars" -> Flowable.just(repositoryService.getRepositories(username).sortedByDescending { it.watchers })
else -> Flowable.just(ArrayList(repositoryService.pageRepositories(username, filter, pageN, itemsPerPage).next()))
}
}
}
override fun apiPageStarred(token: String, username: String, pageN: Int, itemsPerPage: Int, filter: HashMap<String, String>?): Flowable<List<Repository>> {
return Flowable.defer {
val starService: StarService = StarService()
starService.client.setOAuth2Token(token)
when (filter?.get("sort")) {
"stars" -> Flowable.just(starService.getStarred(username).sortedByDescending { it.watchers })
"pushed" -> Flowable.just(starService.getStarred(username).sortedByDescending { it.pushedAt })
"updated" -> Flowable.just(starService.getStarred(username).sortedByDescending { it.updatedAt })
"alphabetical" -> Flowable.just(starService.getStarred(username).sortedBy { it.name })
else -> Flowable.just(ArrayList(starService.pageStarred(username, filter, pageN, itemsPerPage).next()))
}
}
}
override fun apiGetFollowed(token: String, username: String): Flowable<String> {
return Flowable.defer {
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
if (userService.isFollowing(username))
Flowable.just("f")
else
Flowable.just("n")
}
}
override fun apiGetFollowers(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> {
return Flowable.defer {
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
Flowable.just(ArrayList(userService.pageFollowers(username, pageN, itemsPerPage).next()))
}
}
override fun apiGetFollowing(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<User>> {
return Flowable.defer {
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
Flowable.just(ArrayList(userService.pageFollowing(username, pageN, itemsPerPage).next()))
}
}
override fun apiFollowUser(token: String, username: String): Completable {
return Completable.create { subscriber ->
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
try {
userService.follow(username)
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiUnfollowUser(token: String, username: String): Completable {
return Completable.create { subscriber ->
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
try {
userService.unfollow(username)
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiPageGists(token: String, username: String?, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> {
return Flowable.defer {
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
Flowable.just(ArrayList(gistService.pageGists(username, pageN, itemsPerPage).next()))
}
}
override fun apiPageStarredGists(token: String, pageN: Int, itemsPerPage: Int): Flowable<List<Gist>> {
return Flowable.defer {
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
Flowable.just(ArrayList(gistService.pageStarredGists(pageN, itemsPerPage).next()))
}
}
override fun apiGetGist(token: String, gistId: String): Flowable<Gist> {
return Flowable.defer {
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
Flowable.just(gistService.getGist(gistId))
}
}
override fun apiGetGistComments(token: String, gistId: String): Flowable<List<Comment>> {
return Flowable.defer {
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
Flowable.just(gistService.getComments(gistId))
}
}
override fun apiStarGist(token: String, gistId: String): Completable {
return Completable.create { subscriber ->
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
try {
gistService.starGist(gistId)
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiUnstarGist(token: String, gistId: String): Completable {
return Completable.create { subscriber ->
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
try {
gistService.unstarGist(gistId)
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiIsGistStarred(token: String, gistId: String): Flowable<Boolean> {
return Flowable.defer {
val gistService: GistService = GistService()
gistService.client.setOAuth2Token(token)
Flowable.just(gistService.isStarred(gistId))
}
}
override fun apiSearchRepos(token: String, query: String, filter: HashMap<String,String>): Flowable<List<Repository>> {
return Flowable.defer {
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
when (filter["sort"]) {
"stars" -> Flowable.just(repoService.searchRepositories(query).sortedByDescending { it.watchers })
"pushed" -> Flowable.just(repoService.searchRepositories(query).sortedByDescending { it.pushedAt })
"updated" -> Flowable.just(repoService.searchRepositories(query).sortedByDescending { it.updatedAt })
"full_name" -> Flowable.just(repoService.searchRepositories(query).sortedBy { it.name })
else -> Flowable.just(repoService.searchRepositories(query))
}
}
}
override fun apiSearchUsers(token: String, query: String, filter: HashMap<String,String>): Flowable<List<SearchUser>> {
return Flowable.defer {
val userService: UserService = UserService()
userService.client.setOAuth2Token(token)
when (filter["sort"]) {
"repos" -> Flowable.just(userService.searchUsers(query).sortedByDescending { it.publicRepos })
"followers" -> Flowable.just(userService.searchUsers(query).sortedByDescending { it.followers })
else -> Flowable.just(userService.searchUsers(query))
}
}
}
override fun apiSearchCode(token: String, query: String): Flowable<List<CodeSearchResult>> {
return Flowable.defer {
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
Flowable.just(repoService.searchCode(query))
}
}
override fun apiIsRepoStarred(token: String, owner: String, name: String): Flowable<Boolean> {
return Flowable.defer {
val starService: StarService = StarService()
starService.client.setOAuth2Token(token)
Flowable.just(starService.isStarring(RepositoryId(owner, name)))
}
}
override fun apiGetRepo(token: String, owner: String, name: String): Flowable<Repository> {
return Flowable.defer {
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
Flowable.just(repoService.getRepository(RepositoryId(owner, name)))
}
}
override fun apiStarRepo(token: String, owner: String, name: String): Completable {
return Completable.create { subscriber ->
val starService: StarService = StarService()
starService.client.setOAuth2Token(token)
try {
starService.star(RepositoryId(owner, name))
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiUnstarRepo(token: String, owner: String, name: String): Completable {
return Completable.create { subscriber ->
val starService: StarService = StarService()
starService.client.setOAuth2Token(token)
try {
starService.unstar(RepositoryId(owner, name))
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiGetReadme(token: String, owner: String, name: String): Flowable<String> {
return Flowable.create({ emitter ->
val contentsService: ContentsService = ContentsService()
contentsService.client.setOAuth2Token(token)
val markdown64: String = contentsService.getReadme(RepositoryId(owner, name)).content
try {
val markdown: String = String(Base64.decode(markdown64, Base64.DEFAULT))
emitter.onNext(markdown)
} catch (e: UnsupportedEncodingException) {
emitter.onError(e)
}
}, BackpressureStrategy.BUFFER)
}
override fun apiGetRepoCommits(token: String, owner: String, name: String): Flowable<List<RepositoryCommit>> {
return Flowable.defer {
val commitService: CommitService = CommitService()
commitService.client.setOAuth2Token(token)
Flowable.just(commitService.getCommits(RepositoryId(owner, name)))
}
}
override fun apiGetContributors(token: String, owner: String, name: String): Flowable<List<Contributor>> {
return Flowable.defer {
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
Flowable.just(repoService.getContributors(RepositoryId(owner, name), true))
}
}
override fun apiGetContent(token: String, owner: String, name: String, path: String): Flowable<List<RepositoryContents>> {
return Flowable.defer {
val contentsService: ContentsService = ContentsService()
contentsService.client.setOAuth2Token(token)
Flowable.just(contentsService.getContents(RepositoryId(owner, name), path))
}
}
override fun apiPageStargazers(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<User>> {
return Flowable.defer {
val stargazerService: StargazerService = StargazerService()
stargazerService.client.setOAuth2Token(token)
Flowable.just(stargazerService.pageStargazers(RepositoryId(owner, name), pageN, itemsPerPage).next().toMutableList())
}
}
override fun apiPageIssues(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int, hashMap: HashMap<String,String>): Flowable<List<Issue>> {
return Flowable.defer {
val issueService: IssueService = IssueService()
issueService.client.setOAuth2Token(token)
Flowable.just(issueService.pageIssues(RepositoryId(owner, name), hashMap, pageN, itemsPerPage).next().toMutableList())
}
}
override fun apiPageForks(token: String, owner: String, name: String, pageN: Int, itemsPerPage: Int): Flowable<List<Repository>> {
return Flowable.defer {
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
Flowable.just(repoService.getForks(RepositoryId(owner, name)))
}
}
override fun apiForkRepo(token: String, owner: String, name: String): Completable {
return Completable.create { subscriber ->
val repoService: RepositoryService = RepositoryService()
repoService.client.setOAuth2Token(token)
try {
repoService.forkRepository(RepositoryId(owner, name))
subscriber.onComplete()
} catch (e: Throwable) {
subscriber.onError(e)
}
}
}
override fun apiRequestAccessToken(clientId: String, clientSecret: String, code: String, redirectUri: String, state: String): Flowable<RequestAccessTokenResponse> {
return mRetrofit.create(ApiInterface::class.java).requestAccessToken(clientId, clientSecret, code, redirectUri, state)
}
override fun apiGetIssue(token: String, owner: String, name: String, issueNumber: Int): Flowable<Issue> {
return Flowable.defer {
val issueService: IssueService = IssueService()
issueService.client.setOAuth2Token(token)
Flowable.just(issueService.getIssue(owner, name, issueNumber))
}
}
override fun apiGetIssueComments(token: String, owner: String, name: String, issueNumber: Int): Flowable<List<Comment>> {
return Flowable.defer {
val issueService: IssueService = IssueService()
issueService.client.setOAuth2Token(token)
Flowable.just(issueService.getComments(owner, name, issueNumber))
}
}
override fun apiGetCommit(token: String, owner: String, name: String, sha: String): Flowable<RepositoryCommit> {
return Flowable.defer {
val commitService: CommitService = CommitService()
commitService.client.setOAuth2Token(token)
Flowable.just(commitService.getCommit(RepositoryId(owner, name), sha))
}
}
override fun apiGetCommitComments(token: String, owner: String, name: String, sha: String): Flowable<List<CommitComment>> {
return Flowable.defer {
val commitService: CommitService = CommitService()
commitService.client.setOAuth2Token(token)
Flowable.just(commitService.getComments(RepositoryId(owner, name), sha))
}
}
}
|
apache-2.0
|
fc132e89eec6e9ca53c8afdaba310b5e
| 42.140496 | 168 | 0.630316 | 4.657595 | false | false | false | false |
InsertKoinIO/koin
|
android/koin-android/src/main/java/org/koin/androidx/scope/ComponentActivityExt.kt
|
1
|
3288
|
/*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.androidx.scope
import android.content.ComponentCallbacks
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import org.koin.android.ext.android.getKoin
import org.koin.android.scope.AndroidScopeComponent
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.component.getScopeId
import org.koin.core.component.getScopeName
import org.koin.core.scope.Scope
/**
* Provide Koin Scope tied to ComponentActivity
*/
fun ComponentActivity.activityScope() = lazy { createActivityScope() }
fun ComponentActivity.activityRetainedScope() = lazy { createActivityRetainedScope() }
@KoinInternalApi
fun ComponentActivity.createScope(source: Any? = null): Scope = getKoin().createScope(getScopeId(), getScopeName(), source)
fun ComponentActivity.getScopeOrNull(): Scope? = getKoin().getScopeOrNull(getScopeId())
/**
* Create Scope for AppCompatActivity, given it's extending AndroidScopeComponent.
* Also register it in AndroidScopeComponent.scope
*/
fun ComponentActivity.createActivityScope(): Scope {
if (this !is AndroidScopeComponent) {
error("Activity should implement AndroidScopeComponent")
}
// if (this.scope != null) {
// error("Activity Scope is already created")
// }
return getKoin().getScopeOrNull(getScopeId()) ?: createScopeForCurrentLifecycle(this)
}
internal fun ComponentCallbacks.createScopeForCurrentLifecycle(owner: LifecycleOwner): Scope {
val scope = getKoin().createScope(getScopeId(), getScopeName(), this)
owner.registerScopeForLifecycle(scope)
return scope
}
internal fun LifecycleOwner.registerScopeForLifecycle(
scope: Scope
) {
lifecycle.addObserver(
object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
scope.close()
}
}
)
}
/**
* Create Retained Scope for AppCompatActivity, given it's extending AndroidScopeComponent.
* Also register it in AndroidScopeComponent.scope
*/
fun ComponentActivity.createActivityRetainedScope(): Scope {
if (this !is AndroidScopeComponent) {
error("Activity should implement AndroidScopeComponent")
}
// if (this.scope != null) {
// error("Activity Scope is already created")
// }
val scopeViewModel = viewModels<ScopeHandlerViewModel>().value
if (scopeViewModel.scope == null) {
val scope = getKoin().createScope(getScopeId(), getScopeName())
scopeViewModel.scope = scope
}
return scopeViewModel.scope!!
}
|
apache-2.0
|
3faea93c9969053bfc2571baf0838a5b
| 34.75 | 123 | 0.74118 | 4.630986 | false | false | false | false |
NerdNumber9/TachiyomiEH
|
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersPresenter.kt
|
1
|
7120
|
package eu.kanade.tachiyomi.ui.recent_updates
import android.os.Bundle
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.MangaChapter
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Calendar
import java.util.Date
import java.util.TreeMap
class RecentChaptersPresenter(
val preferences: PreferencesHelper = Injekt.get(),
private val db: DatabaseHelper = Injekt.get(),
private val downloadManager: DownloadManager = Injekt.get(),
private val sourceManager: SourceManager = Injekt.get()
) : BasePresenter<RecentChaptersController>() {
/**
* List containing chapter and manga information
*/
private var chapters: List<RecentChapterItem> = emptyList()
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
getRecentChaptersObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache(RecentChaptersController::onNextRecentChapters)
getChapterStatusObservable()
.subscribeLatestCache(RecentChaptersController::onChapterStatusChange,
{ _, error -> Timber.e(error) })
}
/**
* Get observable containing recent chapters and date
*
* @return observable containing recent chapters and date
*/
fun getRecentChaptersObservable(): Observable<List<RecentChapterItem>> {
// Set date limit for recent chapters
val cal = Calendar.getInstance().apply {
time = Date()
add(Calendar.MONTH, -1)
}
return db.getRecentChapters(cal.time).asRxObservable()
// Convert to a list of recent chapters.
.map { mangaChapters ->
val map = TreeMap<Date, MutableList<MangaChapter>> { d1, d2 -> d2.compareTo(d1) }
val byDay = mangaChapters
.groupByTo(map, { getMapKey(it.chapter.date_fetch) })
byDay.flatMap {
val dateItem = DateItem(it.key)
it.value.map { RecentChapterItem(it.chapter, it.manga, dateItem) }
}
}
.doOnNext {
it.forEach { item ->
// Find an active download for this chapter.
val download = downloadManager.queue.find { it.chapter.id == item.chapter.id }
// If there's an active download, assign it, otherwise ask the manager if
// the chapter is downloaded and assign it to the status.
if (download != null) {
item.download = download
}
}
setDownloadedChapters(it)
chapters = it
}
}
/**
* Get date as time key
*
* @param date desired date
* @return date as time key
*/
private fun getMapKey(date: Long): Date {
val cal = Calendar.getInstance()
cal.time = Date(date)
cal[Calendar.HOUR_OF_DAY] = 0
cal[Calendar.MINUTE] = 0
cal[Calendar.SECOND] = 0
cal[Calendar.MILLISECOND] = 0
return cal.time
}
/**
* Returns observable containing chapter status.
*
* @return download object containing download progress.
*/
private fun getChapterStatusObservable(): Observable<Download> {
return downloadManager.queue.getStatusObservable()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { download -> onDownloadStatusChange(download) }
}
/**
* Finds and assigns the list of downloaded chapters.
*
* @param items the list of chapter from the database.
*/
private fun setDownloadedChapters(items: List<RecentChapterItem>) {
for (item in items) {
val manga = item.manga
val chapter = item.chapter
if (downloadManager.isChapterDownloaded(chapter, manga)) {
item.status = Download.DOWNLOADED
}
}
}
/**
* Update status of chapters.
*
* @param download download object containing progress.
*/
private fun onDownloadStatusChange(download: Download) {
// Assign the download to the model object.
if (download.status == Download.QUEUE) {
val chapter = chapters.find { it.chapter.id == download.chapter.id }
if (chapter != null && chapter.download == null) {
chapter.download = download
}
}
}
/**
* Mark selected chapter as read
*
* @param items list of selected chapters
* @param read read status
*/
fun markChapterRead(items: List<RecentChapterItem>, read: Boolean) {
val chapters = items.map { it.chapter }
chapters.forEach {
it.read = read
if (!read) {
it.last_page_read = 0
}
}
Observable.fromCallable { db.updateChaptersProgress(chapters).executeAsBlocking() }
.subscribeOn(Schedulers.io())
.subscribe()
}
/**
* Delete selected chapters
*
* @param chapters list of chapters
*/
fun deleteChapters(chapters: List<RecentChapterItem>) {
Observable.just(chapters)
.doOnNext { deleteChaptersInternal(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst({ view, _ ->
view.onChaptersDeleted()
}, RecentChaptersController::onChaptersDeletedError)
}
/**
* Download selected chapters
* @param items list of recent chapters seleted.
*/
fun downloadChapters(items: List<RecentChapterItem>) {
items.forEach { downloadManager.downloadChapters(it.manga, listOf(it.chapter)) }
}
/**
* Delete selected chapters
*
* @param items chapters selected
*/
private fun deleteChaptersInternal(chapterItems: List<RecentChapterItem>) {
val itemsByManga = chapterItems.groupBy { it.manga.id }
for ((_, items) in itemsByManga) {
val manga = items.first().manga
val source = sourceManager.get(manga.source) ?: continue
val chapters = items.map { it.chapter }
downloadManager.deleteChapters(chapters, manga, source)
items.forEach {
it.status = Download.NOT_DOWNLOADED
it.download = null
}
}
}
}
|
apache-2.0
|
ea769e2f7a97593fa7f78715fc24cac7
| 33.731707 | 102 | 0.596208 | 4.958217 | false | false | false | false |
da1z/intellij-community
|
python/src/com/jetbrains/python/sdk/add/PyAddSdkDialog.kt
|
1
|
5162
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.components.JBList
import com.intellij.ui.popup.list.GroupedItemsListRenderer
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.JBUI
import com.jetbrains.python.sdk.PreferredSdkComparator
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.detectVirtualEnvs
import com.jetbrains.python.sdk.isAssociatedWithProject
import icons.PythonIcons
import java.awt.CardLayout
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author vlan
*/
class PyAddSdkDialog(private val project: Project?,
private val existingSdks: List<Sdk>,
private val newProjectPath: String?) : DialogWrapper(project) {
private var selectedPanel: PyAddSdkPanel? = null
private var panels: List<PyAddSdkPanel> = emptyList()
init {
init()
title = "Add Local Python Interpreter"
}
override fun createCenterPanel(): JComponent {
val sdks = existingSdks
.filter { it.sdkType is PythonSdkType && !PythonSdkType.isInvalid(it) }
.sortedWith(PreferredSdkComparator())
return createCardSplitter(listOf(createVirtualEnvPanel(project, sdks, newProjectPath),
createAnacondaPanel(),
PyAddSystemWideInterpreterPanel(existingSdks)))
}
override fun postponeValidation() = false
override fun doValidateAll(): List<ValidationInfo> = selectedPanel?.validateAll() ?: emptyList()
fun getOrCreateSdk(): Sdk? = selectedPanel?.getOrCreateSdk()
private fun createCardSplitter(panels: List<PyAddSdkPanel>): Splitter {
this.panels = panels
return Splitter(false, 0.25f).apply {
val cardLayout = CardLayout()
val cardPanel = JPanel(cardLayout).apply {
preferredSize = JBUI.size(640, 480)
for (panel in panels) {
add(panel, panel.panelName)
}
}
val cardsList = JBList(panels).apply {
val descriptor = object : ListItemDescriptorAdapter<PyAddSdkPanel>() {
override fun getTextFor(value: PyAddSdkPanel) = StringUtil.toTitleCase(value.panelName)
override fun getIconFor(value: PyAddSdkPanel) = value.icon
}
cellRenderer = object : GroupedItemsListRenderer<PyAddSdkPanel>(descriptor) {
override fun createItemComponent() = super.createItemComponent().apply {
border = JBUI.Borders.empty(4, 4, 4, 10)
}
}
addListSelectionListener {
selectedPanel = selectedValue
cardLayout.show(cardPanel, selectedValue.panelName)
}
selectedPanel = panels.getOrNull(0)
selectedIndex = 0
}
firstComponent = cardsList
secondComponent = cardPanel
}
}
private fun createVirtualEnvPanel(project: Project?,
existingSdks: List<Sdk>,
newProjectPath: String?): PyAddSdkPanel {
val newVirtualEnvPanel = if (project != null || PlatformUtils.isPyCharmEducational())
PyAddNewVirtualEnvPanel(project, existingSdks, newProjectPath)
else
null
val existingVirtualEnvPanel = PyAddExistingVirtualEnvPanel(project, existingSdks, newProjectPath)
val panels = listOf(newVirtualEnvPanel,
existingVirtualEnvPanel)
.filterNotNull()
val defaultPanel = when {
detectVirtualEnvs(project, existingSdks).any { it.isAssociatedWithProject(project) } -> existingVirtualEnvPanel
newVirtualEnvPanel != null -> newVirtualEnvPanel
else -> existingVirtualEnvPanel
}
return PyAddSdkGroupPanel("Virtualenv environment", PythonIcons.Python.Virtualenv, panels, defaultPanel)
}
private fun createAnacondaPanel(): PyAddSdkPanel {
val newCondaEnvPanel = when {
project != null || PlatformUtils.isPyCharmEducational() -> PyAddNewCondaEnvPanel(project, existingSdks, newProjectPath)
else -> null
}
val panels = listOf(newCondaEnvPanel,
PyAddExistingCondaEnvPanel(project, existingSdks, newProjectPath))
.filterNotNull()
return PyAddSdkGroupPanel("Conda environment", PythonIcons.Python.Anaconda, panels, panels[0])
}
}
|
apache-2.0
|
7eca8770c875aa8f7455fec8242b7471
| 38.707692 | 125 | 0.707284 | 4.906844 | false | false | false | false |
jdiazcano/modulartd
|
editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/MainMenu.kt
|
1
|
2914
|
package com.jdiazcano.modulartd.ui
import com.github.salomonbrys.kodein.instance
import com.jdiazcano.modulartd.ActionManager
import com.jdiazcano.modulartd.bus.Bus
import com.jdiazcano.modulartd.bus.BusTopic
import com.jdiazcano.modulartd.injections.kodein
import com.jdiazcano.modulartd.plugins.actions.Action
import com.jdiazcano.modulartd.plugins.actions.Menus
import com.jdiazcano.modulartd.plugins.actions.ParentedAction
import com.jdiazcano.modulartd.plugins.actions.SeparatorPlace
import com.jdiazcano.modulartd.utils.getOrThrow
import com.jdiazcano.modulartd.utils.translate
import com.kotcrab.vis.ui.widget.Menu
import com.kotcrab.vis.ui.widget.MenuBar
import com.kotcrab.vis.ui.widget.PopupMenu
class MainMenu : MenuBar() {
private val actionManager = kodein.instance<ActionManager>()
private val menuItems: MutableMap<Action, ActionedMenuItem> = mutableMapOf()
private val menus = mapOf(
Menus.FILE to Menu(translate("menu.file")),
Menus.VIEW to Menu(translate("menu.view")),
Menus.EDIT to Menu(translate("menu.edit")),
Menus.GAME to Menu(translate("menu.game")),
Menus.HELP to Menu(translate("menu.help"))
)
init {
menus.forEach { addMenu(it.value) }
Bus.register<ParentedAction>(BusTopic.ACTION_REGISTERED) {
createMenu(it)
}
}
fun createMenu(parentedAction: ParentedAction) {
val (action, parentId) = parentedAction
val separator = action.separator
if (parentId in menus) {
val menu = menus[parentId]!!
val item = ActionedMenuItem(action)
if (separator == SeparatorPlace.ABOVE || separator == SeparatorPlace.BOTH) {
menu.addSeparator()
}
menu.addItem(item)
if (separator == SeparatorPlace.BELOW || separator == SeparatorPlace.BOTH) {
menu.addSeparator()
}
menuItems[action] = item
} else {
val parentAction = actionManager.findAction(parentId)
if (parentAction != null) {
val parentMenu = findMenuForAction(parentAction)
if (parentMenu.subMenu == null) {
parentMenu.subMenu = PopupMenu()
}
val item = ActionedMenuItem(action)
parentMenu.subMenu.addItem(item)
if (separator == SeparatorPlace.ABOVE || separator == SeparatorPlace.BOTH) {
parentMenu.subMenu.addSeparator()
}
parentMenu.subMenu.addItem(item)
if (separator == SeparatorPlace.BELOW || separator == SeparatorPlace.BOTH) {
parentMenu.subMenu.addSeparator()
}
menuItems[action] = item
}
}
}
fun findMenuForAction(action: Action) = menuItems.getOrThrow(action)
}
|
apache-2.0
|
976f65c2667b5ebc4b6be92645f015ba
| 38.378378 | 92 | 0.635553 | 4.574568 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt
|
1
|
2273
|
package eu.kanade.tachiyomi.ui.reader.loader
import android.app.Application
import android.net.Uri
import com.hippo.unifile.UniFile
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadProvider
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.io.File
/**
* Loader used to load a chapter from the downloaded chapters.
*/
class DownloadPageLoader(
private val chapter: ReaderChapter,
private val manga: Manga,
private val source: Source,
private val downloadManager: DownloadManager,
private val downloadProvider: DownloadProvider,
) : PageLoader() {
// Needed to open input streams
private val context: Application by injectLazy()
/**
* Returns an observable containing the pages found on this downloaded chapter.
*/
override fun getPages(): Observable<List<ReaderPage>> {
val dbChapter = chapter.chapter
val chapterPath = downloadProvider.findChapterDir(dbChapter.name, dbChapter.scanlator, manga.title, source)
return if (chapterPath?.isFile == true) {
getPagesFromArchive(chapterPath)
} else {
getPagesFromDirectory()
}
}
private fun getPagesFromArchive(chapterPath: UniFile): Observable<List<ReaderPage>> {
val loader = ZipPageLoader(File(chapterPath.filePath!!))
return loader.getPages()
}
private fun getPagesFromDirectory(): Observable<List<ReaderPage>> {
return downloadManager.buildPageList(source, manga, chapter.chapter)
.map { pages ->
pages.map { page ->
ReaderPage(page.index, page.url, page.imageUrl) {
context.contentResolver.openInputStream(page.uri ?: Uri.EMPTY)!!
}.apply {
status = Page.READY
}
}
}
}
override fun getPage(page: ReaderPage): Observable<Int> {
return Observable.just(Page.READY)
}
}
|
apache-2.0
|
0dd3e69f4fc43b70f6f9cfbd8fcbc8d0
| 33.969231 | 115 | 0.679718 | 4.610548 | false | false | false | false |
Adventech/sabbath-school-android-2
|
common/core/src/main/java/com/cryart/sabbathschool/core/extensions/view/FadeTo.kt
|
1
|
3107
|
/*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.core.extensions.view
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
// https://gist.github.com/gpeal/2784b455cfd22d7ba567fa9c24144656
/**
* Fade a view to visible or gone. This function is idempotent - it can be called over and over again with the same
* value without affecting an in-progress animation.
*/
fun View.fadeTo(visible: Boolean, duration: Long = 500, startDelay: Long = 0, toAlpha: Float = 1f) {
// Make this idempotent.
val tagKey = "fadeTo".hashCode()
if (visible == isVisible && animation == null && getTag(tagKey) == null) return
if (getTag(tagKey) == visible) return
setTag(tagKey, visible)
setTag("fadeToAlpha".hashCode(), toAlpha)
if (visible && alpha == 1f) alpha = 0f
animate()
.alpha(if (visible) toAlpha else 0f)
.withStartAction {
if (visible) isVisible = true
}
.withEndAction {
setTag(tagKey, null)
if (isAttachedToWindow && !visible) isVisible = false
}
.setInterpolator(FastOutSlowInInterpolator())
.setDuration(duration)
.setStartDelay(startDelay)
.start()
}
/**
* Cancels the animation started by [fadeTo] and jumps to the end of it.
*/
fun View.cancelFade() {
val tagKey = "fadeTo".hashCode()
val visible = getTag(tagKey)?.castOrNull<Boolean>() ?: return
animate().cancel()
isVisible = visible
alpha = if (visible) getTag("fadeToAlpha".hashCode())?.castOrNull<Float>() ?: 1f else 0f
setTag(tagKey, null)
}
/**
* Cancels the fade for this view and any ancestors.
*/
fun View.cancelFadeRecursively() {
cancelFade()
castOrNull<ViewGroup>()?.children?.asSequence()?.forEach { it.cancelFade() }
}
private inline fun <reified T> Any.castOrNull(): T? {
return this as? T
}
|
mit
|
72a7079ff2890bacaa2702463370c337
| 35.988095 | 115 | 0.705826 | 4.126162 | false | false | false | false |
Adventech/sabbath-school-android-2
|
features/media/src/main/kotlin/app/ss/media/playback/players/MediaSessionCallback.kt
|
1
|
4795
|
package app.ss.media.playback.players
import android.media.AudioManager
import android.os.Bundle
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat.Builder
import android.support.v4.media.session.PlaybackStateCompat.STATE_NONE
import androidx.core.os.bundleOf
import app.ss.media.playback.AudioFocusHelper
import app.ss.media.playback.AudioQueueManager
import app.ss.media.playback.BY_UI_KEY
import app.ss.media.playback.PAUSE_ACTION
import app.ss.media.playback.PLAY_ACTION
import app.ss.media.playback.SET_MEDIA_STATE
import app.ss.media.playback.UPDATE_META_DATA
import app.ss.media.playback.UPDATE_QUEUE
import app.ss.media.playback.extensions.isPlaying
import app.ss.media.playback.model.toQueueItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
const val QUEUE_MEDIA_ID_KEY = "queue_media_id_key"
const val QUEUE_LIST_KEY = "queue_list_key"
class MediaSessionCallback(
private val mediaSession: MediaSessionCompat,
private val audioPlayer: SSAudioPlayer,
private val audioFocusHelper: AudioFocusHelper,
private val audioQueueManager: AudioQueueManager
) : MediaSessionCompat.Callback(), CoroutineScope by MainScope() {
init {
audioFocusHelper.onAudioFocusGain {
if (isAudioFocusGranted && !audioPlayer.getSession().isPlaying()) {
audioPlayer.playAudio()
} else audioFocusHelper.setVolume(AudioManager.ADJUST_RAISE)
isAudioFocusGranted = false
}
audioFocusHelper.onAudioFocusLoss {
abandonPlayback()
isAudioFocusGranted = false
audioPlayer.pause()
}
audioFocusHelper.onAudioFocusLossTransient {
if (audioPlayer.getSession().isPlaying()) {
isAudioFocusGranted = true
audioPlayer.pause()
}
}
audioFocusHelper.onAudioFocusLossTransientCanDuck {
audioFocusHelper.setVolume(AudioManager.ADJUST_LOWER)
}
}
override fun onPause() {
audioPlayer.pause()
}
override fun onPlay() {
playOnFocus()
}
override fun onFastForward() {
audioPlayer.fastForward()
}
override fun onRewind() {
audioPlayer.rewind()
}
override fun onPlayFromMediaId(mediaId: String, extras: Bundle?) {
launch { audioPlayer.setDataFromMediaId(mediaId, extras ?: bundleOf()) }
}
override fun onSeekTo(position: Long) {
audioPlayer.seekTo(position)
}
override fun onSkipToNext() {
launch { audioPlayer.nextAudio() }
}
override fun onSkipToPrevious() {
launch { audioPlayer.previousAudio() }
}
override fun onSkipToQueueItem(id: Long) {
launch { audioPlayer.skipTo(id.toInt()) }
}
override fun onStop() {
audioPlayer.stop()
}
override fun onSetRepeatMode(repeatMode: Int) {
super.onSetRepeatMode(repeatMode)
val bundle = mediaSession.controller.playbackState.extras ?: Bundle()
audioPlayer.setPlaybackState(
Builder(mediaSession.controller.playbackState)
.setExtras(
bundle.apply {
putInt(REPEAT_MODE, repeatMode)
}
).build()
)
}
override fun onCustomAction(action: String?, extras: Bundle?) {
when (action) {
SET_MEDIA_STATE -> setSavedMediaSessionState()
PAUSE_ACTION -> audioPlayer.pause(extras ?: bundleOf(BY_UI_KEY to true))
PLAY_ACTION -> playOnFocus(extras ?: bundleOf(BY_UI_KEY to true))
UPDATE_QUEUE -> {
val audios = audioQueueManager.queue
mediaSession.setQueue(
audios.mapIndexed { index, audio ->
audio.toQueueItem(index.toLong())
}
)
}
UPDATE_META_DATA -> {
audioPlayer.resetMedia()
}
}
}
private fun setSavedMediaSessionState() {
val controller = mediaSession.controller ?: return
if (controller.playbackState == null || controller.playbackState.state == STATE_NONE) {
// audioPlayer.restoreQueueState()
} else {
restoreMediaSession()
}
}
private fun restoreMediaSession() {
mediaSession.setMetadata(mediaSession.controller.metadata)
audioPlayer.setPlaybackState(mediaSession.controller.playbackState)
}
private fun playOnFocus(extras: Bundle = bundleOf(BY_UI_KEY to true)) {
if (audioFocusHelper.requestPlayback()) {
audioPlayer.playAudio(extras)
}
}
}
|
mit
|
7572c4572468038ca38e84b87f048d17
| 31.181208 | 95 | 0.645673 | 4.766402 | false | false | false | false |
PolymerLabs/arcs
|
java/arcs/core/data/expression/PaxelParser.kt
|
1
|
11650
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data.expression
import arcs.core.data.expression.Expression.FieldExpression
import arcs.core.data.expression.Expression.QualifiedExpression
import arcs.core.data.expression.Expression.Scope
import arcs.core.util.BigInt
import arcs.core.util.Grammar
import arcs.core.util.ParseResult
import arcs.core.util.Parser
import arcs.core.util.ParserException
import arcs.core.util.any
import arcs.core.util.div
import arcs.core.util.eof
import arcs.core.util.many
import arcs.core.util.map
import arcs.core.util.optional
import arcs.core.util.parser
import arcs.core.util.plus
import arcs.core.util.regex
import arcs.core.util.toBigInt
import arcs.core.util.token
import arcs.core.util.unaryMinus
/**
* A parser combinator implementation of the Paxel expression parser.
*/
object PaxelParser : Grammar<Expression<Any>>() {
private const val WS = "[\\s\\n]"
sealed class DiscreteType<T : Number> {
object PaxelBigInt : DiscreteType<BigInt>() {
override fun parse(number: String) = BigInt(number)
}
object PaxelInt : DiscreteType<Int>() {
override fun parse(number: String) = number.toInt()
}
object PaxelLong : DiscreteType<Long>() {
override fun parse(number: String) = number.toLong()
}
abstract fun parse(number: String): T
}
sealed class Unit(val conversionFactor: Int) {
open fun convert(number: Number): Number = when (number) {
is BigInt -> number.multiply(conversionFactor.toBigInt())
is Long -> number * conversionFactor
is Double -> number * conversionFactor.toDouble()
else -> number.toLong() * conversionFactor
}
object Identity : Unit(1) {
override fun convert(number: Number) = number
}
object Millisecond : Unit(1)
object Second : Unit(1000)
object Minute : Unit(Second.conversionFactor * 60)
object Hour : Unit(Minute.conversionFactor * 60)
object Day : Unit(Hour.conversionFactor * 24)
}
private val whitespace = -regex("($WS+)")
private val oCurly by -regex("(\\{$WS*)")
private val cCurly by -regex("($WS*\\})")
private val comma by -regex("($WS*,$WS*)")
private val colon by -regex("($WS*:$WS*)")
private val units by
optional(
whitespace +
(
regex("(millisecond)s?").map { Unit.Millisecond } /
regex("(second)s?").map { Unit.Second } /
regex("(minute)s?").map { Unit.Minute } /
regex("(hour)s?").map { Unit.Hour } /
regex("(day)s?").map { Unit.Day }
)
).map {
it ?: Unit.Identity
}
private val typeIdentifier by
token("n").map { DiscreteType.PaxelBigInt } /
token("i").map { DiscreteType.PaxelInt } /
token("l").map { DiscreteType.PaxelLong }
private val discreteValue by
(regex("(-?[0-9]+)") + typeIdentifier + units).map { (number, type, units) ->
Expression.NumberLiteralExpression(units.convert(type.parse(number)))
}
// IEEE-754 float: +-[integralPart].[fractionPart]e+-[exponent]
private val numberValue by (regex("([+-]?[0-9]+\\.?[0-9]*(?:[eE][+-]?[0-9]+)?)") + units)
.map { (number, units) ->
Expression.NumberLiteralExpression(units.convert(number.toDouble()))
}
private val booleanValue by
token("true").map { true.asExpr() } / token("false").map { false.asExpr() }
private val nullValue by token("null").map { nullExpr() }
// JSON-style string: all legal chars but ' or \, otherwise \'\b\n\r\f\t \\ and \u{hex} allowed
private val textValue by regex("\'((?:[^\'\\\\]|\\\\[\'\\\\/bfnrt]|\\\\u[0-9a-f]{4})*)\'").map {
Expression.TextLiteralExpression(unescape(it))
}
private val ident by regex("((?!from|select|let|orderby|where)[A-Za-z_][A-Za-z0-9_]*)")
// optional whitespace
private val ows by -regex("($WS*)")
private val functionArguments: Parser<List<Expression<Any>>> by optional(
parser(::paxelExpression) + many(-regex("($WS*,$WS*)") + parser(::paxelExpression))
).map {
it?.let { (arg, rest) ->
listOf(arg) + rest
} ?: emptyList()
}
private val functionCall by
(ident + -token("(") + ows + functionArguments + ows + -token(")")).map { (id, args) ->
Expression.FunctionExpression<Any>(
maybeFail("unknown function name $id") {
GlobalFunction.of(id)
},
args
)
}
private val scopeQualifier by
functionCall / ident.map { FieldExpression<Any>(null, it, false) } /
parser(::nestedExpression)
@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalStdlibApi::class)
private val scopeLookup by
(scopeQualifier + many((token("?.") / token(".")) + ident)).map { (initial, rest) ->
rest.fold(initial) { qualifier, (operator, id) ->
FieldExpression<Scope>(qualifier as Expression<Scope>, id, operator == "?.")
}
}
private val query by regex("\\?([a-zA-Z_][a-zA-Z0-9_]*)").map {
Expression.QueryParameterExpression<Any>(it)
}
private val nestedExpression by
-regex("(\\($WS*)") + parser(::paxelExpression) + -regex("($WS*\\))")
@Suppress("UNCHECKED_CAST")
private val unaryOperation by
((token("not ") / token("-")) + ows + parser(::primaryExpression)).map { (token, expr) ->
Expression.UnaryExpression(
Expression.UnaryOp.fromToken(token.trim()) as Expression.UnaryOp<Any?, Any?>, expr
)
}
private val primaryExpression: Parser<Expression<Any?>> by
discreteValue /
numberValue /
unaryOperation /
booleanValue /
textValue /
nullValue /
scopeLookup /
query
private val multiplyExpression by primaryExpression sepBy binaryOp("*", "/")
private val additiveExpression by multiplyExpression sepBy binaryOp("+", "-")
private val ifNullExpression by additiveExpression sepBy binaryOp("?:")
private val comparativeExpression by ifNullExpression sepBy binaryOp("<=", "<", ">=", ">")
private val equalityExpression by comparativeExpression sepBy binaryOp("==", "!=")
private val andExpression by equalityExpression sepBy binaryOp("and ")
private val orExpression by andExpression sepBy binaryOp("or ")
private val refinementExpression by orExpression
private val sourceExpression by scopeLookup / nestedExpression
private val fromIter by -token("from") + (whitespace + ident + whitespace)
private val fromIn by -token("in") + (whitespace + sourceExpression)
@Suppress("UNCHECKED_CAST")
private val fromExpression: Parser<QualifiedExpression> by
(fromIter + fromIn).map { (iter, src) ->
Expression.FromExpression(null, src as Expression<Sequence<Any>>, iter)
}
@Suppress("UNCHECKED_CAST")
private val whereExpression: Parser<QualifiedExpression> by
(-token("where") + whitespace + refinementExpression).map { expr ->
Expression.WhereExpression(
expr as Expression<Sequence<Scope>>, expr as Expression<Boolean>
)
}
private val letVar by -token("let") + (whitespace + ident + ows)
private val letSource by -token("=") + (whitespace + sourceExpression)
@Suppress("UNCHECKED_CAST")
private val letExpression: Parser<QualifiedExpression> by
(letVar + letSource).map { (varName, src) ->
Expression.LetExpression(
src as Expression<Sequence<Scope>>,
src as Expression<Any>,
varName
)
}
private val orderDirection by optional(ows + (token("descending") / token("ascending"))).map {
it?.let { dir -> dir == "descending" } ?: false
}
@Suppress("UNCHECKED_CAST")
private val selectorExpression by (refinementExpression + orderDirection).map { (expr, dir) ->
Expression.OrderByExpression.Selector(expr as Expression<Any>, dir)
}
private val orderBySelectors by
(selectorExpression + many(comma + selectorExpression)).map { (first, rest) ->
listOf(first) + rest
}
@Suppress("UNCHECKED_CAST")
private val orderByExpression by -token("orderby") +
(whitespace + orderBySelectors).map { selectors ->
Expression.OrderByExpression<Any>(
selectors[0].expr as Expression<Sequence<Scope>>,
selectors
)
}
private val schemaNames by (ident + many(whitespace + ident)).map { (ident, rest) ->
setOf(ident) + rest.toSet()
}
private val newField by (ident + colon + parser(::paxelExpression))
private val newFields by optional(newField + many(comma + newField)).map { fields ->
fields?.let { (name, expr, otherFields) ->
listOf(name to expr) + otherFields
} ?: emptyList()
}
private val newFieldsDecl by oCurly + newFields + cCurly
private val newExpression: Parser<Expression<Any>> by
(-token("new") + whitespace + schemaNames + ows + newFieldsDecl).map { (names, fields) ->
Expression.NewExpression(names, fields)
}
private val selectExprArg by newExpression / refinementExpression
@Suppress("UNCHECKED_CAST")
private val selectExpression: Parser<QualifiedExpression> by
(-token("select") + ows + selectExprArg).map { expr ->
Expression.SelectExpression(expr as Expression<Sequence<Scope>>, expr)
}
private val qualifiedExpression: Parser<QualifiedExpression> by
(fromExpression / whereExpression / letExpression / orderByExpression)
private val expressionWithQualifier by
(fromExpression + many(ows + qualifiedExpression) + (ows + selectExpression))
.map { (first, rest, select) ->
val all: List<QualifiedExpression> = listOf(first) + rest + listOf(select)
val nullQualifier: QualifiedExpression? = null
all.fold(nullQualifier) { qualifier: QualifiedExpression?, qualified: QualifiedExpression ->
qualified.withQualifier(qualifier)
}
}
@Suppress("UNCHECKED_CAST")
private val paxelExpression by
(newExpression / expressionWithQualifier / refinementExpression) as Parser<Expression<Any>>
override val topLevel by paxelExpression + ows + eof
@Suppress("UNCHECKED_CAST")
private fun binaryOp(vararg tokens: String) = ows + any(
tokens.map { token(it) }.toList()
).map { token ->
Expression.BinaryOp.fromToken(token.trim()) as Expression.BinaryOp<Any?, Any?, Any?>
}
private infix fun Parser<Expression<Any?>>.sepBy(
tokens: Parser<Expression.BinaryOp<Any?, Any?, Any?>>
) = (this + many(tokens + ows + this)).map { (left, rest) ->
rest.fold(left) { lhs, (op, rhs) ->
Expression.BinaryExpression(op, lhs, rhs)
}
}
private fun <T> maybeFail(msg: String, block: () -> T) = try {
block()
} catch (e: Exception) {
throw ParserException(msg, e)
}
private fun unescape(string: String) = string.replace(
Regex("\\\\[\'/bfnrt]|\\\\u[0-9a-f]{4}")
) { match: MatchResult ->
when {
escapes.contains(match.value) -> escapes[match.value]!!
match.value.startsWith("\\u") -> {
match.value.substring(3).toInt(16).toChar().toString()
}
else -> throw IllegalArgumentException("${match.value} shouldn't match")
}
}
private val escapes = mapOf(
"\\\\" to "\\",
"\\\"" to "\"",
"\\\'" to "\'",
"\\b" to "\b",
"\\f" to 12.toChar().toString(),
"\\n" to "\n",
"\\r" to "\r",
"\\t" to "\t"
)
/** Parses a paxel expression in string format and returns an [Expression] */
fun parse(paxelInput: String) =
when (val result = this(paxelInput)) {
is ParseResult.Success<*> -> result.value as Expression<*>
is ParseResult.Failure -> throw IllegalArgumentException(
"Parse Failed reading ${paxelInput.substring(result.start.offset)}\n$result"
)
}
}
|
bsd-3-clause
|
d2121a40fc1d0e3a205c8d0d62fefda5
| 32.866279 | 98 | 0.666266 | 3.930499 | false | false | false | false |
ingokegel/intellij-community
|
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/ReviewListCellRenderer.kt
|
1
|
14849
|
// 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.collaboration.ui.codereview.list
import com.intellij.collaboration.messages.CollaborationToolsBundle.message
import com.intellij.ide.IdeTooltip
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.JBList
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.IconUtil
import com.intellij.util.containers.nullize
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import icons.CollaborationToolsIcons
import java.awt.*
import java.awt.geom.RoundRectangle2D
import java.awt.image.BufferedImage
import javax.swing.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class ReviewListCellRenderer<T>(private val presenter: (T) -> ReviewListItemPresentation)
: ListCellRenderer<T>, JPanel(null) {
private val toolTipManager
get() = IdeTooltipManager.getInstance()
private val title = JLabel().apply {
minimumSize = JBDimension(30, 0)
}
private val info = JLabel()
private val tags = JLabel()
private val state = JLabel().apply {
border = JBUI.Borders.empty(0, 4)
foreground = stateForeground
}
private val statePanel = StatePanel(state).apply {
background = stateBackground
}
private val nonMergeable = JLabel()
private val buildStatus = JLabel()
private val userGroup1 = JLabel()
private val userGroup2 = JLabel()
private val comments = JLabel()
init {
val firstLinePanel = JPanel(HorizontalSidesLayout(6)).apply {
isOpaque = false
add(title, SwingConstants.LEFT as Any)
add(tags, SwingConstants.LEFT as Any)
add(statePanel, SwingConstants.RIGHT as Any)
add(nonMergeable, SwingConstants.RIGHT as Any)
add(buildStatus, SwingConstants.RIGHT as Any)
add(userGroup1, SwingConstants.RIGHT as Any)
add(userGroup2, SwingConstants.RIGHT as Any)
add(comments, SwingConstants.RIGHT as Any)
}
layout = BorderLayout()
border = JBUI.Borders.empty(6)
add(firstLinePanel, BorderLayout.CENTER)
add(info, BorderLayout.SOUTH)
UIUtil.forEachComponentInHierarchy(this) {
it.isFocusable = false
}
}
override fun getListCellRendererComponent(list: JList<out T>,
value: T,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
background = ListUiUtil.WithTallRow.background(list, isSelected, list.hasFocus())
val primaryTextColor = ListUiUtil.WithTallRow.foreground(isSelected, list.hasFocus())
val secondaryTextColor = ListUiUtil.WithTallRow.secondaryForeground(isSelected, list.hasFocus())
val presentation = presenter(value)
title.apply {
text = presentation.title
foreground = primaryTextColor
}
info.apply {
val author = presentation.author
if (author != null) {
text = message("review.list.info.author",
presentation.id,
DateFormatUtil.formatPrettyDate(presentation.createdDate),
author.getPresentableName())
}
else {
text = message("review.list.info",
presentation.id,
DateFormatUtil.formatPrettyDate(presentation.createdDate))
}
foreground = secondaryTextColor
}
val tagGroup = presentation.tagGroup
tags.apply {
icon = CollaborationToolsIcons.Branch
isVisible = tagGroup != null
}.also {
if (tagGroup != null) {
val tooltip = LazyIdeToolTip(it) {
createTitledList(tagGroup) { label, tag, _ ->
label.text = tag.name
label.foreground = UIUtil.getToolTipForeground()
val color = tag.color
if (color != null) {
//TODO: need a separate untinted icon to color properly
label.icon = IconUtil.colorize(CollaborationToolsIcons.Branch, color)
}
else {
label.icon = CollaborationToolsIcons.Branch
}
}
}
toolTipManager.setCustomTooltip(it, tooltip)
}
else {
toolTipManager.setCustomTooltip(it, null)
}
}
state.apply {
font = JBUI.Fonts.smallFont()
text = presentation.state
isVisible = presentation.state != null
}
statePanel.isVisible = presentation.state != null
nonMergeable.apply {
val status = presentation.mergeableStatus
icon = status?.icon
toolTipText = status?.tooltip
isVisible = status != null
}
buildStatus.apply {
val status = presentation.buildStatus
icon = status?.icon
toolTipText = status?.tooltip
isVisible = status != null
}
showUsersIcon(userGroup1, presentation.userGroup1)
showUsersIcon(userGroup2, presentation.userGroup2)
comments.apply {
val counter = presentation.commentsCounter
icon = CollaborationToolsIcons.Comment
text = counter?.count.toString()
toolTipText = counter?.tooltip
isVisible = counter != null
}
return this
}
private fun <T> createTitledList(collection: NamedCollection<T>, customizer: SimpleListCellRenderer.Customizer<T>): JComponent {
val title = JLabel().apply {
font = JBUI.Fonts.smallFont()
foreground = UIUtil.getContextHelpForeground()
text = collection.namePlural
border = JBUI.Borders.empty(0, 10, 4, 0)
}
val list = JBList(collection.items).apply {
isOpaque = false
cellRenderer = SimpleListCellRenderer.create(customizer)
}
return JPanel(BorderLayout()).apply {
isOpaque = false
add(title, BorderLayout.NORTH)
add(list, BorderLayout.CENTER)
}
}
private fun showUsersIcon(label: JLabel, users: NamedCollection<UserPresentation>?) {
val icons = users?.items?.map { it.avatarIcon }?.nullize()
if (icons == null) {
label.isVisible = false
label.icon = null
}
else {
label.isVisible = true
label.icon = OverlaidOffsetIconsIcon(icons)
}
if (users != null) {
val tooltip = LazyIdeToolTip(label) {
createTitledList(users) { label, user, _ ->
label.text = user.getPresentableName()
label.icon = user.avatarIcon
label.foreground = UIUtil.getToolTipForeground()
}
}
toolTipManager.setCustomTooltip(label, tooltip)
}
}
companion object {
// TODO: register metadata provider somehow?
private val stateForeground = JBColor.namedColor("ReviewList.state.foreground", 0x797979)
private val stateBackground = JBColor.namedColor("ReviewList.state.background", 0xDFE1E5)
/**
* Paints [icons] in a stack - one over the other with a slight offset
* Assumes that icons all have the same size
*/
private class OverlaidOffsetIconsIcon(
private val icons: List<Icon>,
private val offsetRate: Float = 0.4f
) : Icon {
override fun getIconHeight(): Int = icons.maxOfOrNull { it.iconHeight } ?: 0
override fun getIconWidth(): Int {
if (icons.isEmpty()) return 0
val iconWidth = icons.first().iconWidth
val width = iconWidth + (icons.size - 1) * iconWidth * offsetRate
return max(width.roundToInt(), 0)
}
override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) {
val bufferImage = ImageUtil.createImage(g, iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB)
val bufferGraphics = bufferImage.createGraphics()
try {
paintToBuffer(bufferGraphics)
}
finally {
bufferGraphics.dispose()
}
StartupUiUtil.drawImage(g, bufferImage, x, y, null)
}
private fun paintToBuffer(g: Graphics2D) {
var rightEdge = iconWidth
icons.reversed().forEachIndexed { index, icon ->
val currentX = rightEdge - icon.iconWidth
// cut out the part of the painted icon slightly bigger then the next one to create a visual gap
if (index > 0) {
val g2 = g.create() as Graphics2D
try {
val scaleX = 1.1
val scaleY = 1.1
// paint a bit higher, so that the cutout is centered
g2.translate(0, -((iconHeight * scaleY - iconHeight) / 2).roundToInt())
g2.scale(scaleX, scaleY)
g2.composite = AlphaComposite.DstOut
icon.paintIcon(null, g2, currentX, 0)
}
finally {
g2.dispose()
}
}
icon.paintIcon(null, g, currentX, 0)
rightEdge -= (icon.iconWidth * offsetRate).roundToInt()
}
}
}
/**
* Draws a background with rounded corners
*/
private class StatePanel(stateLabel: JLabel) : JPanel(BorderLayout()) {
init {
add(stateLabel, BorderLayout.CENTER)
isOpaque = false
}
override fun paintComponent(g: Graphics) {
g as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE)
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
val insets = insets
val bounds = bounds
JBInsets.removeFrom(bounds, insets)
val arc = JBUIScale.scale(6)
val rect = RoundRectangle2D.Float(0f, 0f,
bounds.width.toFloat(), bounds.height.toFloat(),
arc.toFloat(), arc.toFloat())
g.color = background
g.fill(rect)
super.paintComponent(g)
}
}
/**
* Lays out the components horizontally in two groups - [SwingConstants.LEFT] and [SwingConstants.RIGHT] anchored to the left and right sides respectively.
* Respects the minimal sizes and does not force the components to grow.
*/
private class HorizontalSidesLayout(gap: Int) : AbstractLayoutManager() {
private val gap = JBValue.UIInteger("", max(0, gap))
private val leftComponents = mutableListOf<Component>()
private val rightComponents = mutableListOf<Component>()
override fun addLayoutComponent(comp: Component, constraints: Any?) {
when (constraints) {
SwingConstants.RIGHT -> rightComponents.add(comp)
else -> leftComponents.add(comp)
}
}
override fun addLayoutComponent(name: String?, comp: Component) {
addLayoutComponent(comp, SwingConstants.LEFT)
}
override fun removeLayoutComponent(comp: Component) {
leftComponents.remove(comp)
rightComponents.remove(comp)
}
override fun minimumLayoutSize(parent: Container): Dimension =
getSize(leftComponents + rightComponents, Component::getMinimumSize)
override fun preferredLayoutSize(parent: Container): Dimension =
getSize(leftComponents + rightComponents, Component::getPreferredSize)
private fun getSize(components: List<Component>, dimensionGetter: (Component) -> Dimension): Dimension {
val visibleComponents = components.asSequence().filter(Component::isVisible)
val dimension = visibleComponents.fold(Dimension()) { acc, component ->
val size = dimensionGetter(component)
acc.width += size.width
acc.height = max(acc.height, size.height)
acc
}
dimension.width += gap.get() * max(0, visibleComponents.count() - 1)
return dimension
}
override fun layoutContainer(parent: Container) {
val bounds = Rectangle(Point(0, 0), parent.size)
JBInsets.removeFrom(bounds, parent.insets)
val height = bounds.height
val widthDeltaFraction = getWidthDeltaFraction(minimumLayoutSize(parent).width,
preferredLayoutSize(parent).width,
bounds.width)
val leftMinWidth = getSize(leftComponents, Component::getMinimumSize).width
val leftPrefWidth = getSize(leftComponents, Component::getPreferredSize).width
val leftWidth = leftMinWidth + ((leftPrefWidth - leftMinWidth) * widthDeltaFraction).toInt()
val leftWidthDeltaFraction = getWidthDeltaFraction(leftMinWidth, leftPrefWidth, leftWidth)
layoutGroup(leftComponents, bounds.location, height, leftWidthDeltaFraction)
val rightMinWidth = getSize(rightComponents, Component::getMinimumSize).width
val rightPrefWidth = getSize(rightComponents, Component::getPreferredSize).width
val rightWidth = min(bounds.width - leftWidth - gap.get(), rightPrefWidth)
val rightX = bounds.x + max(leftWidth + gap.get(), bounds.width - rightWidth)
val rightWidthDeltaFraction = getWidthDeltaFraction(rightMinWidth, rightPrefWidth, rightWidth)
layoutGroup(rightComponents, Point(rightX, bounds.y), height, rightWidthDeltaFraction)
}
private fun getWidthDeltaFraction(minWidth: Int, prefWidth: Int, currentWidth: Int): Float {
if (prefWidth <= minWidth) {
return 0f
}
return ((currentWidth - minWidth) / (prefWidth - minWidth).toFloat())
.coerceAtLeast(0f)
.coerceAtMost(1f)
}
private fun layoutGroup(components: List<Component>, startPoint: Point, height: Int, groupWidthDeltaFraction: Float) {
var x = startPoint.x
components.asSequence().filter(Component::isVisible).forEach {
val minSize = it.minimumSize
val prefSize = it.preferredSize
val width = minSize.width + ((prefSize.width - minSize.width) * groupWidthDeltaFraction).toInt()
val size = Dimension(width, min(prefSize.height, height))
val y = startPoint.y + (height - size.height) / 2
val location = Point(x, y)
it.bounds = Rectangle(location, size)
x += size.width + gap.get()
}
}
}
private class LazyIdeToolTip(component: JComponent,
private val tipFactory: () -> JComponent)
: IdeTooltip(component, Point(0, 0), null, component) {
init {
isToCenter = true
layer = Balloon.Layer.top
preferredPosition = Balloon.Position.atRight
}
override fun beforeShow(): Boolean {
tipComponent = tipFactory()
return true
}
}
}
}
|
apache-2.0
|
d5ecf5c5eafc77692a8b698f13cea3e9
| 34.609113 | 159 | 0.642063 | 4.702027 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/base/compiler-configuration/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCommonCompilerArgumentsHolder.kt
|
4
|
3229
|
// 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.compiler.configuration
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import org.jdom.Element
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.setApiVersionToLanguageVersionIfNeeded
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.config.SettingConstants.KOTLIN_COMMON_COMPILER_ARGUMENTS_SECTION
@State(name = KOTLIN_COMMON_COMPILER_ARGUMENTS_SECTION, storages = [(Storage(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE))])
class KotlinCommonCompilerArgumentsHolder(project: Project) : BaseKotlinCompilerSettings<CommonCompilerArguments>(project) {
override fun getState(): Element {
return super.getState().apply {
dropVersionsIfNecessary(settings)
}
}
override fun loadState(state: Element) {
super.loadState(state)
update {
// To fix earlier configurations with incorrect combination of language and API version
setApiVersionToLanguageVersionIfNeeded()
detectVersionAutoAdvance()
}
}
fun updateLanguageAndApi(project: Project, modules: Array<Module>? = null) {
val kotlinFacetSettingsProvider = KotlinFacetSettingsProvider.getInstance(project)
val languageVersions = linkedSetOf<LanguageVersion>()
val apiVersions = linkedSetOf<LanguageVersion>()
for (module in modules ?: ModuleManager.getInstance(project).modules) {
if (module.isDisposed) continue
val settings = kotlinFacetSettingsProvider?.getSettings(module) ?: continue
if (settings.useProjectSettings) continue
settings.languageLevel?.let(languageVersions::add)
settings.apiLevel?.let(apiVersions::add)
}
val languageVersion = languageVersions.singleOrNull()
val apiVersion = apiVersions.singleOrNull()
update {
if (languageVersion != null) {
this.languageVersion = languageVersion.versionString
}
if (apiVersion != null) {
this.apiVersion = apiVersion.versionString
}
}
}
override fun createSettings() = CommonCompilerArguments.DummyImpl()
companion object {
/**
* @see org.jetbrains.kotlin.idea.facet.getInstance
*/
@JvmStatic
fun getInstance(project: Project): KotlinCommonCompilerArgumentsHolder = project.service()
}
}
fun isKotlinLanguageVersionConfigured(arguments: KotlinCommonCompilerArgumentsHolder): Boolean {
val settings = arguments.settings
return settings.languageVersion != null && settings.apiVersion != null
}
fun isKotlinLanguageVersionConfigured(project: Project): Boolean {
return isKotlinLanguageVersionConfigured(KotlinCommonCompilerArgumentsHolder.getInstance(project))
}
|
apache-2.0
|
893cc1590a3c6c0fd10585c10067dfe3
| 40.410256 | 127 | 0.726541 | 5.319605 | false | true | false | false |
WhisperSystems/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/custom/CustomChatColorCreatorFragment.kt
|
4
|
1605
|
package org.thoughtcrime.securesms.conversation.colors.ui.custom
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import org.thoughtcrime.securesms.R
class CustomChatColorCreatorFragment : Fragment(R.layout.custom_chat_color_creator_fragment) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
val tabLayout: TabLayout = view.findViewById(R.id.tab_layout)
val pager: ViewPager2 = view.findViewById(R.id.pager)
val adapter = CustomChatColorPagerAdapter(this, requireArguments())
val tabLayoutMediator = TabLayoutMediator(tabLayout, pager) { tab, position ->
tab.setText(
if (position == 0) {
R.string.CustomChatColorCreatorFragment__solid
} else {
R.string.CustomChatColorCreatorFragment__gradient
}
)
}
toolbar.setNavigationOnClickListener {
Navigation.findNavController(it).popBackStack()
}
pager.isUserInputEnabled = false
pager.adapter = adapter
if (Build.VERSION.SDK_INT < 21) {
tabLayout.visibility = View.GONE
} else {
tabLayoutMediator.attach()
}
val startPage = CustomChatColorCreatorFragmentArgs.fromBundle(requireArguments()).startPage
pager.setCurrentItem(startPage, false)
}
}
|
gpl-3.0
|
39dae7ba8d9c32e425d4ab1128c867b8
| 33.148936 | 95 | 0.748287 | 4.458333 | false | false | false | false |
iMeiji/Daily
|
app/src/main/java/com/meiji/daily/data/local/AppDatabase.kt
|
1
|
1388
|
package com.meiji.daily.data.local
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
import android.support.annotation.VisibleForTesting
import com.meiji.daily.bean.ZhuanlanBean
import com.meiji.daily.data.local.converter.ZhuanlanBeanConverter
import com.meiji.daily.data.local.dao.ZhuanlanDao
/**
* Created by Meiji on 2017/11/28.
*/
@Database(entities = [(ZhuanlanBean::class)], version = 1, exportSchema = false)
@TypeConverters(ZhuanlanBeanConverter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun zhuanlanDao(): ZhuanlanDao
companion object {
@VisibleForTesting
val DATABASE_NAME = "Daily"
@Volatile
private var sInstance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
if (sInstance == null) {
synchronized(AppDatabase::class.java) {
if (sInstance == null) {
sInstance = Room.databaseBuilder(context,
AppDatabase::class.java,
DATABASE_NAME
).build()
}
}
}
return sInstance!!
}
}
}
|
apache-2.0
|
48acf6b2224a98194818dad4d0a48da0
| 30.545455 | 80 | 0.631844 | 4.753425 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/ide/bookmark/ui/ContextMenuActionGroup.kt
|
2
|
2243
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.ui
import com.intellij.ide.bookmark.ui.tree.GroupNode
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Separator
import com.intellij.openapi.project.DumbAware
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.JTree
import javax.swing.tree.DefaultMutableTreeNode
internal class ContextMenuActionGroup(private val tree: JTree) : DumbAware, ActionGroup() {
override fun getChildren(event: AnActionEvent?): Array<AnAction> {
val paths = TreeUtil.getSelectedPathsIfAll(tree) { it.parentPath?.findFolderNode != null }
val actions = mutableListOf<AnAction>()
val addGroup: (String) -> Unit = {
val group = (CustomActionsSchema.getInstance().getCorrectedAction(it) as? ActionGroup)
if (group != null) actions.add(group)
}
if (paths != null) {
// Sub-item of a folder bookmark
val projectActions = (CustomActionsSchema.getInstance().getCorrectedAction("ProjectViewPopupMenu") as? ActionGroup)?.getChildren(event) ?: AnAction.EMPTY_ARRAY
actions.addAll(projectActions)
}
else {
// Bookmark item
addGroup("Bookmarks.ToolWindow.PopupMenu")
if ((TreeUtil.getSelectedPathIfOne(tree)?.lastPathComponent as? DefaultMutableTreeNode)?.userObject !is GroupNode) {
// Not a bookmark group: add some project view context menu actions
actions.add(Separator())
addGroup("AnalyzeMenu")
actions.add(Separator())
addGroup("ProjectViewPopupMenuRefactoringGroup")
actions.add(Separator())
addGroup("ProjectViewPopupMenuRunGroup")
actions.add(Separator())
addGroup("VersionControlsGroup")
actions.add(Separator())
val selectAction = CustomActionsSchema.getInstance().getCorrectedAction("SelectInProjectView")
if (selectAction != null) actions.add(selectAction)
}
}
return actions.toTypedArray()
}
}
|
apache-2.0
|
0a2c000d766ed8f6beb96d033416aa3b
| 42.134615 | 165 | 0.737851 | 4.586912 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/code-insight/intentions-shared/src/org/jetbrains/kotlin/idea/codeInsight/intentions/shared/RemoveUnnecessaryParenthesesIntention.kt
|
1
|
2230
|
// 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.codeInsight.intentions.shared
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.utils.appendSemicolonBeforeLambdaContainingElement
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
class RemoveUnnecessaryParenthesesIntention : SelfTargetingRangeIntention<KtParenthesizedExpression>(
KtParenthesizedExpression::class.java, KotlinBundle.lazyMessage("remove.unnecessary.parentheses")
) {
override fun applicabilityRange(element: KtParenthesizedExpression): TextRange? {
element.expression ?: return null
if (!KtPsiUtil.areParenthesesUseless(element)) return null
return element.textRange
}
override fun applyTo(element: KtParenthesizedExpression, editor: Editor?) {
val commentSaver = CommentSaver(element)
val innerExpression = element.expression ?: return
val binaryExpressionParent = element.parent as? KtBinaryExpression
val replaced = if (binaryExpressionParent != null &&
innerExpression is KtBinaryExpression &&
binaryExpressionParent.right == element
) {
binaryExpressionParent.replace(
KtPsiFactory(element).createExpressionByPattern(
"$0 $1 $2 $3 $4",
binaryExpressionParent.left!!.text,
binaryExpressionParent.operationReference.text,
innerExpression.left!!.text,
innerExpression.operationReference.text,
innerExpression.right!!.text,
)
)
} else
element.replace(innerExpression)
if (innerExpression.firstChild is KtLambdaExpression) {
KtPsiFactory(element).appendSemicolonBeforeLambdaContainingElement(replaced)
}
commentSaver.restore(replaced)
}
}
|
apache-2.0
|
5623938c734a6fd576f2bfb19e74ce31
| 44.510204 | 120 | 0.710314 | 5.64557 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSerializersImpl.kt
|
1
|
46746
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.openapi.components.ExpandMacroToPathMap
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.impl.ModulePathMacroManager
import com.intellij.openapi.components.impl.ProjectPathMacroManager
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.PathUtil
import com.intellij.util.containers.BidirectionalMap
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.ide.impl.FileInDirectorySourceNames
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.impl.reportErrorAndAttachStorage
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.util.JpsPathUtil
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.Collectors
class JpsProjectSerializersImpl(directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>,
moduleListSerializers: List<JpsModuleListSerializer>,
reader: JpsFileContentReader,
private val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>,
private val configLocation: JpsProjectConfigLocation,
private val externalStorageMapping: JpsExternalStorageMapping,
private val enableExternalStorage: Boolean,
private val virtualFileManager: VirtualFileUrlManager,
fileInDirectorySourceNames: FileInDirectorySourceNames) : JpsProjectSerializers {
private val lock = Any()
val moduleSerializers = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsModuleListSerializer>()
internal val serializerToDirectoryFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsDirectoryEntitiesSerializerFactory<*>>()
private val internalSourceToExternal = HashMap<JpsFileEntitySource, JpsFileEntitySource>()
internal val fileSerializersByUrl = BidirectionalMultiMap<String, JpsFileEntitiesSerializer<*>>()
internal val fileIdToFileName = Int2ObjectOpenHashMap<String>()
// Map of module serializer to boolean that defines whenever modules.xml is external or not
private val moduleSerializerToExternalSourceBool = mutableMapOf<JpsFileEntitiesSerializer<*>, Boolean>()
init {
synchronized(lock) {
for (factory in directorySerializersFactories) {
createDirectorySerializers(factory, fileInDirectorySourceNames).associateWithTo(serializerToDirectoryFactory) { factory }
}
val enabledModuleListSerializers = moduleListSerializers.filter { enableExternalStorage || !it.isExternalStorage }
val moduleFiles = enabledModuleListSerializers.flatMap { ser ->
ser.loadFileList(reader, virtualFileManager).map {
Triple(it.first, it.second, ser.isExternalStorage)
}
}
for ((moduleFile, moduleGroup, isOriginallyExternal) in moduleFiles) {
val directoryUrl = virtualFileManager.getParentVirtualUrl(moduleFile)!!
val internalSource =
bindExistingSource(fileInDirectorySourceNames, ModuleEntity::class.java, moduleFile.fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, moduleFile.fileName)
for (moduleListSerializer in enabledModuleListSerializers) {
val moduleSerializer = moduleListSerializer.createSerializer(internalSource, moduleFile, moduleGroup)
moduleSerializers[moduleSerializer] = moduleListSerializer
moduleSerializerToExternalSourceBool[moduleSerializer] = isOriginallyExternal
}
}
val allFileSerializers = entityTypeSerializers.filter { enableExternalStorage || !it.isExternalStorage } +
serializerToDirectoryFactory.keys + moduleSerializers.keys
allFileSerializers.forEach {
fileSerializersByUrl.put(it.fileUrl.url, it)
}
}
}
internal val directorySerializerFactoriesByUrl = directorySerializersFactories.associateBy { it.directoryUrl }
val moduleListSerializersByUrl = moduleListSerializers.associateBy { it.fileUrl }
private fun createFileInDirectorySource(directoryUrl: VirtualFileUrl, fileName: String): JpsFileEntitySource.FileInDirectory {
val source = JpsFileEntitySource.FileInDirectory(directoryUrl, configLocation)
// Don't convert to links[key] = ... because it *may* became autoboxing
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "createFileInDirectorySource: ${source.fileNameId}=$fileName" }
return source
}
private fun createDirectorySerializers(factory: JpsDirectoryEntitiesSerializerFactory<*>,
fileInDirectorySourceNames: FileInDirectorySourceNames): List<JpsFileEntitiesSerializer<*>> {
val osPath = JpsPathUtil.urlToOsPath(factory.directoryUrl)
val libPath = Paths.get(osPath)
val files = when {
Files.isDirectory(libPath) -> Files.list(libPath).use { stream ->
stream.filter { path: Path -> PathUtil.getFileExtension(path.toString()) == "xml" && Files.isRegularFile(path) }
.collect(Collectors.toList())
}
else -> emptyList()
}
return files.map {
val fileName = it.fileName.toString()
val directoryUrl = virtualFileManager.fromUrl(factory.directoryUrl)
val entitySource =
bindExistingSource(fileInDirectorySourceNames, factory.entityClass, fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", entitySource, virtualFileManager)
}
}
private fun bindExistingSource(fileInDirectorySourceNames: FileInDirectorySourceNames,
entityType: Class<out WorkspaceEntity>,
fileName: String,
directoryUrl: VirtualFileUrl): JpsFileEntitySource.FileInDirectory? {
val source = fileInDirectorySourceNames.findSource(entityType, fileName)
if (source == null || source.directory != directoryUrl) return null
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "bindExistingSource: ${source.fileNameId}=$fileName" }
return source
}
override fun reloadFromChangedFiles(change: JpsConfigurationFilesChange,
reader: JpsFileContentReader,
errorReporter: ErrorReporter): Pair<Set<EntitySource>, MutableEntityStorage> {
val obsoleteSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val newFileSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val addedFileUrls = change.addedFileUrls.flatMap {
val file = JpsPathUtil.urlToFile(it)
if (file.isDirectory) {
file.list()?.map { fileName -> "$it/$fileName" } ?: emptyList()
} else listOf(it)
}.toSet()
val affectedFileLoaders: LinkedHashSet<JpsFileEntitiesSerializer<*>>
val changedSources = HashSet<JpsFileEntitySource>()
synchronized(lock) {
for (addedFileUrl in addedFileUrls) {
// The file may already be processed during class initialization
if (fileSerializersByUrl.containsKey(addedFileUrl)) continue
val factory = directorySerializerFactoriesByUrl[PathUtil.getParentPath(addedFileUrl)]
val newFileSerializer = factory?.createSerializer(addedFileUrl, createFileInDirectorySource(
virtualFileManager.fromUrl(factory.directoryUrl), PathUtil.getFileName(addedFileUrl)), virtualFileManager)
if (newFileSerializer != null) {
newFileSerializers.add(newFileSerializer)
serializerToDirectoryFactory[newFileSerializer] = factory
}
}
for (changedUrl in change.changedFileUrls) {
val serializerFactory = moduleListSerializersByUrl[changedUrl]
if (serializerFactory != null) {
val newFileUrls = serializerFactory.loadFileList(reader, virtualFileManager)
val oldSerializers: List<JpsFileEntitiesSerializer<*>> = moduleSerializers.getKeysByValue(serializerFactory) ?: emptyList()
val oldFileUrls = oldSerializers.mapTo(HashSet()) { it.fileUrl }
val newFileUrlsSet = newFileUrls.mapTo(HashSet()) { it.first }
val obsoleteSerializersForFactory = oldSerializers.filter { it.fileUrl !in newFileUrlsSet }
obsoleteSerializersForFactory.forEach {
moduleSerializers.remove(it, serializerFactory)
moduleSerializerToExternalSourceBool.remove(it)
}
val newFileSerializersForFactory = newFileUrls.filter { it.first !in oldFileUrls }.map {
serializerFactory.createSerializer(createFileInDirectorySource(virtualFileManager.getParentVirtualUrl(it.first)!!,
it.first.fileName), it.first, it.second)
}
newFileSerializersForFactory.associateWithTo(moduleSerializerToExternalSourceBool) { serializerFactory.isExternalStorage }
newFileSerializersForFactory.associateWithTo(moduleSerializers) { serializerFactory }
obsoleteSerializers.addAll(obsoleteSerializersForFactory)
newFileSerializers.addAll(newFileSerializersForFactory)
}
}
for (newSerializer in newFileSerializers) {
fileSerializersByUrl.put(newSerializer.fileUrl.url, newSerializer)
}
for (obsoleteSerializer in obsoleteSerializers) {
fileSerializersByUrl.remove(obsoleteSerializer.fileUrl.url, obsoleteSerializer)
}
affectedFileLoaders = LinkedHashSet(newFileSerializers)
addedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
change.changedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
affectedFileLoaders.mapTo(changedSources) { it.internalEntitySource }
for (fileUrl in change.removedFileUrls) {
val directorySerializer = directorySerializerFactoriesByUrl[fileUrl]
if (directorySerializer != null) {
val serializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer)?.toList() ?: emptyList()
for (serializer in serializers) {
fileSerializersByUrl.removeValue(serializer)
obsoleteSerializers.add(serializer)
serializerToDirectoryFactory.remove(serializer, directorySerializer)
}
} else {
val obsolete = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
obsoleteSerializers.addAll(obsolete)
obsolete.forEach {
serializerToDirectoryFactory.remove(it)
}
}
}
obsoleteSerializers.mapTo(changedSources) { it.internalEntitySource }
obsoleteSerializers.asSequence().map { it.internalEntitySource }.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).forEach {
fileIdToFileName.remove(it.fileNameId)
LOG.debug { "remove association for ${it.fileNameId}" }
}
}
val builder = MutableEntityStorage.create()
affectedFileLoaders.forEach {
loadEntitiesAndReportExceptions(it, builder, reader, errorReporter)
}
return Pair(changedSources, builder)
}
override suspend fun loadAll(reader: JpsFileContentReader,
builder: MutableEntityStorage,
errorReporter: ErrorReporter,
project: Project?): List<EntitySource> {
val serializers = synchronized(lock) { fileSerializersByUrl.values.toList() }
val builders = coroutineScope {
serializers.map { serializer ->
async {
val result = MutableEntityStorage.create()
loadEntitiesAndReportExceptions(serializer, result, reader, errorReporter)
result
}
}
}.awaitAll()
val sourcesToUpdate = removeDuplicatingEntities(builders, serializers, project)
val squashedBuilder = squash(builders)
builder.addDiff(squashedBuilder)
return sourcesToUpdate
}
private fun loadEntitiesAndReportExceptions(serializer: JpsFileEntitiesSerializer<*>,
builder: MutableEntityStorage,
reader: JpsFileContentReader,
errorReporter: ErrorReporter) {
fun reportError(e: Exception, url: VirtualFileUrl) {
errorReporter.reportError(ProjectModelBundle.message("module.cannot.load.error", url.presentableUrl, e.localizedMessage), url)
}
try {
serializer.loadEntities(builder, reader, errorReporter, virtualFileManager)
}
catch (e: JDOMException) {
reportError(e, serializer.fileUrl)
}
catch (e: IOException) {
reportError(e, serializer.fileUrl)
}
}
// Check if the same module is loaded from different source. This may happen in case of two `modules.xml` with the same module.
// See IDEA-257175
// This code may be removed if we'll get rid of storing modules.xml and friends in external storage (cache/external_build_system)
private fun removeDuplicatingEntities(builders: List<MutableEntityStorage>, serializers: List<JpsFileEntitiesSerializer<*>>, project: Project?): List<EntitySource> {
if (project == null) return emptyList()
val modules = mutableMapOf<String, MutableList<Triple<ModuleId, MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>()
val libraries = mutableMapOf<LibraryId, MutableList<Pair<MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>()
val artifacts = mutableMapOf<ArtifactId, MutableList<Pair<MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>()
builders.forEachIndexed { i, builder ->
if (enableExternalStorage) {
builder.entities(ModuleEntity::class.java).forEach { module ->
val moduleId = module.symbolicId
modules.computeIfAbsent(moduleId.name.lowercase(Locale.US)) { ArrayList() }.add(Triple(moduleId, builder, serializers[i]))
}
}
builder.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }.forEach { library ->
libraries.computeIfAbsent(library.symbolicId) { ArrayList() }.add(builder to serializers[i])
}
builder.entities(ArtifactEntity::class.java).forEach { artifact ->
artifacts.computeIfAbsent(artifact.symbolicId) { ArrayList() }.add(builder to serializers[i])
}
}
val sourcesToUpdate = mutableListOf<EntitySource>()
for ((_, buildersWithModule) in modules) {
if (buildersWithModule.size <= 1) continue
var correctModuleFound = false
var leftModuleId = 0
// Leave only first module with "correct" entity source
// If there is no such module, leave the last one
buildersWithModule.forEachIndexed { index, (moduleId, builder, ser) ->
val originalExternal = moduleSerializerToExternalSourceBool[ser] ?: return@forEachIndexed
val moduleEntity = builder.resolve(moduleId)!!
if (index != buildersWithModule.lastIndex) {
if (!correctModuleFound && originalExternal) {
correctModuleFound = true
leftModuleId = index
}
else {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
}
else {
if (correctModuleFound) {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
else {
leftModuleId = index
}
}
}
reportIssue(project, buildersWithModule.mapTo(HashSet()) { it.first }, buildersWithModule.map { it.third }, leftModuleId)
}
for ((libraryId, buildersWithSerializers) in libraries) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(libraryId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(libraryId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val library = builder.resolve(libraryId)!!
val entitySource = library.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, library, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${libraryId.name}' library.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Libraries defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
for ((artifactId, buildersWithSerializers) in artifacts) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(artifactId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(artifactId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val artifact = builder.resolve(artifactId)!!
val entitySource = artifact.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, artifact, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${artifactId.name}' artifact.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Artifacts defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
return sourcesToUpdate
}
private fun reportIssue(project: Project, moduleIds: Set<ModuleId>, serializers: List<JpsFileEntitiesSerializer<*>>, leftModuleId: Int) {
var serializerCounter = -1
val attachments = mutableMapOf<String, Attachment>()
val serializersInfo = serializers.joinToString(separator = "\n\n") {
serializerCounter++
it as ModuleImlFileEntitiesSerializer
val externalFileUrl = it.let {
it.externalModuleListSerializer?.createSerializer(it.internalEntitySource, it.fileUrl, it.modulePath.group)
}?.fileUrl
val fileUrl = it.fileUrl
val internalModuleListSerializerUrl = it.internalModuleListSerializer?.fileUrl
val externalModuleListSerializerUrl = it.externalModuleListSerializer?.fileUrl
if (externalFileUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalFileUrl.url))) {
attachments[externalFileUrl.url] = AttachmentFactory.createAttachment(externalFileUrl.toPath(), false)
}
if (FileUtil.exists(JpsPathUtil.urlToPath(fileUrl.url))) {
attachments[fileUrl.url] = AttachmentFactory.createAttachment(fileUrl.toPath(), false)
}
if (internalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(internalModuleListSerializerUrl))) {
attachments[internalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(internalModuleListSerializerUrl)
), false)
}
if (externalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalModuleListSerializerUrl))) {
attachments[externalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(externalModuleListSerializerUrl)), false
)
}
"""
Serializer info #$serializerCounter:
Is external: ${moduleSerializerToExternalSourceBool[it]}
fileUrl: ${fileUrl.presentableUrl}
externalFileUrl: ${externalFileUrl?.presentableUrl}
internal modules.xml: $internalModuleListSerializerUrl
external modules.xml: $externalModuleListSerializerUrl
""".trimIndent()
}
val text = """
|Trying to load multiple modules with the same name.
|
|Project: ${project.name}
|Module: ${moduleIds.map { it.name }}
|Amount of modules: ${serializers.size}
|Leave module of nth serializer: $leftModuleId
|
|$serializersInfo
""".trimMargin()
LOG.error(text, *attachments.values.toTypedArray())
}
private fun squash(builders: List<MutableEntityStorage>): MutableEntityStorage {
var result = builders
while (result.size > 1) {
result = result.chunked(2) { list ->
val res = list.first()
if (list.size == 2) res.addDiff(list.last())
res
}
}
return result.singleOrNull() ?: MutableEntityStorage.create() }
@TestOnly
override fun saveAllEntities(storage: EntityStorage, writer: JpsFileContentWriter) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
val allSources = storage.entitiesBySource { true }.keys
saveEntities(storage, allSources, writer)
}
internal fun getActualFileUrl(source: EntitySource): String? {
val actualFileSource = getActualFileSource(source) ?: return null
return when (actualFileSource) {
is JpsFileEntitySource.ExactFile -> actualFileSource.file.url
is JpsFileEntitySource.FileInDirectory -> {
val fileName = fileIdToFileName.get(actualFileSource.fileNameId) ?: run {
// We have a situations when we don't have an association at for `fileIdToFileName` entity source returned from `getActualFileSource`
// but we have it for the original `JpsImportedEntitySource.internalFile` and base on it we try to calculate actual file url
if (source is JpsImportedEntitySource && source.internalFile is JpsFileEntitySource.FileInDirectory && source.storedExternally) {
fileIdToFileName.get((source.internalFile as JpsFileEntitySource.FileInDirectory).fileNameId)?.substringBeforeLast(".")?.let { "$it.xml" }
} else null
}
if (fileName != null) actualFileSource.directory.url + "/" + fileName else null
}
else -> error("Unexpected implementation of JpsFileEntitySource: ${actualFileSource.javaClass}")
}
}
private fun getActualFileSource(source: EntitySource): JpsFileEntitySource? {
return when (source) {
is JpsImportedEntitySource -> {
if (source.storedExternally) {
//todo remove obsolete entries
internalSourceToExternal.getOrPut(source.internalFile) { externalStorageMapping.getExternalSource(source.internalFile) }
}
else {
source.internalFile
}
}
else -> getInternalFileSource(source)
}
}
override fun getAllModulePaths(): List<ModulePath> {
synchronized(lock) {
return fileSerializersByUrl.values.filterIsInstance<ModuleImlFileEntitiesSerializer>().mapTo(LinkedHashSet()) { it.modulePath }.toList()
}
}
override fun saveEntities(storage: EntityStorage, affectedSources: Set<EntitySource>, writer: JpsFileContentWriter) {
val affectedModuleListSerializers = HashSet<JpsModuleListSerializer>()
val serializersToRun = HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>()
synchronized(lock) {
if (LOG.isTraceEnabled) {
LOG.trace("save entities; current serializers (${fileSerializersByUrl.values.size}):")
fileSerializersByUrl.values.forEach {
LOG.trace(it.toString())
}
}
val affectedEntityTypeSerializers = HashSet<JpsFileEntityTypeSerializer<*>>()
fun processObsoleteSource(fileUrl: String, deleteModuleFile: Boolean) {
val obsoleteSerializers = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
LOG.trace { "processing obsolete source $fileUrl: serializers = $obsoleteSerializers" }
obsoleteSerializers.forEach {
// Clean up module files content
val moduleListSerializer = moduleSerializers.remove(it)
if (moduleListSerializer != null) {
if (deleteModuleFile) {
moduleListSerializer.deleteObsoleteFile(fileUrl, writer)
}
LOG.trace { "affected module list: $moduleListSerializer" }
affectedModuleListSerializers.add(moduleListSerializer)
}
// Remove libraries under `.idea/libraries` folder
val directoryFactory = serializerToDirectoryFactory.remove(it)
if (directoryFactory != null) {
writer.saveComponent(fileUrl, directoryFactory.componentName, null)
}
// Remove libraries under `external_build_system/libraries` folder
if (it in entityTypeSerializers) {
if (getFilteredEntitiesForSerializer(it as JpsFileEntityTypeSerializer, storage).isEmpty()) {
it.deleteObsoleteFile(fileUrl, writer)
}
else {
affectedEntityTypeSerializers.add(it)
}
}
}
}
val sourcesStoredInternally = affectedSources.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { !it.storedExternally }
.associateBy { it.internalFile }
val internalSourcesOfCustomModuleEntitySources = affectedSources.mapNotNullTo(HashSet()) { (it as? CustomModuleEntitySource)?.internalSource }
/* Entities added via JPS and imported entities stored in internal storage must be passed to serializers together, otherwise incomplete
data will be stored.
It isn't necessary to save entities stored in external storage when their internal parts are affected, but add them to the list
to ensure that obsolete *.iml files will be removed if their modules are stored in external storage.
*/
val entitiesToSave = storage.entitiesBySource { source ->
source in affectedSources
|| source in sourcesStoredInternally
|| source is JpsImportedEntitySource && source.internalFile in affectedSources
|| source in internalSourcesOfCustomModuleEntitySources
|| source is CustomModuleEntitySource && source.internalSource in affectedSources
}
if (LOG.isTraceEnabled) {
LOG.trace("Affected sources: $affectedSources")
LOG.trace("Entities to save:")
for ((source, entities) in entitiesToSave) {
LOG.trace(" $source: $entities")
}
}
val internalSourceConvertedToImported = affectedSources.filterIsInstance<JpsImportedEntitySource>().mapTo(HashSet()) {
it.internalFile
}
val sourcesStoredExternally = entitiesToSave.keys.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { it.storedExternally }
.associateBy { it.internalFile }
val obsoleteSources = affectedSources - entitiesToSave.keys
LOG.trace { "Obsolete sources: $obsoleteSources" }
for (source in obsoleteSources) {
val fileUrl = getActualFileUrl(source)
if (fileUrl != null) {
val affectedImportedSourceStoredExternally = when {
source is JpsImportedEntitySource && source.storedExternally -> sourcesStoredInternally[source.internalFile]
source is JpsImportedEntitySource && !source.storedExternally -> sourcesStoredExternally[source.internalFile]
source is JpsFileEntitySource -> sourcesStoredExternally[source]
else -> null
}
// When user removes module from project we don't delete corresponding *.iml file located under project directory by default
// (because it may be included in other projects). However we do remove the module file if module actually wasn't removed, just
// its storage has been changed, e.g. if module was marked as imported from external system, or the place where module imported
// from external system was changed, or part of a module configuration is imported from external system and data stored in *.iml
// file was removed.
val deleteObsoleteFile = source in internalSourceConvertedToImported || (affectedImportedSourceStoredExternally != null &&
affectedImportedSourceStoredExternally !in obsoleteSources)
processObsoleteSource(fileUrl, deleteObsoleteFile)
val actualSource = if (source is JpsImportedEntitySource && !source.storedExternally) source.internalFile else source
if (actualSource is JpsFileEntitySource.FileInDirectory) {
fileIdToFileName.remove(actualSource.fileNameId)
LOG.debug { "remove association for obsolete source $actualSource" }
}
}
}
fun processNewlyAddedDirectoryEntities(entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
directorySerializerFactoriesByUrl.values.forEach { factory ->
val added = entitiesMap[factory.entityClass]
if (added != null) {
val newSerializers = createSerializersForDirectoryEntities(factory, added)
newSerializers.forEach {
serializerToDirectoryFactory[it.key] = factory
fileSerializersByUrl.put(it.key.fileUrl.url, it.key)
}
newSerializers.forEach { (serializer, entitiesMap) -> mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap) }
}
}
}
entitiesToSave.forEach { (source, entities) ->
val actualFileSource = getActualFileSource(source)
if (actualFileSource is JpsFileEntitySource.FileInDirectory) {
val fileNameByEntity = calculateFileNameForEntity(actualFileSource, source, entities)
val oldFileName = fileIdToFileName.get(actualFileSource.fileNameId)
if (oldFileName != fileNameByEntity) {
// Don't convert to links[key] = ... because it *may* became autoboxing
fileIdToFileName.put(actualFileSource.fileNameId, fileNameByEntity)
LOG.debug { "update association for ${actualFileSource.fileNameId} to $fileNameByEntity (was $oldFileName)" }
if (oldFileName != null) {
processObsoleteSource("${actualFileSource.directory.url}/$oldFileName", true)
}
val existingSerializers = fileSerializersByUrl.getValues("${actualFileSource.directory.url}/$fileNameByEntity").filter {
it in serializerToDirectoryFactory
}
if (existingSerializers.isNotEmpty()) {
val existingSources = existingSerializers.map { it.internalEntitySource }
val entitiesWithOldSource = storage.entitiesBySource { it in existingSources }
val entitiesSymbolicIds = entitiesWithOldSource.values
.flatMap { it.values }
.flatten()
.filterIsInstance<WorkspaceEntityWithSymbolicId>()
.joinToString(separator = "||") { "$it (SymbolicId: ${it.symbolicId})" }
//technically this is not an error, but cases when different entities have the same default file name are rare so let's report this
// as error for now to find real cause of IDEA-265327
val message = """
|Cannot save entities to $fileNameByEntity because it's already used for other entities;
|Current entity source: $actualFileSource
|Old file name: $oldFileName
|Existing serializers: $existingSerializers
|Their entity sources: $existingSources
|Entities with these sources in the storage: ${entitiesWithOldSource.mapValues { (_, value) -> value.values }}
|Entities with symbolic ids: $entitiesSymbolicIds
|Original entities to save: ${entities.values.flatten().joinToString(separator = "||") { "$it (Persistent Id: ${(it as? WorkspaceEntityWithSymbolicId)?.symbolicId})" }}
""".trimMargin()
reportErrorAndAttachStorage(message, storage)
}
if (existingSerializers.isEmpty() || existingSerializers.any { it.internalEntitySource != actualFileSource }) {
processNewlyAddedDirectoryEntities(entities)
}
}
}
val url = getActualFileUrl(source)
val internalSource = getInternalFileSource(source)
if (url != null && internalSource != null
&& (ModuleEntity::class.java in entities
|| FacetEntity::class.java in entities
|| ModuleGroupPathEntity::class.java in entities
|| ContentRootEntity::class.java in entities
|| SourceRootEntity::class.java in entities
|| ExcludeUrlEntity::class.java in entities
)) {
val existingSerializers = fileSerializersByUrl.getValues(url)
val moduleGroup = (entities[ModuleGroupPathEntity::class.java]?.first() as? ModuleGroupPathEntity)?.path?.joinToString("/")
if (existingSerializers.isEmpty() || existingSerializers.any { it is ModuleImlFileEntitiesSerializer && it.modulePath.group != moduleGroup }) {
moduleListSerializersByUrl.values.forEach { moduleListSerializer ->
if (moduleListSerializer.entitySourceFilter(source)) {
if (existingSerializers.isNotEmpty()) {
existingSerializers.forEach {
if (it is ModuleImlFileEntitiesSerializer) {
moduleSerializers.remove(it)
fileSerializersByUrl.remove(url, it)
}
}
}
val newSerializer = moduleListSerializer.createSerializer(internalSource, virtualFileManager.fromUrl(url), moduleGroup)
fileSerializersByUrl.put(url, newSerializer)
moduleSerializers[newSerializer] = moduleListSerializer
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
for (serializer in existingSerializers) {
val moduleListSerializer = moduleSerializers[serializer]
val storedExternally = moduleSerializerToExternalSourceBool[serializer]
if (moduleListSerializer != null && storedExternally != null &&
(moduleListSerializer.isExternalStorage == storedExternally && !moduleListSerializer.entitySourceFilter(source)
|| moduleListSerializer.isExternalStorage != storedExternally && moduleListSerializer.entitySourceFilter(source))) {
moduleSerializerToExternalSourceBool[serializer] = !storedExternally
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
}
entitiesToSave.forEach { (source, entities) ->
val serializers = fileSerializersByUrl.getValues(getActualFileUrl(source))
serializers.filter { it !is JpsFileEntityTypeSerializer }.forEach { serializer ->
mergeSerializerEntitiesMap(serializersToRun, serializer, entities)
}
}
for (serializer in entityTypeSerializers) {
if (entitiesToSave.any { serializer.mainEntityClass in it.value } || serializer in affectedEntityTypeSerializers) {
val entitiesMap = mutableMapOf(serializer.mainEntityClass to getFilteredEntitiesForSerializer(serializer, storage))
serializer.additionalEntityTypes.associateWithTo(entitiesMap) {
storage.entities(it).toList()
}
fileSerializersByUrl.put(serializer.fileUrl.url, serializer)
mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap)
}
}
}
if (affectedModuleListSerializers.isNotEmpty()) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
}
serializersToRun.forEach {
saveEntitiesBySerializer(it.key, it.value.mapValues { entitiesMapEntry -> entitiesMapEntry.value.toList() }, storage, writer)
}
}
override fun changeEntitySourcesToDirectoryBasedFormat(builder: MutableEntityStorage) {
for (factory in directorySerializerFactoriesByUrl.values) {
factory.changeEntitySourcesToDirectoryBasedFormat(builder, configLocation)
}
}
private fun mergeSerializerEntitiesMap(existingSerializer2EntitiesMap: HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>,
serializer: JpsFileEntitiesSerializer<*>,
entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
val existingEntitiesMap = existingSerializer2EntitiesMap.computeIfAbsent(serializer) { HashMap() }
entitiesMap.forEach { (type, entity) ->
val existingEntities = existingEntitiesMap.computeIfAbsent(type) { HashSet() }
existingEntities.addAll(entity)
}
}
private fun calculateFileNameForEntity(source: JpsFileEntitySource.FileInDirectory,
originalSource: EntitySource,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val directoryFactory = directorySerializerFactoriesByUrl[source.directory.url]
if (directoryFactory != null) {
return getDefaultFileNameForEntity(directoryFactory, entities)
}
if (ModuleEntity::class.java in entities
|| FacetEntity::class.java in entities
|| ContentRootEntity::class.java in entities
|| SourceRootEntity::class.java in entities
|| ExcludeUrlEntity::class.java in entities
) {
val moduleListSerializer = moduleListSerializersByUrl.values.find {
it.entitySourceFilter(originalSource)
}
if (moduleListSerializer != null) {
return getFileNameForModuleEntity(moduleListSerializer, entities)
}
}
return null
}
private fun <E : WorkspaceEntity> getDefaultFileNameForEntity(directoryFactory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
@Suppress("UNCHECKED_CAST") val entity = entities[directoryFactory.entityClass]?.singleOrNull() as? E ?: return null
return FileUtil.sanitizeFileName(directoryFactory.getDefaultFileName(entity)) + ".xml"
}
private fun getFileNameForModuleEntity(moduleListSerializer: JpsModuleListSerializer,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val entity = entities[ModuleEntity::class.java]?.singleOrNull() as? ModuleEntity
if (entity != null) {
return moduleListSerializer.getFileName(entity)
}
val contentRootEntity = entities[ContentRootEntity::class.java]?.firstOrNull() as? ContentRootEntity
if (contentRootEntity != null) {
return moduleListSerializer.getFileName(contentRootEntity.module)
}
val sourceRootEntity = entities[SourceRootEntity::class.java]?.firstOrNull() as? SourceRootEntity
if (sourceRootEntity != null) {
return moduleListSerializer.getFileName(sourceRootEntity.contentRoot.module)
}
val excludeUrlEntity = entities[ExcludeUrlEntity::class.java]?.firstOrNull() as? ExcludeUrlEntity
val module = excludeUrlEntity?.contentRoot?.module
if (module != null) {
return moduleListSerializer.getFileName(module)
}
val additionalEntity = entities[FacetEntity::class.java]?.firstOrNull() as? FacetEntity ?: return null
return moduleListSerializer.getFileName(additionalEntity.module)
}
private fun <E : WorkspaceEntity> getFilteredEntitiesForSerializer(serializer: JpsFileEntityTypeSerializer<E>,
storage: EntityStorage): List<E> {
return storage.entities(serializer.mainEntityClass).filter(serializer.entityFilter).toList()
}
private fun <E : WorkspaceEntity> saveEntitiesBySerializer(serializer: JpsFileEntitiesSerializer<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: EntityStorage,
writer: JpsFileContentWriter) {
@Suppress("UNCHECKED_CAST")
serializer.saveEntities(entities[serializer.mainEntityClass] as? Collection<E> ?: emptyList(), entities, storage, writer)
}
private fun <E : WorkspaceEntity> createSerializersForDirectoryEntities(factory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: List<WorkspaceEntity>)
: Map<JpsFileEntitiesSerializer<*>, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> {
val serializers = serializerToDirectoryFactory.getKeysByValue(factory) ?: emptyList()
val nameGenerator = UniqueNameGenerator(serializers) {
PathUtil.getFileName(it.fileUrl.url)
}
return entities.asSequence()
.filter { @Suppress("UNCHECKED_CAST") factory.entityFilter(it as E) }
.associate { entity ->
@Suppress("UNCHECKED_CAST")
val defaultFileName = FileUtil.sanitizeFileName(factory.getDefaultFileName(entity as E))
val fileName = nameGenerator.generateUniqueName(defaultFileName, "", ".xml")
val entityMap = mapOf<Class<out WorkspaceEntity>, List<WorkspaceEntity>>(factory.entityClass to listOf(entity))
val currentSource = entity.entitySource as? JpsFileEntitySource.FileInDirectory
val source =
if (currentSource != null && fileIdToFileName.get(currentSource.fileNameId) == fileName) currentSource
else createFileInDirectorySource(virtualFileManager.fromUrl(factory.directoryUrl), fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", source, virtualFileManager) to entityMap
}
}
private fun saveModulesList(it: JpsModuleListSerializer, storage: EntityStorage, writer: JpsFileContentWriter) {
LOG.trace("saving modules list")
it.saveEntitiesList(storage.entities(ModuleEntity::class.java), writer)
}
companion object {
private val LOG = logger<JpsProjectSerializersImpl>()
}
}
class CachingJpsFileContentReader(private val configLocation: JpsProjectConfigLocation) : JpsFileContentReader {
private val projectPathMacroManager = ProjectPathMacroManager.createInstance(
configLocation::projectFilePath,
{ JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) },
null
)
private val fileContentCache = ConcurrentHashMap<String, Map<String, Element>>()
override fun loadComponent(fileUrl: String, componentName: String, customModuleFilePath: String?): Element? {
val content = fileContentCache.computeIfAbsent(fileUrl + customModuleFilePath) {
loadComponents(fileUrl, customModuleFilePath)
}
return content[componentName]
}
override fun getExpandMacroMap(fileUrl: String): ExpandMacroToPathMap {
return getMacroManager(fileUrl, null).expandMacroMap
}
private fun loadComponents(fileUrl: String, customModuleFilePath: String?): Map<String, Element> {
val macroManager = getMacroManager(fileUrl, customModuleFilePath)
val file = Paths.get(JpsPathUtil.urlToPath(fileUrl))
return if (Files.isRegularFile(file)) loadStorageFile(file, macroManager) else emptyMap()
}
private fun getMacroManager(fileUrl: String,
customModuleFilePath: String?): PathMacroManager {
val path = JpsPathUtil.urlToPath(fileUrl)
return if (FileUtil.extensionEquals(fileUrl, "iml") || isExternalModuleFile(path)) {
ModulePathMacroManager.createInstance(configLocation::projectFilePath) { customModuleFilePath ?: path }
}
else {
projectPathMacroManager
}
}
}
internal fun Element.getAttributeValueStrict(name: String): String =
getAttributeValue(name) ?: throw JDOMException("Expected attribute $name under ${this.name} element")
fun isExternalModuleFile(filePath: String): Boolean {
val parentPath = PathUtil.getParentPath(filePath)
return FileUtil.extensionEquals(filePath, "xml") && PathUtil.getFileName(parentPath) == "modules"
&& PathUtil.getFileName(PathUtil.getParentPath(parentPath)) != ".idea"
}
internal fun getInternalFileSource(source: EntitySource) = when (source) {
is JpsFileDependentEntitySource -> source.originalSource
is CustomModuleEntitySource -> source.internalSource
is JpsFileEntitySource -> source
else -> null
}
|
apache-2.0
|
969f4195008dcff25609e4e8b63a0a81
| 50.710177 | 181 | 0.697792 | 5.845442 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveMethod/MoveKotlinMethodProcessor.kt
|
4
|
18661
|
// 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.refactoring.move.moveMethod
import com.intellij.ide.util.EditorHelper
import com.intellij.java.JavaBundle
import com.intellij.openapi.util.Ref
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.caches.resolve.*
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForExistingElement
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.Mover
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.util.getFactoryForImplicitReceiverWithSubtypeOf
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.tail
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isAncestorOf
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly
import org.jetbrains.kotlin.util.containingNonLocalDeclaration
class MoveKotlinMethodProcessor(
private val method: KtNamedFunction,
private val targetVariable: KtNamedDeclaration,
private val oldClassParameterNames: Map<KtClass, String>,
private val openInEditor: Boolean = false
) : BaseRefactoringProcessor(method.project) {
private val targetClassOrObject: KtClassOrObject = if (targetVariable is KtObjectDeclaration) targetVariable else
(targetVariable.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType?.constructor?.declarationDescriptor?.findPsi() as KtClass
private val factory = KtPsiFactory(myProject)
private val conflicts = MultiMap<PsiElement, String>()
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
return MoveMultipleElementsViewDescriptor(
arrayOf(method), (targetClassOrObject.fqName ?: JavaBundle.message("default.package.presentable.name")).toString()
)
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun findUsages(): Array<UsageInfo> {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Class(method.containingClassOrObject!!.fqName!!),
ContainerInfo.Class(targetClassOrObject.fqName!!)
)
val conflictChecker =
MoveConflictChecker(myProject, listOf(method), KotlinMoveTargetForExistingElement(targetClassOrObject), method)
val searchScope = myProject.projectScope()
val internalUsages = mutableSetOf<UsageInfo>()
val methodCallUsages = mutableSetOf<UsageInfo>()
methodCallUsages += ReferencesSearch.search(method, searchScope).mapNotNull { ref ->
createMoveUsageInfoIfPossible(ref, method, addImportToOriginalFile = true, isInternal = method.isAncestor(ref.element))
}
if (targetVariableIsMethodParameter()) {
internalUsages += ReferencesSearch.search(targetVariable, searchScope).mapNotNull { ref ->
createMoveUsageInfoIfPossible(ref, targetVariable, addImportToOriginalFile = false, isInternal = true)
}
}
internalUsages += method.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
traverseOuterInstanceReferences(method) { internalUsages += it }
conflictChecker.checkAllConflicts(
methodCallUsages.filter { it is KotlinMoveUsage && !it.isInternal }.toMutableSet(), internalUsages, conflicts
)
if (oldClassParameterNames.size > 1) {
for (usage in methodCallUsages.filter { it.element is KtNameReferenceExpression || it.element is PsiReferenceExpression }) {
conflicts.putValue(usage.element, KotlinBundle.message("text.references.to.outer.classes.have.to.be.added.manually"))
}
}
return (internalUsages + methodCallUsages).toTypedArray()
}
override fun performRefactoring(usages: Array<out UsageInfo>) {
val usagesToProcess = mutableListOf<UsageInfo>()
fun changeMethodSignature() {
if (targetVariableIsMethodParameter()) {
val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter)
method.valueParameterList?.removeParameter(parameterIndex)
}
for ((ktClass, parameterName) in oldClassParameterNames) {
method.valueParameterList?.addParameterBefore(
factory.createParameter("$parameterName: ${ktClass.nameAsSafeName.identifier}"),
method.valueParameters.firstOrNull()
)
}
}
fun KtNameReferenceExpression.getImplicitReceiver(): KtExpression? {
val scope = getResolutionScope(this.analyze()) ?: return null
val descriptor = this.resolveToCall()?.resultingDescriptor ?: return null
val receiverDescriptor = descriptor.extensionReceiverParameter
?: descriptor.dispatchReceiverParameter
?: return null
val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverDescriptor.type)
?: return null
val receiverText = if (expressionFactory.isImmediate) "this" else expressionFactory.expressionText
return factory.createExpression(receiverText)
}
fun escalateTargetVariableVisibilityIfNeeded(where: DeclarationDescriptor?, languageVersionSettings: LanguageVersionSettings) {
if (where == null || targetVariableIsMethodParameter()) return
val targetDescriptor = targetVariable.resolveToDescriptorIfAny() as? DeclarationDescriptorWithVisibility
?: return
if (!DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, where, languageVersionSettings) && method.manager.isInProject(targetVariable)) {
targetVariable.setVisibility(KtTokens.PUBLIC_KEYWORD)
}
}
fun correctMethodCall(expression: PsiElement) {
when (expression) {
is KtNameReferenceExpression -> {
val callExpression = expression.parent as? KtCallExpression ?: return
escalateTargetVariableVisibilityIfNeeded(
callExpression.containingNonLocalDeclaration()?.resolveToDescriptorIfAny(),
callExpression.getResolutionFacade().languageVersionSettings
)
val oldReceiver = callExpression.getQualifiedExpressionForSelector()?.receiverExpression
?: expression.getImplicitReceiver()
?: return
val newReceiver = if (targetVariable is KtObjectDeclaration) {
factory.createExpression(targetVariable.nameAsSafeName.identifier)
} else if (targetVariableIsMethodParameter()) {
val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter)
if (parameterIndex in callExpression.valueArguments.indices) {
val argumentExpression = callExpression.valueArguments[parameterIndex].getArgumentExpression()
?: return
callExpression.valueArgumentList?.removeArgument(parameterIndex)
argumentExpression
} else targetVariable.defaultValue
} else {
factory.createExpression("${oldReceiver.text}.${targetVariable.nameAsSafeName.identifier}")
} ?: return
if (method.containingClassOrObject in oldClassParameterNames) {
callExpression.valueArgumentList?.addArgumentBefore(
factory.createArgument(oldReceiver),
callExpression.valueArguments.firstOrNull()
)
}
val resultingExpression = callExpression.getQualifiedExpressionForSelectorOrThis()
.replace(factory.createExpressionByPattern("$0.$1", newReceiver.text, callExpression))
if (targetVariable is KtObjectDeclaration) {
val ref = (resultingExpression as? KtQualifiedExpression)?.receiverExpression?.mainReference ?: return
createMoveUsageInfoIfPossible(
ref, targetClassOrObject, addImportToOriginalFile = true,
isInternal = targetClassOrObject.isAncestor(ref.element)
)?.let { usagesToProcess += it }
}
}
is PsiReferenceExpression -> {
val callExpression = expression.parent as? PsiMethodCallExpression ?: return
val oldReceiver = callExpression.methodExpression.qualifierExpression ?: return
val newReceiver = if (targetVariable is KtObjectDeclaration) {
// todo: fix usage of target object (import might be needed)
val targetObjectName = targetVariable.fqName?.tail(targetVariable.containingKtFile.packageFqName)?.toString()
?: targetVariable.nameAsSafeName.identifier
JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("$targetObjectName.INSTANCE", null)
} else if (targetVariableIsMethodParameter()) {
val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter)
val arguments = callExpression.argumentList.expressions
if (parameterIndex in arguments.indices) {
val argumentExpression = arguments[parameterIndex].copy() ?: return
arguments[parameterIndex].delete()
argumentExpression
} else return
} else {
val getterName = "get${targetVariable.nameAsSafeName.identifier.capitalizeAsciiOnly()}"
JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("${oldReceiver.text}.$getterName()", null)
}
if (method.containingClassOrObject in oldClassParameterNames) {
callExpression.argumentList.addBefore(oldReceiver, callExpression.argumentList.expressions.firstOrNull())
}
oldReceiver.replace(newReceiver)
}
}
}
fun replaceReferenceToTargetWithThis(element: KtExpression) {
val scope = element.getResolutionScope(element.analyze()) ?: return
val receivers = scope.getImplicitReceiversHierarchy()
val receiverText =
if (receivers.isEmpty() || receivers[0].containingDeclaration == method.containingClassOrObject?.resolveToDescriptorIfAny())
"this" else "this@${targetClassOrObject.nameAsSafeName.identifier}"
element.replace(factory.createExpression(receiverText))
}
val (methodCallUsages, internalUsages) = usages.partition { it is MoveRenameUsageInfo && it.referencedElement == method }
val newInternalUsages = mutableListOf<UsageInfo>()
val oldInternalUsages = mutableListOf<UsageInfo>()
try {
for (usage in methodCallUsages) {
usage.element?.let { element ->
correctMethodCall(element)
}
}
for (usage in internalUsages) {
val element = usage.element ?: continue
if (usage is MoveRenameUsageInfo) {
if (usage.referencedElement == targetVariable && element is KtNameReferenceExpression) {
replaceReferenceToTargetWithThis(element)
} else {
oldInternalUsages += usage
}
}
if (usage is SourceInstanceReferenceUsageInfo) {
if (usage.member == targetVariable && element is KtNameReferenceExpression) {
replaceReferenceToTargetWithThis(
(element as? KtThisExpression)?.getQualifiedExpressionForReceiver() ?: element
)
} else {
val receiverText = oldClassParameterNames[usage.sourceOrOuter] ?: continue
when (element) {
is KtThisExpression -> element.replace(factory.createExpression(receiverText))
is KtNameReferenceExpression -> {
val elementToReplace = (element.parent as? KtCallExpression) ?: element
elementToReplace.replace(factory.createExpressionByPattern("$0.$1", receiverText, elementToReplace))
}
}
}
}
}
changeMethodSignature()
markInternalUsages(oldInternalUsages)
val movedMethod = Mover.Default(method, targetClassOrObject)
val oldToNewMethodMap = mapOf<PsiElement, PsiElement>(method to movedMethod)
newInternalUsages += restoreInternalUsages(movedMethod, oldToNewMethodMap)
usagesToProcess += newInternalUsages
postProcessMoveUsages(usagesToProcess, oldToNewMethodMap)
if (openInEditor) EditorHelper.openInEditor(movedMethod)
} catch (e: IncorrectOperationException) {
} finally {
cleanUpInternalUsages(oldInternalUsages + newInternalUsages)
}
}
private fun targetVariableIsMethodParameter(): Boolean = targetVariable is KtParameter && !targetVariable.hasValOrVar()
override fun getCommandName(): String = KotlinBundle.message("title.move.method")
}
internal fun getThisClassesToMembers(method: KtNamedFunction) = traverseOuterInstanceReferences(method)
internal fun KtNamedDeclaration.type() = (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType
internal fun KtClass.defaultType() = resolveToDescriptorIfAny()?.defaultType
private fun traverseOuterInstanceReferences(
method: KtNamedFunction,
body: (SourceInstanceReferenceUsageInfo) -> Unit = {}
): Map<KtClass, MutableSet<KtNamedDeclaration>> {
val context = method.analyzeWithContent()
val containingClassOrObject = method.containingClassOrObject ?: return emptyMap()
val descriptor = containingClassOrObject.unsafeResolveToDescriptor()
fun getClassOrObjectAndMemberReferencedBy(reference: KtExpression): Pair<DeclarationDescriptor?, CallableDescriptor?> {
var classOrObjectDescriptor: DeclarationDescriptor? = null
var memberDescriptor: CallableDescriptor? = null
if (reference is KtThisExpression) {
classOrObjectDescriptor = context[BindingContext.REFERENCE_TARGET, reference.instanceReference]
if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) {
memberDescriptor =
reference.getQualifiedExpressionForReceiver()?.selectorExpression?.getResolvedCall(context)?.resultingDescriptor
}
}
if (reference is KtNameReferenceExpression) {
val dispatchReceiver = reference.getResolvedCall(context)?.dispatchReceiver as? ImplicitReceiver
classOrObjectDescriptor = dispatchReceiver?.declarationDescriptor
if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) {
memberDescriptor = reference.getResolvedCall(context)?.resultingDescriptor
}
}
return classOrObjectDescriptor to memberDescriptor
}
val thisClassesToMembers = mutableMapOf<KtClass, MutableSet<KtNamedDeclaration>>()
method.bodyExpression?.forEachDescendantOfType<KtExpression> { reference ->
val (classOrObjectDescriptor, memberDescriptor) = getClassOrObjectAndMemberReferencedBy(reference)
(classOrObjectDescriptor?.findPsi() as? KtClassOrObject)?.let { resolvedClassOrObject ->
val resolvedMember = memberDescriptor?.findPsi() as? KtNamedDeclaration
if (resolvedClassOrObject is KtClass) {
if (resolvedClassOrObject in thisClassesToMembers) thisClassesToMembers[resolvedClassOrObject]?.add(
resolvedMember
?: resolvedClassOrObject
)
else thisClassesToMembers[resolvedClassOrObject] = mutableSetOf(resolvedMember ?: resolvedClassOrObject)
}
body(SourceInstanceReferenceUsageInfo(reference, resolvedClassOrObject, resolvedMember))
}
}
return thisClassesToMembers
}
internal class SourceInstanceReferenceUsageInfo(
reference: KtExpression, val sourceOrOuter: KtClassOrObject, val member: KtNamedDeclaration?
) : UsageInfo(reference)
|
apache-2.0
|
467161cac289a72eafe264e2dd860681
| 53.564327 | 167 | 0.675634 | 6.272605 | false | false | false | false |
YutaKohashi/FakeLineApp
|
app/src/main/java/jp/yuta/kohashi/fakelineapp/models/TalkItem.kt
|
1
|
1784
|
package jp.yuta.kohashi.fakelineapp.models
import android.os.Parcel
import android.os.Parcelable
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 19 / 08 / 2017
*/
/**
* トークページの一つ一つのセル
*/
class TalkItem(text: String, time: String, isRead: Boolean, imgPath: String, writerType: WriterType, cellType: CellType) : Parcelable {
var text: String? = text
var time: String? = time
var isRead: Boolean = isRead
var imgPath: String = imgPath
var writerType: WriterType = writerType
var cellType: CellType = cellType
enum class WriterType(val num: Int) {
YOU(0), ME(1), DATE(3);
companion object {
fun from(findValue: Int): WriterType =WriterType.values().first { it.num == findValue }
}
}
enum class CellType {
TEXT, IMAGE, STAMP
}
constructor(source: Parcel) : this(
source.readString(),
source.readString(),
1 == source.readInt(),
source.readString(),
WriterType.values()[source.readInt()],
CellType.values()[source.readInt()]
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(text)
writeString(time)
writeInt((if (isRead) 1 else 0))
writeString(imgPath)
writeInt(writerType.ordinal)
writeInt(cellType.ordinal)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<TalkItem> = object : Parcelable.Creator<TalkItem> {
override fun createFromParcel(source: Parcel): TalkItem = TalkItem(source)
override fun newArray(size: Int): Array<TalkItem?> = arrayOfNulls(size)
}
}
}
|
mit
|
6c3f139b94c5bcea32f8e51c81545c85
| 25.621212 | 135 | 0.61959 | 4.074246 | false | false | false | false |
jk1/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/hints/AnnotationHintsPass.kt
|
2
|
3759
|
// 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.codeInsight.hints
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.codeInsight.InferredAnnotationsManager
import com.intellij.codeInsight.daemon.impl.HintRenderer
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifierListOwner
class AnnotationHintsPass(
rootElement: PsiElement, editor: Editor,
modificationStampHolder: ModificationStampHolder
) : ElementProcessingHintPass(rootElement, editor, modificationStampHolder) {
override fun isAvailable(virtualFile: VirtualFile): Boolean =
(CodeInsightSettings.getInstance().SHOW_EXTERNAL_ANNOTATIONS_INLINE
&& ExternalAnnotationsManager.getInstance(myProject).hasAnnotationRootsForFile(virtualFile))
|| CodeInsightSettings.getInstance().SHOW_INFERRED_ANNOTATIONS_INLINE
override fun collectElementHints(element: PsiElement, collector: (offset: Int, hint: String) -> Unit) {
if (element is PsiModifierListOwner) {
var annotations = emptySequence<PsiAnnotation>()
if (CodeInsightSettings.getInstance().SHOW_EXTERNAL_ANNOTATIONS_INLINE) {
annotations += ExternalAnnotationsManager.getInstance(myProject).findExternalAnnotations(element).orEmpty()
}
if (CodeInsightSettings.getInstance().SHOW_INFERRED_ANNOTATIONS_INLINE) {
annotations += InferredAnnotationsManager.getInstance(myProject).findInferredAnnotations(element)
}
val shownAnnotations = mutableSetOf<String>()
annotations.forEach {
val nameReferenceElement = it.nameReferenceElement
if (nameReferenceElement != null && element.modifierList != null &&
(shownAnnotations.add(nameReferenceElement.qualifiedName) || JavaDocInfoGenerator.isRepeatableAnnotationType(it))) {
val offset = element.modifierList!!.textRange.startOffset
collector.invoke(offset, "@" + nameReferenceElement.referenceName + it.parameterList.text)
}
}
}
}
override fun getHintKey(): Key<Boolean> = ANNOTATION_INLAY_KEY
override fun createRenderer(text: String): HintRenderer = AnnotationHintRenderer(text)
companion object {
private val ANNOTATION_INLAY_KEY = Key.create<Boolean>("ANNOTATION_INLAY_KEY")
}
private class AnnotationHintRenderer(text: String) : HintRenderer(text) {
override fun getContextMenuGroupId() = "AnnotationHintsContextMenu"
}
class ToggleExternalAnnotationsHintsAction : ToggleAction() {
override fun isSelected(e: AnActionEvent?): Boolean = CodeInsightSettings.getInstance().SHOW_EXTERNAL_ANNOTATIONS_INLINE
override fun setSelected(e: AnActionEvent?, state: Boolean) {
CodeInsightSettings.getInstance().SHOW_EXTERNAL_ANNOTATIONS_INLINE = state
AnnotationHintsPassFactory.modificationStampHolder.forceHintsUpdateOnNextPass()
}
}
class ToggleInferredAnnotationsHintsAction : ToggleAction() {
override fun isSelected(e: AnActionEvent?): Boolean = CodeInsightSettings.getInstance().SHOW_INFERRED_ANNOTATIONS_INLINE
override fun setSelected(e: AnActionEvent?, state: Boolean) {
CodeInsightSettings.getInstance().SHOW_INFERRED_ANNOTATIONS_INLINE = state
AnnotationHintsPassFactory.modificationStampHolder.forceHintsUpdateOnNextPass()
}
}
}
|
apache-2.0
|
44cf37abced5fc4e254ed020040d4533
| 47.205128 | 140 | 0.784251 | 5.066038 | false | false | false | false |
CzBiX/v2ex-android
|
app/src/main/kotlin/com/czbix/v2ex/network/V2exService.kt
|
1
|
3335
|
package com.czbix.v2ex.network
import com.czbix.v2ex.db.Comment
import com.czbix.v2ex.model.*
import com.czbix.v2ex.parser.Parser
import com.czbix.v2ex.parser.TopicParser
import com.czbix.v2ex.util.TrackerUtils
import com.google.common.base.Stopwatch
import okhttp3.FormBody
import okhttp3.internal.EMPTY_REQUEST
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.system.measureTimeMillis
class V2exService @Inject constructor(
private val helper: RequestHelper
) {
suspend fun getTopic(topic: Topic, page: Int): TopicResponse {
require(page > 0) {
"Page must greater than zero"
}
Timber.d("Request topic with comments, topic: %s, page: %d", topic, page)
val request = helper.newRequest(useMobile = true)
.url(topic.url + "?p=" + page)
.build()
val html = helper.sendRequestSuspend(request) { response ->
check(!response.isRedirect) {
"Topic page shouldn't redirect"
}
response.body!!.string()
}
val doc = Parser.toDoc(html)
helper.processUserState(doc, Parser.PageType.Topic)
lateinit var result: TopicResponse
val measureTime = measureTimeMillis {
result = TopicParser.parseDoc(doc, topic, page)
}
TrackerUtils.onParseTopic(measureTime, result.comments.size)
return result
}
suspend fun postComment(topic: Topic, content: String, onceToken: String) {
Timber.d("Post comment to topic: %s", topic)
// @Suppress("NAME_SHADOWING")
// val onceToken = onceToken ?: helper.getOnceToken().await()
val requestBody = FormBody.Builder()
.add("once", onceToken)
.add("content", content.replace("\n", "\r\n"))
.build()
val request = RequestHelper.newRequest(useMobile = true)
.url(topic.url)
.post(requestBody).build()
helper.sendRequestSuspend(request, false) { response ->
// v2ex will redirect if reply success
check(response.isRedirect)
}
}
suspend fun favor(favable: Favable, bool: Boolean, csrfToken: String) {
Timber.d("Favorite %s, bool: %s", favable, bool)
val url = if (bool) favable.getFavUrl(csrfToken) else favable.getUnFavUrl(csrfToken)
val request = RequestHelper.newRequest().url(url)
.build()
helper.sendRequestSuspend(request, false) { response ->
check(response.isRedirect)
}
}
suspend fun thank(obj: Thankable, onceToken: String) {
Timber.d("Thank %s", obj)
val request = RequestHelper.newRequest().apply {
url(obj.thankUrl + "?once=" + onceToken)
post(EMPTY_REQUEST)
}.build()
helper.sendRequestSuspend(request)
}
suspend fun ignore(obj: Ignorable, onceToken: String) {
Timber.d("Ignore %s", obj)
val builder = RequestHelper.newRequest().url(obj.ignoreUrl + "?once=" + onceToken)
val isComment = obj is Comment
if (isComment) {
builder.post(EMPTY_REQUEST)
}
val request = builder.build()
helper.sendRequestSuspend(request, isComment) {}
}
}
|
apache-2.0
|
63a65555711fec63a0ab2f8d47d44a21
| 30.471698 | 92 | 0.617091 | 4.107143 | false | false | false | false |
javecs/text2expr
|
src/test/kotlin/xyz/javecs/tools/text2expr/test/kotlin/templates/SimpleExprTest.kt
|
1
|
735
|
package xyz.javecs.tools.text2expr.test.kotlin.templates
import org.junit.Test
import xyz.javecs.tools.text2expr.Text2Expr
import kotlin.test.assertEquals
class SimpleExprTest {
@Test fun simpleExpr1() {
val expected = """
|答えは、
|151.27796
""".trimMargin("|")
val text2Expr = Text2Expr()
assertEquals(expected, text2Expr.eval("94マイルは何キロメートルですか?", rendered = true))
}
@Test fun simpleExpr2() {
val expected = """
|151.27796
""".trimMargin("|")
val text2Expr = Text2Expr()
assertEquals(expected, text2Expr.eval("94マイルは何キロメートルですか?", rendered = false))
}
}
|
mit
|
9e8167e3156971b39d87035e384ac789
| 26.5 | 85 | 0.628225 | 3.311558 | false | true | false | false |
onnerby/musikcube
|
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/util/Duration.kt
|
2
|
686
|
package io.casey.musikcube.remote.ui.shared.util
import java.util.*
object Duration {
fun format(seconds: Double): String {
val mins = seconds.toInt() / 60
val secs = seconds.toInt() - mins * 60
return String.format(Locale.getDefault(), "%d:%02d", mins, secs)
}
fun formatWithHours(seconds: Double): String {
return when(val hours = seconds.toInt() / 3600) {
0 -> format(seconds)
else -> {
val mins = (seconds.toInt() % 3600) / 60
val secs = (seconds.toInt() % 60)
String.format(Locale.getDefault(), "%d:%02d:%02d", hours, mins, secs)
}
}
}
}
|
bsd-3-clause
|
e95d1f6d0f7dee25bbfcecb85a142836
| 30.181818 | 85 | 0.542274 | 3.897727 | false | false | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/api/widgetsDataPlotting.kt
|
2
|
2305
|
package imgui.api
import glm_.vec2.Vec2
import imgui.ImGui.plotEx
import imgui.internal.sections.PlotType
interface widgetsDataPlotting {
fun plotLines(label: String, values: FloatArray, valuesOffset: Int = 0, overlayText: String = "", scaleMin: Float = Float.MAX_VALUE,
scaleMax: Float = Float.MAX_VALUE, graphSize: Vec2 = Vec2(), stride: Int = 1) =
plotEx(PlotType.Lines, label, PlotArrayData(values, stride), valuesOffset, overlayText, scaleMin, scaleMax, graphSize)
fun plotLines(label: String, valuesGetter: (idx: Int) -> Float, valuesCount: Int, valuesOffset: Int = 0,
overlayText: String = "", scaleMin: Float = Float.MAX_VALUE, scaleMax: Float = Float.MAX_VALUE,
graphSize: Vec2 = Vec2()) =
plotEx(PlotType.Lines, label, PlotArrayFunc(valuesGetter, valuesCount), valuesOffset, overlayText, scaleMin, scaleMax, graphSize)
fun plotHistogram(label: String, values: FloatArray, valuesOffset: Int = 0, overlayText: String = "",
scaleMin: Float = Float.MAX_VALUE, scaleMax: Float = Float.MAX_VALUE, graphSize: Vec2 = Vec2(), stride: Int = 1) =
plotEx(PlotType.Histogram, label, PlotArrayData(values, stride), valuesOffset, overlayText, scaleMin, scaleMax, graphSize)
fun plotHistogram(label: String, valuesGetter: (idx: Int) -> Float, valuesCount: Int, valuesOffset: Int = 0,
overlayText: String = "", scaleMin: Float = Float.MAX_VALUE, scaleMax: Float = Float.MAX_VALUE,
graphSize: Vec2 = Vec2()) =
plotEx(PlotType.Histogram, label, PlotArrayFunc(valuesGetter, valuesCount), valuesOffset, overlayText, scaleMin, scaleMax, graphSize)
companion object {
interface PlotArray {
operator fun get(idx: Int): Float
fun count(): Int
}
class PlotArrayData(val values: FloatArray, val stride: Int) : PlotArray {
override operator fun get(idx: Int): Float = values[idx * stride]
override fun count(): Int = values.size
}
class PlotArrayFunc(val func: (Int) -> Float, val count: Int) : PlotArray {
override operator fun get(idx: Int): Float = func(idx)
override fun count(): Int = count
}
}
}
|
mit
|
530873d003f0b726456b954707d2fb5a
| 51.409091 | 145 | 0.646421 | 3.887015 | false | false | false | false |
lucasgcampos/kotlin-for-android-developers
|
KotlinAndroid/app/src/main/java/com/lucasgcampos/kotlinandroid/data/server/ForecastRequest.kt
|
1
|
598
|
package com.lucasgcampos.kotlinandroid.data.server
import com.google.gson.Gson
import java.net.URL
class ForecastRequest(val zipCode: Long) {
companion object {
private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce"
private val URL = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=metric&cnt=7"
private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
}
fun execute(): ForecastResult {
val forecastJsonStr = URL(COMPLETE_URL + zipCode).readText()
return Gson().fromJson(forecastJsonStr, ForecastResult::class.java)
}
}
|
mit
|
0503760f0845e35a6d2b75aa6b8a150e
| 32.222222 | 110 | 0.704013 | 3.378531 | false | false | false | false |
mdanielwork/intellij-community
|
plugins/settings-repository/src/git/CommitMessageFormatter.kt
|
5
|
2436
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import org.eclipse.jgit.lib.Ref
import org.eclipse.jgit.merge.MergeMessageFormatter
import java.net.InetAddress
interface CommitMessageFormatter {
fun message(text: String): String = text
fun prependMessage(builder: StringBuilder = StringBuilder()): StringBuilder = builder
fun mergeMessage(refsToMerge: List<Ref>, target: Ref): String = MergeMessageFormatter().format(refsToMerge, target)
}
class IdeaCommitMessageFormatter : CommitMessageFormatter {
override fun message(text: String): String = StringBuilder().appendCommitOwnerInfo().append(text).toString()
override fun prependMessage(builder: StringBuilder): StringBuilder = builder.appendCommitOwnerInfo()
override fun mergeMessage(refsToMerge: List<Ref>, target: Ref): String = StringBuilder().appendCommitOwnerInfo().append(super.mergeMessage(refsToMerge, target)).toString()
fun StringBuilder.appendCommitOwnerInfo(avoidAppInfoInstantiation: Boolean = false): StringBuilder {
if (avoidAppInfoInstantiation) {
append(ApplicationNamesInfo.getInstance().productName)
}
else {
appendAppName()
}
append(' ').append('<').append(System.getProperty("user.name", "unknown-user")).append('@').append(InetAddress.getLocalHost().hostName)
append(' ')
return this
}
fun StringBuilder.appendAppName() {
val appInfo = ApplicationInfoEx.getInstanceEx()
if (appInfo != null) {
val build = appInfo.build
append(build.productCode).append('-')
if (appInfo.majorVersion != null && !appInfo.isEAP) {
append(appInfo.fullVersion)
}
else {
append(build.asStringWithoutProductCodeAndSnapshot())
}
}
}
}
|
apache-2.0
|
4eff28a19aaaaffe97f9e7f333b7eef5
| 37.078125 | 173 | 0.743432 | 4.527881 | false | false | false | false |
spotify/heroic
|
heroic-component/src/main/java/com/spotify/heroic/suggest/MatchOptions.kt
|
1
|
1988
|
/*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"): you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.suggest
data class MatchOptions(
val fuzzy: Boolean,
val fuzzyPrefixLength: Int,
val fuzzyMaxExpansions: Int,
val tokenize: Boolean
) {
data class Builder(
var fuzzy: Boolean = false,
var fuzzyPrefixLength: Int = 2,
var fuzzyMaxExpansions: Int = 20,
var tokenize: Boolean = false
) {
fun build(): MatchOptions {
return MatchOptions(fuzzy, fuzzyPrefixLength, fuzzyMaxExpansions, tokenize)
}
fun fuzzy(fuzzy: Boolean): Builder {
this.fuzzy = fuzzy
return this
}
fun fuzzyPrefixLength(fuzzyPrefixLength: Int): Builder {
this.fuzzyPrefixLength = fuzzyPrefixLength
return this
}
fun fuzzyMaxExpansions(fuzzyMaxExpansions: Int): Builder {
this.fuzzyMaxExpansions = fuzzyMaxExpansions
return this
}
fun tokenize(tokenize: Boolean): Builder {
this.tokenize = tokenize
return this
}
}
companion object {
@JvmStatic fun builder(): Builder = Builder()
}
}
|
apache-2.0
|
a00d2a852668f539b0c01f33fc2807a9
| 30.0625 | 87 | 0.65996 | 4.591224 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/me/drakeet/support/toast/ToastCompat.kt
|
1
|
5947
|
/*
original implementation is https://github.com/PureWriter/ToastCompat
modification:
- convert from Java to Kotlin
- because Android 11's Toast.getView() returns null, we need to support view==null case.
- only in case of API 25 device, we have to create custom context and set it to view.
*/
package me.drakeet.support.toast
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Resources
import android.util.Log
import android.view.Display
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.WindowManager.BadTokenException
import android.widget.Toast
import androidx.annotation.StringRes
import jp.juggler.util.LogCategory
fun interface BadTokenListener {
fun onBadTokenCaught(toast: Toast)
}
internal class SafeToastContext(base: Context, private val toast: Toast) : ContextWrapper(base) {
companion object {
private const val TAG = "WindowManagerWrapper"
}
private var badTokenListener: BadTokenListener? = null
fun setBadTokenListener(badTokenListener: BadTokenListener?) {
this.badTokenListener = badTokenListener
}
override fun getApplicationContext(): Context =
ApplicationContextWrapper(baseContext.applicationContext)
private inner class ApplicationContextWrapper(base: Context) : ContextWrapper(base) {
override fun getSystemService(name: String): Any? =
if (WINDOW_SERVICE == name) {
// noinspection ConstantConditions
WindowManagerWrapper(baseContext.getSystemService(name) as WindowManager)
} else {
super.getSystemService(name)
}
}
private inner class WindowManagerWrapper(private val base: WindowManager) : WindowManager {
@Suppress("DEPRECATION")
@Deprecated("Use Context.getDisplay() instead.")
override fun getDefaultDisplay(): Display? =
base.defaultDisplay
override fun removeViewImmediate(view: View) =
base.removeViewImmediate(view)
override fun updateViewLayout(view: View, params: ViewGroup.LayoutParams) =
base.updateViewLayout(view, params)
override fun removeView(view: View) =
base.removeView(view)
override fun addView(view: View, params: ViewGroup.LayoutParams) {
try {
Log.d(TAG, "WindowManager's addView(view, params) has been hooked.")
base.addView(view, params)
} catch (e: BadTokenException) {
e.message?.let { Log.i(TAG, it) }
badTokenListener?.onBadTokenCaught(toast)
} catch (throwable: Throwable) {
Log.e(TAG, "[addView]", throwable)
}
}
}
}
@Suppress("TooManyFunctions")
class ToastCompat private constructor(
context: Context,
private val base: Toast,
) : Toast(context) {
companion object {
private val log = LogCategory("ToastCompat")
/**
* Make a standard toast that just contains a text view with the text from a resource.
*
* @param context The context to use. Usually your [android.app.Application]
* or [android.app.Activity] object.
* @param resId The resource id of the string resource to use. Can be formatted text.
* @param duration How long to display the message. Either [.LENGTH_SHORT] or
* [.LENGTH_LONG]
* @throws Resources.NotFoundException if the resource can't be found.
*/
@Suppress("unused")
fun makeText(context: Context, @StringRes resId: Int, duration: Int) =
makeText(context, context.resources.getText(resId), duration)
/**
* Make a standard toast that just contains a text view.
*
* @param context The context to use. Usually your [android.app.Application]
* or [android.app.Activity] object.
* @param text The text to show. Can be formatted text.
* @param duration How long to display the message. Either [.LENGTH_SHORT] or
* [.LENGTH_LONG]
*/
@Suppress("ShowToast", "DEPRECATION")
fun makeText(context: Context, text: CharSequence?, duration: Int): ToastCompat {
// We cannot pass the SafeToastContext to Toast.makeText() because
// the View will unwrap the base context and we are in vain.
val base = Toast.makeText(context, text, duration)
return ToastCompat(context, base)
}
}
@Suppress("DEPRECATION")
fun setBadTokenListener(listener: BadTokenListener?): ToastCompat {
(base.view?.context as? SafeToastContext)
?.setBadTokenListener(listener)
return this
}
@Suppress("DEPRECATION")
@Deprecated(message = "Custom toast views are deprecated in API level 30.")
override fun setView(view: View) {
base.view = view
}
@Suppress("DEPRECATION")
@Deprecated(message = "Custom toast views are deprecated in API level 30.")
override fun getView(): View? = base.view
override fun show() = base.show()
override fun setDuration(duration: Int) {
base.duration = duration
}
override fun setGravity(gravity: Int, xOffset: Int, yOffset: Int) =
base.setGravity(gravity, xOffset, yOffset)
override fun setMargin(horizontalMargin: Float, verticalMargin: Float) =
base.setMargin(horizontalMargin, verticalMargin)
override fun setText(resId: Int) = base.setText(resId)
override fun setText(s: CharSequence) = base.setText(s)
override fun getHorizontalMargin() = base.horizontalMargin
override fun getVerticalMargin() = base.verticalMargin
override fun getDuration() = base.duration
override fun getGravity() = base.gravity
override fun getXOffset() = base.xOffset
override fun getYOffset() = base.yOffset
}
|
apache-2.0
|
e235f17f9d2e31ac673e764ee32aa633
| 35.042424 | 97 | 0.666723 | 4.606507 | false | false | false | false |
spark1991z/spok
|
project/net/http/HttpRequest.kt
|
1
|
7042
|
package project.net.http
import project.crypto.MD5
import project.log.Loggable
import java.net.Socket
import java.net.URI
import java.net.URLDecoder
import java.nio.charset.Charset
import java.util.*
/**
* @author spark1991z
*/
class HttpRequest(private var socket: Socket, private var res: HttpResponse) : Loggable {
companion object {
private var methods: Vector<String> = Vector<String>()
var METHOD_GET = "GET"
var METHOD_POST = "POST"
var METHOD_PUT = "PUT"
var METHOD_HEAD = "HEAD"
init {
methods.add(METHOD_GET)
methods.add(METHOD_POST)
methods.add(METHOD_PUT)
methods.add(METHOD_HEAD)
}
fun checkMethod(method: String?): Boolean {
if (method != null)
return methods.contains(method)
return false
}
}
private var method: String? = null
private var path: String = "/"
private var ready: Boolean = true
private var headers: Hashtable<String, String> = Hashtable<String, String>()
private var query: Hashtable<String, String> = Hashtable<String, String>()
private var cookies: Hashtable<String, String> = Hashtable<String, String>()
init {
init()
}
private fun nextLine(): String? {
var bf: String? = null
while (true) {
var r: Int = read()
if (r < 0 || r.toChar() == '\n') break
if (r.toChar() == '\r') continue
if (bf == null) bf = ""
bf += r.toChar()
}
return bf
}
private fun init() {
/**
* Base
*/
var rs: String? = nextLine()
if (rs == null) {
ready = false
socket.close()
return
}
debug(rs)
var h: List<String> = rs.split(" ")
/**
* Headers
*/
while (true) {
var line: String? = nextLine()
if (line == null || line.isEmpty()) break
debug(line)
var y: Int = line.indexOf(":")
var hn: String = line.substring(0, y).trim()
var hv: String = line.substring(y + 1, line.length).trim()
headers.put(hn, hv)
}
/**
* Prepare
*/
if (!methods.contains(h[0])) {
ready = false
res.status(HttpResponse.STATUS_501_NOT_IMPLEMENTED)
res.printError("Method ${h[0]} is not exists or not supported on this server.")
res.close()
return
}
method = h[0]
var x: Int = h[1].indexOf("%")
if (x > 0) {
try {
var uri: URI = URI(h[1])
path = uri.path
var x2: Int = h[1].indexOf("?")
if (x2 > 0) {
for (kp in uri.query.split("&")) {
var kv: List<String> = kp.split("=")
debug("Query <- ${kv[0]}=${kv[1]}")
query.put(kv[0], kv[1])
}
}
} catch (e: Exception) {
ready = false
res.status(HttpResponse.STATUS_400_BAD_REQUEST)
res.printError("Your request URI is bad: ${h[1]}")
res.close()
return
}
} else path = h[1]
path = path!!.replace("///", "/")
.replace("/../", "/")
.replace("./", "/")
.replace("//", "/")
if (!path!!.equals("/") && path!!.endsWith("/")) path = path!!.substring(0, path!!.length - 1)
var pv = h[2].split("/")
var protocol: String = pv[0]
var version: Double = java.lang.Double.valueOf(pv[1])
if (!protocol.equals("HTTP") || version < HttpResponse.PROTOCOL_VERSION) {
ready = false
res.status(HttpResponse.STATUS_426_UPGRADE_REQUIRED)
res.connection(HttpResponse.CONNECTION_UPGRADE)
res.header("Upgrade", "HTTP/${HttpResponse.PROTOCOL_VERSION}")
res.printError("This server requires use of the HTTP/${HttpResponse.PROTOCOL_VERSION} protocol.")
res.close()
return
}
//Cookies
var v: String? = header("Cookie")
if (v != null) {
headers.remove("Cookie")
for (cookie in v.split("; ")) {
var kv: List<String> = cookie.split("=")
debug("Cookie <- ${kv[0]}=${kv[1]}")
cookies.put(kv[0], kv[1])
}
}
//Cookie session_id
var c: String? = cookie("session_id")
if (c == null) {
var ua: String? = header("User-Agent")
if (ua != null)
res.cookie("session_id", MD5.digest(ua), null, 60 * 60, null, "/", false, true)
}
/**
* POST/PUT Query
*/
if (method.equals(METHOD_POST) || method.equals(METHOD_PUT)) {
var ctype: String? = header("Content-Type")
if (ctype == null) {
ready = false
res.status(HttpResponse.STATUS_415_UNSUPPORTED_MEDIA_TYPE)
res.close()
return
}
var clen: Int = Integer.valueOf(header("Content-Length")).toInt()
if (clen < 0) {
ready = false
res.status(HttpResponse.STATUS_411_LENGTH_REQUIRED)
res.close()
return
}
if (ctype.contains("boundary")) return //Disable accept files
var qb: ByteArray = kotlin.ByteArray(clen)
if (socket.isClosed()) return
if (socket.getInputStream().read(qb) < clen) {
ready = false
res.status(HttpResponse.STATUS_422_UNPROCESSABLE_ENTITY)
res.close()
return
}
var q: String = String(qb)
if (q.contains("%")) q = URLDecoder.decode(q, Charset.defaultCharset().displayName())
debug(q)
var query_arr: List<String> = q.split("&")
for (kp in query_arr) {
var kv: List<String> = q.split("=")
debug("Query <- ${kv[0]}=${kv[1]}")
query.put(kv[0], kv[1])
}
}
}
fun cookie(key: String): String? {
if (cookies.containsKey(key))
return cookies.get(key)
return null
}
fun read(): Int {
if (socket.isClosed()) return -1
return socket.getInputStream().read()
}
fun ready(): Boolean {
return ready
}
fun method(): String? {
return method
}
fun path(): String {
return path
}
fun header(key: String): String? {
if (headers.containsKey(key))
return headers.get(key)
return null
}
fun query(key: String): String? {
if (query.containsKey(key))
return query.get(key)
return null
}
}
|
gpl-3.0
|
2d6b256f6142e011030b2821103364dc
| 29.755459 | 109 | 0.478415 | 4.260133 | false | false | false | false |
google/intellij-community
|
platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt
|
2
|
9866
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems", "ReplaceGetOrSet")
package com.intellij.ide.plugins
import com.intellij.diagnostic.PluginException
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.stubs.StubElementTypeHolderEP
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.getErrorsAsString
import io.github.classgraph.*
import java.lang.reflect.Constructor
import kotlin.properties.Delegates.notNull
@Suppress("HardCodedStringLiteral")
private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val errors = mutableListOf<Throwable>()
runModalTask("Creating All Services And Extensions", cancellable = true) { indicator ->
val taskExecutor: (task: () -> Unit) -> Unit = { task ->
try {
task()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
errors.add(e)
}
}
// check first
checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor)
val application = ApplicationManager.getApplication() as ComponentManagerImpl
checkContainer(application, indicator, taskExecutor)
val project = ProjectUtil.getOpenProjects().firstOrNull() as? ComponentManagerImpl
project?.let {
checkContainer(it, indicator, taskExecutor)
}
indicator.text2 = "Checking light services..."
for (mainDescriptor in PluginManagerCore.getPluginSet().enabledPlugins) {
// we don't check classloader for sub descriptors because url set is the same
val pluginClassLoader = mainDescriptor.pluginClassLoader as? PluginClassLoader
?: continue
scanClassLoader(pluginClassLoader).use { scanResult ->
for (classInfo in scanResult.getClassesWithAnnotation(Service::class.java.name)) {
checkLightServices(classInfo, mainDescriptor, application, project) {
val error = when (it) {
is ProcessCanceledException -> throw it
is PluginException -> it
else -> PluginException("Cannot create ${classInfo.name}", it, mainDescriptor.pluginId)
}
errors.add(error)
}
}
}
}
}
if (errors.isNotEmpty()) {
logger<ComponentManagerImpl>().error(getErrorsAsString(errors))
}
// some errors are not thrown but logged
val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors."
Notification("Error Report", "", message, NotificationType.INFORMATION).notify(null)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
private class CreateAllServicesAndExtensionsActivity : AppLifecycleListener {
init {
if (!ApplicationManager.getApplication().isInternal ||
!java.lang.Boolean.getBoolean("ide.plugins.create.all.services.and.extensions")) {
throw ExtensionNotApplicableException.create()
}
}
override fun appStarted() = ApplicationManager.getApplication().invokeLater {
performAction()
}
}
fun performAction() {
val actionManager = ActionManager.getInstance()
actionManager.tryToExecute(
actionManager.getAction(ACTION_ID),
null,
null,
ActionPlaces.UNKNOWN,
true,
)
}
// external usage in [src/com/jetbrains/performancePlugin/commands/chain/generalCommandChain.kt]
const val ACTION_ID = "CreateAllServicesAndExtensions"
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val badServices = java.util.Set.of(
"com.intellij.usageView.impl.UsageViewContentManagerImpl",
"com.jetbrains.python.scientific.figures.PyPlotToolWindow",
"com.intellij.analysis.pwa.analyser.PwaServiceImpl",
"com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl",
)
@Suppress("HardCodedStringLiteral")
private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) {
indicator.text2 = "Checking ${container.activityNamePrefix()}services..."
ComponentManagerImpl.createAllServices(container, badServices)
indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..."
container.extensionArea.processExtensionPoints { extensionPoint ->
// requires a read action
if (extensionPoint.name == "com.intellij.favoritesListProvider" ||
extensionPoint.name == "org.jetbrains.kotlin.defaultErrorMessages") {
return@processExtensionPoints
}
checkExtensionPoint(extensionPoint, taskExecutor)
}
}
private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) {
var extensionClass: Class<out Any> by notNull()
taskExecutor {
extensionClass = extensionPoint.extensionClass
}
extensionPoint.checkImplementations { extension ->
taskExecutor {
val extensionInstance: Any
try {
extensionInstance = (extension.createInstance(extensionPoint.componentManager) ?: return@taskExecutor)
}
catch (e: Exception) {
throw PluginException("Failed to instantiate extension (extension=$extension, pointName=${extensionPoint.name})",
e, extension.pluginDescriptor.pluginId)
}
if (!extensionClass.isInstance(extensionInstance)) {
throw PluginException("$extension does not implement $extensionClass", extension.pluginDescriptor.pluginId)
}
}
}
}
private fun scanClassLoader(pluginClassLoader: PluginClassLoader): ScanResult {
return ClassGraph()
.enableAnnotationInfo()
.ignoreParentClassLoaders()
.overrideClassLoaders(pluginClassLoader)
.scan()
}
private fun checkLightServices(
classInfo: ClassInfo,
mainDescriptor: IdeaPluginDescriptorImpl,
application: ComponentManagerImpl,
project: ComponentManagerImpl?,
onThrowable: (Throwable) -> Unit,
) {
try {
val lightServiceClass = when (val className = classInfo.name) {
// wants EDT/read action in constructor
"org.jetbrains.plugins.grails.runner.GrailsConsole",
"com.jetbrains.rdserver.editors.MultiUserCaretSynchronizerProjectService",
"com.intellij.javascript.web.webTypes.nodejs.WebTypesNpmLoader" -> null
// not clear - from what classloader light service will be loaded in reality
else -> loadLightServiceClass(className, mainDescriptor)
} ?: return
val (isAppLevel, isProjectLevel) = classInfo.getAnnotationInfo(Service::class.java.name)
.parameterValues
.find { it.name == "value" }
?.let { levelsByAnnotations(it) }
?: levelsByConstructors(lightServiceClass.declaredConstructors)
val components = listOfNotNull(
if (isAppLevel) application else null,
if (isProjectLevel) project else null,
)
for (component in components) {
try {
component.getService(lightServiceClass)
}
catch (e: Throwable) {
onThrowable(e)
}
}
}
catch (e: Throwable) {
onThrowable(e)
}
}
private data class Levels(
val isAppLevel: Boolean,
val isProjectLevel: Boolean,
)
private fun levelsByConstructors(constructors: Array<Constructor<*>>): Levels {
return Levels(
isAppLevel = constructors.any { it.parameterCount == 0 },
isProjectLevel = constructors.any { constructor ->
constructor.parameterCount == 1
&& constructor.parameterTypes.get(0) == Project::class.java
},
)
}
private fun levelsByAnnotations(annotationParameterValue: AnnotationParameterValue): Levels {
fun hasLevel(level: Service.Level) =
(annotationParameterValue.value as Array<*>).asSequence()
.map { it as AnnotationEnumValue }
.any { it.name == level.name }
return Levels(
isAppLevel = hasLevel(Service.Level.APP),
isProjectLevel = hasLevel(Service.Level.PROJECT),
)
}
private fun loadLightServiceClass(
className: String,
mainDescriptor: IdeaPluginDescriptorImpl,
): Class<*>? {
fun loadClass(descriptor: IdeaPluginDescriptorImpl) =
(descriptor.pluginClassLoader as? PluginClassLoader)?.loadClass(className, true)
for (moduleItem in mainDescriptor.content.modules) {
try {
// module is not loaded - dependency is not provided
return loadClass(moduleItem.requireDescriptor())
}
catch (_: PluginException) {
}
catch (_: ClassNotFoundException) {
}
}
// ok, or no plugin dependencies at all, or all are disabled, resolve from main
return loadClass(mainDescriptor)
}
|
apache-2.0
|
d1a5f56ed93e46bf1f9bbaa1b849b010
| 36.371212 | 134 | 0.701906 | 5.08033 | false | false | false | false |
google/intellij-community
|
plugins/settings-sync/tests/com/intellij/settingsSync/SettingsSyncPluginManagerTest.kt
|
1
|
8826
|
package com.intellij.settingsSync
import com.intellij.configurationStore.ComponentSerializationUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.settingsSync.plugins.PluginManagerProxy
import com.intellij.settingsSync.plugins.SettingsSyncPluginManager
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.replaceService
import com.intellij.util.io.readText
import com.intellij.util.xmlb.XmlSerializer
import junit.framework.TestCase
import org.jdom.Element
import org.jdom.output.Format
import org.jdom.output.XMLOutputter
import java.io.StringWriter
// region Test data
private const val incomingPluginData = """<component name="SettingsSyncPlugins">
<option name="plugins">
<map>
<entry key="QuickJump">
<value>
<PluginData>
<option name="dependencies">
<set>
<option value="com.intellij.modules.platform" />
</set>
</option>
<option name="enabled" value="false" />
</PluginData>
</value>
</entry>
<entry key="codeflections.typengo">
<value>
<PluginData>
<option name="dependencies">
<set>
<option value="com.intellij.modules.platform" />
</set>
</option>
</PluginData>
</value>
</entry>
<entry key="color.scheme.IdeaLight">
<value>
<PluginData>
<option name="category" value="UI" />
<option name="dependencies">
<set>
<option value="com.intellij.modules.lang" />
</set>
</option>
</PluginData>
</value>
</entry>
<entry key="com.company.plugin">
<value>
<PluginData>
<option name="dependencies">
<set>
<option value="com.intellij.modules.lang" />
<option value="com.company.other.plugin" />
</set>
</option>
</PluginData>
</value>
</entry>
</map>
</option>
</component>"""
// endregion
class SettingsSyncPluginManagerTest : LightPlatformTestCase() {
private lateinit var pluginManager: SettingsSyncPluginManager
private lateinit var testPluginManager: TestPluginManager
private val quickJump = TestPluginDescriptor(
"QuickJump",
listOf(TestPluginDependency("com.intellij.modules.platform", isOptional = false))
)
private val typengo = TestPluginDescriptor(
"codeflections.typengo",
listOf(TestPluginDependency("com.intellij.modules.platform", isOptional = false))
)
override fun setUp() {
super.setUp()
SettingsSyncSettings.getInstance().syncEnabled = true
testPluginManager = TestPluginManager()
ApplicationManager.getApplication().replaceService(PluginManagerProxy::class.java, testPluginManager, testRootDisposable)
pluginManager = SettingsSyncPluginManager()
Disposer.register(testRootDisposable, pluginManager)
}
fun `test install missing plugins`() {
pluginManager.updateStateFromFileStateContent(getTestDataFileState())
pluginManager.pushChangesToIde()
val installedPluginIds = testPluginManager.installer.installedPluginIds
// Make sure QuickJump is skipped because it is disabled
TestCase.assertEquals(2, installedPluginIds.size)
TestCase.assertTrue(installedPluginIds.containsAll(
listOf("codeflections.typengo", "color.scheme.IdeaLight")))
}
private fun getTestDataFileState(): FileState.Modified {
val content = incomingPluginData.toByteArray()
return FileState.Modified(SettingsSyncPluginManager.FILE_SPEC, content, content.size)
}
fun `test do not install when plugin sync is disabled`() {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.PLUGINS, false)
try {
pluginManager.updateStateFromFileStateContent(getTestDataFileState())
pluginManager.pushChangesToIde()
val installedPluginIds = testPluginManager.installer.installedPluginIds
// IdeaLight is a UI plugin, it doesn't fall under PLUGINS category
TestCase.assertEquals(1, installedPluginIds.size)
TestCase.assertTrue(installedPluginIds.contains("color.scheme.IdeaLight"))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.PLUGINS, true)
}
}
fun `test do not install UI plugin when UI category is disabled`() {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, false)
try {
pluginManager.updateStateFromFileStateContent(getTestDataFileState())
pluginManager.pushChangesToIde()
val installedPluginIds = testPluginManager.installer.installedPluginIds
// IdeaLight is a UI plugin, it doesn't fall under PLUGINS category
TestCase.assertEquals(1, installedPluginIds.size)
TestCase.assertTrue(installedPluginIds.contains("codeflections.typengo"))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, true)
}
}
fun `test disable installed plugin`() {
testPluginManager.addPluginDescriptors(pluginManager, quickJump)
pluginManager.updateStateFromFileStateContent(getTestDataFileState())
assertTrue(quickJump.isEnabled)
pluginManager.pushChangesToIde()
assertFalse(quickJump.isEnabled)
}
fun `test default state is empty` () {
val state = pluginManager.state
TestCase.assertTrue(state.plugins.isEmpty())
}
fun `test state contains installed plugin` () {
testPluginManager.addPluginDescriptors(pluginManager, quickJump)
assertSerializedStateEquals(
"""
<component>
<option name="plugins">
<map>
<entry key="QuickJump">
<value>
<PluginData>
<option name="dependencies">
<set>
<option value="com.intellij.modules.platform" />
</set>
</option>
</PluginData>
</value>
</entry>
</map>
</option>
</component>""".trimIndent())
}
fun `test disable two plugins at once`() {
// install two plugins
testPluginManager.addPluginDescriptors(pluginManager, quickJump, typengo)
pluginManager.updateStateFromFileStateContent(getTestDataFileState())
pluginManager.state.plugins["codeflections.typengo"] = SettingsSyncPluginManager.PluginData().apply {
this.isEnabled = false
}
TestCase.assertTrue(quickJump.isEnabled)
TestCase.assertTrue(typengo.isEnabled)
pluginManager.pushChangesToIde()
TestCase.assertFalse(quickJump.isEnabled)
TestCase.assertFalse(typengo.isEnabled)
}
fun `test plugin manager collects state on start`() {
testPluginManager.addPluginDescriptors(pluginManager, quickJump)
val element = JDOMUtil.load(incomingPluginData)
ComponentSerializationUtil.loadComponentState(pluginManager, element)
val dataForQuickJump = pluginManager.state.plugins[quickJump.idString]
assertNotNull("The data about ${quickJump.idString} plugin is not in the state", dataForQuickJump)
TestCase.assertTrue("Plugin is enabled in the IDE but disabled in the state", dataForQuickJump!!.isEnabled)
}
fun `test state deserialization`() {
pluginManager.state.plugins["A"] = SettingsSyncPluginManager.PluginData().apply { this.isEnabled = false }
(ApplicationManager.getApplication() as ComponentManagerImpl).componentStore.saveComponent(pluginManager)
val serializedComponent = PathManager.getConfigDir().resolve("options").resolve("settingsSyncPlugins.xml").readText()
pluginManager.state.plugins.clear()
val byteArray = serializedComponent.toByteArray()
pluginManager.updateStateFromFileStateContent(FileState.Modified("options/settingsSyncPlugins.xml", byteArray, byteArray.size))
val pluginData = pluginManager.state.plugins["A"]
assertNotNull("Plugin data for A is not found in ${pluginManager.state.plugins}", pluginData)
TestCase.assertFalse(pluginData!!.isEnabled)
}
private fun assertSerializedStateEquals(expected: String) {
val state = pluginManager.state
val e = Element("component")
XmlSerializer.serializeInto(state, e)
val writer = StringWriter()
val format = Format.getPrettyFormat()
format.lineSeparator = "\n"
XMLOutputter(format).output(e, writer)
val actual = writer.toString()
TestCase.assertEquals(expected, actual)
}
}
|
apache-2.0
|
baaf70cbcd5684cd8fb929853832bf4c
| 36.244726 | 131 | 0.70247 | 4.936242 | false | true | false | false |
JetBrains/intellij-community
|
python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingTablesView.kt
|
1
|
6183
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.packaging.toolwindow
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.ui.JBColor
import com.jetbrains.python.PyBundle.message
import com.jetbrains.python.packaging.repository.PyPackageRepository
import java.awt.Rectangle
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JTable
class PyPackagingTablesView(private val project: Project,
private val container: JPanel,
private val controller: PyPackagingToolWindowPanel) {
private val repositories: MutableList<PyPackagingTableGroup<DisplayablePackage>> = mutableListOf()
private val installedPackages = PyPackagingTableGroup(
object : PyPackageRepository(message("python.toolwindow.packages.installed.label"), "", "") {},
PyPackagesTable(project, PyPackagesTableModel(), this, controller))
private val invalidRepositories: MutableMap<String, JPanel> = mutableMapOf()
init {
installedPackages.addTo(container)
installedPackages.expand()
}
fun showSearchResult(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) {
updatePackages(installed, repoData)
installedPackages.expand()
installedPackages.updateHeaderText(installed.size)
val tableToData = repositories.map { repo -> repo to repoData.find { it.repository.name == repo.name }!! }
tableToData.forEach { (table, data) ->
table.updateHeaderText(data.packages.size + data.moreItems)
table.expand()
}
// todo[akniazev]: selecting a package in 'installed' list might make more sense
tableToData
.firstOrNull { (_, data) -> data.exactMatch != -1 }
?.let { selectPackage(it.second) }
}
fun resetSearch(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) {
updatePackages(installed, repoData)
installedPackages.expand()
installedPackages.updateHeaderText(null)
repositories.forEach {
it.collapse()
it.updateHeaderText(null)
}
container.scrollRectToVisible(Rectangle(0, 0))
}
private fun updatePackages(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) {
installedPackages.table.items = installed
val (validRepoData, invalid) = repoData.partition { it !is PyInvalidRepositoryViewData }
for (data in validRepoData) {
val existingRepo = findTableForRepo(data.repository)
val withExpander = if (data.moreItems > 0) data.packages + listOf(ExpandResultNode(data.moreItems, data.repository)) else data.packages
if (existingRepo != null) {
// recreate order of the repositories -- it might have changed in the package manager (e.g. Sdk switch)
existingRepo.removeFrom(container)
existingRepo.items = withExpander
existingRepo.addTo(container)
}
else {
val newTable = PyPackagesTable(project, PyPackagesTableModel(), this, controller)
newTable.items = withExpander
val newTableGroup = PyPackagingTableGroup(data.repository, newTable)
repositories.add(newTableGroup)
newTableGroup.addTo(container)
}
}
val existingRepositories = validRepoData.map { it.repository.name }
val removedRepositories = repositories.filter { it.name !in existingRepositories }
removedRepositories.forEach { it.removeFrom(container) }
repositories.removeAll(removedRepositories)
@Suppress("UNCHECKED_CAST")
refreshInvalidRepositories(invalid as List<PyInvalidRepositoryViewData>)
}
private fun refreshInvalidRepositories(invalid: List<PyInvalidRepositoryViewData>) {
val invalidRepoNames = invalid.map { it.repository.name }
invalidRepositories.forEach { container.remove(it.value) }
invalidRepositories.keys.removeIf { it !in invalidRepoNames }
invalid.asSequence()
.map { it.repository.name!! }
.filterNot { it in invalidRepositories }
.map {
val label = JLabel(message("python.toolwindow.packages.custom.repo.invalid", it)).apply {
foreground = JBColor.RED
icon = AllIcons.General.Error
}
it to headerPanel(label, null)
}
.forEach {
invalidRepositories[it.first] = it.second
}
invalidRepositories.forEach { container.add(it.value) }
}
private fun selectPackage(matchData: PyPackagesViewData) {
val tableWithMatch = findTableForRepo(matchData.repository)!!.table
val exactMatch = matchData.exactMatch
tableWithMatch.setRowSelectionInterval(exactMatch, exactMatch)
}
fun requestSelection(table: JTable) {
if (table != installedPackages.table) installedPackages.table.clearSelection()
repositories.asSequence()
.filter { it.table != table }
.forEach { it.table.clearSelection() }
}
private fun findTableForRepo(repository: PyPackageRepository) = repositories.find { it.name == repository.name }
fun selectNextFrom(currentTable: JTable) {
val targetGroup = when (currentTable) {
installedPackages.table -> repositories.firstOrNull()
else -> {
val currentIndex = repositories.indexOfFirst { it.table == currentTable }
if (currentIndex + 1 != repositories.size) repositories[currentIndex + 1]
else return
}
}
targetGroup?.apply {
if (items.isNotEmpty()) {
expand()
table.setRowSelectionInterval(0, 0)
table.requestFocus()
}
}
}
fun selectPreviousOf(currentTable: JTable) {
val targetGroup = when (currentTable) {
installedPackages.table -> return
repositories.firstOrNull()?.table -> installedPackages
else -> {
val currentIndex = repositories.indexOfFirst { it.table == currentTable }
repositories[currentIndex - 1]
}
}
targetGroup.apply {
if (items.isNotEmpty()) {
expand()
val newIndex = items.size - 1
table.setRowSelectionInterval(newIndex, newIndex)
table.requestFocus()
}
}
}
}
|
apache-2.0
|
8dbf6aefd816690aba370815da2350cb
| 36.253012 | 158 | 0.705321 | 4.57661 | false | false | false | false |
CobaltVO/2048-Neural-network
|
src/main/java/ru/falseteam/neural2048/gnn/crossower/TwoPointsNeuronsCrossover.kt
|
1
|
1560
|
package ru.falseteam.neural2048.gnn.crossower
import ru.falseteam.neural2048.ga.MutatorCrossover
import ru.falseteam.neural2048.nn.NeuralNetwork
import java.util.*
/**
* Автор: Евгений Рудзянский
* Дата : 09.10.17
*/
class TwoPointsNeuronsCrossover : MutatorCrossover.Crossing<NeuralNetwork> {
private val random = Random()
override fun crossing(chromosome1: NeuralNetwork, chromosome2: NeuralNetwork): List<NeuralNetwork> {
val anotherClone = chromosome2.clone()
val thisClone = chromosome1.clone()
// case of switch
val thisNeurons = thisClone.neurons
val anotherNeurons = anotherClone.neurons
//this.twoPointsNeuronsCrossover(thisClone.neurons, anotherClone.neurons)
//this.twoPointsNeuronsCrossover(thisNeurons: MutableList<Neuron>, anotherNeurons: MutableList<Neuron>)
var left = this.random.nextInt(thisNeurons.size)
var right = this.random.nextInt(thisNeurons.size)
if (left > right) {
val tmp = right
right = left
left = tmp
}
for (i in left until right) {
val thisNeuron = thisNeurons[i]
thisNeurons[i] = anotherNeurons[i]
anotherNeurons[i] = thisNeuron
}
// end func
// after switch
val ret = ArrayList<NeuralNetwork>()
ret.add(anotherClone)
ret.add(thisClone)
//ret.add(anotherClone.mutate_());
//ret.add(thisClone.mutate_());//TODO мазафака
return ret
}
}
|
gpl-3.0
|
1478c53ea498d7e9086273759b0f9377
| 33.704545 | 111 | 0.651376 | 3.548837 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddSpreadOperatorForArrayAsVarargAfterSam.kt
|
1
|
1563
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
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.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
object AddSpreadOperatorForArrayAsVarargAfterSamFixFactory : KotlinSingleIntentionActionFactory() {
public override fun createAction(diagnostic: Diagnostic): IntentionAction {
val diagnosticWithParameters = Errors.TYPE_INFERENCE_CANDIDATE_WITH_SAM_AND_VARARG.cast(diagnostic)
val argument = diagnosticWithParameters.psiElement
return AddSpreadOperatorForArrayAsVarargAfterSamFix(argument)
}
}
class AddSpreadOperatorForArrayAsVarargAfterSamFix(element: PsiElement) : KotlinQuickFixAction<PsiElement>(element) {
override fun getFamilyName() = KotlinBundle.message("fix.add.spread.operator.after.sam")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
element.addBefore(KtPsiFactory(project).createStar(), element.firstChild)
}
}
|
apache-2.0
|
f7234712fc4e42a0e19804ce0f5fd4cb
| 43.685714 | 120 | 0.805502 | 4.570175 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationWithArgumentsFix.kt
|
1
|
7911
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
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.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.constants.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
// TODO: It might be useful to unify [AddAnnotationWithArgumentsFix] and [AddAnnotationFix] as they do almost the same thing
/**
* A quick fix to add an annotation with arbitrary arguments to a KtModifierListOwner element.
*
* This quick fix is similar to [AddAnnotationFix] but allows to use arbitrary strings as an inner text
* ([AddAnnotationFix] allows a single class argument).
*
* @param element the element to annotate
* @param annotationFqName the fully qualified name of the annotation class
* @param arguments the list of strings that should be added as the annotation arguments
* @param kind the action type that determines the action description text, see [Kind] for details
* @param useSiteTarget the optional use site target of the annotation (e.g., "@file:Annotation")
* @param existingAnnotationEntry existing annotation entry (it is updated if not null instead of creating the new annotation)
*/
class AddAnnotationWithArgumentsFix(
element: KtModifierListOwner,
private val annotationFqName: FqName,
private val arguments: List<String>,
private val kind: Kind = Kind.Self,
private val useSiteTarget: AnnotationUseSiteTarget? = null,
private val existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : KotlinQuickFixAction<KtModifierListOwner>(element) {
/**
* The way to specify the target (the declaration to which the annotation is added) and the source (the declaration
* from which the annotation, or its template, has been obtained).
*/
sealed class Kind {
/**
* No specification of source and target.
*/
object Self : Kind()
/**
* The target is specified, there is no explicit source.
*/
class Target(val target: String) : Kind()
/**
* Both source and target are specified.
*/
class Copy(val source: String, val target: String) : Kind()
}
override fun getText(): String {
val annotationName = annotationFqName.shortName().render()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.add.annotation.text.self", annotationName)
is Kind.Target -> KotlinBundle.message("fix.add.annotation.text.declaration", annotationName, kind.target)
is Kind.Copy -> KotlinBundle.message("fix.add.annotation.with.arguments.text.copy", annotationName, kind.source, kind.target)
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.add.annotation.family")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val declaration = element ?: return
val innerText = if (arguments.isNotEmpty()) arguments.joinToString() else null
val entry = existingAnnotationEntry?.element
if (entry != null) {
if (innerText != null) {
val psiFactory = KtPsiFactory(project)
entry.valueArgumentList?.addArgument(psiFactory.createArgument(innerText))
?: entry.addAfter(psiFactory.createCallArguments("($innerText)"), entry.lastChild)
}
} else {
declaration.addAnnotation(annotationFqName, innerText, useSiteTarget = useSiteTarget, searchForExistingEntry = false)
}
}
/**
* A factory for `OVERRIDE_DEPRECATION` warning. It provides an action that copies the `@Deprecated` annotation
* from the ancestor's deprecated function/property to the overriding function/property in the derived class.
*/
object CopyDeprecatedAnnotation : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
if (diagnostic.factory != Errors.OVERRIDE_DEPRECATION) return emptyList()
val deprecation = Errors.OVERRIDE_DEPRECATION.cast(diagnostic)
val declaration = deprecation.psiElement
return deprecation.c.mapNotNull {
val annotation = it.target.annotations.findAnnotation(StandardNames.FqNames.deprecated) ?: return@mapNotNull null
val arguments = formatDeprecatedAnnotationArguments(annotation)
val sourceName = renderName(it.target)
val destinationName = renderName(deprecation.b)
AddAnnotationWithArgumentsFix(
declaration,
StandardNames.FqNames.deprecated,
arguments,
kind = Kind.Copy(sourceName, destinationName)
)
}
}
private val MESSAGE_ARGUMENT = Name.identifier("message")
private val REPLACE_WITH_ARGUMENT = Name.identifier("replaceWith")
private val LEVEL_ARGUMENT = Name.identifier("level")
private val EXPRESSION_ARGUMENT = Name.identifier("expression")
private val IMPORTS_ARGUMENT = Name.identifier("imports")
// A custom pretty-printer for the `@Deprecated` annotation that deals with optional named arguments and varargs.
private fun formatDeprecatedAnnotationArguments(annotation: AnnotationDescriptor): List<String> {
val arguments = mutableListOf<String>()
annotation.allValueArguments[MESSAGE_ARGUMENT]?.safeAs<StringValue>()?.let { arguments.add(it.toString()) }
val replaceWith = annotation.allValueArguments[REPLACE_WITH_ARGUMENT]?.safeAs<AnnotationValue>()?.value
if (replaceWith != null) {
val expression = replaceWith.allValueArguments[EXPRESSION_ARGUMENT]?.safeAs<StringValue>()?.toString()
val imports = replaceWith.allValueArguments[IMPORTS_ARGUMENT]?.safeAs<ArrayValue>()?.value
val importsArg = if (imports.isNullOrEmpty()) "" else (", " + imports.joinToString { it.toString() })
if (expression != null) {
arguments.add("replaceWith = ReplaceWith(${expression}${importsArg})")
}
}
annotation.allValueArguments[LEVEL_ARGUMENT]?.safeAs<EnumValue>()?.let { arguments.add("level = $it") }
return arguments
}
// A renderer for function/property names: uses qualified names when available to disambiguate names of overrides
private fun renderName(descriptor: DeclarationDescriptor): String {
val containerPrefix = descriptor.containingDeclaration?.let { "${it.name.render()}." } ?: ""
val name = descriptor.name.render()
return containerPrefix + name
}
}
}
|
apache-2.0
|
48390fbb701a951466639a813b552709
| 51.046053 | 158 | 0.702313 | 5.14704 | false | false | false | false |
nielsutrecht/adventofcode
|
src/main/kotlin/com/nibado/projects/advent/graph/Graph.kt
|
1
|
4001
|
package com.nibado.projects.advent.graph
class Graph<N, E> : Collection<N> {
private val nodes: MutableMap<N, Node<N>>
private val nodeToEdge : MutableMap<N, MutableSet<Edge<N, E>>>
private constructor(nodes: MutableMap<N, Node<N>>, nodeToEdge: MutableMap<N, MutableSet<Edge<N, E>>>) {
this.nodes = nodes
this.nodeToEdge = nodeToEdge
}
constructor() : this(mutableMapOf<N, Node<N>>(), mutableMapOf<N, MutableSet<Edge<N, E>>>())
/**
* Copy constructor
*/
constructor(graph: Graph<N, E>) : this(graph.nodes.toMap().toMutableMap(), graph.nodeToEdge.toMap().toMutableMap())
override val size: Int
get() = nodes.size
data class Node<N>(val key: N)
data class Edge<N, E>(val value: E, val to: Node<N>)
fun addAll(vararg pairs: Pair<N, N>, edge: E, bidirectional: Boolean = false) : Graph<N, E> {
pairs.forEach { (a, b) -> add(a, b, edge, bidirectional) }
return this
}
fun addAll(pairs: Collection<Pair<N, N>>, edge: E, bidirectional: Boolean = false) : Graph<N, E> {
pairs.forEach { (a, b) -> add(a, b, edge, bidirectional) }
return this
}
fun add(from: N, to: N, edge: E, bidirectional: Boolean = false): Node<N> {
val fromNode = nodes.computeIfAbsent(from) { node(it) }
nodes.computeIfAbsent(to) { node(it) }
setEdge(from, to, edge)
if (bidirectional) {
setEdge(to, from, edge)
}
return fromNode
}
/**
* Searches for all paths from 'from' to 'to' using the provided strategy and a provided node filter.
*
* See Year 2021 Day 12 for usage.
*/
fun paths(
from: N,
to: N,
strategy: SearchStrategy = SearchStrategy.DEPTH_FIRST,
nodeFilter: (Node<N>, Map<Node<N>, Int>) -> Boolean) : List<List<Node<N>>> =
when(strategy) {
SearchStrategy.DEPTH_FIRST -> mutableListOf<List<Node<N>>>().also { depthFirst(this[from], this[to], emptyMap(), emptyList(), it, nodeFilter) }
}
//TODO: Implement with stack instead of recursion.
private fun depthFirst(
from: Node<N>,
to: Node<N>,
visited: Map<Node<N>, Int>,
path: List<Node<N>>,
paths: MutableList<List<Node<N>>>,
nodeFilter: (Node<N>, Map<Node<N>, Int>) -> Boolean) {
if (from == to) {
paths += path
return
}
val newVisited = visited + (from to visited.getOrDefault(from, 0) + 1)
nodes(from).filter { nodeFilter(it, newVisited) }.forEach {
depthFirst(it, to, newVisited, path + it, paths, nodeFilter)
}
}
private fun setEdge(from: N, to: N, e: E): Edge<N, E> {
val edge = edge(e, get(to))
nodeToEdge.computeIfAbsent(from) { mutableSetOf() } += edge
return edge
}
operator fun get(key: N) = nodes[key] ?: throw NoSuchElementException("No node with key '$key'")
operator fun get(from: N, to: N) = edges(from).first { it.to.key == to }
fun getOrNull(from: N, to: N) = edges(from).firstOrNull { it.to.key == to }
fun edges(key: N): Set<Edge<N, E>> = nodeToEdge[key] ?: emptySet()
fun edges(node: Node<N>) = edges(node.key)
fun nodes(key: N) = edges(key).map { it.to }
fun nodes(node: Node<N>) = edges(node).map { it.to }
fun nodes() : Set<N> = nodes.keys
fun hasEdge(from: N, to: N) : Boolean = edges(from).any { it.to.key == to }
override fun contains(element: N) = nodes.keys.contains(element)
override fun containsAll(elements: Collection<N>) = nodes.keys.containsAll(elements)
override fun isEmpty() = nodes.isEmpty()
override fun iterator() = nodes.keys.iterator()
companion object {
fun <T> node(value: T) = Node(value)
fun <E, N> edge(value: E, node: Node<N>) = Edge(value, node)
fun <E, N> edge(value: E, node: N) = Edge(value, node(node))
}
enum class SearchStrategy {
DEPTH_FIRST
}
}
|
mit
|
d2b578d5e5c5ed2bb92efdb0efb7c587
| 33.491379 | 155 | 0.587353 | 3.491274 | false | false | false | false |
bmunzenb/feed-buddy
|
src/main/kotlin/com/munzenberger/feed/config/FeedProcessorFactory.kt
|
1
|
2058
|
package com.munzenberger.feed.config
import com.munzenberger.feed.FeedContext
import com.munzenberger.feed.Item
import com.munzenberger.feed.engine.FeedProcessor
import com.munzenberger.feed.engine.FileItemRegistry
import com.munzenberger.feed.filter.ItemFilter
import com.munzenberger.feed.handler.ItemHandler
import com.munzenberger.feed.source.XMLFeedSource
import java.net.URL
import java.nio.file.Path
class FeedProcessorFactory(
private val registryDirectory: Path,
private val itemFilterFactory: ItemProcessorFactory<ItemFilter> = DefaultItemProcessorFactory(),
private val itemHandlerFactory: ItemProcessorFactory<ItemHandler> = DefaultItemProcessorFactory()
) {
fun getInstance(feedConfig: FeedConfig): FeedProcessor {
val url = URL(feedConfig.url)
val source = XMLFeedSource(
source = url,
userAgent = feedConfig.userAgent)
val itemRegistry = FileItemRegistry(registryDirectory.resolve(url.registryFilename))
val itemFilter = object : ItemFilter {
private val filters = feedConfig.filters.map(itemFilterFactory::getInstance)
override fun evaluate(context: FeedContext, item: Item): Boolean {
return filters.all { it.evaluate(context, item) }
}
}
val itemHandler = object : ItemHandler {
private val handlers = feedConfig.handlers.map(itemHandlerFactory::getInstance)
override fun execute(context: FeedContext, item: Item) {
handlers.forEach { it.execute(context, item) }
}
}
return FeedProcessor(source, itemRegistry, itemFilter, itemHandler)
}
}
fun String.filteredForPath(): String {
val invalidChars = "<>:\"/\\|?*="
val sb = StringBuilder(this)
for (i in sb.indices) {
if (sb[i] in invalidChars) {
sb[i] = '-'
}
}
return sb.toString()
}
private val URL.registryFilename: String
get() = host.filteredForPath() + file.filteredForPath() + ".processed"
|
apache-2.0
|
bf320de75f1b1041ab39c62053710f50
| 33.881356 | 105 | 0.682702 | 4.543046 | false | true | false | false |
choyg/Hiking-Altimeter
|
app/src/main/java/org/testb/java/altimeter/view/calibrate/CalibratePresenterImpl.kt
|
1
|
2274
|
package org.testb.java.altimeter.view.calibrate
import com.f2prateek.rx.preferences2.RxSharedPreferences
import io.reactivex.disposables.CompositeDisposable
import org.testb.java.altimeter.*
import org.testb.java.altimeter.Unit
import org.testb.java.altimeter.service.AltimeterService
class CalibratePresenterImpl(val view: CalibrateView,
preference: RxSharedPreferences,
val altimeterService: AltimeterService
) : CalibratePresenter {
val compositeDisposable = CompositeDisposable()
val unitPref = preference.getEnum(PREF_UNITS, Unit.m, Unit::class.java)
val calibrationPresurePref = preference.getFloat(PREF_CALIBRATION_PRESSURE)
val calibrationTimepref = preference.getLong(PREF_CALIBRATION_TIME)
var altitudeString = "0"
override fun attachView() {
view.setCalibrationText(altitudeString, unitPref.get())
unitPref.asObservable()
.subscribe {
view.setCalibrationText(altitudeString, it)
}
}
override fun detachView() {
compositeDisposable.clear()
}
override fun setCalibration() {
var knownAltitude = altitudeString.toDouble()
if (unitPref.get() == Unit.ft) {
knownAltitude = convertFeetToMeters(knownAltitude)
}
val qnh = calculateQNH(knownAltitude, altimeterService.getPressureOnce())
calibrationPresurePref.set(qnh.toFloat())
calibrationTimepref.set(System.currentTimeMillis())
}
override fun clearCalibration() {
altitudeString = "0"
view.setCalibrationText(altitudeString, unitPref.get())
}
override fun appendCalibration(char: Char) {
if (altitudeString.length > 8 || (char == '.' && altitudeString.contains('.')))
return
if (altitudeString == "0" && char != '.') {
altitudeString = char.toString()
} else {
altitudeString += char
}
view.setCalibrationText(altitudeString, unitPref.get())
view.save(altitudeString)
}
override fun onLoad(altitude: String) {
altitudeString = altitude
view.setCalibrationText(altitudeString, unitPref.get())
view.save(altitudeString)
}
}
|
mit
|
b827cdbc5f9148047df4b2c1f6dbb51d
| 33.469697 | 87 | 0.66095 | 4.424125 | false | true | false | false |
fluidsonic/fluid-json
|
coding/sources-jvm/implementations/FixedCodecProvider.kt
|
1
|
1857
|
package io.fluidsonic.json
import java.util.concurrent.*
import kotlin.reflect.*
internal class FixedCodecProvider<in Context : JsonCodingContext>(
providers: Iterable<JsonCodecProvider<Context>>
) : JsonCodecProvider<Context> {
private val providers = providers.toSet().toTypedArray()
private val decoderCodecByType = ConcurrentHashMap<JsonCodingType<*>, JsonDecoderCodec<*, Context>>()
private val encoderCodecByClass = ConcurrentHashMap<KClass<*>, JsonEncoderCodec<*, Context>>()
@Suppress("LoopToCallChain", "UNCHECKED_CAST")
override fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>? {
return decoderCodecByType.getOrPut(decodableType) {
for (provider in providers) {
val decoder = provider.decoderCodecForType(decodableType)
if (decoder != null) {
return@getOrPut decoder
}
}
return null
} as JsonDecoderCodec<ActualValue, Context>
}
@Suppress("LoopToCallChain", "UNCHECKED_CAST")
override fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>? {
return encoderCodecByClass.getOrPut(encodableClass) {
for (provider in providers) {
val encoder = provider.encoderCodecForClass(encodableClass)
if (encoder != null) {
return@getOrPut encoder
}
}
return null
} as JsonEncoderCodec<ActualValue, Context>
}
}
@Suppress("FunctionName")
public fun <Context : JsonCodingContext> JsonCodecProvider(
vararg providers: JsonCodecProvider<Context>
): JsonCodecProvider<Context> =
JsonCodecProvider(providers.asIterable())
@Suppress("FunctionName")
public fun <Context : JsonCodingContext> JsonCodecProvider(
providers: Iterable<JsonCodecProvider<Context>>
): JsonCodecProvider<Context> =
FixedCodecProvider(providers = providers)
|
apache-2.0
|
123c10c87b39a6ce70949c782cf494c4
| 30.474576 | 140 | 0.767905 | 4.308585 | false | false | false | false |
allotria/intellij-community
|
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/TreeExpanderAction.kt
|
1
|
1753
|
// 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.analysis.problemsView.toolWindow
import com.intellij.ide.TreeExpander
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.project.DumbAwareAction
internal class TreeExpandAllAction : TreeExpanderAction(IdeActions.ACTION_EXPAND_ALL) {
override fun isEnabled(expander: TreeExpander) = expander.canExpand()
override fun actionPerformed(expander: TreeExpander) = expander.expandAll()
}
internal class TreeCollapseAllAction : TreeExpanderAction(IdeActions.ACTION_COLLAPSE_ALL) {
override fun isEnabled(expander: TreeExpander) = expander.canCollapse()
override fun actionPerformed(expander: TreeExpander) = expander.collapseAll()
}
internal abstract class TreeExpanderAction(actionId: String) : DumbAwareAction() {
init {
ActionManager.getInstance().getAction(actionId)?.let { copyFrom(it) }
}
private fun getExpander(event: AnActionEvent) = ProblemsView.getSelectedPanel(event.project)?.treeExpander
abstract fun isEnabled(expander: TreeExpander): Boolean
override fun update(event: AnActionEvent) {
val expander = ProblemsView.getSelectedPanel(event.project)?.treeExpander
event.presentation.isEnabled = expander?.let { isEnabled(it) } ?: false
event.presentation.isVisible = expander != null
}
abstract fun actionPerformed(expander: TreeExpander)
override fun actionPerformed(event: AnActionEvent) {
val expander = getExpander(event) ?: return
if (isEnabled(expander)) actionPerformed(expander)
}
}
|
apache-2.0
|
9c6a9b8fb7189b40e804431df2dc0560
| 43.948718 | 140 | 0.795208 | 4.60105 | false | false | false | false |
scenerygraphics/scenery
|
src/main/kotlin/graphics/scenery/backends/opengl/OpenGLRenderer.kt
|
1
|
119327
|
package graphics.scenery.backends.opengl
import cleargl.*
import com.jogamp.nativewindow.WindowClosingProtocol
import com.jogamp.newt.event.WindowAdapter
import com.jogamp.newt.event.WindowEvent
import com.jogamp.opengl.*
import com.jogamp.opengl.util.Animator
import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil
import graphics.scenery.*
import graphics.scenery.backends.*
import graphics.scenery.geometry.GeometryType
import graphics.scenery.primitives.Plane
import graphics.scenery.attribute.HasDelegationType
import graphics.scenery.attribute.DelegationType
import graphics.scenery.attribute.geometry.Geometry
import graphics.scenery.attribute.material.Material
import graphics.scenery.attribute.renderable.Renderable
import graphics.scenery.textures.Texture
import graphics.scenery.textures.Texture.BorderColor
import graphics.scenery.textures.Texture.RepeatMode
import graphics.scenery.textures.UpdatableTexture
import graphics.scenery.utils.*
import kotlinx.coroutines.*
import net.imglib2.type.numeric.NumericType
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.DoubleType
import net.imglib2.type.numeric.real.FloatType
import org.joml.*
import org.lwjgl.system.MemoryUtil
import org.lwjgl.system.Platform
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.image.DataBufferInt
import java.io.File
import java.io.FileOutputStream
import java.lang.Math
import java.lang.reflect.Field
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.IntBuffer
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
import javax.imageio.ImageIO
import javax.swing.BorderFactory
import kotlin.collections.LinkedHashMap
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
/**
* Deferred Lighting Renderer for scenery
*
* This is the main class of scenery's Deferred Lighting Renderer. Currently,
* a rendering strategy using a 32bit position, 16bit normal, 32bit RGBA diffuse/albedo,
* and 24bit depth buffer is employed. The renderer supports HDR rendering and does that
* by default. By deactivating the `hdr.Active` [Settings], HDR can be programmatically
* deactivated. The renderer also supports drawing to HMDs via OpenVR. If this is intended,
* make sure the `vr.Active` [Settings] is set to `true`, and that the `Hub` has a HMD
* instance attached.
*
* @param[hub] Hub instance to use and attach to.
* @param[applicationName] The name of this application.
* @param[scene] The [Scene] instance to initialize first.
* @param[width] Horizontal window size.
* @param[height] Vertical window size.
* @param[embedIn] An optional [SceneryPanel] in which to embed the renderer instance.
* @param[renderConfigFile] The file to create a [RenderConfigReader.RenderConfig] from.
*
* @author Ulrik Günther <[email protected]>
*/
@Suppress("MemberVisibilityCanBePrivate")
open class OpenGLRenderer(hub: Hub,
applicationName: String,
scene: Scene,
width: Int,
height: Int,
renderConfigFile: String,
final override var embedIn: SceneryPanel? = null,
var embedInDrawable: GLAutoDrawable? = null) : Renderer(), Hubable, ClearGLEventListener {
/** slf4j logger */
private val logger by LazyLogger()
private val className = this.javaClass.simpleName
/** [GL4] instance handed over, coming from [ClearGLDefaultEventListener]*/
private lateinit var gl: GL4
/** should the window close on next looping? */
@Volatile override var shouldClose = false
/** the scenery window */
final override var window: SceneryWindow = SceneryWindow.UninitializedWindow()
/** separately stored ClearGLWindow */
var cglWindow: ClearGLWindow? = null
/** drawble for offscreen rendering */
var drawable: GLAutoDrawable? = null
/** Whether the renderer manages its own event loop, which is the case for this one. */
override var managesRenderLoop = true
/** The currently active scene */
var scene: Scene = Scene()
/** Cache of [Node]s, needed e.g. for fullscreen quad rendering */
private var nodeStore = ConcurrentHashMap<String, Node>()
/** [Settings] for the renderer */
final override var settings: Settings = Settings()
/** The hub used for communication between the components */
final override var hub: Hub?
private var textureCache = HashMap<String, GLTexture>()
private var shaderPropertyCache = HashMap<Class<*>, List<Field>>()
private var uboCache = ConcurrentHashMap<String, OpenGLUBO>()
private var joglDrawable: GLAutoDrawable? = null
private var screenshotRequested = false
private var screenshotOverwriteExisting = false
private var screenshotFilename = ""
private var encoder: VideoEncoder? = null
private var recordMovie = false
private var movieFilename = ""
/**
* Activate or deactivate push-based rendering mode (render only on scene changes
* or input events). Push mode is activated if [pushMode] is true.
*/
override var pushMode: Boolean = false
private var updateLatch: CountDownLatch? = null
private var lastResizeTimer = Timer()
@Volatile private var mustRecreateFramebuffers = false
private var framebufferRecreateHook: () -> Unit = {}
private var gpuStats: GPUStats? = null
private var maxTextureUnits = 8
/** heartbeat timer */
private var heartbeatTimer = Timer()
override var lastFrameTime = System.nanoTime() * 1.0f
private var currentTime = System.nanoTime()
@Volatile override var initialized = false
override var firstImageReady: Boolean = false
protected set
protected var frames = 0L
var fps = 0
protected set
protected var framesPerSec = 0
val pboCount = 2
@Volatile private var pbos: IntArray = IntArray(pboCount) { 0 }
private var pboBuffers: Array<ByteBuffer?> = Array(pboCount) { null }
private var readIndex = 0
private var updateIndex = 1
private var renderCalled = false
private var renderConfig: RenderConfigReader.RenderConfig
final override var renderConfigFile = ""
set(config) {
field = config
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
mustRecreateFramebuffers = true
}
private var renderpasses = LinkedHashMap<String, OpenGLRenderpass>()
private var flow: List<String>
/**
* Extension function of Boolean to use Booleans in GLSL
*
* This function converts a Boolean to Int 0, if false, and to 1, if true
*/
fun Boolean.toInt(): Int {
return if (this) {
1
} else {
0
}
}
var applicationName = ""
inner class OpenGLResizeHandler: ResizeHandler {
@Volatile override var lastResize = -1L
override var lastWidth = 0
override var lastHeight = 0
@Synchronized override fun queryResize() {
if (lastWidth <= 0 || lastHeight <= 0) {
lastWidth = Math.max(1, lastWidth)
lastHeight = Math.max(1, lastHeight)
return
}
if (lastResize > 0L && lastResize + WINDOW_RESIZE_TIMEOUT < System.nanoTime()) {
lastResize = System.nanoTime()
return
}
if (lastWidth == window.width && lastHeight == window.height) {
return
}
mustRecreateFramebuffers = true
gl.glDeleteBuffers(pboCount, pbos, 0)
pbos = IntArray(pboCount) { 0 }
lastWidth = window.width
lastHeight = window.height
if(drawable is GLOffscreenAutoDrawable) {
(drawable as? GLOffscreenAutoDrawable)?.setSurfaceSize(window.width, window.height)
}
logger.debug("queryResize: $lastWidth/$lastHeight")
lastResize = -1L
}
}
/**
* OpenGL Buffer class, creates a buffer associated with the context [gl] and size [size] in bytes.
*
* @author Ulrik Guenther <[email protected]>
*/
class OpenGLBuffer(var gl: GL4, var size: Int) {
/** Temporary buffer for data before it is sent to the GPU. */
var buffer: ByteBuffer
private set
/** OpenGL id of the buffer. */
var id = intArrayOf(-1)
private set
/** Required buffer offset alignment for uniform buffers, determined from [GL4.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT] */
var alignment = 256L
private set
init {
val tmp = intArrayOf(0, 0)
gl.glGetIntegerv(GL4.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, tmp, 0)
alignment = tmp[0].toLong()
gl.glGenBuffers(1, id, 0)
buffer = MemoryUtil.memAlloc(maxOf(tmp[0], size))
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferData(GL4.GL_UNIFORM_BUFFER, size * 1L, null, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
}
/** Copies the [buffer] from main memory to GPU memory. */
fun copyFromStagingBuffer() {
buffer.flip()
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferSubData(GL4.GL_UNIFORM_BUFFER, 0, buffer.remaining() * 1L, buffer)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
}
/** Resets staging buffer position and limit */
fun reset() {
buffer.position(0)
buffer.limit(size)
}
/**
* Resizes the backing buffer to [newSize], which is 1.5x the original size by default,
* and returns the staging buffer.
*/
fun resize(newSize: Int = (buffer.capacity() * 1.5f).roundToInt()): ByteBuffer {
logger.debug("Resizing backing buffer of $this from ${buffer.capacity()} to $newSize")
// resize main memory-backed buffer
buffer = MemoryUtil.memRealloc(buffer, newSize) ?: throw IllegalStateException("Could not resize buffer")
size = buffer.capacity()
// resize OpenGL buffer as well
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, id[0])
gl.glBufferData(GL4.GL_UNIFORM_BUFFER, size * 1L, null, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0)
return buffer
}
/**
* Returns the [buffer]'s remaining bytes.
*/
fun remaining() = buffer.remaining()
/**
* Advances the backing buffer for population, aligning it by [alignment], or any given value
* that overrides it (not recommended), returns the buffers new position.
*/
fun advance(align: Long = this.alignment): Int {
val pos = buffer.position()
val rem = pos.rem(align)
if (rem != 0L) {
val newpos = pos + align.toInt() - rem.toInt()
buffer.position(newpos)
}
return buffer.position()
}
}
data class DefaultBuffers(var UBOs: OpenGLBuffer,
var LightParameters: OpenGLBuffer,
var ShaderParameters: OpenGLBuffer,
var VRParameters: OpenGLBuffer,
var ShaderProperties: OpenGLBuffer)
protected lateinit var buffers: DefaultBuffers
protected val sceneUBOs = CopyOnWriteArrayList<Node>()
protected val resizeHandler = OpenGLResizeHandler()
companion object {
private const val WINDOW_RESIZE_TIMEOUT = 200L
private const val MATERIAL_HAS_DIFFUSE = 0x0001
private const val MATERIAL_HAS_AMBIENT = 0x0002
private const val MATERIAL_HAS_SPECULAR = 0x0004
private const val MATERIAL_HAS_NORMAL = 0x0008
private const val MATERIAL_HAS_ALPHAMASK = 0x0010
}
/**
* Constructor for OpenGLRenderer, initialises geometry buffers
* according to eye configuration. Also initialises different rendering passes.
*
*/
init {
logger.info("Initializing OpenGL Renderer...")
this.hub = hub
this.settings = loadDefaultRendererSettings(hub.get(SceneryElement.Settings) as Settings)
this.window.width = width
this.window.height = height
this.renderConfigFile = renderConfigFile
this.renderConfig = RenderConfigReader().loadFromFile(renderConfigFile)
this.flow = this.renderConfig.createRenderpassFlow()
logger.info("Loaded ${renderConfig.name} (${renderConfig.description ?: "no description"})")
this.scene = scene
this.applicationName = applicationName
val hmd = hub.getWorkingHMDDisplay()
if (settings.get("vr.Active") && hmd != null) {
this.window.width = hmd.getRenderTargetSize().x() * 2
this.window.height = hmd.getRenderTargetSize().y()
}
if (embedIn != null || embedInDrawable != null) {
if (embedIn != null && embedInDrawable == null) {
val profile = GLProfile.getMaxProgrammableCore(true)
if (!profile.isGL4) {
throw UnsupportedOperationException("Could not create OpenGL 4 context, perhaps you need a graphics driver update?")
}
val caps = GLCapabilities(profile)
caps.hardwareAccelerated = true
caps.doubleBuffered = true
caps.isOnscreen = false
caps.numSamples = 1
caps.isPBuffer = true
caps.redBits = 8
caps.greenBits = 8
caps.blueBits = 8
caps.alphaBits = 8
val panel = embedIn
/* maybe better?
var canvas: ClearGLWindow? = null
SwingUtilities.invokeAndWait {
canvas = ClearGLWindow("", width, height, this)
canvas!!.newtCanvasAWT.shallUseOffscreenLayer = true
panel.component = canvas!!.newtCanvasAWT
panel.layout = BorderLayout()
panel.add(canvas!!.newtCanvasAWT, BorderLayout.CENTER)
panel.preferredSize = Dimension(width, height)
val frame = SwingUtilities.getAncestorOfClass(JFrame::class.java, panel) as JFrame
frame.preferredSize = Dimension(width, height)
frame.layout = BorderLayout()
frame.pack()
frame.isVisible = true
}
canvas!!.glAutoDrawable
*/
drawable = if (panel is SceneryJPanel) {
val surfaceScale = hub.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f)
this.window.width = (panel.width * surfaceScale.x()).toInt()
this.window.height = (panel.height * surfaceScale.y()).toInt()
panel.panelWidth = this.window.width
panel.panelHeight = this.window.height
logger.debug("Surface scale: $surfaceScale")
val canvas = ClearGLWindow("",
this.window.width,
this.window.height, null)
canvas.newtCanvasAWT.shallUseOffscreenLayer = true
panel.component = canvas.newtCanvasAWT
panel.cglWindow = canvas
panel.layout = BorderLayout()
panel.preferredSize = Dimension(
(window.width * surfaceScale.x()).toInt(),
(window.height * surfaceScale.y()).toInt())
canvas.newtCanvasAWT.preferredSize = panel.preferredSize
panel.border = BorderFactory.createEmptyBorder()
panel.add(canvas.newtCanvasAWT, BorderLayout.CENTER)
cglWindow = canvas
canvas.glAutoDrawable
} else {
val factory = GLDrawableFactory.getFactory(profile)
factory.createOffscreenAutoDrawable(factory.defaultDevice, caps,
DefaultGLCapabilitiesChooser(), window.width, window.height)
}
} else {
drawable = embedInDrawable
}
drawable?.apply {
addGLEventListener(this@OpenGLRenderer)
animator = Animator()
animator.add(this)
animator.start()
embedInDrawable?.let { glAutoDrawable ->
window = SceneryWindow.JOGLDrawable(glAutoDrawable)
}
window.width = width
window.height = height
resizeHandler.lastWidth = window.width
resizeHandler.lastHeight = window.height
embedIn?.let { panel ->
panel.imageScaleY = -1.0f
window = panel.init(resizeHandler)
val surfaceScale = hub.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f)
window.width = (panel.panelWidth * surfaceScale.x()).toInt()
window.height = (panel.panelHeight * surfaceScale.y()).toInt()
}
resizeHandler.lastWidth = window.width
resizeHandler.lastHeight = window.height
}
} else {
val w = this.window.width
val h = this.window.height
// need to leak this here unfortunately
@Suppress("LeakingThis")
cglWindow = ClearGLWindow("",
w,
h, this,
false).apply {
if(embedIn == null) {
window = SceneryWindow.ClearGLWindow(this)
window.width = w
window.height = h
val windowAdapter = object: WindowAdapter() {
override fun windowDestroyNotify(e: WindowEvent?) {
logger.debug("Signalling close from window event")
e?.isConsumed = true
}
}
this.addWindowListener(windowAdapter)
this.setFPS(60)
this.start()
this.setDefaultCloseOperation(WindowClosingProtocol.WindowClosingMode.DISPOSE_ON_CLOSE)
this.isVisible = true
}
}
}
while(!initialized) {
Thread.sleep(20)
}
}
override fun init(pDrawable: GLAutoDrawable) {
this.gl = pDrawable.gl.gL4
val width = this.window.width
val height = this.window.height
gl.swapInterval = 0
val driverString = gl.glGetString(GL4.GL_RENDERER)
val driverVersion = gl.glGetString(GL4.GL_VERSION)
logger.info("OpenGLRenderer: $width x $height on $driverString, $driverVersion")
if (driverVersion.lowercase().indexOf("nvidia") != -1 && System.getProperty("os.name").lowercase().indexOf("windows") != -1) {
gpuStats = NvidiaGPUStats()
}
val tmp = IntArray(1)
gl.glGetIntegerv(GL4.GL_MAX_TEXTURE_IMAGE_UNITS, tmp, 0)
maxTextureUnits = tmp[0]
val numExtensionsBuffer = IntBuffer.allocate(1)
gl.glGetIntegerv(GL4.GL_NUM_EXTENSIONS, numExtensionsBuffer)
val extensions = (0 until numExtensionsBuffer[0]).map { gl.glGetStringi(GL4.GL_EXTENSIONS, it) }
logger.debug("Available OpenGL extensions: ${extensions.joinToString(", ")}")
settings.set("ssao.FilterRadius", Vector2f(5.0f / width, 5.0f / height))
buffers = DefaultBuffers(
UBOs = OpenGLBuffer(gl, 10 * 1024 * 1024),
LightParameters = OpenGLBuffer(gl, 10 * 1024 * 1024),
VRParameters = OpenGLBuffer(gl, 2 * 1024),
ShaderProperties = OpenGLBuffer(gl, 10 * 1024 * 1024),
ShaderParameters = OpenGLBuffer(gl, 128 * 1024))
prepareDefaultTextures()
renderpasses = prepareRenderpasses(renderConfig, window.width, window.height)
// enable required features
// gl.glEnable(GL4.GL_TEXTURE_GATHER)
gl.glEnable(GL4.GL_PROGRAM_POINT_SIZE)
heartbeatTimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
fps = framesPerSec
framesPerSec = 0
if(!pushMode) {
(hub?.get(SceneryElement.Statistics) as? Statistics)?.add("Renderer.fps", fps, false)
}
gpuStats?.let {
it.update(0)
hub?.get(SceneryElement.Statistics).let { s ->
val stats = s as Statistics
stats.add("GPU", it.get("GPU"), isTime = false)
stats.add("GPU bus", it.get("Bus"), isTime = false)
stats.add("GPU mem", it.get("AvailableDedicatedVideoMemory"), isTime = false)
}
if (settings.get("Renderer.PrintGPUStats")) {
logger.info(it.utilisationToString())
logger.info(it.memoryUtilisationToString())
}
}
}
}, 0, 1000)
initialized = true
}
private fun Renderable.rendererMetadata(): OpenGLObjectState? {
return this.metadata["OpenGLRenderer"] as? OpenGLObjectState
}
private fun getSupersamplingFactor(window: ClearGLWindow?): Float {
val supersamplingFactor = if(settings.get<Float>("Renderer.SupersamplingFactor").toInt() == 1) {
if(window != null && ClearGLWindow.isRetina(window.gl)) {
logger.debug("Setting Renderer.SupersamplingFactor to 0.5, as we are rendering on a retina display.")
settings.set("Renderer.SupersamplingFactor", 0.5f)
0.5f
} else {
settings.get("Renderer.SupersamplingFactor")
}
} else {
settings.get("Renderer.SupersamplingFactor")
}
return supersamplingFactor
}
fun prepareRenderpasses(config: RenderConfigReader.RenderConfig, windowWidth: Int, windowHeight: Int): LinkedHashMap<String, OpenGLRenderpass> {
if(config.sRGB) {
gl.glEnable(GL4.GL_FRAMEBUFFER_SRGB)
} else {
gl.glDisable(GL4.GL_FRAMEBUFFER_SRGB)
}
buffers.ShaderParameters.reset()
val framebuffers = ConcurrentHashMap<String, GLFramebuffer>()
val passes = LinkedHashMap<String, OpenGLRenderpass>()
val flow = renderConfig.createRenderpassFlow()
val supersamplingFactor = getSupersamplingFactor(cglWindow)
scene.findObserver()?.let { cam ->
when(cam.projectionType) {
Camera.ProjectionType.Perspective -> cam.perspectiveCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
Camera.ProjectionType.Orthographic -> cam.orthographicCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
Camera.ProjectionType.Undefined -> {
logger.warn("Camera ${cam.name} has undefined projection type, using default perspective projection")
cam.perspectiveCamera(
cam.fov,
(windowWidth * supersamplingFactor).roundToInt(),
(windowHeight * supersamplingFactor).roundToInt(),
cam.nearPlaneDistance,
cam.farPlaneDistance
)
}
}
}
settings.set("Renderer.displayWidth", (windowWidth * supersamplingFactor).toInt())
settings.set("Renderer.displayHeight", (windowHeight * supersamplingFactor).toInt())
flow.map { passName ->
val passConfig = config.renderpasses.getValue(passName)
val pass = OpenGLRenderpass(passName, passConfig)
var width = windowWidth
var height = windowHeight
config.rendertargets.filter { it.key == passConfig.output.name }.map { rt ->
width = (supersamplingFactor * windowWidth * rt.value.size.first).toInt()
height = (supersamplingFactor * windowHeight * rt.value.size.second).toInt()
logger.info("Creating render framebuffer ${rt.key} for pass $passName (${width}x$height)")
settings.set("Renderer.$passName.displayWidth", width)
settings.set("Renderer.$passName.displayHeight", height)
if (framebuffers.containsKey(rt.key)) {
logger.info("Reusing already created framebuffer")
pass.output.put(rt.key, framebuffers.getValue(rt.key))
} else {
val framebuffer = GLFramebuffer(gl, width, height, renderConfig.sRGB)
rt.value.attachments.forEach { att ->
logger.info(" + attachment ${att.key}, ${att.value.name}")
when (att.value) {
RenderConfigReader.TargetFormat.RGBA_Float32 -> framebuffer.addFloatRGBABuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RGBA_Float16 -> framebuffer.addFloatRGBABuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGB_Float32 -> framebuffer.addFloatRGBBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RGB_Float16 -> framebuffer.addFloatRGBBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RG_Float32 -> framebuffer.addFloatRGBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.RG_Float16 -> framebuffer.addFloatRGBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.R_Float16 -> framebuffer.addFloatRBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGBA_UInt16 -> framebuffer.addUnsignedByteRGBABuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.RGBA_UInt8 -> framebuffer.addUnsignedByteRGBABuffer(gl, att.key, 8)
RenderConfigReader.TargetFormat.R_UInt16 -> framebuffer.addUnsignedByteRBuffer(gl, att.key, 16)
RenderConfigReader.TargetFormat.R_UInt8 -> framebuffer.addUnsignedByteRBuffer(gl, att.key, 8)
RenderConfigReader.TargetFormat.Depth32 -> framebuffer.addDepthBuffer(gl, att.key, 32)
RenderConfigReader.TargetFormat.Depth24 -> framebuffer.addDepthBuffer(gl, att.key, 24)
}
}
pass.output[rt.key] = framebuffer
framebuffers.put(rt.key, framebuffer)
}
}
if(passConfig.output.name == "Viewport") {
width = (supersamplingFactor * windowWidth).toInt()
height = (supersamplingFactor * windowHeight).toInt()
logger.info("Creating render framebuffer Viewport for pass $passName (${width}x$height)")
settings.set("Renderer.$passName.displayWidth", width)
settings.set("Renderer.$passName.displayHeight", height)
val framebuffer = GLFramebuffer(gl, width, height)
framebuffer.addUnsignedByteRGBABuffer(gl, "Viewport", 8)
pass.output["Viewport"] = framebuffer
framebuffers["Viewport"] = framebuffer
}
pass.openglMetadata.renderArea = OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt())
logger.debug("Render area for $passName: ${pass.openglMetadata.renderArea.width}x${pass.openglMetadata.renderArea.height}")
pass.openglMetadata.viewport = OpenGLRenderpass.Viewport(OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt()),
0.0f, 1.0f)
pass.openglMetadata.scissor = OpenGLRenderpass.Rect2D(
(pass.passConfig.viewportSize.first * width).toInt(),
(pass.passConfig.viewportSize.second * height).toInt(),
(pass.passConfig.viewportOffset.first * width).toInt(),
(pass.passConfig.viewportOffset.second * height).toInt())
pass.openglMetadata.eye = pass.passConfig.eye
pass.defaultShader = prepareShaderProgram(
Shaders.ShadersFromFiles(pass.passConfig.shaders.map { "shaders/$it" }.toTypedArray()))
pass.initializeShaderParameters(settings, buffers.ShaderParameters)
passes.put(passName, pass)
}
// connect inputs
passes.forEach { pass ->
val passConfig = config.renderpasses.getValue(pass.key)
passConfig.inputs?.forEach { inputTarget ->
val targetName = if(inputTarget.name.contains(".")) {
inputTarget.name.substringBefore(".")
} else {
inputTarget.name
}
passes.filter {
it.value.output.keys.contains(targetName)
}.forEach {
val output = it.value.output[targetName] ?: throw IllegalStateException("Output for $targetName not found in configuration")
pass.value.inputs[inputTarget.name] = output
}
}
with(pass.value) {
// initialize pass if needed
}
}
return passes
}
protected fun prepareShaderProgram(shaders: Shaders): OpenGLShaderProgram? {
val modules = HashMap<ShaderType, OpenGLShaderModule>()
ShaderType.values().forEach { type ->
try {
// we still request Vulkan shaders here, albeit working on OpenGL, as the shaders
// are written for Vulkan and will be converted on-the-fly by [OpenGLShaderModule].
val m = OpenGLShaderModule.getFromCacheOrCreate(gl, "main", shaders.get(Shaders.ShaderTarget.Vulkan, type))
modules[m.shaderType] = m
} catch (e: ShaderNotFoundException) {
if(shaders is Shaders.ShadersFromFiles) {
logger.debug("Could not locate shader for $shaders, type=$type, ${shaders.shaders.joinToString(",")} - this is normal if there are no errors reported")
} else {
logger.debug("Could not locate shader for $shaders, type=$type - this is normal if there are no errors reported")
}
}
}
val program = OpenGLShaderProgram(gl, modules)
return if(program.isValid()) {
program
} else {
null
}
}
override fun display(pDrawable: GLAutoDrawable) {
val fps = pDrawable.animator?.lastFPS ?: 0.0f
if(embedIn == null) {
window.title = "$applicationName [${[email protected]}] - ${fps.toInt()} fps"
}
this.joglDrawable = pDrawable
if (mustRecreateFramebuffers) {
logger.info("Recreating framebuffers (${window.width}x${window.height})")
// FIXME: This needs to be done here in order to be able to run on HiDPI screens correctly
// FIXME: On macOS, this _must_ not be called, otherwise JOGL bails out, on Windows, it needs to be called.
if(embedIn != null && Platform.get() != Platform.MACOSX) {
cglWindow?.newtCanvasAWT?.setBounds(0, 0, window.width, window.height)
}
renderpasses = prepareRenderpasses(renderConfig, window.width, window.height)
flow = renderConfig.createRenderpassFlow()
framebufferRecreateHook.invoke()
frames = 0
mustRecreateFramebuffers = false
}
[email protected]()
}
override fun setClearGLWindow(pClearGLWindow: ClearGLWindow) {
cglWindow = pClearGLWindow
}
override fun getClearGLWindow(): ClearGLDisplayable {
return cglWindow ?: throw IllegalStateException("No ClearGL window available")
}
override fun reshape(pDrawable: GLAutoDrawable,
pX: Int,
pY: Int,
pWidth: Int,
pHeight: Int) {
var height = pHeight
if (height == 0)
height = 1
[email protected](pWidth, height)
}
override fun dispose(pDrawable: GLAutoDrawable) {
initialized = false
try {
scene.discover(scene, { _ -> true }).forEach {
destroyNode(it, onShutdown = true)
}
// The hub might contain elements that are both in the scene graph,
// and in the hub, e.g. a VolumeManager. We clean them here as well.
hub?.find { it is Node }?.forEach { (_, node) ->
(node as? Node)?.let { destroyNode(it, onShutdown = true) }
}
hub?.elements?.values?.forEach {
(it as? Node)?.renderableOrNull()?.close()
}
scene.initialized = false
if(cglWindow != null) {
logger.debug("Closing window")
joglDrawable?.animator?.stop()
} else {
logger.debug("Closing drawable")
joglDrawable?.animator?.stop()
}
} catch(e: ThreadDeath) {
logger.debug("Caught JOGL ThreadDeath, ignoring.")
}
}
/**
* Based on the [GLFramebuffer], devises a texture unit that can be used
* for object textures.
*
* @param[type] texture type
* @return Int of the texture unit to be used
*/
fun textureTypeToUnit(target: OpenGLRenderpass, type: String): Int {
val offset = if (target.inputs.values.isNotEmpty()) {
target.inputs.values.sumOf { it.boundBufferNum }
} else {
0
}
return offset + when (type) {
"ambient" -> 0
"diffuse" -> 1
"specular" -> 2
"normal" -> 3
"alphamask" -> 4
"displacement" -> 5
"3D-volume" -> 6
else -> {
logger.warn("Unknown ObjecTextures type $type")
0
}
}
}
private fun textureTypeToArrayName(type: String): String {
return when (type) {
"ambient" -> "ObjectTextures[0]"
"diffuse" -> "ObjectTextures[1]"
"specular" -> "ObjectTextures[2]"
"normal" -> "ObjectTextures[3]"
"alphamask" -> "ObjectTextures[4]"
"displacement" -> "ObjectTextures[5]"
"3D-volume" -> "VolumeTextures"
else -> {
logger.debug("Unknown texture type $type")
type
}
}
}
/**
* Converts a [GeometryType] to an OpenGL geometry type
*
* @return Int of the OpenGL geometry type.
*/
private fun GeometryType.toOpenGLType(): Int {
return when (this) {
GeometryType.TRIANGLE_STRIP -> GL4.GL_TRIANGLE_STRIP
GeometryType.POLYGON -> GL4.GL_TRIANGLES
GeometryType.TRIANGLES -> GL4.GL_TRIANGLES
GeometryType.TRIANGLE_FAN -> GL4.GL_TRIANGLE_FAN
GeometryType.POINTS -> GL4.GL_POINTS
GeometryType.LINE -> GL4.GL_LINE_STRIP
GeometryType.LINES_ADJACENCY -> GL4.GL_LINES_ADJACENCY
GeometryType.LINE_STRIP_ADJACENCY -> GL4.GL_LINE_STRIP_ADJACENCY
}
}
fun Int.toggle(): Int {
if (this == 0) {
return 1
} else if (this == 1) {
return 0
}
logger.warn("Property is not togglable.")
return this
}
/**
* Toggles deferred shading buffer debug view. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand]
*/
@Suppress("UNUSED")
fun toggleDebug() {
settings.getAllSettings().forEach {
if (it.lowercase().contains("debug")) {
try {
val property = settings.get<Int>(it).toggle()
settings.set(it, property)
} catch(e: Exception) {
logger.warn("$it is a property that is not togglable.")
}
}
}
}
/**
* Toggles Screen-space ambient occlusion. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun toggleSSAO() {
if (!settings.get<Boolean>("ssao.Active")) {
settings.set("ssao.Active", true)
} else {
settings.set("ssao.Active", false)
}
}
/**
* Toggles HDR rendering. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun toggleHDR() {
if (!settings.get<Boolean>("hdr.Active")) {
settings.set("hdr.Active", true)
} else {
settings.set("hdr.Active", false)
}
}
/**
* Increases the HDR exposure value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun increaseExposure() {
val exp: Float = settings.get("hdr.Exposure")
settings.set("hdr.Exposure", exp + 0.05f)
}
/**
* Decreases the HDR exposure value.Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("UNUSED")
fun decreaseExposure() {
val exp: Float = settings.get("hdr.Exposure")
settings.set("hdr.Exposure", exp - 0.05f)
}
/**
* Increases the HDR gamma value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun increaseGamma() {
val gamma: Float = settings.get("hdr.Gamma")
settings.set("hdr.Gamma", gamma + 0.05f)
}
/**
* Decreases the HDR gamma value. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun decreaseGamma() {
val gamma: Float = settings.get("hdr.Gamma")
if (gamma - 0.05f >= 0) settings.set("hdr.Gamma", gamma - 0.05f)
}
/**
* Toggles fullscreen. Used for e.g.
* [graphics.scenery.controls.behaviours.ToggleCommand].
*/
@Suppress("unused")
fun toggleFullscreen() {
if (!settings.get<Boolean>("wantsFullscreen")) {
settings.set("wantsFullscreen", true)
} else {
settings.set("wantsFullscreen", false)
}
}
/**
* Convenience function that extracts the [OpenGLObjectState] from a [Node]'s
* metadata.
*
* @param[renderable] The node of interest
* @return The [OpenGLObjectState] of the [Renderable]
*/
fun getOpenGLObjectStateFromNode(renderable: Renderable): OpenGLObjectState {
return renderable.metadata["OpenGLRenderer"] as OpenGLObjectState
}
/**
* Initializes the [Scene] with the [OpenGLRenderer], to be called
* before [render].
*/
@Synchronized override fun initializeScene() {
scene.discover(scene, { it.geometryOrNull() != null })
.forEach { node ->
val renderable = node.renderableOrNull()
if(renderable != null) renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(node)
}
scene.initialized = true
logger.info("Initialized ${textureCache.size} textures")
}
@Suppress("UNUSED_VALUE")
@Synchronized protected fun updateDefaultUBOs(cam: Camera): Boolean {
// sticky boolean
var updated: Boolean by StickyBoolean(initial = false)
val hmd = hub?.getWorkingHMDDisplay()?.wantsVR(settings)
val camSpatial = cam.spatial()
camSpatial.view = camSpatial.getTransformation()
buffers.VRParameters.reset()
val vrUbo = uboCache.computeIfAbsent("VRParameters") {
OpenGLUBO(backingBuffer = buffers.VRParameters)
}
vrUbo.add("projection0", {
(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection)
})
vrUbo.add("projection1", {
(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection)
})
vrUbo.add("inverseProjection0", {
Matrix4f(hmd?.getEyeProjection(0, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).invert()
})
vrUbo.add("inverseProjection1", {
Matrix4f(hmd?.getEyeProjection(1, cam.nearPlaneDistance, cam.farPlaneDistance)
?: camSpatial.projection).invert()
})
vrUbo.add("headShift", { hmd?.getHeadToEyeTransform(0) ?: Matrix4f().identity() })
vrUbo.add("IPD", { hmd?.getIPD() ?: 0.05f })
vrUbo.add("stereoEnabled", { renderConfig.stereoEnabled.toInt() })
updated = vrUbo.populate()
buffers.VRParameters.copyFromStagingBuffer()
buffers.UBOs.reset()
buffers.ShaderProperties.reset()
sceneUBOs.forEach { node ->
var nodeUpdated: Boolean by StickyBoolean(initial = false)
val renderable = node.renderableOrNull() ?: return@forEach
val material = node.materialOrNull() ?: return@forEach
val spatial = node.spatialOrNull()
if (!renderable.metadata.containsKey(className)) {
return@forEach
}
val s = renderable.metadata[className] as? OpenGLObjectState
if(s == null) {
logger.warn("Could not get OpenGLObjectState for ${node.name}")
return@forEach
}
val ubo = s.UBOs["Matrices"]
if(ubo?.backingBuffer == null) {
logger.warn("Matrices UBO for ${node.name} does not exist or does not have a backing buffer")
return@forEach
}
preDrawAndUpdateGeometryForNode(node)
var bufferOffset = ubo.advanceBackingBuffer()
ubo.offset = bufferOffset
spatial?.view?.set(camSpatial.view)
nodeUpdated = ubo.populate(offset = bufferOffset.toLong())
val materialUbo = (renderable.metadata["OpenGLRenderer"]!! as OpenGLObjectState).UBOs.getValue("MaterialProperties")
bufferOffset = ubo.advanceBackingBuffer()
materialUbo.offset = bufferOffset
nodeUpdated = materialUbo.populate(offset = bufferOffset.toLong())
if (s.UBOs.containsKey("ShaderProperties")) {
val propertyUbo = s.UBOs.getValue("ShaderProperties")
// TODO: Correct buffer advancement
val offset = propertyUbo.backingBuffer!!.advance()
updated = propertyUbo.populate(offset = offset.toLong())
propertyUbo.offset = offset
}
nodeUpdated = loadTexturesForNode(node, s)
nodeUpdated = if(material.materialHashCode() != s.materialHash) {
s.initialized = false
initializeNode(node)
true
} else {
false
}
if(nodeUpdated && node.getScene()?.onNodePropertiesChanged?.isNotEmpty() == true) {
GlobalScope.launch { node.getScene()?.onNodePropertiesChanged?.forEach { it.value.invoke(node) } }
}
updated = nodeUpdated
}
buffers.UBOs.copyFromStagingBuffer()
buffers.LightParameters.reset()
// val lights = sceneObjects.filter { it is PointLight }
val lightUbo = uboCache.computeIfAbsent("LightParameters") {
OpenGLUBO(backingBuffer = buffers.LightParameters)
}
lightUbo.add("ViewMatrix0", { camSpatial.getTransformationForEye(0) })
lightUbo.add("ViewMatrix1", { camSpatial.getTransformationForEye(1) })
lightUbo.add("InverseViewMatrix0", { camSpatial.getTransformationForEye(0).invert() })
lightUbo.add("InverseViewMatrix1", { camSpatial.getTransformationForEye(1).invert() })
lightUbo.add("ProjectionMatrix", { camSpatial.projection })
lightUbo.add("InverseProjectionMatrix", { Matrix4f(camSpatial.projection).invert() })
lightUbo.add("CamPosition", { camSpatial.position })
// lightUbo.add("numLights", { lights.size })
// lights.forEachIndexed { i, light ->
// val l = light as PointLight
// l.updateWorld(true, false)
//
// lightUbo.add("Linear-$i", { l.linear })
// lightUbo.add("Quadratic-$i", { l.quadratic })
// lightUbo.add("Intensity-$i", { l.intensity })
// lightUbo.add("Radius-$i", { -l.linear + Math.sqrt(l.linear * l.linear - 4 * l.quadratic * (1.0 - (256.0f / 5.0) * 100)).toFloat() })
// lightUbo.add("Position-$i", { l.position })
// lightUbo.add("Color-$i", { l.emissionColor })
// lightUbo.add("filler-$i", { 0.0f })
// }
updated = lightUbo.populate()
buffers.ShaderParameters.reset()
renderpasses.forEach { name, pass ->
logger.trace("Updating shader parameters for {}", name)
updated = pass.updateShaderParameters()
}
buffers.ShaderParameters.copyFromStagingBuffer()
buffers.LightParameters.copyFromStagingBuffer()
buffers.ShaderProperties.copyFromStagingBuffer()
return updated
}
/**
* Update a [Node]'s geometry, if needed and run it's preDraw() routine.
*
* @param[node] The Node to update and preDraw()
*/
private fun preDrawAndUpdateGeometryForNode(node: Node) {
val renderable = node.renderableOrNull() ?: return
node.ifGeometry {
if (dirty) {
renderable.preUpdate(this@OpenGLRenderer, hub)
if (node.lock.tryLock()) {
if (vertices.remaining() > 0 && normals.remaining() > 0) {
updateVertices(getOpenGLObjectStateFromNode(renderable))
updateNormals(getOpenGLObjectStateFromNode(renderable))
}
if (texcoords.remaining() > 0) {
updateTextureCoords(getOpenGLObjectStateFromNode(renderable))
}
if (indices.remaining() > 0) {
updateIndices(getOpenGLObjectStateFromNode(renderable))
}
dirty = false
node.lock.unlock()
}
}
renderable.preDraw()
}
}
/**
* Set a [GLProgram]'s uniforms according to a [Node]'s [ShaderProperty]s.
*
* This functions uses reflection to query for a Node's declared fields and checks
* whether they are marked up with the [ShaderProperty] annotation. If this is the case,
* the [GLProgram]'s uniform with the same name as the field is set to its value.
*
* Currently limited to Vector3f, Matrix4f, Int and Float properties.
*
* @param[n] The Node to search for [ShaderProperty]s
* @param[program] The [GLProgram] used to render the Node
*/
@Suppress("unused")
private fun setShaderPropertiesForNode(n: Node, program: GLProgram) {
shaderPropertyCache
.getOrPut(n.javaClass) { n.javaClass.declaredFields.filter { it.isAnnotationPresent(ShaderProperty::class.java) } }
.forEach { property ->
property.isAccessible = true
val field = property.get(n)
when (property.type) {
Vector2f::class.java -> {
val v = field as Vector2f
program.getUniform(property.name).setFloatVector2(v.x, v.y)
}
Vector3f::class.java -> {
val v = field as Vector3f
program.getUniform(property.name).setFloatVector3(v.x, v.y, v.z)
}
Vector4f::class.java -> {
val v = field as Vector4f
program.getUniform(property.name).setFloatVector3(v.x, v.y, v.z, v.w)
}
Int::class.java -> {
program.getUniform(property.name).setInt(field as Int)
}
Float::class.java -> {
program.getUniform(property.name).setFloat(field as Float)
}
Matrix4f::class.java -> {
val m = field as Matrix4f
val array = FloatArray(16)
m.get(array)
program.getUniform(property.name).setFloatMatrix(array, false)
}
else -> {
logger.warn("Could not derive shader data type for @ShaderProperty ${n.javaClass.canonicalName}.${property.name} of type ${property.type}!")
}
}
}
}
private fun blitFramebuffers(source: GLFramebuffer?, target: GLFramebuffer?,
sourceOffset: OpenGLRenderpass.Rect2D,
targetOffset: OpenGLRenderpass.Rect2D,
colorOnly: Boolean = false, depthOnly: Boolean = false,
sourceName: String? = null) {
if (target != null) {
target.setDrawBuffers(gl)
} else {
gl.glBindFramebuffer(GL4.GL_DRAW_FRAMEBUFFER, 0)
}
if (source != null) {
if(sourceName != null) {
source.setReadBuffers(gl, sourceName)
} else {
source.setReadBuffers(gl)
}
} else {
gl.glBindFramebuffer(GL4.GL_READ_FRAMEBUFFER, 0)
}
val (blitColor, blitDepth) = when {
colorOnly && !depthOnly -> true to false
!colorOnly && depthOnly -> false to true
else -> true to true
}
if(blitColor) {
if (source?.hasColorAttachment() != false) {
gl.glBlitFramebuffer(
sourceOffset.offsetX, sourceOffset.offsetY,
sourceOffset.offsetX + sourceOffset.width, sourceOffset.offsetY + sourceOffset.height,
targetOffset.offsetX, targetOffset.offsetY,
targetOffset.offsetX + targetOffset.width, targetOffset.offsetY + targetOffset.height,
GL4.GL_COLOR_BUFFER_BIT, GL4.GL_LINEAR)
}
}
if(blitDepth) {
if ((source?.hasDepthAttachment() != false && target?.hasDepthAttachment() != false) || (depthOnly && !colorOnly)) {
gl.glBlitFramebuffer(
sourceOffset.offsetX, sourceOffset.offsetY,
sourceOffset.offsetX + sourceOffset.width, sourceOffset.offsetY + sourceOffset.height,
targetOffset.offsetX, targetOffset.offsetY,
targetOffset.offsetX + targetOffset.width, targetOffset.offsetY + targetOffset.height,
GL4.GL_DEPTH_BUFFER_BIT, GL4.GL_NEAREST)
} else {
logger.trace("Either source or target don't have a depth buffer. If blitting to window surface, this is not a problem.")
}
}
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0)
}
private fun updateInstanceBuffers(sceneObjects:List<Node>): Boolean {
val instanceMasters = sceneObjects.filter { it is InstancedNode }.map { it as InstancedNode }
instanceMasters.forEach { parent ->
val renderable = parent.renderableOrNull()
var metadata = renderable?.rendererMetadata()
if(metadata == null) {
if(renderable != null) renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(parent)
metadata = renderable?.rendererMetadata()
}
updateInstanceBuffer(parent, metadata)
}
return instanceMasters.isNotEmpty()
}
private fun updateInstanceBuffer(parentNode: InstancedNode, state: OpenGLObjectState?): OpenGLObjectState {
if(state == null) {
throw IllegalStateException("Metadata for ${parentNode.name} is null at updateInstanceBuffer(${parentNode.name}). This is a bug.")
}
// parentNode.instances is a CopyOnWrite array list, and here we keep a reference to the original.
// If it changes in the meantime, no problemo.
val instances = parentNode.instances
logger.trace("Updating instance buffer for ${parentNode.name}")
if (instances.isEmpty()) {
logger.debug("$parentNode has no child instances attached, returning.")
return state
}
val maxUpdates = parentNode.metadata["MaxInstanceUpdateCount"] as? AtomicInteger
if(maxUpdates?.get() ?: 1 < 1) {
logger.debug("Instances updates blocked for ${parentNode.name}, returning")
return state
}
// first we create a fake UBO to gauge the size of the needed properties
val ubo = OpenGLUBO()
ubo.fromInstance(instances.first())
val instanceBufferSize = ubo.getSize() * instances.size
val existingStagingBuffer = state.vertexBuffers["instanceStaging"]
val stagingBuffer = if(existingStagingBuffer != null
&& existingStagingBuffer.capacity() >= instanceBufferSize
&& existingStagingBuffer.capacity() < 1.5*instanceBufferSize) {
existingStagingBuffer
} else {
logger.debug("${parentNode.name}: Creating new staging buffer with capacity=$instanceBufferSize (${ubo.getSize()} x ${parentNode.instances.size})")
val buffer = BufferUtils.allocateByte((1.2 * instanceBufferSize).toInt())
state.vertexBuffers["instanceStaging"] = buffer
buffer
}
logger.trace("{}: Staging buffer position, {}, cap={}", parentNode.name, stagingBuffer.position(), stagingBuffer.capacity())
val index = AtomicInteger(0)
instances.parallelStream().forEach { node ->
if(node.visible) {
node.ifSpatial {
updateWorld(true, false)
}
stagingBuffer.duplicate().order(ByteOrder.LITTLE_ENDIAN).run {
ubo.populateParallel(this,
offset = index.getAndIncrement() * ubo.getSize() * 1L,
elements = node.instancedProperties)
}
}
}
stagingBuffer.position(stagingBuffer.limit())
stagingBuffer.flip()
val instanceBuffer = state.additionalBufferIds.getOrPut("instance") {
logger.debug("Instance buffer for ${parentNode.name} needs to be reallocated due to insufficient size ($instanceBufferSize vs ${state.vertexBuffers["instance"]?.capacity() ?: "<not allocated yet>"})")
val bufferArray = intArrayOf(0)
gl.glGenBuffers(1, bufferArray, 0)
gl.glBindVertexArray(state.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, bufferArray[0])
// instance data starts after vertex, normal, texcoord
val locationBase = 3
var location = locationBase
var baseOffset = 0L
val stride = parentNode.instances.first().instancedProperties.map {
val res = it.value.invoke()
ubo.getSizeAndAlignment(res).first
}.sum()
parentNode.instances.first().instancedProperties.entries.forEachIndexed { locationOffset, element ->
val result = element.value.invoke()
val sizeAlignment = ubo.getSizeAndAlignment(result)
location += locationOffset
val glType = when(result.javaClass) {
java.lang.Integer::class.java,
Int::class.java -> GL4.GL_INT
java.lang.Float::class.java,
Float::class.java -> GL4.GL_FLOAT
java.lang.Boolean::class.java,
Boolean::class.java -> GL4.GL_INT
Matrix4f::class.java -> GL4.GL_FLOAT
Vector3f::class.java -> GL4.GL_FLOAT
else -> { logger.error("Don't know how to serialise ${result.javaClass} for instancing."); GL4.GL_FLOAT }
}
val count = when (result) {
is Matrix4f -> 4
is Vector2f -> 2
is Vector3f -> 3
is Vector4f -> 4
is Vector2i -> 2
is Vector3i -> 3
is Vector4i -> 4
else -> { logger.error("Don't know element size of ${result.javaClass} for instancing."); 1 }
}
val necessaryAttributes = if(result is Matrix4f) {
4 * 4 / count
} else {
1
}
logger.trace("{} needs {} locations with {} elements:", result.javaClass, necessaryAttributes, count)
(0 until necessaryAttributes).forEach { attributeLocation ->
// val stride = sizeAlignment.first
val offset = baseOffset + 1L * attributeLocation * (sizeAlignment.first/necessaryAttributes)
logger.trace("{}, stride={}, offset={}",
location + attributeLocation,
stride,
offset)
gl.glEnableVertexAttribArray(location + attributeLocation)
// glVertexAttribPoint takes parameters:
// * index: attribute location
// * size: element count per location
// * type: the OpenGL type
// * normalized: whether the OpenGL type should be taken as normalized
// * stride: the stride between different occupants in the instance array
// * pointer_buffer_offset: the offset of the current element (e.g. matrix row) with respect
// to the start of the element in the instance array
gl.glVertexAttribPointer(location + attributeLocation, count, glType, false,
stride, offset)
gl.glVertexAttribDivisor(location + attributeLocation, 1)
if(attributeLocation == necessaryAttributes - 1) {
baseOffset += sizeAlignment.first
}
}
location += necessaryAttributes - 1
}
gl.glBindVertexArray(0)
state.additionalBufferIds["instance"] = bufferArray[0]
bufferArray[0]
}
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, instanceBuffer)
gl.glBufferData(GL4.GL_ARRAY_BUFFER, instanceBufferSize.toLong(), stagingBuffer, GL4.GL_DYNAMIC_DRAW)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
state.instanceCount = index.get()
logger.trace("Updated instance buffer, {parentNode.name} has {} instances.", parentNode.name, state.instanceCount)
maxUpdates?.decrementAndGet()
return state
}
protected fun destroyNode(node: Node, onShutdown: Boolean = false) {
node.ifRenderable {
this.metadata.remove("OpenGLRenderer")
val s = this.metadata["OpenGLRenderer"] as? OpenGLObjectState ?: return@ifRenderable
gl.glDeleteBuffers(s.mVertexBuffers.size, s.mVertexBuffers, 0)
gl.glDeleteBuffers(1, s.mIndexBuffer, 0)
s.additionalBufferIds.forEach { _, id ->
gl.glDeleteBuffers(1, intArrayOf(id), 0)
}
node.metadata.remove("OpenGLRenderer")
if(onShutdown) {
s.textures.forEach { (_, texture) ->
texture.delete()
}
}
initialized = false
}
}
protected var previousSceneObjects: HashSet<Node> = HashSet(256)
/**
* Renders the [Scene].
*
* The general rendering workflow works like this:
*
* 1) All visible elements of the Scene are gathered into the renderOrderList, based on their position
* 2) Nodes that are an instance of another Node, as indicated by their instanceOf property, are gathered
* into the instanceGroups map.
* 3) The eye-dependent geometry buffers are cleared, both color and depth buffers.
* 4) First for the non-instanced Nodes, then for the instanced Nodes the following steps are executed
* for each eye:
*
* i) The world state of the given Node is updated
* ii) Model, view, and model-view-projection matrices are calculated for each. If a HMD is present,
* the transformation coming from that is taken into account.
* iii) The Node's geometry is updated, if necessary.
* iv) The eye's geometry buffer is activated and the Node drawn into it.
*
* 5) The deferred shading pass is executed, together with eventual post-processing steps, such as SSAO.
* 6) If HDR is active, Exposure/Gamma tone mapping is performed. Else, this part is skipped.
* 7) The resulting image is drawn to the screen, or -- if a HMD is present -- submitted to the OpenVR
* compositor.
*/
override fun render(activeCamera: Camera, sceneNodes: List<Node>) {
currentObserver = activeCamera
currentSceneNodes = sceneNodes
renderCalled = true
}
var currentObserver: Camera? = null
var currentSceneNodes: List<Node> = emptyList()
@Synchronized fun renderInternal() = runBlocking {
if(!initialized || !renderCalled) {
return@runBlocking
}
if (scene.children.count() == 0 || !scene.initialized) {
initializeScene()
return@runBlocking
}
val newTime = System.nanoTime()
lastFrameTime = (System.nanoTime() - currentTime)/1e6f
currentTime = newTime
val stats = hub?.get(SceneryElement.Statistics) as? Statistics
if (shouldClose) {
initialized = false
return@runBlocking
}
val running = hub?.getApplication()?.running ?: true
embedIn?.let {
resizeHandler.queryResize()
}
if (scene.children.count() == 0 || renderpasses.isEmpty() || mustRecreateFramebuffers || !running) {
delay(200)
return@runBlocking
}
val cam = currentObserver ?: return@runBlocking
val sceneObjects = currentSceneNodes
val startUboUpdate = System.nanoTime()
val ubosUpdated = updateDefaultUBOs(cam)
stats?.add("OpenGLRenderer.updateUBOs", System.nanoTime() - startUboUpdate)
var sceneUpdated = true
if(pushMode) {
val actualSceneObjects = sceneObjects.toHashSet()
sceneUpdated = actualSceneObjects != previousSceneObjects
previousSceneObjects = actualSceneObjects
}
val startInstanceUpdate = System.nanoTime()
val instancesUpdated = updateInstanceBuffers(sceneObjects)
stats?.add("OpenGLRenderer.updateInstanceBuffers", System.nanoTime() - startInstanceUpdate)
// if(pushMode) {
// logger.info("Push mode: ubosUpdated={} sceneUpdated={} screenshotRequested={} instancesUpdated={}", ubosUpdated, sceneUpdated, screenshotRequested, instancesUpdated)
// }
if(pushMode && !ubosUpdated && !sceneUpdated && !screenshotRequested && !recordMovie && !instancesUpdated) {
if(updateLatch == null) {
updateLatch = CountDownLatch(4)
}
logger.trace("UBOs have not been updated, returning ({})", updateLatch?.count)
if(updateLatch?.count == 0L) {
// val animator = when {
// cglWindow != null -> cglWindow?.glAutoDrawable?.animator
// drawable != null -> drawable?.animator
// else -> null
// } as? FPSAnimator
//
// if(animator != null && animator.fps > 15) {
// animator.stop()
// animator.fps = 15
// animator.start()
// }
delay(15)
return@runBlocking
}
}
if(ubosUpdated || sceneUpdated || screenshotRequested || recordMovie) {
updateLatch = null
}
flow.forEach { t ->
if(logger.isDebugEnabled || logger.isTraceEnabled) {
val error = gl.glGetError()
if (error != 0) {
throw Exception("OpenGL error: $error")
}
}
val pass = renderpasses.getValue(t)
logger.trace("Running pass {}", pass.passName)
val startPass = System.nanoTime()
if (pass.passConfig.blitInputs) {
pass.inputs.forEach { name, input ->
val targetName = name.substringAfter(".")
if(name.contains(".") && input.getTextureType(targetName) == 0) {
logger.trace("Blitting {} into {} (color only)", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area, colorOnly = true, sourceName = name.substringAfter("."))
} else if(name.contains(".") && input.getTextureType(targetName) == 1) {
logger.trace("Blitting {} into {} (depth only)", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area, depthOnly = true)
} else {
logger.trace("Blitting {} into {}", targetName, pass.output.values.first().id)
blitFramebuffers(input, pass.output.values.firstOrNull(),
pass.openglMetadata.viewport.area, pass.openglMetadata.viewport.area)
}
}
}
if (pass.output.isNotEmpty()) {
pass.output.values.first().setDrawBuffers(gl)
} else {
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0)
}
// bind framebuffers to texture units and determine total number
pass.inputs.values.reversed().fold(0) { acc, fb -> acc + fb.bindTexturesToUnitsWithOffset(gl, acc) }
gl.glViewport(
pass.openglMetadata.viewport.area.offsetX,
pass.openglMetadata.viewport.area.offsetY,
pass.openglMetadata.viewport.area.width,
pass.openglMetadata.viewport.area.height)
gl.glScissor(
pass.openglMetadata.scissor.offsetX,
pass.openglMetadata.scissor.offsetY,
pass.openglMetadata.scissor.width,
pass.openglMetadata.scissor.height
)
gl.glEnable(GL4.GL_SCISSOR_TEST)
gl.glClearColor(
pass.openglMetadata.clearValues.clearColor.x(),
pass.openglMetadata.clearValues.clearColor.y(),
pass.openglMetadata.clearValues.clearColor.z(),
pass.openglMetadata.clearValues.clearColor.w())
if (!pass.passConfig.blitInputs) {
pass.output.values.forEach {
if (it.hasDepthAttachment()) {
gl.glClear(GL4.GL_DEPTH_BUFFER_BIT)
}
}
gl.glClear(GL4.GL_COLOR_BUFFER_BIT)
}
gl.glDisable(GL4.GL_SCISSOR_TEST)
gl.glDepthRange(
pass.openglMetadata.viewport.minDepth.toDouble(),
pass.openglMetadata.viewport.maxDepth.toDouble())
if (pass.passConfig.type == RenderConfigReader.RenderpassType.geometry ||
pass.passConfig.type == RenderConfigReader.RenderpassType.lights) {
gl.glEnable(GL4.GL_DEPTH_TEST)
gl.glEnable(GL4.GL_CULL_FACE)
if (pass.passConfig.renderTransparent) {
gl.glEnable(GL4.GL_BLEND)
gl.glBlendFuncSeparate(
pass.passConfig.srcColorBlendFactor.toOpenGL(),
pass.passConfig.dstColorBlendFactor.toOpenGL(),
pass.passConfig.srcAlphaBlendFactor.toOpenGL(),
pass.passConfig.dstAlphaBlendFactor.toOpenGL())
gl.glBlendEquationSeparate(
pass.passConfig.colorBlendOp.toOpenGL(),
pass.passConfig.alphaBlendOp.toOpenGL()
)
} else {
gl.glDisable(GL4.GL_BLEND)
}
val actualObjects = if(pass.passConfig.type == RenderConfigReader.RenderpassType.geometry) {
sceneObjects.filter { it !is Light }.toMutableList()
} else {
sceneObjects.filter { it is Light }.toMutableList()
}
actualObjects.sortBy { (it as? RenderingOrder)?.renderingOrder }
var currentShader: OpenGLShaderProgram? = null
val seenDelegates = ArrayList<Renderable>(5)
actualObjects.forEach renderLoop@ { node ->
val renderable = node.renderableOrNull() ?: return@renderLoop
val material = node.materialOrNull() ?: return@renderLoop
if(node is HasDelegationType && node.getDelegationType() == DelegationType.OncePerDelegate) {
if(seenDelegates.contains(renderable)) {
return@renderLoop
} else {
seenDelegates.add(renderable)
}
}
if (pass.passConfig.renderOpaque && material.blending.transparent && pass.passConfig.renderOpaque != pass.passConfig.renderTransparent) {
return@renderLoop
}
if (pass.passConfig.renderTransparent && !material.blending.transparent && pass.passConfig.renderOpaque != pass.passConfig.renderTransparent) {
return@renderLoop
}
gl.glEnable(GL4.GL_CULL_FACE)
when(material.cullingMode) {
Material.CullingMode.None -> gl.glDisable(GL4.GL_CULL_FACE)
Material.CullingMode.Front -> gl.glCullFace(GL4.GL_FRONT)
Material.CullingMode.Back -> gl.glCullFace(GL4.GL_BACK)
Material.CullingMode.FrontAndBack -> gl.glCullFace(GL4.GL_FRONT_AND_BACK)
}
val depthTest = when(material.depthTest) {
Material.DepthTest.Less -> GL4.GL_LESS
Material.DepthTest.Greater -> GL4.GL_GREATER
Material.DepthTest.LessEqual -> GL4.GL_LEQUAL
Material.DepthTest.GreaterEqual -> GL4.GL_GEQUAL
Material.DepthTest.Always -> GL4.GL_ALWAYS
Material.DepthTest.Never -> GL4.GL_NEVER
Material.DepthTest.Equal -> GL4.GL_EQUAL
}
gl.glDepthFunc(depthTest)
if(material.wireframe) {
gl.glPolygonMode(GL4.GL_FRONT_AND_BACK, GL4.GL_LINE)
} else {
gl.glPolygonMode(GL4.GL_FRONT_AND_BACK, GL4.GL_FILL)
}
if (material.blending.transparent) {
with(material.blending) {
gl.glBlendFuncSeparate(
sourceColorBlendFactor.toOpenGL(),
destinationColorBlendFactor.toOpenGL(),
sourceAlphaBlendFactor.toOpenGL(),
destinationAlphaBlendFactor.toOpenGL()
)
gl.glBlendEquationSeparate(
colorBlending.toOpenGL(),
alphaBlending.toOpenGL()
)
}
}
if (!renderable.metadata.containsKey("OpenGLRenderer") || !node.initialized) {
renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
initializeNode(node)
return@renderLoop
}
val s = getOpenGLObjectStateFromNode(renderable)
val shader = s.shader ?: pass.defaultShader!!
if(currentShader != shader) {
shader.use(gl)
}
currentShader = shader
if (renderConfig.stereoEnabled) {
shader.getUniform("currentEye.eye").setInt(pass.openglMetadata.eye)
}
var unit = 0
pass.inputs.keys.reversed().forEach { name ->
renderConfig.rendertargets[name.substringBefore(".")]?.attachments?.forEach {
shader.getUniform("Input" + it.key).setInt(unit)
unit++
}
}
val unboundSamplers = (unit until maxTextureUnits).toMutableList()
var maxSamplerIndex = 0
val textures = s.textures.entries.groupBy { Texture.objectTextures.contains(it.key) }
val objectTextures = textures[true]
val others = textures[false]
objectTextures?.forEach { texture ->
val samplerIndex = textureTypeToUnit(pass, texture.key)
maxSamplerIndex = max(samplerIndex, maxSamplerIndex)
@Suppress("SENSELESS_COMPARISON")
if (texture.value != null) {
gl.glActiveTexture(GL4.GL_TEXTURE0 + samplerIndex)
val target = if (texture.value.depth > 1) {
GL4.GL_TEXTURE_3D
} else {
GL4.GL_TEXTURE_2D
}
gl.glBindTexture(target, texture.value.id)
shader.getUniform(textureTypeToArrayName(texture.key)).setInt(samplerIndex)
unboundSamplers.remove(samplerIndex)
}
}
var samplerIndex = maxSamplerIndex
others?.forEach { texture ->
@Suppress("SENSELESS_COMPARISON")
if(texture.value != null) {
val minIndex = unboundSamplers.minOrNull() ?: maxSamplerIndex
gl.glActiveTexture(GL4.GL_TEXTURE0 + minIndex)
val target = if (texture.value.depth > 1) {
GL4.GL_TEXTURE_3D
} else {
GL4.GL_TEXTURE_2D
}
gl.glBindTexture(target, texture.value.id)
shader.getUniform(texture.key).setInt(minIndex)
samplerIndex++
unboundSamplers.remove(minIndex)
}
}
var binding = 0
(s.UBOs + pass.UBOs).forEach { name, ubo ->
val actualName = if (name.contains("ShaderParameters")) {
"ShaderParameters"
} else {
name
}
if(shader.uboSpecs.containsKey(actualName) && shader.isValid()) {
val index = shader.getUniformBlockIndex(actualName)
logger.trace("Binding {} for {}, index={}, binding={}, size={}", actualName, node.name, index, binding, ubo.getSize())
if (index == -1) {
logger.error("Failed to bind UBO $actualName for ${node.name} to $binding")
} else {
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
ubo.backingBuffer!!.id[0], 1L * ubo.offset, 1L * ubo.getSize())
binding++
}
}
}
arrayOf("VRParameters" to buffers.VRParameters,
"LightParameters" to buffers.LightParameters).forEach uboBinding@ { b ->
val buffer = b.second
val name = b.first
if (shader.uboSpecs.containsKey(name) && shader.isValid()) {
val index = shader.getUniformBlockIndex(name)
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $name for ${pass.passName} to $binding, though it is required by the shader")
} else {
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
buffer.id[0],
0L, buffer.buffer.remaining().toLong())
binding++
}
}
}
if(node is InstancedNode) {
drawNodeInstanced(node)
} else {
drawNode(node)
}
}
} else {
gl.glDisable(GL4.GL_CULL_FACE)
if (pass.output.any { it.value.hasDepthAttachment() }) {
gl.glEnable(GL4.GL_DEPTH_TEST)
} else {
gl.glDisable(GL4.GL_DEPTH_TEST)
}
if (pass.passConfig.renderTransparent) {
gl.glEnable(GL4.GL_BLEND)
gl.glBlendFuncSeparate(
pass.passConfig.srcColorBlendFactor.toOpenGL(),
pass.passConfig.dstColorBlendFactor.toOpenGL(),
pass.passConfig.srcAlphaBlendFactor.toOpenGL(),
pass.passConfig.dstAlphaBlendFactor.toOpenGL())
gl.glBlendEquationSeparate(
pass.passConfig.colorBlendOp.toOpenGL(),
pass.passConfig.alphaBlendOp.toOpenGL()
)
} else {
gl.glDisable(GL4.GL_BLEND)
}
pass.defaultShader?.let { shader ->
shader.use(gl)
var unit = 0
pass.inputs.keys.reversed().forEach { name ->
renderConfig.rendertargets[name.substringBefore(".")]?.attachments?.forEach {
shader.getUniform("Input" + it.key).setInt(unit)
unit++
}
}
var binding = 0
pass.UBOs.forEach { name, ubo ->
val actualName = if (name.contains("ShaderParameters")) {
"ShaderParameters"
} else {
name
}
val index = shader.getUniformBlockIndex(actualName)
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
ubo.backingBuffer!!.id[0],
1L * ubo.offset, 1L * ubo.getSize())
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $actualName for ${pass.passName} to $binding")
}
binding++
}
arrayOf("LightParameters" to buffers.LightParameters,
"VRParameters" to buffers.VRParameters).forEach { b ->
val name = b.first
val buffer = b.second
if (shader.uboSpecs.containsKey(name)) {
val index = shader.getUniformBlockIndex(name)
gl.glUniformBlockBinding(shader.id, index, binding)
gl.glBindBufferRange(GL4.GL_UNIFORM_BUFFER, binding,
buffer.id[0],
0L, buffer.buffer.remaining().toLong())
if (index == -1) {
logger.error("Failed to bind shader parameter UBO $name for ${pass.passName} to $binding, though it is required by the shader")
}
binding++
}
}
renderFullscreenQuad(shader)
}
}
stats?.add("Renderer.$t.renderTiming", System.nanoTime() - startPass)
}
if(logger.isDebugEnabled || logger.isTraceEnabled) {
val error = gl.glGetError()
if (error != 0) {
throw Exception("OpenGL error: $error")
}
}
logger.trace("Running viewport pass")
val startPass = System.nanoTime()
val viewportPass = renderpasses.getValue(flow.last())
gl.glBindFramebuffer(GL4.GL_DRAW_FRAMEBUFFER, 0)
blitFramebuffers(viewportPass.output.values.first(), null,
OpenGLRenderpass.Rect2D(
settings.get("Renderer.${viewportPass.passName}.displayWidth"),
settings.get("Renderer.${viewportPass.passName}.displayHeight"), 0, 0),
OpenGLRenderpass.Rect2D(window.width, window.height, 0, 0))
// submit to OpenVR if attached
if(hub?.getWorkingHMDDisplay()?.hasCompositor() == true && !mustRecreateFramebuffers) {
hub?.getWorkingHMDDisplay()?.wantsVR(settings)?.submitToCompositor(
viewportPass.output.values.first().getTextureId("Viewport"))
}
val w = viewportPass.output.values.first().width
val h = viewportPass.output.values.first().height
if((embedIn != null && embedIn !is SceneryJPanel) || recordMovie) {
if (shouldClose || mustRecreateFramebuffers) {
encoder?.finish()
encoder = null
return@runBlocking
}
if (recordMovie && (encoder == null || encoder?.frameWidth != w || encoder?.frameHeight != h)) {
val file = SystemHelpers.addFileCounter(if(movieFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.mp4")
} else {
File(movieFilename)
}, false)
val supersamplingFactor = getSupersamplingFactor(cglWindow)
encoder = VideoEncoder(
(supersamplingFactor * window.width).toInt(),
(supersamplingFactor * window.height).toInt(),
file.absolutePath,
hub = hub)
}
readIndex = (readIndex + 1) % pboCount
updateIndex = (updateIndex + 1) % pboCount
if (pbos.any { it == 0 } || mustRecreateFramebuffers) {
gl.glGenBuffers(pboCount, pbos, 0)
pbos.forEachIndexed { index, pbo ->
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbo)
gl.glBufferData(GL4.GL_PIXEL_PACK_BUFFER, w * h * 4L, null, GL4.GL_STREAM_READ)
if(pboBuffers[index] != null) {
MemoryUtil.memFree(pboBuffers[index])
pboBuffers[index] = null
}
}
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, 0)
}
pboBuffers.forEachIndexed { i, _ ->
if(pboBuffers[i] == null) {
pboBuffers[i] = MemoryUtil.memAlloc(4 * w * h)
}
}
viewportPass.output.values.first().setReadBuffers(gl)
val startUpdate = System.nanoTime()
if(frames < pboCount) {
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbos[updateIndex])
gl.glReadPixels(0, 0, w, h, GL4.GL_BGRA, GL4.GL_UNSIGNED_BYTE, 0)
} else {
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, pbos[updateIndex])
val readBuffer = gl.glMapBuffer(GL4.GL_PIXEL_PACK_BUFFER, GL4.GL_READ_ONLY)
MemoryUtil.memCopy(readBuffer, pboBuffers[readIndex]!!)
gl.glUnmapBuffer(GL4.GL_PIXEL_PACK_BUFFER)
gl.glReadPixels(0, 0, w, h, GL4.GL_BGRA, GL4.GL_UNSIGNED_BYTE, 0)
}
if (!mustRecreateFramebuffers && frames > pboCount) {
embedIn?.let { embedPanel ->
pboBuffers[readIndex]?.let {
val id = viewportPass.output.values.first().getTextureId("Viewport")
embedPanel.update(it, id = id)
}
}
encoder?.let { e ->
pboBuffers[readIndex]?.let {
e.encodeFrame(it, flip = true)
}
}
}
val updateDuration = (System.nanoTime() - startUpdate)*1.0f
stats?.add("Renderer.updateEmbed", updateDuration, true)
gl.glBindBuffer(GL4.GL_PIXEL_PACK_BUFFER, 0)
}
val request = try {
imageRequests.poll()
} catch(e: NoSuchElementException) {
null
}
if ((screenshotRequested || request != null) && joglDrawable != null) {
try {
val readBufferUtil = AWTGLReadBufferUtil(joglDrawable!!.glProfile, false)
val image = readBufferUtil.readPixelsToBufferedImage(gl, true)
val file = SystemHelpers.addFileCounter(if(screenshotFilename == "") {
File(System.getProperty("user.home"), "Desktop" + File.separator + "$applicationName - ${SystemHelpers.formatDateTime()}.png")
} else {
File(screenshotFilename)
}, screenshotOverwriteExisting)
if(request != null) {
request.width = window.width
request.height = window.height
val data = (image.raster.dataBuffer as DataBufferInt).data
val tmp = ByteBuffer.allocate(data.size * 4)
data.forEach { value ->
val r = (value shr 16).toByte()
val g = (value shr 8).toByte()
val b = value.toByte()
tmp.put(0)
tmp.put(b)
tmp.put(g)
tmp.put(r)
}
request.data = tmp.array()
}
if(screenshotRequested && image != null) {
ImageIO.write(image, "png", file)
logger.info("Screenshot saved to ${file.absolutePath}")
}
} catch (e: Exception) {
logger.error("Unable to take screenshot: ")
e.printStackTrace()
}
screenshotOverwriteExisting = false
screenshotRequested = false
}
stats?.add("Renderer.${flow.last()}.renderTiming", System.nanoTime() - startPass)
updateLatch?.countDown()
firstImageReady = true
frames++
framesPerSec++
}
/**
* Renders a fullscreen quad, using from an on-the-fly generated
* Node that is saved in [nodeStore], with the [GLProgram]'s ID.
*
* @param[program] The [GLProgram] to draw into the fullscreen quad.
*/
fun renderFullscreenQuad(program: OpenGLShaderProgram) {
val quad: Node
val quadName = "fullscreenQuad-${program.id}"
quad = nodeStore.getOrPut(quadName) {
val q = Plane(Vector3f(1.0f, 1.0f, 0.0f))
q.ifRenderable {
this.metadata["OpenGLRenderer"] = OpenGLObjectState()
}
initializeNode(q)
q
}
drawNode(quad, count = 3)
program.gl.glBindTexture(GL4.GL_TEXTURE_2D, 0)
}
/**
* Initializes a given [Node].
*
* This function initializes a Node, equipping its metadata with an [OpenGLObjectState],
* generating VAOs and VBOs. If the Node has a [Material] assigned, a [GLProgram] fitting
* this Material will be used. Else, a default GLProgram will be used.
*
* For the assigned Material case, the GLProgram is derived either from the class name of the
* Node (if useClassDerivedShader is set), or from a set [ShaderMaterial] which may define
* the whole shader pipeline for the Node.
*
* If the [Node] implements [HasGeometry], it's geometry is also initialized by this function.
*
* @param[node]: The [Node] to initialise.
* @return True if the initialisation went alright, False if it failed.
*/
@Synchronized fun initializeNode(node: Node): Boolean {
val renderable = node.renderableOrNull() ?: return false
val material = node.materialOrNull() ?: return false
val spatial = node.spatialOrNull()
if(!node.lock.tryLock()) {
return false
}
if(renderable.rendererMetadata() == null) {
renderable.metadata["OpenGLRenderer"] = OpenGLObjectState()
}
val s = renderable.metadata["OpenGLRenderer"] as OpenGLObjectState
if (s.initialized) {
return true
}
// generate VAO for attachment of VBO and indices
gl.glGenVertexArrays(1, s.mVertexArrayObject, 0)
// generate three VBOs for coords, normals, texcoords
gl.glGenBuffers(3, s.mVertexBuffers, 0)
gl.glGenBuffers(1, s.mIndexBuffer, 0)
when {
material is ShaderMaterial -> {
val shaders = material.shaders
try {
s.shader = prepareShaderProgram(shaders)
} catch (e: ShaderCompilationException) {
logger.warn("Shader compilation for node ${node.name} with shaders $shaders failed, falling back to default shaders.")
logger.warn("Shader compiler error was: ${e.message}")
}
}
else -> s.shader = null
}
node.ifGeometry {
setVerticesAndCreateBufferForNode(s)
setNormalsAndCreateBufferForNode(s)
if (this.texcoords.limit() > 0) {
setTextureCoordsAndCreateBufferForNode(s)
}
if (this.indices.limit() > 0) {
setIndicesAndCreateBufferForNode(s)
}
}
s.materialHash = material.materialHashCode()
val matricesUbo = OpenGLUBO(backingBuffer = buffers.UBOs)
with(matricesUbo) {
name = "Matrices"
if(spatial != null) {
add("ModelMatrix", { spatial.world })
add("NormalMatrix", { Matrix4f(spatial.world).invert().transpose() })
}
add("isBillboard", { renderable.isBillboard.toInt() })
sceneUBOs.add(node)
s.UBOs.put("Matrices", this)
}
loadTexturesForNode(node, s)
val materialUbo = OpenGLUBO(backingBuffer = buffers.UBOs)
with(materialUbo) {
name = "MaterialProperties"
add("materialType", { node.materialOrNull()!!.materialToMaterialType(s) })
add("Ka", { node.materialOrNull()!!.ambient })
add("Kd", { node.materialOrNull()!!.diffuse })
add("Ks", { node.materialOrNull()!!.specular })
add("Roughness", { node.materialOrNull()!!.roughness })
add("Metallic", { node.materialOrNull()!!.metallic })
add("Opacity", { node.materialOrNull()!!.blending.opacity })
s.UBOs.put("MaterialProperties", this)
}
if (renderable.parent.javaClass.kotlin.memberProperties.filter { it.findAnnotation<ShaderProperty>() != null }.count() > 0) {
val shaderPropertyUBO = OpenGLUBO(backingBuffer = buffers.ShaderProperties)
with(shaderPropertyUBO) {
name = "ShaderProperties"
val shader = if (material is ShaderMaterial) {
s.shader
} else {
renderpasses.filter {
(it.value.passConfig.type == RenderConfigReader.RenderpassType.geometry || it.value.passConfig.type == RenderConfigReader.RenderpassType.lights)
&& it.value.passConfig.renderTransparent == material.blending.transparent
}.entries.firstOrNull()?.value?.defaultShader
}
logger.debug("Shader properties are: ${shader?.getShaderPropertyOrder()}")
shader?.getShaderPropertyOrder()?.forEach { name, offset ->
add(name, { renderable.parent.getShaderProperty(name) ?: 0 }, offset)
}
}
s.UBOs["ShaderProperties"] = shaderPropertyUBO
}
s.initialized = true
node.initialized = true
renderable.metadata[className] = s
s.initialized = true
node.lock.unlock()
return true
}
private val defaultTextureNames = arrayOf("ambient", "diffuse", "specular", "normal", "alphamask", "displacement")
private fun Material.materialToMaterialType(s: OpenGLObjectState): Int {
var materialType = 0
if (this.textures.containsKey("ambient") && !s.defaultTexturesFor.contains("ambient")) {
materialType = materialType or MATERIAL_HAS_AMBIENT
}
if (this.textures.containsKey("diffuse") && !s.defaultTexturesFor.contains("diffuse")) {
materialType = materialType or MATERIAL_HAS_DIFFUSE
}
if (this.textures.containsKey("specular") && !s.defaultTexturesFor.contains("specular")) {
materialType = materialType or MATERIAL_HAS_SPECULAR
}
if (this.textures.containsKey("normal") && !s.defaultTexturesFor.contains("normal")) {
materialType = materialType or MATERIAL_HAS_NORMAL
}
if (this.textures.containsKey("alphamask") && !s.defaultTexturesFor.contains("alphamask")) {
materialType = materialType or MATERIAL_HAS_ALPHAMASK
}
return materialType
}
/**
* Initializes a default set of textures that the renderer can fall back to and provide a non-intrusive
* hint to the user that a texture could not be loaded.
*/
private fun prepareDefaultTextures() {
val t = GLTexture.loadFromFile(gl, Renderer::class.java.getResourceAsStream("DefaultTexture.png"), "png", false, true, 8)
if(t == null) {
logger.error("Could not load default texture! This indicates a serious issue.")
} else {
textureCache["DefaultTexture"] = t
}
}
/**
* Returns true if the current [GLTexture] can be reused to store the information in the [Texture]
* [other]. Returns false otherwise.
*/
protected fun GLTexture.canBeReused(other: Texture): Boolean {
return this.width == other.dimensions.x() &&
this.height == other.dimensions.y() &&
this.depth == other.dimensions.z() &&
this.nativeType.equivalentTo(other.type)
}
private fun GLTypeEnum.equivalentTo(type: NumericType<*>): Boolean {
return when {
this == GLTypeEnum.UnsignedByte && type is UnsignedByteType -> true
this == GLTypeEnum.Byte && type is ByteType -> true
this == GLTypeEnum.UnsignedShort && type is UnsignedShortType -> true
this == GLTypeEnum.Short && type is ShortType -> true
this == GLTypeEnum.UnsignedInt && type is UnsignedIntType -> true
this == GLTypeEnum.Int && type is IntType -> true
this == GLTypeEnum.Float && type is FloatType -> true
this == GLTypeEnum.Double && type is DoubleType -> true
else -> false
}
}
@Suppress("unused")
private fun dumpTextureToFile(gl: GL4, name: String, texture: GLTexture) {
val filename = "${name}_${Date().toInstant().epochSecond}.raw"
val bytes = texture.width*texture.height*texture.depth*texture.channels*texture.bitsPerChannel/8
logger.info("Dumping $name to $filename ($bytes bytes)")
val buffer = MemoryUtil.memAlloc(bytes)
gl.glPixelStorei(GL4.GL_PACK_ALIGNMENT, 1)
texture.bind()
gl.glGetTexImage(texture.textureTarget, 0, texture.format, texture.type, buffer)
texture.unbind()
val stream = FileOutputStream(filename)
val outChannel = stream.channel
outChannel.write(buffer)
logger.info("Written $texture to $stream")
outChannel.close()
stream.close()
MemoryUtil.memFree(buffer)
}
private fun RepeatMode.toOpenGL(): Int {
return when(this) {
RepeatMode.Repeat -> GL4.GL_REPEAT
RepeatMode.MirroredRepeat -> GL4.GL_MIRRORED_REPEAT
RepeatMode.ClampToEdge -> GL4.GL_CLAMP_TO_EDGE
RepeatMode.ClampToBorder -> GL4.GL_CLAMP_TO_BORDER
}
}
private fun BorderColor.toOpenGL(): FloatArray {
return when(this) {
BorderColor.TransparentBlack -> floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f)
BorderColor.OpaqueBlack -> floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f)
BorderColor.OpaqueWhite -> floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f)
}
}
private fun NumericType<*>.toOpenGL(): GLTypeEnum {
return when(this) {
is UnsignedByteType -> GLTypeEnum.UnsignedByte
is ByteType -> GLTypeEnum.Byte
is UnsignedShortType -> GLTypeEnum.UnsignedShort
is ShortType -> GLTypeEnum.Short
is UnsignedIntType -> GLTypeEnum.UnsignedInt
is IntType -> GLTypeEnum.Int
is FloatType -> GLTypeEnum.Float
is DoubleType -> GLTypeEnum.Double
else -> throw IllegalStateException("Type ${this.javaClass.simpleName} is not supported as OpenGL texture type")
}
}
/**
* Loads textures for a [Node]. The textures are loaded from a [Material.textures].
*
* @param[node] The [Node] to load textures for.
* @param[s] The [Node]'s [OpenGLObjectState]
*/
@Suppress("USELESS_ELVIS")
private fun loadTexturesForNode(node: Node, s: OpenGLObjectState): Boolean {
val material = node.materialOrNull() ?: return false
var changed = false
val last = s.texturesLastSeen
val now = System.nanoTime()
material.textures.forEachChanged(last) { (type, texture) ->
changed = true
logger.debug("Loading texture $texture for ${node.name}")
val generateMipmaps = Texture.mipmappedObjectTextures.contains(type)
val contentsNew = texture.contents?.duplicate()
logger.debug("Dims of $texture: ${texture.dimensions}, mipmaps=$generateMipmaps")
val mm = generateMipmaps or texture.mipmap
val miplevels = if (mm && texture.dimensions.z() == 1) {
1 + floor(ln(max(texture.dimensions.x() * 1.0, texture.dimensions.y() * 1.0)) / ln(2.0)).toInt()
} else {
1
}
val existingTexture = s.textures[type]
val t = if(existingTexture != null && existingTexture.canBeReused(texture)) {
existingTexture
} else {
GLTexture(gl, texture.type.toOpenGL(), texture.channels,
texture.dimensions.x(),
texture.dimensions.y(),
texture.dimensions.z() ?: 1,
texture.minFilter == Texture.FilteringMode.Linear,
miplevels, 32,
texture.normalized, renderConfig.sRGB)
}
if (mm) {
t.updateMipMaps()
}
t.setRepeatModeS(texture.repeatUVW.first.toOpenGL())
t.setRepeatModeT(texture.repeatUVW.second.toOpenGL())
t.setRepeatModeR(texture.repeatUVW.third.toOpenGL())
t.setTextureBorderColor(texture.borderColor.toOpenGL())
// textures might have very uneven dimensions, so we adjust GL_UNPACK_ALIGNMENT here correspondingly
// in case the byte count of the texture is not divisible by it.
val unpackAlignment = intArrayOf(0)
gl.glGetIntegerv(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment, 0)
texture.contents?.let { contents ->
t.copyFrom(contents.duplicate())
}
if (contentsNew != null && texture is UpdatableTexture && !texture.hasConsumableUpdates()) {
if (contentsNew.remaining() % unpackAlignment[0] == 0 && texture.dimensions.x() % unpackAlignment[0] == 0) {
t.copyFrom(contentsNew)
} else {
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, 1)
t.copyFrom(contentsNew)
}
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment[0])
}
if (texture is UpdatableTexture && texture.hasConsumableUpdates()) {
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, 1)
texture.getConsumableUpdates().forEach { update ->
t.copyFrom(update.contents,
update.extents.w, update.extents.h, update.extents.d,
update.extents.x, update.extents.y, update.extents.z, true)
update.consumed = true
}
texture.clearConsumedUpdates()
gl.glPixelStorei(GL4.GL_UNPACK_ALIGNMENT, unpackAlignment[0])
}
s.textures[type] = t
// textureCache.put(texture, t)
}
// update default textures
// s.defaultTexturesFor = defaultTextureNames.mapNotNull { if(!s.textures.containsKey(it)) { it } else { null } }.toHashSet()
s.defaultTexturesFor.clear()
defaultTextureNames.forEach {
if (!s.textures.containsKey(it)) {
s.defaultTexturesFor.add(it)
}
}
s.texturesLastSeen = now
s.initialized = true
return changed
}
/**
* Reshape the renderer's viewports
*
* This routine is called when a change in window size is detected, e.g. when resizing
* it manually or toggling fullscreen. This function updates the sizes of all used
* geometry buffers and will also create new buffers in case vr.Active is changed.
*
* This function also clears color and depth buffer bits.
*
* @param[newWidth] The resized window's width
* @param[newHeight] The resized window's height
*/
override fun reshape(newWidth: Int, newHeight: Int) {
if (!initialized) {
return
}
lastResizeTimer.cancel()
lastResizeTimer = Timer()
lastResizeTimer.schedule(object : TimerTask() {
override fun run() {
val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f))
?: Vector2f(1.0f, 1.0f)
val panel = embedIn
if(panel is SceneryJPanel && panel.width != (newWidth/surfaceScale.x()).toInt() && panel.height != (newWidth/surfaceScale.y()).toInt()) {
logger.debug("Panel is ${panel.width}x${panel.height} vs $newWidth x $newHeight")
window.width = (newWidth * surfaceScale.x()).toInt()
window.height = (newHeight * surfaceScale.y()).toInt()
} else {
window.width = newWidth
window.height = newHeight
}
logger.debug("Resizing window to ${newWidth}x$newHeight")
mustRecreateFramebuffers = true
}
}, WINDOW_RESIZE_TIMEOUT)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s vertices.
*/
fun Geometry.setVerticesAndCreateBufferForNode(s: OpenGLObjectState) {
updateVertices(s)
}
/**
* Updates a [Geometry]'s vertices.
*/
fun Geometry.updateVertices(s: OpenGLObjectState) {
val pVertexBuffer: FloatBuffer = vertices.duplicate()
s.mStoredPrimitiveCount = pVertexBuffer.remaining() / vertexSize
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[0])
gl.glEnableVertexAttribArray(0)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pVertexBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pVertexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(0,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s normals.
*/
fun Geometry.setNormalsAndCreateBufferForNode(s: OpenGLObjectState) {
val pNormalBuffer: FloatBuffer = normals.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[1])
if (pNormalBuffer.limit() > 0) {
gl.glEnableVertexAttribArray(1)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pNormalBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pNormalBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(1,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
}
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Updates a given [Geometry]'s normals.
*/
fun Geometry.updateNormals(s: OpenGLObjectState) {
val pNormalBuffer: FloatBuffer = normals.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, s.mVertexBuffers[1])
gl.glEnableVertexAttribArray(1)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pNormalBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pNormalBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(1,
vertexSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates VAOs and VBO for a given [Geometry]'s texcoords.
*/
fun Geometry.setTextureCoordsAndCreateBufferForNode(s: OpenGLObjectState) {
updateTextureCoords(s)
}
/**
* Updates a given [Geometry]'s texcoords.
*/
fun Geometry.updateTextureCoords(s: OpenGLObjectState) {
val pTextureCoordsBuffer: FloatBuffer = texcoords.duplicate()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER,
s.mVertexBuffers[2])
gl.glEnableVertexAttribArray(2)
gl.glBufferData(GL4.GL_ARRAY_BUFFER,
(pTextureCoordsBuffer.remaining() * (java.lang.Float.SIZE / java.lang.Byte.SIZE)).toLong(),
pTextureCoordsBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glVertexAttribPointer(2,
texcoordSize,
GL4.GL_FLOAT,
false,
0,
0)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0)
}
/**
* Creates a index buffer for a given [Geometry]'s indices.
*/
fun Geometry.setIndicesAndCreateBufferForNode(s: OpenGLObjectState) {
val pIndexBuffer: IntBuffer = indices.duplicate()
s.mStoredIndexCount = pIndexBuffer.remaining()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, s.mIndexBuffer[0])
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER,
(pIndexBuffer.remaining() * (Integer.SIZE / java.lang.Byte.SIZE)).toLong(),
pIndexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
}
/**
* Updates a given [Geometry]'s indices.
*/
fun Geometry.updateIndices(s: OpenGLObjectState) {
val pIndexBuffer: IntBuffer = indices.duplicate()
s.mStoredIndexCount = pIndexBuffer.remaining()
gl.glBindVertexArray(s.mVertexArrayObject[0])
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, s.mIndexBuffer[0])
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER,
(pIndexBuffer.remaining() * (Integer.SIZE / java.lang.Byte.SIZE)).toLong(),
pIndexBuffer,
GL4.GL_DYNAMIC_DRAW)
gl.glBindVertexArray(0)
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
}
/**
* Draws a given [Node], either in element or in index draw mode.
*
* @param[node] The node to be drawn.
* @param[offset] offset in the array or index buffer.
*/
fun drawNode(node: Node, offset: Int = 0, count: Int? = null) {
val renderable = node.renderableOrNull() ?: return
val s = getOpenGLObjectStateFromNode(renderable)
if (s.mStoredIndexCount == 0 && s.mStoredPrimitiveCount == 0) {
return
}
logger.trace("Drawing {} with {}, {} primitives, {} indices", node.name, s.shader?.modules?.entries?.joinToString(", "), s.mStoredPrimitiveCount, s.mStoredIndexCount)
node.ifGeometry {
gl.glBindVertexArray(s.mVertexArrayObject[0])
if (s.mStoredIndexCount > 0) {
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER,
s.mIndexBuffer[0])
gl.glDrawElements(geometryType.toOpenGLType(),
count ?: s.mStoredIndexCount,
GL4.GL_UNSIGNED_INT,
offset.toLong())
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0)
} else {
gl.glDrawArrays(geometryType.toOpenGLType(), offset, count ?: s.mStoredPrimitiveCount)
}
// gl.glUseProgram(0)
// gl.glBindVertexArray(0)
}
}
/**
* Draws a given instanced [Node] either in element or in index draw mode.
*
* @param[node] The node to be drawn.
* @param[offset] offset in the array or index buffer.
*/
protected fun drawNodeInstanced(node: Node, offset: Long = 0) {
node.ifRenderable {
val s = getOpenGLObjectStateFromNode(this)
node.ifGeometry {
gl.glBindVertexArray(s.mVertexArrayObject[0])
if (s.mStoredIndexCount > 0) {
gl.glDrawElementsInstanced(
geometryType.toOpenGLType(),
s.mStoredIndexCount,
GL4.GL_UNSIGNED_INT,
offset,
s.instanceCount)
} else {
gl.glDrawArraysInstanced(
geometryType.toOpenGLType(),
0, s.mStoredPrimitiveCount, s.instanceCount)
}
// gl.glUseProgram(0)
// gl.glBindVertexArray(0)
}
}
}
override fun screenshot(filename: String, overwrite: Boolean) {
screenshotRequested = true
screenshotOverwriteExisting = overwrite
screenshotFilename = filename
}
@Suppress("unused")
override fun recordMovie(filename: String, overwrite: Boolean) {
if(recordMovie) {
encoder?.finish()
encoder = null
recordMovie = false
} else {
movieFilename = filename
recordMovie = true
}
}
private fun Blending.BlendFactor.toOpenGL() = when (this) {
Blending.BlendFactor.Zero -> GL4.GL_ZERO
Blending.BlendFactor.One -> GL4.GL_ONE
Blending.BlendFactor.SrcAlpha -> GL4.GL_SRC_ALPHA
Blending.BlendFactor.OneMinusSrcAlpha -> GL4.GL_ONE_MINUS_SRC_ALPHA
Blending.BlendFactor.SrcColor -> GL4.GL_SRC_COLOR
Blending.BlendFactor.OneMinusSrcColor -> GL4.GL_ONE_MINUS_SRC_COLOR
Blending.BlendFactor.DstColor -> GL4.GL_DST_COLOR
Blending.BlendFactor.OneMinusDstColor -> GL4.GL_ONE_MINUS_DST_COLOR
Blending.BlendFactor.DstAlpha -> GL4.GL_DST_ALPHA
Blending.BlendFactor.OneMinusDstAlpha -> GL4.GL_ONE_MINUS_DST_ALPHA
Blending.BlendFactor.ConstantColor -> GL4.GL_CONSTANT_COLOR
Blending.BlendFactor.OneMinusConstantColor -> GL4.GL_ONE_MINUS_CONSTANT_COLOR
Blending.BlendFactor.ConstantAlpha -> GL4.GL_CONSTANT_ALPHA
Blending.BlendFactor.OneMinusConstantAlpha -> GL4.GL_ONE_MINUS_CONSTANT_ALPHA
Blending.BlendFactor.Src1Color -> GL4.GL_SRC1_COLOR
Blending.BlendFactor.OneMinusSrc1Color -> GL4.GL_ONE_MINUS_SRC1_COLOR
Blending.BlendFactor.Src1Alpha -> GL4.GL_SRC1_ALPHA
Blending.BlendFactor.OneMinusSrc1Alpha -> GL4.GL_ONE_MINUS_SRC1_ALPHA
Blending.BlendFactor.SrcAlphaSaturate -> GL4.GL_SRC_ALPHA_SATURATE
}
private fun Blending.BlendOp.toOpenGL() = when (this) {
Blending.BlendOp.add -> GL4.GL_FUNC_ADD
Blending.BlendOp.subtract -> GL4.GL_FUNC_SUBTRACT
Blending.BlendOp.min -> GL4.GL_MIN
Blending.BlendOp.max -> GL4.GL_MAX
Blending.BlendOp.reverse_subtract -> GL4.GL_FUNC_REVERSE_SUBTRACT
}
/**
* Sets the rendering quality, if the loaded renderer config file supports it.
*
* @param[quality] The [RenderConfigReader.RenderingQuality] to be set.
*/
override fun setRenderingQuality(quality: RenderConfigReader.RenderingQuality) {
fun setConfigSetting(key: String, value: Any) {
val setting = "Renderer.$key"
logger.debug("Setting $setting: ${settings.get<Any>(setting)} -> $value")
settings.set(setting, value)
}
if(renderConfig.qualitySettings.isNotEmpty()) {
logger.info("Setting rendering quality to $quality")
renderConfig.qualitySettings[quality]?.forEach { setting ->
if(setting.key.endsWith(".shaders") && setting.value is List<*>) {
val pass = setting.key.substringBeforeLast(".shaders")
@Suppress("UNCHECKED_CAST")
val shaders = setting.value as? List<String> ?: return@forEach
renderConfig.renderpasses[pass]?.shaders = shaders
mustRecreateFramebuffers = true
framebufferRecreateHook = {
renderConfig.qualitySettings[quality]?.filter { !it.key.endsWith(".shaders") }?.forEach {
setConfigSetting(it.key, it.value)
}
framebufferRecreateHook = {}
}
} else {
setConfigSetting(setting.key, setting.value)
}
}
} else {
logger.warn("The current renderer config, $renderConfigFile, does not support setting quality options.")
}
}
/**
* Closes this renderer instance.
*/
override fun close() {
if (shouldClose || !initialized) {
return
}
shouldClose = true
lastResizeTimer.cancel()
encoder?.finish()
cglWindow?.closeNoEDT()
joglDrawable?.destroy()
}
}
|
lgpl-3.0
|
a904daf925e9c5f8f3b6ccc9ba717015
| 38.538105 | 212 | 0.562459 | 4.739484 | false | false | false | false |
leafclick/intellij-community
|
plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateFromSourcesDialog.kt
|
1
|
2444
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.actions.updateFromSources
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.layout.*
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
class UpdateFromSourcesDialog(private val project: Project,
private val showApplyButton: Boolean) : DialogWrapper(project, true) {
private lateinit var panel: DialogPanel
private val state = UpdateFromSourcesSettingsState().apply {
copyFrom(UpdateFromSourcesSettings.getState())
}
init {
title = "Update IDE from Sources"
setOKButtonText("Update")
init()
}
override fun createCenterPanel(): DialogPanel {
panel = panel {
row("IDE installation:") {
textFieldWithBrowseButton({ state.workIdePath ?: PathManager.getHomePath() },
{ state.workIdePath = it },
"Choose IDE Installation Directory", project,
//todo use filter
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
row {
checkBox("Build disabled and non-bundled plugins", state::buildDisabledPlugins)
}
row {
checkBox("Do not show this dialog again", { !state.showSettings }, { state.showSettings = !it },
"You can invoke 'Update From Sources Settings' action to change settings")
}
}
return panel
}
override fun doOKAction() {
applyChanges()
super.doOKAction()
}
override fun createActions(): Array<Action> {
if (showApplyButton) {
val applyAction = object : AbstractAction("Apply") {
override fun actionPerformed(e: ActionEvent?) {
applyChanges()
close(NEXT_USER_EXIT_CODE)
}
}
return arrayOf(okAction, applyAction, cancelAction)
}
return super.createActions()
}
private fun applyChanges() {
panel.apply()
service<UpdateFromSourcesSettings>().loadState(state)
}
}
|
apache-2.0
|
8be213e27ad732c9de46029c922d5022
| 33.928571 | 140 | 0.670213 | 5.070539 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/extensionProperties/inClassLongTypeInReceiver.kt
|
5
|
503
|
class Test {
var doubleStorage = "fail"
var longStorage = "fail"
var Double.foo: String
get() = doubleStorage
set(value) {
doubleStorage = value
}
var Long.bar: String
get() = longStorage
set(value) {
longStorage = value
}
fun test(): String {
val d = 1.0
d.foo = "O"
val l = 1L
l.bar = "K"
return d.foo + l.bar
}
}
fun box(): String {
return Test().test()
}
|
apache-2.0
|
932b4412743605811cca4ce91b729ba8
| 16.964286 | 33 | 0.469185 | 3.725926 | false | true | false | false |
smmribeiro/intellij-community
|
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/run/PythonRunLessonsUtils.kt
|
9
|
1296
|
// 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.lesson.run
import training.dsl.parseLessonSample
object PythonRunLessonsUtils {
const val demoConfigurationName = "sandbox"
val demoSample = parseLessonSample("""
def find_average(value):
check_input(value)
result = 0
for s in value:
<caret>result += <select id=1>validate_number(extract_number(remove_quotes(s)))</select>
<caret id=3/>return <select id=4>result / len(value)</select>
def prepare_values():
return ["'apple 1'", "orange 2", "'tomato 3'"]
def extract_number(s):
return int(<select id=2>s.split()[0]</select>)
def check_input(value):
if (value is None) or (len(value) == 0):
raise ValueError(value)
def remove_quotes(s):
if len(s) > 1 and s[0] == "'" and s[-1] == "'":
return s[1:-1]
return s
def validate_number(number):
if number < 0:
raise ValueError(number)
return number
average = find_average(prepare_values())
print("The average is ", average)
""".trimIndent())
}
|
apache-2.0
|
3c0a9939b6566fb732273ece98e68869
| 27.173913 | 140 | 0.589506 | 3.97546 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/filePrediction/src/com/intellij/filePrediction/references/FilePredictionReferencesHelper.kt
|
12
|
2564
|
// 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.filePrediction.references
import com.intellij.filePrediction.FileReferencesComputationResult
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import org.jetbrains.annotations.ApiStatus
internal object FilePredictionReferencesHelper {
private val EXTERNAL_REFERENCES_EP_NAME = ExtensionPointName<FileExternalReferencesProvider>(
"com.intellij.filePrediction.referencesProvider")
fun calculateExternalReferences(project: Project, file: VirtualFile?): FileReferencesComputationResult {
val start = System.currentTimeMillis()
val result = calculateReferencesInReadAction(project, file)
return FileReferencesComputationResult(result, start)
}
private fun calculateReferencesInReadAction(project: Project, file: VirtualFile?): ExternalReferencesResult {
var attempts = 0
val result = Ref<ExternalReferencesResult?>(null)
while (attempts < 5) {
val succeed = ProgressManager.getInstance().runInReadActionWithWriteActionPriority(
{ result.set(computeReferences(project, file)) }, EmptyProgressIndicator()
)
if (succeed) break
attempts++
}
return result.get() ?: ExternalReferencesResult.FAILED_COMPUTATION
}
private fun computeReferences(project: Project, file: VirtualFile?): ExternalReferencesResult {
if (file?.isValid == false) {
return ExternalReferencesResult.FAILED_COMPUTATION
}
val psiFile = file?.let { PsiManager.getInstance(project).findFile(it) }
if (DumbService.isDumb(project)) {
return ExternalReferencesResult.FAILED_COMPUTATION
}
return psiFile?.let { getReferencesProvider(it) } ?: ExternalReferencesResult.NO_REFERENCES
}
private fun getReferencesProvider(file: PsiFile): ExternalReferencesResult {
return EXTERNAL_REFERENCES_EP_NAME.extensions.mapNotNull { it.externalReferences(file) }.firstOrNull() ?: ExternalReferencesResult.FAILED_COMPUTATION
}
}
@ApiStatus.Internal
internal interface FileExternalReferencesProvider {
fun externalReferences(file: PsiFile): ExternalReferencesResult?
}
|
apache-2.0
|
3a182017b938504148e95b6d7fe99a74
| 41.75 | 153 | 0.791342 | 4.846881 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/SmartStepTargetVisitor.kt
|
1
|
14936
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import com.intellij.debugger.actions.MethodSmartStepTarget
import com.intellij.debugger.actions.SmartStepTarget
import com.intellij.psi.PsiMethod
import com.intellij.util.Range
import com.intellij.util.containers.OrderedSet
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.debugger.breakpoints.isInlineOnly
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.isFromJava
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.annotations.argumentValue
import org.jetbrains.kotlin.resolve.calls.callUtil.getParentCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.types.checker.isSingleClassifierType
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
// TODO support class initializers, local functions, delegated properties with specified type, setter for properties
class SmartStepTargetVisitor(
private val element: KtElement,
private val lines: Range<Int>,
private val consumer: OrderedSet<SmartStepTarget>
) : KtTreeVisitorVoid() {
private fun append(target: SmartStepTarget) {
consumer += target
}
private val intrinsicMethods = run {
val jvmTarget = element.platform.firstIsInstanceOrNull<JdkPlatform>()?.targetVersion ?: JvmTarget.DEFAULT
IntrinsicMethods(jvmTarget)
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
recordFunction(lambdaExpression.functionLiteral)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!recordFunction(function)) {
super.visitNamedFunction(function)
}
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
recordCallableReference(expression)
super.visitCallableReferenceExpression(expression)
}
private fun recordCallableReference(expression: KtCallableReferenceExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.callableReference.getResolvedCall(bindingContext) ?: return
when (val descriptor = resolvedCall.resultingDescriptor) {
is FunctionDescriptor -> recordFunctionReference(expression, descriptor)
is PropertyDescriptor -> recordGetter(expression, descriptor, bindingContext)
}
}
private fun recordFunctionReference(expression: KtCallableReferenceExpression, descriptor: FunctionDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava && declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, true, lines))
} else if (declaration is KtNamedFunction) {
val label = KotlinMethodSmartStepTarget.calcLabel(descriptor)
append(KotlinMethodReferenceSmartStepTarget(expression, lines, label, descriptor.getMethodName(), declaration))
}
}
private fun recordGetter(expression: KtExpression, descriptor: PropertyDescriptor, bindingContext: BindingContext) {
val getterDescriptor = descriptor.getter
if (getterDescriptor == null || getterDescriptor.isDefault) return
val ktDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, getterDescriptor) as? KtDeclaration ?: return
val delegatedResolvedCall = bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getterDescriptor]
if (delegatedResolvedCall != null) {
val delegatedPropertyGetterDescriptor = delegatedResolvedCall.resultingDescriptor
val delegateDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(
element.project, delegatedPropertyGetterDescriptor
) as? KtDeclarationWithBody ?: return
val label = "${descriptor.name}." + KotlinMethodSmartStepTarget.calcLabel(delegatedPropertyGetterDescriptor)
appendPropertyFilter(delegatedPropertyGetterDescriptor, delegateDeclaration, label, expression, lines)
} else {
if (ktDeclaration is KtPropertyAccessor && ktDeclaration.hasBody()) {
val label = KotlinMethodSmartStepTarget.calcLabel(getterDescriptor)
appendPropertyFilter(getterDescriptor, ktDeclaration, label, expression, lines)
}
}
}
private fun appendPropertyFilter(
descriptor: CallableMemberDescriptor,
declaration: KtDeclarationWithBody,
label: String,
expression: KtExpression,
lines: Range<Int>
) =
when (expression) {
is KtCallableReferenceExpression ->
append(KotlinMethodReferenceSmartStepTarget(expression, lines, label, descriptor.getMethodName(), declaration))
else ->
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
CallableMemberInfo(descriptor)
)
)
}
private fun recordFunction(function: KtFunction): Boolean {
val functionParameterInfo = function.getFunctionParameterInfo() ?: return false
val target = createSmartStepTarget(function, functionParameterInfo)
if (target != null) {
append(target)
return true
}
return false
}
private fun createSmartStepTarget(
function: KtFunction,
functionParameterInfo: FunctionParameterInfo
): KotlinLambdaSmartStepTarget? {
val (param, resultingDescriptor) = functionParameterInfo
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, resultingDescriptor) as? KtDeclaration ?: return null
val callerMethodOrdinal = countExistingMethodCalls(declaration)
if (param.isSamLambdaParameterDescriptor()) {
val methodDescriptor = param.type.getFirstAbstractMethodDescriptor() ?: return null
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
param,
callerMethodOrdinal,
true,
methodDescriptor.getMethodName()
)
)
}
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
param,
callerMethodOrdinal
)
)
}
private fun countExistingMethodCalls(declaration: KtDeclaration): Int {
return consumer
.filterIsInstance<KotlinMethodSmartStepTarget>()
.count { it.declaration != null && it.declaration === declaration }
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Skip calls in object declarations
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.condition?.accept(this)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
expression.condition?.accept(this)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
expression.condition?.accept(this)
}
override fun visitForExpression(expression: KtForExpression) {
expression.loopRange?.accept(this)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
expression.subjectExpression?.accept(this)
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
recordFunctionCall(expression)
super.visitArrayAccessExpression(expression)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
recordFunctionCall(expression.operationReference)
super.visitUnaryExpression(expression)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
recordFunctionCall(expression.operationReference)
super.visitBinaryExpression(expression)
}
override fun visitCallExpression(expression: KtCallExpression) {
val calleeExpression = expression.calleeExpression
if (calleeExpression != null) {
recordFunctionCall(calleeExpression)
}
super.visitCallExpression(expression)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return
val propertyDescriptor = resolvedCall.resultingDescriptor as? PropertyDescriptor ?: return
recordGetter(expression, propertyDescriptor, bindingContext)
super.visitSimpleNameExpression(expression)
}
private fun recordFunctionCall(expression: KtExpression) {
val resolvedCall = expression.resolveToCall() ?: return
val descriptor = resolvedCall.resultingDescriptor
if (descriptor !is FunctionDescriptor || isIntrinsic(descriptor)) return
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava) {
if (declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, false, lines))
}
} else {
if (declaration == null && !isInvokeInBuiltinFunction(descriptor)) {
return
}
if (declaration !is KtDeclaration?) return
if (descriptor is ConstructorDescriptor && descriptor.isPrimary) {
if (declaration is KtClass && declaration.getAnonymousInitializers().isEmpty()) {
// There is no constructor or init block, so do not show it in smart step into
return
}
}
// We can't step into @InlineOnly callables as there is no LVT, so skip them
if (declaration is KtCallableDeclaration && declaration.isInlineOnly()) {
return
}
val callLabel = KotlinMethodSmartStepTarget.calcLabel(descriptor)
val label = when (descriptor) {
is FunctionInvokeDescriptor -> {
when (expression) {
is KtSimpleNameExpression -> "${runReadAction { expression.text }}.$callLabel"
else -> callLabel
}
}
else -> callLabel
}
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
CallableMemberInfo(descriptor)
)
)
}
}
private fun isIntrinsic(descriptor: CallableMemberDescriptor): Boolean {
return intrinsicMethods.getIntrinsic(descriptor) != null
}
}
private val JVM_NAME_FQ_NAME = FqName("kotlin.jvm.JvmName")
private fun PropertyAccessorDescriptor.getJvmMethodName(): String {
val jvmNameAnnotation = annotations.findAnnotation(JVM_NAME_FQ_NAME)
val jvmName = jvmNameAnnotation?.argumentValue(JvmName::name.name)?.value as? String
if (jvmName != null) {
return jvmName
}
return JvmAbi.getterName(correspondingProperty.name.asString())
}
internal fun DeclarationDescriptor.getMethodName() =
when (this) {
is ClassDescriptor, is ConstructorDescriptor -> "<init>"
is PropertyAccessorDescriptor -> getJvmMethodName()
else -> name.asString()
}
private data class FunctionParameterInfo(val parameter: ValueParameterDescriptor, val resultingDescriptor: CallableMemberDescriptor)
fun KtFunction.isSamLambda(): Boolean {
val functionParameterInfo = getFunctionParameterInfo() ?: return false
return functionParameterInfo.parameter.isSamLambdaParameterDescriptor()
}
private fun ValueParameterDescriptor.isSamLambdaParameterDescriptor(): Boolean {
val type = type
return !type.isFunctionType && type is SimpleType && type.isSingleClassifierType
}
private fun KtFunction.getFunctionParameterInfo(): FunctionParameterInfo? {
val context = analyze()
val resolvedCall = getParentCall(context).getResolvedCall(context) ?: return null
val descriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return null
val arguments = resolvedCall.valueArguments
for ((param, argument) in arguments) {
if (argument.arguments.any { getArgumentExpression(it) == this }) {
return FunctionParameterInfo(param, descriptor)
}
}
return null
}
private fun getArgumentExpression(it: ValueArgument): KtExpression? {
return (it.getArgumentExpression() as? KtLambdaExpression)?.functionLiteral ?: it.getArgumentExpression()
}
private fun KotlinType.getFirstAbstractMethodDescriptor() =
memberScope
.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS)
.firstOrNull {
it is FunctionDescriptor && it.modality == Modality.ABSTRACT
}
private fun isInvokeInBuiltinFunction(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is FunctionInvokeDescriptor) return false
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false
return classDescriptor.defaultType.isBuiltinFunctionalType
}
|
apache-2.0
|
6954be230ee027d93cb77f1d8795507d
| 41.311615 | 158 | 0.700522 | 5.993579 | false | false | false | false |
anitawoodruff/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/FAQDetailFragment.kt
|
1
|
2139
|
package com.habitrpg.android.habitica.ui.fragments.support
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.FAQRepository
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.MarkdownParser
import com.habitrpg.android.habitica.ui.helpers.bindOptionalView
import com.habitrpg.android.habitica.ui.helpers.resetViews
import io.reactivex.functions.Consumer
import javax.inject.Inject
class FAQDetailFragment : BaseMainFragment() {
@Inject
lateinit var faqRepository: FAQRepository
private val questionTextView: TextView? by bindOptionalView(R.id.questionTextView)
private val answerTextView: TextView? by bindOptionalView(R.id.answerTextView)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
hidesToolbar = true
super.onCreateView(inflater, container, savedInstanceState)
return container?.inflate(R.layout.fragment_faq_detail)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resetViews()
arguments?.let {
val args = FAQDetailFragmentArgs.fromBundle(it)
compositeSubscription.add(faqRepository.getArticle(args.position).subscribe(Consumer { faq ->
this.questionTextView?.text = faq.question
this.answerTextView?.text = MarkdownParser.parseMarkdown(faq.answer)
}, RxErrorHandler.handleEmptyError()))
}
this.answerTextView?.movementMethod = LinkMovementMethod.getInstance()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
}
|
gpl-3.0
|
b655a4ef9119715a5b8cbd239ec11d9d
| 39.377358 | 116 | 0.769986 | 4.753333 | false | false | false | false |
anitawoodruff/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/OwnedMount.kt
|
1
|
950
|
package com.habitrpg.android.habitica.models.user
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class OwnedMount : RealmObject(), OwnedObject {
@PrimaryKey
override var combinedKey: String? = null
override var userID: String? = null
set(value) {
field = value
combinedKey = field + key
}
override var key: String? = null
set(value) {
field = value
combinedKey = field + key
}
var owned = false
override fun equals(other: Any?): Boolean {
return if (other?.javaClass == OwnedMount::class.java) {
this.combinedKey == (other as OwnedMount).combinedKey
} else super.equals(other)
}
override fun hashCode(): Int {
var result = combinedKey.hashCode()
result = 31 * result + userID.hashCode()
result = 31 * result + key.hashCode()
return result
}
}
|
gpl-3.0
|
894c838cc6ca9392e3183fa3e0efff21
| 26.142857 | 65 | 0.603158 | 4.481132 | false | false | false | false |
zdary/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/history/ReachableNodesUtil.kt
|
15
|
1930
|
// 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.vcs.log.history
import com.intellij.openapi.util.Ref
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.impl.facade.VisibleGraphImpl
import com.intellij.vcs.log.graph.utils.DfsWalk
import com.intellij.vcs.log.visible.VisiblePack
fun LinearGraph.findAncestorNode(startNodeId: Int, condition: (Int) -> Boolean): Int? {
val resultNodeId = Ref<Int>()
DfsWalk(setOf(startNodeId), this).walk(true) { currentNodeId: Int ->
if (condition(currentNodeId)) {
resultNodeId.set(currentNodeId)
false // stop walk, we have found it
}
else {
true // continue walk
}
}
return resultNodeId.get()
}
fun findVisibleAncestorRow(commitId: Int, visiblePack: VisiblePack): Int? {
val dataPack = visiblePack.dataPack
val visibleGraph = visiblePack.visibleGraph
if (dataPack is DataPack && dataPack.permanentGraph is PermanentGraphInfo<*> && visibleGraph is VisibleGraphImpl) {
return findVisibleAncestorRow(commitId, visibleGraph.linearGraph, dataPack.permanentGraph as PermanentGraphInfo<Int>) { true }
}
return null
}
fun findVisibleAncestorRow(commitId: Int,
visibleLinearGraph: LinearGraph,
permanentGraphInfo: PermanentGraphInfo<Int>,
condition: (Int) -> Boolean): Int? {
val startNodeId = permanentGraphInfo.permanentCommitsInfo.getNodeId(commitId)
val ancestorNodeId = permanentGraphInfo.linearGraph.findAncestorNode(startNodeId) { nodeId: Int ->
condition(nodeId) && visibleLinearGraph.getNodeIndex(nodeId) != null
} ?: return null
return visibleLinearGraph.getNodeIndex(ancestorNodeId)
}
|
apache-2.0
|
3384bbddbf8eccb3a26939a92c98a470
| 40.978261 | 140 | 0.739896 | 4.396355 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/lazy/resolve/FirLazyBodiesCalculator.kt
|
2
|
5833
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.lazy.resolve
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.builder.RawFirBuilder
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.expressions.FirWrappedDelegateExpression
import org.jetbrains.kotlin.fir.expressions.impl.FirLazyBlock
import org.jetbrains.kotlin.fir.expressions.impl.FirLazyExpression
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.visitors.CompositeTransformResult
import org.jetbrains.kotlin.fir.visitors.FirTransformer
import org.jetbrains.kotlin.fir.visitors.compose
import org.jetbrains.kotlin.idea.fir.low.level.api.providers.firIdeProvider
import org.jetbrains.kotlin.psi.*
internal object FirLazyBodiesCalculator {
fun calculateLazyBodiesInside(element: FirElement) {
element.transform<FirElement, Nothing?>(FirLazyBodiesCalculatorTransformer, null)
}
fun calculateLazyBodiesIfPhaseRequires(firFile: FirFile, phase: FirResolvePhase) {
if (phase == FIRST_PHASE_WHICH_NEEDS_BODIES) {
calculateLazyBodiesInside(firFile)
}
}
fun calculateLazyBodiesForFunction(simpleFunction: FirSimpleFunction) {
if (simpleFunction.body !is FirLazyBlock) return
val rawFirBuilder = createRawFirBuilder(simpleFunction)
val newFunction = rawFirBuilder.buildFunctionWithBody(simpleFunction.psi as KtNamedFunction, simpleFunction) as FirSimpleFunction
simpleFunction.apply {
replaceBody(newFunction.body)
replaceContractDescription(newFunction.contractDescription)
}
}
fun calculateLazyBodyForSecondaryConstructor(secondaryConstructor: FirConstructor) {
require(!secondaryConstructor.isPrimary)
if (secondaryConstructor.body !is FirLazyBlock) return
val rawFirBuilder = createRawFirBuilder(secondaryConstructor)
val newFunction = rawFirBuilder.buildSecondaryConstructor(secondaryConstructor.psi as KtSecondaryConstructor, secondaryConstructor)
secondaryConstructor.apply {
replaceBody(newFunction.body)
}
}
fun calculateLazyBodyForProperty(firProperty: FirProperty) {
if (!needCalculatingLazyBodyForProperty(firProperty)) return
val rawFirBuilder = createRawFirBuilder(firProperty)
val newProperty = rawFirBuilder.buildPropertyWithBody(firProperty.psi as KtProperty, firProperty)
firProperty.getter?.takeIf { it.body is FirLazyBlock }?.let { getter ->
val newGetter = newProperty.getter!!
getter.replaceBody(newGetter.body)
getter.replaceContractDescription(newGetter.contractDescription)
}
firProperty.setter?.takeIf { it.body is FirLazyBlock }?.let { setter ->
val newSetter = newProperty.setter!!
setter.replaceBody(newSetter.body)
setter.replaceContractDescription(newSetter.contractDescription)
}
if (firProperty.initializer is FirLazyExpression) {
firProperty.replaceInitializer(newProperty.initializer)
}
val delegate = firProperty.delegate
if (delegate is FirWrappedDelegateExpression && delegate.expression is FirLazyExpression) {
val newDelegate = newProperty.delegate as FirWrappedDelegateExpression
delegate.replaceExpression(newDelegate.expression)
}
}
fun needCalculatingLazyBodyForProperty(firProperty: FirProperty): Boolean =
firProperty.getter?.body is FirLazyBlock
|| firProperty.setter?.body is FirLazyBlock
|| firProperty.initializer is FirLazyExpression
|| (firProperty.delegate as? FirWrappedDelegateExpression)?.expression is FirLazyExpression
private fun createRawFirBuilder(firDeclaration: FirDeclaration): RawFirBuilder {
val scopeProvider = firDeclaration.session.firIdeProvider.kotlinScopeProvider
return RawFirBuilder(firDeclaration.session, scopeProvider)
}
private val FIRST_PHASE_WHICH_NEEDS_BODIES = FirResolvePhase.CONTRACTS
}
private object FirLazyBodiesCalculatorTransformer : FirTransformer<Nothing?>() {
override fun <E : FirElement> transformElement(element: E, data: Nothing?): CompositeTransformResult<E> {
@Suppress("UNCHECKED_CAST")
return (element.transformChildren(this, data) as E).compose()
}
override fun transformSimpleFunction(simpleFunction: FirSimpleFunction, data: Nothing?): CompositeTransformResult<FirDeclaration> {
if (simpleFunction.body is FirLazyBlock) {
FirLazyBodiesCalculator.calculateLazyBodiesForFunction(simpleFunction)
return simpleFunction.compose()
}
return (simpleFunction.transformChildren(this, data) as FirDeclaration).compose()
}
override fun transformConstructor(constructor: FirConstructor, data: Nothing?): CompositeTransformResult<FirDeclaration> {
if (constructor.body is FirLazyBlock) {
FirLazyBodiesCalculator.calculateLazyBodyForSecondaryConstructor(constructor)
return constructor.compose()
}
return (constructor.transformChildren(this, data) as FirDeclaration).compose()
}
override fun transformProperty(property: FirProperty, data: Nothing?): CompositeTransformResult<FirDeclaration> {
if (FirLazyBodiesCalculator.needCalculatingLazyBodyForProperty(property)) {
FirLazyBodiesCalculator.calculateLazyBodyForProperty(property)
return property.compose()
}
return super.transformProperty(property, data)
}
}
|
apache-2.0
|
ca0b927832c321e6b5c75ec6b7f5ac1a
| 45.664 | 139 | 0.743357 | 4.804778 | false | false | false | false |
siosio/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/SwingUtils.kt
|
1
|
960
|
@file:Suppress("MagicNumber") // Swing dimension constants
package com.jetbrains.packagesearch.intellij.plugin.ui.util
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import javax.swing.UIManager
@ScaledPixels
internal fun scrollbarWidth() = UIManager.get("ScrollBar.width") as Int
internal fun mouseListener(
onClick: (e: MouseEvent) -> Unit = {},
onPressed: (e: MouseEvent) -> Unit = {},
onReleased: (e: MouseEvent) -> Unit = {},
onEntered: (e: MouseEvent) -> Unit = {},
onExited: (e: MouseEvent) -> Unit = {}
) = object : MouseListener {
override fun mouseClicked(e: MouseEvent) {
onClick(e)
}
override fun mousePressed(e: MouseEvent) {
onPressed(e)
}
override fun mouseReleased(e: MouseEvent) {
onReleased(e)
}
override fun mouseEntered(e: MouseEvent) {
onEntered(e)
}
override fun mouseExited(e: MouseEvent) {
onExited(e)
}
}
|
apache-2.0
|
d5a3681201be887455533ce6cf603a9c
| 24.263158 | 71 | 0.655208 | 3.950617 | false | false | false | false |
siosio/intellij-community
|
plugins/javaFX/testSrc/org/jetbrains/plugins/javaFX/JavaFxModuleBuilderTest.kt
|
1
|
6507
|
// 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.javaFX
import com.intellij.ide.starters.local.StarterModuleBuilder.Companion.setupTestModule
import com.intellij.ide.starters.shared.*
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase.JAVA_11
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase4
import org.jetbrains.plugins.javaFX.wizard.JavaFxModuleBuilder
import org.junit.Test
class JavaFxModuleBuilderTest : LightJavaCodeInsightFixtureTestCase4(JAVA_11) {
@Test
fun emptyMavenProject() {
JavaFxModuleBuilder().setupTestModule(fixture.module) {
language = JAVA_STARTER_LANGUAGE
projectType = MAVEN_PROJECT
testFramework = JUNIT_TEST_RUNNER
isCreatingNewProject = true
}
expectFile("src/main/java/com/example/demo/HelloApplication.java", """
package com.example.demo;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
""".trimIndent())
val dlr = "\$"
expectFile("pom.xml", """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>light_idea_test_case</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>${dlr}{junit.version}</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${dlr}{junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${dlr}{junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.6</version>
<executions>
<execution>
<!-- Default configuration for running with: mvn clean javafx:run -->
<id>default-cli</id>
<configuration>
<mainClass>com.example.demo/com.example.demo.HelloApplication</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
""".trimIndent())
}
@Test
fun emptyGradleProject() {
JavaFxModuleBuilder().setupTestModule(fixture.module) {
language = JAVA_STARTER_LANGUAGE
projectType = GRADLE_PROJECT
testFramework = TESTNG_TEST_RUNNER
isCreatingNewProject = true
}
expectFile("src/main/java/com/example/demo/HelloController.java", """
package com.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class HelloController {
@FXML
private Label welcomeText;
@FXML
protected void onHelloButtonClick() {
welcomeText.setText("Welcome to JavaFX Application!");
}
}
""".trimIndent())
expectFile("build.gradle", """
plugins {
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.10'
}
group 'com.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
sourceCompatibility = '11'
targetCompatibility = '11'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
application {
mainModule = 'com.example.demo'
mainClass = 'com.example.demo.HelloApplication'
}
javafx {
version = '11.0.2'
modules = ['javafx.controls', 'javafx.fxml']
}
dependencies {
testImplementation('org.testng:testng:7.4.0')
}
test {
useTestNG()
}
""".trimIndent())
expectFile("settings.gradle", """
rootProject.name = "demo"
""".trimIndent())
}
private fun expectFile(path: String, content: String) {
fixture.configureFromTempProjectFile(path)
fixture.checkResult(content)
}
}
|
apache-2.0
|
1274e83737199b5b2cd731525ea7690f
| 31.868687 | 140 | 0.557553 | 4.749635 | false | true | false | false |
vovagrechka/fucking-everything
|
phizdets/phizdetsc/src/org/jetbrains/kotlin/serialization/js/KotlinJavascriptSerializationUtil.kt
|
3
|
10066
|
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.serialization.js
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.serialization.AnnotationSerializer
import org.jetbrains.kotlin.serialization.DescriptorSerializer
import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfiguration
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.JsMetadataVersion
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.util.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object KotlinJavascriptSerializationUtil {
val CLASS_METADATA_FILE_EXTENSION: String = "kjsm"
@JvmStatic
fun readModule(
metadata: ByteArray, storageManager: StorageManager, module: ModuleDescriptor, configuration: DeserializationConfiguration
): JsModuleDescriptor<PackageFragmentProvider?> {
val jsModule = metadata.deserializeToLibraryParts(module.name.asString())
return jsModule.copy(createKotlinJavascriptPackageFragmentProvider(storageManager, module, jsModule.data, configuration))
}
fun serializeMetadata(
bindingContext: BindingContext,
module: ModuleDescriptor,
moduleKind: ModuleKind,
importedModules: List<String>
): JsProtoBuf.Library {
val builder = JsProtoBuf.Library.newBuilder()
val moduleProtoKind = when (moduleKind) {
ModuleKind.PLAIN -> JsProtoBuf.Library.Kind.PLAIN
ModuleKind.AMD -> JsProtoBuf.Library.Kind.AMD
ModuleKind.COMMON_JS -> JsProtoBuf.Library.Kind.COMMON_JS
ModuleKind.UMD -> JsProtoBuf.Library.Kind.UMD
}
if (builder.kind != moduleProtoKind) {
builder.kind = moduleProtoKind
}
importedModules.forEach { builder.addImportedModule(it) }
for (fqName in getPackagesFqNames(module)) {
val part = serializePackage(bindingContext, module, fqName)
if (part.hasPackage() || part.class_Count > 0) {
builder.addPart(part)
}
}
return builder.build()
}
fun metadataAsString(bindingContext: BindingContext, jsDescriptor: JsModuleDescriptor<ModuleDescriptor>): String =
KotlinJavascriptMetadataUtils.formatMetadataAsString(jsDescriptor.name, jsDescriptor.serializeToBinaryMetadata(bindingContext))
fun serializePackage(bindingContext: BindingContext, module: ModuleDescriptor, fqName: FqName): JsProtoBuf.Library.Part {
val builder = JsProtoBuf.Library.Part.newBuilder()
val packageView = module.getPackage(fqName)
// TODO: ModuleDescriptor should be able to return the package only with the contents of that module, without dependencies
val skip: (DeclarationDescriptor) -> Boolean = { DescriptorUtils.getContainingModule(it) != module || (it is MemberDescriptor && it.isHeader) }
val fileRegistry = KotlinFileRegistry()
val serializerExtension = KotlinJavascriptSerializerExtension(fileRegistry, fqName)
val serializer = DescriptorSerializer.createTopLevel(serializerExtension)
val classDescriptors = DescriptorSerializer.sort(
packageView.memberScope.getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS)
).filterIsInstance<ClassDescriptor>()
fun serializeClasses(descriptors: Collection<DeclarationDescriptor>) {
fun serializeClass(classDescriptor: ClassDescriptor) {
if (skip(classDescriptor)) return
val classProto = serializer.classProto(classDescriptor).build() ?: error("Class not serialized: $classDescriptor")
builder.addClass_(classProto)
serializeClasses(classDescriptor.unsubstitutedInnerClassesScope.getContributedDescriptors())
}
for (descriptor in descriptors) {
if (descriptor is ClassDescriptor) {
serializeClass(descriptor)
}
}
}
serializeClasses(classDescriptors)
val stringTable = serializerExtension.stringTable
val fragments = packageView.fragments
val members = fragments
.flatMap { fragment -> DescriptorUtils.getAllDescriptors(fragment.getMemberScope()) }
.filterNot(skip)
builder.`package` = serializer.packagePartProto(members).apply {
setExtension(JsProtoBuf.packageFqName, stringTable.getPackageFqNameIndex(fqName))
}.build()
builder.files = serializeFiles(fileRegistry, bindingContext, AnnotationSerializer(stringTable))
val (strings, qualifiedNames) = stringTable.buildProto()
builder.strings = strings
builder.qualifiedNames = qualifiedNames
return builder.build()
}
private fun serializeFiles(
fileRegistry: KotlinFileRegistry,
bindingContext: BindingContext,
serializer: AnnotationSerializer
): JsProtoBuf.Files {
val filesProto = JsProtoBuf.Files.newBuilder()
for ((file, id) in fileRegistry.fileIds.entries.sortedBy { it.value }) {
val fileProto = JsProtoBuf.File.newBuilder()
if (id != filesProto.fileCount) {
fileProto.id = id
}
for (annotationPsi in file.annotationEntries) {
val annotation = bindingContext[BindingContext.ANNOTATION, annotationPsi]!!
fileProto.addAnnotation(serializer.serializeAnnotation(annotation))
}
filesProto.addFile(fileProto)
}
return filesProto.build()
}
fun toContentMap(bindingContext: BindingContext, module: ModuleDescriptor): Map<String, ByteArray> {
val contentMap = hashMapOf<String, ByteArray>()
for (fqName in getPackagesFqNames(module)) {
val part = serializePackage(bindingContext, module, fqName)
if (part.class_Count == 0 && part.`package`.let { packageProto ->
packageProto.functionCount == 0 && packageProto.propertyCount == 0 && packageProto.typeAliasCount == 0
}) continue
val stream = ByteArrayOutputStream()
with(DataOutputStream(stream)) {
val version = JsMetadataVersion.INSTANCE.toArray()
writeInt(version.size)
version.forEach(this::writeInt)
}
serializeHeader(fqName).writeDelimitedTo(stream)
part.writeTo(stream)
contentMap[JsSerializerProtocol.getKjsmFilePath(fqName)] = stream.toByteArray()
}
return contentMap
}
fun serializeHeader(packageFqName: FqName?): JsProtoBuf.Header {
val header = JsProtoBuf.Header.newBuilder()
if (packageFqName != null) {
header.packageFqName = packageFqName.asString()
}
// TODO: write pre-release flag if needed
// TODO: write JS code binary version
return header.build()
}
private fun getPackagesFqNames(module: ModuleDescriptor): Set<FqName> {
return HashSet<FqName>().apply {
getSubPackagesFqNames(module.getPackage(FqName.ROOT), this)
add(FqName.ROOT)
}
}
private fun getSubPackagesFqNames(packageView: PackageViewDescriptor, result: MutableSet<FqName>) {
val fqName = packageView.fqName
if (!fqName.isRoot) {
result.add(fqName)
}
for (descriptor in packageView.memberScope.getContributedDescriptors(DescriptorKindFilter.PACKAGES, MemberScope.ALL_NAME_FILTER)) {
if (descriptor is PackageViewDescriptor) {
getSubPackagesFqNames(descriptor, result)
}
}
}
private fun JsModuleDescriptor<ModuleDescriptor>.serializeToBinaryMetadata(bindingContext: BindingContext): ByteArray {
return ByteArrayOutputStream().apply {
GZIPOutputStream(this).use { stream ->
serializeHeader(null).writeDelimitedTo(stream)
serializeMetadata(bindingContext, data, kind, imported).writeTo(stream)
}
}.toByteArray()
}
private fun ByteArray.deserializeToLibraryParts(name: String): JsModuleDescriptor<List<JsProtoBuf.Library.Part>> {
val content = GZIPInputStream(ByteArrayInputStream(this)).use { stream ->
JsProtoBuf.Header.parseDelimitedFrom(stream, JsSerializerProtocol.extensionRegistry)
JsProtoBuf.Library.parseFrom(stream, JsSerializerProtocol.extensionRegistry)
}
return JsModuleDescriptor(
name = name,
data = content.partList,
kind = when (content.kind) {
null, JsProtoBuf.Library.Kind.PLAIN -> ModuleKind.PLAIN
JsProtoBuf.Library.Kind.AMD -> ModuleKind.AMD
JsProtoBuf.Library.Kind.COMMON_JS -> ModuleKind.COMMON_JS
JsProtoBuf.Library.Kind.UMD -> ModuleKind.UMD
},
imported = content.importedModuleList
)
}
}
|
apache-2.0
|
2b02119bf2dbf3f72c36ea4f83e67484
| 41.117155 | 151 | 0.680707 | 5.212843 | false | false | false | false |
youdonghai/intellij-community
|
platform/configuration-store-impl/src/ApplicationStoreImpl.kt
|
2
|
4825
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.application.options.PathMacrosImpl
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.impl.BasePathMacroManager
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.NamedJDOMExternalizable
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.io.delete
import com.intellij.util.io.outputStream
import org.jdom.Element
private class ApplicationPathMacroManager : BasePathMacroManager(null)
const val APP_CONFIG = "\$APP_CONFIG$"
class ApplicationStoreImpl(private val application: Application, pathMacroManager: PathMacroManager? = null) : ComponentStoreImpl() {
override val storageManager = ApplicationStorageManager(application, pathMacroManager)
// number of app components require some state, so, we load default state in test mode
override val loadPolicy: StateLoadPolicy
get() = if (application.isUnitTestMode) StateLoadPolicy.LOAD_ONLY_DEFAULT else StateLoadPolicy.LOAD
override fun setPath(path: String) {
// app config must be first, because collapseMacros collapse from fist to last, so, at first we must replace APP_CONFIG because it overlaps ROOT_CONFIG value
storageManager.addMacro(APP_CONFIG, "$path/${ApplicationStorageManager.FILE_STORAGE_DIR}")
storageManager.addMacro(ROOT_CONFIG, path)
val configDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)
if (configDir != null) {
invokeAndWaitIfNeed {
// not recursive, config directory contains various data - for example, ICS or shelf should not be refreshed,
// but we refresh direct children to avoid refreshAndFindFile in SchemeManager (to find schemes directory)
VfsUtil.markDirtyAndRefresh(false, false, true, configDir)
val optionsDir = configDir.findChild(ApplicationStorageManager.FILE_STORAGE_DIR)
if (optionsDir != null) {
// not recursive, options directory contains only files
VfsUtil.markDirtyAndRefresh(false, false, true, optionsDir)
}
}
}
}
}
class ApplicationStorageManager(application: Application, pathMacroManager: PathMacroManager? = null) : StateStorageManagerImpl("application", pathMacroManager?.createTrackingSubstitutor(), application) {
companion object {
private val DEFAULT_STORAGE_SPEC = "${PathManager.DEFAULT_OPTIONS_FILE_NAME}${FileStorageCoreUtil.DEFAULT_EXT}"
val FILE_STORAGE_DIR = "options"
}
override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? {
return if (component is NamedJDOMExternalizable) {
"${component.externalFileName}${FileStorageCoreUtil.DEFAULT_EXT}"
}
else {
DEFAULT_STORAGE_SPEC
}
}
override fun getMacroSubstitutor(fileSpec: String) = if (fileSpec == "${PathMacrosImpl.EXT_FILE_NAME}${FileStorageCoreUtil.DEFAULT_EXT}") null else super.getMacroSubstitutor(fileSpec)
override val isUseXmlProlog: Boolean
get() = false
override fun dataLoadedFromProvider(storage: FileBasedStorage, element: Element?) {
// IDEA-144052 When "Settings repository" is enabled changes in 'Path Variables' aren't saved to default path.macros.xml file causing errors in build process
if (storage.fileSpec != "path.macros.xml") {
return
}
LOG.catchAndLog {
if (element == null) {
storage.file.delete()
}
else {
JDOMUtil.writeElement(element, storage.file.outputStream().writer(), "\n")
}
}
}
override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), APP_CONFIG)
override fun expandMacros(path: String) = if (path[0] == '$') {
super.expandMacros(path)
}
else {
"${expandMacro(APP_CONFIG)}/$path"
}
}
|
apache-2.0
|
c194cc8bfa069186a22e98ec1860714c
| 42.089286 | 204 | 0.758342 | 4.711914 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt
|
3
|
4122
|
// 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.scratch.actions
import com.intellij.execution.lineMarker.RunLineMarkerContributor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.psi.getLineCount
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.getScratchFile
import org.jetbrains.kotlin.idea.scratch.isKotlinScratch
import org.jetbrains.kotlin.idea.scratch.isKotlinWorksheet
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ScratchRunLineMarkerContributor : RunLineMarkerContributor() {
override fun getInfo(element: PsiElement): Info? {
element.containingFile.safeAs<KtFile>()?.takeIf {
val file = it.virtualFile
file.isKotlinWorksheet || file.isKotlinScratch || it.isScript()
} ?: return null
val declaration = element.getStrictParentOfType<KtNamedDeclaration>()
if (declaration != null && declaration !is KtParameter && declaration.nameIdentifier == element) {
return isLastExecutedExpression(element)
}
element.getParentOfType<KtScriptInitializer>(true)?.body?.let { scriptInitializer ->
return if (scriptInitializer.findDescendantOfType<LeafPsiElement>() == element) {
isLastExecutedExpression(element)
} else null
}
// Show arrow for last added empty line
if (declaration is KtScript && element is PsiWhiteSpace) {
getLastExecutedExpression(element)?.let { _ ->
if (element.getLineNumber() == element.containingFile.getLineCount() ||
element.getLineNumber(false) == element.containingFile.getLineCount()
) return Info(RunScratchFromHereAction())
}
}
return null
}
private fun isLastExecutedExpression(element: PsiElement): Info? {
val expression = getLastExecutedExpression(element) ?: return null
if (element.getLineNumber(true) != expression.lineStart) {
return null
}
return if (PsiTreeUtil.isAncestor(expression.element, element, false)) {
Info(RunScratchFromHereAction())
} else null
}
private fun getLastExecutedExpression(element: PsiElement): ScratchExpression? {
val scratchFile = getSingleOpenedTextEditor(element.containingFile)?.getScratchFile() ?: return null
if (!scratchFile.options.isRepl) return null
val replExecutor = scratchFile.replScratchExecutor ?: return null
return replExecutor.getFirstNewExpression()
}
/**
* This method returns single editor in which passed [psiFile] opened.
* If there is no such editor or there is more than one editor, it returns `null`.
*
* We use [PsiDocumentManager.getCachedDocument] instead of [PsiDocumentManager.getDocument]
* so this would not require read action.
*/
private fun getSingleOpenedTextEditor(psiFile: PsiFile): TextEditor? {
val document = PsiDocumentManager.getInstance(psiFile.project).getCachedDocument(psiFile) ?: return null
val singleOpenedEditor = EditorFactory.getInstance().getEditors(document, psiFile.project).singleOrNull() ?: return null
return TextEditorProvider.getInstance().getTextEditor(singleOpenedEditor)
}
}
|
apache-2.0
|
657974527e3c836f0c797a35dfa45be3
| 46.930233 | 158 | 0.733624 | 5.063882 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedMainParameterInspection.kt
|
1
|
1699
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.parameterVisitor
import org.jetbrains.kotlin.resolve.BindingContext.UNUSED_MAIN_PARAMETER
class UnusedMainParameterInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
parameterVisitor(fun(parameter: KtParameter) {
val function = parameter.ownerFunction as? KtNamedFunction ?: return
if (function.name != "main") return
val context = function.analyzeWithContent()
if (context[UNUSED_MAIN_PARAMETER, parameter] == true) {
holder.registerProblem(
parameter,
KotlinBundle.message("since.kotlin.1.3.main.parameter.is.not.necessary"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
IntentionWrapper(RemoveUnusedFunctionParameterFix(parameter), parameter.containingFile)
)
}
})
}
|
apache-2.0
|
6453ac4fe7357c821004d892f8e22112
| 50.515152 | 158 | 0.74691 | 5.179878 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/util/animation/ShowHideAnimator.kt
|
1
|
2403
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.animation
import com.intellij.openapi.util.registry.Registry.intValue
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.DoubleConsumer
import kotlin.math.roundToInt
open class ShowHideAnimator(easing: Easing, private val consumer: DoubleConsumer) {
private val animator = JBAnimator()
private val atomicVisible = AtomicBoolean()
private val statefulEasing = easing.stateful()
constructor(consumer: DoubleConsumer) : this(Easing.LINEAR, consumer)
fun setVisible(visible: Boolean, updateVisibility: () -> Unit) {
if (visible != atomicVisible.getAndSet(visible)) {
val value = statefulEasing.value
when {
!visible && value > 0.0 -> animator.animate(createHidingAnimation(value, updateVisibility))
visible && value < 1.0 -> animator.animate(createShowingAnimation(value, updateVisibility))
else -> animator.stop()
}
}
}
fun setVisibleImmediately(visible: Boolean) {
animator.stop()
if (visible != atomicVisible.getAndSet(visible)) {
consumer.accept(statefulEasing.calc(if (visible) 1.0 else 0.0))
}
}
private val showingDelay
get() = intValue("ide.animation.showing.delay", 0)
private val showingDuration
get() = intValue("ide.animation.showing.duration", 130)
private val hidingDelay
get() = intValue("ide.animation.hiding.delay", 140)
private val hidingDuration
get() = intValue("ide.animation.hiding.duration", 150)
private fun createShowingAnimation(value: Double, visibility: () -> Unit) = Animation(consumer).apply {
if (value > 0.0) {
duration = (showingDuration * (1 - value)).roundToInt()
easing = statefulEasing.coerceIn(value, 1.0)
}
else {
delay = showingDelay
duration = showingDuration
easing = statefulEasing
}
}.runWhenScheduled(visibility)
private fun createHidingAnimation(value: Double, visibility: () -> Unit) = Animation(consumer).apply {
if (value < 1.0) {
duration = (hidingDuration * value).roundToInt()
easing = statefulEasing.coerceIn(0.0, value).reverse()
}
else {
delay = hidingDelay
duration = hidingDuration
easing = statefulEasing.reverse()
}
}.runWhenExpiredOrCancelled(visibility)
}
|
apache-2.0
|
fa951186958e2ad6e08db139de7ffa49
| 33.826087 | 120 | 0.702871 | 4.171875 | false | false | false | false |
GunoH/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/handlers/MarkdownTableReformatAfterActionHook.kt
|
2
|
2728
|
// 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.intellij.plugins.markdown.editor.tables.handlers
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import org.intellij.plugins.markdown.editor.tables.TableFormattingUtils.reformatColumnOnChange
import org.intellij.plugins.markdown.editor.tables.TableUtils
import org.intellij.plugins.markdown.settings.MarkdownSettings
internal class MarkdownTableReformatAfterActionHook(private val baseHandler: EditorActionHandler?): EditorWriteActionHandler() {
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
return baseHandler?.isEnabled(editor, caret, dataContext) == true
}
override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) {
baseHandler?.execute(editor, caret, dataContext)
actuallyExecute(editor, caret, dataContext)
}
private fun actuallyExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
val project = editor.project ?: return
if (!Registry.`is`("markdown.tables.editing.support.enable") || !MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) {
return
}
val document = editor.document
val caretOffset = caret?.offset ?: return
if (!TableUtils.isProbablyInsideTableCell(document, caretOffset) || editor.caretModel.caretCount != 1) {
return
}
val documentManager = PsiDocumentManager.getInstance(project)
val file = documentManager.getPsiFile(document) ?: return
if (!TableUtils.isFormattingEnabledForTables(file)) {
return
}
PsiDocumentManager.getInstance(project).commitDocument(document)
val cell = TableUtils.findCell(file, caretOffset)
val table = cell?.parentTable
val columnIndex = cell?.columnIndex
if (cell == null || table == null || columnIndex == null) {
return
}
val text = document.charsSequence
if (cell.textRange.let { text.substring(it.startOffset, it.endOffset) }.isBlank()) {
return
}
executeCommand(table.project) {
table.reformatColumnOnChange(
document,
editor.caretModel.allCarets,
columnIndex,
trimToMaxContent = false,
preventExpand = false
)
}
}
}
|
apache-2.0
|
f32c23f94ac6f233f3c8d4c8c93b7cb3
| 43 | 158 | 0.756232 | 4.647359 | false | false | false | false |
Helabs/generator-he-kotlin-mvp
|
app/templates/app_arch_comp/src/mock/kotlin/data/remote/FakeAppApi.kt
|
1
|
6493
|
package <%= appPackage %>.data.remote
import <%= appPackage %>.data.model.*
import <%= appPackage %>.data.model.request.*
import <%= appPackage %>.data.model.response.*
import <%= appPackage %>.extensions.asGB
import <%= appPackage %>.extensions.asMB
import <%= appPackage %>.extensions.dateOf
import io.reactivex.Observable
import retrofit2.Call
import java.util.*
import java.util.concurrent.TimeUnit
class FakeAppApi : AppApi {
override fun requestTokenSync(request: TokenRequest): Call<TokenRequestResponse>? {
return null
}
override fun requestToken(request: TokenRequest): Observable<TokenRequestResponse> =
TokenRequestResponse("", emptyList(), "", TokenResponseReturn(token = "123")).run {
Observable.just(this)
}
override fun requestSMSCode(appToken: String, request: SMSCodeRequest): Observable<SMSCodeResponse> =
SMSCodeResponse(`return` = SMSCodeResponseReturn("hussan", "pass", "1")).run { Observable.just(this) }
override fun authenticateCode(appToken: String, request: AuthenticateRequest): Observable<Any> = Observable.just(Any())
override fun resendSMSCode(appToken: String, request: ResendSMSCodeRequest): Observable<Any> = Observable.just(Any())
override fun getOrderDetail(userToken: String, orderId: String, idLine: String): Observable<GetOrderDetailResponse>
= GetOrderDetailResponse("", emptyList(), "", OrderDetail("A3259557", "nextel", "Portabilidade", "Vivo Controle Giga 2,5GB",
listOf(OrderDetailStep("Análise de crédito", true, dateOf(14, 2, 2016)),
OrderDetailStep("Ativação de serviço", false, dateOf(14, 2, 2016), true),
OrderDetailStep("Preparando para envio", false, null),
OrderDetailStep("Enviado à transportadora", false, null),
OrderDetailStep("Entregue ao cliente", false, null))))
.run { Observable.just(this) }
override fun getConsumerData(telephone: String?): Observable<Consumer> {
// For test with 2 types of users
val consumer: Consumer
if (telephone?.equals("45988137777") ?: false)
consumer = Consumer(null, "45988137777", null, false)
else
consumer = Consumer("Houssan A. Hijazi", "4588130770", registered = true, plan = Plan(cycle = Date(), dueDate = Date(), name = "Claro Controle 1.5GB", operator = "Claro", callSeconds = 1000, mobileBytes = 1073741824L))
return consumer.run { Observable.just(this) }
}
override fun purchase(planId: String?): Observable<Any> = Observable.just(Any())
.delay(2, TimeUnit.SECONDS)
override fun getPlanOffers(): Observable<List<PlanOffer>> {
return listOf(
PlanOffer("12", "Claro Controle 500MB", 500L.asMB(), 9.90, "http://www.google.com",
arrayListOf("R$ 5,00 de saldo livre", "Ligações à vontade para Claro, Claro Fone e NET Fone"), "PRÉ", true),
PlanOffer("12", "Claro Controle 1GB", 1L.asGB(), 19.90, "http://www.google.com",
arrayListOf("R$ 10,00 de saldo livre", "Ligações à vontade para Claro, Claro Fone e NET Fone"), "PRÉ", false),
PlanOffer("123", "Claro Controle 1,5GB", 1.5.asGB().toLong(), 49.90, "http://www.google.com",
arrayListOf("R$ 15,00 de saldo livre", "WhatsApp sem descontar da internet", "Ligações à vontade para Claro, Claro Fone e NET Fone"), "PRÉ", false),
PlanOffer("1234", "Claro Controle 2GB", 2L.asGB(), 59.90, "http://www.google.com",
arrayListOf("R$ 25,00 de saldo livre", "WhatsApp sem descontar da internet", "SMS ilimitado", "Ligações à vontade para Claro, Claro Fone e NET Fone"), "PRÉ", false),
PlanOffer("12345", "Claro Controle 5GB", 5L.asGB(), 69.90, "http://www.google.com",
arrayListOf("R$ 50,00 de saldo livre", "WhatsApp sem descontar da internet", "SMS ilimitado", "Ligações à vontade para Claro, Claro Fone e NET Fone"), "PRÉ", false)
).run { Observable.just(this) }
}
override fun getAddress(cep: String): Observable<Address> = Address("Av. Brasil", "Centro", "São Paulo", "SP")
.run { Observable.just(this) }
override fun saverOrder(orderRequest: OrderRequest): Observable<Any> = Observable.just(Any())
.delay(2, TimeUnit.SECONDS)
override fun getOrders(userToken: String, idLine: String): Observable<GetOrdersResponse> {
return GetOrdersResponse("", emptyList(), "", GetOrdersResponseReturn(listOf(
OrderDetail("A3259557", "vivo", "Portabilidade", "Vivo Controle Giga 2,5GB",
listOf(OrderDetailStep("Análise de crédito", true, dateOf(14, 2, 2016)),
OrderDetailStep("Ativação de serviço", false, dateOf(14, 2, 2016), true),
OrderDetailStep("Preparando para envio", false, null),
OrderDetailStep("Enviado à transportadora", false, null),
OrderDetailStep("Entregue ao cliente", false, null))),
OrderDetail("A3259558", "vivo", "Portabilidade", "Vivo Controle Giga 1,5GB",
listOf(OrderDetailStep("Análise de crédito", true, dateOf(14, 2, 2016)),
OrderDetailStep("Ativação de serviço", false, null),
OrderDetailStep("Preparando para envio", false, null),
OrderDetailStep("Enviado à transportadora", false, null),
OrderDetailStep("Entregue ao cliente", false, null))))
))
.run { Observable.just(this) }
}
override fun sendFCMToken(appToken: String, request: FCMTokenRequest): Observable<Any> {
return Observable.just(Any())
}
override fun getOperatorContacts(userToken: String, idLine: String): Observable<GetContactsResponse> {
return GetContactsResponse("", emptyList(), "", GetContactsResponseReturn(
listOf(OperatorContact("CLARO", "[email protected]", "9999-12345"))
)).run { Observable.just(this) }
}
override fun syncAllStatisticsHistory(userToken: String, request: StatisticsRequest): Observable<SyncAllStatisticsHistoryResponse> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
|
mit
|
5f46ff014a7cef46a091ded4fd9f19ed
| 58.759259 | 230 | 0.633406 | 3.894991 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/parameters/FirLightTypeParameter.kt
|
2
|
8313
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.asJava.elements
import com.intellij.lang.Language
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.impl.PsiClassImplUtil
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.search.SearchScope
import org.jetbrains.kotlin.asJava.classes.KotlinSuperTypeListBuilder
import org.jetbrains.kotlin.asJava.classes.cannotModify
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.elements.KtLightAbstractAnnotation
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.asJava.basicIsEquivalentTo
import org.jetbrains.kotlin.idea.asJava.invalidAccess
import org.jetbrains.kotlin.idea.asJava.mapSupertype
import org.jetbrains.kotlin.idea.frontend.api.isValid
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtTypeParameterSymbol
import org.jetbrains.kotlin.idea.frontend.api.types.KtClassType
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.psi.psiUtil.startOffset
internal class FirLightTypeParameter(
private val parent: FirLightTypeParameterListForSymbol,
private val index: Int,
private val typeParameterSymbol: KtTypeParameterSymbol
) : LightElement(parent.manager, KotlinLanguage.INSTANCE), PsiTypeParameter,
KtLightDeclaration<KtTypeParameter, PsiTypeParameter> {
override val clsDelegate: PsiTypeParameter get() = invalidAccess()
override val givenAnnotations: List<KtLightAbstractAnnotation>? get() = invalidAccess()
override val kotlinOrigin: KtTypeParameter? = typeParameterSymbol.psi as? KtTypeParameter
override fun copy(): PsiElement =
FirLightTypeParameter(parent, index, typeParameterSymbol)
override fun accept(visitor: PsiElementVisitor) {
if (visitor is JavaElementVisitor) {
visitor.visitTypeParameter(this)
} else {
super<LightElement>.accept(visitor)
}
}
private val _extendsList: PsiReferenceList by lazyPub {
val listBuilder = KotlinSuperTypeListBuilder(
kotlinOrigin = null,
manager = manager,
language = language,
role = PsiReferenceList.Role.EXTENDS_LIST
)
typeParameterSymbol.upperBounds
.filterIsInstance<KtClassType>()
.filter { it.classId != StandardClassIds.Any }
.mapNotNull {
it.mapSupertype(
psiContext = this,
kotlinCollectionAsIs = true,
annotations = emptyList()
)
}
.forEach { listBuilder.addReference(it) }
listBuilder
}
override fun getExtendsList(): PsiReferenceList = _extendsList
override fun getExtendsListTypes(): Array<PsiClassType> =
PsiClassImplUtil.getExtendsListTypes(this)
//PsiClass simple implementation
override fun getImplementsList(): PsiReferenceList? = null
override fun getImplementsListTypes(): Array<PsiClassType> = PsiClassType.EMPTY_ARRAY
override fun getSuperClass(): PsiClass? = null
override fun getInterfaces(): Array<PsiClass> = PsiClass.EMPTY_ARRAY
override fun getSupers(): Array<PsiClass> = PsiClass.EMPTY_ARRAY
override fun getSuperTypes(): Array<PsiClassType> = PsiClassType.EMPTY_ARRAY
override fun getConstructors(): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun getInitializers(): Array<PsiClassInitializer> = PsiClassInitializer.EMPTY_ARRAY
override fun getAllFields(): Array<PsiField> = PsiField.EMPTY_ARRAY
override fun getAllMethods(): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun getAllInnerClasses(): Array<PsiClass> = PsiClass.EMPTY_ARRAY
override fun findFieldByName(name: String?, checkBases: Boolean): PsiField? = null
override fun findMethodBySignature(patternMethod: PsiMethod?, checkBases: Boolean): PsiMethod? = null
override fun findMethodsBySignature(patternMethod: PsiMethod?, checkBases: Boolean): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun findMethodsAndTheirSubstitutorsByName(name: String?, checkBases: Boolean)
: MutableList<Pair<PsiMethod, PsiSubstitutor>> = mutableListOf()
override fun getAllMethodsAndTheirSubstitutors()
: MutableList<Pair<PsiMethod, PsiSubstitutor>> = mutableListOf()
override fun findInnerClassByName(name: String?, checkBases: Boolean): PsiClass? = null
override fun getLBrace(): PsiElement? = null
override fun getRBrace(): PsiElement? = null
override fun getScope(): PsiElement = parent
override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean = false
override fun isInheritorDeep(baseClass: PsiClass?, classToByPass: PsiClass?): Boolean = false
override fun getVisibleSignatures(): MutableCollection<HierarchicalMethodSignature> = mutableListOf()
override fun setName(name: String): PsiElement = cannotModify()
override fun getNameIdentifier(): PsiIdentifier? = null
override fun getModifierList(): PsiModifierList? = null
override fun hasModifierProperty(name: String): Boolean = false
override fun getOwner(): PsiTypeParameterListOwner? = parent.owner
override fun getParent(): PsiElement = parent
override fun getAnnotations(): Array<PsiAnnotation> = PsiAnnotation.EMPTY_ARRAY
override fun getContainingClass(): PsiClass? = null
override fun getDocComment(): PsiDocComment? = null
override fun isDeprecated(): Boolean = false
override fun getTypeParameters(): Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY
override fun hasTypeParameters(): Boolean = false
override fun getTypeParameterList(): PsiTypeParameterList? = null
override fun getQualifiedName(): String? = null
override fun getMethods(): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun findMethodsByName(name: String?, checkBases: Boolean): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun getFields(): Array<PsiField> = PsiField.EMPTY_ARRAY
override fun getInnerClasses(): Array<PsiClass> = PsiClass.EMPTY_ARRAY
override fun isInterface(): Boolean = false
override fun isAnnotationType(): Boolean = false
override fun isEnum(): Boolean = false
override fun findAnnotation(qualifiedName: String): PsiAnnotation? = null
override fun addAnnotation(qualifiedName: String): PsiAnnotation = cannotModify()
//End of PsiClass simple implementation
override fun getText(): String = kotlinOrigin?.text ?: ""
override fun getName(): String? = typeParameterSymbol.name.asString()
override fun getIndex(): Int = index
override fun getApplicableAnnotations(): Array<PsiAnnotation> = PsiAnnotation.EMPTY_ARRAY //TODO
override fun toString(): String = "FirLightTypeParameter:$name"
override fun getNavigationElement(): PsiElement =
kotlinOrigin ?: parent.navigationElement
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
override fun getUseScope(): SearchScope =
kotlinOrigin?.useScope ?: parent.useScope
override fun equals(other: Any?): Boolean =
this === other ||
(other is FirLightTypeParameter && index == other.index && typeParameterSymbol == other.typeParameterSymbol)
override fun hashCode(): Int = typeParameterSymbol.hashCode() + index
override fun isEquivalentTo(another: PsiElement): Boolean =
basicIsEquivalentTo(this, another)
override fun getTextRange(): TextRange? = kotlinOrigin?.textRange
override fun getContainingFile(): PsiFile = parent.containingFile
override fun getTextOffset(): Int = kotlinOrigin?.startOffset ?: super.getTextOffset()
override fun getStartOffsetInParent(): Int = kotlinOrigin?.startOffsetInParent ?: super.getStartOffsetInParent()
override fun isValid(): Boolean = super.isValid() && typeParameterSymbol.isValid()
}
|
apache-2.0
|
018418b5d80a70624263d240edc30c7d
| 48.482143 | 129 | 0.747023 | 5.163354 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt
|
2
|
8580
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.analysis.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@Suppress("DEPRECATION")
class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) {
override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL
override fun additionalFixes(element: KtTypeArgumentList): List<LocalQuickFix>? {
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return null
if (!RemoveExplicitTypeIntention.isApplicableTo(declaration)) return null
return listOf(RemoveExplicitTypeFix(declaration.nameAsSafeName.asString()))
}
private class RemoveExplicitTypeFix(private val declarationName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.explicit.type.specification.from.0", declarationName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtTypeArgumentList ?: return
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return
RemoveExplicitTypeIntention.removeExplicitType(declaration)
}
}
}
class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>(
KtTypeArgumentList::class.java,
KotlinBundle.lazyMessage("remove.explicit.type.arguments")
) {
companion object {
fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean {
val callExpression = element.parent as? KtCallExpression ?: return false
val typeArguments = callExpression.typeArguments
if (typeArguments.isEmpty() || typeArguments.any { it.typeReference?.annotationEntries?.isNotEmpty() == true }) return false
val resolutionFacade = callExpression.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_WITH_CFA)
val originalCall = callExpression.getResolvedCall(bindingContext) ?: return false
val (contextExpression, expectedType) = findContextToAnalyze(callExpression, bindingContext)
val resolutionScope = contextExpression.getResolutionScope(bindingContext, resolutionFacade)
val key = Key<Unit>("RemoveExplicitTypeArgumentsIntention")
callExpression.putCopyableUserData(key, Unit)
val expressionToAnalyze = contextExpression.copied()
callExpression.putCopyableUserData(key, null)
val newCallExpression = expressionToAnalyze.findDescendantOfType<KtCallExpression> { it.getCopyableUserData(key) != null }!!
newCallExpression.typeArgumentList!!.delete()
val newBindingContext = expressionToAnalyze.analyzeInContext(
resolutionScope,
contextExpression,
trace = DelegatingBindingTrace(bindingContext, "Temporary trace"),
dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression),
expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE,
isStatement = contextExpression.isUsedAsStatement(bindingContext)
)
val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false
val args = originalCall.typeArguments
val newArgs = newCall.typeArguments
fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean {
return if (approximateFlexible) {
KotlinTypeChecker.DEFAULT.equalTypes(type1, type2)
} else {
type1 == type2
}
}
return args.size == newArgs.size && args.values.zip(newArgs.values).all { (argType, newArgType) ->
equalTypes(argType, newArgType)
}
}
private fun findContextToAnalyze(expression: KtExpression, bindingContext: BindingContext): Pair<KtExpression, KotlinType?> {
for (element in expression.parentsWithSelf) {
if (element !is KtExpression) continue
if (element.getQualifiedExpressionForSelector() != null) continue
if (element is KtFunctionLiteral) continue
if (!element.isUsedAsExpression(bindingContext)) return element to null
when (val parent = element.parent) {
is KtNamedFunction -> {
val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType())
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
else
null
return element to expectedType
}
is KtVariableDeclaration -> {
val expectedType = if (element == parent.initializer && parent.typeReference != null)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtParameter -> {
val expectedType = if (element == parent.defaultValue)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtPropertyAccessor -> {
val property = parent.parent as KtProperty
val expectedType = when {
element != parent.bodyExpression || parent.hasBlockBody() -> null
parent.isSetter -> parent.builtIns.unitType
property.typeReference == null -> null
else -> (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
}
return element to expectedType
}
}
}
return expression to null
}
}
override fun isApplicableTo(element: KtTypeArgumentList): Boolean = isApplicableTo(element, approximateFlexible = false)
override fun applyTo(element: KtTypeArgumentList, editor: Editor?) = element.delete()
}
|
apache-2.0
|
b603501fc940695b194d2a492cec8c6a
| 51.323171 | 158 | 0.685082 | 6.146132 | false | false | false | false |
smmribeiro/intellij-community
|
platform/configuration-store-impl/src/SaveResult.kt
|
5
|
1372
|
// 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.configurationStore
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.util.SmartList
import com.intellij.util.throwIfNotEmpty
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class SaveResult {
companion object {
val EMPTY = SaveResult()
}
private val errors: MutableList<Throwable> = SmartList()
val readonlyFiles: MutableList<SaveSessionAndFile> = SmartList()
@Suppress("MemberVisibilityCanBePrivate")
var isChanged = false
@Synchronized
fun addError(error: Throwable) {
errors.add(error)
}
@Synchronized
fun addReadOnlyFile(info: SaveSessionAndFile) {
readonlyFiles.add(info)
}
fun addErrors(list: List<Throwable>) {
if (list.isEmpty()) {
return
}
synchronized(this) {
errors.addAll(list)
}
}
@Synchronized
fun appendTo(saveResult: SaveResult) {
if (this === EMPTY) {
return
}
synchronized(saveResult) {
saveResult.errors.addAll(errors)
saveResult.readonlyFiles.addAll(readonlyFiles)
if (isChanged) {
saveResult.isChanged = isChanged
}
}
}
@Synchronized
fun throwIfErrored() {
throwIfNotEmpty(errors)
}
}
|
apache-2.0
|
0cb09a2e55cbaf2c50f772facd50554c
| 21.508197 | 140 | 0.707726 | 4.369427 | false | false | false | false |
WillowChat/Kale
|
src/main/kotlin/chat/willow/kale/irc/message/extension/batch/BatchMessage.kt
|
2
|
3092
|
package chat.willow.kale.irc.message.extension.batch
import chat.willow.kale.core.ICommand
import chat.willow.kale.core.message.*
import chat.willow.kale.irc.CharacterCodes
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.PrefixParser
import chat.willow.kale.irc.prefix.PrefixSerialiser
object BatchMessage : ICommand {
override val command = "BATCH"
object Start : ISubcommand {
override val subcommand = CharacterCodes.PLUS.toString()
data class Message(val source: Prefix, val reference: String, val type: String, val parameters: List<String> = listOf()) {
// BATCH +something
// todo: descriptor
object Parser : PrefixSubcommandParser<Message>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val source = PrefixParser.parse(components.prefix ?: "") ?: return null
val reference = components.parameters[0]
val type = components.parameters[1]
val parameters = components.parameters.drop(2)
return Message(source, reference, type, parameters)
}
}
object Serialiser : PrefixSubcommandSerialiser<Message>(command, subcommand) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val parameters = listOf(message.reference, message.type) + message.parameters
val prefix = PrefixSerialiser.serialise(message.source)
return IrcMessageComponents(prefix = prefix, parameters = parameters)
}
}
}
}
object End : ISubcommand {
override val subcommand = CharacterCodes.MINUS.toString()
data class Message(val source: Prefix, val reference: String) {
// BATCH -something
// todo: descriptor
object Parser : PrefixSubcommandParser<Message>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.isEmpty()) {
return null
}
val source = PrefixParser.parse(components.prefix ?: "") ?: return null
val reference = components.parameters[0]
return Message(source, reference)
}
}
object Serialiser : PrefixSubcommandSerialiser<Message>(command, subcommand) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val prefix = PrefixSerialiser.serialise(message.source)
val parameters = listOf(message.reference)
return IrcMessageComponents(prefix = prefix, parameters = parameters)
}
}
}
}
}
|
isc
|
fe82ab38b2f0f0b5a6444908db9ace93
| 31.557895 | 130 | 0.594437 | 5.621818 | false | false | false | false |
kageiit/buck
|
tools/datascience/src/com/facebook/buck/datascience/traces/TraceAnalyzer.kt
|
5
|
12886
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.datascience.traces
import com.facebook.buck.util.ObjectMappers
import com.facebook.buck.util.concurrent.MostExecutors
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListeningExecutorService
import com.google.common.util.concurrent.MoreExecutors
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStream
import java.net.URL
import java.util.PriorityQueue
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ExecutionException
import java.util.zip.GZIPInputStream
/**
* See the Chrome Trace Event Format doc.
*/
enum class EventPhase {
B,
E,
I,
C,
M,
}
/**
* A single trace event.
*/
data class TraceEvent(
val name: String,
val cat: List<String>,
val ph: EventPhase,
val ts: Long,
val tts: Long,
val pid: Int,
val tid: Int,
val args: ObjectNode
)
/**
* Current state of the trace.
*/
data class TraceState(
/**
* Current stack of active events for each thread.
* Events in each thread will appear in the same order that they began.
*/
val threadStacks: Map<Int, List<TraceEvent>>
)
/**
* Business logic class that will analyze traces.
* A separate instance will be created for each trace.
* A final instance will be created to combine the results.
*/
interface TraceAnalysisVisitor<SummaryT> {
/**
* Initialize this visitor before using it to process a trace.
* Args are from the command line.
*/
fun init(args: List<String>) {}
/**
* Process a begin ("B") event.
*
* @param event The event.
* @param state The state after incorporating the event.
*/
fun eventBegin(event: TraceEvent, state: TraceState) {}
/**
* Process an end ("E") event.
*
* @param event The event.
* @param state The state before removing the corresponding begin event.
*/
fun eventEnd(event: TraceEvent, state: TraceState) {}
fun eventMisc(event: TraceEvent, state: TraceState) {}
/**
* Finish analyzing a trace and return data to be processed by the final analysis.
*/
fun traceComplete(): SummaryT
/**
* Combine results from each trace and print analysis to the console.
* This will be called on a fresh instance.
*/
fun finishAnalysis(args: List<String>, intermediates: List<SummaryT>)
}
/**
* Main entry point. To use this tool to analyze traces:
*
* - Get a bunch of traces and put their filenames or urls in a file.
* - Create a subclass of TraceAnalysisVisitor and compile it along with this tool.
* - Run the tool with the visitor class name as the first argument (minus package)
* and the path to the file as the second argument.
*/
fun main(args: Array<String>) {
if (args.size != 2) {
System.err.println("usage: TraceAnalyzer {VisitorClassSimpleName} {TraceListFile}")
System.exit(2)
}
val visitorName = args[0]
val infile = args[1]
val logicClass = Class.forName("com.facebook.buck.datascience.traces." + visitorName)
val processThreadCount = Runtime.getRuntime().availableProcessors()
val fetchThreadCount = processThreadCount / 2
val fetchThreadPool = MoreExecutors.listeningDecorator(
MostExecutors.newMultiThreadExecutor("fetch", fetchThreadCount))
val processThreadPool = MoreExecutors.listeningDecorator(
MostExecutors.newMultiThreadExecutor("process", processThreadCount))
val eventBufferDepth = 1 shl 16
processTraces(
args.asList().subList(2, args.size),
File(infile),
logicClass as Class<TraceAnalysisVisitor<Any>>,
eventBufferDepth,
fetchThreadPool,
processThreadPool)
}
private data class QueuedTrace(
val name: String,
val stream: () -> InputStream
)
private fun <SummaryT : Any> processTraces(
args: List<String>,
traceListFile: File,
visitorClass: Class<TraceAnalysisVisitor<SummaryT>>,
eventBufferDepth: Int,
fetchThreadPool: ListeningExecutorService,
processThreadPool: ListeningExecutorService
) {
val blobQueue = ArrayBlockingQueue<QueuedTrace>(1)
val processFutures = traceListFile.readLines().map {
val fetchFuture = fetchThreadPool.submit {
System.err.println(it)
val lazyStream = openTrace(it)
blobQueue.put(QueuedTrace(it, lazyStream))
}
val processFuture = Futures.transform(
fetchFuture,
com.google.common.base.Function<Any, SummaryT> {
val (name, lazyStream) = blobQueue.poll()
val visitor = visitorClass.newInstance()
val summary = processOneTrace(args, name, lazyStream, visitor, eventBufferDepth)
summary
},
processThreadPool)
processFuture.addListener(Runnable {
try {
processFuture.get()
} catch (e: ExecutionException) {
// The ExecutionException isn't interesting. Log the cause.
e.cause!!.printStackTrace()
}
}, MoreExecutors.directExecutor())
processFuture
}
try {
val summaries = Futures.successfulAsList(processFutures).get().filterNotNull()
val finisher = visitorClass.newInstance()
finisher.finishAnalysis(args, summaries)
} finally {
fetchThreadPool.shutdownNow()
processThreadPool.shutdownNow()
}
}
/**
* Open a path or URL, slurp the contents into memory, and return a lazy InputStream
* that will gunzip the contents if necessary (inferred from the path).
* The return value is lazy to ensure we don't create a GZIPInputStream
* (which allocates native resources) until we're in a position to close it.
*/
private fun openTrace(pathOrUrl: String): () -> InputStream {
val bytes: ByteArray
val path: String
if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://")) {
val url = URL(pathOrUrl)
path = url.path
val connection = url.openConnection()
bytes = connection.getInputStream().use { it.readBytes() }
} else {
path = pathOrUrl
bytes = File(path).inputStream().use { it.readBytes() }
}
if (path.endsWith(".gz")) {
return { BufferedInputStream(GZIPInputStream(ByteArrayInputStream(bytes))) }
} else {
return { ByteArrayInputStream(bytes) }
}
}
/**
* Wrapper for TraceEvent that ensures stable sorting.
*/
private data class BufferedTraceEvent(
val ts: Long,
val order: Long,
val event: TraceEvent
)
private fun <SummaryT> processOneTrace(
args: List<String>,
name: String,
lazyStream: () -> InputStream,
visitor: TraceAnalysisVisitor<SummaryT>,
eventBufferDepth: Int
): SummaryT {
try {
lazyStream().use { stream ->
return processOneTraceStream(args, stream, visitor, eventBufferDepth)
}
} catch (e: Exception) {
throw RuntimeException("Exception while processing " + name, e)
}
}
private fun <SummaryT> processOneTraceStream(
args: List<String>,
stream: InputStream,
visitor: TraceAnalysisVisitor<SummaryT>,
eventBufferDepth: Int
): SummaryT {
visitor.init(args)
val parser = ObjectMappers.createParser(stream)
if (parser.nextToken() != JsonToken.START_ARRAY) {
throw IllegalStateException("Invalid token: " + parser.currentToken)
}
// Timestamps are not monotonic in trace files.
// Part of this is because events from different threads can be reordered,
// But I've also seen re-orderings within a thread.
// In theory, we could load the entire trace into memory and sort by timestamp.
// Instead, let's prematurely optimize and use a priority queue.
val pq = PriorityQueue<BufferedTraceEvent>(
eventBufferDepth + 4, // +4 so I don't need to think about math.
compareBy({it.ts}, {it.order}))
var lastTimestamp = 0L
var order = 1L
val threadStacks = mutableMapOf<Int, MutableList<TraceEvent>>()
while (true) {
when (parser.nextToken()) {
null -> {
// At EOF. Nothing left to do.
}
JsonToken.START_OBJECT -> {
// Got an object, enqueue it.
val node = ObjectMappers.READER.readTree<JsonNode>(parser)
val event = parseTraceEvent(node)
pq.add(BufferedTraceEvent(event.ts, order++, event))
}
JsonToken.END_ARRAY -> {
// End of our array of events.
val nextNextToken = parser.nextToken()
if (nextNextToken != null) {
throw IllegalStateException("Got token after END_ARRAY: " + nextNextToken)
}
}
else -> {
throw IllegalStateException("Invalid token: " + parser.currentToken)
}
}
if (pq.isEmpty() && parser.isClosed) {
// No more events in queue or parser.
break
} else if (parser.isClosed || pq.size > eventBufferDepth) {
// Parser is closed (so we need to train the queue),
// OR the queue is "full" so we need to take something out.
val nextEvent = pq.poll()
if (nextEvent.ts < lastTimestamp) {
throw IllegalStateException(
"Event went back in time. Try a bigger queue.\n" + nextEvent)
}
lastTimestamp = nextEvent.ts
processOneEvent(visitor, nextEvent.event, threadStacks)
}
}
return visitor.traceComplete()
}
private fun processOneEvent(
visitor: TraceAnalysisVisitor<*>,
event: TraceEvent,
threadStacks: MutableMap<Int, MutableList<TraceEvent>>
) {
when (event.ph) {
EventPhase.B -> {
threadStacks
.getOrPut(event.tid, { mutableListOf() })
.add(event)
visitor.eventBegin(event, TraceState(threadStacks))
}
EventPhase.E -> {
val stack = threadStacks[event.tid]
?: throw IllegalStateException("Couldn't find stack for thread " + event.tid)
if (stack.isEmpty()) {
throw IllegalStateException("Empty stack for thread " + event.tid)
}
prepareStackForEndEvent(stack, event)
val topOfStack = stack.last()
if (topOfStack.name != event.name) {
throw IllegalStateException(
"Event name mismatch on thread %d at time %d: %s != %s".format(
event.tid, event.ts, topOfStack.name, event.name))
}
visitor.eventEnd(event, TraceState(threadStacks))
stack.removeAt(stack.lastIndex)
}
else -> {
visitor.eventMisc(event, TraceState(threadStacks))
}
}
}
private fun prepareStackForEndEvent(stack: MutableList<TraceEvent>, event: TraceEvent) {
if (event.name == "javac_jar") {
// Events inside javac_jar aren't always closed on compile errors.
// Just silently remove them from the stack.
val idx = stack.indexOfLast { it.name == "javac_jar" }
if (idx > 0) {
// Found start event. Remove everything after it.
while (idx < stack.lastIndex) {
stack.removeAt(stack.lastIndex)
}
}
}
}
private fun parseTraceEvent(node: JsonNode): TraceEvent {
// TODO: Switch to ig-json-parser or jackson-module-kotlin or something more type-safe.
return TraceEvent(
node["name"].textValue()!!,
(node["cat"].textValue() ?: "").split(","),
EventPhase.valueOf(node["ph"].textValue()!!),
node["ts"].longValue(),
node["tts"].longValue(),
node["pid"].intValue(),
node["tid"].intValue(),
node["args"] as ObjectNode
)
}
|
apache-2.0
|
0f8fe4835754b6cba34e75f1f4ebd802
| 32.644909 | 100 | 0.630064 | 4.444981 | false | false | false | false |
smmribeiro/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/tasks/trace.kt
|
1
|
2051
|
// 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.intellij.build.tasks
import io.opentelemetry.api.GlobalOpenTelemetry
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.SpanBuilder
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.context.Context
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes
import java.util.concurrent.Callable
import java.util.concurrent.ForkJoinTask
import java.util.function.Supplier
internal val tracer: Tracer by lazy(LazyThreadSafetyMode.NONE) { GlobalOpenTelemetry.getTracer("build-script") }
fun <T> createTask(spanBuilder: SpanBuilder, task: Supplier<T>): ForkJoinTask<T> {
val context = Context.current()
return ForkJoinTask.adapt(Callable {
val thread = Thread.currentThread()
val span = spanBuilder
.setParent(context)
.setAttribute(SemanticAttributes.THREAD_NAME, thread.name)
.setAttribute(SemanticAttributes.THREAD_ID, thread.id)
.startSpan()
span.makeCurrent().use {
span.use {
task.get()
}
}
})
}
internal inline fun task(spanBuilder: SpanBuilder, crossinline operation: () -> Unit): ForkJoinTask<*> {
val context = Context.current()
return ForkJoinTask.adapt(Runnable {
val thread = Thread.currentThread()
spanBuilder
.setParent(context)
.setAttribute(SemanticAttributes.THREAD_NAME, thread.name)
.setAttribute(SemanticAttributes.THREAD_ID, thread.id)
.startSpan()
.useWithScope {
operation()
}
})
}
inline fun <T> Span.useWithScope(operation: (Span) -> T): T {
return makeCurrent().use {
use {
operation(it)
}
}
}
inline fun <T> Span.use(operation: (Span) -> T): T {
try {
return operation(this)
}
catch (e: Throwable) {
recordException(e)
setStatus(StatusCode.ERROR)
throw e
}
finally {
end()
}
}
|
apache-2.0
|
6dacd73c791296178d9668fbacabf52f
| 28.73913 | 158 | 0.715261 | 4.005859 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer
|
app/src/main/java/sk/styk/martin/apkanalyzer/ui/applist/main/MainAppListViewModel.kt
|
1
|
6689
|
package sk.styk.martin.apkanalyzer.ui.applist.main
import android.app.Activity
import android.net.Uri
import android.view.MenuItem
import android.widget.SearchView
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.*
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.perf.metrics.AddTrace
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import sk.styk.martin.apkanalyzer.R
import sk.styk.martin.apkanalyzer.manager.appanalysis.InstalledAppsManager
import sk.styk.martin.apkanalyzer.manager.navigationdrawer.NavigationDrawerModel
import sk.styk.martin.apkanalyzer.model.detail.AppSource
import sk.styk.martin.apkanalyzer.model.list.AppListData
import sk.styk.martin.apkanalyzer.ui.applist.*
import sk.styk.martin.apkanalyzer.util.TextInfo
import sk.styk.martin.apkanalyzer.util.components.SnackBarComponent
import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider
import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent
import javax.inject.Inject
@HiltViewModel
class MainAppListViewModel @Inject constructor(
private val installedAppsManager: InstalledAppsManager,
private val navigationDrawerModel: NavigationDrawerModel,
private val dispatcherProvider: DispatcherProvider,
adapter: AppListAdapter
) : BaseAppListViewModel(adapter), DefaultLifecycleObserver, SearchView.OnQueryTextListener, SearchView.OnCloseListener, Toolbar.OnMenuItemClickListener {
override var appListData = listOf<AppListData>()
set(value) {
field = value
adapter.data = value
viewStateLiveData.value = when {
allApps.isEmpty() -> LOADING_STATE
value.isEmpty() -> EMPTY_STATE
else -> DATA_STATE
}
}
private var allApps: List<AppListData> = emptyList()
private val openFilePickerEvent = SingleLiveEvent<Unit>()
val openFilePicker: LiveData<Unit> = openFilePickerEvent
private val showSnackEvent = SingleLiveEvent<SnackBarComponent>()
val showSnack: LiveData<SnackBarComponent> = showSnackEvent
private val indefiniteSnackbarEvent = MutableLiveData<SnackBarComponent?>()
val indeterminateSnackbar: LiveData<SnackBarComponent?> = indefiniteSnackbarEvent
private var setQueryTextLiveData = SingleLiveEvent<String>()
var setQueryText: LiveData<String> = setQueryTextLiveData
private var queryTextInternal: String = ""
private val filteredSourceLiveData = MutableLiveData<AppSource?>()
val filteredSource: LiveData<AppSource?> = filteredSourceLiveData
private val openDetailFromFileEvent = SingleLiveEvent<Uri>()
val openDetailFromFile: LiveData<Uri> = openDetailFromFileEvent
val filePickerResult = ActivityResultCallback<ActivityResult> {
if (it?.resultCode == Activity.RESULT_OK) {
it.data?.data?.let { openDetailFromFileEvent.value = it }
}
}
init {
viewModelScope.launch(dispatcherProvider.default()) {
@AddTrace(name = "initialAppListLoad")
fun loadApps() = installedAppsManager.getAll()
allApps = loadApps()
withContext(dispatcherProvider.main()) {
appListData = allApps
}
withContext(dispatcherProvider.io()) {
installedAppsManager.preload(appListData)
}
}
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
setQueryTextLiveData.value = queryTextInternal
}
fun onFilePickerClick() {
openFilePickerEvent.call()
}
override fun onQueryTextChange(newText: String?): Boolean {
queryTextInternal = newText ?: ""
setDataFiltered()
return true
}
override fun onQueryTextSubmit(p0: String?) = true
override fun onClose(): Boolean {
queryTextInternal = ""
setQueryTextLiveData.value = ""
return false
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_analyze_not_installed -> onFilePickerClick()
R.id.menu_show_all_apps -> {
item.isChecked = true
filteredSourceLiveData.value = null
setDataFiltered()
}
R.id.menu_show_google_play_apps -> {
item.isChecked = true
filteredSourceLiveData.value = AppSource.GOOGLE_PLAY
setDataFiltered()
}
R.id.menu_show_amazon_store_apps -> {
item.isChecked = true
filteredSourceLiveData.value = AppSource.AMAZON_STORE
setDataFiltered()
}
R.id.menu_show_system_pre_installed_apps -> {
item.isChecked = true
filteredSourceLiveData.value = AppSource.SYSTEM_PREINSTALED
setDataFiltered()
}
R.id.menu_show_unknown_source_apps -> {
item.isChecked = true
filteredSourceLiveData.value = AppSource.UNKNOWN
setDataFiltered()
}
}
return true
}
fun onNavigationClick() = viewModelScope.launch {
navigationDrawerModel.openDrawer()
}
private fun setDataFiltered() {
val nameQuery = queryTextInternal
val source = filteredSource.value
val hasFilters = nameQuery.isNotBlank() || source != null
appListData = if (!hasFilters) {
allApps
} else allApps.filter { entry ->
fun textSearch(name: String) = nameQuery.isBlank() ||
name.startsWith(nameQuery, ignoreCase = true) ||
name.split(" ".toRegex()).any { it.startsWith(nameQuery, ignoreCase = true) } ||
name.split(".".toRegex()).any { it.startsWith(nameQuery, ignoreCase = true) }
(source == null || entry.source == source) && (textSearch(entry.applicationName) || textSearch(entry.packageName))
}
indefiniteSnackbarEvent.value = if (hasFilters) SnackBarComponent(
message = TextInfo.from(R.string.app_filtering_active),
duration = Snackbar.LENGTH_INDEFINITE,
action = TextInfo.from(R.string.clear),
callback = {
filteredSourceLiveData.value = null
setQueryTextLiveData.value = ""
appListData = allApps
}
) else null
}
}
|
gpl-3.0
|
22317218c65a36c231035d30c7426609
| 37.228571 | 154 | 0.658843 | 4.936531 | false | false | false | false |
morizooo/conference2017-android
|
app/src/main/kotlin/io/builderscon/conference2017/model/repository/TimetableRepository.kt
|
1
|
1676
|
package io.builderscon.conference2017.model.repository
import io.builderscon.client.model.Session
import io.builderscon.conference2017.extension.getFormatDate
import io.builderscon.conference2017.infra.ConferenceDAO
import io.builderscon.conference2017.infra.SessionDAO
import io.builderscon.conference2017.infra.api.ApiConferenceDAO
import io.builderscon.conference2017.infra.api.ApiSessionDAO
import io.builderscon.conference2017.infra.file.FileConferenceDAO
import io.builderscon.conference2017.infra.file.FileSessionDAO
import io.builderscon.conference2017.model.Timetable
class TimetableRepository {
val conferenceRepository: ConferenceDAO = ApiConferenceDAO().let {
if (it.id.isEmpty()) FileConferenceDAO() else ApiConferenceDAO()
}
val sessionRepository: SessionDAO = ApiSessionDAO().let {
if (it.id.isEmpty()) FileSessionDAO() else ApiSessionDAO()
}
fun read(): List<Timetable> {
if (cachedTimetable.isEmpty()) cachedTimetable = loadTimetable()
return cachedTimetable
}
private fun loadTimetable(): List<Timetable> {
val conference = conferenceRepository.findAll()
val sessions = sessionRepository.findAll()
val tracks = conference?.tracks ?: emptyList()
return conference?.schedules?.map { schedule ->
val scheduledSessions: List<Session> = sessions?.filter {
it.startsOn.getFormatDate() == schedule.open.getFormatDate()
} ?: emptyList()
Timetable(schedule, tracks, scheduledSessions)
} ?: emptyList()
}
companion object {
private var cachedTimetable: List<Timetable> = emptyList()
}
}
|
apache-2.0
|
8dfbdd0d6e0a539d9f60090317c352ea
| 35.456522 | 76 | 0.727327 | 4.481283 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/ViewModelExtensions.kt
|
1
|
2234
|
package ch.rmy.android.framework.extensions
import android.app.Application
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import ch.rmy.android.framework.viewmodel.BaseViewModel
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
inline fun <reified V : ViewModel> FragmentActivity.bindViewModel(): ReadOnlyProperty<FragmentActivity, V> =
bindViewModelOf(V::class.java)
inline fun <reified V : ViewModel> Fragment.bindViewModel(noinline getKey: (() -> String)? = null): ReadOnlyProperty<Fragment, V> =
bindViewModelOf(V::class.java, getKey)
fun <V : ViewModel> FragmentActivity.bindViewModelOf(clazz: Class<V>): ReadOnlyProperty<FragmentActivity, V> =
bind(clazz, viewModelProviderFinder)
fun <V : ViewModel> Fragment.bindViewModelOf(clazz: Class<V>, getKey: (() -> String)? = null): ReadOnlyProperty<Fragment, V> =
bind(clazz, viewModelProviderFinder, getKey)
@Suppress("unused")
private val FragmentActivity.viewModelProviderFinder: FragmentActivity.() -> ViewModelProvider
get() = { ViewModelProvider(this) }
@Suppress("unused")
private val Fragment.viewModelProviderFinder: Fragment.() -> ViewModelProvider
get() = { ViewModelProvider(this) }
private fun <T, V : ViewModel> bind(clazz: Class<V>, finder: T.() -> ViewModelProvider, getKey: (() -> String)? = null) =
LazyWithTarget { t: T, _ ->
t.finder().run {
if (getKey != null) {
get(getKey(), clazz)
} else {
get(clazz)
}
}
}
private class LazyWithTarget<in T, out V : Any>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private var value: V? = null
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == null) {
value = initializer(thisRef, property)
}
return value!!
}
}
val AndroidViewModel.context: Context
get() = getApplication<Application>().applicationContext
fun BaseViewModel<Unit, *>.initialize() {
initialize(Unit)
}
|
mit
|
f2efcf05fc1eca792e876538502f17b4
| 35.032258 | 131 | 0.702328 | 4.337864 | false | false | false | false |
myunusov/maxur-mserv
|
maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/embedded/grizzly/StaticHttpHandlerSpec.kt
|
1
|
5340
|
package org.maxur.mserv.frame.embedded.grizzly
import com.nhaarman.mockito_kotlin.verify
import org.assertj.core.api.Assertions.assertThat
import org.glassfish.grizzly.http.Method
import org.glassfish.grizzly.http.util.HttpStatus
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.maxur.mserv.frame.embedded.properties.WebAppProperties
import org.maxur.mserv.frame.relativePath
@RunWith(JUnitPlatform::class)
class StaticHttpHandlerSpec : Spek({
describe("a StaticHttpHandler") {
val webFolder = this::class.java.getResource("/web")
context("Create StaticHttpHandler") {
it("should return new StaticHttpHandler instance with folder from classpath") {
val handler = StaticHttpHandler("web", "classpath:/web/")
assertThat(handler).isNotNull()
}
it("should return new StaticHttpHandler instance with folder from file system") {
val handler = StaticHttpHandler("web", "src/test/resources/web/")
assertThat(handler).isNotNull()
}
}
context("Create StaticHttpHandler on jar and send request") {
val handler = StaticHttpHandler("web", WebAppProperties.SWAGGER_URL)
it("should return status 200 on request folder (root)") {
val (response, request) = RequestUtil.resreq("/")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 200 on request file") {
val (response, request) = RequestUtil.resreq("/index.html")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 404 on request invalid file") {
val (response, request) = RequestUtil.resreq("/error.html")
handler.service(request, response)
verify(response).sendError(404)
}
}
context("Create StaticHttpHandler on classpath and send request") {
val handler = StaticHttpHandler("web", "classpath:/web/")
it("should return status 200 from classpath") {
val (response, request) = RequestUtil.resreq("/")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 404 on request invalid folder") {
val (response, request) = RequestUtil.resreq("/error/")
handler.service(request, response)
verify(response).sendError(404)
}
it("should return status 405 on request by invalid method") {
val (response, request) = RequestUtil.resreq("/", Method.POST)
handler.service(request, response)
verify(response).setStatus(HttpStatus.METHOD_NOT_ALLOWED_405)
}
}
context("Create StaticHttpHandler on file system folder by absolute path and send request") {
val handler = StaticHttpHandler("web", "$webFolder/")
it("should return status 200 on request file") {
val (response, request) = RequestUtil.resreq("/index.html")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
}
context("Create StaticHttpHandler on file system folder and send request") {
val handler = StaticHttpHandler("web", webFolder.relativePath())
it("should return status 200 on request folder (root)") {
val (response, request) = RequestUtil.resreq("/")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 200 on request file") {
val (response, request) = RequestUtil.resreq("/index.html")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 200 and default page on empty request") {
val (response, request) = RequestUtil.resreq("")
handler.service(request, response)
verify(response).setStatus(HttpStatus.OK_200)
}
it("should return status 301 and redirect request without tailed slash") {
val (response, request) = RequestUtil.resreq("folder")
handler.service(request, response)
verify(response).setStatus(HttpStatus.MOVED_PERMANENTLY_301)
}
}
context("Create StaticHttpHandler on invalid file system folder and send request") {
it("should return status 404 on request invalid folder") {
val handler = StaticHttpHandler("web", "classpath:/error/")
val (response, request) = RequestUtil.resreq("/")
handler.service(request, response)
verify(response).sendError(404)
}
}
}
})
|
apache-2.0
|
1e58bd8a983ebe57093f9c80879f1cc7
| 42.414634 | 101 | 0.608052 | 4.899083 | false | false | false | false |
WYKCode/WYK-Android
|
app/src/main/java/college/wyk/app/commons/gallery/CardScaleHelper.kt
|
1
|
4315
|
package college.wyk.app.commons.gallery
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Created by jameson on 8/30/16.
*/
class CardScaleHelper {
private var mRecyclerView: RecyclerView? = null
private var mContext: Context? = null
private var mScale = 0.9f // 两边视图scale
private var mPagePadding = 15 // 卡片的padding, 卡片间的距离等于2倍的mPagePadding
private var mShowLeftCardWidth = 15 // 左边卡片显示大小
private var mCardWidth: Int = 0 // 卡片宽度
private var mOnePageWidth: Int = 0 // 滑动一页的距离
private var mCardGalleryWidth: Int = 0
var currentItemPos: Int = 0
private var mCurrentItemOffset: Int = 0
private val mLinearSnapHelper = CardLinearSnapHelper()
fun attachToRecyclerView(mRecyclerView: RecyclerView) {
this.mRecyclerView = mRecyclerView
mContext = mRecyclerView.context
mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
mLinearSnapHelper.mNoNeedToScroll = mCurrentItemOffset == 0 || mCurrentItemOffset == getDestItemOffset(mRecyclerView.adapter.itemCount - 1)
} else {
mLinearSnapHelper.mNoNeedToScroll = false
}
}
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
// dx>0则表示右滑, dx<0表示左滑, dy<0表示上滑, dy>0表示下滑
mCurrentItemOffset += dx
computeCurrentItemPos()
onScrolledChangedCallback()
}
})
initWidth()
mLinearSnapHelper.attachToRecyclerView(mRecyclerView)
}
/**
* 初始化卡片宽度
*/
private fun initWidth() {
mRecyclerView!!.post {
mCardGalleryWidth = mRecyclerView!!.width
mCardWidth = mCardGalleryWidth - ScreenUtil.dip2px(mContext, (2 * (mPagePadding + mShowLeftCardWidth)).toFloat())
mOnePageWidth = mCardWidth
mRecyclerView!!.smoothScrollToPosition(currentItemPos)
onScrolledChangedCallback()
}
}
private fun getDestItemOffset(destPos: Int): Int {
return mOnePageWidth * destPos
}
/**
* 计算mCurrentItemOffset
*/
private fun computeCurrentItemPos() {
if (mOnePageWidth <= 0) return
currentItemPos = Math.ceil(mCurrentItemOffset.toDouble() / mOnePageWidth.toDouble()).toInt()
}
/**
* RecyclerView位移事件监听, view大小随位移事件变化
*/
private fun onScrolledChangedCallback() {
val offset = mCurrentItemOffset - currentItemPos * mOnePageWidth
val percent = Math.max(Math.abs(offset) * 1.0 / mOnePageWidth, 0.0001).toFloat()
var leftView: View? = null
val currentView: View?
var rightView: View? = null
if (currentItemPos > 0) {
leftView = mRecyclerView!!.layoutManager.findViewByPosition(currentItemPos - 1)
}
currentView = mRecyclerView!!.layoutManager.findViewByPosition(currentItemPos)
if (currentItemPos < mRecyclerView!!.adapter.itemCount - 1) {
rightView = mRecyclerView!!.layoutManager.findViewByPosition(currentItemPos + 1)
}
if (leftView != null) {
// y = (1 - mScale)x + mScale
leftView.scaleY = (1 - mScale) * percent + mScale
}
if (currentView != null) {
// y = (mScale - 1)x + 1
currentView.scaleY = (mScale - 1) * percent + 1
}
if (rightView != null) {
// y = (1 - mScale)x + mScale
rightView.scaleY = (1 - mScale) * percent + mScale
}
}
fun setScale(scale: Float) {
mScale = scale
}
fun setPagePadding(pagePadding: Int) {
mPagePadding = pagePadding
}
fun setShowLeftCardWidth(showLeftCardWidth: Int) {
mShowLeftCardWidth = showLeftCardWidth
}
}
|
mit
|
68fabd39ccbc1008a4e7e94af3dde023
| 32.829268 | 159 | 0.623648 | 4.483836 | false | false | false | false |
gatling/gatling
|
src/docs/content/reference/current/core/injection/code/InjectionSampleKotlin.kt
|
1
|
3607
|
/*
* Copyright 2011-2021 GatlingCorp (https://gatling.io)
*
* 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 io.gatling.javaapi.core.CoreDsl.*
import io.gatling.javaapi.core.Simulation
import io.gatling.javaapi.http.HttpDsl.http
class InjectionSampleKotlin : Simulation() {
private val httpProtocol = http
private val scn = scenario("scenario")
init {
//#open-injection
setUp(
scn.injectOpen(
nothingFor(4), // 1
atOnceUsers(10), // 2
rampUsers(10).during(5), // 3
constantUsersPerSec(20.0).during(15), // 4
constantUsersPerSec(20.0).during(15).randomized(), // 5
rampUsersPerSec(10.0).to(20.0).during(10), // 6
rampUsersPerSec(10.0).to(20.0).during(10).randomized(), // 7
stressPeakUsers(1000).during(20) // 8
).protocols(httpProtocol)
)
//#open-injection
//#closed-injection
setUp(
scn.injectClosed(
constantConcurrentUsers(10).during(10), // 1
rampConcurrentUsers(10).to(20).during(10) // 2
)
)
//#closed-injection
//#incrementConcurrentUsers
setUp(
// generate a closed workload injection profile
// with levels of 10, 15, 20, 25 and 30 concurrent users
// each level lasting 10 seconds
// separated by linear ramps lasting 10 seconds
scn.injectClosed(
incrementConcurrentUsers(5)
.times(5)
.eachLevelLasting(10)
.separatedByRampsLasting(10)
.startingFrom(10) // Int
)
)
//#incrementConcurrentUsers
//#incrementUsersPerSec
setUp(
// generate an open workload injection profile
// with levels of 10, 15, 20, 25 and 30 arriving users per second
// each level lasting 10 seconds
// separated by linear ramps lasting 10 seconds
scn.injectOpen(
incrementUsersPerSec(5.0)
.times(5)
.eachLevelLasting(10)
.separatedByRampsLasting(10)
.startingFrom(10.0) // Double
)
)
//#incrementUsersPerSec
val scenario1 = scenario("scenario1")
val scenario2 = scenario("scenario2")
val injectionProfile1 = atOnceUsers(1)
val injectionProfile2 = atOnceUsers(1)
//#multiple
setUp(
scenario1.injectOpen(injectionProfile1),
scenario2.injectOpen(injectionProfile2)
)
//#multiple
val parent = scenario("parent")
val child1 = scenario("child1")
val child2 = scenario("child2")
val child3 = scenario("child3")
val grandChild = scenario("grandChild")
val injectionProfile = constantConcurrentUsers(5).during(5)
//#andThen
setUp(
parent.injectClosed(injectionProfile)
// child1 and child2 will start at the same time when last parent user will terminate
.andThen(
child1.injectClosed(injectionProfile)
// grandChild will start when last child1 user will terminate
.andThen(grandChild.injectClosed(injectionProfile)),
child2.injectClosed(injectionProfile)
).andThen(
// child3 will start when last grandChild and child2 users will terminate
child3.injectClosed(injectionProfile)
)
)
//#andThen
//#noShard
setUp(
// parent load won't be sharded
parent.injectOpen(atOnceUsers(1)).noShard()
.andThen(
// child load will be sharded
child1.injectClosed(injectionProfile)
)
)
//#noShard
}
}
|
apache-2.0
|
dd15339d3868112cf1eb01c85c336535
| 26.96124 | 89 | 0.715276 | 3.669379 | false | false | false | false |
mikepenz/MaterialDrawer
|
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/interfaces/SelectIconable.kt
|
1
|
2662
|
package com.mikepenz.materialdrawer.model.interfaces
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import com.mikepenz.materialdrawer.holder.ImageHolder
/**
* Defines a [IDrawerItem] with support for an icon
*/
interface SelectIconable {
/** the icon to show when this item gets selected */
var selectedIcon: ImageHolder?
/** defines if the icon should get proper tinting with the defined color */
var isIconTinted: Boolean
}
var <T : Iconable> T.selectedIconDrawable: Drawable
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(value) {
this.icon = ImageHolder(value)
}
var <T : Iconable> T.selectedIconBitmap: Bitmap
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(value) {
this.icon = ImageHolder(value)
}
var <T : Iconable> T.selectedIconRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(@DrawableRes value) {
this.icon = ImageHolder(value)
}
var <T : Iconable> T.selectedIconUrl: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(value) {
this.icon = ImageHolder(value)
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectIconable> T.withSelectedIcon(selectedIcon: Drawable): T {
this.selectedIcon = ImageHolder(selectedIcon)
return this as T
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectIconable> T.withSelectedIcon(@DrawableRes selectedIconRes: Int): T {
this.selectedIcon = ImageHolder(selectedIconRes)
return this as T
}
/** will tint the icon with the default (or set) colors (default and selected state) */
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectIconable> T.withIconTintingEnabled(iconTintingEnabled: Boolean): T {
this.isIconTinted = iconTintingEnabled
return this as T
}
/** will tint the icon with the default (or set) colors (default and selected state) */
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectIconable> T.withIconTinted(iconTintingEnabled: Boolean): T {
this.isIconTinted = iconTintingEnabled
return this as T
}
|
apache-2.0
|
181266c8b9a890932eb7a3a71ceb41c7
| 36.507042 | 87 | 0.73704 | 4.342577 | false | false | false | false |
aosp-mirror/platform_frameworks_support
|
room/compiler/src/main/kotlin/androidx/room/writer/TableInfoValidationWriter.kt
|
1
|
5417
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.writer
import androidx.room.ext.CommonTypeNames
import androidx.room.ext.L
import androidx.room.ext.N
import androidx.room.ext.RoomTypeNames
import androidx.room.ext.S
import androidx.room.ext.T
import androidx.room.ext.typeName
import androidx.room.parser.SQLTypeAffinity
import androidx.room.solver.CodeGenScope
import androidx.room.vo.Entity
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.ParameterizedTypeName
import stripNonJava
import java.util.Arrays
import java.util.HashMap
import java.util.HashSet
class TableInfoValidationWriter(val entity: Entity) {
fun write(dbParam: ParameterSpec, scope: CodeGenScope) {
val suffix = entity.tableName.stripNonJava().capitalize()
val expectedInfoVar = scope.getTmpVar("_info$suffix")
scope.builder().apply {
val columnListVar = scope.getTmpVar("_columns$suffix")
val columnListType = ParameterizedTypeName.get(HashMap::class.typeName(),
CommonTypeNames.STRING, RoomTypeNames.TABLE_INFO_COLUMN)
addStatement("final $T $L = new $T($L)", columnListType, columnListVar,
columnListType, entity.fields.size)
entity.fields.forEach { field ->
addStatement("$L.put($S, new $T($S, $S, $L, $L))",
columnListVar, field.columnName, RoomTypeNames.TABLE_INFO_COLUMN,
/*name*/ field.columnName,
/*type*/ field.affinity?.name ?: SQLTypeAffinity.TEXT.name,
/*nonNull*/ field.nonNull,
/*pkeyPos*/ entity.primaryKey.fields.indexOf(field) + 1)
}
val foreignKeySetVar = scope.getTmpVar("_foreignKeys$suffix")
val foreignKeySetType = ParameterizedTypeName.get(HashSet::class.typeName(),
RoomTypeNames.TABLE_INFO_FOREIGN_KEY)
addStatement("final $T $L = new $T($L)", foreignKeySetType, foreignKeySetVar,
foreignKeySetType, entity.foreignKeys.size)
entity.foreignKeys.forEach {
val myColumnNames = it.childFields
.joinToString(",") { "\"${it.columnName}\"" }
val refColumnNames = it.parentColumns
.joinToString(",") { "\"$it\"" }
addStatement("$L.add(new $T($S, $S, $S," +
"$T.asList($L), $T.asList($L)))", foreignKeySetVar,
RoomTypeNames.TABLE_INFO_FOREIGN_KEY,
/*parent table*/ it.parentTable,
/*on delete*/ it.onDelete.sqlName,
/*on update*/ it.onUpdate.sqlName,
Arrays::class.typeName(),
/*parent names*/ myColumnNames,
Arrays::class.typeName(),
/*parent column names*/ refColumnNames)
}
val indicesSetVar = scope.getTmpVar("_indices$suffix")
val indicesType = ParameterizedTypeName.get(HashSet::class.typeName(),
RoomTypeNames.TABLE_INFO_INDEX)
addStatement("final $T $L = new $T($L)", indicesType, indicesSetVar,
indicesType, entity.indices.size)
entity.indices.forEach { index ->
val columnNames = index.fields
.joinToString(",") { "\"${it.columnName}\"" }
addStatement("$L.add(new $T($S, $L, $T.asList($L)))",
indicesSetVar,
RoomTypeNames.TABLE_INFO_INDEX,
index.name,
index.unique,
Arrays::class.typeName(),
columnNames)
}
addStatement("final $T $L = new $T($S, $L, $L, $L)",
RoomTypeNames.TABLE_INFO, expectedInfoVar, RoomTypeNames.TABLE_INFO,
entity.tableName, columnListVar, foreignKeySetVar, indicesSetVar)
val existingVar = scope.getTmpVar("_existing$suffix")
addStatement("final $T $L = $T.read($N, $S)",
RoomTypeNames.TABLE_INFO, existingVar, RoomTypeNames.TABLE_INFO,
dbParam, entity.tableName)
beginControlFlow("if (! $L.equals($L))", expectedInfoVar, existingVar).apply {
addStatement("throw new $T($S + $L + $S + $L)",
IllegalStateException::class.typeName(),
"Migration didn't properly handle ${entity.tableName}" +
"(${entity.element.qualifiedName}).\n Expected:\n",
expectedInfoVar, "\n Found:\n", existingVar)
}
endControlFlow()
}
}
}
|
apache-2.0
|
11237011457f3c41af4b12199393e095
| 46.517544 | 90 | 0.579287 | 4.694107 | false | false | false | false |
marsdevapps/ercot-simple-client
|
src/main/kotlin/com/marsdev/samples/ercot/simple/ui/ERCOTApp.kt
|
1
|
6897
|
/*
* Copyright (c) 2017, mars dev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* THIS 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 MARS DEV BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.marsdev.samples.ercot.simple.ui
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReference
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.marsdev.samples.ercot.simple.common.ERCOTNode
import com.marsdev.samples.ercot.simple.common.SPPValue
import com.marsdev.util.ToolTipDefaultsFixer
import javafx.collections.FXCollections
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.scene.chart.CategoryAxis
import javafx.scene.chart.NumberAxis
import javafx.scene.control.Tooltip
import javafx.scene.text.FontWeight
import tornadofx.*
import java.time.LocalDate
class ERCOTApp : App(ERCOTNodeList::class, Styles::class) {
init {
ToolTipDefaultsFixer.setTooltipTimers(25, 5000, 200)
reloadStylesheetsOnFocus()
}
}
class ERCOTNodeList : View("ERCOT Nodes") {
val controller: ERCOTController by inject()
val model: ERCOTSelectionModel by inject()
lateinit var ercotNodes: Set<ERCOTNode>
val mapView: MapView
val map: ArcGISMap
val priceAxis = NumberAxis()
val spatialReference: SpatialReference
init {
spatialReference = SpatialReferences.getWebMercator()
map = ArcGISMap(Basemap.Type.IMAGERY_WITH_LABELS, 27.607441, -97.310196, 10)
mapView = MapView()
mapView.map = map
ercotNodes = controller.getERCOTNodes()
val ercotNode = ercotNodes.elementAt(0)
priceAxis.isAutoRanging = false
mapView.graphicsOverlays.add(myDemoLayer())
}
override val root = borderpane {
prefWidth = 1200.0
prefHeight = 800.0
left {
listview<ERCOTNode> {
items = FXCollections.observableArrayList(controller.getERCOTNodes())
cellCache {
label(it.name)
}
bindSelected(model.ercotNode)
selectionModel.selectFirst()
selectionModel.selectedItemProperty().onChange {
mapView.setViewpointCenterAsync(Point(model.ercotNode.value.lon, model.ercotNode.value.lat, SpatialReferences.getWgs84()), 12000.0)
controller.setSettlementPointPricesForSelection()
}
}
}
center {
splitpane {
orientation = Orientation.VERTICAL
linechart("ERCOT DA Hourly Prices", CategoryAxis(), priceAxis) {
series("Settlement Point Prices") {
data = controller.chartSeries
data.onChange {
// todo need to bind the selected node to the series title; this feels dirty?
name = "SPP - " + model.ercotNode.value.name
data.forEach {
Tooltip.install(it.node, Tooltip((it.yValue.toString())))
}
priceAxis.upperBoundProperty().set(model.maxPrice.value as Double)
priceAxis.lowerBoundProperty().set(model.minPrice.value as Double)
}
}
animated = false
}
add(mapView)
}
}
right {
// todo come up with a better way to display the hours
listview<SPPValue> {
items = controller.settlementPointPrices
cellCache {
label("Hour Ending ${it.hourEnding + 1}: $${it.settlementPointPrice}") {
alignment = Pos.CENTER_RIGHT
style {
fontSize = 16.px
fontWeight = FontWeight.MEDIUM
}
}
}
}
}
bottom {
hbox {
combobox<LocalDate>(model.date) {
items = controller.availableDates
selectionModel.selectFirst()
selectionModel.selectedItemProperty().onChange {
controller.setSettlementPointPricesForSelection()
// todo better way to bind/handle this?
var max = controller.getMinMaxPrices(model.date.value).first
var min = controller.getMinMaxPrices(model.date.value).second
model.maxPrice.value = Math.ceil(max) + 5
model.minPrice.value = Math.floor(min) - 5
}
}
}
}
}
private fun myDemoLayer(): GraphicsOverlay {
val graphicsOverlay = GraphicsOverlay()
ercotNodes.forEach { n ->
val point = Point(n.lon, n.lat, SpatialReferences.getWgs84())
val symbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFFFF0000.toInt(), 10f)
val graphic = Graphic(point, symbol)
graphicsOverlay.graphics.add(graphic)
// circle.tooltip(n.name)
}
return graphicsOverlay
}
}
|
gpl-3.0
|
a855a096d1014cc8212871bfd607fec0
| 39.333333 | 151 | 0.621575 | 4.723973 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
module/webview/src/main/java/jp/hazuki/yuzubrowser/webview/YuzuWebSettings.kt
|
1
|
10365
|
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.webview
import android.annotation.SuppressLint
import android.os.Build
import android.webkit.WebSettings
import androidx.annotation.RequiresApi
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature
import jp.hazuki.yuzubrowser.webview.utility.trimForHttpHeader
class YuzuWebSettings(private val origin: WebSettings) {
var appCacheEnabled = false
set(flag) {
origin.setAppCacheEnabled(flag)
field = flag
}
var geolocationEnabled = false
set(flag) {
origin.setGeolocationEnabled(flag)
field = flag
}
var mediaPlaybackRequiresUserGesture: Boolean
get() = origin.mediaPlaybackRequiresUserGesture
set(require) {
origin.mediaPlaybackRequiresUserGesture = require
}
var allowFileAccess: Boolean
get() = origin.allowFileAccess
set(allow) {
origin.allowFileAccess = allow
}
var allowContentAccess: Boolean
get() = origin.allowContentAccess
set(allow) {
origin.allowContentAccess = allow
}
var loadWithOverviewMode: Boolean
get() = origin.loadWithOverviewMode
set(overview) {
origin.loadWithOverviewMode = overview
}
var saveFormData: Boolean
@Deprecated("")
get() = origin.saveFormData
@Deprecated("")
set(save) {
origin.saveFormData = save
}
var savePassword: Boolean
@Suppress("DEPRECATION")
@Deprecated("")
get() = origin.savePassword
@Suppress("DEPRECATION")
@Deprecated("")
set(save) {
origin.savePassword = save
}
var textZoom: Int
get() = origin.textZoom
set(textZoom) {
origin.textZoom = textZoom
}
var lightTouchEnabled: Boolean
@Suppress("DEPRECATION")
@Deprecated("")
get() = origin.lightTouchEnabled
@Suppress("DEPRECATION")
@Deprecated("")
set(enabled) {
origin.lightTouchEnabled = enabled
}
var useWideViewPort: Boolean
get() = origin.useWideViewPort
set(use) {
origin.useWideViewPort = use
}
var layoutAlgorithm: WebSettings.LayoutAlgorithm
get() = origin.layoutAlgorithm
set(l) {
origin.layoutAlgorithm = l
}
var standardFontFamily: String
get() = origin.standardFontFamily
set(font) {
origin.standardFontFamily = font
}
var fixedFontFamily: String
get() = origin.fixedFontFamily
set(font) {
origin.fixedFontFamily = font
}
var sansSerifFontFamily: String
get() = origin.sansSerifFontFamily
set(font) {
origin.sansSerifFontFamily = font
}
var serifFontFamily: String
get() = origin.serifFontFamily
set(font) {
origin.serifFontFamily = font
}
var cursiveFontFamily: String
get() = origin.cursiveFontFamily
set(font) {
origin.cursiveFontFamily = font
}
var fantasyFontFamily: String
get() = origin.fantasyFontFamily
set(font) {
origin.fantasyFontFamily = font
}
var minimumFontSize: Int
get() = origin.minimumFontSize
set(size) {
origin.minimumFontSize = size
}
var minimumLogicalFontSize: Int
get() = origin.minimumLogicalFontSize
set(size) {
origin.minimumLogicalFontSize = size
}
var defaultFontSize: Int
get() = origin.defaultFontSize
set(size) {
origin.defaultFontSize = size
}
var defaultFixedFontSize: Int
get() = origin.defaultFixedFontSize
set(size) {
origin.defaultFixedFontSize = size
}
var loadsImagesAutomatically: Boolean
get() = origin.loadsImagesAutomatically
set(flag) {
origin.loadsImagesAutomatically = flag
}
var blockNetworkImage: Boolean
get() = origin.blockNetworkImage
set(flag) {
origin.blockNetworkImage = flag
}
var blockNetworkLoads: Boolean
get() = origin.blockNetworkLoads
set(flag) {
origin.blockNetworkLoads = flag
}
var domStorageEnabled: Boolean
get() = origin.domStorageEnabled
set(flag) {
origin.domStorageEnabled = flag
}
var databasePath: String
@Suppress("DEPRECATION")
@Deprecated("")
get() = origin.databasePath
@Suppress("DEPRECATION")
@Deprecated("")
set(databasePath) {
origin.databasePath = databasePath
}
var databaseEnabled: Boolean
get() = origin.databaseEnabled
set(flag) {
origin.databaseEnabled = flag
}
var javaScriptEnabled: Boolean
get() = origin.javaScriptEnabled
set(flag) {
origin.javaScriptEnabled = flag
}
var allowUniversalAccessFromFileURLs: Boolean
get() = origin.allowUniversalAccessFromFileURLs
set(flag) {
origin.allowUniversalAccessFromFileURLs = flag
}
var allowFileAccessFromFileURLs: Boolean
get() = origin.allowFileAccessFromFileURLs
set(flag) {
origin.allowFileAccessFromFileURLs = flag
}
var javaScriptCanOpenWindowsAutomatically: Boolean
get() = origin.javaScriptCanOpenWindowsAutomatically
set(flag) {
origin.javaScriptCanOpenWindowsAutomatically = flag
}
var defaultTextEncodingName: String
get() = origin.defaultTextEncodingName
set(encoding) {
origin.defaultTextEncodingName = encoding
}
var userAgentString: String?
get() = origin.userAgentString
set(ua) {
origin.userAgentString = trimForHttpHeader(ua)
}
var cacheMode: Int
get() = origin.cacheMode
set(mode) {
origin.cacheMode = mode
}
var mixedContentMode: Int
get() = origin.mixedContentMode
set(mode) {
origin.mixedContentMode = mode
}
var offscreenPreRaster: Boolean
get() = origin.offscreenPreRaster
set(enabled) {
origin.offscreenPreRaster = enabled
}
var safeBrowsingEnabled: Boolean
@RequiresApi(api = Build.VERSION_CODES.O)
get() = origin.safeBrowsingEnabled
@RequiresApi(api = Build.VERSION_CODES.O)
set(enabled) {
origin.safeBrowsingEnabled = enabled
}
var disabledActionModeMenuItems: Int
@RequiresApi(api = Build.VERSION_CODES.N)
get() = origin.disabledActionModeMenuItems
@RequiresApi(api = Build.VERSION_CODES.N)
set(menuItems) {
origin.disabledActionModeMenuItems = menuItems
}
var displayZoomButtons: Boolean
get() = origin.displayZoomControls
set(show) {
origin.setSupportZoom(true)
origin.builtInZoomControls = true
origin.displayZoomControls = show
}
var webTheme: Int = 0
set(value) {
if (value !in 0..4) throw IllegalArgumentException("webTheme")
field = value
setWebTheme()
}
fun setSupportZoom(support: Boolean) {
origin.setSupportZoom(support)
}
fun supportZoom(): Boolean {
return origin.supportZoom()
}
@Suppress("DEPRECATION")
@Deprecated("")
fun setEnableSmoothTransition(enable: Boolean) {
origin.setEnableSmoothTransition(enable)
}
fun setSupportMultipleWindows(support: Boolean) {
origin.setSupportMultipleWindows(support)
}
fun supportMultipleWindows(): Boolean {
return origin.supportMultipleWindows()
}
@Suppress("DEPRECATION")
@Deprecated("")
fun setGeolocationDatabasePath(databasePath: String) {
origin.setGeolocationDatabasePath(databasePath)
}
fun setAppCachePath(appCachePath: String) {
origin.setAppCachePath(appCachePath)
}
@Suppress("DEPRECATION")
@Deprecated("")
fun setAppCacheMaxSize(appCacheMaxSize: Long) {
origin.setAppCacheMaxSize(appCacheMaxSize)
}
fun setNeedInitialFocus(flag: Boolean) {
origin.setNeedInitialFocus(flag)
}
@SuppressLint("RequiresFeature")
private fun setWebTheme() {
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK) &&
WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK_STRATEGY)) {
if (webTheme == WEB_THEME_LIGHT) {
WebSettingsCompat.setForceDark(origin, WebSettingsCompat.FORCE_DARK_OFF)
} else {
WebSettingsCompat.setForceDark(origin, WebSettingsCompat.FORCE_DARK_ON)
val strategy = when (webTheme) {
WEB_THEME_DARK -> WebSettingsCompat.DARK_STRATEGY_WEB_THEME_DARKENING_ONLY
WEB_THEME_PREFER_WEB_OVER_FORCE_DARK -> WebSettingsCompat.DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING
WEB_THEME_FORCE_DARK -> WebSettingsCompat.DARK_STRATEGY_USER_AGENT_DARKENING_ONLY
else -> throw IllegalStateException()
}
WebSettingsCompat.setForceDarkStrategy(origin, strategy)
}
}
}
companion object {
const val WEB_THEME_LIGHT = 0
const val WEB_THEME_DARK = 1
const val WEB_THEME_PREFER_WEB_OVER_FORCE_DARK = 2
const val WEB_THEME_FORCE_DARK = 3
}
}
|
apache-2.0
|
f87a77711c302376bb750439a1037668
| 27.475275 | 134 | 0.615919 | 4.823174 | false | false | false | false |
bropane/Job-Seer
|
app/src/main/java/com/taylorsloan/jobseer/data/job/repo/sources/DataSource.kt
|
1
|
779
|
package com.taylorsloan.jobseer.data.job.repo.sources
import com.taylorsloan.jobseer.data.common.model.DataResult
import com.taylorsloan.jobseer.domain.job.models.Job
import io.reactivex.Flowable
/**
* Created by taylorsloan on 10/28/17.
*/
interface DataSource {
fun jobs(description: String? = null,
location: String? = null,
lat: Double? = null,
long: Double? = null,
fullTime: Boolean? = null,
page: Int = 0,
saved: Boolean? = null): Flowable<DataResult<List<Job>>>
fun job(id: String): Flowable<DataResult<Job>>
fun savedJobs(description: String?,
location: String?,
fullTime: Boolean?): Flowable<DataResult<List<Job>>>
fun clearJobs()
}
|
mit
|
a460e9308f28d0b909d31970a583d6af
| 29 | 70 | 0.623877 | 4.078534 | false | false | false | false |
serorigundam/numeri3
|
app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/ConversationActivityUI.kt
|
1
|
1668
|
package net.ketc.numeri.presentation.view.activity.ui
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import net.ketc.numeri.R
import net.ketc.numeri.presentation.view.activity.ConversationActivity
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.recyclerview.v7.recyclerView
class ConversationActivityUI : IConversationActivityUI {
override lateinit var toolbar: Toolbar
private set
override lateinit var tweetsRecycler: RecyclerView
private set
override fun createView(ui: AnkoContext<ConversationActivity>) = with(ui) {
coordinatorLayout {
appBarLayout {
toolbar {
id = R.id.toolbar
toolbar = this
}.lparams(matchParent, wrapContent) {
scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or
AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
}
}.lparams(matchParent, wrapContent)
recyclerView {
id = R.id.users_recycler
tweetsRecycler = this
isVerticalScrollBarEnabled = true
}.lparams(matchParent, matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
}
}
}
interface IConversationActivityUI : AnkoComponent<ConversationActivity> {
val toolbar: Toolbar
val tweetsRecycler: RecyclerView
}
|
mit
|
4c82dc8af78c31a8a200fc4fd852a163
| 36.066667 | 87 | 0.67446 | 5.148148 | false | false | false | false |
square/sqldelight
|
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/lang/SqlDelightFile.kt
|
1
|
2008
|
package com.squareup.sqldelight.core.lang
import com.alecstrong.sql.psi.core.SqlFileBase
import com.intellij.lang.Language
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileViewProvider
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.GlobalSearchScopesCore
import com.squareup.sqldelight.core.SqlDelightFileIndex
import com.squareup.sqldelight.core.SqlDelightProjectService
abstract class SqlDelightFile(
viewProvider: FileViewProvider,
language: Language
) : SqlFileBase(viewProvider, language) {
protected val module: Module?
get() = SqlDelightProjectService.getInstance(project).module(requireNotNull(virtualFile, { "Null virtualFile" }))
val generatedDirectories by lazy {
val packageName = packageName ?: return@lazy null
generatedDirectories(packageName)
}
internal fun generatedDirectories(packageName: String): List<String>? {
val module = module ?: return null
return SqlDelightFileIndex.getInstance(module).outputDirectory(this).map { outputDirectory ->
"$outputDirectory/${packageName.replace('.', '/')}"
}
}
internal val dialect
get() = SqlDelightProjectService.getInstance(project).dialectPreset
internal abstract val packageName: String?
override fun getVirtualFile(): VirtualFile? {
if (myOriginalFile != null) return myOriginalFile.virtualFile
return super.getVirtualFile()
}
override fun searchScope(): GlobalSearchScope {
val default = GlobalSearchScope.fileScope(this)
val module = module ?: return default
val index = SqlDelightFileIndex.getInstance(module)
val sourceFolders = index.sourceFolders(virtualFile ?: return default)
if (sourceFolders.isEmpty()) return default
// TODO Deal with database files?
return sourceFolders
.map { GlobalSearchScopesCore.directoryScope(project, it, true) }
.reduce { totalScope, directoryScope -> totalScope.union(directoryScope) }
}
}
|
apache-2.0
|
3d6dda7889da0a69d0a7d1f44c9f3bbf
| 34.857143 | 117 | 0.769422 | 4.897561 | false | false | false | false |
EMResearch/EvoMaster
|
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/fieldWithDifferentArgument/DataRepository.kt
|
1
|
1304
|
package com.foo.graphql.fieldWithDifferentArgument
import com.foo.graphql.fieldWithDifferentArgument.type.Flower
import com.foo.graphql.fieldWithDifferentArgument.type.Store
import org.springframework.stereotype.Component
@Component
open class DataRepository {
private val flowers = mutableMapOf<Int, Flower>()
private val stores = mutableMapOf<Int, Store>()
init {
listOf(
Flower(0, "Roses", "Red"),
Flower(1, "Tulips", "Pink"),
Flower(2, "Lilies", "White"),
Flower(3, "Limonium", "Purple")
).forEach { flowers[it.id] = it }
listOf(
Store(0, "Roses" , 5),
Store(1, "Tulips",9),
).forEach { stores[it.id] = it }
}
fun findByIdAndColor(id: Int?, color: String?): Flower {
if (id != null || color != null) {
for (flower in flowers) {
if (flower.value.id == id)
if (flower.value.color == color)
return flower.value
}
return Flower(100, "X", "Color:X")
} else return Flower(100, "X", "Color:X")
}
fun findById(id: Int): Flower {
return flowers[id]!!
}
fun findStores():Store{
return stores[0]!!
}
}
|
lgpl-3.0
|
9c23721939b84c827b888b698c02e26d
| 22.285714 | 61 | 0.539877 | 3.869436 | false | false | false | false |
sonnytron/FitTrainerBasic
|
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/ExerciseActivity.kt
|
1
|
3071
|
package com.sonnyrodriguez.fittrainer.fittrainerbasic
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.ExerciseFragment
import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.StatsFragment
import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.WorkoutFragment
import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.NavPosition
import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.active
import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.disableShiftMode
import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.replaceFragment
import org.jetbrains.anko.toast
class ExerciseActivity: AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
val positionKey = "positionKey"
var navigationPosition: NavPosition = NavPosition.EXERCISES
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_exercise)
restoreSavedInstanceState(savedInstanceState)
initializeViews()
restoreFragment(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putInt(positionKey, navigationPosition.id)
super.onSaveInstanceState(outState)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
navigationPosition = NavPosition.positionById(item.itemId)
return when(item.itemId) {
R.id.navigation_exercises_item -> loadExerciseFragment()
R.id.navigation_workouts_item -> loadWorkoutFragment()
R.id.navigation_stats_item -> loadStatsFragment()
else -> return false
}
}
internal fun initializeViews() {
findViewById<BottomNavigationView>(R.id.navigation_menu).apply { initializeBottomNavigation(this) }
}
internal fun initializeBottomNavigation(bottomNavigationView: BottomNavigationView) {
bottomNavigationView.disableShiftMode()
bottomNavigationView.active(navigationPosition.position)
bottomNavigationView.setOnNavigationItemSelectedListener(this)
}
fun loadWorkoutFragment(): Boolean {
replaceFragment(WorkoutFragment.newInstance())
return true
}
fun loadExerciseFragment(): Boolean {
replaceFragment(ExerciseFragment.newInstance())
return true
}
fun loadStatsFragment(): Boolean {
replaceFragment(StatsFragment.newInstance())
return true
}
internal fun restoreSavedInstanceState(savedInstanceState: Bundle?) {
savedInstanceState?.let {
val id = it.getInt(positionKey, NavPosition.EXERCISES.id)
navigationPosition = NavPosition.positionById(id)
}
}
internal fun restoreFragment(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
loadExerciseFragment()
}
}
}
|
apache-2.0
|
ca92eeaa1f28b6a463064a940420e1f5
| 36.45122 | 107 | 0.746988 | 5.387719 | false | false | false | false |
proxer/ProxerLibAndroid
|
library/src/test/kotlin/me/proxer/library/api/manga/ChapterEndpointTest.kt
|
2
|
1443
|
package me.proxer.library.api.manga
import me.proxer.library.ProxerTest
import me.proxer.library.entity.manga.Chapter
import me.proxer.library.entity.manga.Page
import me.proxer.library.enums.Language
import me.proxer.library.runRequest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
import java.util.Date
/**
* @author Ruben Gees
*/
class ChapterEndpointTest : ProxerTest() {
private val expectedChapter = Chapter(
id = "1954", entryId = "2784", title = "Chapter 1", uploaderId = "0", uploaderName = "nobody",
date = Date(1318716000L * 1000), scanGroupId = null, scanGroupName = null, server = "0",
pages = listOf(
Page(name = "fairy-001-01.jpg", height = 1100, width = 765),
Page(name = "fairy-001-02-03.jpg", height = 641, width = 900)
)
)
@Test
fun testDefault() {
val (result, _) = server.runRequest("chapter.json") {
api.manga
.chapter("15", 1, Language.ENGLISH)
.build()
.execute()
}
result shouldBeEqualTo expectedChapter
}
@Test
fun testPath() {
val (_, request) = server.runRequest("chapter.json") {
api.manga.chapter("4523", 1, Language.GERMAN)
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/manga/chapter?id=4523&episode=1&language=de"
}
}
|
gpl-3.0
|
242d7c579589f00135cd874b390ab702
| 29.0625 | 102 | 0.607069 | 3.807388 | false | true | false | false |
facebook/fresco
|
vito/source/src/main/java/com/facebook/fresco/vito/source/ImageSourceProvider.kt
|
1
|
3236
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.source
import android.net.Uri
/**
* Create image sources that can be passed to Fresco's image components. For example, to create a
* single image source for a given URI, call [forUri(Uri)] or [forUri(String)].
*
* It is also possible to set your own provider by calling [setImplementation(Implementation)]
*/
object ImageSourceProvider {
/** @return an empty image source if no image URI is available to pass to the UI component */
@JvmStatic fun emptySource(): ImageSource = EmptyImageSource
/**
* Create a single image source for a given image URI.
*
* @param uri the image URI to use
* @return the ImageSource to be passed to the UI component
*/
@JvmStatic
fun forUri(uri: Uri?): ImageSource =
if (uri == null) {
emptySource()
} else {
SingleImageSource(uri)
}
/**
* Create a single image source for a given image URI.
*
* @param uriString the image URI String to use
* @return the ImageSource to be passed to the UI component
*/
@JvmStatic
fun forUri(uriString: String?): ImageSource =
if (uriString == null) {
emptySource()
} else {
SingleImageSource(Uri.parse(uriString))
}
/**
* Create a multi image source for a given set of sources. Image sources are obtained in order.
* Only if the current source fails, or if it finishes without a result, the next one will be
* tried.
*
* @param imageSources the list of image sources to be used
* @return the ImageSource to be passed to the UI component
*/
@JvmStatic
fun firstAvailable(vararg imageSources: ImageSource): ImageSource =
FirstAvailableImageSource(imageSources)
/**
* Create a multi image source for a low- and high resolution image. Both requests will be sent
* off, the low resolution will be used as an intermediate image until the high resolution one is
* available.
*
* @param lowResImageSource the low resolution image source to be used
* @param highResImageSource the high resolution image source to be used
* @return the ImageSource to be passed to the UI component
*/
@JvmStatic
fun increasingQuality(
lowResImageSource: ImageSource,
highResImageSource: ImageSource
): ImageSource = IncreasingQualityImageSource(lowResImageSource, highResImageSource)
/**
* Create a multi image source for a low- and high resolution image. Both requests will be sent
* off, the low resolution will be used as an intermediate image until the high resolution one is
* available.
*
* @param lowResImageUri the low resolution image URI to be used
* @param highResImageUri the high resolution image URI to be used
* @return the ImageSource to be passed to the UI component
*/
@JvmStatic
fun increasingQuality(lowResImageUri: Uri?, highResImageUri: Uri?): ImageSource =
if (lowResImageUri == null) {
forUri(highResImageUri)
} else IncreasingQualityImageSource(forUri(lowResImageUri), forUri(highResImageUri))
}
|
mit
|
8eb2cb53d4801ace090a55337cde76dd
| 34.173913 | 99 | 0.707046 | 4.432877 | false | false | false | false |
UweTrottmann/SeriesGuide
|
billing/src/main/java/com/uwetrottmann/seriesguide/billing/localdb/CachedPurchase.kt
|
1
|
3722
|
/**
* Copyright (C) 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uwetrottmann.seriesguide.billing.localdb
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.Purchase
/**
* This [Entity] is used partly for convenience and partly for security.
*
* - Convenience: when Play Billing calls onConsumeResponse, entitlements can be disbursed without
* first consulting the secure server, which might be temporarily down for, say, maintenance.
*
* - Security: Imagine a situation where four users of Trivial
* Drive decide to share one premium car purchase amongst themselves. So one user would buy the
* car and then log into the Play Store on each phone and as soon as they open the Trivial Drive
* app on a phone, they would see a Premium car. That would be fraudulent, but since this [Entity] is part
* of the local cache, the [BillingRepository] would notice there is a purchase in this local
* cache that the secure server does not recognize as belonging to this user. The secure server
* would then conduct further investigations and discover the fraud.
*
* This [Entity] will only be tracking active purchases. Hence, it's unlikely that very much data
* will ever be saved here. It will keep subscriptions and non-consumables definitely, but
* temporarily store consumables until Play confirms they have been consumed.
*
* While it would be more natural to simply call this class "Purchase," that might confuse new
* developers to your team since [BillingClient] already calls its data [Purchase]. So it's better
* to give it a different name. Also recall that [BillingRepository] must handle three different
* data sources. So letting each source call its data by a slightly different name might make
* reading the code easier.
*/
//TODO: This is the preferred implementation. Blocked on issue with ignoreColumns.
//@Entity(tableName = "purchase_table", ignoredColumns = arrayOf("mParsedJson"))
//class CachedPurchase(mOriginalJson: String, mSignature: String) : Purchase(mOriginalJson, mSignature) {
// @PrimaryKey(autoGenerate = true)
// var id: Int = 0
//}
@Entity(tableName = "purchase_table")
@TypeConverters(PurchaseTypeConverter::class)
class CachedPurchase(val data: Purchase) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@Ignore
val purchaseToken = data.purchaseToken
@Ignore
val sku: String = data.skus[0]
override fun equals(other: Any?): Boolean {
return when (other) {
is CachedPurchase -> data == other.data
is Purchase -> data == other
else -> false
}
}
override fun hashCode(): Int {
return data.hashCode()
}
}
class PurchaseTypeConverter {
@TypeConverter
fun toString(purchase: Purchase): String = purchase.originalJson + '|' + purchase.signature
@TypeConverter
fun toPurchase(data: String): Purchase = data.split('|').let {
Purchase(it[0], it[1])
}
}
|
apache-2.0
|
ce60aac3e40da405019524b66b5d7e62
| 39.032258 | 108 | 0.731865 | 4.263459 | false | false | false | false |
mpv-android/mpv-android
|
app/src/main/java/is/xyz/mpv/BackgroundPlaybackService.kt
|
1
|
6188
|
package `is`.xyz.mpv
import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.media.app.NotificationCompat.MediaStyle
/*
All this service does is
- Discourage Android from killing mpv while it's in background
- Update the persistent notification (which we're forced to display)
*/
class BackgroundPlaybackService : Service(), MPVLib.EventObserver {
override fun onCreate() {
MPVLib.addObserver(this)
}
private var cachedMetadata = Utils.AudioMetadata()
private var paused: Boolean = false
private var shouldShowPrevNext: Boolean = false
private fun buildNotificationAction(@DrawableRes icon: Int, @StringRes title: Int, intentAction: String): NotificationCompat.Action {
val intent = NotificationButtonReceiver.createIntent(this, intentAction)
val builder = NotificationCompat.Action.Builder(icon, getString(title), intent)
with (builder) {
setContextual(false)
setShowsUserInterface(false)
return build()
}
}
@SuppressLint("UnspecifiedImmutableFlag")
private fun buildNotification(): Notification {
val notificationIntent = Intent(this, MPVActivity::class.java)
val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
else
PendingIntent.getActivity(this, 0, notificationIntent, 0)
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
with (builder) {
setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
setPriority(NotificationCompat.PRIORITY_LOW)
setContentTitle(cachedMetadata.formatTitle())
setContentText(cachedMetadata.formatArtistAlbum())
setSmallIcon(R.drawable.ic_mpv_symbolic)
setContentIntent(pendingIntent)
setOngoing(true)
}
thumbnail?.let {
builder.setLargeIcon(it)
builder.setColorized(true)
// scale thumbnail to a single color in two steps
val b1 = Bitmap.createScaledBitmap(it, 16, 16, true)
val b2 = Bitmap.createScaledBitmap(b1, 1, 1, true)
builder.setColor(b2.getPixel(0, 0))
b2.recycle(); b1.recycle()
}
val playPauseAction = if (paused)
buildNotificationAction(R.drawable.ic_play_arrow_black_24dp, R.string.btn_play, "PLAY_PAUSE")
else
buildNotificationAction(R.drawable.ic_pause_black_24dp, R.string.btn_pause, "PLAY_PAUSE")
if (shouldShowPrevNext) {
builder.addAction(buildNotificationAction(
R.drawable.ic_skip_previous_black_24dp, R.string.dialog_prev, "ACTION_PREV"
))
builder.addAction(playPauseAction)
builder.addAction(buildNotificationAction(
R.drawable.ic_skip_next_black_24dp, R.string.dialog_next, "ACTION_NEXT"
))
builder.setStyle(MediaStyle().setShowActionsInCompactView(0, 2))
} else {
builder.addAction(playPauseAction)
builder.setStyle(MediaStyle())
}
return builder.build()
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.v(TAG, "BackgroundPlaybackService: starting")
// read some metadata
cachedMetadata.readAll()
paused = MPVLib.getPropertyBoolean("pause")
shouldShowPrevNext = MPVLib.getPropertyInt("playlist-count") ?: 0 > 1
// create notification and turn this into a "foreground service"
val notification = buildNotification()
startForeground(NOTIFICATION_ID, notification)
return START_NOT_STICKY // Android can't restart this service on its own
}
override fun onDestroy() {
MPVLib.removeObserver(this)
Log.v(TAG, "BackgroundPlaybackService: destroyed")
}
override fun onBind(intent: Intent): IBinder? { return null }
/* Event observers */
override fun eventProperty(property: String) { }
override fun eventProperty(property: String, value: Boolean) {
if (property != "pause")
return
paused = value
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, buildNotification())
}
override fun eventProperty(property: String, value: Long) { }
override fun eventProperty(property: String, value: String) {
if (!cachedMetadata.update(property, value))
return
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, buildNotification())
}
override fun event(eventId: Int) {
if (eventId == MPVLib.mpvEventId.MPV_EVENT_IDLE)
stopSelf()
}
companion object {
/* Using this property MPVActivity gives us a thumbnail
to display alongside the permanent notification */
var thumbnail: Bitmap? = null
private const val NOTIFICATION_ID = 12345
private const val NOTIFICATION_CHANNEL_ID = "background_playback"
fun createNotificationChannel(context: Context) {
val manager = NotificationManagerCompat.from(context)
val builder = NotificationChannelCompat.Builder(NOTIFICATION_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_MIN)
manager.createNotificationChannel(with (builder) {
setName(context.getString(R.string.pref_background_play_title))
build()
})
}
private const val TAG = "mpv"
}
}
|
mit
|
79edcd0f4d6fef1b509c04cad86f38c8
| 35.187135 | 137 | 0.6734 | 4.922832 | false | false | false | false |
google/grpc-kapt
|
processor/src/main/kotlin/com/google/api/grpc/kapt/generator/Generator.kt
|
1
|
15549
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.grpc.kapt.generator
import com.google.api.grpc.kapt.FallbackMarshallerProvider
import com.google.api.grpc.kapt.GrpcClient
import com.google.api.grpc.kapt.GrpcServer
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
import io.grpc.MethodDescriptor
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.metadata.Flag
import kotlinx.metadata.Flags
import kotlinx.metadata.KmClassVisitor
import kotlinx.metadata.KmFunctionVisitor
import kotlinx.metadata.KmTypeVisitor
import kotlinx.metadata.KmValueParameterVisitor
import kotlinx.metadata.KmVariance
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement
import javax.lang.model.type.MirroredTypeException
import javax.tools.Diagnostic
/** A generator component running in the annotation processor's [environment]. */
internal abstract class Generator<T>(
val environment: ProcessingEnvironment
) {
/** Generate the component for the given [element]. */
abstract fun generate(element: Element): T
/** Extract the type info from the annotation, using values from the [element] as needed. */
protected fun GrpcClient.extractTypeInfo(
element: Element,
suffix: String,
providers: List<GeneratedInterfaceProvider>
): AnnotatedTypeInfo =
extractTypeInfo(element, name, packageName, definedBy, suffix, providers)
/** Extract the type info from the annotation, using values from the [element] as needed. */
protected fun GrpcServer.extractTypeInfo(
element: Element,
suffix: String
): AnnotatedTypeInfo =
extractTypeInfo(element, name, packageName, "", suffix)
private fun extractTypeInfo(
element: Element,
nameFromAnnotation: String,
packageNameFromAnnotation: String,
definedByFromAnnotation: String,
suffix: String,
providers: List<GeneratedInterfaceProvider> = listOf()
): AnnotatedTypeInfo {
// determine appropriate names to use for the service
val simpleServiceName = if (nameFromAnnotation.isNotBlank()) {
nameFromAnnotation
} else {
element.asGeneratedInterfaceName()
}
val typeName = if (packageNameFromAnnotation.isNotBlank()) {
ClassName(packageNameFromAnnotation, simpleServiceName + suffix)
} else {
ClassName(
environment.elementUtils.getPackageOf(element).qualifiedName.toString(),
simpleServiceName + suffix
)
}
// determine name and provider
var provider: GeneratedInterfaceProvider? = null
val qualifiedServiceName = if (packageNameFromAnnotation.isNotBlank()) {
"$packageNameFromAnnotation.$simpleServiceName"
} else if (definedByFromAnnotation.isNotBlank()) {
provider = providers.firstOrNull { it.isDefinedBy(definedByFromAnnotation) }
provider?.findFullyQualifiedServiceName(definedByFromAnnotation)
?: throw CodeGenerationException("No suitable generator found for definedBy='$definedByFromAnnotation'")
} else {
environment.elementUtils.getPackageOf(element).qualifiedName.toString() + "." + simpleServiceName
}
return AnnotatedTypeInfo(
simpleName = simpleServiceName,
fullName = qualifiedServiceName,
type = typeName,
source = provider?.getSource(definedByFromAnnotation)
)
}
companion object {
var DEFAULT_MARSHALLER: TypeName = FallbackMarshallerProvider::class.asTypeName()
}
}
/**
* Used for a client/server interface type that is auto-generated (instead of written by the user).
*
* The associated [methodInfo] contains whatever additional metadata the client/server generators requires
* that is not contained in the interface named [typeName].
*
* The map must contain an entry for each function in the type named by [typeName].
*
* The [typeName] must be in the [types] list along with any other supplemental generated types.
*/
internal data class GeneratedInterface(
val typeName: String,
val methodInfo: Map<FunSpec, KotlinMethodInfo> = mapOf(),
val simpleTypeName: String? = null,
val types: List<TypeSpec> = listOf()
) {
fun asMethods(): List<KotlinMethodInfo> = methodInfo.values.toList()
}
/** Interface for generators that produce the @GrpcClient interface definition. */
internal interface GeneratedInterfaceProvider {
/**
* Tests if this generator is relevant for the value given in [GrpcClient.definedBy].
*/
fun isDefinedBy(value: String): Boolean
/**
* Find the fully qualified name of the service.
*
* The [value] corresponds to the value provided in [GrpcClient.definedBy].
*/
fun findFullyQualifiedServiceName(value: String): String
fun getSource(value: String): SchemaDescriptorProvider?
}
/** Interface for generators that produce @GrpcServer's that support reflection */
internal interface SchemaDescriptorProvider {
fun getSchemaDescriptorType(): TypeSpec?
fun getSchemaDescriptorFor(methodName: String? = null): CodeBlock?
}
/**
* Type information about a generated gRPC client/server.
*
* The [simpleName] is the same as the [type] without any suffix.
* The [fullName] is used for the gRPC service name.
* The [provider] of the type info (if an external source was used - i.e. proto)
*/
internal data class AnnotatedTypeInfo(
val simpleName: String,
val fullName: String,
val type: ClassName,
val source: SchemaDescriptorProvider?
)
/** Generic exception for [Generator] components to throw. */
internal class CodeGenerationException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
// logging helpers
internal fun ProcessingEnvironment.error(message: String) = this.messager.printMessage(Diagnostic.Kind.ERROR, message)
internal fun ProcessingEnvironment.warn(message: String) = this.messager.printMessage(Diagnostic.Kind.WARNING, message)
/** Class name used for the gRPC generated type (client & server). */
internal fun Element.asGeneratedInterfaceName() = this.simpleName.toString()
/** Class type used for the gRPC generated type (client & server). */
internal fun Element.asGeneratedInterfaceType() = this.asType().asTypeName()
/** Parse the marshaller provider from the annotation class. */
internal fun GrpcClient.asMarshallerType(): TypeName = try {
this.marshaller.asTypeName()
} catch (e: MirroredTypeException) {
e.typeMirror.asTypeName()
}.asMarshallerClass()
/** Parse the marshaller provider from the annotation class. */
internal fun GrpcServer.asMarshallerType(): TypeName = try {
this.marshaller.asTypeName()
} catch (e: MirroredTypeException) {
e.typeMirror.asTypeName()
}.asMarshallerClass()
private fun TypeName.asMarshallerClass() = if (Unit::class.asTypeName() == this) {
Generator.DEFAULT_MARSHALLER
} else {
this
}
/**
* Extract the Kotlin compiler metadata from the [Element].
*
* The element must correspond to a Class or a [CodeGenerationException] will be thrown.
*/
internal fun Element.asKotlinMetadata(): KotlinClassMetadata.Class {
val annotation = this.getAnnotation(Metadata::class.java)
?: throw CodeGenerationException("Kotlin metadata not found on element: ${this.simpleName}")
return when (val metadata = KotlinClassMetadata.read(
KotlinClassHeader(
kind = annotation.kind,
metadataVersion = annotation.metadataVersion,
bytecodeVersion = annotation.bytecodeVersion,
data1 = annotation.data1,
data2 = annotation.data2,
extraString = annotation.extraString,
packageName = annotation.packageName,
extraInt = annotation.extraInt
)
)) {
is KotlinClassMetadata.Class -> metadata
else -> throw CodeGenerationException("Kotlin metadata of unexpected type or unreadable")
}
}
/** Get all the methods on this element that are candidate for RPC calls */
internal fun Element.filterRpcMethods(): List<ExecutableElement> =
this.enclosedElements
.filter { it.kind == ElementKind.METHOD }
.mapNotNull { it as? ExecutableElement }
.filter { it.parameters.size > 0 } // TODO: better filtering?
/** Info about a Kotlin function (including info extracted from the @Metadata annotation). */
internal data class KotlinMethodInfo(
val name: String,
val isSuspend: Boolean,
val parameters: List<ParameterInfo>,
val returns: TypeName,
val rpc: RpcInfo
)
/** Info about the RPC associated with a method. */
internal data class RpcInfo(
val name: String,
val type: MethodDescriptor.MethodType,
val inputType: TypeName,
val outputType: TypeName
)
/** Parse information about a Kotlin function from the [kotlin.Metadata] annotation. */
internal fun KotlinClassMetadata.Class.describeElement(
method: ExecutableElement
): KotlinMethodInfo {
val funName = method.simpleName.toString()
var isSuspend = false
val parameters = mutableListOf<ParameterInfo>()
var returns: TypeName = Unit::class.asTypeName()
this.accept(object : KmClassVisitor() {
override fun visitFunction(flags: Flags, name: String): KmFunctionVisitor? {
if (funName != name) return null
isSuspend = Flag.Function.IS_SUSPEND(flags)
return object : KmFunctionVisitor() {
private val returnTypeVisitor = TypeArgVisitor()
override fun visitValueParameter(flags: Flags, name: String): KmValueParameterVisitor? {
val paramName = name
val paramTypeVisitor = TypeArgVisitor()
return object : KmValueParameterVisitor() {
override fun visitType(flags: Flags): KmTypeVisitor {
return paramTypeVisitor
}
override fun visitEnd() {
val type = paramTypeVisitor.type
?: throw CodeGenerationException("Unable to determine param type of '$paramName' in method: '$funName'.")
parameters.add(ParameterInfo(paramName, type))
}
}
}
override fun visitReturnType(flags: Flags): KmTypeVisitor? {
return returnTypeVisitor
}
override fun visitEnd() {
returns = returnTypeVisitor.type
?: throw CodeGenerationException("Unable to determine return type of method: '$funName'.")
}
}
}
})
// sanity checks
if (parameters.size != 1) {
throw CodeGenerationException("Unexpected number of parameters (${parameters.size}) in method ${method.simpleName}")
}
// determine rpc type from method signature
val inputType = parameters.first().type
val methodType = when {
returns.isReceiveChannel() && inputType.isReceiveChannel() -> MethodDescriptor.MethodType.BIDI_STREAMING
returns.isReceiveChannel() -> MethodDescriptor.MethodType.SERVER_STREAMING
inputType.isReceiveChannel() -> MethodDescriptor.MethodType.CLIENT_STREAMING
else -> MethodDescriptor.MethodType.UNARY
}
return KotlinMethodInfo(
name = funName,
isSuspend = isSuspend,
parameters = parameters,
returns = returns,
rpc = RpcInfo(
name = funName.capitalize(),
type = methodType,
inputType = when (methodType) {
MethodDescriptor.MethodType.CLIENT_STREAMING -> inputType.extractStreamType()
MethodDescriptor.MethodType.BIDI_STREAMING -> inputType.extractStreamType()
else -> inputType
},
outputType = when (methodType) {
MethodDescriptor.MethodType.SERVER_STREAMING -> returns.extractStreamType()
MethodDescriptor.MethodType.BIDI_STREAMING -> returns.extractStreamType()
else -> returns
}
)
)
}
// Helper for constructing a full type with arguments
private class TypeArgVisitor : KmTypeVisitor() {
private var typeName: TypeName? = null
private var className: ClassName? = null
private val args = mutableListOf<TypeArgVisitor>()
val type: TypeName?
get() = typeName
override fun visitClass(name: kotlinx.metadata.ClassName) {
className = name.asClassName()
}
override fun visitArgument(flags: Flags, variance: KmVariance): KmTypeVisitor? {
val nested = TypeArgVisitor()
args += nested
return nested
}
override fun visitEnd() {
typeName = if (args.isNotEmpty()) {
val typeArgs = args.mapNotNull { it.className }
className?.parameterizedBy(*typeArgs.toTypedArray())
} else {
className
}
}
}
/** Test if the type is a [ReceiveChannel]. */
internal fun TypeName.isReceiveChannel() = this.isRawType(ReceiveChannel::class.asTypeName())
/** Test if the given [type] matches this type. */
internal fun TypeName.isRawType(type: TypeName): Boolean {
val rawType = if (this is ParameterizedTypeName) {
this.rawType
} else {
this
}
return rawType == type
}
/** Extracts the type that should be used for the rpc (first type argument) */
internal fun TypeName.extractStreamType(): TypeName {
val t = this as? ParameterizedTypeName ?: throw CodeGenerationException("Invalid type for streaming method: $this.")
if (t.typeArguments.size != 1) {
throw CodeGenerationException("Invalid type arguments for streaming method (expected 1).")
}
return t.typeArguments.first()
}
/** Convert from a Kotlin [kotlinx.metadata.ClassName] to a KotlinPoet [ClassName]. */
internal fun kotlinx.metadata.ClassName.asClassName() = ClassName.bestGuess(this.replace("/", "."))
/** Describes a named parameter in a function of the given [name] and [type]. */
internal data class ParameterInfo(val name: String, val type: TypeName)
/** Ensures the string does not equal any of the [others]. */
internal fun String.unless(vararg others: String): String = if (others.contains(this)) {
"_$this".unless(*others)
} else {
this
}
|
apache-2.0
|
97fc458da1379ddd721eef5836974eaa
| 37.29803 | 137 | 0.689176 | 4.928368 | false | false | false | false |
luxons/seven-wonders
|
sw-server/src/main/kotlin/org/luxons/sevenwonders/server/controllers/GameBrowserController.kt
|
1
|
4442
|
package org.luxons.sevenwonders.server.controllers
import org.luxons.sevenwonders.model.api.GameListEvent
import org.luxons.sevenwonders.model.api.GameListEventWrapper
import org.luxons.sevenwonders.model.api.LobbyDTO
import org.luxons.sevenwonders.model.api.actions.CreateGameAction
import org.luxons.sevenwonders.model.api.actions.JoinGameAction
import org.luxons.sevenwonders.model.api.wrap
import org.luxons.sevenwonders.server.ApiMisuseException
import org.luxons.sevenwonders.server.api.toDTO
import org.luxons.sevenwonders.server.lobby.Lobby
import org.luxons.sevenwonders.server.repositories.LobbyRepository
import org.luxons.sevenwonders.server.repositories.PlayerRepository
import org.slf4j.LoggerFactory
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.messaging.simp.annotation.SendToUser
import org.springframework.messaging.simp.annotation.SubscribeMapping
import org.springframework.stereotype.Controller
import org.springframework.validation.annotation.Validated
import java.security.Principal
/**
* This is the place where the player looks for a game.
*/
@Controller
class GameBrowserController(
private val lobbyController: LobbyController,
private val lobbyRepository: LobbyRepository,
private val playerRepository: PlayerRepository,
private val template: SimpMessagingTemplate,
) {
/**
* Gets the created or updated games. The list of existing games is received on this topic at once upon
* subscription, and then each time the list changes.
*
* @param principal the connected user's information
*
* @return the current list of [Lobby]s
*/
@SubscribeMapping("/games") // prefix /topic not shown
fun listGames(principal: Principal): GameListEventWrapper {
logger.info("Player '{}' subscribed to /topic/games", principal.name)
return GameListEvent.ReplaceList(lobbyRepository.list().map { it.toDTO() }).wrap()
}
/**
* Creates a new [Lobby].
*
* @param action the action to create the game
* @param principal the connected user's information
*
* @return the newly created [Lobby]
*/
@MessageMapping("/lobby/create")
@SendToUser("/queue/lobby/joined")
fun createGame(@Validated action: CreateGameAction, principal: Principal): LobbyDTO {
checkThatUserIsNotInAGame(principal, "cannot create another game")
val player = playerRepository.find(principal.name)
val lobby = lobbyRepository.create(action.gameName, owner = player)
logger.info("Game '{}' ({}) created by {} ({})", lobby.name, lobby.id, player.displayName, player.username)
// notify everyone that a new game exists
val lobbyDto = lobby.toDTO()
template.convertAndSend("/topic/games", GameListEvent.CreateOrUpdate(lobbyDto).wrap())
return lobbyDto
}
/**
* Joins an existing [Lobby].
*
* @param action the action to join the game
* @param principal the connected user's information
*
* @return the [Lobby] that has just been joined
*/
@MessageMapping("/lobby/join")
@SendToUser("/queue/lobby/joined")
fun joinGame(@Validated action: JoinGameAction, principal: Principal): LobbyDTO {
checkThatUserIsNotInAGame(principal, "cannot join another game")
val lobby = lobbyRepository.find(action.gameId)
val player = playerRepository.find(principal.name)
synchronized(lobby) {
lobby.addPlayer(player)
logger.info("Player '{}' ({}) joined game {}", player.displayName, player.username, lobby.name)
lobbyController.sendLobbyUpdateToPlayers(lobby)
}
return lobby.toDTO()
}
private fun checkThatUserIsNotInAGame(principal: Principal, impossibleActionDescription: String) {
val player = playerRepository.find(principal.name)
if (player.isInLobby || player.isInGame) {
throw UserAlreadyInGameException(player.lobby.name, impossibleActionDescription)
}
}
internal class UserAlreadyInGameException(gameName: String, impossibleActionDescription: String) :
ApiMisuseException("Client already in game '$gameName', $impossibleActionDescription")
companion object {
private val logger = LoggerFactory.getLogger(GameBrowserController::class.java)
}
}
|
mit
|
cb2294a91cbd6460b40501f8e5ed2f8f
| 40.12963 | 115 | 0.730527 | 4.541922 | false | false | false | false |
nfrankel/kaadin
|
kaadin-core/src/main/kotlin/ch/frankel/kaadin/DataInputTextualDate.kt
|
1
|
4898
|
/*
* Copyright 2016 Nicolas Fränkel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.frankel.kaadin
import com.vaadin.data.*
import com.vaadin.ui.*
import com.vaadin.ui.Calendar
import com.vaadin.ui.components.calendar.event.*
import java.util.*
/**
* see http://demo.vaadin.com/sampler/#ui/data-input/text-input
* see http://demo.vaadin.com/sampler/#ui/data-input/dates
*/
private fun <F : AbstractField<T>, T : Any> F.process(container: HasComponents,
caption: String?,
value: T?,
dataSource: Property<out Any>?,
init: F.() -> Unit): F {
return apply {
caption?.let { this.caption = caption }
value?.let { this.value = value }
dataSource?.let { this.propertyDataSource = dataSource }
}
.apply(init)
.addTo(container)
}
fun HasComponents.textField(caption: String? = null,
value: String = "",
init: TextField.() -> Unit = {}) = TextField()
.process(this, caption, value, null, init)
fun HasComponents.textField(caption: String? = null,
dataSource: Property<String>,
init: TextField.() -> Unit = {}) = TextField()
.process(this, caption, null, dataSource, init)
fun HasComponents.textArea(caption: String? = null,
value: String? = "",
init: TextArea.() -> Unit = {}) = TextArea()
.process(this, caption, value, null, init)
fun HasComponents.textArea(caption: String? = null,
dataSource: Property<String>,
init: TextArea.() -> Unit = {}) = TextArea()
.process(this, caption, null, dataSource, init)
fun HasComponents.richTextArea(caption: String? = null,
value: String = "",
init: RichTextArea.() -> Unit = {}) = RichTextArea()
.process(this, caption, value, null, init)
fun HasComponents.richTextArea(caption: String? = null,
dataSource: Property<String>,
init: RichTextArea.() -> Unit = {}) = RichTextArea()
.process(this, caption, null, dataSource, init)
fun HasComponents.passwordField(caption: String? = null,
value: String? = "",
init: PasswordField.() -> Unit = {}) = PasswordField()
.process(this, caption, value, null, init)
fun HasComponents.passwordField(caption: String? = null,
dataSource: Property<String>,
init: PasswordField.() -> Unit = {}) = PasswordField()
.process(this, caption, null, dataSource, init)
fun HasComponents.dateField(caption: String? = null,
value: Date? = null,
init: DateField.() -> Unit = {}) = DateField()
.process(this, caption, value, null, init)
fun HasComponents.dateField(caption: String? = null,
dataSource: Property<Date>,
init: DateField.() -> Unit = {}) = DateField()
.process(this, caption, null, dataSource, init)
fun HasComponents.inlineDateField(caption: String? = null,
value: Date? = null,
init: InlineDateField.() -> Unit = {}) = InlineDateField()
.process(this, caption, value, null, init)
fun HasComponents.inlineDateField(caption: String? = null,
dataSource: Property<Date>,
init: InlineDateField.() -> Unit = {}) = InlineDateField()
.process(this, caption, null, dataSource, init)
fun HasComponents.calendar(caption: String? = null,
eventProvider: CalendarEventProvider = BasicEventProvider(),
init: Calendar.() -> Unit = {}): Calendar {
return Calendar()
.apply {
caption?.let { this.caption = caption }
this.eventProvider = eventProvider
}
.apply(init)
.addTo(this)
}
|
apache-2.0
|
4b697c5f9060da37c0777ee0702f57a6
| 42.723214 | 92 | 0.535634 | 4.824631 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/CommandMentions.kt
|
1
|
1586
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla
import dev.kord.common.entity.DiscordApplicationCommand
/**
* Holds Discord style command mentions of Loritta's commands.
*
* Mentions are automatically validated based on the commands registered. If a command doesn't exist, the class will fail to initialize!
*/
class CommandMentions(private val registeredCommands: List<DiscordApplicationCommand>) {
val achievements = commandMention("achievements")
val daily = commandMention("daily")
val sonhosRank = commandMention("sonhos rank")
val ban = commandMention("ban")
val packageTrack = commandMention("package track")
val packageList = commandMention("package list")
val brokerInfo = commandMention("broker info")
val brokerBuy = commandMention("broker buy")
val brokerSell = commandMention("broker sell")
val brokerPortfolio = commandMention("broker portfolio")
val betCoinflipGlobal = commandMention("bet coinflip global")
val webhookSendSimple = commandMention("webhook send simple")
val webhookSendRepost = commandMention("webhook send repost")
/**
* Creates a command mention of [path]. If the command doesn't exist, an error will be thrown.
*/
private fun commandMention(path: String): String {
val rootCommandLabel = path.substringBefore(" ")
val registeredCommand = registeredCommands.firstOrNull { it.name == rootCommandLabel } ?: error("Couldn't find a command with label $rootCommandLabel!")
return "</${path}:${registeredCommand.id}>"
}
}
|
agpl-3.0
|
b5fda2ae9d3b0aa625ec07745a8df4fb
| 36.785714 | 160 | 0.734552 | 4.777108 | false | false | false | false |
LorittaBot/Loritta
|
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/transactions/SparklyPowerLSXSonhosTransactionsLog.kt
|
1
|
808
|
package net.perfectdreams.loritta.cinnamon.pudding.tables.transactions
import net.perfectdreams.exposedpowerutils.sql.postgresEnumeration
import net.perfectdreams.loritta.common.utils.SparklyPowerLSXTransactionEntryAction
import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog
import org.jetbrains.exposed.dao.id.LongIdTable
object SparklyPowerLSXSonhosTransactionsLog : LongIdTable() {
val timestampLog = reference("timestamp_log", SonhosTransactionsLog).index()
val action = postgresEnumeration<SparklyPowerLSXTransactionEntryAction>("action")
val sonhos = long("sonhos")
val sparklyPowerSonhos = long("sparklypower_sonhos")
val playerName = text("player_name")
val playerUniqueId = uuid("player_unique_id")
val exchangeRate = double("exchange_rate")
}
|
agpl-3.0
|
853aca6fcbf691738c893eccedc2a28c
| 49.5625 | 85 | 0.811881 | 4.67052 | false | false | false | false |
NoodleMage/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/ConductorExtensions.kt
|
3
|
1226
|
package eu.kanade.tachiyomi.ui.base.controller
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Build
import android.support.v4.content.ContextCompat
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
fun Router.popControllerWithTag(tag: String): Boolean {
val controller = getControllerWithTag(tag)
if (controller != null) {
popController(controller)
return true
}
return false
}
fun Controller.requestPermissionsSafe(permissions: Array<String>, requestCode: Int) {
val activity = activity ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
permissions.forEach { permission ->
if (ContextCompat.checkSelfPermission(activity, permission) != PERMISSION_GRANTED) {
requestPermissions(arrayOf(permission), requestCode)
}
}
}
}
fun Controller.withFadeTransaction(): RouterTransaction {
return RouterTransaction.with(this)
.pushChangeHandler(FadeChangeHandler())
.popChangeHandler(FadeChangeHandler())
}
|
apache-2.0
|
d838ef53c526cbdc6bef251e6c582eb7
| 34.028571 | 96 | 0.736542 | 4.884462 | false | false | false | false |
AlmasB/GroupNet
|
src/main/kotlin/icurves/diagram/Curve.kt
|
1
|
2117
|
package icurves.diagram
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import icurves.diagram.curve.CircleCurve
import icurves.diagram.curve.PathCurve
import icurves.util.Label
import javafx.beans.property.DoubleProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.geometry.Point2D
import javafx.scene.shape.Shape
import math.geom2d.polygon.Polygon2D
/**
* A closed curve, c (element of C).
*
* @author Almas Baimagambetov ([email protected])
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes(
JsonSubTypes.Type(CircleCurve::class),
JsonSubTypes.Type(PathCurve::class)
)
abstract class Curve(val label: Label) : Comparable<Curve> {
private val labelPositionX = SimpleDoubleProperty()
private val labelPositionY = SimpleDoubleProperty()
fun labelPositionXProperty(): DoubleProperty = labelPositionX
fun labelPositionYProperty(): DoubleProperty = labelPositionY
fun getLabelPositionX(): Double = labelPositionX.value
fun getLabelPositionY(): Double = labelPositionY.value
fun setLabelPositionX(value: Double) {
labelPositionX.value = value
}
fun setLabelPositionY(value: Double) {
labelPositionY.value = value
}
val cachedPolygon by lazy { computePolygon() }
val cachedShape by lazy { computeShape() }
/**
* @return a curve model for computational geometry.
*/
fun getPolygon() = computePolygon()
/**
* @return a bitmap view for rendering.
*/
fun getShape() = computeShape()
abstract fun computePolygon(): Polygon2D
abstract fun computeShape(): Shape
abstract fun copyWithNewLabel(newLabel: String): Curve
abstract fun translate(translate: Point2D): Curve
abstract fun scale(scale: Double, pivot: Point2D): Curve
abstract fun toDebugString(): String
override fun compareTo(other: Curve): Int {
return label.compareTo(other.label)
}
override fun toString() = label
}
|
apache-2.0
|
331a119b120e2406b67c8c855c99f092
| 26.153846 | 65 | 0.721304 | 4.485169 | false | false | false | false |
ryuta46/eval-spec-maker
|
project/src/main/kotlin/com/ryuta46/evalspecmaker/MarkdownParser.kt
|
1
|
2830
|
package com.ryuta46.evalspecmaker
import com.ryuta46.evalspecmaker.util.Logger
import org.pegdown.PegDownProcessor
import org.pegdown.ast.*
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.Locale
object MarkdownParser {
val logger = Logger(this.javaClass.simpleName)
@Throws(IOException::class)
internal fun parse(file: String): TestItem {
logger.trace {
val inputMarkdown = File(file)
val buff = CharArray(inputMarkdown.length().toInt())
FileReader(inputMarkdown).use { reader ->
reader.read(buff)
val processor = PegDownProcessor()
val rootNode = processor.parseMarkdown(buff)
val rootItem = TestItem().apply { level = 0 }
convertToTestItem(rootNode, mutableListOf(rootItem))
return rootItem
}
}
}
private fun convertToTestItem(node: Node, parentStack: MutableList<TestItem>) {
logger.trace {
if (node is HeaderNode) {
val nodeLevel = node.level
logger.i(String.format(Locale.JAPAN, "h%d", nodeLevel))
// 自分より階層が上の直近のノードを親する
parentStack.removeAll{ it.level >= nodeLevel }
val target = parentStack.lastOrNull() ?: return
val newItem = TestItem().apply { level = nodeLevel }
target.addChild(newItem)
parentStack.add(newItem)
} else {
val target = parentStack.lastOrNull() ?: return
when(node) {
is TextNode -> {
val text = node.text.trim { it <= ' ' }
if (!text.isEmpty()) {
logger.i(String.format(Locale.JAPAN, "text:%s", text))
target.addText(text)
}
}
is ListItemNode -> target.setAddTarget(TestItem.TextContainer.METHOD)
is RefLinkNode -> target.setAddTarget(TestItem.TextContainer.CONFIRM)
else -> logger.d("Class:" + node.javaClass.name)
}
}
for (childNode in node.children) {
convertToTestItem(childNode, parentStack)
}
}
}
private fun printNode(node: Node, level: Int) {
logger.trace {
val builder = StringBuilder()
for (i in 0..level - 1) {
builder.append("-")
}
val prefix = builder.toString()
println(prefix + node.javaClass.name)
for (childNode in node.children) {
printNode(childNode, level+1)
}
}
}
}
|
mit
|
25384f21d771ee88e33ca96601897d70
| 31.465116 | 89 | 0.52937 | 4.676717 | false | true | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/ui/theme/Theme.kt
|
1
|
1116
|
package mil.nga.giat.mage.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val LightColorPalette = lightColors(
primary = Blue600,
primaryVariant = Blue800,
secondary = OrangeA700,
error = Red800
)
private val DarkColorPalette = darkColors(
primary = Grey800,
primaryVariant = Grey800,
secondary = BlueA200,
error = Red300,
onPrimary = Color.White
)
@Composable
fun MageTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) DarkColorPalette else LightColorPalette
MaterialTheme(
colors = colors,
content = content
)
}
val Colors.warning: Color @Composable get() = Amber700
val Colors.topAppBarBackground: Color @Composable get() = primary
val Colors.importantBackground: Color @Composable get() = OrangeA400
val Colors.linkColor: Color @Composable get() {
return if (isSystemInDarkTheme()) MaterialTheme.colors.onSurface.copy(alpha = ContentAlpha.medium) else primary
}
|
apache-2.0
|
6f37ea7c8628a748965133e5313513fa
| 26.243902 | 112 | 0.767025 | 4.275862 | false | false | false | false |
ruuvi/Android_RuuvitagScanner
|
app/src/main/java/com/ruuvi/station/receivers/RebootSchedulerReceiver.kt
|
2
|
1405
|
package com.ruuvi.station.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import com.ruuvi.station.bluetooth.BluetoothForegroundService
import com.ruuvi.station.bluetooth.ScanningPeriodicReceiver
import com.ruuvi.station.util.BackgroundScanModes
import com.ruuvi.station.app.preferences.Preferences
import timber.log.Timber
class RebootSchedulerReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Timber.d("ruuvi.BOOT_COMPLETED.onReceive")
context?.let {
val prefs = Preferences(it)
Timber.d("Start from reboot")
if (prefs.backgroundScanMode == BackgroundScanModes.BACKGROUND) {
ScanningPeriodicReceiver.start(it, prefs.backgroundScanInterval * 1000L)
startForegroundService(it)
} else {
Timber.d("Background scan disabled")
}
}
}
private fun startForegroundService(context: Context) {
Timber.d("startForegroundService after reboot")
val serviceIntent = Intent(context, BluetoothForegroundService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
}
|
mit
|
fb8c9f90bf1e3405c25a7128f42a90f9
| 37 | 88 | 0.697509 | 4.844828 | false | false | false | false |
DUCodeWars/TournamentFramework
|
src/main/java/org/DUCodeWars/framework/server/tournament/KnockoutStage.kt
|
2
|
1933
|
package org.DUCodeWars.framework.server.tournament
import org.DUCodeWars.framework.server.AbstractGame
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.server.Server
import org.DUCodeWars.framework.server.shuffle
class KnockoutStage(val gameCreator: (List<PlayerConnection>, TournamentStage) -> AbstractGame,
server: Server,
childStage: ChildStage?,
numberOfPlayersProgressing: Int) :
TournamentStage(server = server,
childStage = childStage,
numberOfPlayersProgressing = numberOfPlayersProgressing) {
override fun getGameIterator(players: Set<PlayerConnection>): Iterator<AbstractGame> {
return KnockoutStageIterator(players, gameCreator, this)
}
override fun toString(): String {
return javaClass.simpleName
}
class KnockoutStageIterator(val players: Set<PlayerConnection>,
val gameCreator: (List<PlayerConnection>, TournamentStage) -> AbstractGame,
val tournamentStage: TournamentStage) : Iterator<AbstractGame> {
val kickoutOrder: MutableList<PlayerConnection> = mutableListOf()
var started = false
override fun hasNext(): Boolean {
val targetKickoutSize = players.size - tournamentStage.numberOfPlayersProgressing
return kickoutOrder.size == targetKickoutSize
}
override fun next(): AbstractGame {
if(started){
kickoutOrder.add(tournamentStage.currentPoints.minBy { it.value }!!.key)
return gameCreator(players.minus(kickoutOrder).toList().shuffle(), tournamentStage)
}
else{
started = true
return gameCreator(players.toList().shuffle(), tournamentStage)
}
}
}
}
|
mit
|
519906ade408fa7bb748c5e670ba75a9
| 40.148936 | 107 | 0.646146 | 5.210243 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/conveyorbelt/BoxedItem.kt
|
2
|
4024
|
package com.cout970.magneticraft.systems.tilemodules.conveyorbelt
import com.cout970.magneticraft.AABB
import com.cout970.magneticraft.IVector3
import com.cout970.magneticraft.api.conveyorbelt.Route
import com.cout970.magneticraft.misc.add
import com.cout970.magneticraft.misc.newNbt
import com.cout970.magneticraft.misc.vector.*
import com.cout970.magneticraft.systems.tilerenderers.PIXEL
import com.cout970.magneticraft.systems.tilerenderers.Utilities
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
data class BoxedItem(
val item: ItemStack,
var position: Float,
val route: Route,
var lastTick: Long,
var locked: Boolean = false
) {
constructor(nbt: NBTTagCompound) : this(
ItemStack(nbt.getCompoundTag("item")),
nbt.getFloat("position"),
Route.values()[nbt.getInteger("route")],
-1L
)
fun move(amount: Float) {
position += amount
}
fun getPos(partialTicks: Float): IVector3 {
val pos = position + if (locked) 0f else partialTicks
if (route.isRect) {
val z = Utilities.interpolate(16f, 0f, pos / 16.0f) * PIXEL
val x = when (route) {
Route.LEFT_FORWARD -> 5 * PIXEL
Route.RIGHT_FORWARD -> 11 * PIXEL
else -> 0.0
}
return vec3Of(x, 0, z)
} else if (route.leftSide) {
val x: Double
val z: Double
if (route.isShort) {
if (pos < 8f) {
x = Utilities.interpolate(0f, 5f, pos / 8.0f) * PIXEL
z = 5 * PIXEL
} else {
x = 5 * PIXEL
z = Utilities.interpolate(5f, 0f, (pos - 8f) / 8f) * PIXEL
}
} else if (route == Route.LEFT_CORNER) {
if (pos < 8f) {
x = Utilities.interpolate(16f, 5f, pos / 8f) * PIXEL
z = 11 * PIXEL
} else {
x = 5f * PIXEL
z = Utilities.interpolate(11f, 0f, (pos - 8f) / 8f) * PIXEL
}
} else {
if (pos < 5f) {
x = Utilities.interpolate(0f, 5f, pos / 5.0f) * PIXEL
z = 11 * PIXEL
} else {
x = 5 * PIXEL
z = Utilities.interpolate(11f, 0f, (pos - 5) / 11.0f) * PIXEL
}
}
return vec3Of(x, 0, z)
} else if (!route.leftSide) {
val x: Double
val z: Double
if (route.isShort) {
if (pos < 8f) {
x = Utilities.interpolate(16f, 11f, pos / 8f) * PIXEL
z = 5 * PIXEL
} else {
x = 11 * PIXEL
z = Utilities.interpolate(5f, 0f, (pos - 8f) / 8f) * PIXEL
}
} else if (route == Route.RIGHT_CORNER) {
if (pos < 8f) {
x = Utilities.interpolate(0f, 11f, pos / 8f) * PIXEL
z = 11f * PIXEL
} else {
x = 11f * PIXEL
z = Utilities.interpolate(11f, 0f, (pos - 8f) / 8f) * PIXEL
}
} else {
if (pos < 5f) {
x = Utilities.interpolate(16f, 11f, pos / 5f) * PIXEL
z = 11 * PIXEL
} else {
x = 11 * PIXEL
z = Utilities.interpolate(11f, 0f, (pos - 5f) / 11f) * PIXEL
}
}
return vec3Of(x, 0.0, z)
}
return vec3Of(0.0, 0.0, 0.0)
}
fun getHitBox(): AABB {
val pos = getPos(0f)
return (pos - vec3Of(2, 0, 2) * PIXEL) createAABBUsing (pos + vec3Of(2, 4, 2) * PIXEL)
}
fun serializeNBT() = newNbt {
add("item", item.serializeNBT())
add("position", position)
add("route", route.ordinal)
}
}
|
gpl-2.0
|
3264208aaeae505643f2d33c8c795e4a
| 31.459677 | 94 | 0.472913 | 3.941234 | false | false | false | false |
f-droid/fdroidclient
|
libs/index/src/androidMain/kotlin/org/fdroid/index/v2/IndexV2FullStreamProcessor.kt
|
1
|
4251
|
package org.fdroid.index.v2
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.decodeFromStream
import org.fdroid.index.IndexParser
import java.io.InputStream
@OptIn(ExperimentalSerializationApi::class)
public class IndexV2FullStreamProcessor(
private val indexStreamReceiver: IndexV2StreamReceiver,
private val certificate: String,
private val json: Json = IndexParser.json,
) : IndexV2StreamProcessor {
@Throws(SerializationException::class, IllegalStateException::class)
public override fun process(
version: Long,
inputStream: InputStream,
onAppProcessed: (Int) -> Unit,
) {
json.decodeFromStream(IndexStreamSerializer(version, onAppProcessed), inputStream)
}
private inner class IndexStreamSerializer(
val version: Long,
private val onAppProcessed: (Int) -> Unit,
) : KSerializer<IndexV2?> {
override val descriptor = IndexV2.serializer().descriptor
private var appsProcessed: Int = 0
override fun deserialize(decoder: Decoder): IndexV2? {
decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
decoder.beginStructure(descriptor)
val repoIndex = descriptor.getElementIndex("repo")
val packagesIndex = descriptor.getElementIndex("packages")
when (val startIndex = decoder.decodeElementIndex(descriptor)) {
repoIndex -> {
deserializeRepo(decoder, startIndex)
val index = decoder.decodeElementIndex(descriptor)
if (index == packagesIndex) deserializePackages(decoder, index)
}
packagesIndex -> {
deserializePackages(decoder, startIndex)
val index = decoder.decodeElementIndex(descriptor)
if (index == repoIndex) deserializeRepo(decoder, index)
}
else -> error("Unexpected startIndex: $startIndex")
}
var currentIndex = 0
while (currentIndex != DECODE_DONE) {
currentIndex = decoder.decodeElementIndex(descriptor)
}
decoder.endStructure(descriptor)
indexStreamReceiver.onStreamEnded()
return null
}
private fun deserializeRepo(decoder: JsonDecoder, index: Int) {
require(index == descriptor.getElementIndex("repo"))
val repo = decoder.decodeSerializableValue(RepoV2.serializer())
indexStreamReceiver.receive(repo, version, certificate)
}
private fun deserializePackages(decoder: JsonDecoder, index: Int) {
require(index == descriptor.getElementIndex("packages"))
val mapDescriptor = descriptor.getElementDescriptor(index)
val compositeDecoder = decoder.beginStructure(mapDescriptor)
while (true) {
val packageIndex = compositeDecoder.decodeElementIndex(descriptor)
if (packageIndex == DECODE_DONE) break
readMapEntry(compositeDecoder, packageIndex)
appsProcessed += 1
onAppProcessed(appsProcessed)
}
compositeDecoder.endStructure(mapDescriptor)
}
private fun readMapEntry(decoder: CompositeDecoder, index: Int) {
val packageName = decoder.decodeStringElement(descriptor, index)
decoder.decodeElementIndex(descriptor)
val packageV2 = decoder.decodeSerializableElement(
descriptor, index + 1, PackageV2.serializer()
)
indexStreamReceiver.receive(packageName, packageV2)
}
override fun serialize(encoder: Encoder, value: IndexV2?) {
error("Not implemented")
}
}
}
|
gpl-3.0
|
4af6701bab298f46f68545ad9f2331d1
| 40.676471 | 90 | 0.662903 | 5.422194 | false | false | false | false |
SUPERCILEX/Robot-Scouter
|
library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/Contexts.kt
|
1
|
4317
|
package com.supercilex.robotscouter.core.ui
import android.content.Intent
import android.graphics.Rect
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.EditText
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceFragmentCompat
import com.google.firebase.analytics.FirebaseAnalytics
interface OnActivityResult {
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
}
abstract class ActivityBase : AppCompatActivity(), OnActivityResult, KeyboardShortcutListener {
private val filteredEvents = mutableMapOf<Long, KeyEvent>()
private var clearFocus: Runnable? = null
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
event.also { filteredEvents[it.downTime] = it }
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (filteredEvents.remove(event.downTime) != null) {
if (onShortcut(keyCode, event)) return true
val fragmentHandled = supportFragmentManager.fragments
.filterIsInstance<KeyboardShortcutListener>()
.any { it.onShortcut(keyCode, event) }
if (fragmentHandled) return true
}
return super.onKeyUp(keyCode, event)
}
override fun onShortcut(keyCode: Int, event: KeyEvent) = false
@Suppress("RedundantOverride") // Needed to relax visibility
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) =
super.onActivityResult(requestCode, resultCode, data)
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val v: View? = currentFocus
if (ev.action == MotionEvent.ACTION_DOWN && v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
clearFocus = Runnable {
if (currentFocus === v || currentFocus !is EditText) {
v.clearFocus()
v.hideKeyboard()
}
clearFocus = null
}.also {
v.postDelayed(it, shortAnimationDuration)
}
}
} else if (
ev.action == MotionEvent.ACTION_MOVE && clearFocus != null &&
ev.eventTime - ev.downTime > shortAnimationDuration / 2
) {
v?.removeCallbacks(clearFocus)
}
return super.dispatchTouchEvent(ev)
}
}
abstract class FragmentBase(
@LayoutRes contentLayoutId: Int = 0
) : Fragment(contentLayoutId), OnActivityResult {
override fun onResume() {
super.onResume()
val screenName = javaClass.simpleName
FirebaseAnalytics.getInstance(requireContext())
.setCurrentScreen(requireActivity(), screenName, screenName)
}
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
if (nextAnim == 0) return null
val animation = AnimationUtils.loadAnimation(activity, nextAnim)
val view = view
if (animation != null && view != null) {
val prevType = view.layerType
view.setLayerType(View.LAYER_TYPE_HARDWARE, null)
animation.setAnimationListener(object : AnimationListener {
override fun onAnimationEnd(animation: Animation) =
view.setLayerType(prevType, null)
override fun onAnimationRepeat(animation: Animation?) = Unit
override fun onAnimationStart(animation: Animation?) = Unit
})
}
return animation
}
}
abstract class PreferenceFragmentBase : PreferenceFragmentCompat(), OnActivityResult {
override fun onResume() {
super.onResume()
val screenName = javaClass.simpleName
FirebaseAnalytics.getInstance(requireContext())
.setCurrentScreen(requireActivity(), screenName, screenName)
}
}
|
gpl-3.0
|
ff30f538afc2fb79bfbb0ce275c39c3c
| 37.20354 | 95 | 0.653695 | 5.251825 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android
|
example/src/main/java/org/wordpress/android/fluxc/example/SiteSelectorDialog.kt
|
2
|
4414
|
package org.wordpress.android.fluxc.example
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import dagger.android.support.AndroidSupportInjection
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.SiteActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.SiteStore.FetchSitesPayload
import org.wordpress.android.fluxc.store.SiteStore.OnSiteChanged
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import javax.inject.Inject
class SiteSelectorDialog : DialogFragment() {
companion object {
@JvmStatic
fun newInstance(listener: Listener, selectedPos: Int) = SiteSelectorDialog().apply {
this.listener = listener
this.selectedPos = selectedPos
}
}
interface Listener {
fun onSiteSelected(site: SiteModel, pos: Int)
}
@Inject internal lateinit var dispatcher: Dispatcher
@Inject internal lateinit var siteStore: SiteStore
var listener: Listener? = null
var selectedPos: Int = -1
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onStart() {
super.onStart()
dispatcher.register(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// get sites from api
if (siteStore.sites.isEmpty()) {
dispatcher.dispatch(SiteActionBuilder.newFetchSitesAction(FetchSitesPayload()))
}
}
override fun onStop() {
super.onStop()
dispatcher.unregister(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val adapter = SiteAdapter(requireActivity(), siteStore.sites)
// Use the Builder class for convenient dialog construction
val builder = AlertDialog.Builder(requireActivity())
builder.setTitle("Select a site")
.setSingleChoiceItems(adapter, selectedPos) { dialog, which ->
val adapter = (dialog as AlertDialog).listView.adapter as SiteAdapter
val site = adapter.getItem(which)
if (site != null) {
listener?.onSiteSelected(site, which)
} else {
prependToLog("SiteChanged error: site at position $which was null.")
}
dialog.dismiss()
}
// Create the AlertDialog object and return it
return builder.create()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onSiteChanged(event: OnSiteChanged) {
if (event.isError) {
AppLog.e(T.TESTS, "SiteChanged error: " + event.error?.type)
prependToLog("SiteChanged error: " + event.error?.type)
} else {
prependToLog("SiteChanged: rowsAffected = " + event.rowsAffected)
siteStore.sites?.let {
val adapter = (dialog as AlertDialog).listView.adapter as SiteAdapter
adapter.refreshSites(it)
}
}
}
class SiteAdapter(
ctx: Context,
items: List<SiteModel>
) : ArrayAdapter<SiteModel>(ctx, android.R.layout.simple_list_item_1, items) {
fun refreshSites(newItems: List<SiteModel>) {
setNotifyOnChange(true)
addAll(newItems)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val cv = convertView
?: LayoutInflater.from(context)
.inflate(android.R.layout.simple_list_item_single_choice, parent, false)
val site = getItem(position)
(cv as TextView).text = site?.displayName ?: site?.name
return cv
}
override fun getItemId(position: Int) = getItem(position)!!.id.toLong()
override fun hasStableIds() = true
}
}
|
gpl-2.0
|
e1591d46469e100e582493de1b05de64
| 34.312 | 100 | 0.652923 | 4.839912 | false | true | false | false |
andycondon/pathfinder-gps
|
src/main/kotlin/io/frontierrobotics/gps/SerialReader.kt
|
1
|
964
|
package io.frontierrobotics.gps
import com.fazecast.jSerialComm.SerialPort
import io.frontierrobotics.gps.nmea.GPRMC
import java.io.Closeable
class SerialReader(portDescriptor: String) : Closeable {
val serialPort = SerialPort.getCommPort(portDescriptor)
init {
serialPort.openPort()
}
override fun close() {
serialPort.closePort()
}
fun readSentence(): GPRMC {
while (serialPort.bytesAvailable() == 0) {
Thread.sleep(20);
}
val bytesAvailable: Int = serialPort.bytesAvailable()
println("Bytes Available: " + bytesAvailable)
val readBuffer = ByteArray(bytesAvailable)
val numRead = serialPort.readBytes(readBuffer, bytesAvailable.toLong())
println("Bytes Read: " + numRead)
val sentence = String(readBuffer)
return GPRMC(sentence)
}
override fun toString(): String {
return "${serialPort.baudRate} baud"
}
}
|
mit
|
8a1d4e212a492f04a00363dee181da7e
| 22.536585 | 79 | 0.656639 | 4.265487 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.