repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-utils/src/main/java/com/safframework/utils/SAFUtils.kt | 1 | 2396 | package com.safframework.utils
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import java.io.File
/**
* Created by Tony Shen on 2017/1/17.
*/
/**
* 调用该方法需要申请权限
* <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
*/
fun isWiFiActive(context: Context): Boolean {
var wm: WifiManager? = null
try {
wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
} catch (e: Exception) {
e.printStackTrace()
}
return wm!=null && wm.isWifiEnabled
}
/**
* 安装apk
* @param fileName apk文件的绝对路径
*
* @param context
*/
fun installAPK(fileName: String, context: Context) {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.fromFile(File(fileName)), "application/vnd.android.package-archive")
context.startActivity(intent)
}
/**
* 检测网络状态
* @param context
*
* @return
*/
fun checkNetworkStatus(context: Context): Boolean {
var resp = false
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetInfo = connMgr.activeNetworkInfo
if (activeNetInfo != null && activeNetInfo.isAvailable) {
resp = true
}
return resp
}
/**
* 检测gps状态
* @param context
*
* @return
*/
fun checkGPSStatus(context: Context): Boolean {
var resp = false
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
resp = true
}
return resp
}
/**
* 生成app日志tag
* 可以这样使用: SAFUtils.makeLogTag(this.getClass());
* @param cls
*
* @return
*/
fun makeLogTag(cls: Class<*>): String {
return cls.simpleName
}
/**
* 获取AndroidManifest.xml中<meta-data>元素的值
* @param context
*
* @param name
*
* @return
*/
fun <T> getMetaData(context: Context, name: String): T? {
try {
val ai = context.packageManager.getApplicationInfo(context.packageName,
PackageManager.GET_META_DATA)
return ai.metaData?.get(name) as T
} catch (e: Exception) {
print("Couldn't find meta-data: " + name)
}
return null
} | apache-2.0 | 8d4e03d09959a11505ab9b93b65ac410 | 21.144231 | 98 | 0.685056 | 3.743089 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransitRegion.kt | 1 | 4286 | /*
* TransitRegion.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.multi.StringResource
import au.id.micolous.metrodroid.util.iso3166AlphaToName
import au.id.micolous.metrodroid.util.Collator
import au.id.micolous.metrodroid.util.Preferences
sealed class TransitRegion {
abstract val translatedName: String
open val sortingKey: Pair<Int, String>
get() = Pair(SECTION_MAIN, translatedName)
data class Iso (val code: String): TransitRegion () {
override val translatedName: String
get() = iso3166AlphaToName(code) ?: code
override val sortingKey: Pair<Int, String>
get() = Pair(
if (code == deviceRegion) SECTION_NEARBY else SECTION_MAIN,
translatedName)
}
object Crimea : TransitRegion () {
override val translatedName: String
get() = Localizer.localizeString(R.string.location_crimea)
override val sortingKey
get() = Pair(
if (deviceRegion in listOf("RU", "UA")) SECTION_NEARBY else SECTION_MAIN,
translatedName)
}
data class SectionItem(val res: StringResource,
val section: Int): TransitRegion () {
override val translatedName: String
get() = Localizer.localizeString(res)
override val sortingKey
get() = Pair(section, translatedName)
}
object RegionComparator : Comparator<TransitRegion> {
val collator = Collator.collator
override fun compare(a: TransitRegion, b: TransitRegion): Int {
val ak = a.sortingKey
val bk = b.sortingKey
if (ak.first != bk.first) {
return ak.first.compareTo(bk.first)
}
return collator.compare(ak.second, bk.second)
}
}
companion object {
// On very top put cards tha are most likely to be relevant to the user
const val SECTION_NEARBY = -2
// Then put "Worldwide" cards like EMV and Amiibo
const val SECTION_WORLDWIDE = -1
// Then goes the rest
const val SECTION_MAIN = 0
private val deviceRegion = Preferences.region
val AUSTRALIA = Iso("AU")
val BELGIUM = Iso("BE")
val BRAZIL = Iso("BR")
val CANADA = Iso("CA")
val CHILE = Iso("CL")
val CHINA = Iso("CN")
val CRIMEA = Crimea
val DENMARK = Iso("DK")
val ESTONIA = Iso("EE")
val FINLAND = Iso("FI")
val FRANCE = Iso("FR")
val GEORGIA = Iso("GE")
val GERMANY = Iso("DE")
val HONG_KONG = Iso("HK")
val INDONESIA = Iso("ID")
val IRELAND = Iso("IE")
val ISRAEL = Iso("IL")
val ITALY = Iso("IT")
val JAPAN = Iso("JP")
val MALAYSIA = Iso("MY")
val NETHERLANDS = Iso("NL")
val NEW_ZEALAND = Iso("NZ")
val POLAND = Iso("PL")
val PORTUGAL = Iso("PT")
val RUSSIA = Iso("RU")
val SINGAPORE = Iso("SG")
val SOUTH_AFRICA = Iso("ZA")
val SOUTH_KOREA = Iso("KR")
val SPAIN = Iso("ES")
val SWEDEN = Iso("SE")
val SWITZERLAND = Iso("CH")
val TAIPEI = Iso("TW")
val TURKEY = Iso("TR")
val UAE = Iso("AE")
val UK = Iso("GB")
val UKRAINE = Iso("UA")
val USA = Iso("US")
val WORLDWIDE = SectionItem(R.string.location_worldwide,
SECTION_WORLDWIDE)
}
}
| gpl-3.0 | c86b62e487d7789f5e86fd4f9ed0f353 | 35.016807 | 90 | 0.60126 | 4.005607 | false | false | false | false |
JavaEden/Orchid-Core | integrations/OrchidGithub/src/main/kotlin/com/eden/orchid/github/wiki/GithubWikiAdapter.kt | 2 | 5647 | package com.eden.orchid.github.wiki
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.annotations.Validate
import com.eden.orchid.api.resources.resource.FileResource
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.api.util.GitFacade
import com.eden.orchid.api.util.GitRepoFacade
import com.eden.orchid.utilities.OrchidUtils
import com.eden.orchid.utilities.SuppressedWarnings
import com.eden.orchid.wiki.adapter.WikiAdapter
import com.eden.orchid.wiki.model.WikiSection
import com.eden.orchid.wiki.pages.WikiPage
import com.eden.orchid.wiki.pages.WikiSummaryPage
import com.eden.orchid.wiki.utils.WikiUtils
import org.apache.commons.io.FilenameUtils
import java.io.File
import javax.inject.Inject
import javax.validation.constraints.NotBlank
@Validate
@Suppress(SuppressedWarnings.UNUSED_PARAMETER)
class GithubWikiAdapter
@Inject
constructor(
val context: OrchidContext,
val git: GitFacade
) : WikiAdapter {
@Option
@Description("The repository to push to, as [username/repo].")
@NotBlank(message = "Must set the GitHub repository.")
lateinit var repo: String
@Option
@StringDefault("github.com")
@Description("The URL for a self-hosted Github Enterprise installation.")
@NotBlank
lateinit var githubUrl: String
@Option
@StringDefault("master")
lateinit var branch: String
override fun getType(): String = "github"
override fun loadWikiPages(section: WikiSection): Pair<WikiSummaryPage, List<WikiPage>>? {
val repo = git.clone(remoteUrl, displayedRemoteUrl, branch, false)
var sidebarFile: File? = null
var footerFile: File? = null // ignored for now
val wikiPageFiles = mutableListOf<File>()
repo.repoDir.toFile()
.walk()
.filter { it.isFile }
.filter { it.exists() }
.filter { !OrchidUtils.normalizePath(it.absolutePath).contains("/.git/") }
.forEach { currentFile ->
if (currentFile.nameWithoutExtension == "_Sidebar") {
sidebarFile = currentFile
} else if (currentFile.nameWithoutExtension == "_Footer") {
footerFile = currentFile
} else {
wikiPageFiles.add(currentFile)
}
}
val wikiContent = if (sidebarFile != null) {
createSummaryFileFromSidebar(repo, section, sidebarFile!!, wikiPageFiles)
} else {
createSummaryFileFromPages(repo, section, wikiPageFiles)
}
if(footerFile != null) {
addFooterComponent(wikiContent.second, footerFile!!)
}
return wikiContent
}
// Cloning Wiki
//----------------------------------------------------------------------------------------------------------------------
private val displayedRemoteUrl: String
get() = "https://$githubUrl/$repo.wiki.git"
private val remoteUrl: String
get() = "https://$githubUrl/$repo.wiki.git"
// Formatting Wiki files to Orchid's wiki format
//----------------------------------------------------------------------------------------------------------------------
private fun createSummaryFileFromSidebar(
repo: GitRepoFacade,
section: WikiSection,
sidebarFile: File,
wikiPages: MutableList<File>
): Pair<WikiSummaryPage, List<WikiPage>> {
val summary = FileResource(
OrchidReference(
context,
FileResource.pathFromFile(sidebarFile, repo.repoDir.toFile())
),
sidebarFile
)
return WikiUtils.createWikiFromSummaryFile(context, section, summary) { linkName, linkTarget, _ ->
val referencedFile = wikiPages.firstOrNull {
val filePath = FilenameUtils.removeExtension(it.relativeTo(repo.repoDir.toFile()).path)
filePath == linkTarget
}
if(referencedFile == null) {
Clog.w("Page referenced in Github Wiki $repo, $linkTarget does not exist")
StringResource(OrchidReference(context, "wiki/${section.key}/$linkTarget/index.md"), linkName)
}
else {
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(referencedFile, repo.repoDir.toFile())
),
referencedFile
)
}
}
}
private fun createSummaryFileFromPages(
repo: GitRepoFacade,
section: WikiSection,
wikiPageFiles: MutableList<File>
): Pair<WikiSummaryPage, List<WikiPage>> {
val wikiPages = wikiPageFiles.map {
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(it, repo.repoDir.toFile())
),
it
)
}
return WikiUtils.createWikiFromResources(context, section, wikiPages)
}
private fun addFooterComponent(wikiPages: List<WikiPage>, footerFile: File) {
// wikiPages.forEach {
// it.components.add(
// JSONObject().apply {
// put("type", "template")
//
// }
// )
// }
}
}
| mit | 61828c02a59a938fcce4af006c7b8734 | 33.644172 | 120 | 0.599433 | 4.966579 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/TryFinally.kt | 9 | 604 | // WITH_STDLIB
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
private fun unzip(zip: ZipFile) {
var errorUnpacking = false
try {
zip.let { zipFile ->
val entries: Enumeration<*> = zipFile.entries()
while (entries.hasMoreElements()) {
val nextElement = entries.nextElement()
nextElement as ZipEntry
}
}
errorUnpacking = false
}
finally {
if (<weak_warning descr="Value of 'errorUnpacking' is always false">errorUnpacking</weak_warning>) {
}
}
}
| apache-2.0 | 9a5b0dbc45650771dbaaf916b830320f | 26.454545 | 108 | 0.586093 | 4.541353 | false | false | false | false |
GunoH/intellij-community | platform/execution/src/com/intellij/execution/target/TargetedCommandLine.kt | 2 | 4569 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.target
import com.intellij.execution.CommandLineUtil
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.ExecutionException
import com.intellij.execution.target.value.TargetValue
import com.intellij.util.execution.ParametersListUtil
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.collectResults
import java.nio.charset.Charset
import java.util.concurrent.TimeoutException
/**
* Command line that can be executed on any [TargetEnvironment].
*
*
* Exe-path, working-directory and other properties are initialized in a lazy way,
* that allows to create a command line before creating a target where it should be run.
*
* @see TargetedCommandLineBuilder
*/
class TargetedCommandLine internal constructor(private val exePath: TargetValue<String>,
private val _workingDirectory: TargetValue<String>,
private val _inputFilePath: TargetValue<String>,
val charset: Charset,
private val parameters: List<TargetValue<String>>,
private val environment: Map<String, TargetValue<String>>,
val isRedirectErrorStream: Boolean,
val ptyOptions: PtyOptions?) {
/**
* [com.intellij.execution.configurations.GeneralCommandLine.getPreparedCommandLine]
*/
@Throws(ExecutionException::class)
fun getCommandPresentation(target: TargetEnvironment): String {
val exePath = exePath.targetValue.resolve("exe path")
?: throw ExecutionException(ExecutionBundle.message("targeted.command.line.exe.path.not.set"))
val parameters = parameters.map { it.targetValue.resolve("parameter") }
val targetPlatform = target.targetPlatform.platform
return CommandLineUtil.toCommandLine(ParametersListUtil.escape(exePath), parameters, targetPlatform).joinToString(separator = " ")
}
@Throws(ExecutionException::class)
fun collectCommandsSynchronously(): List<String> =
try {
collectCommands().blockingGet(0)!!
}
catch (e: java.util.concurrent.ExecutionException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.collector.failed"), e)
}
catch (e: TimeoutException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.collector.failed"), e)
}
fun collectCommands(): Promise<List<String>> {
val promises: MutableList<Promise<String>> = ArrayList(parameters.size + 1)
promises.add(exePath.targetValue.then { command: String? ->
checkNotNull(command) { "Resolved value for exe path is null" }
command
})
for (parameter in parameters) {
promises.add(parameter.targetValue)
}
return promises.collectResults()
}
@get:Throws(ExecutionException::class)
val workingDirectory: String?
get() = _workingDirectory.targetValue.resolve("working directory")
@get:Throws(ExecutionException::class)
val inputFilePath: String?
get() = _inputFilePath.targetValue.resolve("input file path")
@get:Throws(ExecutionException::class)
val environmentVariables: Map<String, String>
get() = environment.mapValues { (name, value) ->
value.targetValue.resolve("environment variable $name")
?: throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolved.env.value.is.null", name))
}
override fun toString(): String =
listOf(exePath).plus(parameters).joinToString(
separator = " ",
prefix = super.toString() + ": ",
transform = { promise ->
runCatching { promise.targetValue.blockingGet(0) }.getOrElse { if (it is TimeoutException) "..." else "<ERROR>" } ?: ""
}
)
companion object {
@Throws(ExecutionException::class)
private fun Promise<String>.resolve(debugName: String): String? =
try {
blockingGet(0)
}
catch (e: java.util.concurrent.ExecutionException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolver.failed.for", debugName), e)
}
catch (e: TimeoutException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolver.failed.for", debugName), e)
}
}
} | apache-2.0 | 78099cb381448b9aee21018956e717ad | 42.942308 | 140 | 0.683519 | 4.950163 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InternalDeclarationConversion.kt | 2 | 1946 | // 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.nj2k.conversions
import com.intellij.psi.PsiMember
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.*
import org.jetbrains.kotlin.nj2k.tree.Visibility.*
class InternalDeclarationConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKVisibilityOwner || element !is JKModalityOwner) return recurse(element)
if (element.visibility != INTERNAL) return recurse(element)
val containingClass = element.parentOfType<JKClass>()
val containingClassKind = containingClass?.classKind ?: element.psi<PsiMember>()?.containingClass?.classKind?.toJk()
val containingClassVisibility = containingClass?.visibility
?: element.psi<PsiMember>()
?.containingClass
?.visibility(context.converter.oldConverterServices.referenceSearcher, null)
?.visibility
val defaultVisibility = if (context.converter.settings.publicByDefault) PUBLIC else INTERNAL
element.visibility = when {
containingClassKind == INTERFACE || containingClassKind == ANNOTATION ->
PUBLIC
containingClassKind == ENUM && element is JKConstructor ->
PRIVATE
element is JKClass && element.isLocalClass() ->
PUBLIC
element is JKConstructor && containingClassVisibility != INTERNAL ->
defaultVisibility
element is JKField || element is JKMethod ->
PUBLIC
else -> defaultVisibility
}
return recurse(element)
}
} | apache-2.0 | f67b63cf530b39444e861d2eaf0104d0 | 40.425532 | 158 | 0.683967 | 5.45098 | false | false | false | false |
KotlinBy/bkug.by | data/src/main/kotlin/by/bkug/data/Meetup1.kt | 1 | 2407 | package by.bkug.data
import by.bkug.data.model.Article
import by.bkug.data.model.HtmlMarkup
import by.bkug.data.model.localDate
import org.intellij.lang.annotations.Language
@Language("html")
private val body = HtmlMarkup("""
<p>Приглашаем вас на митап Belarus Kotlin User Group по Kotlin, который пройдет в 19.00, 24 марта в <a href="http://eventspace.by">Space</a>.</p>
<p>На митапе выступят Антон Руткевич и Руслан Ибрагимов. Данное событие откроет серию митапов про Kotlin и будет особенно полезен тем, кто только начинает смотреть на данный язык.</p>
<h2>Программа:</h2>
<ul>
<li>19:00 - 20:00 – <strong>Антон Руткевич</strong> сделает введение в язык и расскажет об основных особенностях языка.</li>
<li>20:00 - 21:00 – <strong>Руслан Ибрагимов</strong> расскажет, как использовать Котлин на бэкенеде на примере Spring приложения, а также рассмотрит стандартную библиотеку Котлин.</li>
</ul>
<p>Встреча организованна при поддержке сообщества <a href="http://jprof.by/">Java Professionals By</a>.</p>
<p>Для участия во встрече необходима предварительная <a href="https://docs.google.com/forms/d/1GdS3ALbh1lwOWpEeAA4VY6DExQjo5dIIOrfmvKzhqlM/viewform?c=0&w=1">регистрация</a> (это поможет нам подготовить необходимое количество печенек :) )</p>
<p><strong>Дата проведения</strong>: 24 марта</p>
<p><strong>Время</strong>: 19:00–21:00</p>
<p><strong>Место проведения</strong>: ул. Октябрьская, 16А – EventSpace. Парковка и вход через ул. Октябрьскую, 10б.</p>
<p><em>Еще больше докладов и общения на тему Kotlin-разработки!</em></p>
$eventSpaceMap
""".trimIndent())
val meetup1 = Article(
title = "Анонс: BKUG #1",
slug = "anons-bkug-1",
category = announcements,
date = localDate("2016-03-17"),
body = body
)
| gpl-3.0 | 810d82dd98ff6078b24e895031977773 | 53.34375 | 245 | 0.745256 | 2.24677 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/ChannelEpg.kt | 1 | 16882 | /*
* Copyright © 2013 dvbviewer-controller Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.dvbviewer.controller.ui.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.view.View.OnClickListener
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.squareup.picasso.Picasso
import okhttp3.ResponseBody
import org.apache.commons.lang3.StringUtils
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.data.entities.EpgEntry
import org.dvbviewer.controller.data.entities.IEPG
import org.dvbviewer.controller.data.entities.Timer
import org.dvbviewer.controller.data.epg.ChannelEpgViewModel
import org.dvbviewer.controller.data.epg.EPGRepository
import org.dvbviewer.controller.data.epg.EpgViewModelFactory
import org.dvbviewer.controller.data.remote.RemoteRepository
import org.dvbviewer.controller.data.timer.TimerRepository
import org.dvbviewer.controller.ui.base.BaseListFragment
import org.dvbviewer.controller.ui.phone.IEpgDetailsActivity
import org.dvbviewer.controller.ui.phone.TimerDetailsActivity
import org.dvbviewer.controller.utils.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* The Class ChannelEpg.
*
* @author RayBa
*/
class ChannelEpg : BaseListFragment(), OnItemClickListener, OnClickListener, PopupMenu.OnMenuItemClickListener {
private var mAdapter: ChannelEPGAdapter? = null
private var clickListener: IEpgDetailsActivity.OnIEPGClickListener? = null
private var channel: String? = null
private var channelId: Long = 0
private var epgId: Long = 0
private var logoUrl: String? = null
private var channelPos: Int = 0
private var favPos: Int = 0
private var selectedPosition: Int = 0
private var channelLogo: ImageView? = null
private var channelName: TextView? = null
private var dayIndicator: TextView? = null
private var mDateInfo: EpgDateInfo? = null
private var lastRefresh: Date? = null
private var header: View? = null
private lateinit var timerRepository: TimerRepository
private lateinit var remoteRepository: RemoteRepository
private lateinit var epgRepository: EPGRepository
private lateinit var epgViewModel: ChannelEpgViewModel
override val layoutRessource: Int
get() = R.layout.fragment_channel_epg
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is EpgDateInfo) {
mDateInfo = context
}
if (context is IEpgDetailsActivity.OnIEPGClickListener) {
clickListener = context
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
timerRepository = TimerRepository(getDmsInterface())
remoteRepository = RemoteRepository(getDmsInterface())
epgRepository = EPGRepository(getDmsInterface())
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
fillFromBundle(arguments!!)
mAdapter = ChannelEPGAdapter()
listAdapter = mAdapter
setListShown(false)
listView!!.onItemClickListener = this
if (header != null && channel != null) {
channelLogo!!.setImageBitmap(null)
val url = ServerConsts.REC_SERVICE_URL + "/" + logoUrl
Picasso.get()
.load(url)
.into(channelLogo)
channelName!!.text = channel
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.tomorrow)
} else {
dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
}
setEmptyText(resources.getString(R.string.no_epg))
val epgObserver = Observer<List<EpgEntry>> { response -> onEpgChanged(response!!) }
val epgViewModelFactory = EpgViewModelFactory(epgRepository)
epgViewModel = ViewModelProvider(this, epgViewModelFactory)
.get(ChannelEpgViewModel::class.java)
val now = Date(mDateInfo!!.epgDate)
val tommorrow = DateUtils.addDay(now)
epgViewModel.getChannelEPG(epgId, now, tommorrow).observe(this, epgObserver)
}
private fun onEpgChanged(response: List<EpgEntry>) {
mAdapter = ChannelEPGAdapter()
listView?.adapter = mAdapter
mAdapter!!.items = response
mAdapter!!.notifyDataSetChanged()
setSelection(0)
val dateText: String
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dateText = getString(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dateText = getString(R.string.tomorrow)
} else {
dateText = DateUtils.formatDateTime(context, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
if (header != null) {
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.tomorrow)
} else {
dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
dayIndicator!!.text = dateText
} else {
val activity = activity as AppCompatActivity?
activity!!.supportActionBar!!.subtitle = dateText
}
lastRefresh = Date(mDateInfo!!.epgDate)
setListShown(true)
}
private fun fillFromBundle(savedInstanceState: Bundle) {
channel = savedInstanceState.getString(KEY_CHANNEL_NAME)
channelId = savedInstanceState.getLong(KEY_CHANNEL_ID)
epgId = savedInstanceState.getLong(KEY_EPG_ID)
logoUrl = savedInstanceState.getString(KEY_CHANNEL_LOGO)
channelPos = savedInstanceState.getInt(KEY_CHANNEL_POS)
favPos = savedInstanceState.getInt(KEY_FAV_POS)
}
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.base.BaseListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = super.onCreateView(inflater, container, savedInstanceState)
if (v != null) {
header = v.findViewById(R.id.epg_header)
channelLogo = v.findViewById(R.id.icon)
channelName = v.findViewById(R.id.title)
dayIndicator = v.findViewById(R.id.dayIndicator)
}
return v
}
/**
* The Class ViewHolder.
*
* @author RayBa
*/
private class ViewHolder {
internal var startTime: TextView? = null
internal var title: TextView? = null
internal var description: TextView? = null
internal var contextMenu: ImageView? = null
}
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val entry = mAdapter!!.getItem(position)
if (clickListener != null) {
clickListener!!.onIEPGClick(entry)
return
}
val i = Intent(context, IEpgDetailsActivity::class.java)
i.putExtra(IEPG::class.java.simpleName, entry)
startActivity(i)
}
/**
* The Class ChannelEPGAdapter.
*
* @author RayBa
*/
inner class ChannelEPGAdapter
/**
* Instantiates a new channel epg adapter.
*/
: ArrayListAdapter<EpgEntry>() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var convertView = convertView
val holder: ViewHolder
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_row_epg, parent, false)
holder = ViewHolder()
holder.startTime = convertView.findViewById(R.id.startTime)
holder.title = convertView.findViewById(R.id.title)
holder.description = convertView.findViewById(R.id.description)
holder.contextMenu = convertView.findViewById(R.id.contextMenu)
holder.contextMenu!!.setOnClickListener(this@ChannelEpg)
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
val epgEntry = getItem(position)
holder.contextMenu!!.tag = position
val flags = DateUtils.FORMAT_SHOW_TIME
val date = DateUtils.formatDateTime(context, epgEntry.start.time, flags)
holder.startTime!!.text = date
holder.title!!.text = epgEntry.title
val subTitle = epgEntry.subTitle
val desc = epgEntry.description
holder.description!!.text = if (TextUtils.isEmpty(subTitle)) desc else subTitle
holder.description!!.visibility = if (TextUtils.isEmpty(holder.description!!.text)) View.GONE else View.VISIBLE
return convertView!!
}
}
/**
* Refreshs the data
*
*/
fun refresh() {
setListShown(false)
val start = Date(mDateInfo!!.epgDate)
val end = DateUtils.addDay(start)
epgViewModel.getChannelEPG(epgId, start, end, true)
}
/**
* Refresh date.
*
*/
private fun refreshDate() {
if (lastRefresh != null && lastRefresh!!.time != mDateInfo!!.epgDate) {
refresh()
}
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_CHANNEL_NAME, channel)
outState.putLong(KEY_CHANNEL_ID, channelId)
outState.putLong(KEY_EPG_ID, epgId)
outState.putString(KEY_CHANNEL_LOGO, logoUrl)
outState.putInt(KEY_CHANNEL_POS, channelPos)
outState.putInt(KEY_FAV_POS, favPos)
outState.putLong(KEY_EPG_DAY, mDateInfo!!.epgDate)
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockFragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.channel_epg, menu)
menu.findItem(R.id.menuPrev).isEnabled = !DateUtils.isToday(mDateInfo!!.epgDate)
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
when (v.id) {
R.id.contextMenu -> {
selectedPosition = v.tag as Int
val popup = PopupMenu(context!!, v)
popup.menuInflater.inflate(R.menu.context_menu_epg, popup.menu)
popup.setOnMenuItemClickListener(this)
popup.show()
}
else -> {
}
}
}
override fun onMenuItemClick(item: MenuItem): Boolean {
val c = mAdapter!!.getItem(selectedPosition)
val timer: Timer
when (item.itemId) {
R.id.menuRecord -> {
timer = cursorToTimer(c)
val call = timerRepository.saveTimer(timer)
call.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
sendMessage(R.string.timer_saved)
logEvent(EVENT_TIMER_CREATED)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
sendMessage(R.string.error_common)
}
})
return true
}
R.id.menuTimer -> {
timer = cursorToTimer(c)
if (UIUtils.isTablet(context!!)) {
val timerdetails = TimerDetails.newInstance()
val args = TimerDetails.buildBundle(timer)
timerdetails.arguments = args
timerdetails.show(activity!!.supportFragmentManager, TimerDetails::class.java.name)
} else {
val timerIntent = Intent(context, TimerDetailsActivity::class.java)
val extras = TimerDetails.buildBundle(timer)
timerIntent.putExtras(extras)
startActivity(timerIntent)
}
return true
}
R.id.menuDetails -> {
val details = Intent(context, IEpgDetailsActivity::class.java)
details.putExtra(IEPG::class.java.simpleName, c)
startActivity(details)
return true
}
R.id.menuSwitch -> {
val prefs = DVBViewerPreferences(context!!)
val target = prefs.getString(DVBViewerPreferences.KEY_SELECTED_CLIENT)
remoteRepository.switchChannel(target, channelId.toString()).enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
sendMessage(R.string.channel_switched)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
sendMessage(R.string.error_common)
}
})
return true
}
else -> {
}
}
return false
}
/**
* The Interface EpgDateInfo.
*
* @author RayBa
*/
interface EpgDateInfo {
var epgDate: Long
}
/**
* Cursor to timer.
*
* @param c the c
* @return the timer©
*/
private fun cursorToTimer(c: EpgEntry): Timer {
val epgTitle = if (StringUtils.isNotBlank(c.title)) c.title else channel
val prefs = DVBViewerPreferences(context!!)
val epgBefore = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, DVBViewerPreferences.DEFAULT_TIMER_TIME_BEFORE)
val epgAfter = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, DVBViewerPreferences.DEFAULT_TIMER_TIME_AFTER)
val timer = Timer()
timer.title = epgTitle
timer.channelId = channelId
timer.channelName = channel
timer.start = c.start
timer.end = c.end
timer.pre = epgBefore
timer.post = epgAfter
timer.eventId = c.eventId
timer.pdc = c.pdc
timer.timerAction = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0)
return timer
}
companion object {
val KEY_CHANNEL_NAME = ChannelEpg::class.java.name + "KEY_CHANNEL_NAME"
val KEY_CHANNEL_ID = ChannelEpg::class.java.name + "KEY_CHANNEL_ID"
val KEY_CHANNEL_LOGO = ChannelEpg::class.java.name + "KEY_CHANNEL_LOGO"
val KEY_CHANNEL_POS = ChannelEpg::class.java.name + "KEY_CHANNEL_POS"
val KEY_FAV_POS = ChannelEpg::class.java.name + "KEY_FAV_POS"
val KEY_EPG_ID = ChannelEpg::class.java.name + "KEY_EPG_ID"
val KEY_EPG_DAY = ChannelEpg::class.java.name + "EPG_DAY"
}
}
| apache-2.0 | 14997743dc076630015352a42cd424dc | 38.255814 | 154 | 0.63827 | 4.724321 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/GAStatics.kt | 1 | 660 | package lt.markmerkk
/**
* @author mariusmerkevicius
* @since 2016-08-14
*/
object GAStatics {
val CATEGORY_BUTTON = "BUTTON"
val CATEGORY_GENERIC = "GENERIC"
val ACTION_ENTER = "ENTER_TIME"
val ACTION_SYNC_MAIN = "SYNC_MAIN"
val ACTION_SYNC_SETTINGS = "SYNC_SETTINGS"
val ACTION_SEARCH_REFRESH = "SEARCH_REFRESH"
val ACTION_START = "START"
val VIEW_DAY = "VIEW_DAY"
val VIEW_DAY_SIMPLE = "VIEW_SIMPLE_DAY"
val VIEW_WEEK = "VIEW_SIMPLE_WEEK"
val VIEW_CALENDAR_DAY = "VIEW_CALENDAR_DAY"
val VIEW_CALENDAR_WEEK = "VIEW_CALENDAR_WEEK"
val VIEW_GRAPH = "VIEW_GRAPH"
val VIEW_SETTINGS = "VIEW_SETTINGS"
} | apache-2.0 | 9f8f1beec0df23bb4c3255d5ecfd3200 | 27.73913 | 49 | 0.665152 | 3.3 | false | false | false | false |
jk1/Intellij-idea-mail | src/test/kotlin/github/jk1/smtpidea/TestUtils.kt | 1 | 1593 | package github.jk1.smtpidea.server.pop3
import java.net.ServerSocket
import javax.mail.internet.MimeMessage
import javax.mail.Session
import java.util.Properties
import javax.mail.internet.InternetAddress
import javax.mail.Message.RecipientType
import org.junit.Assert.*
import javax.mail.Message
public trait TestUtils{
public fun findFreePort(): Int {
val socket = ServerSocket(0)
val port = socket.getLocalPort()
socket.close()
return port
}
public fun assertMailEquals(expected: Message, actual: Message) {
assertEquals(expected.getSubject(), actual.getSubject())
assertArrayEquals(expected.getFrom(), actual.getFrom())
assertEquals(expected.getContent().toString().trim(), actual.getContent().toString().trim())
assertArrayEquals(expected.getAllRecipients(), actual.getAllRecipients())
}
public fun createMimeMessage(content: String): MimeMessage
= createMimeMessage("[email protected]", "[email protected]", content)
public fun createMimeMessage(to: String, from: String, content: String): MimeMessage =
createMimeMessage(to, from, "subject", content)
public fun createMimeMessage(to: String, from: String, subject: String, content: String): MimeMessage {
val message = MimeMessage(Session.getInstance(Properties()))
message.setFrom(InternetAddress(from))
message.setRecipient(RecipientType.TO, InternetAddress(to))
message.setSubject(subject)
message.setText(content)
message.saveChanges()
return message
}
}
| gpl-2.0 | 54f40879c2a0618013a7e0059032c932 | 36.046512 | 107 | 0.71312 | 4.713018 | false | false | false | false |
javecs/text2expr | src/main/kotlin/xyz/javecs/tools/text2expr/rules/RuleParser.kt | 1 | 2232 | package xyz.javecs.tools.text2expr.rules
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import xyz.javecs.tools.text2expr.parser.Text2ExprBaseVisitor
import xyz.javecs.tools.text2expr.parser.Text2ExprLexer
import xyz.javecs.tools.text2expr.parser.Text2ExprParser
internal data class Field(var key: String = "",
var value: MutableList<String> = ArrayList(),
var isOptional: Boolean = false,
var optionalValue: Double = Double.NaN)
internal class Word(var fields: MutableList<Field> = ArrayList(), val id: String = "") {
fun isOptional() = fields.find { it.isOptional } != null
fun optionalValue(): Double? = fields.find { it.isOptional }?.optionalValue
}
internal fun parser(source: String): Text2ExprParser {
val charStream = CharStreams.fromString(source)
val lexer = Text2ExprLexer(charStream)
val tokens = CommonTokenStream(lexer)
return Text2ExprParser(tokens)
}
internal class RuleParser : Text2ExprBaseVisitor<Unit>() {
var expr = StringBuffer()
var rule = ArrayList<Word>()
override fun visitWordDefine(ctx: Text2ExprParser.WordDefineContext) {
rule.add(Word())
super.visitWordDefine(ctx)
}
override fun visitWordAssign(ctx: Text2ExprParser.WordAssignContext) {
rule.add(Word(id = ctx.ID().text))
super.visitWordAssign(ctx)
}
override fun visitField(ctx: Text2ExprParser.FieldContext) {
val field = Field()
if (ctx.op.text == "?") field.isOptional = true
field.key = ctx.PREFIX().text
field.value = ArrayList()
rule.last().fields.add(field)
visit(ctx.value())
}
override fun visitValue(ctx: Text2ExprParser.ValueContext) {
val field = rule.last().fields.last()
if (ctx.JAPANESE() != null) field.value.add(ctx.JAPANESE().text)
if (ctx.SYMBOL() != null) field.value.add(ctx.SYMBOL().text.replace("\"", ""))
if (ctx.optionalValue() != null) field.optionalValue = ctx.optionalValue().NUMBER().text.toDouble()
ctx.value().forEach { visit(it) }
}
override fun visitExpr(ctx: Text2ExprParser.ExprContext) {
expr.append(ctx.text)
}
} | mit | 017effe184eeb878f6b9c47f0eff03b8 | 36.216667 | 107 | 0.675179 | 3.915789 | false | false | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediaoverview/MediaGridDividerDecoration.kt | 1 | 1663 | package org.thoughtcrime.securesms.mediaoverview
import android.graphics.Rect
import android.view.View
import androidx.annotation.Px
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.util.ViewUtil
internal class MediaGridDividerDecoration(
private val spanCount: Int,
@Px private val space: Int,
private val adapter: MediaGalleryAllAdapter
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val holder = parent.getChildViewHolder(view)
val adapterPosition = holder.adapterPosition
val section = adapter.getAdapterPositionSection(adapterPosition)
val itemSectionOffset = adapter.getItemSectionOffset(section, adapterPosition)
if (itemSectionOffset == -1) {
return
}
val sectionItemViewType = adapter.getSectionItemViewType(section, itemSectionOffset)
if (sectionItemViewType != MediaGalleryAllAdapter.GALLERY) {
return
}
val column = itemSectionOffset % spanCount
val isRtl = ViewUtil.isRtl(view)
val distanceFromEnd = spanCount - 1 - column
val spaceStart = (column / spanCount.toFloat()) * space
val spaceEnd = (distanceFromEnd / spanCount.toFloat()) * space
outRect.setStart(spaceStart.toInt(), isRtl)
outRect.setEnd(spaceEnd.toInt(), isRtl)
outRect.bottom = space
}
private fun Rect.setEnd(end: Int, isRtl: Boolean) {
if (isRtl) {
left = end
} else {
right = end
}
}
private fun Rect.setStart(start: Int, isRtl: Boolean) {
if (isRtl) {
right = start
} else {
left = start
}
}
}
| gpl-3.0 | c56838098200cf2ccc2f46da2f68fac5 | 27.186441 | 107 | 0.716777 | 4.494595 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/enrollment/EnrollmentServiceShould.kt | 1 | 12568 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.enrollment
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Single
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.arch.helpers.AccessHelper
import org.hisp.dhis.android.core.arch.helpers.DateUtils
import org.hisp.dhis.android.core.common.Access
import org.hisp.dhis.android.core.common.DataAccess
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentServiceImpl
import org.hisp.dhis.android.core.event.Event
import org.hisp.dhis.android.core.event.EventCollectionRepository
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitCollectionRepository
import org.hisp.dhis.android.core.program.AccessLevel
import org.hisp.dhis.android.core.program.Program
import org.hisp.dhis.android.core.program.ProgramCollectionRepository
import org.hisp.dhis.android.core.program.ProgramStage
import org.hisp.dhis.android.core.program.ProgramStageCollectionRepository
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceCollectionRepository
import org.hisp.dhis.android.core.trackedentity.ownership.ProgramTempOwner
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
class EnrollmentServiceShould {
private val enrollmentUid: String = "enrollmentUid"
private val trackedEntityInstanceUid: String = "trackedEntityInstanceUid"
private val programUid: String = "programUid"
private val organisationUnitId: String = "organisationUnitId"
private val enrollment: Enrollment = mock()
private val trackedEntityInstance: TrackedEntityInstance = mock()
private val program: Program = mock()
private val programTempOwner: ProgramTempOwner = mock()
private val enrollmentRepository: EnrollmentCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val trackedEntityInstanceRepository: TrackedEntityInstanceCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programRepository: ProgramCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val organisationUnitRepository: OrganisationUnitCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val eventCollectionRepository: EventCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programStageCollectionRepository: ProgramStageCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programTempOwnerStore: ObjectWithoutUidStore<ProgramTempOwner> = mock()
private lateinit var enrollmentService: EnrollmentService
@Before
fun setUp() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(
trackedEntityInstanceRepository
.uid(trackedEntityInstanceUid).blockingGet()
) doReturn trackedEntityInstance
whenever(programRepository.uid(programUid).blockingGet()) doReturn program
whenever(enrollment.uid()) doReturn enrollmentUid
whenever(trackedEntityInstance.organisationUnit()) doReturn organisationUnitId
enrollmentService = EnrollmentServiceImpl(
enrollmentRepository,
trackedEntityInstanceRepository,
programRepository,
organisationUnitRepository,
eventCollectionRepository,
programStageCollectionRepository,
programTempOwnerStore
)
}
@Test
fun `IsOpen should return true if enrollment is not found`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn null
assertTrue(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `IsOpen should return false if enrollment is not active`() {
whenever(enrollment.status()) doReturn EnrollmentStatus.COMPLETED
assertFalse(enrollmentService.blockingIsOpen(enrollmentUid))
whenever(enrollment.status()) doReturn null
assertFalse(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `IsOpen should return true if enrollment is active`() {
whenever(enrollment.status()) doReturn EnrollmentStatus.ACTIVE
assertTrue(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `GetEnrollmentAccess should return no access if program not found`() {
whenever(programRepository.uid("other uid").blockingGet()) doReturn null
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, "other uid")
assert(access == EnrollmentAccess.NO_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return data access if program is open`() {
whenever(program.accessLevel()) doReturn AccessLevel.OPEN
whenever(program.access()) doReturn AccessHelper.createForDataWrite(false)
val accessRead = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(accessRead == EnrollmentAccess.READ_ACCESS)
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
val accessWrite = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(accessWrite == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return data access if protected program in capture scope`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn true
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return access denied if protected program not in capture scope`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn false
whenever(programTempOwnerStore.selectWhere(any())) doReturn listOf(programTempOwner)
whenever(programTempOwner.validUntil()) doReturn DateUtils.DATE_FORMAT.parse("1999-01-01T00:00:00.000")
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.PROTECTED_PROGRAM_DENIED)
}
@Test
fun `GetEnrollmentAccess should return data access if protected program has broken glass`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn false
whenever(programTempOwnerStore.selectWhere(any())) doReturn listOf(programTempOwner)
whenever(programTempOwner.validUntil()) doReturn DateUtils.DATE_FORMAT.parse("2999-01-01T00:00:00.000")
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `Enrollment has any events that allows events creation`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(enrollment.program()) doReturn programUid
whenever(
programStageCollectionRepository.byProgramUid().eq(programUid)
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.byAccessDataWrite().isTrue
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.get()
) doReturn Single.just(getProgramStages())
whenever(
eventCollectionRepository.byEnrollmentUid().eq(enrollmentUid)
) doReturn eventCollectionRepository
whenever(
eventCollectionRepository.byDeleted().isFalse
) doReturn eventCollectionRepository
whenever(eventCollectionRepository.get()) doReturn Single.just(getEventList())
assertTrue(enrollmentService.blockingGetAllowEventCreation(enrollmentUid, listOf("1")))
}
@Test
fun `Enrollment has not any events that allows events creation`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(enrollment.program()) doReturn programUid
whenever(
programStageCollectionRepository.byProgramUid().eq(programUid)
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.byAccessDataWrite().isTrue
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.get()
) doReturn Single.just(getProgramStages())
whenever(
eventCollectionRepository.byEnrollmentUid().eq(enrollmentUid)
) doReturn eventCollectionRepository
whenever(
eventCollectionRepository.byDeleted().isFalse
) doReturn eventCollectionRepository
whenever(eventCollectionRepository.get()) doReturn Single.just(getEventList())
assertFalse(enrollmentService.blockingGetAllowEventCreation(enrollmentUid, listOf("1", "2")))
}
private fun getEventList() = listOf(
Event.builder()
.uid("eventUid1")
.programStage("1")
.build(),
Event.builder()
.uid("eventUid2")
.programStage("2")
.build()
)
private fun getProgramStages() = listOf(
ProgramStage.builder()
.access(Access.create(true, true, DataAccess.create(true, true)))
.uid("1")
.repeatable(true)
.build(),
ProgramStage.builder()
.access(Access.create(true, true, DataAccess.create(true, true)))
.uid("2")
.repeatable(true)
.build()
)
}
| bsd-3-clause | 33974e1df492cfe8e50495aa05bf9ccf | 44.536232 | 119 | 0.735519 | 5.524396 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt | 1 | 19736 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler
import com.intellij.refactoring.rename.RenameUtil
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.usageView.UsageViewUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.HashingStrategy
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.base.util.restrictByFileType
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.deleteSingle
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.math.max
import kotlin.math.min
interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration {
object Default : Mover {
override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
return when (targetContainer) {
is KtFile -> {
val declarationContainer: KtElement =
if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer
declarationContainer.add(originalElement) as KtNamedDeclaration
}
is KtClassOrObject -> targetContainer.addDeclaration(originalElement)
else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}")
}.apply {
val container = originalElement.containingClassOrObject
if (container is KtObjectDeclaration &&
container.isCompanion() &&
container.declarations.singleOrNull() == originalElement &&
KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false)
.findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty()
) {
container.deleteSingle()
} else {
originalElement.deleteSingle()
}
}
}
}
}
sealed class MoveSource {
abstract val elementsToMove: Collection<KtNamedDeclaration>
class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource()
class File(val file: KtFile) : MoveSource() {
override val elementsToMove: Collection<KtNamedDeclaration>
get() = file.declarations.filterIsInstance<KtNamedDeclaration>()
}
}
fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration))
fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations)
fun MoveSource(file: KtFile) = MoveSource.File(file)
class MoveDeclarationsDescriptor @JvmOverloads constructor(
val project: Project,
val moveSource: MoveSource,
val moveTarget: KotlinMoveTarget,
val delegate: MoveDeclarationsDelegate,
val searchInCommentsAndStrings: Boolean = true,
val searchInNonCode: Boolean = true,
val deleteSourceFiles: Boolean = false,
val moveCallback: MoveCallback? = null,
val openInEditor: Boolean = false,
val allElementsToMove: List<PsiElement>? = null,
val analyzeConflicts: Boolean = true,
val searchReferences: Boolean = true
)
class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element)
private object ElementHashingStrategy : HashingStrategy<PsiElement> {
override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean {
if (e1 === e2) return true
// Name should be enough to distinguish different light elements based on the same original declaration
if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) {
return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name
}
return false
}
override fun hashCode(e: PsiElement?): Int {
return when (e) {
null -> 0
is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0)
else -> e.hashCode()
}
}
}
class MoveKotlinDeclarationsProcessor(
val descriptor: MoveDeclarationsDescriptor,
val mover: Mover = Mover.Default,
private val throwOnConflicts: Boolean = false
) : BaseRefactoringProcessor(descriptor.project) {
companion object {
const val REFACTORING_ID = "move.kotlin.declarations"
}
val project get() = descriptor.project
private var nonCodeUsages: Array<NonCodeUsageInfo>? = null
private val moveEntireFile = descriptor.moveSource is MoveSource.File
private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e ->
e.parent != descriptor.moveTarget.getTargetPsiIfExists(e)
}
private val kotlinToLightElementsBySourceFile = elementsToMove
.groupBy { it.containingKtFile }
.mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } }
private val conflicts = MultiMap<PsiElement, String>()
override fun getRefactoringId() = REFACTORING_ID
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let {
if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString()
} ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name")
return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName)
}
fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) }
public override fun findUsages(): Array<UsageInfo> {
if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY
val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: ""
fun getSearchScope(element: PsiElement): GlobalSearchScope? {
val projectScope = project.projectScope()
val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope
if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope
val moveTarget = descriptor.moveTarget
val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget)
val targetModule = moveTarget.getTargetModule(project) ?: return projectScope
if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope
// Check if facade class may change
if (newContainer is ContainerInfo.Package) {
val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE)
val currentFile = ktDeclaration.containingKtFile
val newFile = when (moveTarget) {
is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null
is KotlinMoveTargetForDeferredFile -> return javaScope
else -> return null
}
val currentFacade = currentFile.findFacadeClass()
val newFacade = newFile.findFacadeClass()
return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null
}
return null
}
fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean {
if (element?.containingFile != usage.element?.containingFile) return false
val firstSegment = segment ?: return false
val secondSegment = usage.segment ?: return false
return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset)
}
fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) {
kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement ->
val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList()
val elementName = lightElement.name ?: return@flatMapTo emptyList()
val newFqName = StringUtil.getQualifiedName(newContainerName, elementName)
val foundReferences = HashSet<PsiReference>()
val results = ReferencesSearch
.search(lightElement, searchScope)
.mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) {
createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false)
} else null
}
val name = lightElement.kotlinFqName?.quoteIfNeeded()?.asString()
if (name != null) {
fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) {
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
name,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqName).quoteIfNeeded().asString(),
results
)
}
val facadeContainer = lightElement.parent as? KtLightClassForFacade
if (facadeContainer != null) {
val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName)
val newFqNameWithFacade = StringUtil.getQualifiedName(
StringUtil.getQualifiedName(newContainerName, facadeContainer.name),
elementName
)
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
oldFqNameWithFacade,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqNameWithFacade).quoteIfNeeded().asString(),
results
)
ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage ->
if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) {
results.add(kotlinNonCodeUsage)
}
}
} else {
searchForKotlinNameUsages(results)
}
}
MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler ->
handler.preprocessUsages(results)
}
results
}
}
val usages = ArrayList<UsageInfo>()
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
descriptor.moveTarget,
elementsToMove.first(),
allElementsToMove = descriptor.allElementsToMove
)
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
val internalUsages = LinkedHashSet<UsageInfo>()
val externalUsages = LinkedHashSet<UsageInfo>()
if (moveEntireFile) {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceFile.packageFqName),
descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
)
internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
} else {
kotlinToLightElements.keys.forEach {
val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget)
internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo)
}
}
internalUsages += descriptor.delegate.findInternalUsages(descriptor)
collectUsages(kotlinToLightElements, externalUsages)
if (descriptor.analyzeConflicts) {
conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts)
descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts)
}
usages += internalUsages
usages += externalUsages
}
return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray())
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList())
internal fun doPerformRefactoring(usages: List<UsageInfo>) {
fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration {
val targetContainer = moveTarget.getOrCreateTargetPsi(declaration)
descriptor.delegate.preprocessDeclaration(descriptor, declaration)
if (moveEntireFile) return declaration
return mover(declaration, targetContainer).apply {
addToBeShortenedDescendantsToWaitingSet()
}
}
val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val newInternalUsages = ArrayList<UsageInfo>()
markInternalUsages(oldInternalUsages)
val usagesToProcess = ArrayList(externalUsages)
try {
descriptor.delegate.preprocessUsages(descriptor, usages)
val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy)
val newDeclarations = ArrayList<KtNamedDeclaration>()
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
for ((oldDeclaration, oldLightElements) in kotlinToLightElements) {
val elementListener = transaction?.getElementListener(oldDeclaration)
val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget)
newDeclarations += newDeclaration
oldToNewElementsMapping[oldDeclaration] = newDeclaration
oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile
elementListener?.elementMoved(newDeclaration)
for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) {
oldToNewElementsMapping[oldElement] = newElement
}
if (descriptor.openInEditor) {
EditorHelper.openInEditor(newDeclaration)
}
}
if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) {
sourceFile.delete()
}
}
val internalUsageScopes: List<KtElement> = if (moveEntireFile) {
newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList()
} else {
newDeclarations
}
internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) }
usagesToProcess += newInternalUsages
nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray()
performDelayedRefactoringRequests(project)
} catch (e: IncorrectOperationException) {
nonCodeUsages = null
RefactoringUIUtil.processIncorrectOperation(myProject, e)
} finally {
cleanUpInternalUsages(newInternalUsages + oldInternalUsages)
}
}
override fun performPsiSpoilingRefactoring() {
nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) }
descriptor.moveCallback?.refactoringCompleted()
}
fun execute(usages: List<UsageInfo>) {
execute(usages.toTypedArray())
}
override fun doRun() {
try {
super.doRun()
} finally {
broadcastRefactoringExit(myProject, refactoringId)
}
}
override fun getCommandName(): String = KotlinBundle.message("command.move.declarations")
}
| apache-2.0 | 26cd8faceb35963b429167f004e52dab | 47.254279 | 138 | 0.672882 | 5.859857 | false | false | false | false |
dahlstrom-g/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/common/PossibleSourceTypesTestBase.kt | 7 | 2520 | // 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.uast.test.common
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.getPossiblePsiSourceTypes
import org.jetbrains.uast.toUElementOfExpectedTypes
import org.junit.Assert
interface PossibleSourceTypesTestBase {
private fun PsiFile.getPsiSourcesByPlainVisitor(psiPredicate: (PsiElement) -> Boolean = { true },
vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val sources = mutableSetOf<PsiElement>()
accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (psiPredicate(element)) {
element.toUElementOfExpectedTypes(*uastTypes)?.let {
sources += element
}
}
super.visitElement(element)
}
})
return sources
}
private fun PsiFile.getPsiSourcesByLanguageAwareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = getPossiblePsiSourceTypes(language, *uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
private fun PsiFile.getPsiSourcesByLanguageUnawareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = UastFacade.getPossiblePsiSourceTypes(*uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
fun checkConsistencyWithRequiredTypes(psiFile: PsiFile, vararg uastTypes: Class<out UElement>) {
val byPlain = psiFile.getPsiSourcesByPlainVisitor(uastTypes = uastTypes)
val byLanguageAware = psiFile.getPsiSourcesByLanguageAwareVisitor(uastTypes = uastTypes)
val byLanguageUnaware = psiFile.getPsiSourcesByLanguageUnawareVisitor(uastTypes = uastTypes)
Assert.assertEquals(
"Filtering PSI elements with getPossiblePsiSourceTypes(${listOf(*uastTypes)}) should not lost or add any conversions",
byPlain,
byLanguageUnaware)
Assert.assertEquals(
"UastFacade implementation(${listOf(*uastTypes)}) should be in sync with language UastLanguagePlugin's one",
byLanguageAware,
byLanguageUnaware)
}
} | apache-2.0 | a65e1727cf2a5aa791e8081f072fa9e9 | 42.465517 | 140 | 0.751984 | 5.163934 | false | false | false | false |
dahlstrom-g/intellij-community | platform/script-debugger/backend/src/debugger/BreakpointManager.kt | 12 | 3124 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.util.Url
import org.jetbrains.concurrency.Promise
import java.util.*
interface BreakpointManager {
enum class MUTE_MODE {
ALL,
ONE,
NONE
}
val breakpoints: Iterable<Breakpoint>
val regExpBreakpointSupported: Boolean
get() = false
fun setBreakpoint(target: BreakpointTarget,
line: Int,
column: Int = Breakpoint.EMPTY_VALUE,
url: Url? = null,
condition: String? = null,
ignoreCount: Int = Breakpoint.EMPTY_VALUE): SetBreakpointResult
fun remove(breakpoint: Breakpoint): Promise<*>
/**
* Supports targets that refer to function text in form of function-returning
* JavaScript expression.
* E.g. you can set a breakpoint on the 5th line of user method addressed as
* 'PropertiesDialog.prototype.loadData'.
* Expression is calculated immediately and never recalculated again.
*/
val functionSupport: ((expression: String) -> BreakpointTarget)?
get() = null
// Could be called multiple times for breakpoint
fun addBreakpointListener(listener: BreakpointListener)
fun removeAll(): Promise<*>
fun getMuteMode(): MUTE_MODE = BreakpointManager.MUTE_MODE.ONE
/**
* Flushes the breakpoint parameter changes (set* methods) into the browser
* and returns a promise of an updated breakpoint. This method must
* be called for the set* method invocations to take effect.
*/
fun flush(breakpoint: Breakpoint): Promise<out Breakpoint>
/**
* Asynchronously enables or disables all breakpoints on remote. 'Enabled' means that
* breakpoints behave as normal, 'disabled' means that VM doesn't stop on breakpoints.
* It doesn't update individual properties of [Breakpoint]s. Method call
* with a null value and not null callback simply returns current value.
*/
fun enableBreakpoints(enabled: Boolean): Promise<*>
fun setBreakOnFirstStatement()
fun isBreakOnFirstStatement(context: SuspendContext<*>): Boolean
interface SetBreakpointResult
data class BreakpointExist(val existingBreakpoint: Breakpoint) : SetBreakpointResult
data class BreakpointCreated(val breakpoint: Breakpoint, val isRegistered: Promise<out Breakpoint>) : SetBreakpointResult
}
interface BreakpointListener : EventListener {
fun resolved(breakpoint: Breakpoint)
fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?)
fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) {
}
} | apache-2.0 | d15c3af9f663c3375b1b9f972505c5f6 | 33.340659 | 123 | 0.728233 | 4.719033 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/util/XYFlicker.kt | 1 | 6875 | package tripleklay.ui.util
import klay.scene.Pointer
import euklid.f.IPoint
import euklid.f.MathUtil
import euklid.f.Point
import react.Signal
import kotlin.math.sign
/**
* Translates pointer input on a layer into an x, y offset. With a sufficiently large drag delta,
* calculates a velocity, applies it to the position over time and diminishes its value by
* friction. For smaller drag deltas, dispatches the pointer end event on the [.clicked]
* signal.
*
* **NOTE:**Clients of this class must call [.update], so that friction and
* other calculations can be applied. This is normally done within the client's own update method
* and followed by some usage of the [.position] method. For example:
* <pre>`XYFlicker flicker = new XYFlicker();
* Layer layer = ...;
* { layer.addListener(flicker); }
* void update (int delta) {
* flicker.update(delta);
* layer.setTranslation(flicker.position().x(), flicker.position().y());
* }
`</pre> *
* TODO: figure out how to implement with two Flickers. could require some changes therein since
* you probably don't want them to have differing states, plus 2x clicked signals is wasteful
*/
class XYFlicker : Pointer.Listener {
/** Signal dispatched when a pointer usage did not end up being a flick. */
var clicked = Signal<klay.core.Pointer.Event>()
/**
* Gets the current position.
*/
fun position(): IPoint {
return _position
}
override fun onStart(iact: Pointer.Interaction) {
_vel.set(0f, 0f)
_maxDeltaSq = 0f
_origPos.set(_position)
getPosition(iact.event!!, _start)
_prev.set(_start)
_cur.set(_start)
_prevStamp = 0.0
_curStamp = iact.event!!.time
}
override fun onDrag(iact: Pointer.Interaction) {
_prev.set(_cur)
_prevStamp = _curStamp
getPosition(iact.event!!, _cur)
_curStamp = iact.event!!.time
var dx = _cur.x - _start.x
var dy = _cur.y - _start.y
setPosition(_origPos.x + dx, _origPos.y + dy)
_maxDeltaSq = maxOf(dx * dx + dy * dy, _maxDeltaSq)
// for the purposes of capturing the event stream, dx and dy are capped by their ranges
dx = _position.x - _origPos.x
dy = _position.y - _origPos.y
if (dx * dx + dy * dy >= maxClickDeltaSq()) iact.capture()
}
override fun onEnd(iact: Pointer.Interaction) {
// just dispatch a click if the pointer didn't move very far
if (_maxDeltaSq < maxClickDeltaSq()) {
clicked.emit(iact.event!!)
return
}
// if not, maybe impart some velocity
val dragTime = (_curStamp - _prevStamp).toFloat()
val delta = Point(_cur.x - _prev.x, _cur.y - _prev.y)
val dragVel = delta.mult(1 / dragTime)
var dragSpeed = dragVel.distance(0f, 0f)
if (dragSpeed > flickSpeedThresh() && delta.distance(0f, 0f) > minFlickDelta()) {
if (dragSpeed > maxFlickSpeed()) {
dragVel.multLocal(maxFlickSpeed() / dragSpeed)
dragSpeed = maxFlickSpeed()
}
_vel.set(dragVel)
_vel.multLocal(flickXfer())
val sx = _vel.x.sign
val sy = _vel.y.sign
_accel.x = -sx * friction()
_accel.y = -sy * friction()
}
}
override fun onCancel(iact: Pointer.Interaction?) {
_vel.set(0f, 0f)
_accel.set(0f, 0f)
}
fun update(delta: Float) {
if (_vel.x == 0f && _vel.y == 0f) return
_prev.set(_position)
// apply x and y velocity
val x = MathUtil.clamp(_position.x + _vel.x * delta, _min.x, _max.x)
val y = MathUtil.clamp(_position.y + _vel.y * delta, _min.y, _max.y)
// stop when we hit the edges
if (x == _position.x) _vel.x = 0f
if (y == _position.y) _vel.y = 0f
_position.set(x, y)
// apply x and y acceleration
_vel.x = applyAccelertion(_vel.x, _accel.x, delta)
_vel.y = applyAccelertion(_vel.y, _accel.y, delta)
}
/**
* Resets the flicker to the given maximum values.
*/
fun reset(maxX: Float, maxY: Float) {
_max.set(maxX, maxY)
// reclamp the position
setPosition(_position.x, _position.y)
}
/**
* Sets the flicker position, in the case of a programmatic change.
*/
fun positionChanged(x: Float, y: Float) {
setPosition(x, y)
}
/** Translates a pointer event into a position. */
private fun getPosition(event: klay.core.Pointer.Event, dest: Point) {
dest.set(-event.x, -event.y)
}
/** Sets the current position, clamping the values between min and max. */
private fun setPosition(x: Float, y: Float) {
_position.set(MathUtil.clamp(x, _min.x, _max.x), MathUtil.clamp(y, _min.y, _max.y))
}
/** Returns the minimum distance (in pixels) the pointer must have moved to register as a
* flick. */
private fun minFlickDelta(): Float {
return 10f
}
/** Returns the deceleration (in pixels per ms per ms) applied to non-zero velocity. */
private fun friction(): Float {
return 0.0015f
}
/** Returns the minimum (positive) speed (in pixels per millisecond) at time of touch release
* required to initiate a flick (i.e. transfer the flick velocity to the entity). */
private fun flickSpeedThresh(): Float {
return 0.5f
}
/** Returns the fraction of flick speed that is transfered to the entity (a value between 0
* and 1). */
private fun flickXfer(): Float {
return 0.95f
}
/** Returns the maximum flick speed that will be transfered to the entity; limits the actual
* flick speed at time of release. This value is not adjusted by [.flickXfer]. */
private fun maxFlickSpeed(): Float {
return 1.4f // pixels/ms
}
/** Returns the square of the maximum distance (in pixels) the pointer is allowed to travel
* while pressed and still register as a click. */
private fun maxClickDeltaSq(): Float {
return 225f
}
private var _maxDeltaSq: Float = 0.toFloat()
private val _position = Point()
private val _vel = Point()
private val _accel = Point()
private val _origPos = Point()
private val _start = Point()
private val _cur = Point()
private val _prev = Point()
private val _max = Point()
private val _min = Point()
private var _prevStamp: Double = 0.toDouble()
private var _curStamp: Double = 0.toDouble()
companion object {
private fun applyAccelertion(v: Float, a: Float, dt: Float): Float {
var v = v
val prev = v
v += a * dt
// if we decelerate past zero velocity, stop
return if (prev.sign == v.sign) v else 0f
}
}
}
| apache-2.0 | 746767cbb23085e576e11331c5b290d0 | 32.536585 | 97 | 0.602473 | 3.775398 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt | 6 | 3498 | // 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.loopToCallChain.result
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.FilterTransformationBase
import org.jetbrains.kotlin.psi.*
class CountTransformation(
loop: KtForExpression,
private val inputVariable: KtCallableDeclaration,
initialization: VariableInitialization,
private val filter: KtExpression?
) : AssignToVariableResultTransformation(loop, initialization) {
override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? {
if (previousTransformation !is FilterTransformationBase) return null
if (previousTransformation.indexVariable != null) return null
val newFilter = if (filter == null)
previousTransformation.effectiveCondition.asExpression(reformat)
else
KtPsiFactory(filter).createExpressionByPattern(
"$0 && $1", previousTransformation.effectiveCondition.asExpression(reformat), filter,
reformat = reformat
)
return CountTransformation(loop, previousTransformation.inputVariable, initialization, newFilter)
}
override val presentation: String
get() = "count" + (if (filter != null) "{}" else "()")
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val reformat = chainedCallGenerator.reformat
val call = if (filter != null) {
val lambda = generateLambda(inputVariable, filter, reformat)
chainedCallGenerator.generate("count $0:'{}'", lambda)
} else {
chainedCallGenerator.generate("count()")
}
return if (initialization.initializer.isZeroConstant()) {
call
} else {
KtPsiFactory(call).createExpressionByPattern("$0 + $1", initialization.initializer, call, reformat = reformat)
}
}
/**
* Matches:
* val variable = 0
* for (...) {
* ...
* variable++ (or ++variable)
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = false
override val shouldUseInputVariables: Boolean
get() = false
override fun match(state: MatchingState): TransformationMatch.Result? {
val operand = state.statements.singleOrNull()?.isPlusPlusOf() ?: return null
val initialization =
operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null
// this should be the only usage of this variable inside the loop
if (initialization.variable.countUsages(state.outerLoop) != 1) return null
val variableType = initialization.variable.resolveToDescriptorIfAny()?.type ?: return null
if (!KotlinBuiltIns.isInt(variableType)) return null
val transformation = CountTransformation(state.outerLoop, state.inputVariable, initialization, null)
return TransformationMatch.Result(transformation)
}
}
} | apache-2.0 | 74dc0f8e5521ce7c016def4099c39fff | 42.7375 | 158 | 0.68582 | 5.431677 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.kt | 3 | 11630 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.PlainTextLikeFileType
import com.intellij.openapi.fileTypes.impl.DetectedByContentFileType
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import com.intellij.ui.EditorNotifications
import com.intellij.ui.HyperlinkLabel
import org.jetbrains.annotations.VisibleForTesting
import java.awt.BorderLayout
import java.util.function.Function
import javax.swing.JComponent
import javax.swing.JLabel
class PluginAdvertiserEditorNotificationProvider : EditorNotificationProvider,
DumbAware {
override fun collectNotificationData(
project: Project,
file: VirtualFile,
): Function<in FileEditor, out JComponent?> {
val suggestionData = getSuggestionData(project, ApplicationInfo.getInstance().build.productCode, file.name, file.fileType)
if (suggestionData == null) {
ProcessIOExecutorService.INSTANCE.execute {
val marketplaceRequests = MarketplaceRequests.getInstance()
marketplaceRequests.loadJetBrainsPluginsIds()
marketplaceRequests.loadExtensionsForIdes()
val extensionsStateService = PluginAdvertiserExtensionsStateService.instance
var shouldUpdateNotifications = extensionsStateService.updateCache(file.name)
val fullExtension = PluginAdvertiserExtensionsStateService.getFullExtension(file.name)
if (fullExtension != null) {
shouldUpdateNotifications = extensionsStateService.updateCache(fullExtension) || shouldUpdateNotifications
}
if (shouldUpdateNotifications) {
ApplicationManager.getApplication().invokeLater(
{ EditorNotifications.getInstance(project).updateNotifications(file) },
project.disposed
)
}
LOG.debug("Tried to update extensions cache for file '${file.name}'. shouldUpdateNotifications=$shouldUpdateNotifications")
}
return EditorNotificationProvider.CONST_NULL
}
return suggestionData
}
class AdvertiserSuggestion(
private val project: Project,
private val extensionOrFileName: String,
dataSet: Set<PluginData>,
jbPluginsIds: Set<String>,
val suggestedIdes: List<SuggestedIde>,
) : Function<FileEditor, EditorNotificationPanel?> {
private var installedPlugin: IdeaPluginDescriptor? = null
private val jbProduced = mutableSetOf<PluginData>()
@VisibleForTesting
val thirdParty = mutableSetOf<PluginData>()
init {
val descriptorsById = PluginManagerCore.buildPluginIdMap()
for (data in dataSet) {
val pluginId = data.pluginId
if (pluginId in descriptorsById) {
installedPlugin = descriptorsById[pluginId]
}
else if (!data.isBundled) {
(if (jbPluginsIds.contains(pluginId.idString)) jbProduced else thirdParty) += data
}
}
}
override fun apply(fileEditor: FileEditor): EditorNotificationPanel? {
lateinit var label: JLabel
val panel = object : EditorNotificationPanel(fileEditor) {
init {
label = myLabel
}
}
val pluginAdvertiserExtensionsState = PluginAdvertiserExtensionsStateService.instance.createExtensionDataProvider(project)
panel.text = IdeBundle.message("plugins.advertiser.plugins.found", extensionOrFileName)
fun createInstallActionLabel(plugins: Set<PluginData>) {
val labelText = plugins.singleOrNull()?.nullablePluginName?.let {
IdeBundle.message("plugins.advertiser.action.install.plugin.name", it)
} ?: IdeBundle.message("plugins.advertiser.action.install.plugins")
panel.createActionLabel(labelText) {
FUSEventSource.EDITOR.logInstallPlugins(plugins.map { it.pluginIdString })
installAndEnable(project, plugins.mapTo(HashSet()) { it.pluginId }, true) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
}
}
}
val installedPlugin = installedPlugin
if (installedPlugin != null) {
if (!installedPlugin.isEnabled) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.enable.plugin", installedPlugin.name)) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
FUSEventSource.EDITOR.logEnablePlugins(listOf(installedPlugin.pluginId.idString), project)
PluginManagerConfigurable.showPluginConfigurableAndEnable(project, setOf(installedPlugin))
}
}
else {
// Plugin supporting the pattern is installed and enabled but the current file is reassigned to a different
// file type
return null
}
}
else if (jbProduced.isNotEmpty()) {
createInstallActionLabel(jbProduced)
}
else if (suggestedIdes.isNotEmpty()) {
if (suggestedIdes.size > 1) {
val parentPanel = label.parent
parentPanel.remove(label)
val hyperlinkLabel = HyperlinkLabel().apply {
setTextWithHyperlink(IdeBundle.message("plugins.advertiser.extensions.supported.in.ides", extensionOrFileName))
addHyperlinkListener { FUSEventSource.EDITOR.learnMoreAndLog(project) }
}
parentPanel.add(hyperlinkLabel, BorderLayout.CENTER)
}
else {
panel.text = IdeBundle.message("plugins.advertiser.extensions.supported.in.ultimate", extensionOrFileName,
suggestedIdes.single().name)
}
for (suggestedIde in suggestedIdes) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.try.ultimate", suggestedIde.name)) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
FUSEventSource.EDITOR.openDownloadPageAndLog(project, suggestedIde.downloadUrl)
}
}
if (suggestedIdes.size == 1) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.learn.more")) {
FUSEventSource.EDITOR.learnMoreAndLog(project)
}
}
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.ignore.ultimate")) {
FUSEventSource.EDITOR.doIgnoreUltimateAndLog(project)
updateAllNotifications(project)
}
return panel // Don't show the "Ignore extension" label
}
else if (thirdParty.isNotEmpty()) {
createInstallActionLabel(thirdParty)
}
else {
return null
}
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.ignore.extension")) {
FUSEventSource.EDITOR.logIgnoreExtension(project)
pluginAdvertiserExtensionsState.ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
}
return panel
}
}
data class SuggestedIde(val name: String, val downloadUrl: String)
companion object {
private val LOG = logger<PluginAdvertiserEditorNotificationProvider>()
@VisibleForTesting
fun getSuggestionData(
project: Project,
activeProductCode: String,
fileName: String,
fileType: FileType,
): AdvertiserSuggestion? {
return PluginAdvertiserExtensionsStateService.instance
.createExtensionDataProvider(project)
.requestExtensionData(fileName, fileType)?.let {
getSuggestionData(project, it, activeProductCode, fileType)
}
}
private fun getSuggestionData(
project: Project,
extensionsData: PluginAdvertiserExtensionsData,
activeProductCode: String,
fileType: FileType,
): AdvertiserSuggestion? {
val marketplaceRequests = MarketplaceRequests.getInstance()
val jbPluginsIds = marketplaceRequests.jetBrainsPluginsIds ?: return null
val ideExtensions = marketplaceRequests.extensionsForIdes ?: return null
val extensionOrFileName = extensionsData.extensionOrFileName
val dataSet = extensionsData.plugins
val hasBundledPlugin = getBundledPluginToInstall(dataSet).isNotEmpty()
val suggestedIdes = if (fileType is PlainTextLikeFileType || fileType is DetectedByContentFileType) {
getSuggestedIdes(activeProductCode, extensionOrFileName, ideExtensions).ifEmpty {
if (hasBundledPlugin && !isIgnoreIdeSuggestion) listOf(ideaUltimate) else emptyList()
}
}
else
emptyList()
return AdvertiserSuggestion(project, extensionOrFileName, dataSet, jbPluginsIds, suggestedIdes)
}
private fun getSuggestedIdes(activeProductCode: String, extensionOrFileName: String, ideExtensions: Map<String, List<String>>): List<SuggestedIde> {
if (isIgnoreIdeSuggestion) {
return emptyList()
}
val productCodes = ideExtensions[extensionOrFileName]
if (productCodes.isNullOrEmpty()) {
return emptyList()
}
val suggestedIde = ides.entries.firstOrNull { it.key in productCodes }
val commercialVersionCode = when (activeProductCode) {
"IC", "IE" -> "IU"
"PC", "PE" -> "PY"
else -> null
}
if (commercialVersionCode != null && suggestedIde != null && suggestedIde.key != commercialVersionCode) {
return listOf(suggestedIde.value, ides[commercialVersionCode]!!)
}
else {
return suggestedIde?.value?.let { listOf(it) } ?: emptyList()
}
}
private fun updateAllNotifications(project: Project) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
val ideaUltimate = SuggestedIde("IntelliJ IDEA Ultimate", "https://www.jetbrains.com/idea/download/")
val pyCharmProfessional = SuggestedIde("PyCharm Professional", "https://www.jetbrains.com/pycharm/download/")
private val ides = linkedMapOf(
"WS" to SuggestedIde("WebStorm", "https://www.jetbrains.com/webstorm/download/"),
"RM" to SuggestedIde("RubyMine", "https://www.jetbrains.com/ruby/download/"),
"PY" to pyCharmProfessional,
"PS" to SuggestedIde("PhpStorm", "https://www.jetbrains.com/phpstorm/download/"),
"GO" to SuggestedIde("GoLand", "https://www.jetbrains.com/go/download/"),
"CL" to SuggestedIde("CLion", "https://www.jetbrains.com/clion/download/"),
"RD" to SuggestedIde("Rider", "https://www.jetbrains.com/rider/download/"),
"OC" to SuggestedIde("AppCode", "https://www.jetbrains.com/objc/download/"),
"IU" to ideaUltimate
)
}
} | apache-2.0 | 8476973aa6f6b30f7fcec37926632cf5 | 40.688172 | 152 | 0.712898 | 5.327531 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/lambdaArgumentInDiffirentPosition.kt | 12 | 249 | fun <X, Y> gener<caret>ic1(p: X, f: (X) -> Y): Y = f(p)
fun usage() {
val a = generic1("abc") { x -> x.length }
val b = generic1("abc", { x -> x.length })
val c = generic1("abc") { it.length }
val d = generic1("abc", { it.length })
} | apache-2.0 | 838c47406d638245644d49c32cf73318 | 34.714286 | 55 | 0.506024 | 2.540816 | false | false | false | false |
phylame/jem | jem-core/src/main/kotlin/jem/epm/Params.kt | 1 | 1499 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.epm
import jclp.io.extName
import jclp.setting.Settings
import jclp.text.or
import jem.Book
import java.io.File
data class ParserParam(val path: String, val format: String = "", val arguments: Settings? = null) {
val epmName inline get() = format or { extName(File(path).canonicalPath) }
override fun toString(): String =
"ParserParam(path='$path', format='$format', epmName='$epmName', arguments=$arguments)"
}
data class MakerParam(val book: Book, val path: String, val format: String = "", val arguments: Settings? = null) {
val epmName inline get() = format or { extName(File(path).canonicalPath) }
var actualPath: String = path
internal set
override fun toString(): String =
"MakerParam(book=$book, path='$path', format='$format', epmName='$epmName', arguments=$arguments)"
}
| apache-2.0 | 516e11d25dceab2002055b27542162ae | 34.690476 | 115 | 0.703803 | 3.955145 | false | false | false | false |
Seancheey/Ark-Sonah | src/com/seancheey/gui/BattleInspectPane.kt | 1 | 8383 | package com.seancheey.gui
import com.seancheey.game.Config
import com.seancheey.game.Game
import com.seancheey.game.GameDirector
import com.seancheey.game.model.GuiNode
import com.seancheey.game.model.Node
import com.seancheey.game.model.RobotModel
import com.seancheey.game.model.RobotNode
import javafx.scene.canvas.Canvas
import javafx.scene.input.KeyCode
import javafx.scene.input.MouseButton
import javafx.scene.layout.AnchorPane
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.transform.Affine
/**
* Created by Seancheey on 01/06/2017.
* GitHub: https://github.com/Seancheey
*/
class BattleInspectPane(val battleCanvas: BattleCanvas) : AnchorPane(), GameInspector by battleCanvas {
constructor(game: Game, clipWidth: Double, clipHeight: Double) : this(BattleCanvas(game, clipWidth, clipHeight))
init {
AnchorPane.setLeftAnchor(battleCanvas, 0.0)
AnchorPane.setTopAnchor(battleCanvas, 0.0)
children.add(battleCanvas)
clip = Rectangle((battleCanvas.guiWidth - battleCanvas.clipWidth) / 2, (battleCanvas.guiHeight - battleCanvas.clipHeight) / 2, battleCanvas.clipWidth, battleCanvas.clipHeight)
battleCanvas.drawGuiNode = { a, b -> drawGuiNode(a, b) }
battleCanvas.clearGuiNode = { clearGuiNodes() }
}
fun drawGuiNode(node: GuiNode, parentNode: Node) {
val parentX = parentNode.x * cameraScale - (battleCanvas.guiWidth * cameraScale - width) / 2 + cameraTransX
val parentY = parentNode.y * cameraScale - (battleCanvas.guiHeight * cameraScale - height) / 2 + cameraTransY
if (node.gui !in children) {
children.add(node.gui)
}
AnchorPane.setLeftAnchor(node.gui, node.leftX + parentX)
AnchorPane.setTopAnchor(node.gui, node.upperY + parentY)
}
fun clearGuiNodes() {
val guiNodes = arrayListOf<GuiNode>()
gameDirector.nodes.forEach {
guiNodes.addAll(it.children.filterIsInstance<GuiNode>())
}
val guis = guiNodes.map { it.gui }
val toRemove = children.filter { it !in guis && it != battleCanvas }
children.removeAll(toRemove)
}
class BattleCanvas(override val game: Game, val clipWidth: Double, val clipHeight: Double) : Canvas(game.field.width, game.field.height), GameInspector {
override fun clickRobot(model: RobotModel) {
if (!model.empty) {
battlefield.nodeAddQueue.add(RobotNode(model, battlefield, battlefield.width / 2, battlefield.height / 2, game.playerMap[Config.player]!!))
}
}
override var cameraTransX: Double = 0.0
set(value) {
field = value
translateX = value
clipCanvas()
}
override var cameraTransY: Double = 0.0
set(value) {
field = value
translateY = value
clipCanvas()
}
override var cameraScale: Double = 1.0
set(value) {
scaleX = value
scaleY = value
scaleZ = value
field = value
clipCanvas()
}
override val guiWidth: Double
get() = width
override val guiHeight: Double
get() = height
override val gameDirector: GameDirector = GameDirector(game, { nodes, lag ->
graphicsContext2D.restore()
graphicsContext2D.fill = Color.LIGHTGRAY
graphicsContext2D.fillRect(0.0, 0.0, this.width, this.height)
graphicsContext2D.save()
graphicsContext2D.fill = Color.ALICEBLUE
graphicsContext2D.scale(cameraScale, cameraScale)
nodes.forEach {
drawNode(it)
}
// request focus to handle key event
requestFocus()
cameraTransX += vx
cameraTransY += vy
// clear Gui Nodes
clearGuiNode()
})
private var vx: Double = 0.0
private var vy: Double = 0.0
var drawGuiNode: (GuiNode, Node) -> Unit = { _, _ -> }
var clearGuiNode: () -> Unit = {}
init {
clipCanvas()
fullMapScale()
setOnMouseClicked { event ->
if (event.button == MouseButton.PRIMARY) {
selectRobotBeside(event.x, event.y)
}
if (event.button == MouseButton.SECONDARY) {
moveFocusedRobotsTo(event.x, event.y)
}
if (event.button == MouseButton.MIDDLE) {
val nodes = gameDirector.nodes.filter { it.containsPoint(event.x, event.y) }.filterIsInstance<RobotModel>()
if (nodes.isNotEmpty()) {
val firstNode: RobotModel = nodes[0]
selectAllRobotsWithSameType(firstNode)
}
}
}
setOnScroll { event ->
if (event.deltaY > 0) {
cameraScale *= 1 - Config.scrollSpeedDelta
} else if (event.deltaY < 0) {
cameraScale *= 1 + Config.scrollSpeedDelta
}
}
setOnKeyPressed { event ->
when (event.code) {
KeyCode.W ->
vy = 1.0
KeyCode.S ->
vy = -1.0
KeyCode.A ->
vx = 1.0
KeyCode.D ->
vx = -1.0
else -> return@setOnKeyPressed
}
}
setOnKeyReleased { event ->
when (event.code) {
KeyCode.A, KeyCode.D ->
vx = 0.0
KeyCode.W, KeyCode.S ->
vy = 0.0
else -> return@setOnKeyReleased
}
}
start()
}
fun fullMapScale() {
cameraScale = minOf(clipWidth / width, clipHeight / height)
}
fun start() {
gameDirector.start()
}
fun stop() {
gameDirector.stop = true
}
fun clipOffsetX() = (width - clipWidth / cameraScale) / 2 - translateX / cameraScale
fun clipOffsetY() = (height - clipHeight / cameraScale) / 2 - translateY / cameraScale
/**
* ensure the canvas doesn't come out
*/
private fun clipCanvas() {
val clipRect = Rectangle(clipOffsetX(), clipOffsetY(), clipWidth / cameraScale, clipHeight / cameraScale)
clip = clipRect
}
private fun nodeTranslation(node: Node): Affine {
return Affine(Affine.translate(node.leftX, node.upperY))
}
private fun nodeRotation(node: Node): Affine {
if (node is RobotNode) {
return Affine(Affine.rotate(node.degreeOrientation + 90.0, node.width / 2, node.height / 2))
} else {
return Affine(Affine.rotate(node.degreeOrientation, node.width / 2, node.height / 2))
}
}
private fun drawNode(node: Node, transform: Affine = Affine()) {
val originalTrans = graphicsContext2D.transform
val newTrans: Affine = transform
newTrans.append(nodeTranslation(node))
newTrans.append(nodeRotation(node))
graphicsContext2D.transform = newTrans
graphicsContext2D.drawImage(node.image, 0.0, 0.0, node.width, node.height)
// draw focus if apply
if (node.focusedByPlayer) {
drawFocus(node)
}
// recursively draw its children, assign a copy to prevent concurrency problem
val children = node.immutableChildren
children.forEach {
if (it is GuiNode) {
drawGuiNode(it, node)
} else {
drawNode(it, newTrans.clone())
}
}
graphicsContext2D.transform = originalTrans
}
private fun drawFocus(node: Node) {
graphicsContext2D.transform = Affine()
graphicsContext2D.strokeOval(node.leftX, node.upperY, node.width, node.height)
}
}
} | mit | d42d235a1353c01ea81df76af086b79f | 35.77193 | 183 | 0.550161 | 4.773918 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/usecases/creating_message_application/src/main/kotlin/com/example/sqs/SendReceiveMessages.kt | 1 | 4409 | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.sqs
import aws.sdk.kotlin.services.comprehend.ComprehendClient
import aws.sdk.kotlin.services.comprehend.model.DetectDominantLanguageRequest
import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest
import aws.sdk.kotlin.services.sqs.model.MessageAttributeValue
import aws.sdk.kotlin.services.sqs.model.PurgeQueueRequest
import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest
import aws.sdk.kotlin.services.sqs.model.SendMessageRequest
import org.springframework.stereotype.Component
@Component
class SendReceiveMessages {
private val queueNameVal = "Message.fifo"
// Purges the queue.
suspend fun purgeMyQueue() {
var queueUrlVal: String
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
SqsClient { region = "us-west-2" }.use { sqsClient ->
queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl.toString()
val queueRequest = PurgeQueueRequest {
queueUrl = queueUrlVal
}
sqsClient.purgeQueue(queueRequest)
}
}
// Retrieves messages from the FIFO queue.
suspend fun getMessages(): List<MessageData>? {
val attr: MutableList<String> = ArrayList()
attr.add("Name")
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
SqsClient { region = "us-west-2" }.use { sqsClient ->
val queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl
val receiveRequest = ReceiveMessageRequest {
queueUrl = queueUrlVal
maxNumberOfMessages = 10
waitTimeSeconds = 20
messageAttributeNames = attr
}
val messages = sqsClient.receiveMessage(receiveRequest).messages
var myMessage: MessageData
val allMessages = mutableListOf<MessageData>()
// Push the messages to a list.
if (messages != null) {
for (m in messages) {
myMessage = MessageData()
myMessage.body = m.body
myMessage.id = m.messageId
val map = m.messageAttributes
val `val` = map?.get("Name")
if (`val` != null) {
myMessage.name = `val`.stringValue
}
allMessages.add(myMessage)
}
}
return allMessages
}
}
// Adds a new message to the FIFO queue.
suspend fun processMessage(msg: MessageData) {
val attributeValue = MessageAttributeValue {
stringValue = msg.name
dataType = "String"
}
val myMap: MutableMap<String, MessageAttributeValue> = HashMap()
myMap["Name"] = attributeValue
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
// Get the language code of the incoming message.
var lanCode = ""
val request = DetectDominantLanguageRequest {
text = msg.body
}
ComprehendClient { region = "us-west-2" }.use { comClient ->
val resp = comClient.detectDominantLanguage(request)
val allLanList = resp.languages
if (allLanList != null) {
for (lang in allLanList) {
println("Language is " + lang.languageCode)
lanCode = lang.languageCode.toString()
}
}
}
// Send the message to the FIFO queue.
SqsClient { region = "us-west-2" }.use { sqsClient ->
val queueUrlVal: String? = sqsClient.getQueueUrl(getQueueRequest).queueUrl
val sendMsgRequest = SendMessageRequest {
queueUrl = queueUrlVal
messageAttributes = myMap
messageGroupId = "GroupA_$lanCode"
messageDeduplicationId = msg.id
messageBody = msg.body
}
sqsClient.sendMessage(sendMsgRequest)
}
}
}
| apache-2.0 | ffa2b2e054e412078074b6a2f1eaa276 | 34.139344 | 86 | 0.57496 | 5.108922 | false | false | false | false |
paplorinc/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GithubPullRequestStatePanel.kt | 1 | 8775 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.details
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.GithubIcons
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsBusyStateTracker
import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsSecurityService
import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsStateService
import org.jetbrains.plugins.github.util.GithubUtil.Delegates.equalVetoingObservable
import java.awt.FlowLayout
import java.awt.event.ActionEvent
import javax.swing.*
internal class GithubPullRequestStatePanel(private val model: GithubPullRequestDetailsModel,
private val securityService: GithubPullRequestsSecurityService,
private val busyStateTracker: GithubPullRequestsBusyStateTracker,
private val stateService: GithubPullRequestsStateService)
: NonOpaquePanel(VerticalFlowLayout(0, 0)), Disposable {
private val stateLabel = JLabel().apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0)
}
private val accessDeniedPanel = JLabel("Repository write access required to merge pull requests").apply {
foreground = UIUtil.getContextHelpForeground()
}
private val closeAction = object : AbstractAction("Close") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.close(number) }
}
}
private val closeButton = JButton(closeAction)
private val reopenAction = object : AbstractAction("Reopen") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.reopen(number) }
}
}
private val reopenButton = JButton(reopenAction)
private val mergeAction = object : AbstractAction("Merge...") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.merge(number) }
}
}
private val rebaseMergeAction = object : AbstractAction("Rebase and Merge") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.rebaseMerge(number) }
}
}
private val squashMergeAction = object : AbstractAction("Squash and Merge...") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.squashMerge(number) }
}
}
private val mergeButton = JBOptionButton(null, null)
private val browseButton = LinkLabel.create("Open on GitHub") {
model.details?.run { BrowserUtil.browse(htmlUrl) }
}.apply {
icon = AllIcons.Ide.External_link_arrow
setHorizontalTextPosition(SwingConstants.LEFT)
}
private val buttonsPanel = NonOpaquePanel(FlowLayout(FlowLayout.LEADING, 0, 0)).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0)
if (Registry.`is`("github.action.pullrequest.state.useapi")) {
add(mergeButton)
add(closeButton)
add(reopenButton)
}
else {
add(browseButton)
}
}
init {
isOpaque = false
add(stateLabel)
add(accessDeniedPanel)
add(buttonsPanel)
model.addDetailsChangedListener(this) {
state = model.details?.let {
GithubPullRequestStatePanel.State(it.number, it.state, it.merged, it.mergeable, it.rebaseable,
securityService.isCurrentUserWithPushAccess(), securityService.isCurrentUser(it.user),
securityService.isMergeAllowed(),
securityService.isRebaseMergeAllowed(),
securityService.isSquashMergeAllowed(),
securityService.isMergeForbiddenForProject(),
busyStateTracker.isBusy(it.number))
}
}
busyStateTracker.addPullRequestBusyStateListener(this) {
if (it == state?.number)
state = state?.copy(busy = busyStateTracker.isBusy(it))
}
}
private var state: GithubPullRequestStatePanel.State? by equalVetoingObservable<GithubPullRequestStatePanel.State?>(null) {
updateText(it)
updateActions(it)
}
private fun updateText(state: GithubPullRequestStatePanel.State?) {
if (state == null) {
stateLabel.text = ""
stateLabel.icon = null
accessDeniedPanel.isVisible = false
}
else {
if (state.state == GithubIssueState.closed) {
if (state.merged) {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is merged"
}
else {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is closed"
}
accessDeniedPanel.isVisible = false
}
else {
val mergeable = state.mergeable
if (mergeable == null) {
stateLabel.icon = AllIcons.RunConfigurations.TestNotRan
stateLabel.text = "Checking for ability to merge automatically..."
}
else {
if (mergeable) {
stateLabel.icon = AllIcons.RunConfigurations.TestPassed
stateLabel.text = "Branch has no conflicts with base branch"
}
else {
stateLabel.icon = AllIcons.RunConfigurations.TestFailed
stateLabel.text = "Branch has conflicts that must be resolved"
}
}
accessDeniedPanel.isVisible = !state.editAllowed
}
}
}
private fun updateActions(state: GithubPullRequestStatePanel.State?) {
if (state == null) {
reopenAction.isEnabled = false
reopenButton.isVisible = false
closeAction.isEnabled = false
closeButton.isVisible = false
mergeAction.isEnabled = false
rebaseMergeAction.isEnabled = false
squashMergeAction.isEnabled = false
mergeButton.action = null
mergeButton.options = emptyArray()
mergeButton.isVisible = false
browseButton.isVisible = false
}
else {
reopenButton.isVisible = (state.editAllowed || state.currentUserIsAuthor) && state.state == GithubIssueState.closed && !state.merged
reopenAction.isEnabled = reopenButton.isVisible && !state.busy
closeButton.isVisible = (state.editAllowed || state.currentUserIsAuthor) && state.state == GithubIssueState.open
closeAction.isEnabled = closeButton.isVisible && !state.busy
mergeButton.isVisible = state.editAllowed && state.state == GithubIssueState.open && !state.merged
mergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !state.busy && !state.mergeForbidden
rebaseMergeAction.isEnabled = mergeButton.isVisible && (state.rebaseable ?: false) && !state.busy && !state.mergeForbidden
squashMergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !state.busy && !state.mergeForbidden
mergeButton.optionTooltipText = if (state.mergeForbidden) "Merge actions are disabled for this project" else null
val allowedActions = mutableListOf<Action>()
if (state.mergeAllowed) allowedActions.add(mergeAction)
if (state.rebaseMergeAllowed) allowedActions.add(rebaseMergeAction)
if (state.squashMergeAllowed) allowedActions.add(squashMergeAction)
val action = allowedActions.firstOrNull()
val actions = if (allowedActions.size > 1) Array(allowedActions.size - 1) { allowedActions[it + 1] } else emptyArray()
mergeButton.action = action
mergeButton.options = actions
browseButton.isVisible = true
}
}
override fun dispose() {}
private data class State(val number: Long,
val state: GithubIssueState,
val merged: Boolean,
val mergeable: Boolean?,
val rebaseable: Boolean?,
val editAllowed: Boolean,
val currentUserIsAuthor: Boolean,
val mergeAllowed: Boolean,
val rebaseMergeAllowed: Boolean,
val squashMergeAllowed: Boolean,
val mergeForbidden: Boolean,
val busy: Boolean)
} | apache-2.0 | ff765c272cb2084fe2c33d31be092748 | 39.442396 | 140 | 0.669744 | 5.176991 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinFieldBreakpoint.kt | 1 | 13900 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.core.breakpoints
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.requests.Requestor
import com.intellij.debugger.ui.breakpoints.BreakpointCategory
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.FieldBreakpoint
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.Method
import com.sun.jdi.ReferenceType
import com.sun.jdi.event.*
import com.sun.jdi.request.EventRequest
import com.sun.jdi.request.MethodEntryRequest
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.symbols.KtKotlinPropertySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.debugger.base.util.safeAllLineLocations
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import javax.swing.Icon
class KotlinFieldBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
) : BreakpointWithHighlighter<KotlinPropertyBreakpointProperties>(project, breakpoint) {
companion object {
private val LOG = Logger.getInstance(KotlinFieldBreakpoint::class.java)
private val CATEGORY: Key<FieldBreakpoint> = BreakpointCategory.lookup("field_breakpoints")
}
private enum class BreakpointType {
FIELD,
METHOD
}
private var breakpointType: BreakpointType = BreakpointType.FIELD
override fun isValid(): Boolean {
return super.isValid() && evaluationElement != null
}
override fun reload() {
super.reload()
val callable = evaluationElement ?: return
val callableName = callable.name ?: return
setFieldName(callableName)
if (callable is KtProperty && callable.isTopLevel) {
properties.myClassName = JvmFileClassUtil.getFileClassInfoNoResolve(callable.getContainingKtFile()).fileClassFqName.asString()
} else {
val ktClass: KtClassOrObject? = PsiTreeUtil.getParentOfType(callable, KtClassOrObject::class.java)
if (ktClass is KtClassOrObject) {
val fqName = ktClass.fqName
if (fqName != null) {
properties.myClassName = fqName.asString()
}
}
}
isInstanceFiltersEnabled = false
}
override fun createRequestForPreparedClass(debugProcess: DebugProcessImpl?, refType: ReferenceType?) {
if (debugProcess == null || refType == null) return
breakpointType = evaluationElement?.let(::computeBreakpointType) ?: return
val vm = debugProcess.virtualMachineProxy
try {
if (properties.watchInitialization) {
val sourcePosition = sourcePosition
if (sourcePosition != null) {
debugProcess.positionManager
.locationsOfLine(refType, sourcePosition)
.filter { it.method().isConstructor || it.method().isStaticInitializer }
.forEach {
val request = debugProcess.requestsManager.createBreakpointRequest(this, it)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
}
}
}
when (breakpointType) {
BreakpointType.FIELD -> {
val field = refType.fieldByName(getFieldName())
if (field != null) {
val manager = debugProcess.requestsManager
if (properties.watchModification && vm.canWatchFieldModification()) {
val request = manager.createModificationWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Modification request added")
}
}
if (properties.watchAccess && vm.canWatchFieldAccess()) {
val request = manager.createAccessWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Field access request added (field = ${field.name()}; refType = ${refType.name()})")
}
}
}
}
BreakpointType.METHOD -> {
val fieldName = getFieldName()
if (properties.watchAccess) {
val getter = refType.methodsByName(JvmAbi.getterName(fieldName)).firstOrNull()
if (getter != null) {
createMethodBreakpoint(debugProcess, refType, getter)
}
}
if (properties.watchModification) {
val setter = refType.methodsByName(JvmAbi.setterName(fieldName)).firstOrNull()
if (setter != null) {
createMethodBreakpoint(debugProcess, refType, setter)
}
}
}
}
} catch (ex: Exception) {
LOG.debug(ex)
}
}
private fun computeBreakpointType(property: KtCallableDeclaration): BreakpointType {
return runReadAction {
analyze(property) {
val hasBackingField = when (val symbol = property.getSymbol()) {
is KtValueParameterSymbol -> symbol.generatedPrimaryConstructorProperty?.hasBackingField ?: false
is KtKotlinPropertySymbol -> symbol.hasBackingField
else -> false
}
if (hasBackingField) BreakpointType.FIELD else BreakpointType.METHOD
}
}
}
private fun createMethodBreakpoint(debugProcess: DebugProcessImpl, refType: ReferenceType, accessor: Method) {
val manager = debugProcess.requestsManager
val line = accessor.safeAllLineLocations().firstOrNull()
if (line != null) {
val request = manager.createBreakpointRequest(this, line)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
} else {
var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this)
if (entryRequest == null) {
entryRequest = manager.createMethodEntryRequest(this)!!
if (LOG.isDebugEnabled) {
LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})")
}
} else {
entryRequest.disable()
}
entryRequest.addClassFilter(refType)
manager.enableRequest(entryRequest)
}
}
private inline fun <reified T : EventRequest> findRequest(
debugProcess: DebugProcessImpl,
requestClass: Class<T>,
requestor: Requestor
): T? {
val requests = debugProcess.requestsManager.findRequests(requestor)
for (eventRequest in requests) {
if (eventRequest::class.java == requestClass) {
return eventRequest as T
}
}
return null
}
override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean {
if (breakpointType == BreakpointType.METHOD && !matchesEvent(event)) {
return false
}
return super.evaluateCondition(context, event)
}
private fun matchesEvent(event: LocatableEvent): Boolean {
val method = event.location()?.method()
// TODO check property type
return method != null && method.name() in getMethodsName()
}
private fun getMethodsName(): List<String> {
val fieldName = getFieldName()
return listOf(JvmAbi.getterName(fieldName), JvmAbi.setterName(fieldName))
}
override fun getEventMessage(event: LocatableEvent): String {
val location = event.location()!!
val locationQName = location.declaringType().name() + "." + location.method().name()
val locationFileName = try {
location.sourceName()
} catch (e: AbsentInformationException) {
fileName
} catch (e: InternalError) {
fileName
}
val locationLine = location.lineNumber()
when (event) {
is ModificationWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is AccessWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is MethodEntryEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.entry.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
is MethodExitEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.exit.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
}
return JavaDebuggerBundle.message(
"status.line.breakpoint.reached",
locationQName,
locationFileName,
locationLine
)
}
fun setFieldName(fieldName: String) {
properties.myFieldName = fieldName
}
@TestOnly
fun setWatchAccess(value: Boolean) {
properties.watchAccess = value
}
@TestOnly
fun setWatchModification(value: Boolean) {
properties.watchModification = value
}
@TestOnly
fun setWatchInitialization(value: Boolean) {
properties.watchInitialization = value
}
override fun getDisabledIcon(isMuted: Boolean): Icon {
val master = DebuggerManagerEx.getInstanceEx(myProject).breakpointManager.findMasterBreakpoint(this)
return when {
isMuted && master == null -> AllIcons.Debugger.Db_muted_disabled_field_breakpoint
isMuted && master != null -> AllIcons.Debugger.Db_muted_dep_field_breakpoint
master != null -> AllIcons.Debugger.Db_dep_field_breakpoint
else -> AllIcons.Debugger.Db_disabled_field_breakpoint
}
}
override fun getSetIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_field_breakpoint
}
}
override fun getVerifiedIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_verified_field_breakpoint
}
}
override fun getVerifiedWarningsIcon(isMuted: Boolean): Icon = AllIcons.Debugger.Db_exception_breakpoint
override fun getCategory() = CATEGORY
override fun getDisplayName(): String {
if (!isValid) {
return JavaDebuggerBundle.message("status.breakpoint.invalid")
}
val className = className
@Suppress("HardCodedStringLiteral")
return if (!className.isNullOrEmpty()) className + "." + getFieldName() else getFieldName()
}
private fun getFieldName(): String {
return runReadAction {
evaluationElement?.name ?: "unknown"
}
}
override fun getEvaluationElement(): KtCallableDeclaration? {
return when (val callable = PositionUtil.getPsiElementAt(project, KtValVarKeywordOwner::class.java, sourcePosition)) {
is KtProperty -> callable
is KtParameter -> callable
else -> null
}
}
}
| apache-2.0 | f24d356f16a714e4d52c44e7940a2bab | 38.942529 | 138 | 0.596475 | 5.645816 | false | false | false | false |
apollographql/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/json/BufferedSourceJsonReader.kt | 1 | 32473 | /*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apollographql.apollo3.api.json
import com.apollographql.apollo3.api.json.internal.JsonScope
import com.apollographql.apollo3.exception.JsonDataException
import com.apollographql.apollo3.exception.JsonEncodingException
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
import okio.EOFException
import okio.IOException
/**
* A [JsonWriter] that reads json from an okio [BufferedSource]
*
* The base implementation was taken from Moshi and ported to Kotlin multiplatform with some tweaks to make it better suited for GraphQL
* (see [JsonReader]).
*
* To read from a [Map], see also [MapJsonReader]
*/
class BufferedSourceJsonReader(private val source: BufferedSource) : JsonReader {
private val buffer: Buffer = source.buffer
private var peeked = PEEKED_NONE
/**
* A peeked value that was composed entirely of digits with an optional leading dash. Positive values may not have a leading 0.
*/
private var peekedLong: Long = 0
/**
* The number of characters in a peeked number literal. Increment 'pos' by this after reading a number.
*/
private var peekedNumberLength = 0
/**
* A peeked string that should be parsed on the next double, long or string.
* This is populated before a numeric value is parsed and used if that parsing fails.
*/
private var peekedString: String? = null
/**
* The nesting stack. Using a manual array rather than an ArrayList saves 20%.
* This stack permits up to MAX_STACK_SIZE levels of nesting including the top-level document.
* Deeper nesting is prone to trigger StackOverflowErrors.
*/
private val stack = IntArray(MAX_STACK_SIZE).apply {
this[0] = JsonScope.EMPTY_DOCUMENT
}
private var stackSize = 1
private val pathNames = arrayOfNulls<String>(MAX_STACK_SIZE)
private val pathIndices = IntArray(MAX_STACK_SIZE)
private var lenient = false
private val indexStack = IntArray(MAX_STACK_SIZE).apply {
this[0] = 0
}
private var indexStackSize = 1
override fun beginArray(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_BEGIN_ARRAY) {
push(JsonScope.EMPTY_ARRAY)
pathIndices[stackSize - 1] = 0
peeked = PEEKED_NONE
} else {
throw JsonDataException("Expected BEGIN_ARRAY but was ${peek()} at path ${getPath()}")
}
}
override fun endArray(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_END_ARRAY) {
stackSize--
pathIndices[stackSize - 1]++
peeked = PEEKED_NONE
} else {
throw JsonDataException("Expected END_ARRAY but was ${peek()} at path ${getPath()}")
}
}
override fun beginObject(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_BEGIN_OBJECT) {
push(JsonScope.EMPTY_OBJECT)
peeked = PEEKED_NONE
indexStackSize++
indexStack[indexStackSize - 1] = 0
} else {
throw JsonDataException("Expected BEGIN_OBJECT but was ${peek()} at path ${getPath()}")
}
}
override fun endObject(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_END_OBJECT) {
stackSize--
pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
pathIndices[stackSize - 1]++
peeked = PEEKED_NONE
indexStackSize--
} else {
throw JsonDataException("Expected END_OBJECT but was ${peek()} at path ${getPath()}")
}
}
override fun hasNext(): Boolean {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY
}
override fun peek(): JsonReader.Token {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_BEGIN_OBJECT -> JsonReader.Token.BEGIN_OBJECT
PEEKED_END_OBJECT -> JsonReader.Token.END_OBJECT
PEEKED_BEGIN_ARRAY -> JsonReader.Token.BEGIN_ARRAY
PEEKED_END_ARRAY -> JsonReader.Token.END_ARRAY
PEEKED_SINGLE_QUOTED_NAME, PEEKED_DOUBLE_QUOTED_NAME, PEEKED_UNQUOTED_NAME -> JsonReader.Token.NAME
PEEKED_TRUE, PEEKED_FALSE -> JsonReader.Token.BOOLEAN
PEEKED_NULL -> JsonReader.Token.NULL
PEEKED_SINGLE_QUOTED, PEEKED_DOUBLE_QUOTED, PEEKED_UNQUOTED, PEEKED_BUFFERED -> JsonReader.Token.STRING
PEEKED_LONG -> JsonReader.Token.LONG
PEEKED_NUMBER -> JsonReader.Token.NUMBER
PEEKED_EOF -> JsonReader.Token.END_DOCUMENT
else -> throw AssertionError()
}
}
private fun doPeek(): Int {
val peekStack = stack[stackSize - 1]
when (peekStack) {
JsonScope.EMPTY_ARRAY -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY
}
JsonScope.NONEMPTY_ARRAY -> {
// Look for a comma before the next element.
val c = nextNonWhitespace(true)
buffer.readByte() // consume ']' or ','.
when (c.toChar()) {
']' -> return PEEKED_END_ARRAY.also { peeked = it }
';' -> checkLenient() // fall-through
',' -> Unit
else -> throw syntaxError("Unterminated array")
}
}
JsonScope.EMPTY_OBJECT, JsonScope.NONEMPTY_OBJECT -> {
stack[stackSize - 1] = JsonScope.DANGLING_NAME
// Look for a comma before the next element.
if (peekStack == JsonScope.NONEMPTY_OBJECT) {
val c = nextNonWhitespace(true)
buffer.readByte() // Consume '}' or ','.
when (c.toChar()) {
'}' -> return PEEKED_END_OBJECT.also { peeked = it }
';' -> checkLenient() // fall-through
',' -> Unit
else -> throw syntaxError("Unterminated object")
}
}
val c = nextNonWhitespace(true)
return when (c.toChar()) {
'"' -> {
buffer.readByte() // consume the '\"'.
PEEKED_DOUBLE_QUOTED_NAME.also { peeked = it }
}
'\'' -> {
buffer.readByte() // consume the '\''.
checkLenient()
PEEKED_SINGLE_QUOTED_NAME.also { peeked = it }
}
'}' -> if (peekStack != JsonScope.NONEMPTY_OBJECT) {
buffer.readByte() // consume the '}'.
PEEKED_END_OBJECT.also { peeked = it }
} else {
throw syntaxError("Expected name")
}
else -> {
checkLenient()
if (isLiteral(c.toChar())) {
PEEKED_UNQUOTED_NAME.also { peeked = it }
} else {
throw syntaxError("Expected name")
}
}
}
}
JsonScope.DANGLING_NAME -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT
// Look for a colon before the value.
val c = nextNonWhitespace(true)
buffer.readByte() // Consume ':'.
when (c.toChar()) {
':' -> {
}
'=' -> {
checkLenient()
if (source.request(1) && buffer[0] == '>'.code.toByte()) {
buffer.readByte() // Consume '>'.
}
}
else -> throw syntaxError("Expected ':'")
}
}
JsonScope.EMPTY_DOCUMENT -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT
}
JsonScope.NONEMPTY_DOCUMENT -> {
val c = nextNonWhitespace(false)
if (c == -1) {
return PEEKED_EOF.also { peeked = it }
} else {
checkLenient()
}
}
else -> check(peekStack != JsonScope.CLOSED) { "JsonReader is closed" }
}
val c = nextNonWhitespace(true)
when (c.toChar()) {
']' -> {
if (peekStack == JsonScope.EMPTY_ARRAY) {
buffer.readByte() // Consume ']'.
return PEEKED_END_ARRAY.also { peeked = it }
}
// In lenient mode, a 0-length literal in an array means 'null'.
return if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
checkLenient()
PEEKED_NULL.also { peeked = it }
} else {
throw syntaxError("Unexpected value")
}
}
';', ',' -> return if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
checkLenient()
PEEKED_NULL.also { peeked = it }
} else {
throw syntaxError("Unexpected value")
}
'\'' -> {
checkLenient()
buffer.readByte() // Consume '\''.
return PEEKED_SINGLE_QUOTED.also { peeked = it }
}
'"' -> {
buffer.readByte() // Consume '\"'.
return PEEKED_DOUBLE_QUOTED.also { peeked = it }
}
'[' -> {
buffer.readByte() // Consume '['.
return PEEKED_BEGIN_ARRAY.also { peeked = it }
}
'{' -> {
buffer.readByte() // Consume '{'.
return PEEKED_BEGIN_OBJECT.also { peeked = it }
}
}
var result = peekKeyword()
if (result != PEEKED_NONE) {
return result
}
result = peekNumber()
if (result != PEEKED_NONE) {
return result
}
if (!isLiteral(buffer[0].toInt().toChar())) {
throw syntaxError("Expected value")
}
checkLenient()
return PEEKED_UNQUOTED.also { peeked = it }
}
private fun peekKeyword(): Int { // Figure out which keyword we're matching against by its first character.
val keyword: String
val keywordUpper: String
val peeking: Int
when (buffer[0]) {
't'.code.toByte(), 'T'.code.toByte() -> {
keyword = "true"
keywordUpper = "TRUE"
peeking = PEEKED_TRUE
}
'f'.code.toByte(), 'F'.code.toByte() -> {
keyword = "false"
keywordUpper = "FALSE"
peeking = PEEKED_FALSE
}
'n'.code.toByte(), 'N'.code.toByte() -> {
keyword = "null"
keywordUpper = "NULL"
peeking = PEEKED_NULL
}
else -> return PEEKED_NONE
}
// Confirm that chars [1..length) match the keyword.
val length = keyword.length
for (i in 1 until length) {
if (!source.request(i + 1.toLong())) {
return PEEKED_NONE
}
val c = buffer[i.toLong()]
if (c != keyword[i].code.toByte() && c != keywordUpper[i].code.toByte()) {
return PEEKED_NONE
}
}
if (source.request(length + 1.toLong()) && isLiteral(buffer[length.toLong()].toInt().toChar())) {
return PEEKED_NONE // Don't match trues, falsey or nullsoft!
}
// We've found the keyword followed either by EOF or by a non-literal character.
buffer.skip(length.toLong())
return peeking.also { peeked = it }
}
private fun peekNumber(): Int {
var value: Long = 0 // Negative to accommodate Long.MIN_VALUE more easily.
var negative = false
var fitsInLong = true
var last = NUMBER_CHAR_NONE
var i = 0
loop@ while (source.request(i + 1.toLong())) {
val c = buffer[i.toLong()]
when (c.toInt().toChar()) {
'-' -> {
when (last) {
NUMBER_CHAR_NONE -> {
negative = true
last = NUMBER_CHAR_SIGN
}
NUMBER_CHAR_EXP_E -> {
last = NUMBER_CHAR_EXP_SIGN
}
else -> {
return PEEKED_NONE
}
}
}
'+' -> {
if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN
} else {
return PEEKED_NONE
}
}
'e', 'E' -> {
if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
last = NUMBER_CHAR_EXP_E
} else {
return PEEKED_NONE
}
}
'.' -> {
if (last == NUMBER_CHAR_DIGIT) {
last = NUMBER_CHAR_DECIMAL
} else {
return PEEKED_NONE
}
}
else -> {
if (c < '0'.code.toByte() || c > '9'.code.toByte()) {
if (!isLiteral(c.toInt().toChar())) {
break@loop
} else {
return PEEKED_NONE
}
}
when (last) {
NUMBER_CHAR_SIGN, NUMBER_CHAR_NONE -> {
value = -(c - '0'.code.toByte()).toLong()
last = NUMBER_CHAR_DIGIT
}
NUMBER_CHAR_DIGIT -> {
if (value == 0L) {
return PEEKED_NONE // Leading '0' prefix is not allowed (since it could be octal).
}
val newValue = value * 10 - (c - '0'.code.toByte())
fitsInLong = fitsInLong and (value > MIN_INCOMPLETE_INTEGER) || value == MIN_INCOMPLETE_INTEGER && newValue < value
value = newValue
}
NUMBER_CHAR_DECIMAL -> {
last = NUMBER_CHAR_FRACTION_DIGIT
}
NUMBER_CHAR_EXP_E, NUMBER_CHAR_EXP_SIGN -> {
last = NUMBER_CHAR_EXP_DIGIT
}
}
}
}
i++
}
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
return if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
peekedLong = if (negative) value else -value
buffer.skip(i.toLong())
PEEKED_LONG.also { peeked = it }
} else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) {
peekedNumberLength = i
PEEKED_NUMBER.also { peeked = it }
} else {
PEEKED_NONE
}
}
private fun isLiteral(c: Char): Boolean {
return when (c) {
'/', '\\', ';', '#', '=' -> {
checkLenient() // fall-through
false
}
'{', '}', '[', ']', ':', ',', ' ', '\t', '\r', '\n' -> false
else -> true
}
}
override fun nextName(): String {
val result = when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_UNQUOTED_NAME -> nextUnquotedValue()
PEEKED_DOUBLE_QUOTED_NAME -> nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
PEEKED_SINGLE_QUOTED_NAME -> nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
else -> throw JsonDataException("Expected a name but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_NONE
pathNames[stackSize - 1] = result
return result
}
override fun nextString(): String? {
val result = when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_UNQUOTED -> nextUnquotedValue()
PEEKED_DOUBLE_QUOTED -> nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
PEEKED_SINGLE_QUOTED -> nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
PEEKED_BUFFERED -> peekedString?.also { peekedString = null }
PEEKED_LONG -> peekedLong.toString()
PEEKED_NUMBER -> buffer.readUtf8(peekedNumberLength.toLong())
else -> throw JsonDataException("Expected a string but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextBoolean(): Boolean {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_TRUE -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
true
}
PEEKED_FALSE -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
false
}
else -> throw JsonDataException("Expected a boolean but was ${peek()} at path ${getPath()}")
}
}
override fun nextNull(): Nothing? {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_NULL -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
null
}
else -> throw JsonDataException("Expected null but was ${peek()} at path ${getPath()}")
}
}
override fun nextDouble(): Double {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return peekedLong.toDouble()
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED -> {
peekedString = nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
}
p == PEEKED_SINGLE_QUOTED -> {
peekedString = nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
}
p == PEEKED_UNQUOTED -> {
peekedString = nextUnquotedValue()
}
p != PEEKED_BUFFERED -> throw JsonDataException("Expected a double but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_BUFFERED
val result = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected a double but was $peekedString at path ${getPath()}")
}
if (!lenient && (result.isNaN() || result.isInfinite())) {
throw JsonEncodingException("JSON forbids NaN and infinities: $result at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextLong(): Long {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return peekedLong
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED || p == PEEKED_SINGLE_QUOTED -> {
peekedString = if (p == PEEKED_DOUBLE_QUOTED) nextQuotedValue(DOUBLE_QUOTE_OR_SLASH) else nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
try {
val result = peekedString!!.toLong()
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
} catch (ignored: NumberFormatException) { // Fall back to parse as a double below.
}
}
p != PEEKED_BUFFERED -> throw JsonDataException("Expected a long but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_BUFFERED
val asDouble: Double = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected a long but was $peekedString at path ${getPath()}")
}
val result = asDouble.toLong()
if (result.toDouble() != asDouble) { // Make sure no precision was lost casting to 'long'.
throw JsonDataException("Expected a long but was $peekedString at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextNumber(): JsonNumber {
return JsonNumber(nextString()!!)
}
/**
* Returns the string up to but not including `quote`, unescaping any character escape
* sequences encountered along the way. The opening quote should have already been read. This
* consumes the closing quote, but does not include it in the returned string.
*
* @throws okio.IOException if any unicode escape sequences are malformed.
*/
private fun nextQuotedValue(runTerminator: ByteString): String {
var builder: StringBuilder? = null
while (true) {
val index = source.indexOfElement(runTerminator)
if (index == -1L) throw syntaxError("Unterminated string")
// If we've got an escape character, we're going to need a string builder.
if (buffer[index] == '\\'.code.toByte()) {
if (builder == null) builder = StringBuilder()
builder.append(buffer.readUtf8(index))
buffer.readByte() // '\'
builder.append(readEscapeCharacter())
continue
}
// If it isn't the escape character, it's the quote. Return the string.
return if (builder == null) {
val result = buffer.readUtf8(index)
buffer.readByte() // Consume the quote character.
result
} else {
builder.append(buffer.readUtf8(index))
buffer.readByte() // Consume the quote character.
builder.toString()
}
}
}
/** Returns an unquoted value as a string. */
private fun nextUnquotedValue(): String {
val i = source.indexOfElement(UNQUOTED_STRING_TERMINALS)
return if (i != -1L) buffer.readUtf8(i) else buffer.readUtf8()
}
private fun skipQuotedValue(runTerminator: ByteString) {
while (true) {
val index = source.indexOfElement(runTerminator)
if (index == -1L) throw syntaxError("Unterminated string")
if (buffer[index] == '\\'.code.toByte()) {
buffer.skip(index + 1)
readEscapeCharacter()
} else {
buffer.skip(index + 1)
return
}
}
}
private fun skipUnquotedValue() {
val i = source.indexOfElement(UNQUOTED_STRING_TERMINALS)
buffer.skip(if (i != -1L) i else buffer.size)
}
override fun nextInt(): Int {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
val result = peekedLong.toInt()
if (peekedLong != result.toLong()) { // Make sure no precision was lost casting to 'int'.
throw JsonDataException("Expected an int but was " + peekedLong
+ " at path " + getPath())
}
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED || p == PEEKED_SINGLE_QUOTED -> {
peekedString = if (p == PEEKED_DOUBLE_QUOTED) nextQuotedValue(DOUBLE_QUOTE_OR_SLASH) else nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
try {
val result = peekedString!!.toInt()
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
} catch (ignored: NumberFormatException) { // Fall back to parse as a double below.
}
}
p != PEEKED_BUFFERED -> {
throw JsonDataException("Expected an int but was ${peek()} at path ${getPath()}")
}
}
peeked = PEEKED_BUFFERED
val asDouble: Double = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected an int but was $peekedString at path ${getPath()}")
}
val result = asDouble.toInt()
if (result.toDouble() != asDouble) { // Make sure no precision was lost casting to 'int'.
throw JsonDataException("Expected an int but was $peekedString at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun close() {
peeked = PEEKED_NONE
stack[0] = JsonScope.CLOSED
stackSize = 1
buffer.clear()
source.close()
}
override fun skipValue() {
var count = 0
do {
when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_BEGIN_ARRAY -> {
push(JsonScope.EMPTY_ARRAY)
count++
}
PEEKED_BEGIN_OBJECT -> {
push(JsonScope.EMPTY_OBJECT)
count++
}
PEEKED_END_ARRAY -> {
stackSize--
count--
}
PEEKED_END_OBJECT -> {
stackSize--
count--
}
PEEKED_UNQUOTED_NAME, PEEKED_UNQUOTED -> {
skipUnquotedValue()
}
PEEKED_DOUBLE_QUOTED, PEEKED_DOUBLE_QUOTED_NAME -> {
skipQuotedValue(DOUBLE_QUOTE_OR_SLASH)
}
PEEKED_SINGLE_QUOTED, PEEKED_SINGLE_QUOTED_NAME -> {
skipQuotedValue(SINGLE_QUOTE_OR_SLASH)
}
PEEKED_NUMBER -> {
buffer.skip(peekedNumberLength.toLong())
}
}
peeked = PEEKED_NONE
} while (count != 0)
pathIndices[stackSize - 1]++
pathNames[stackSize - 1] = "null"
}
override fun selectName(names: List<String>): Int {
if (names.isEmpty()) {
return -1
}
while (hasNext()) {
val name = nextName()
val expectedIndex = indexStack[indexStackSize - 1]
if (names[expectedIndex] == name) {
return expectedIndex.also {
indexStack[indexStackSize - 1] = expectedIndex + 1
if (indexStack[indexStackSize - 1] == names.size) {
indexStack[indexStackSize - 1] = 0
}
}
} else {
// guess failed, fallback to full search
var index = expectedIndex
while (true) {
index++
if (index == names.size) {
index = 0
}
if (index == expectedIndex) {
break
}
if (names[index] == name) {
return index.also {
indexStack[indexStackSize - 1] = index + 1
if (indexStack[indexStackSize - 1] == names.size) {
indexStack[indexStackSize - 1] = 0
}
}
}
}
skipValue()
}
}
return -1
}
private fun push(newTop: Int) {
if (stackSize == stack.size) throw JsonDataException("Nesting too deep at " + getPath())
stack[stackSize++] = newTop
}
/**
* Returns the next character in the stream that is neither whitespace nor a part of a comment.
* When this returns, the returned character is always at `buffer[pos-1]`; this means the caller can always push back the returned
* character by decrementing `pos`.
*/
private fun nextNonWhitespace(throwOnEof: Boolean): Int {
/**
* This code uses ugly local variables 'p' and 'l' representing the 'pos' and 'limit' fields respectively. Using locals rather than
* fields saves a few field reads for each whitespace character in a pretty-printed document, resulting in a 5% speedup.
* We need to flush 'p' to its field before any (potentially indirect) call to fillBuffer() and reread both 'p' and 'l' after any
* (potentially indirect) call to the same method.
*/
var p = 0
loop@ while (source.request(p + 1.toLong())) {
val c = buffer[p++.toLong()].toInt()
if (c == '\n'.code || c == ' '.code || c == '\r'.code || c == '\t'.code) {
continue
}
buffer.skip(p - 1.toLong())
if (c == '/'.code) {
if (!source.request(2)) {
return c
}
checkLenient()
val peek = buffer[1]
return when (peek.toInt().toChar()) {
'*' -> {
// skip a /* c-style comment */
buffer.readByte() // '/'
buffer.readByte() // '*'
if (!skipTo("*/")) {
throw syntaxError("Unterminated comment")
}
buffer.readByte() // '*'
buffer.readByte() // '/'
p = 0
continue@loop
}
'/' -> {
// skip a // end-of-line comment
buffer.readByte() // '/'
buffer.readByte() // '/'
skipToEndOfLine()
p = 0
continue@loop
}
else -> c
}
} else if (c == '#'.code) { // Skip a # hash end-of-line comment. The JSON RFC doesn't specify this behaviour, but it's
// required to parse existing documents.
checkLenient()
skipToEndOfLine()
p = 0
} else {
return c
}
}
return if (throwOnEof) {
throw EOFException("End of input")
} else {
-1
}
}
private fun checkLenient() {
if (!lenient) throw syntaxError("Use JsonReader.setLenient(true) to accept malformed JSON")
}
/**
* Advances the position until after the next newline character. If the line
* is terminated by "\r\n", the '\n' must be consumed as whitespace by the
* caller.
*/
private fun skipToEndOfLine() {
val index = source.indexOfElement(LINEFEED_OR_CARRIAGE_RETURN)
buffer.skip(if (index != -1L) index + 1 else buffer.size)
}
/**
* @param toFind a string to search for. Must not contain a newline.
*/
private fun skipTo(toFind: String): Boolean {
outer@ while (source.request(toFind.length.toLong())) {
for (c in toFind.indices) {
if (buffer[c.toLong()] != toFind[c].code.toByte()) {
buffer.readByte()
continue@outer
}
}
return true
}
return false
}
private fun getPath(): String = JsonScope.getPath(stackSize, stack, pathNames, pathIndices)
/**
* Unescapes the character identified by the character or characters that immediately follow a backslash. The backslash '\' should have
* already been read. This supports both unicode escapes "u000A" and two-character escapes "\n".
*
* @throws okio.IOException if any unicode escape sequences are malformed.
*/
private fun readEscapeCharacter(): Char {
if (!source.request(1)) throw syntaxError("Unterminated escape sequence")
return when (val escaped = buffer.readByte().toInt().toChar()) {
'u' -> {
if (!source.request(4)) {
throw EOFException("Unterminated escape sequence at path " + getPath())
}
// Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16);
var result = 0.toChar()
var i = 0
val end = i + 4
while (i < end) {
val c = buffer[i.toLong()]
result = (result.code shl 4).toChar()
result += when {
c >= '0'.code.toByte() && c <= '9'.code.toByte() -> (c - '0'.code.toByte())
c >= 'a'.code.toByte() && c <= 'f'.code.toByte() -> (c - 'a'.code.toByte() + 10)
c >= 'A'.code.toByte() && c <= 'F'.code.toByte() -> (c - 'A'.code.toByte() + 10)
else -> throw syntaxError("\\u" + buffer.readUtf8(4))
}
i++
}
buffer.skip(4)
result
}
't' -> '\t'
'b' -> '\b'
'n' -> '\n'
'r' -> '\r'
'f' -> '\u000C'
'\n', '\'', '"', '\\', '/' -> escaped
else -> {
if (!lenient) throw syntaxError("Invalid escape sequence: \\$escaped")
escaped
}
}
}
override fun rewind() {
error("BufferedSourceJsonReader cannot rewind.")
}
/**
* Returns a new exception with the given message and a context snippet with this reader's content.
*/
private fun syntaxError(message: String): JsonEncodingException =
JsonEncodingException(message + " at path " + getPath())
companion object {
private const val MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10
private val SINGLE_QUOTE_OR_SLASH = "'\\".encodeUtf8()
private val DOUBLE_QUOTE_OR_SLASH = "\"\\".encodeUtf8()
private val UNQUOTED_STRING_TERMINALS = "{}[]:, \n\t\r/\\;#=".encodeUtf8()
private val LINEFEED_OR_CARRIAGE_RETURN = "\n\r".encodeUtf8()
private const val PEEKED_NONE = 0
private const val PEEKED_BEGIN_OBJECT = 1
private const val PEEKED_END_OBJECT = 2
private const val PEEKED_BEGIN_ARRAY = 3
private const val PEEKED_END_ARRAY = 4
private const val PEEKED_TRUE = 5
private const val PEEKED_FALSE = 6
private const val PEEKED_NULL = 7
private const val PEEKED_SINGLE_QUOTED = 8
private const val PEEKED_DOUBLE_QUOTED = 9
private const val PEEKED_UNQUOTED = 10
/** When this is returned, the string value is stored in peekedString. */
private const val PEEKED_BUFFERED = 11
private const val PEEKED_SINGLE_QUOTED_NAME = 12
private const val PEEKED_DOUBLE_QUOTED_NAME = 13
private const val PEEKED_UNQUOTED_NAME = 14
/** When this is returned, the integer value is stored in peekedLong. */
private const val PEEKED_LONG = 15
private const val PEEKED_NUMBER = 16
private const val PEEKED_EOF = 17
/* State machine when parsing numbers */
private const val NUMBER_CHAR_NONE = 0
private const val NUMBER_CHAR_SIGN = 1
private const val NUMBER_CHAR_DIGIT = 2
private const val NUMBER_CHAR_DECIMAL = 3
private const val NUMBER_CHAR_FRACTION_DIGIT = 4
private const val NUMBER_CHAR_EXP_E = 5
private const val NUMBER_CHAR_EXP_SIGN = 6
private const val NUMBER_CHAR_EXP_DIGIT = 7
internal const val MAX_STACK_SIZE = 256
}
}
| mit | fd6c2a42e4c826dcb0b55dd3ca5612a0 | 31.867409 | 137 | 0.580174 | 4.327425 | false | false | false | false |
JetBrains/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt | 1 | 8457 | // 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.codegen
import com.intellij.openapi.util.registry.Registry
import com.intellij.workspaceModel.codegen.classes.*
import com.intellij.workspaceModel.codegen.deft.meta.ObjClass
import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty
import com.intellij.workspaceModel.codegen.deft.meta.OwnProperty
import com.intellij.workspaceModel.codegen.deft.meta.ValueType
import com.intellij.workspaceModel.codegen.engine.GenerationProblem
import com.intellij.workspaceModel.codegen.engine.ProblemLocation
import com.intellij.workspaceModel.codegen.engine.impl.ProblemReporter
import com.intellij.workspaceModel.codegen.fields.javaMutableType
import com.intellij.workspaceModel.codegen.fields.javaType
import com.intellij.workspaceModel.codegen.fields.wsCode
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.utils.fqn7
import com.intellij.workspaceModel.codegen.utils.lines
import com.intellij.workspaceModel.codegen.writer.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
val SKIPPED_TYPES: Set<String> = setOfNotNull(WorkspaceEntity::class.simpleName,
WorkspaceEntity.Builder::class.simpleName,
WorkspaceEntityWithSymbolicId::class.simpleName)
fun ObjClass<*>.generateBuilderCode(reporter: ProblemReporter): String = lines {
checkSuperTypes(this@generateBuilderCode, reporter)
line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})")
val (typeParameter, typeDeclaration) =
if (openness.extendable) "T" to "<T: $javaFullName>" else javaFullName to ""
val superBuilders = superTypes.filterIsInstance<ObjClass<*>>().filter { !it.isStandardInterface }.joinToString {
", ${it.name}.Builder<$typeParameter>"
}
val header = "interface Builder$typeDeclaration: $javaFullName$superBuilders, ${WorkspaceEntity.Builder::class.fqn}<$typeParameter>, ${ObjBuilder::class.fqn}<$typeParameter>"
section(header) {
list(allFields.noSymbolicId()) {
checkProperty(this, reporter)
wsBuilderApi
}
}
}
fun checkSuperTypes(objClass: ObjClass<*>, reporter: ProblemReporter) {
objClass.superTypes.filterIsInstance<ObjClass<*>>().forEach {superClass ->
if (!superClass.openness.extendable) {
reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended", GenerationProblem.Level.ERROR,
ProblemLocation.Class(objClass)))
}
else if (!superClass.openness.openHierarchy && superClass.module != objClass.module) {
reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended from other modules",
GenerationProblem.Level.ERROR, ProblemLocation.Class(objClass)))
}
}
}
private fun checkProperty(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
checkInheritance(objProperty, reporter)
checkPropertyType(objProperty, reporter)
}
fun checkInheritance(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
objProperty.receiver.allSuperClasses.mapNotNull { it.fieldsByName[objProperty.name] }.forEach { overriddenField ->
if (!overriddenField.open) {
reporter.reportProblem(
GenerationProblem("Property '${overriddenField.receiver.name}::${overriddenField.name}' cannot be overriden",
GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty)))
}
}
}
private fun checkPropertyType(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
val errorMessage = when (val type = objProperty.valueType) {
is ValueType.ObjRef<*> -> {
if (type.child) "Child references should always be nullable"
else null
}
else -> checkType(type)
}
if (errorMessage != null) {
reporter.reportProblem(GenerationProblem(errorMessage, GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty)))
}
}
private fun checkType(type: ValueType<*>): String? = when (type) {
is ValueType.Optional -> when (type.type) {
is ValueType.List<*> -> "Optional lists aren't supported"
is ValueType.Set<*> -> "Optional sets aren't supported"
else -> checkType(type.type)
}
is ValueType.Set<*> -> {
if (type.elementType.isRefType()) {
"Set of references isn't supported"
}
else checkType(type.elementType)
}
is ValueType.Map<*, *> -> {
checkType(type.keyType) ?: checkType(type.valueType)
}
is ValueType.Blob<*> -> {
if (!keepUnknownFields && type.javaClassName !in knownInterfaces) {
"Unsupported type '${type.javaClassName}'"
}
else null
}
else -> null
}
private val keepUnknownFields: Boolean
get() = Registry.`is`("workspace.model.generator.keep.unknown.fields")
private val knownInterfaces = setOf(
VirtualFileUrl::class.qualifiedName!!,
EntitySource::class.qualifiedName!!,
SymbolicEntityId::class.qualifiedName!!,
)
fun ObjClass<*>.generateCompanionObject(): String = lines {
val builderGeneric = if (openness.extendable) "<$javaFullName>" else ""
val companionObjectHeader = buildString {
append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(")
val base = superTypes.filterIsInstance<ObjClass<*>>().firstOrNull()
if (base != null && base.name !in SKIPPED_TYPES)
append(base.javaFullName)
append(")")
}
val mandatoryFields = allFields.mandatoryFields()
if (mandatoryFields.isNotEmpty()) {
val fields = mandatoryFields.joinToString { "${it.name}: ${it.valueType.javaType}" }
section(companionObjectHeader) {
line("@${JvmOverloads::class.fqn}")
line("@${JvmStatic::class.fqn}")
line("@${JvmName::class.fqn}(\"create\")")
section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
list(mandatoryFields) {
if (this.valueType is ValueType.Set<*> && !this.valueType.isRefType()) {
"builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceSet)}()"
} else if (this.valueType is ValueType.List<*> && !this.valueType.isRefType()) {
"builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceList)}()"
} else {
"builder.$name = $name"
}
}
line("init?.invoke(builder)")
line("return builder")
}
}
}
else {
section(companionObjectHeader) {
line("@${JvmOverloads::class.fqn}")
line("@${JvmStatic::class.fqn}")
line("@${JvmName::class.fqn}(\"create\")")
section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
line("init?.invoke(builder)")
line("return builder")
}
}
}
}
fun List<OwnProperty<*, *>>.mandatoryFields(): List<ObjProperty<*, *>> {
var fields = this.noRefs().noOptional().noSymbolicId().noDefaultValue()
if (fields.isNotEmpty()) {
fields = fields.noEntitySource() + fields.single { it.name == "entitySource" }
}
return fields
}
fun ObjClass<*>.generateExtensionCode(): String? {
val fields = module.extensions.filter { it.receiver == this || it.receiver.module != module && it.valueType.isRefType() && it.valueType.getRefType().target == this }
if (openness.extendable && fields.isEmpty()) return null
return lines {
if (!openness.extendable) {
line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)")
}
fields.sortedWith(compareBy({ it.receiver.name }, { it.name })).forEach { line(it.wsCode) }
}
}
val ObjProperty<*, *>.wsBuilderApi: String
get() {
val returnType = if (valueType is ValueType.Collection<*, *> && !valueType.isRefType()) valueType.javaMutableType else valueType.javaType
return "override var $javaName: $returnType"
}
| apache-2.0 | ebe32c6aebe9df6c6d1e198e3d92f36f | 42.592784 | 184 | 0.700485 | 4.496013 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/util/Keys.kt | 3 | 4456 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.util
enum class Key {
ENTER,
BACK_SPACE,
TAB,
CANCEL,
CLEAR,
PAUSE,
CAPS_LOCK,
ESCAPE,
SPACE,
PAGE_UP,
PAGE_DOWN,
END,
HOME,
LEFT,
UP,
RIGHT,
DOWN,
COMMA,
MINUS,
PERIOD,
SLASH,
d0,
d1,
d2,
d3,
d4,
d5,
d6,
d7,
d8,
d9,
SEMICOLON,
EQUALS,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
OPEN_BRACKET,
BACK_SLASH,
CLOSE_BRACKET,
NUMPAD0,
NUMPAD1,
NUMPAD2,
NUMPAD3,
NUMPAD4,
NUMPAD5,
NUMPAD6,
NUMPAD7,
NUMPAD8,
NUMPAD9,
MULTIPLY,
ADD,
SEPARATER,
SEPARATOR,
SUBTRACT,
DECIMAL,
DIVIDE,
DELETE,
NUM_LOCK,
SCROLL_LOCK,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
PRINTSCREEN,
INSERT,
HELP,
BACK_QUOTE,
QUOTE,
KP_UP,
KP_DOWN,
KP_LEFT,
KP_RIGHT,
DEAD_GRAVE,
DEAD_ACUTE,
DEAD_CIRCUMFLEX,
DEAD_TILDE,
DEAD_MACRON,
DEAD_BREVE,
DEAD_ABOVEDOT,
DEAD_DIAERESIS,
DEAD_ABOVERING,
DEAD_DOUBLEACUTE,
DEAD_CARON,
DEAD_CEDILLA,
DEAD_OGONEK,
DEAD_IOTA,
DEAD_VOICED,
DEAD_SEMIVOICED,
AMPERSAND,
ASTERISK,
QUOTEDBL,
LESS,
GREATER,
BRACELEFT,
BRACERIGHT,
AT,
COLON,
CIRCUMFLEX,
DOLLAR,
EURO_SIGN,
EXCLAMATION_MARK,
INVERTED_EXCLAMATION,
LEFT_PARENTHESIS,
NUMBER_SIGN,
PLUS,
RIGHT_PARENTHESIS,
UNDERSCORE,
WINDOWS,
CONTEXT_MENU,
FINAL,
CONVERT,
NONCONVERT,
ACCEPT,
MODECHANGE,
KANA,
KANJI,
ALPHANUMERIC,
KATAKANA,
HIRAGANA,
FULL_WIDTH,
HALF_WIDTH,
ROMAN_CHARACTERS,
ALL_CANDIDATES,
PREVIOUS_CANDIDATE,
CODE_INPUT,
JAPANESE_KATAKANA,
JAPANESE_HIRAGANA,
JAPANESE_ROMAN,
KANA_LOCK,
INPUT_METHOD,
CUT,
COPY,
PASTE,
UNDO,
AGAIN,
FIND,
PROPS,
STOP,
COMPOSE,
BEGIN,
UNDEFINED
}
enum class Modifier {
SHIFT,
CONTROL,
ALT,
META,
ALT_GR
}
class Shortcut(var modifiers: HashSet<Modifier> = HashSet(), var key: Key? = null) {
fun getKeystroke(): String {
val mods = modifiers.toList().sorted().joinToString(" ") { it.name.toLowerCase() }
if (key == null) return ""
val cleanKeyName = (if (key!!.name.startsWith("d")) key!!.name.substring(1) else key!!.name).toLowerCase()
return if (mods.isNotEmpty()) "$mods $cleanKeyName" else cleanKeyName
}
override fun toString(): String = getKeystroke()
}
operator fun Modifier.plus(modifier: Modifier): Shortcut {
return Shortcut(hashSetOf(this, modifier), null)
}
operator fun Modifier.plus(key: Key): Shortcut {
return Shortcut(hashSetOf(this), key)
}
operator fun Shortcut.plus(modifier: Modifier): Shortcut {
return Shortcut(hashSetOf(*this.modifiers.toTypedArray(), modifier), null)
}
operator fun Shortcut.plus(key: Key): Shortcut {
if (this.key != null) throw Exception("Unable to merge shortcut with key ${this.key!!.name} and ${key.name}")
return Shortcut(this.modifiers, key)
}
operator fun Modifier.plus(shortcut: Shortcut): Shortcut {
val unionOfModifier = hashSetOf<Modifier>(this)
unionOfModifier.addAll(shortcut.modifiers)
return Shortcut(unionOfModifier, shortcut.key)
}
operator fun Shortcut.plus(shortcut: Shortcut): Shortcut {
if (this.key != null && shortcut.key != null) throw Exception(
"Unable to merge shortcut with key ${this.key!!.name} and ${shortcut.key!!.name}")
val unionOfModifier = hashSetOf<Modifier>()
unionOfModifier.addAll(this.modifiers)
unionOfModifier.addAll(shortcut.modifiers)
val newKey = if (this.key != null) this.key else shortcut.key
return Shortcut(unionOfModifier, newKey)
}
fun resolveKey(inputString: String): Key {
return if (Regex("\\d]").matches(inputString)) Key.valueOf("d$inputString")
else Key.valueOf(inputString)
} | apache-2.0 | 624286ada0abf38fa1f18a2a85dfd621 | 16.076628 | 111 | 0.665395 | 3.131413 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/flow/NumbersBenchmark.kt | 1 | 3178 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.flow
import benchmarks.flow.scrabble.flow
import io.reactivex.*
import io.reactivex.functions.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.Callable
@Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
open class NumbersBenchmark {
companion object {
private const val primes = 100
private const val natural = 1000L
}
private fun numbers(limit: Long = Long.MAX_VALUE) = flow {
for (i in 2L..limit) emit(i)
}
private fun primesFlow(): Flow<Long> = flow {
var source = numbers()
while (true) {
val next = source.take(1).single()
emit(next)
source = source.filter { it % next != 0L }
}
}
private fun rxNumbers() =
Flowable.generate(Callable { 1L }, BiFunction<Long, Emitter<Long>, Long> { state, emitter ->
val newState = state + 1
emitter.onNext(newState)
newState
})
private fun generateRxPrimes(): Flowable<Long> = Flowable.generate(Callable { rxNumbers() },
BiFunction<Flowable<Long>, Emitter<Long>, Flowable<Long>> { state, emitter ->
// Not the most fair comparison, but here we go
val prime = state.firstElement().blockingGet()
emitter.onNext(prime)
state.filter { it % prime != 0L }
})
@Benchmark
fun primes() = runBlocking {
primesFlow().take(primes).count()
}
@Benchmark
fun primesRx() = generateRxPrimes().take(primes.toLong()).count().blockingGet()
@Benchmark
fun zip() = runBlocking {
val numbers = numbers(natural)
val first = numbers
.filter { it % 2L != 0L }
.map { it * it }
val second = numbers
.filter { it % 2L == 0L }
.map { it * it }
first.zip(second) { v1, v2 -> v1 + v2 }.filter { it % 3 == 0L }.count()
}
@Benchmark
fun zipRx() {
val numbers = rxNumbers().take(natural)
val first = numbers
.filter { it % 2L != 0L }
.map { it * it }
val second = numbers
.filter { it % 2L == 0L }
.map { it * it }
first.zipWith(second, { v1, v2 -> v1 + v2 }).filter { it % 3 == 0L }.count()
.blockingGet()
}
@Benchmark
fun transformations(): Int = runBlocking {
numbers(natural)
.filter { it % 2L != 0L }
.map { it * it }
.filter { (it + 1) % 3 == 0L }.count()
}
@Benchmark
fun transformationsRx(): Long {
return rxNumbers().take(natural)
.filter { it % 2L != 0L }
.map { it * it }
.filter { (it + 1) % 3 == 0L }.count()
.blockingGet()
}
}
| apache-2.0 | f54d7b8e1841e0288815c1b4106e9dc3 | 28.700935 | 102 | 0.561359 | 3.947826 | false | false | false | false |
Szewek/FL | src/main/java/szewek/fl/kotlin/NBTX.kt | 1 | 1247 | package szewek.fl.kotlin
import net.minecraft.nbt.*
inline operator fun NBTTagCompound.get(s: String): NBTBase = getTag(s)
inline operator fun NBTTagCompound.set(s: String, tag: NBTBase) = setTag(s, tag)
inline operator fun NBTTagCompound.contains(s: String) = hasKey(s)
inline operator fun NBTTagList.plusAssign(tag: NBTBase) = appendTag(tag)
inline val NBTBase.asBoolean
get() = if (this is NBTPrimitive) this.byte != (0).toByte() else false
inline val NBTBase.asByte
get() = (this as? NBTPrimitive)?.byte ?: (0).toByte()
inline val NBTBase.asShort
get() = (this as? NBTPrimitive)?.short ?: (0).toShort()
inline val NBTBase.asInt
get() = (this as? NBTPrimitive)?.int ?: 0
inline val NBTBase.asLong
get() = (this as? NBTPrimitive)?.long ?: 0L
inline val NBTBase.asFloat
get() = (this as? NBTPrimitive)?.float ?: 0F
inline val NBTBase.asDouble
get() = (this as? NBTPrimitive)?.double ?: 0.0
inline val NBTBase.asString
get() = (this as? NBTTagString)?.string ?: ""
inline val NBTBase.asByteArray
get() = (this as? NBTTagByteArray)?.byteArray
inline val NBTBase.asIntArray
get() = (this as? NBTTagIntArray)?.intArray
inline val NBTBase.asCompound
get() = this as? NBTTagCompound
inline val NBTBase.asList
get() = this as? NBTTagList | mit | 901ee401770a4a6cfe2d27f22dd039d5 | 35.705882 | 80 | 0.729751 | 3.583333 | false | false | false | false |
zdary/intellij-community | plugins/ide-features-trainer/src/training/ui/views/LearningItems.kt | 1 | 7131 | // 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 training.ui.views
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.guessCurrentProject
import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.HeightLimitedPane
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.IconUtil
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.FeaturesTrainerIcons
import org.jetbrains.annotations.NotNull
import training.learn.CourseManager
import training.learn.LearnBundle
import training.learn.course.IftModule
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.ui.UISettings
import training.util.createBalloon
import training.util.learningProgressString
import training.util.rigid
import training.util.scaledRigid
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.border.EmptyBorder
private val HOVER_COLOR: Color get() = JBColor.namedColor("Plugins.hoverBackground", JBColor(0xEDF6FE, 0x464A4D))
class LearningItems : JPanel() {
var modules: List<IftModule> = emptyList()
private val expanded: MutableSet<IftModule> = mutableSetOf()
init {
name = "learningItems"
layout = BoxLayout(this, BoxLayout.Y_AXIS)
isOpaque = false
isFocusable = false
}
fun updateItems(showModule: IftModule? = null) {
if (showModule != null) expanded.add(showModule)
removeAll()
for (module in modules) {
if (module.lessons.isEmpty()) continue
add(createModuleItem(module))
if (expanded.contains(module)) {
for (lesson in module.lessons) {
add(createLessonItem(lesson))
}
}
}
revalidate()
repaint()
}
private fun createLessonItem(lesson: Lesson): JPanel {
val result = JPanel()
result.isOpaque = false
result.layout = BoxLayout(result, BoxLayout.X_AXIS)
result.alignmentX = LEFT_ALIGNMENT
result.border = EmptyBorder(JBUI.scale(7), JBUI.scale(7), JBUI.scale(6), JBUI.scale(7))
val checkmarkIconLabel = createLabelIcon(if (lesson.passed) FeaturesTrainerIcons.Img.GreenCheckmark else EmptyIcon.ICON_16)
result.add(createLabelIcon(EmptyIcon.ICON_16))
result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0))
result.add(checkmarkIconLabel)
val name = LinkLabel<Any>(lesson.name, null)
name.setListener(
{ _, _ ->
val project = guessCurrentProject(this)
val cantBeOpenedInDumb = DumbService.getInstance(project).isDumb && !lesson.properties.canStartInDumbMode
if (cantBeOpenedInDumb && !LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) {
val balloon = createBalloon(LearnBundle.message("indexing.message"))
balloon.showInCenterOf(name)
return@setListener
}
CourseManager.instance.openLesson(project, lesson)
}, null)
result.add(rigid(4, 0))
result.add(name)
return result
}
private fun createModuleItem(module: IftModule): JPanel {
val modulePanel = JPanel()
modulePanel.isOpaque = false
modulePanel.layout = BoxLayout(modulePanel, BoxLayout.Y_AXIS)
modulePanel.alignmentY = TOP_ALIGNMENT
modulePanel.background = Color(0, 0, 0, 0)
val result = object : JPanel() {
private var onInstall = true
override fun paint(g: Graphics?) {
if (onInstall && mouseAlreadyInside(this)) {
setCorrectBackgroundOnInstall(this)
onInstall = false
}
super.paint(g)
}
}
result.isOpaque = true
result.background = UISettings.instance.backgroundColor
result.layout = BoxLayout(result, BoxLayout.X_AXIS)
result.border = EmptyBorder(JBUI.scale(8), JBUI.scale(7), JBUI.scale(10), JBUI.scale(7))
result.alignmentX = LEFT_ALIGNMENT
val mouseAdapter = object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) {
if (!result.visibleRect.contains(e.point)) return
if (expanded.contains(module)) {
expanded.remove(module)
}
else {
expanded.clear()
expanded.add(module)
}
updateItems()
}
override fun mouseEntered(e: MouseEvent) {
setCorrectBackgroundOnInstall(result)
result.revalidate()
result.repaint()
}
override fun mouseExited(e: MouseEvent) {
result.background = UISettings.instance.backgroundColor
result.cursor = Cursor.getDefaultCursor()
result.revalidate()
result.repaint()
}
}
val expandPanel = JPanel().also {
it.layout = BoxLayout(it, BoxLayout.Y_AXIS)
it.isOpaque = false
it.background = Color(0, 0, 0, 0)
it.alignmentY = TOP_ALIGNMENT
//it.add(Box.createVerticalStrut(JBUI.scale(1)))
it.add(rigid(0, 1))
val rawIcon = if (expanded.contains(module)) UIUtil.getTreeExpandedIcon() else UIUtil.getTreeCollapsedIcon()
it.add(createLabelIcon(rawIcon))
}
result.add(expandPanel)
val name = JLabel(module.name)
name.font = UISettings.instance.modulesFont
modulePanel.add(name)
scaledRigid(UISettings.instance.progressModuleGap, 0)
modulePanel.add(scaledRigid(0, UISettings.instance.progressModuleGap))
if (expanded.contains(module)) {
modulePanel.add(HeightLimitedPane(module.description ?: "", -1, UIUtil.getLabelForeground() as JBColor).also {
it.addMouseListener(mouseAdapter)
})
}
else {
modulePanel.add(createModuleProgressLabel(module))
}
result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0))
result.add(modulePanel)
result.add(Box.createHorizontalGlue())
result.addMouseListener(mouseAdapter)
return result
}
private fun createLabelIcon(rawIcon: @NotNull Icon): JLabel = JLabel(IconUtil.toSize(rawIcon, JBUI.scale(16), JBUI.scale(16)))
private fun createModuleProgressLabel(module: IftModule): JBLabel {
val progressStr = learningProgressString(module.lessons)
val progressLabel = JBLabel(progressStr)
progressLabel.name = "progressLabel"
val hasNotPassedLesson = module.lessons.any { !it.passed }
progressLabel.foreground = if (hasNotPassedLesson) UISettings.instance.moduleProgressColor else UISettings.instance.completedColor
progressLabel.font = UISettings.instance.getFont(-1)
progressLabel.alignmentX = LEFT_ALIGNMENT
return progressLabel
}
private fun setCorrectBackgroundOnInstall(component: Component) {
component.background = HOVER_COLOR
component.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
private fun mouseAlreadyInside(c: Component): Boolean {
val mousePos: Point = MouseInfo.getPointerInfo()?.location ?: return false
val bounds: Rectangle = c.bounds
bounds.location = c.locationOnScreen
return bounds.contains(mousePos)
}
}
| apache-2.0 | 4c293dddcce193b32b94a933c1adea35 | 34.655 | 140 | 0.715888 | 4.262403 | false | false | false | false |
Raizlabs/DBFlow | tests/src/androidTest/java/com/dbflow5/query/list/FlowCursorListTest.kt | 1 | 2287 | package com.dbflow5.query.list
import com.dbflow5.BaseUnitTest
import com.dbflow5.config.databaseForTable
import com.dbflow5.models.SimpleModel
import com.dbflow5.query.select
import com.dbflow5.structure.save
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Description:
*/
class FlowCursorListTest : BaseUnitTest() {
@Test
fun validateCursorPassed() {
databaseForTable<SimpleModel> { db ->
val cursor = (select from SimpleModel::class).cursor(db)
val list = FlowCursorList.Builder(select from SimpleModel::class, db)
.cursor(cursor)
.build()
assertEquals(cursor, list.cursor)
}
}
@Test
fun validateModelQueriable() {
databaseForTable<SimpleModel> { db ->
val modelQueriable = (select from SimpleModel::class)
val list = FlowCursorList.Builder(modelQueriable, db)
.build()
assertEquals(modelQueriable, list.modelQueriable)
}
}
@Test
fun validateGetAll() {
databaseForTable<SimpleModel> { db ->
(0..9).forEach {
SimpleModel("$it").save(db)
}
val list = (select from SimpleModel::class).cursorList(db)
val all = list.all
assertEquals(list.count, all.size.toLong())
}
}
@Test
fun validateCursorChange() {
databaseForTable<SimpleModel> { db ->
(0..9).forEach {
SimpleModel("$it").save(db)
}
val list = (select from SimpleModel::class).cursorList(db)
var cursorListFound: FlowCursorList<SimpleModel>? = null
var count = 0
val listener: (FlowCursorList<SimpleModel>) -> Unit = { loadedList ->
cursorListFound = loadedList
count++
}
list.addOnCursorRefreshListener(listener)
assertEquals(10, list.count)
SimpleModel("10").save(db)
list.refresh()
assertEquals(11, list.count)
assertEquals(list, cursorListFound)
list.removeOnCursorRefreshListener(listener)
list.refresh()
assertEquals(1, count)
}
}
}
| mit | 8de6dcfe8c1bcffecce5b47daeeac4c7 | 26.890244 | 81 | 0.577613 | 4.824895 | false | true | false | false |
romannurik/muzei | android-client-common/src/main/java/com/google/android/apps/muzei/render/ImageLoader.kt | 1 | 6760 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.render
import android.content.ContentResolver
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.nurik.roman.muzei.androidclientcommon.BuildConfig
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import kotlin.math.max
fun InputStream.isValidImage(): Boolean {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
inPreferredConfig = Bitmap.Config.ARGB_8888
}
BitmapFactory.decodeStream(this, null, options)
return with(options) {
outWidth != 0 && outHeight != 0 &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
outConfig == Bitmap.Config.ARGB_8888)
}
}
/**
* Base class for loading images with the correct rotation
*/
sealed class ImageLoader {
companion object {
private const val TAG = "ImageLoader"
suspend fun decode(
contentResolver: ContentResolver,
uri: Uri,
targetWidth: Int = 0,
targetHeight: Int = targetWidth
) = withContext(Dispatchers.IO) {
ContentUriImageLoader(contentResolver, uri)
.decode(targetWidth, targetHeight)
}
}
fun getSize(): Pair<Int, Int> {
return try {
val (originalWidth, originalHeight) = openInputStream()?.use { input ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(input, null, options)
options.outWidth to options.outHeight
} ?: return 0 to 0
val rotation = getRotation()
val width = if (rotation == 90 || rotation == 270) originalHeight else originalWidth
val height = if (rotation == 90 || rotation == 270) originalWidth else originalHeight
return width to height
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Error decoding ${toString()}: ${e.message}")
}
0 to 0
}
}
fun decode(
targetWidth: Int = 0,
targetHeight: Int = targetWidth
) : Bitmap? {
return try {
val (originalWidth, originalHeight) = openInputStream()?.use { input ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(input, null, options)
Pair(options.outWidth, options.outHeight)
} ?: return null
val rotation = getRotation()
val width = if (rotation == 90 || rotation == 270) originalHeight else originalWidth
val height = if (rotation == 90 || rotation == 270) originalWidth else originalHeight
openInputStream()?.use { input ->
BitmapFactory.decodeStream(input, null,
BitmapFactory.Options().apply {
inPreferredConfig = Bitmap.Config.ARGB_8888
if (targetWidth != 0) {
inSampleSize = max(
width.sampleSize(targetWidth),
height.sampleSize(targetHeight))
}
})
}?.run {
when (rotation) {
0 -> this
else -> {
val rotateMatrix = Matrix().apply {
postRotate(rotation.toFloat())
}
Bitmap.createBitmap(
this, 0, 0,
this.width, this.height,
rotateMatrix, true).also { rotatedBitmap ->
if (rotatedBitmap != this) {
recycle()
}
}
}
}
}
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Error decoding ${toString()}: ${e.message}")
}
null
}
}
fun getRotation(): Int = try {
openInputStream()?.use { input ->
val exifInterface = ExifInterface(input)
when (exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL)) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
} ?: 0
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Couldn't open EXIF interface for ${toString()}", e)
}
0
}
abstract fun openInputStream() : InputStream?
}
/**
* An [ImageLoader] capable of loading images from a [ContentResolver]
*/
class ContentUriImageLoader constructor(
private val contentResolver: ContentResolver,
private val uri: Uri
) : ImageLoader() {
@Throws(FileNotFoundException::class)
override fun openInputStream(): InputStream? =
contentResolver.openInputStream(uri)
override fun toString(): String {
return uri.toString()
}
}
/**
* An [ImageLoader] capable of loading images from [AssetManager]
*/
class AssetImageLoader constructor(
private val assetManager: AssetManager,
private val fileName: String
) : ImageLoader() {
@Throws(IOException::class)
override fun openInputStream(): InputStream =
assetManager.open(fileName)
override fun toString(): String {
return fileName
}
} | apache-2.0 | 126b445326b55316decf43a43843dcb2 | 34.031088 | 97 | 0.564349 | 5.365079 | false | true | false | false |
AndroidX/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/ComposableTargetChecker.kt | 3 | 20645 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin
import androidx.compose.compiler.plugins.kotlin.analysis.ComposeWritableSlices
import androidx.compose.compiler.plugins.kotlin.inference.ErrorReporter
import androidx.compose.compiler.plugins.kotlin.inference.TypeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.ApplierInferencer
import androidx.compose.compiler.plugins.kotlin.inference.Item
import androidx.compose.compiler.plugins.kotlin.inference.LazyScheme
import androidx.compose.compiler.plugins.kotlin.inference.LazySchemeStorage
import androidx.compose.compiler.plugins.kotlin.inference.NodeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.NodeKind
import androidx.compose.compiler.plugins.kotlin.inference.Open
import androidx.compose.compiler.plugins.kotlin.inference.Scheme
import androidx.compose.compiler.plugins.kotlin.inference.Token
import androidx.compose.compiler.plugins.kotlin.inference.deserializeScheme
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.backend.jvm.ir.psiElement
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.codegen.kotlinType
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.types.KotlinType
private sealed class InferenceNode(val element: PsiElement) {
open val kind: NodeKind get() = when (element) {
is KtLambdaExpression, is KtFunctionLiteral -> NodeKind.Lambda
is KtFunction -> NodeKind.Function
else -> NodeKind.Expression
}
abstract val type: InferenceNodeType
}
private sealed class InferenceNodeType {
abstract fun toScheme(callContext: CallCheckerContext): Scheme
abstract fun isTypeFor(descriptor: CallableDescriptor): Boolean
}
private class InferenceDescriptorType(val descriptor: CallableDescriptor) : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme =
descriptor.toScheme(callContext)
override fun isTypeFor(descriptor: CallableDescriptor) = this.descriptor == descriptor
override fun hashCode(): Int = 31 * descriptor.original.hashCode()
override fun equals(other: Any?): Boolean =
other is InferenceDescriptorType && other.descriptor.original == descriptor.original
}
private class InferenceKotlinType(val type: KotlinType) : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme = type.toScheme()
override fun isTypeFor(descriptor: CallableDescriptor): Boolean = false
override fun hashCode(): Int = 31 * type.hashCode()
override fun equals(other: Any?): Boolean =
other is InferenceKotlinType && other.type == type
}
private class InferenceUnknownType : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme = Scheme(Open(-1))
override fun isTypeFor(descriptor: CallableDescriptor): Boolean = false
override fun hashCode(): Int = System.identityHashCode(this)
override fun equals(other: Any?): Boolean = other === this
}
private class PsiElementNode(
element: PsiElement,
val bindingContext: BindingContext
) : InferenceNode(element) {
override val type: InferenceNodeType = when (element) {
is KtLambdaExpression -> descriptorTypeOf(element.functionLiteral)
is KtFunctionLiteral, is KtFunction -> descriptorTypeOf(element)
is KtProperty -> kotlinTypeOf(element)
is KtPropertyAccessor -> kotlinTypeOf(element)
is KtExpression -> kotlinTypeOf(element)
else -> descriptorTypeOf(element)
}
private fun descriptorTypeOf(element: PsiElement): InferenceNodeType =
bindingContext[BindingContext.FUNCTION, element]?.let {
InferenceDescriptorType(it)
} ?: InferenceUnknownType()
private fun kotlinTypeOf(element: KtExpression) = element.kotlinType(bindingContext)?.let {
InferenceKotlinType(it)
} ?: InferenceUnknownType()
}
private class ResolvedPsiElementNode(
element: PsiElement,
override val type: InferenceNodeType,
) : InferenceNode(element) {
override val kind: NodeKind get() = NodeKind.Function
}
private class ResolvedPsiParameterReference(
element: PsiElement,
override val type: InferenceNodeType,
val index: Int,
val container: PsiElement
) : InferenceNode(element) {
override val kind: NodeKind get() = NodeKind.ParameterReference
}
class ComposableTargetChecker : CallChecker, StorageComponentContainerContributor {
private lateinit var callContext: CallCheckerContext
private fun containerOf(element: PsiElement): PsiElement? {
var current: PsiElement? = element.parent
while (current != null) {
when (current) {
is KtLambdaExpression, is KtFunction, is KtProperty, is KtPropertyAccessor ->
return current
is KtClass, is KtFile -> break
}
current = current.parent as? KtElement
}
return null
}
private fun containerNodeOf(element: PsiElement) =
containerOf(element)?.let {
PsiElementNode(it, callContext.trace.bindingContext)
}
// Create an InferApplier instance with adapters for the Psi front-end
private val infer = ApplierInferencer(
typeAdapter = object : TypeAdapter<InferenceNodeType> {
override fun declaredSchemaOf(type: InferenceNodeType): Scheme =
type.toScheme(callContext)
override fun currentInferredSchemeOf(type: InferenceNodeType): Scheme? = null
override fun updatedInferredScheme(type: InferenceNodeType, scheme: Scheme) { }
},
nodeAdapter = object : NodeAdapter<InferenceNodeType, InferenceNode> {
override fun containerOf(node: InferenceNode): InferenceNode =
containerNodeOf(node.element) ?: node
override fun kindOf(node: InferenceNode) = node.kind
override fun schemeParameterIndexOf(
node: InferenceNode,
container: InferenceNode
): Int = (node as? ResolvedPsiParameterReference)?.let {
if (it.container == container.element) it.index else -1
} ?: -1
override fun typeOf(node: InferenceNode): InferenceNodeType = node.type
override fun referencedContainerOf(node: InferenceNode): InferenceNode? {
return null
}
},
errorReporter = object : ErrorReporter<InferenceNode> {
/**
* Find the `description` value from ComposableTargetMarker if the token refers to an
* annotation with the marker or just return [token] if it cannot be found.
*/
private fun descriptionFrom(token: String): String {
val fqName = FqName(token)
val cls = callContext.moduleDescriptor.findClassAcrossModuleDependencies(
ClassId.topLevel(fqName)
)
return cls?.let {
it.annotations.findAnnotation(
ComposeFqNames.ComposableTargetMarker
)?.let { marker ->
marker.allValueArguments.firstNotNullOfOrNull { entry ->
val name = entry.key
if (
!name.isSpecial &&
name.identifier == ComposeFqNames.ComposableTargetMarkerDescription
) {
(entry.value as? StringValue)?.value
} else null
}
}
} ?: token
}
override fun reportCallError(node: InferenceNode, expected: String, received: String) {
if (expected != received) {
val expectedDescription = descriptionFrom(expected)
val receivedDescription = descriptionFrom(received)
callContext.trace.report(
ComposeErrors.COMPOSE_APPLIER_CALL_MISMATCH.on(
node.element,
expectedDescription,
receivedDescription
)
)
}
}
override fun reportParameterError(
node: InferenceNode,
index: Int,
expected: String,
received: String
) {
if (expected != received) {
val expectedDescription = descriptionFrom(expected)
val receivedDescription = descriptionFrom(received)
callContext.trace.report(
ComposeErrors.COMPOSE_APPLIER_PARAMETER_MISMATCH.on(
node.element,
expectedDescription,
receivedDescription
)
)
}
}
override fun log(node: InferenceNode?, message: String) {
// ignore log messages in the front-end
}
},
lazySchemeStorage = object : LazySchemeStorage<InferenceNode> {
override fun getLazyScheme(node: InferenceNode): LazyScheme? =
callContext.trace.bindingContext.get(
ComposeWritableSlices.COMPOSE_LAZY_SCHEME,
node.type
)
override fun storeLazyScheme(node: InferenceNode, value: LazyScheme) {
callContext.trace.record(
ComposeWritableSlices.COMPOSE_LAZY_SCHEME,
node.type,
value
)
}
}
)
override fun registerModuleComponents(
container: StorageComponentContainer,
platform: TargetPlatform,
moduleDescriptor: ModuleDescriptor
) {
container.useInstance(this)
}
override fun check(
resolvedCall: ResolvedCall<*>,
reportOn: PsiElement,
context: CallCheckerContext
) {
if (!resolvedCall.isComposableInvocation()) return
callContext = context
val bindingContext = callContext.trace.bindingContext
val parameters = resolvedCall.candidateDescriptor.valueParameters.filter {
(it.type.isFunctionType && it.type.hasComposableAnnotation()) || it.isSamComposable()
}
val arguments = parameters.map {
val argument = resolvedCall.valueArguments.entries.firstOrNull { entry ->
entry.key.original == it
}?.value
if (argument is ExpressionValueArgument) {
argumentToInferenceNode(it, argument.valueArgument?.asElement() ?: reportOn)
} else {
// Generate a node that is ignored
PsiElementNode(reportOn, bindingContext)
}
}
infer.visitCall(
call = PsiElementNode(reportOn, bindingContext),
target = resolvedCallToInferenceNode(resolvedCall),
arguments = arguments
)
}
private fun resolvedCallToInferenceNode(resolvedCall: ResolvedCall<*>) =
when (resolvedCall) {
is VariableAsFunctionResolvedCall ->
descriptorToInferenceNode(
resolvedCall.variableCall.candidateDescriptor,
resolvedCall.call.callElement
)
else -> {
val receiver = resolvedCall.dispatchReceiver
val expression = (receiver as? ExpressionReceiver)?.expression
val referenceExpression = expression as? KtReferenceExpression
val candidate = referenceExpression?.let { r ->
val callableReference =
callContext.trace[BindingContext.REFERENCE_TARGET, r] as?
CallableDescriptor
callableReference?.let { reference ->
descriptorToInferenceNode(reference, resolvedCall.call.callElement)
}
}
candidate ?: descriptorToInferenceNode(
resolvedCall.resultingDescriptor,
resolvedCall.call.callElement
)
}
}
private fun argumentToInferenceNode(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode {
val bindingContext = callContext.trace.bindingContext
val lambda = lambdaOrNull(element)
if (lambda != null) return PsiElementNode(lambda, bindingContext)
val parameter = findParameterReferenceOrNull(descriptor, element)
if (parameter != null) return parameter
return PsiElementNode(element, bindingContext)
}
private fun lambdaOrNull(element: PsiElement): KtFunctionLiteral? {
var container = (element as? KtLambdaArgument)?.children?.singleOrNull()
while (true) {
container = when (container) {
null -> return null
is KtLabeledExpression -> container.lastChild
is KtFunctionLiteral -> return container
is KtLambdaExpression -> container.children.single()
else -> throw Error("Unknown type: ${container.javaClass}")
}
}
}
private fun descriptorToInferenceNode(
descriptor: CallableDescriptor,
element: PsiElement
): InferenceNode = when (descriptor) {
is ValueParameterDescriptor -> parameterDescriptorToInferenceNode(descriptor, element)
else -> {
// If this is a call to the accessor of the variable find the original descriptor
val original = descriptor.original
if (original is ValueParameterDescriptor)
parameterDescriptorToInferenceNode(original, element)
else ResolvedPsiElementNode(element, InferenceDescriptorType(descriptor))
}
}
private fun parameterDescriptorToInferenceNode(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode {
val parameter = findParameterReferenceOrNull(descriptor, element)
return parameter ?: PsiElementNode(element, callContext.trace.bindingContext)
}
private fun findParameterReferenceOrNull(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode? {
val bindingContext = callContext.trace.bindingContext
val declaration = descriptor.containingDeclaration
var currentContainer: InferenceNode? = containerNodeOf(element)
while (currentContainer != null) {
val type = currentContainer.type
if (type.isTypeFor(declaration)) {
val index =
declaration.valueParameters.filter {
it.isComposableCallable(bindingContext) ||
it.isSamComposable()
}.indexOf(descriptor)
return ResolvedPsiParameterReference(
element,
InferenceDescriptorType(descriptor),
index,
currentContainer.element
)
}
currentContainer = containerNodeOf(currentContainer.element)
}
return null
}
}
private fun Annotated.schemeItem(): Item {
val explicitTarget = compositionTarget()
val explicitOpen = if (explicitTarget == null) compositionOpenTarget() else null
return when {
explicitTarget != null -> Token(explicitTarget)
explicitOpen != null -> Open(explicitOpen)
else -> Open(-1, isUnspecified = true)
}
}
private fun Annotated.scheme(): Scheme? = compositionScheme()?.let { deserializeScheme(it) }
internal fun CallableDescriptor.toScheme(callContext: CallCheckerContext?): Scheme =
scheme()
?: Scheme(
target = schemeItem().let {
// The item is unspecified see if the containing has an annotation we can use
if (it.isUnspecified) {
val target = callContext?.let { context -> fileScopeTarget(context) }
if (target != null) return@let target
}
it
},
parameters = valueParameters.filter {
it.type.hasComposableAnnotation() || it.isSamComposable()
}.map {
it.samComposableOrNull()?.toScheme(callContext) ?: it.type.toScheme()
}
).mergeWith(overriddenDescriptors.map { it.toScheme(null) })
private fun CallableDescriptor.fileScopeTarget(callContext: CallCheckerContext): Item? =
(psiElement?.containingFile as? KtFile)?.let {
for (entry in it.annotationEntries) {
val annotationDescriptor =
callContext.trace.bindingContext[BindingContext.ANNOTATION, entry]
annotationDescriptor?.compositionTarget()?.let { token ->
return Token(token)
}
}
null
}
private fun KotlinType.toScheme(): Scheme = Scheme(
target = schemeItem(),
parameters = arguments.filter { it.type.hasComposableAnnotation() }.map { it.type.toScheme() }
)
private fun ValueParameterDescriptor.samComposableOrNull() =
(type.constructor.declarationDescriptor as? ClassDescriptor)?.let {
getSingleAbstractMethodOrNull(it)
}
private fun ValueParameterDescriptor.isSamComposable() =
samComposableOrNull()?.hasComposableAnnotation() == true
internal fun Scheme.mergeWith(schemes: List<Scheme>): Scheme {
if (schemes.isEmpty()) return this
val lazyScheme = LazyScheme(this)
val bindings = lazyScheme.bindings
fun unifySchemes(a: LazyScheme, b: LazyScheme) {
bindings.unify(a.target, b.target)
for ((ap, bp) in a.parameters.zip(b.parameters)) {
unifySchemes(ap, bp)
}
}
schemes.forEach {
val overrideScheme = LazyScheme(it, bindings = lazyScheme.bindings)
unifySchemes(lazyScheme, overrideScheme)
}
return lazyScheme.toScheme()
} | apache-2.0 | 907db197d88f8f99f05873b69b43104c | 40.878296 | 99 | 0.655171 | 5.673262 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/Constraints.kt | 1 | 2984 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.gridLayout
import com.intellij.ui.dsl.checkNonNegative
import com.intellij.ui.dsl.checkPositive
import com.intellij.ui.dsl.gridLayout.impl.GridImpl
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
enum class HorizontalAlign {
LEFT,
CENTER,
RIGHT,
FILL
}
enum class VerticalAlign {
TOP,
CENTER,
BOTTOM,
FILL
}
data class Constraints(
/**
* Grid destination
*/
val grid: Grid,
/**
* Cell x coordinate in [grid]
*/
val x: Int,
/**
* Cell y coordinate in [grid]
*/
val y: Int,
/**
* Columns number occupied by the cell
*/
val width: Int = 1,
/**
* Rows number occupied by the cell
*/
val height: Int = 1,
/**
* Horizontal alignment of content inside the cell
*/
val horizontalAlign: HorizontalAlign = HorizontalAlign.LEFT,
/**
* Vertical alignment of content inside the cell
*/
val verticalAlign: VerticalAlign = VerticalAlign.CENTER,
/**
* If true then vertical align is done by baseline:
*
* 1. All cells in the same grid row with [baselineAlign] true, [height] equals 1 and with the same [verticalAlign]
* (except [VerticalAlign.FILL], which doesn't support baseline) are aligned by baseline together
* 2. Sub grids (see [GridImpl.registerSubGrid]) with only one row and that contain cells only with [VerticalAlign.FILL] and another
* specific [VerticalAlign] (at least one cell without fill align) have own baseline and can be aligned by baseline in parent grid
*/
val baselineAlign: Boolean = false,
/**
* Gaps between grid cell bounds and components visual bounds (visual bounds is component bounds minus [visualPaddings])
*/
val gaps: Gaps = Gaps.EMPTY,
/**
* Gaps between component bounds and its visual bounds. Can be used when component has focus ring outside of
* its usual size. In such case components size is increased on focus size (so focus ring is not clipped)
* and [visualPaddings] should be set to maintain right alignments
*
* 1. Layout manager aligns components by their visual bounds
* 2. Cell size with gaps is calculated as component.bounds + [gaps] - [visualPaddings]
*/
var visualPaddings: Gaps = Gaps.EMPTY,
/**
* Component helper for custom behaviour
*/
@ApiStatus.Experimental
val componentHelper: ComponentHelper? = null
) {
init {
checkNonNegative("x", x)
checkNonNegative("y", y)
checkPositive("width", width)
checkPositive("height", height)
}
}
/**
* A helper for custom behaviour for components in cells
*/
@ApiStatus.Experimental
interface ComponentHelper {
/**
* Returns custom baseline or null if default baseline calculation should be used
*
* @see JComponent.getBaseline
*/
fun getBaseline(width: Int, height: Int): Int?
}
| apache-2.0 | 1a5163e3e8c01b643fe2d86eff5f24c4 | 25.40708 | 158 | 0.702748 | 4.232624 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt | 1 | 6368 | // 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.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.highlighter.AbstractKotlinHighlightVisitor
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.ReplaceObsoleteLabelSyntaxFix
import org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
// required to simplify the inspection registration in tests
override fun getDisplayName(): String = KotlinBundle.message("usage.of.redundant.or.deprecated.syntax.or.deprecated.symbols")
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? {
if (isOnTheFly || file !is KtFile || !ProjectRootsUtil.isInProjectSource(file)) {
return null
}
val analysisResult = file.analyzeWithAllCompilerChecks()
if (analysisResult.isError()) {
return null
}
val diagnostics = analysisResult.bindingContext.diagnostics
val problemDescriptors = arrayListOf<ProblemDescriptor>()
val importsToRemove = DeprecatedSymbolUsageFix.importDirectivesToBeRemoved(file)
for (import in importsToRemove) {
val removeImportFix = RemoveImportFix(import)
val problemDescriptor = createProblemDescriptor(import, removeImportFix.text, listOf(removeImportFix), manager)
problemDescriptors.add(problemDescriptor)
}
file.forEachDescendantOfType<PsiElement> { element ->
for (diagnostic in diagnostics.forElement(element)) {
if (diagnostic.isCleanup()) {
val fixes = diagnostic.toCleanupFixes()
if (fixes.isNotEmpty()) {
problemDescriptors.add(diagnostic.toProblemDescriptor(fixes, file, manager))
}
}
}
}
return problemDescriptors.toTypedArray()
}
private fun Diagnostic.isCleanup() = factory in cleanupDiagnosticsFactories || isObsoleteLabel()
private val cleanupDiagnosticsFactories = setOf(
Errors.MISSING_CONSTRUCTOR_KEYWORD,
Errors.UNNECESSARY_NOT_NULL_ASSERTION,
Errors.UNNECESSARY_SAFE_CALL,
Errors.USELESS_CAST,
Errors.USELESS_ELVIS,
ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION,
Errors.DEPRECATION,
Errors.DEPRECATION_ERROR,
Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION,
Errors.OPERATOR_MODIFIER_REQUIRED,
Errors.INFIX_MODIFIER_REQUIRED,
Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX,
Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS,
Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT,
ErrorsJs.WRONG_EXTERNAL_DECLARATION,
Errors.YIELD_IS_RESERVED,
Errors.DEPRECATED_MODIFIER_FOR_TARGET,
Errors.DEPRECATED_MODIFIER
)
private fun Diagnostic.isObsoleteLabel(): Boolean {
val annotationEntry = psiElement.getNonStrictParentOfType<KtAnnotationEntry>() ?: return false
return ReplaceObsoleteLabelSyntaxFix.looksLikeObsoleteLabel(annotationEntry)
}
private fun Diagnostic.toCleanupFixes(): Collection<CleanupFix> {
return AbstractKotlinHighlightVisitor.createQuickFixes(this).filterIsInstance<CleanupFix>()
}
private class Wrapper(val intention: IntentionAction) : IntentionWrapper(intention) {
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (intention.isAvailable(
project,
editor,
file
)
) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change)
super.invoke(project, editor, file)
}
}
}
private fun Diagnostic.toProblemDescriptor(fixes: Collection<CleanupFix>, file: KtFile, manager: InspectionManager): ProblemDescriptor {
// TODO: i18n DefaultErrorMessages.render
@NlsSafe val message = DefaultErrorMessages.render(this)
return createProblemDescriptor(psiElement, message, fixes, manager)
}
private fun createProblemDescriptor(
element: PsiElement,
@Nls message: String,
fixes: Collection<CleanupFix>,
manager: InspectionManager
): ProblemDescriptor {
return manager.createProblemDescriptor(
element,
message,
false,
fixes.map { Wrapper(it) }.toTypedArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
private class RemoveImportFix(import: KtImportDirective) : KotlinQuickFixAction<KtImportDirective>(import), CleanupFix {
override fun getFamilyName() = KotlinBundle.message("remove.deprecated.symbol.import")
@Nls
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
}
}
| apache-2.0 | 8d73a8d35baf678524853ae2dfad27c1 | 42.616438 | 158 | 0.71608 | 5.206868 | false | false | false | false |
DanielGrech/anko | dsl/src/org/jetbrains/android/anko/sources/SourceManager.kt | 3 | 2409 | /*
* Copyright 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.android.anko.sources
import com.github.javaparser.ast.Node
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.body.TypeDeclaration
import com.github.javaparser.ast.visitor.VoidVisitorAdapter
import org.jetbrains.android.anko.getJavaClassName
public class SourceManager(private val provider: SourceProvider) {
public fun getArgumentNames(classFqName: String, methodName: String, argumentJavaTypes: List<String>): List<String>? {
val parsed = provider.parse(classFqName) ?: return null
val className = getJavaClassName(classFqName)
val argumentNames = arrayListOf<String>()
var done = false
object : VoidVisitorAdapter<Any>() {
override fun visit(method: MethodDeclaration, arg: Any?) {
if (done) return
if (methodName != method.getName() || argumentJavaTypes.size() != method.getParameters().size()) return
if (method.getParentClassName() != className) return
val parameters = method.getParameters()
for ((argumentFqType, param) in argumentJavaTypes.zip(parameters)) {
if (argumentFqType.substringAfterLast('.') != param.getType().toString()) return
}
parameters.forEach { argumentNames.add(it.getId().getName()) }
done = true
}
}.visit(parsed, null)
return if (done) argumentNames else null
}
private fun Node.getParentClassName(): String {
val parent = getParentNode()
return if (parent is TypeDeclaration) {
val outerName = parent.getParentClassName()
if (outerName.isNotEmpty()) "$outerName.${parent.getName()}" else parent.getName()
} else ""
}
} | apache-2.0 | 76a4819dde66e0167f2290fd2dd589c7 | 38.508197 | 122 | 0.673308 | 4.650579 | false | false | false | false |
leafclick/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalSystemJdkComboBoxUtil.kt | 1 | 2170 | // 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.
@file:JvmName("ExternalSystemJdkComboBoxUtil")
package com.intellij.openapi.externalSystem.service.ui
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkException
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.USE_PROJECT_JDK
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.ui.configuration.SdkComboBox
import com.intellij.openapi.roots.ui.configuration.SdkListItem
import org.jetbrains.annotations.TestOnly
fun SdkComboBox.getSelectedJdkReference() = resolveJdkReference(selectedItem)
private fun resolveJdkReference(item: SdkListItem?): String? {
return when (item) {
is SdkListItem.ProjectSdkItem -> USE_PROJECT_JDK
is SdkListItem.SdkItem -> item.sdk.name
is SdkListItem.InvalidSdkItem -> item.sdkName
else -> null
}
}
fun SdkComboBox.setSelectedJdkReference(jdkReference: String?) {
selectedItem = resolveSdkItem(jdkReference)
}
private fun SdkComboBox.resolveSdkItem(jdkReference: String?): SdkListItem {
if (jdkReference == null) return showNoneSdkItem()
if (jdkReference == USE_PROJECT_JDK) return showProjectSdkItem()
try {
val selectedJdk = ExternalSystemJdkUtil.resolveJdkName(null, jdkReference)
if (selectedJdk == null) return showInvalidSdkItem(jdkReference)
return findSdkItem(selectedJdk) ?: addAndGetSdkItem(selectedJdk)
}
catch (ex: ExternalSystemJdkException) {
return showInvalidSdkItem(jdkReference)
}
}
private fun SdkComboBox.addAndGetSdkItem(sdk: Sdk): SdkListItem {
SdkConfigurationUtil.addSdk(sdk)
model.sdksModel.addSdk(sdk)
reloadModel()
return findSdkItem(sdk) ?: showInvalidSdkItem(sdk.name)
}
private fun SdkComboBox.findSdkItem(sdk: Sdk): SdkListItem? {
return model.listModel.findSdkItem(sdk)
}
@TestOnly
fun resolveJdkReferenceInTests(item: SdkListItem?) = resolveJdkReference(item)
| apache-2.0 | 8eaec1b0d633cd87ab8d18ad7df088ba | 38.454545 | 140 | 0.804608 | 4.437628 | false | true | false | false |
idea4bsd/idea4bsd | java/execution/impl/src/com/intellij/testIntegration/RunConfigurationEntry.kt | 17 | 3726 | /*
* 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 com.intellij.testIntegration
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.testframework.TestIconMapper
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.ERROR_INDEX
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.FAILED_INDEX
import com.intellij.icons.AllIcons
import com.intellij.openapi.vfs.VirtualFileManager
import java.util.*
import javax.swing.Icon
interface RecentTestsPopupEntry {
val icon: Icon?
val presentation: String
val runDate: Date
val failed: Boolean
fun accept(visitor: TestEntryVisitor)
}
abstract class TestEntryVisitor {
open fun visitTest(test: SingleTestEntry) = Unit
open fun visitSuite(suite: SuiteEntry) = Unit
open fun visitRunConfiguration(configuration: RunConfigurationEntry) = Unit
}
private fun String.toClassName(allowedDots: Int): String {
val fqn = VirtualFileManager.extractPath(this)
var dots = 0
return fqn.takeLastWhile {
if (it == '.') dots++
dots <= allowedDots
}
}
class SingleTestEntry(val url: String,
override val runDate: Date,
val runConfiguration: RunnerAndConfigurationSettings,
magnitude: TestStateInfo.Magnitude) : RecentTestsPopupEntry
{
override val presentation = url.toClassName(1)
override val icon = TestIconMapper.getIcon(magnitude)
override val failed = magnitude == ERROR_INDEX || magnitude == FAILED_INDEX
var suite: SuiteEntry? = null
override fun accept(visitor: TestEntryVisitor) {
visitor.visitTest(this)
}
}
class SuiteEntry(val suiteUrl: String,
override val runDate: Date,
var runConfiguration: RunnerAndConfigurationSettings) : RecentTestsPopupEntry {
val tests = hashSetOf<SingleTestEntry>()
val suiteName = VirtualFileManager.extractPath(suiteUrl)
var runConfigurationEntry: RunConfigurationEntry? = null
override val presentation = suiteUrl.toClassName(0)
override val icon: Icon? = AllIcons.RunConfigurations.Junit
override val failed: Boolean
get() {
return tests.find { it.failed } != null
}
fun addTest(test: SingleTestEntry) {
tests.add(test)
test.suite = this
}
override fun accept(visitor: TestEntryVisitor) {
visitor.visitSuite(this)
}
}
class RunConfigurationEntry(val runSettings: RunnerAndConfigurationSettings) : RecentTestsPopupEntry {
val suites = arrayListOf<SuiteEntry>()
override val runDate: Date
get() {
return suites.minBy { it.runDate }!!.runDate
}
override val failed: Boolean
get() {
return suites.find { it.failed } != null
}
fun addSuite(suite: SuiteEntry) {
suites.add(suite)
suite.runConfigurationEntry = this
}
override val presentation: String = runSettings.name
override val icon: Icon? = AllIcons.RunConfigurations.Junit
override fun accept(visitor: TestEntryVisitor) {
visitor.visitRunConfiguration(this)
}
} | apache-2.0 | 0ed0a8bc939bde92d300bed148de4216 | 27.450382 | 102 | 0.731616 | 4.425178 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/GradleKotlinxCoroutinesDeprecationInspection.kt | 1 | 5783 | // 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.groovy.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.configuration.MigrationInfo
import org.jetbrains.kotlin.idea.configuration.getWholeModuleGroup
import org.jetbrains.kotlin.idea.configuration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.inspections.ReplaceStringInDocumentFix
import org.jetbrains.kotlin.idea.inspections.gradle.KotlinGradleInspectionVisitor
import org.jetbrains.kotlin.idea.inspections.migration.DEPRECATED_COROUTINES_LIBRARIES_INFORMATION
import org.jetbrains.kotlin.idea.inspections.migration.DeprecatedForKotlinLibInfo
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.idea.versions.LibInfo
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
private val LibInfo.gradleMarker get() = "$groupId:$name:"
@Suppress("SpellCheckingInspection")
class GradleKotlinxCoroutinesDeprecationInspection : BaseInspection(), CleanupLocalInspectionTool, MigrationFix {
override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_2, LanguageVersion.KOTLIN_1_3)
}
override fun buildVisitor(): BaseInspectionVisitor = DependencyFinder()
private open class DependencyFinder : KotlinGradleInspectionVisitor() {
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return
if (dependenciesCall.invokedExpression.text != "dependencies") return
val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS)
for (dependencyStatement in dependencyEntries) {
for (outdatedInfo in DEPRECATED_COROUTINES_LIBRARIES_INFORMATION) {
val dependencyText = dependencyStatement.text
val libMarker = outdatedInfo.lib.gradleMarker
if (!dependencyText.contains(libMarker)) continue
if (!checkKotlinVersion(dependencyStatement.containingFile, outdatedInfo.sinceKotlinLanguageVersion)) {
// Same result will be for all invocations in this file, so exit
return
}
val libVersion =
DifferentStdlibGradleVersionInspection.getResolvedLibVersion(
dependencyStatement.containingFile, outdatedInfo.lib.groupId, listOf(outdatedInfo.lib.name)
) ?: DeprecatedGradleDependencyInspection.libraryVersionFromOrderEntry(
dependencyStatement.containingFile,
outdatedInfo.lib.name
) ?: continue
val updatedVersion = outdatedInfo.versionUpdater.updateVersion(libVersion)
if (libVersion == updatedVersion) {
continue
}
if (dependencyText.contains(updatedVersion)) {
continue
}
val reportOnElement = reportOnElement(dependencyStatement, outdatedInfo)
val fix = if (dependencyText.contains(libVersion)) {
ReplaceStringInDocumentFix(reportOnElement, libVersion, updatedVersion)
} else {
null
}
registerError(
reportOnElement, outdatedInfo.message,
if (fix != null) arrayOf(fix) else emptyArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
break
}
}
}
private fun reportOnElement(classpathEntry: GrCallExpression, deprecatedForKotlinInfo: DeprecatedForKotlinLibInfo): PsiElement {
val indexOf = classpathEntry.text.indexOf(deprecatedForKotlinInfo.lib.name)
if (indexOf < 0) return classpathEntry
return classpathEntry.findElementAt(indexOf) ?: classpathEntry
}
private fun checkKotlinVersion(file: PsiFile, languageVersion: LanguageVersion): Boolean {
val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return false
val moduleGroup = module.getWholeModuleGroup()
return moduleGroup.sourceRootModules.any { moduleInGroup ->
moduleInGroup.languageVersionSettings.languageVersion >= languageVersion
}
}
}
} | apache-2.0 | 3614cb84da942355c62b03e86216d9dd | 51.581818 | 158 | 0.70102 | 5.865112 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationOnlyHandler2.kt | 1 | 3810 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.codeInsight.navigation.impl.*
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiFile
import com.intellij.ui.list.createTargetPopup
internal object GotoDeclarationOnlyHandler2 : CodeInsightActionHandler {
override fun startInWriteAction(): Boolean = false
private fun gotoDeclaration(project: Project, editor: Editor, file: PsiFile, offset: Int): GTDActionData? {
return fromGTDProviders(project, editor, offset)
?: gotoDeclaration(file, offset)
}
fun getCtrlMouseInfo(editor: Editor, file: PsiFile, offset: Int): CtrlMouseInfo? {
return gotoDeclaration(file.project, editor, file, offset)?.ctrlMouseInfo()
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration.only")
if (navigateToLookupItem(project, editor, file)) {
return
}
if (EditorUtil.isCaretInVirtualSpace(editor)) {
return
}
val offset = editor.caretModel.offset
val actionResult: GTDActionResult? = try {
underModalProgress(project, CodeInsightBundle.message("progress.title.resolving.reference")) {
gotoDeclaration(project, editor, file, offset)?.result()
}
}
catch (e: IndexNotReadyException) {
DumbService.getInstance(project).showDumbModeNotification(
CodeInsightBundle.message("popup.content.navigation.not.available.during.index.update"))
return
}
if (actionResult == null) {
notifyNowhereToGo(project, editor, file, offset)
}
else {
gotoDeclaration(editor, file, actionResult)
}
}
internal fun gotoDeclaration(editor: Editor, file: PsiFile, actionResult: GTDActionResult) {
when (actionResult) {
is GTDActionResult.SingleTarget -> {
recordAndNavigate(
editor, file, actionResult.navigatable(),
GotoDeclarationAction.getCurrentEventData(), actionResult.navigationProvider
)
}
is GTDActionResult.MultipleTargets -> {
// obtain event data before showing the popup,
// because showing the popup will finish the GotoDeclarationAction#actionPerformed and clear the data
val eventData: List<EventPair<*>> = GotoDeclarationAction.getCurrentEventData()
val popup = createTargetPopup(
CodeInsightBundle.message("declaration.navigation.title"),
actionResult.targets, GTDTarget::presentation
) { (navigatable, _, navigationProvider) ->
recordAndNavigate(editor, file, navigatable(), eventData, navigationProvider)
}
popup.showInBestPositionFor(editor)
}
}
}
private fun recordAndNavigate(
editor: Editor,
file: PsiFile,
navigatable: Navigatable,
eventData: List<EventPair<*>>,
navigationProvider: Any?
) {
if (navigationProvider != null) {
GTDUCollector.recordNavigated(eventData, navigationProvider.javaClass)
}
gotoTarget(editor, file, navigatable)
}
}
| apache-2.0 | f67dad5c32618422d685d317782f4440 | 38.278351 | 140 | 0.739895 | 4.897172 | false | false | false | false |
JetBrains/kotlin-native | tools/performance-server/src/main/kotlin/database/BenchmarksIndexesDispatcher.kt | 1 | 16272 | /*
* Copyright 2010-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.database
import kotlin.js.Promise
import org.jetbrains.elastic.*
import org.jetbrains.utils.*
import org.jetbrains.report.json.*
import org.jetbrains.report.*
fun <T> Iterable<T>.isEmpty() = count() == 0
fun <T> Iterable<T>.isNotEmpty() = !isEmpty()
inline fun <T: Any> T?.str(block: (T) -> String): String =
if (this != null) block(this)
else ""
// Dispatcher to create and control benchmarks indexes separated by some feature.
// Feature can be choosen as often used as filtering entity in case there is no need in separate indexes.
// Default behaviour of dispatcher is working with one index (case when separating isn't needed).
class BenchmarksIndexesDispatcher(connector: ElasticSearchConnector, val feature: String,
featureValues: Iterable<String> = emptyList()) {
// Becnhmarks indexes to work with in case of existing feature values.
private val benchmarksIndexes =
if (featureValues.isNotEmpty())
featureValues.map { it to BenchmarksIndex("benchmarks_${it.replace(" ", "_").toLowerCase()}", connector) }
.toMap()
else emptyMap()
// Single benchmark index.
private val benchmarksSingleInstance =
if (featureValues.isEmpty()) BenchmarksIndex("benchmarks", connector) else null
// Get right index in ES.
private fun getIndex(featureValue: String = "") =
benchmarksSingleInstance ?: benchmarksIndexes[featureValue]
?: error("Used wrong feature value $featureValue. Indexes are separated using next values: ${benchmarksIndexes.keys}")
// Used filter to get data with needed feature value.
var featureFilter: ((String) -> String)? = null
// Get benchmark reports corresponding to needed build number.
fun getBenchmarksReports(buildNumber: String, featureValue: String): Promise<List<String>> {
val queryDescription = """
{
"size": 1000,
"query": {
"bool": {
"must": [
{ "match": { "buildNumber": "$buildNumber" } }
]
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("hits.hits._source")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")?.let { results ->
results.map {
val element = it as JsonObject
element.getObject("_source").toString()
}
} ?: emptyList()
}
}
// Get benchmarkes names corresponding to needed build number.
fun getBenchmarksList(buildNumber: String, featureValue: String): Promise<List<String>> {
return getBenchmarksReports(buildNumber, featureValue).then { reports ->
reports.map {
val dbResponse = JsonTreeParser.parse(it).jsonObject
parseBenchmarksArray(dbResponse.getArray("benchmarks"))
.map { it.name }
}.flatten()
}
}
// Delete benchmarks from database.
fun deleteBenchmarks(featureValue: String, buildNumber: String? = null): Promise<String> {
// Delete all or for choosen build number.
val matchQuery = buildNumber?.let {
""""match": { "buildNumber": "$it" }"""
} ?: """"match_all": {}"""
val queryDescription = """
{
"query": {
$matchQuery
}
}
""".trimIndent()
return getIndex(featureValue).delete(queryDescription)
}
// Get benchmarks values of needed metric for choosen build number.
fun getSamples(metricName: String, featureValue: String = "", samples: List<String>, buildsCountToShow: Int,
buildNumbers: Iterable<String>? = null,
normalize: Boolean = false): Promise<List<Pair<String, Array<Double?>>>> {
val queryDescription = """
{
"_source": ["buildNumber"],
"size": ${samples.size * buildsCountToShow},
"query": {
"bool": {
"must": [
${buildNumbers.str { builds ->
"""
{ "terms" : { "buildNumber" : [${builds.map { "\"$it\"" }.joinToString()}] } },""" }
}
${featureFilter.str { "${it(featureValue)}," } }
{"nested" : {
"path" : "benchmarks",
"query" : {
"bool": {
"must": [
{ "match": { "benchmarks.metric": "$metricName" } },
{ "terms": { "benchmarks.name": [${samples.map { "\"${it.toLowerCase()}\"" }.joinToString()}] }}
]
}
}, "inner_hits": {
"size": ${samples.size},
"_source": ["benchmarks.name",
"benchmarks.${if (normalize) "normalizedScore" else "score"}"]
}
}
}
]
}
}
}"""
return getIndex(featureValue).search(queryDescription, listOf("hits.hits._source", "hits.hits.inner_hits"))
.then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val results = dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")
?: error("Wrong response:\n$responseString")
// Get indexes for provided samples.
val indexesMap = samples.mapIndexed { index, it -> it to index }.toMap()
val valuesMap = buildNumbers?.map {
it to arrayOfNulls<Double?>(samples.size)
}?.toMap()?.toMutableMap() ?: mutableMapOf<String, Array<Double?>>()
// Parse and save values in requested order.
results.forEach {
val element = it as JsonObject
val build = element.getObject("_source").getPrimitive("buildNumber").content
buildNumbers?.let { valuesMap.getOrPut(build) { arrayOfNulls<Double?>(samples.size) } }
element
.getObject("inner_hits")
.getObject("benchmarks")
.getObject("hits")
.getArray("hits").forEach {
val source = (it as JsonObject).getObject("_source")
valuesMap[build]!![indexesMap[source.getPrimitive("name").content]!!] =
source.getPrimitive(if (normalize) "normalizedScore" else "score").double
}
}
valuesMap.toList()
}
}
fun insert(data: JsonSerializable, featureValue: String = "") =
getIndex(featureValue).insert(data)
fun delete(data: String, featureValue: String = "") =
getIndex(featureValue).delete(data)
// Get failures number happned during build.
fun getFailuresNumber(featureValue: String = "", buildNumbers: Iterable<String>? = null): Promise<Map<String, Int>> {
val queryDescription = """
{
"_source": false,
${featureFilter.str {
"""
"query": {
"bool": {
"must": [ ${it(featureValue)} ]
}
}, """
} }
${buildNumbers.str { builds ->
"""
"aggs" : {
"builds": {
"filters" : {
"filters": {
${builds.map { "\"$it\": { \"match\" : { \"buildNumber\" : \"$it\" }}" }
.joinToString(",\n")}
}
},"""
} }
"aggs" : {
"metric_build" : {
"nested" : {
"path" : "benchmarks"
},
"aggs" : {
"metric_samples": {
"filters" : {
"filters": { "samples": { "match": { "benchmarks.status": "FAILED" } } }
},
"aggs" : {
"failed_count": {
"value_count": {
"field" : "benchmarks.score"
}
}
}
}
}
${buildNumbers.str {
""" }
}"""
} }
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("aggregations")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val aggregations = dbResponse.getObjectOrNull("aggregations") ?: error("Wrong response:\n$responseString")
buildNumbers?.let {
// Get failed number for each provided build.
val buckets = aggregations
.getObjectOrNull("builds")
?.getObjectOrNull("buckets")
?: error("Wrong response:\n$responseString")
buildNumbers.map {
it to buckets
.getObject(it)
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObject("failed_count")
.getPrimitive("value")
.int
}.toMap()
} ?: listOf("golden" to aggregations
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObject("failed_count")
.getPrimitive("value")
.int
).toMap()
}
}
// Get geometric mean for benchmarks values of needed metric.
fun getGeometricMean(metricName: String, featureValue: String = "",
buildNumbers: Iterable<String>? = null, normalize: Boolean = false,
excludeNames: List<String> = emptyList()): Promise<List<Pair<String, List<Double?>>>> {
// Filter only with metric or also with names.
val filterBenchmarks = if (excludeNames.isEmpty())
"""
"match": { "benchmarks.metric": "$metricName" }
"""
else """
"bool": {
"must": { "match": { "benchmarks.metric": "$metricName" } },
"must_not": [ ${excludeNames.map { """{ "match_phrase" : { "benchmarks.name" : "$it" } }"""}.joinToString() } ]
}
""".trimIndent()
val queryDescription = """
{
"_source": false,
${featureFilter.str {
"""
"query": {
"bool": {
"must": [ ${it(featureValue)} ]
}
}, """
} }
${buildNumbers.str { builds ->
"""
"aggs" : {
"builds": {
"filters" : {
"filters": {
${builds.map { "\"$it\": { \"match\" : { \"buildNumber\" : \"$it\" }}" }
.joinToString(",\n")}
}
},"""
} }
"aggs" : {
"metric_build" : {
"nested" : {
"path" : "benchmarks"
},
"aggs" : {
"metric_samples": {
"filters" : {
"filters": { "samples": { $filterBenchmarks } }
},
"aggs" : {
"sum_log_x": {
"sum": {
"field" : "benchmarks.${if (normalize) "normalizedScore" else "score"}",
"script" : {
"source": "if (_value == 0) { 0.0 } else { Math.log(_value) }"
}
}
},
"geom_mean": {
"bucket_script": {
"buckets_path": {
"sum_log_x": "sum_log_x",
"x_cnt": "_count"
},
"script": "Math.exp(params.sum_log_x/params.x_cnt)"
}
}
}
}
}
${buildNumbers.str {
""" }
}"""
} }
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("aggregations")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val aggregations = dbResponse.getObjectOrNull("aggregations") ?: error("Wrong response:\n$responseString")
buildNumbers?.let {
val buckets = aggregations
.getObjectOrNull("builds")
?.getObjectOrNull("buckets")
?: error("Wrong response:\n$responseString")
buildNumbers.map {
it to listOf(buckets
.getObject(it)
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObjectOrNull("geom_mean")
?.getPrimitive("value")
?.double
)
}
} ?: listOf("golden" to listOf(aggregations
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObjectOrNull("geom_mean")
?.getPrimitive("value")
?.double
)
)
}
}
} | apache-2.0 | fc9911e4748a7892c8c8c24e6a7dcbbd | 43.461749 | 140 | 0.406772 | 6.046823 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/OnEnumDeclaration.kt | 9 | 560 | /**
* Useless one
*/
enum class SomeEnum<caret>
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">final</span> <span style="color:#000080;font-weight:bold;">enum class</span> <span style="color:#000000;">SomeEnum</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Useless one</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> OnEnumDeclaration.kt<br/></div>
| apache-2.0 | 4a1e508b8cf2d98f55de2bc07dbd6a4e | 92.333333 | 508 | 0.708929 | 3.294118 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/references/paths/MarkdownUnresolvedFileReferenceInspection.kt | 7 | 2426 | // 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.lang.references.paths
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceOwner
import org.intellij.plugins.markdown.lang.psi.MarkdownElementVisitor
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDestination
import org.intellij.plugins.markdown.lang.references.paths.github.GithubWikiLocalFileReference
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class MarkdownUnresolvedFileReferenceInspection: LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object: MarkdownElementVisitor() {
override fun visitLinkDestination(linkDestination: MarkdownLinkDestination) {
checkReference(linkDestination, holder)
}
}
}
private fun checkReference(element: PsiElement, holder: ProblemsHolder) {
val references = element.references.asSequence()
val fileReferences = references.filter { it is FileReferenceOwner }
val unresolvedReferences = fileReferences.filter { !shouldSkip(it) && isValidRange(it) && it.resolve() == null }
for (reference in unresolvedReferences) {
holder.registerProblem(
reference,
ProblemsHolder.unresolvedReferenceMessage(reference),
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
}
}
private fun isValidRange(reference: PsiReference): Boolean {
val elementRange = reference.element.textRange
return reference.rangeInElement.endOffset <= elementRange.endOffset - elementRange.startOffset
}
/**
* Since we resolve any username and any repository github wiki reference,
* even if the file is not present in this repository,
* the link may still refer to an existing file, so there must not be a warning.
*
* See [GithubWikiLocalFileReferenceProvider.linkPattern].
*/
private fun shouldSkip(reference: PsiReference): Boolean {
return reference is GithubWikiLocalFileReference
}
}
| apache-2.0 | 8e65d0ae687522ea7ee57ef7100b1ffc | 43.925926 | 158 | 0.78648 | 4.920892 | false | false | false | false |
JetBrains/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/VcsLogNewUiTableCellRenderer.kt | 1 | 6345 | // 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.vcs.log.ui.table
import com.intellij.ui.hover.TableHoverListener
import com.intellij.ui.popup.list.SelectablePanel
import com.intellij.ui.popup.list.SelectablePanel.Companion.wrap
import com.intellij.ui.popup.list.SelectablePanel.SelectionArcCorners
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTable
import javax.swing.table.TableCellRenderer
@ApiStatus.Internal
internal class VcsLogNewUiTableCellRenderer(val delegate: TableCellRenderer) : TableCellRenderer, VcsLogCellRenderer {
private var isRight = false
private var isLeft = false
private var cachedRenderer: JComponent? = null
private lateinit var selectablePanel: SelectablePanel
override fun getTableCellRendererComponent(table: JTable,
value: Any,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int): Component {
val columnRenderer = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) as JComponent
// +1 – root column selection is not supported right now
val isLeftColumn = column == ROOT_COLUMN_INDEX + 1
val isRightColumn = column == table.columnCount - 1
updateSelectablePanelIfNeeded(isRightColumn, isLeftColumn, columnRenderer)
selectablePanel.apply {
background = getUnselectedBackground(table, row, column, isSelected, hasFocus)
selectionColor = if (isSelected) VcsLogGraphTable.getSelectionBackground(table.hasFocus()) else null
selectionArc = 0
selectionArcCorners = SelectionArcCorners.ALL
if (isSelected && (isLeft || isRight)) {
getSelectedRowType(table, row).tune(selectablePanel, isLeft, isRight)
}
}
return selectablePanel
}
private fun updateSelectablePanelIfNeeded(isRightColumn: Boolean, isLeftColumn: Boolean, columnRenderer: JComponent) {
if (isRight != isRightColumn || isLeft != isLeftColumn || cachedRenderer !== columnRenderer) {
cachedRenderer = columnRenderer
isLeft = isLeftColumn
isRight = isRightColumn
selectablePanel = wrap(createWrappablePanel(columnRenderer, isLeft, isRight))
}
}
private fun createWrappablePanel(renderer: JComponent, isLeft: Boolean = false, isRight: Boolean = false): BorderLayoutPanel {
val panel = BorderLayoutPanel().addToCenter(renderer).andTransparent()
if (isLeft) {
panel.addToLeft(createEmptyPanel())
}
if (isRight) {
panel.addToRight(createEmptyPanel())
}
return panel
}
override fun getCellController(): VcsLogCellController? {
if (cachedRenderer != null && cachedRenderer is VcsLogCellRenderer) {
return (cachedRenderer as VcsLogCellRenderer).cellController
}
return null
}
private fun getUnselectedBackground(table: JTable, row: Int, column: Int, isSelected: Boolean, hasFocus: Boolean): Color? {
val hovered = if (isSelected) false else row == TableHoverListener.getHoveredRow(table)
return (table as VcsLogGraphTable)
.getStyle(row, column, hasFocus, false, hovered)
.background
}
private fun getSelectedRowType(table: JTable, row: Int): SelectedRowType {
val selection = table.selectionModel
val max = selection.maxSelectionIndex
val min = selection.minSelectionIndex
if (max == min) return SelectedRowType.SINGLE
val isTopRowSelected = selection.isSelectedIndex(row - 1)
val isBottomRowSelected = selection.isSelectedIndex(row + 1)
return when {
isTopRowSelected && isBottomRowSelected -> SelectedRowType.MIDDLE
isTopRowSelected -> SelectedRowType.BOTTOM
isBottomRowSelected -> SelectedRowType.TOP
else -> SelectedRowType.SINGLE
}
}
companion object {
private val INSETS
get() = 4
private val ARC
get() = JBUI.CurrentTheme.Popup.Selection.ARC.get()
private fun createEmptyPanel(): JPanel = object : JPanel(null) {
init {
isOpaque = false
}
override fun getPreferredSize(): Dimension = JBDimension(8, 0)
}
private const val ROOT_COLUMN_INDEX = 0
}
private enum class SelectedRowType {
SINGLE {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.ALL
isLeft -> SelectionArcCorners.LEFT
isRight -> SelectionArcCorners.RIGHT
else -> SelectionArcCorners.ALL
}
}
},
TOP {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.TOP
isLeft -> SelectionArcCorners.TOP_LEFT
isRight -> SelectionArcCorners.TOP_RIGHT
else -> SelectionArcCorners.ALL
}
}
},
MIDDLE {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = 0
}
},
BOTTOM {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.BOTTOM
isLeft -> SelectionArcCorners.BOTTOM_LEFT
isRight -> SelectionArcCorners.BOTTOM_RIGHT
else -> SelectionArcCorners.ALL
}
}
};
fun tune(selectablePanel: SelectablePanel, isLeft: Boolean, isRight: Boolean) {
selectablePanel.selectionInsets = JBUI.insets(0, if (isLeft) INSETS else 0, 0, if (isRight) INSETS else 0)
selectablePanel.tuneArcAndCorners(isLeft, isRight)
}
protected abstract fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean)
}
} | apache-2.0 | dee9e659b31dfde7ce4d1f178d8a79b1 | 34.244444 | 128 | 0.690998 | 5.177959 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/FilterChipTokens.kt | 3 | 4496 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object FilterChipTokens {
val ContainerHeight = 32.0.dp
val ContainerShape = ShapeKeyTokens.CornerSmall
val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint
val DisabledLabelTextColor = ColorSchemeKeyTokens.OnSurface
const val DisabledLabelTextOpacity = 0.38f
val DraggedContainerElevation = ElevationTokens.Level4
val ElevatedContainerElevation = ElevationTokens.Level1
val ElevatedDisabledContainerColor = ColorSchemeKeyTokens.OnSurface
val ElevatedDisabledContainerElevation = ElevationTokens.Level0
const val ElevatedDisabledContainerOpacity = 0.12f
val ElevatedFocusContainerElevation = ElevationTokens.Level1
val ElevatedHoverContainerElevation = ElevationTokens.Level2
val ElevatedPressedContainerElevation = ElevationTokens.Level1
val ElevatedSelectedContainerColor = ColorSchemeKeyTokens.SecondaryContainer
val ElevatedUnselectedContainerColor = ColorSchemeKeyTokens.Surface
val FlatContainerElevation = ElevationTokens.Level0
val FlatDisabledSelectedContainerColor = ColorSchemeKeyTokens.OnSurface
const val FlatDisabledSelectedContainerOpacity = 0.12f
val FlatDisabledUnselectedOutlineColor = ColorSchemeKeyTokens.OnSurface
const val FlatDisabledUnselectedOutlineOpacity = 0.12f
val FlatSelectedContainerColor = ColorSchemeKeyTokens.SecondaryContainer
val FlatSelectedFocusContainerElevation = ElevationTokens.Level0
val FlatSelectedHoverContainerElevation = ElevationTokens.Level1
val FlatSelectedOutlineWidth = 0.0.dp
val FlatSelectedPressedContainerElevation = ElevationTokens.Level0
val FlatUnselectedFocusContainerElevation = ElevationTokens.Level0
val FlatUnselectedFocusOutlineColor = ColorSchemeKeyTokens.OnSurfaceVariant
val FlatUnselectedHoverContainerElevation = ElevationTokens.Level0
val FlatUnselectedOutlineColor = ColorSchemeKeyTokens.Outline
val FlatUnselectedOutlineWidth = 1.0.dp
val FlatUnselectedPressedContainerElevation = ElevationTokens.Level0
val LabelTextFont = TypographyKeyTokens.LabelLarge
val SelectedDraggedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedFocusLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedHoverLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedPressedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val UnselectedDraggedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedFocusLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedHoverLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedPressedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val DisabledIconColor = ColorSchemeKeyTokens.OnSurface
const val DisabledIconOpacity = 0.38f
val IconSize = 18.0.dp
val SelectedDraggedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedFocusIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedHoverIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedPressedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val UnselectedDraggedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedFocusIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedHoverIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedPressedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
} | apache-2.0 | bb429fdce4fb88336e5323ef7d5b65c2 | 55.924051 | 81 | 0.831406 | 6.323488 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/list/TvLazyListScopeImpl.kt | 3 | 2969 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.foundation.lazy.list
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.layout.IntervalList
import androidx.compose.foundation.lazy.layout.LazyLayoutIntervalContent
import androidx.compose.foundation.lazy.layout.MutableIntervalList
import androidx.compose.runtime.Composable
import androidx.tv.foundation.ExperimentalTvFoundationApi
@Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta
@OptIn(ExperimentalFoundationApi::class)
internal class TvLazyListScopeImpl : TvLazyListScope {
private val _intervals = MutableIntervalList<LazyListIntervalContent>()
val intervals: IntervalList<LazyListIntervalContent> = _intervals
private var _headerIndexes: MutableList<Int>? = null
val headerIndexes: List<Int> get() = _headerIndexes ?: emptyList()
override fun items(
count: Int,
key: ((index: Int) -> Any)?,
contentType: (index: Int) -> Any?,
itemContent: @Composable TvLazyListItemScope.(index: Int) -> Unit
) {
_intervals.addInterval(
count,
LazyListIntervalContent(
key = key,
type = contentType,
item = itemContent
)
)
}
override fun item(
key: Any?,
contentType: Any?,
content: @Composable TvLazyListItemScope.() -> Unit
) {
_intervals.addInterval(
1,
LazyListIntervalContent(
key = if (key != null) { _: Int -> key } else null,
type = { contentType },
item = { content() }
)
)
}
@ExperimentalTvFoundationApi
override fun stickyHeader(
key: Any?,
contentType: Any?,
content: @Composable TvLazyListItemScope.() -> Unit
) {
val headersIndexes = _headerIndexes ?: mutableListOf<Int>().also {
_headerIndexes = it
}
headersIndexes.add(_intervals.size)
item(key, contentType, content)
}
}
@OptIn(ExperimentalFoundationApi::class)
internal class LazyListIntervalContent(
override val key: ((index: Int) -> Any)?,
override val type: ((index: Int) -> Any?),
val item: @Composable TvLazyListItemScope.(index: Int) -> Unit
) : LazyLayoutIntervalContent
| apache-2.0 | 3181e6a2f8841281dce94ce4e037f680 | 33.126437 | 93 | 0.66386 | 4.7504 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt | 2 | 1329 | // 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.sdk.flavors
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
class MayaSdkFlavor private constructor() : CPythonSdkFlavor<PyFlavorData.Empty>() {
override fun getFlavorDataClass(): Class<PyFlavorData.Empty> = PyFlavorData.Empty::class.java
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
val INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
}
| apache-2.0 | 3af14239c97850d1db5c43a213507267 | 31.414634 | 140 | 0.742664 | 4.205696 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Game/Game.kt | 1 | 2947 | package io.github.sdsstudios.ScoreKeeper.Game
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import io.github.sdsstudios.ScoreKeeper.Database.Dao.GameDao
import io.github.sdsstudios.ScoreKeeper.TimeLimit.Companion.DEFAULT_TIME
import java.util.*
import kotlin.coroutines.experimental.buildSequence
/**
* Created by sethsch1 on 29/10/17.
*/
@Entity(tableName = GameDao.TABLE_NAME)
open class Game(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0,
@ColumnInfo(name = GameDao.KEY_CREATION_DATE)
var creationDate: Date = Date(),
@ColumnInfo(name = GameDao.KEY_LAST_PLAYED_DATE)
var lastPlayedDate: Date = creationDate,
@ColumnInfo(name = GameDao.KEY_WINNING_SCORE)
var scoreToWin: Int? = null,
@ColumnInfo(name = GameDao.KEY_SCORE_INTERVAL)
var scoreInterval: Int = 1,
@ColumnInfo(name = GameDao.KEY_SCORE_DIFF_TO_WIN)
var scoreDiffToWin: Int? = null,
@ColumnInfo(name = GameDao.KEY_NUM_SETS_CHOSEN)
var numSetsChosen: Int = 1,
@ColumnInfo(name = GameDao.KEY_NUM_SETS_PLAYED)
var numSetsPlayed: Int = 1,
@ColumnInfo(name = GameDao.KEY_STARTING_SCORE)
var startingScore: Int = 0,
@ColumnInfo(name = GameDao.KEY_COMPLETED)
var completed: Boolean = false,
@ColumnInfo(name = GameDao.KEY_REVERSE_SCORING)
var reverseScoring: Boolean = false,
@ColumnInfo(name = GameDao.KEY_USE_STOPWATCH)
var useStopwatch: Boolean = false,
@ColumnInfo(name = GameDao.KEY_NOTES)
var notes: String = "",
@ColumnInfo(name = GameDao.KEY_DURATION)
var duration: String = DEFAULT_TIME,
@ColumnInfo(name = GameDao.KEY_TITLE)
var title: String = "The Game With No Name",
@ColumnInfo(name = GameDao.KEY_TIME_LIMIT)
var timeLimit: String = DEFAULT_TIME
) : Comparable<Game> {
open fun createSetsForPlayers(playerIds: List<Long>): Array<Scores> = buildSequence {
playerIds.forEach { id ->
yield(Scores(
playerId = id,
gameId = [email protected],
scores = mutableListOf(startingScore.toLong())
))
}
}.toList().toTypedArray()
fun newTimeLimit(timeLimitString: String) {
timeLimit = timeLimitString
completed = false
}
fun haveAllSetsBeenPlayed() = numSetsPlayed == numSetsChosen
fun usesSets() = numSetsChosen > 1
override fun compareTo(other: Game): Int =
other.lastPlayedDate.compareTo(this.lastPlayedDate)
} | gpl-3.0 | 88634d316070c08b03e82d37a0b9ce0e | 33.682353 | 91 | 0.600271 | 4.513017 | false | false | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsSettings.kt | 4 | 8376 | // 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.codeInsight.hints
import com.intellij.configurationStore.deserializeInto
import com.intellij.configurationStore.serialize
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.messages.Topic
import org.jdom.Element
import java.util.*
@State(name = "InlayHintsSettings", storages = [Storage("editor.xml")], category = SettingsCategory.CODE)
class InlayHintsSettings : PersistentStateComponent<InlayHintsSettings.State> {
companion object {
@JvmStatic
fun instance(): InlayHintsSettings {
return ApplicationManager.getApplication().getService(InlayHintsSettings::class.java)
}
/**
* Inlay hints settings changed.
*/
@Topic.AppLevel
@JvmStatic
val INLAY_SETTINGS_CHANGED: Topic<SettingsListener> = Topic(SettingsListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN)
}
private val listener: SettingsListener
get() = ApplicationManager.getApplication().messageBus.syncPublisher(INLAY_SETTINGS_CHANGED)
private var myState = State()
private val lock = Any()
class State {
// explicitly enabled languages (because of enabled by default setting, we can't say that everything which is not disabled is enabled)
var enabledHintProviderIds: TreeSet<String> = sortedSetOf()
var disabledHintProviderIds: TreeSet<String> = sortedSetOf()
// We can't store Map<String, Any> directly, because values deserialized as Object
var settingsMapElement: Element = Element("settingsMapElement")
var lastViewedProviderKeyId: String? = null
var isEnabled: Boolean = true
var disabledLanguages: TreeSet<String> = sortedSetOf()
}
// protected by lock
private val myCachedSettingsMap: MutableMap<String, Any> = hashMapOf()
// protected by lock
private val isEnabledByDefaultIdsCache: MutableMap<String, Boolean> = hashMapOf()
init {
InlayHintsProviderExtension.inlayProviderName.addChangeListener(Runnable {
synchronized(lock) {
isEnabledByDefaultIdsCache.clear()
}
}, null)
}
fun changeHintTypeStatus(key: SettingsKey<*>, language: Language, enable: Boolean) {
synchronized(lock) {
val id = key.getFullId(language)
if (enable) {
if (!isEnabledByDefault(key, language)) {
myState.enabledHintProviderIds.add(id)
}
myState.disabledHintProviderIds.remove(id)
}
else {
myState.enabledHintProviderIds.remove(id)
myState.disabledHintProviderIds.add(id)
}
}
listener.settingsChanged()
}
fun setHintsEnabledForLanguage(language: Language, enabled: Boolean) {
val settingsChanged = synchronized(lock) {
val id = language.id
if (enabled) {
myState.disabledLanguages.remove(id)
}
else {
myState.disabledLanguages.add(id)
}
}
if (settingsChanged) {
listener.languageStatusChanged()
listener.settingsChanged()
}
}
fun saveLastViewedProviderId(providerId: String): Unit = synchronized(lock) {
myState.lastViewedProviderKeyId = providerId
}
fun getLastViewedProviderId() : String? {
return myState.lastViewedProviderKeyId
}
fun setEnabledGlobally(enabled: Boolean) {
val settingsChanged = synchronized(lock) {
if (myState.isEnabled != enabled) {
myState.isEnabled = enabled
listener.globalEnabledStatusChanged(enabled)
true
} else {
false
}
}
if (settingsChanged) {
listener.settingsChanged()
}
}
fun hintsEnabledGlobally() : Boolean = synchronized(lock) {
return myState.isEnabled
}
/**
* @param createSettings is a setting, that was obtained from createSettings method of provider
*/
fun <T: Any> findSettings(key: SettingsKey<T>, language: Language, createSettings: ()->T): T = synchronized(lock) {
val fullId = key.getFullId(language)
return getSettingCached(fullId, createSettings)
}
fun <T: Any> storeSettings(key: SettingsKey<T>, language: Language, value: T) {
synchronized(lock){
val fullId = key.getFullId(language)
myCachedSettingsMap[fullId] = value as Any
val element = myState.settingsMapElement.clone()
element.removeChild(fullId)
val serialized = serialize(value)
if (serialized == null) {
myState.settingsMapElement = element
}
else {
val storeElement = Element(fullId)
val wrappedSettingsElement = storeElement.addContent(serialized)
myState.settingsMapElement = element.addContent(wrappedSettingsElement)
element.sortAttributes(compareBy { it.name })
}
}
listener.settingsChanged()
}
fun hintsEnabled(language: Language) : Boolean = synchronized(lock) {
return language.id !in myState.disabledLanguages
}
fun hintsShouldBeShown(language: Language) : Boolean = synchronized(lock) {
if (!hintsEnabledGlobally()) return false
return hintsEnabled(language)
}
fun hintsEnabled(key: SettingsKey<*>, language: Language) : Boolean {
synchronized(lock) {
if (explicitlyDisabled(language, key)) {
return false
}
if (isEnabledByDefault(key, language)) {
return true
}
return key.getFullId(language) in state.enabledHintProviderIds
}
}
private fun explicitlyDisabled(language: Language, key: SettingsKey<*>): Boolean {
var lang: Language? = language
while (lang != null) {
if (key.getFullId(lang) in myState.disabledHintProviderIds) {
return true
}
lang = lang.baseLanguage
}
return false
}
fun hintsShouldBeShown(key: SettingsKey<*>, language: Language): Boolean = synchronized(lock) {
return hintsEnabledGlobally() &&
hintsEnabled(language) &&
hintsEnabled(key, language)
}
override fun getState(): State = synchronized(lock) {
return myState
}
override fun loadState(state: State): Unit = synchronized(lock) {
val elementChanged = myState.settingsMapElement != state.settingsMapElement
if (elementChanged) {
myCachedSettingsMap.clear()
}
myState = state
}
// may return parameter settings object or cached object
private fun <T : Any> getSettingCached(id: String, settings: ()->T): T {
synchronized(lock) {
@Suppress("UNCHECKED_CAST")
val cachedValue = myCachedSettingsMap[id] as T?
if (cachedValue != null) return cachedValue
val notCachedSettings = getSettingNotCached(id, settings())
myCachedSettingsMap[id] = notCachedSettings
return notCachedSettings
}
}
private fun <T : Any> getSettingNotCached(id: String, settings: T): T {
val state = myState.settingsMapElement
val settingsElement = state.getChild(id)
if (settingsElement == null) return settings
val settingsElementChildren= settingsElement.children
if (settingsElementChildren.isEmpty()) return settings
settingsElementChildren.first().deserializeInto(settings)
return settings
}
// must be called under lock
private fun isEnabledByDefault(key: SettingsKey<*>, language: Language) : Boolean {
return isEnabledByDefaultIdsCache.computeIfAbsent(key.getFullId(language)) { computeIsEnabledByDefault(it) }
}
private fun computeIsEnabledByDefault(id: String) : Boolean {
val bean = InlayHintsProviderExtension.inlayProviderName.extensionList
.firstOrNull {
val keyId = it.settingsKeyId ?: return@firstOrNull false
SettingsKey.getFullId(it.language!!, keyId) == id
} ?: return true
return bean.isEnabledByDefault
}
interface SettingsListener {
/**
* @param newEnabled whether inlay hints are globally switched on or off now
*/
fun globalEnabledStatusChanged(newEnabled: Boolean) {}
/**
* Called, when hints are enabled/disabled for some language
*/
fun languageStatusChanged() {}
/**
* Called when any settings in inlay hints were changed
*/
fun settingsChanged() {}
}
}
| apache-2.0 | 262bb28498d0425e7d34c8107debd0e7 | 31.465116 | 138 | 0.703438 | 4.794505 | false | false | false | false |
siosio/intellij-community | platform/util/src/com/intellij/util/io/writeAheadLog.kt | 1 | 15208 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.io
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.CompressionUtil
import com.intellij.util.ConcurrencyUtil
import it.unimi.dsi.fastutil.Hash
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap
import java.io.*
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.concurrent.ExecutorService
private const val VERSION = 0
internal enum class WalOpCode(internal val code: Int) {
PUT(0),
REMOVE(1),
APPEND(2)
}
internal class PersistentEnumeratorWal<Data> @Throws(IOException::class) @JvmOverloads constructor(dataDescriptor: KeyDescriptor<Data>,
useCompression: Boolean,
file: Path,
walIoExecutor: ExecutorService,
compact: Boolean = false) : Closeable {
private val underlying = PersistentMapWal(dataDescriptor, integerExternalizer, useCompression, file, walIoExecutor, compact)
fun enumerate(data: Data, id: Int) = underlying.put(data, id)
fun flush() = underlying.flush()
override fun close() = underlying.close()
}
internal class PersistentMapWal<K, V> @Throws(IOException::class) @JvmOverloads constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
private val useCompression: Boolean,
private val file: Path,
private val walIoExecutor: ExecutorService /*todo ensure sequential*/,
compact: Boolean = false) : Closeable {
private val out: DataOutputStream
val version: Int = VERSION
init {
if (compact) {
tryCompact(file, keyDescriptor, valueExternalizer)?.let { compactedWal ->
FileUtil.deleteWithRenaming(file)
FileUtil.rename(compactedWal.toFile(), file.toFile())
}
}
ensureCompatible(version, useCompression, file)
out = DataOutputStream(Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND).buffered())
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, useCompression: Boolean, file: Path) {
if (!Files.exists(file)) {
Files.createDirectories(file.parent)
DataOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)).use {
DataInputOutputUtil.writeINT(it, expectedVersion)
it.writeBoolean(useCompression)
}
return
}
val (actualVersion, actualUsesCompression) = DataInputStream(Files.newInputStream(file, StandardOpenOption.READ)).use {
DataInputOutputUtil.readINT(it) to it.readBoolean()
}
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
if (actualUsesCompression != useCompression) {
throw VersionUpdatedException(file, useCompression, actualUsesCompression)
}
}
private fun WalOpCode.write(outputStream: DataOutputStream): Unit = outputStream.writeByte(code)
private fun ByteArray.write(outputStream: DataOutputStream) {
if (useCompression) {
CompressionUtil.writeCompressed(outputStream, this, 0, size)
}
else {
outputStream.writeInt(size)
outputStream.write(this)
}
}
private fun AppendablePersistentMap.ValueDataAppender.writeToByteArray(): ByteArray {
val baos = UnsyncByteArrayOutputStream()
append(DataOutputStream(baos))
return baos.toByteArray()
}
@Throws(IOException::class)
fun appendData(key: K, appender: AppendablePersistentMap.ValueDataAppender) {
walIoExecutor.submit {
WalOpCode.APPEND.write(out)
keyDescriptor.save(out, key)
appender.writeToByteArray().write(out)
}
}
@Throws(IOException::class)
fun put(key: K, value: V) {
walIoExecutor.submit {
WalOpCode.PUT.write(out)
keyDescriptor.save(out, key)
writeData(value, valueExternalizer).write(out)
}
}
@Throws(IOException::class)
fun remove(key: K) {
walIoExecutor.submit {
WalOpCode.REMOVE.write(out)
keyDescriptor.save(out, key)
}
}
@Throws(IOException::class) // todo rethrow io exception
fun flush() {
walIoExecutor.submit {
out.flush()
}.get()
}
// todo rethrow io exception
@Throws(IOException::class)
override fun close() {
walIoExecutor.submit {
out.close()
}.get()
}
@Throws(IOException::class)
fun closeAndDelete() {
close()
FileUtil.deleteWithRenaming(file)
}
}
private val integerExternalizer: EnumeratorIntegerDescriptor
get() = EnumeratorIntegerDescriptor.INSTANCE
sealed class WalEvent<K, V> {
data class PutEvent<K, V>(override val key: K, val value: V): WalEvent<K, V>()
data class RemoveEvent<K, V>(override val key: K): WalEvent<K, V>()
data class AppendEvent<K, V>(override val key: K, val data: ByteArray): WalEvent<K, V>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppendEvent<*, *>
if (key != other.key) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = key?.hashCode() ?: 0
result = 31 * result + data.contentHashCode()
return result
}
}
abstract val key: K
}
@Throws(IOException::class)
fun <Data> restoreMemoryEnumeratorFromWal(walFile: Path,
dataDescriptor: KeyDescriptor<Data>): List<Data> {
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, List<Data>> {
val result = arrayListOf<Data>()
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) {
assert(result.size == value)
result.add(key)
}
override fun result(): List<Data> = result
}).toList()
}
@Throws(IOException::class)
fun <Data> restorePersistentEnumeratorFromWal(walFile: Path,
outputMapFile: Path,
dataDescriptor: KeyDescriptor<Data>): PersistentEnumerator<Data> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, PersistentEnumerator<Data>> {
val result = PersistentEnumerator(outputMapFile, dataDescriptor, 1024)
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) = assert(result.enumerate(key) == value)
override fun result(): PersistentEnumerator<Data> = result
})
}
@Throws(IOException::class)
fun <K, V> restorePersistentMapFromWal(walFile: Path,
outputMapFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): PersistentMap<K, V> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, PersistentMap<K, V>> {
val result = PersistentHashMap(outputMapFile, keyDescriptor, valueExternalizer)
override fun get(key: K): V? = result.get(key)
override fun remove(key: K) = result.remove(key)
override fun put(key: K, value: V) = result.put(key, value)
override fun result(): PersistentMap<K, V> = result
})
}
@Throws(IOException::class)
fun <K, V> restoreHashMapFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Map<K, V> {
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, Map<K, V>> {
private val map = linkedMapOf<K, V>()
override fun get(key: K): V? = map.get(key)
override fun remove(key: K) {
map.remove(key)
}
override fun put(key: K, value: V) {
map.put(key, value)
}
override fun result(): Map<K, V> = map
})
}
private fun <K, V> tryCompact(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Path? {
if (!Files.exists(walFile)) {
return null
}
val keyToLastEvent = Object2ObjectOpenCustomHashMap<K, IntSet>(object : Hash.Strategy<K> {
override fun equals(a: K?, b: K?): Boolean {
if (a == b) return true
if (a == null) return false
if (b == null) return false
return keyDescriptor.isEqual(a, b)
}
override fun hashCode(o: K?): Int = keyDescriptor.getHashCode(o)
})
val shouldCompact = PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
var eventCount = 0
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> keyToLastEvent.computeIfAbsent(walEvent.key) { IntLinkedOpenHashSet() }.add(eventCount)
is WalEvent.PutEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet().also{ set -> set.add(eventCount) })
is WalEvent.RemoveEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet())
}
keyToLastEvent.computeIfAbsent(walEvent.key) { IntLinkedOpenHashSet() }.add(eventCount)
eventCount++
}
keyToLastEvent.size * 2 < eventCount
}
if (!shouldCompact) return null
val compactedWalFile = walFile.resolveSibling("${walFile.fileName}_compacted")
PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { walPlayer ->
PersistentMapWal(keyDescriptor, valueExternalizer, walPlayer.useCompression, compactedWalFile, ConcurrencyUtil.newSameThreadExecutorService()).use { compactedWal ->
walPlayer.readWal().forEachIndexed{index, walEvent ->
val key = walEvent.key
val events = keyToLastEvent.get(key) ?: throw IOException("No events found for key = $key")
if (events.contains(index)) {
when (walEvent) {
is WalEvent.AppendEvent -> compactedWal.appendData(key, AppendablePersistentMap.ValueDataAppender { out -> out.write(walEvent.data) })
is WalEvent.PutEvent -> compactedWal.put(key, walEvent.value)
is WalEvent.RemoveEvent -> {/*do nothing*/}
}
}
}
}
}
return compactedWalFile
}
private fun <V> readData(array: ByteArray, valueExternalizer: DataExternalizer<V>): V {
return valueExternalizer.read(DataInputStream(ByteArrayInputStream(array)))
}
private fun <V> writeData(value: V, valueExternalizer: DataExternalizer<V>): ByteArray {
val baos = UnsyncByteArrayOutputStream()
valueExternalizer.save(DataOutputStream(baos), value)
return baos.toByteArray()
}
private interface Accumulator<K, V, R> {
fun get(key: K): V?
fun remove(key: K)
fun put(key: K, value: V)
fun result(): R
}
private fun <K, V, R> restoreFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>,
accumulator: Accumulator<K, V, R>): R {
return PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> {
val previous = accumulator.get(walEvent.key)
val currentData = if (previous == null) walEvent.data else writeData(previous, valueExternalizer) + walEvent.data
accumulator.put(walEvent.key, readData(currentData, valueExternalizer))
}
is WalEvent.PutEvent -> accumulator.put(walEvent.key, walEvent.value)
is WalEvent.RemoveEvent -> accumulator.remove(walEvent.key)
}
}
accumulator.result()
}
}
class PersistentMapWalPlayer<K, V> @Throws(IOException::class) constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
file: Path) : Closeable {
private val input: DataInputStream
internal val useCompression: Boolean
val version: Int = VERSION
init {
if (!Files.exists(file)) {
throw FileNotFoundException(file.toString())
}
input = DataInputStream(Files.newInputStream(file).buffered())
ensureCompatible(version, input, file)
useCompression = input.readBoolean()
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, input: DataInputStream, file: Path) {
val actualVersion = DataInputOutputUtil.readINT(input)
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
}
fun readWal(): Sequence<WalEvent<K, V>> = generateSequence {
readNextEvent()
}
@Throws(IOException::class)
override fun close() = input.close()
@Throws(IOException::class)
private fun readNextEvent(): WalEvent<K, V>? {
val walOpCode: WalOpCode
try {
walOpCode = readNextOpCode(input)
}
catch (e: EOFException) {
return null
}
return when (walOpCode) {
WalOpCode.PUT -> WalEvent.PutEvent(keyDescriptor.read(input), readData(readByteArray(input), valueExternalizer))
WalOpCode.REMOVE -> WalEvent.RemoveEvent(keyDescriptor.read(input))
WalOpCode.APPEND -> WalEvent.AppendEvent(keyDescriptor.read(input), readByteArray(input))
}
}
private fun readByteArray(inputStream: DataInputStream): ByteArray {
if (useCompression) {
return CompressionUtil.readCompressed(inputStream)
}
else {
return ByteArray(inputStream.readInt()).also { inputStream.readFully(it) }
}
}
private fun readNextOpCode(inputStream: DataInputStream): WalOpCode =
WalOpCode.values()[inputStream.readByte().toInt()]
} | apache-2.0 | 0ca453cda22c20f3cc5b5fd6e18b5237 | 35.825666 | 168 | 0.642557 | 4.897907 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/kotlin/KotlinPlugin.kt | 5 | 10825 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildFileIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.withIrs
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.buildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import java.nio.file.Path
class KotlinPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "kotlin"
private val moduleDependenciesValidator = settingValidator<List<Module>> { modules ->
val allModules = modules.withAllSubModules(includeSourcesets = true).toSet()
val allModulePaths = allModules.map(Module::path).toSet()
allModules.flatMap { module ->
module.dependencies.map { dependency ->
val isValidModule = when (dependency) {
is ModuleReference.ByPath -> dependency.path in allModulePaths
is ModuleReference.ByModule -> dependency.module in allModules
}
ValidationResult.create(isValidModule) {
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
dependency,
module.path
)
}
}
}.fold()
}
val version by property(
// todo do not hardcode kind & repository
WizardKotlinVersion(
Versions.KOTLIN,
KotlinVersionKind.M,
Repositories.KOTLIN_EAP_MAVEN_CENTRAL,
KotlinVersionProviderService.getBuildSystemPluginRepository(
KotlinVersionKind.M,
devRepository = Repositories.JETBRAINS_KOTLIN_DEV
)
)
)
val initKotlinVersions by pipelineTask(GenerationPhase.PREPARE_GENERATION) {
title = KotlinNewProjectWizardBundle.message("plugin.kotlin.downloading.kotlin.versions")
withAction {
val version = service<KotlinVersionProviderService>().getKotlinVersion(projectKind.settingValue)
KotlinPlugin.version.update { version.asSuccess() }
}
}
val projectKind by enumSetting<ProjectKind>(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.project.kind"),
GenerationPhase.FIRST_STEP,
)
private fun List<Module>.findDuplicatesByName() =
groupingBy { it.name }.eachCount().filter { it.value > 1 }
val modules by listSetting(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.modules"),
GenerationPhase.SECOND_STEP,
Module.parser,
) {
validate { value ->
val allModules = value.withAllSubModules()
val duplicatedModules = allModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}
validate { value ->
value.withAllSubModules().filter { it.kind == ModuleKind.multiplatform }.map { module ->
val duplicatedModules = module.subModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.targets",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}.fold()
}
validate(moduleDependenciesValidator)
}
val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
runAfter(StructurePlugin.createProjectDir)
withAction {
BuildSystemPlugin.buildFiles.update {
val modules = modules.settingValue
val (buildFiles) = createBuildFiles(modules)
buildFiles.map { it.withIrs(RepositoryIR(DefaultRepository.MAVEN_CENTRAL)) }.asSuccess()
}
}
}
val createPluginRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
withAction {
val version = version.propertyValue
if (version.kind.isStable) return@withAction UNIT_SUCCESS
val pluginRepository = version.buildSystemPluginRepository(buildSystemType) ?: return@withAction UNIT_SUCCESS
BuildSystemPlugin.pluginRepositoreis.addValues(pluginRepository) andThen
updateBuildFiles { buildFile ->
buildFile.withIrs(RepositoryIR(version.repository)).asSuccess()
}
}
}
val createResourceDirectories by booleanSetting("Generate Resource Folders", GenerationPhase.PROJECT_GENERATION) {
defaultValue = value(true)
}
val createSourcesetDirectories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(createModules)
withAction {
fun Path?.createKotlinAndResourceDirectories(moduleConfigurator: ModuleConfigurator): TaskResult<Unit> {
if (this == null) return UNIT_SUCCESS
return with(service<FileSystemWizardService>()) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.kotlinDirectoryName) andThen
if (createResourceDirectories.settingValue) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.resourcesDirectoryName)
} else {
UNIT_SUCCESS
}
}
}
forEachModule { moduleIR ->
moduleIR.sourcesets.mapSequenceIgnore { sourcesetIR ->
sourcesetIR.path.createKotlinAndResourceDirectories(moduleIR.originalModule.configurator)
}
}
}
}
private fun Writer.createBuildFiles(modules: List<Module>): TaskResult<List<BuildFileIR>> =
with(
ModulesToIRsConverter(
ModulesToIrConversionData(
modules,
projectPath,
StructurePlugin.name.settingValue,
version.propertyValue,
buildSystemType,
pomIR()
)
)
) { createBuildFiles() }
}
override val settings: List<PluginSetting<*, *>> =
listOf(
projectKind,
modules,
createResourceDirectories,
)
override val pipelineTasks: List<PipelineTask> =
listOf(
initKotlinVersions,
createModules,
createPluginRepositories,
createSourcesetDirectories
)
override val properties: List<Property<*>> =
listOf(version)
}
enum class ProjectKind(
@Nls override val text: String,
val supportedBuildSystems: Set<BuildSystemType>,
val shortName: String = text,
val message: String? = null,
) : DisplayableSettingItem {
Singleplatform(
KotlinNewProjectWizardBundle.message("project.kind.singleplatform"),
supportedBuildSystems = BuildSystemType.values().toSet()
),
Multiplatform(KotlinNewProjectWizardBundle.message("project.kind.multiplatform"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Android(KotlinNewProjectWizardBundle.message("project.kind.android"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Js(KotlinNewProjectWizardBundle.message("project.kind.kotlin.js"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
COMPOSE(
KotlinNewProjectWizardBundle.message("project.kind.compose"),
supportedBuildSystems = setOf(BuildSystemType.GradleKotlinDsl),
shortName = KotlinNewProjectWizardBundle.message("project.kind.compose.short.name"),
message = "uses Kotlin ${Versions.KOTLIN_VERSION_FOR_COMPOSE}"
)
}
fun List<Module>.withAllSubModules(includeSourcesets: Boolean = false): List<Module> = buildList {
fun handleModule(module: Module) {
+module
if (module.kind != ModuleKind.multiplatform
|| includeSourcesets && module.kind == ModuleKind.multiplatform
) {
module.subModules.forEach(::handleModule)
}
}
forEach(::handleModule)
}
| apache-2.0 | f775310f393df22830784a42a4b9c8e4 | 44.868644 | 158 | 0.630947 | 6.084879 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/uname/UName.kt | 2 | 857 | package com.github.kerubistan.kerub.utils.junix.uname
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import org.apache.sshd.client.session.ClientSession
object UName : OsCommand {
// any unix-like OS should have an uname
override fun available(hostCapabilities: HostCapabilities?): Boolean = true
fun kernelName(session: ClientSession) = session.executeOrDie("uname -s").trim()
fun machineType(session: ClientSession) = session.executeOrDie("uname -m").trim()
fun processorType(session: ClientSession) = session.executeOrDie("uname -p").trim()
fun kernelVersion(session: ClientSession) = session.executeOrDie("uname -r").trim()
fun operatingSystem(session: ClientSession) = session.executeOrDie("uname -o").trim()
} | apache-2.0 | 5769d4bd032ad6f7bfd8de369dfba626 | 39.857143 | 86 | 0.791132 | 3.949309 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/lValueUtil.kt | 7 | 2022 | // 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.
@file:JvmName("GroovyLValueUtil")
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.POSTFIX_UNARY_OP_SET
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.UnknownArgument
/**
* The expression is a rValue when it is in rValue position or it's a lValue of operator assignment.
*/
fun GrExpression.isRValue(): Boolean {
val (parent, lastParent) = skipParentsOfType<GrParenthesizedExpression>() ?: return true
return parent !is GrAssignmentExpression || lastParent != parent.lValue || parent.isOperatorAssignment
}
/**
* The expression is a lValue when it's on the left of whatever assignment.
*/
fun GrExpression.isLValue(): Boolean {
return when (val parent = parent) {
is GrTuple -> true
is GrAssignmentExpression -> this == parent.lValue
is GrUnaryExpression -> parent.operationTokenType in POSTFIX_UNARY_OP_SET
else -> false
}
}
/**
* @return non-null result iff this expression is an l-value
*/
fun GrExpression.getRValue(): Argument? {
val parent = parent
return when {
parent is GrTuple -> UnknownArgument
parent is GrAssignmentExpression && parent.lValue === this -> {
if (parent.isOperatorAssignment) {
ExpressionArgument(parent)
}
else {
parent.rValue?.let(::ExpressionArgument) ?: UnknownArgument
}
}
parent is GrUnaryExpression && parent.operationTokenType in POSTFIX_UNARY_OP_SET -> IncDecArgument(parent)
else -> null
}
}
private data class IncDecArgument(private val unary: GrUnaryExpression) : Argument {
override val type: PsiType? get() = unary.operationType
}
| apache-2.0 | 04ff8749697d91e7f345823a31bb8e6a | 35.763636 | 140 | 0.742334 | 4.265823 | false | false | false | false |
appmattus/layercache | samples/androidApp/src/main/kotlin/com/appmattus/layercache/samples/sharedprefs/SharedPrefsViewModel.kt | 1 | 4600 | /*
* Copyright 2021 Appmattus Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appmattus.layercache.samples.sharedprefs
import android.content.Context
import androidx.lifecycle.ViewModel
import com.appmattus.layercache.Cache
import com.appmattus.layercache.asStringCache
import com.appmattus.layercache.encrypt
import com.appmattus.layercache.get
import com.appmattus.layercache.samples.data.LastRetrievedWrapper
import com.appmattus.layercache.samples.data.network.KtorDataSource
import com.appmattus.layercache.samples.domain.PersonalDetails
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.serialization.json.Json.Default.decodeFromString
import kotlinx.serialization.json.Json.Default.encodeToString
import org.orbitmvi.orbit.Container
import org.orbitmvi.orbit.ContainerHost
import org.orbitmvi.orbit.syntax.simple.intent
import org.orbitmvi.orbit.syntax.simple.reduce
import org.orbitmvi.orbit.viewmodel.container
import javax.inject.Inject
@HiltViewModel
class SharedPrefsViewModel @Inject constructor(
@ApplicationContext context: Context
) : ViewModel(), ContainerHost<SharedPrefsState, Unit> {
// Stores the name of the cache data was returned from
private val lastRetrievedWrapper = LastRetrievedWrapper()
// Network fetcher, wrapped so we can detect when get returns a value
private val ktorDataSource: Cache<Unit, PersonalDetails> = with(lastRetrievedWrapper) { KtorDataSource().wrap("Ktor network call") }
// Encrypted shared preferences cache
private val sharedPreferences = context.getSharedPreferences("encrypted", Context.MODE_PRIVATE)
private val encryptedSharedPreferencesDataSource: Cache<Unit, PersonalDetails> = with(lastRetrievedWrapper) {
sharedPreferences
// Access as a Cache<String, String>
.asStringCache()
// Wrap the cache so we can detect when get returns a value
.wrap("Shared preferences")
// Encrypt all keys and values stored in this cache
.encrypt(context)
// We are only storing one value so using a default key and mapping externally to Unit, i.e. cache becomes Cache<Unit, String>
.keyTransform<Unit> {
"personalDetails"
}
// Transform string values to PersonalDetails, i.e. cache becomes Cache<Unit, PersonalDetails>
.valueTransform(transform = {
decodeFromString(PersonalDetails.serializer(), it)
}, inverseTransform = {
encodeToString(PersonalDetails.serializer(), it)
})
}
// Combine shared preferences and ktor caches, i.e. first retrieve value from shared preferences and if not available retrieve from network
private val repository = encryptedSharedPreferencesDataSource.compose(ktorDataSource)
override val container: Container<SharedPrefsState, Unit> = container(SharedPrefsState()) {
loadPreferencesContent()
}
// Update state with personal details retrieved from the repository
fun loadPersonalDetails() = intent {
lastRetrievedWrapper.reset()
reduce {
state.copy(personalDetails = null, loadedFrom = "")
}
val personalDetails = repository.get()
reduce {
state.copy(personalDetails = personalDetails, loadedFrom = lastRetrievedWrapper.lastRetrieved ?: "")
}
loadPreferencesContent()
}
// Update the state with the current contents of shared preferences so we can demonstrate that the data is stored encrypted
private fun loadPreferencesContent() = intent {
val content = sharedPreferences.all
reduce {
state.copy(preferences = content)
}
}
// Clear all data from shared preferences and the state object
fun clear() = intent {
reduce {
state.copy(personalDetails = null, loadedFrom = "")
}
sharedPreferences.edit().clear().apply()
loadPreferencesContent()
}
}
| apache-2.0 | 1ff004b35b7d95d5dd7640f2332f8c9d | 39.350877 | 143 | 0.72087 | 5.016358 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowInfoImpl.kt | 1 | 5780 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.facet.ui.FacetDependentToolWindow
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ext.LibraryDependentToolWindow
import com.intellij.util.xmlb.Converter
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Rectangle
import kotlin.math.max
import kotlin.math.min
private val LOG = logger<WindowInfoImpl>()
@Suppress("EqualsOrHashCode")
@Tag("window_info")
@Property(style = Property.Style.ATTRIBUTE)
class WindowInfoImpl : Cloneable, WindowInfo, BaseState() {
companion object {
internal const val TAG = "window_info"
const val DEFAULT_WEIGHT = 0.33f
}
@get:Attribute("active")
override var isActiveOnStart by property(false)
@get:Attribute(converter = ToolWindowAnchorConverter::class)
override var anchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT }
@get:Attribute(converter = ToolWindowAnchorConverter::class)
override var largeStripeAnchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT }
@get:Attribute("auto_hide")
override var isAutoHide by property(false)
/**
* Bounds of window in "floating" mode. It equals to `null` if floating bounds are undefined.
*/
@get:Property(flat = true, style = Property.Style.ATTRIBUTE)
override var floatingBounds by property<Rectangle?>(null) { it == null || (it.width == 0 && it.height == 0 && it.x == 0 && it.y == 0) }
/**
* This attribute persists state 'maximized' for `ToolWindowType.WINDOWED` where decoration is presented by JFrame
*/
@get:Attribute("maximized")
override var isMaximized by property(false)
/**
* ID of the tool window
*/
override var id by string()
/**
* @return type of the tool window in internal (docked or sliding) mode. Actually the tool
* window can be in floating mode, but this method has sense if you want to know what type
* tool window had when it was internal one.
*/
@get:Attribute("internal_type")
override var internalType by enum(ToolWindowType.DOCKED)
override var type by enum(ToolWindowType.DOCKED)
@get:Attribute("visible")
override var isVisible by property(false)
@get:Attribute("show_stripe_button")
override var isShowStripeButton by property(true)
@get:Attribute("visibleOnLargeStripe")
override var isVisibleOnLargeStripe by property(false)
/**
* Internal weight of tool window. "weight" means how much of internal desktop
* area the tool window is occupied. The weight has sense if the tool window is docked or
* sliding.
*/
override var weight by property(DEFAULT_WEIGHT) { max(0f, min(1f, it)) }
override var sideWeight by property(0.5f) { max(0f, min(1f, it)) }
@get:Attribute("side_tool")
override var isSplit by property(false)
@get:Attribute("content_ui", converter = ContentUiTypeConverter::class)
override var contentUiType: ToolWindowContentUiType by property(ToolWindowContentUiType.TABBED) { it == ToolWindowContentUiType.TABBED }
/**
* Defines order of tool window button inside the stripe.
*/
override var order by property(-1)
@get:Attribute("orderOnLargeStripe")
override var orderOnLargeStripe by property(-1)
@get:Transient
override var isFromPersistentSettings = true
internal set
fun copy(): WindowInfoImpl {
val info = WindowInfoImpl()
info.copyFrom(this)
info.isFromPersistentSettings = isFromPersistentSettings
return info
}
override val isDocked: Boolean
get() = type == ToolWindowType.DOCKED
internal fun normalizeAfterRead() {
setTypeAndCheck(type)
if (isVisible && id != null && !canActivateOnStart(id!!)) {
isVisible = false
}
}
internal fun setType(type: ToolWindowType) {
if (ToolWindowType.DOCKED == type || ToolWindowType.SLIDING == type) {
internalType = type
}
setTypeAndCheck(type)
}
// hardcoded to avoid single-usage-API
private fun setTypeAndCheck(value: ToolWindowType) {
type = if (ToolWindowId.PREVIEW === id && value == ToolWindowType.DOCKED) ToolWindowType.SLIDING else value
}
override fun hashCode(): Int {
return anchor.hashCode() + id!!.hashCode() + type.hashCode() + order
}
override fun toString() = "id: $id, ${super.toString()}"
}
private class ContentUiTypeConverter : Converter<ToolWindowContentUiType>() {
override fun fromString(value: String): ToolWindowContentUiType = ToolWindowContentUiType.getInstance(value)
override fun toString(value: ToolWindowContentUiType): String = value.name
}
private class ToolWindowAnchorConverter : Converter<ToolWindowAnchor>() {
override fun fromString(value: String): ToolWindowAnchor {
try {
return ToolWindowAnchor.fromText(value)
}
catch (e: IllegalArgumentException) {
if (!value.equals("none", ignoreCase = true)) {
LOG.warn(e)
}
return ToolWindowAnchor.LEFT
}
}
override fun toString(value: ToolWindowAnchor) = value.toString()
}
private fun canActivateOnStart(id: String): Boolean {
val ep = findEp(ToolWindowEP.EP_NAME.iterable, id)
?: findEp(FacetDependentToolWindow.EXTENSION_POINT_NAME.iterable, id)
?: findEp(LibraryDependentToolWindow.EXTENSION_POINT_NAME.iterable, id)
return ep == null || !ep.isDoNotActivateOnStart
}
private fun findEp(list: Iterable<ToolWindowEP>, id: String): ToolWindowEP? {
return list.firstOrNull { id == it.id }
} | apache-2.0 | fa46d2228f0c2ebc29d888fe041a600c | 32.610465 | 138 | 0.731315 | 4.256259 | false | false | false | false |
erdo/asaf-project | fore-kt-core/src/main/java/co/early/fore/kt/core/time/Time.kt | 1 | 1232 | package co.early.fore.kt.core.time
import co.early.fore.kt.core.delegate.Fore
import co.early.fore.kt.core.logging.Logger
import java.text.DecimalFormat
val nanosFormat = DecimalFormat("#,###")
/**
* invokes the function,
* returns the result,
* then logs the time taken in a standard format
*/
inline fun <T> measureNanos(logger: Logger? = null, function: () -> T): T {
return measureNanos({ nanos ->
Fore.getLogger(logger).i("operation took: ${nanosFormat.format(nanos)} ns " +
"thread:${Thread.currentThread().id}")
}) { function.invoke() }
}
/**
* invokes the function,
* invokes timeTaken with the time taken in ns to run the function,
* returns the result or the function
*/
inline fun <T> measureNanos(timeTaken: (Long) -> Unit, function: () -> T): T {
val decoratedResult = measureNanos(function)
timeTaken(decoratedResult.second)
return decoratedResult.first
}
/**
* invokes the function,
* returns a Pair(first = result of the function, second = time taken in ns)
*/
inline fun <T> measureNanos(function: () -> T): Pair<T, Long> {
val startTime = System.nanoTime()
val result: T = function.invoke()
return result to (System.nanoTime() - startTime)
}
| apache-2.0 | 6449afd02cb55dcceee314267834b84d | 29.8 | 85 | 0.67776 | 3.744681 | false | false | false | false |
Coding/Coding-Android | terminal-coding/src/main/java/net/coding/program/terminal/TerminalActivity.kt | 1 | 8051 | package net.coding.program.terminal
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_terminal.*
import net.coding.program.common.ui.BackActivity
class TerminalActivity : BackActivity() {
lateinit var fixationKeys: List<View>
lateinit var lastSelectRadio: View
var ctrlPressed = false
var altPressed = false
private val colorSelect = 0xFFBBC2CA.toInt()
private val colorNormal = 0xFFFFFFFF.toInt()
private val colorSelectExt = 0xFFA7B0BD.toInt()
var showLogin = false
val clickKeyButton = View.OnClickListener {
val tag = it.tag
if (tag is KeyItem) {
when (tag) {
KeyItem.CTRL -> {
ctrlPressed = !ctrlPressed
it.setBackgroundColor(if (ctrlPressed) colorNormal else colorSelect)
}
KeyItem.ALT -> {
altPressed = !altPressed
it.setBackgroundColor(if (altPressed) colorNormal else colorSelect)
}
KeyItem.ESC -> {
showLogin = !showLogin
if (showLogin) {
var url = "http://ide.xiayule.net"
url = "http://ide.xiayule.net"
loadUrl(url)
showMiddleToast("打开登录页面")
} else {
var url = "http://ide.test:8060"
url = "http://ide.test:8060 "
loadUrl(url)
showMiddleToast("打开Terminal")
}
}
else -> {
webView.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, tag.value))
webView.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, tag.value))
}
}
}
}
fun loadUrl(url: String) {
// url = "http://192.168.0.212:8060"
// url = "http://www.baidu.com"
// url = "http://ide.xiayule.net"
webView.settings.let {
it.javaScriptEnabled = true
it.domStorageEnabled = true
it.setAppCachePath(cacheDir.absolutePath)
it.allowFileAccess = true
it.setAppCacheEnabled(true)
it.cacheMode
}
webView.loadUrl(url)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_terminal)
maskView.setOnClickListener { showKeyExt(false) }
fixationKeys = listOf(keyEsc, keyCtrl, keyAlt, keyTab, keyMore)
val fixationItems = listOf(KeyItem.ESC, KeyItem.CTRL, KeyItem.ALT, KeyItem.TAB, KeyItem.MORE)
val action: (Pair<View, KeyItem>) -> Unit = {
val view = it.first
view.setTag(it.second)
if ((view is TextView)) {
view.setText(it.second.text)
} else if ((view is ImageView)) {
view.setImageResource(it.second.icon)
}
if (view == keyMore) {
view.setOnClickListener { showKeyExt(maskView.visibility != View.VISIBLE) }
} else {
view.setOnClickListener(clickKeyButton)
}
}
fixationKeys.zip(fixationItems).forEach(action)
initKeyExt()
initWebView()
edit.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
Logger.d("CKEY ww ");
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
Logger.d("CKEY ww ");
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Logger.d("CKEY ww ");
}
})
}
private fun initWebView() {
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (view != null && url != null) {
loadUrl(url)
return true
}
return false
}
}
loadUrl("http://ide.test:8060")
}
private fun initKeyExt() {
val first = listOf(KeyItem.SLASH, KeyItem.MINUS, KeyItem.VER_LINE, KeyItem.AT)
val second = listOf(KeyItem.WAVY_LINE, KeyItem.POINT, KeyItem.COLON, KeyItem.SEMICOLON)
val third = listOf(KeyItem.UP, KeyItem.DOWN, KeyItem.LEFT, KeyItem.RIGHT)
val inflater = LayoutInflater.from(this)
listOf(first, second, third).forEach { lineIt ->
val lineLayout = LinearLayout(this)
layoutExt.addView(lineLayout)
val radioButton = inflater.inflate(R.layout.key_ext_image_item, lineLayout, false)
radioButton.setBackgroundResource(R.mipmap.key_radio_normal)
lastSelectRadio = radioButton
lineLayout.addView(radioButton)
val lineButtons = arrayListOf<View>()
lineIt.forEach {
val itemView = inflater.inflate(R.layout.key_ext_item, lineLayout, false) as TextView
itemView.setTag(it)
itemView.setOnClickListener(clickKeyButton)
itemView.text = it.text
lineLayout.addView(itemView)
lineButtons.add(itemView)
}
radioButton.tag = lineButtons
radioButton.setOnClickListener {
lastSelectRadio.radioSelect(false)
lastSelectRadio = it
lastSelectRadio.radioSelect(true)
}
}
lastSelectRadio.performClick()
maskView.performClick()
}
fun showKeyExt(show: Boolean) {
val visable = if (show) View.VISIBLE else View.GONE
maskView.visibility = visable
layoutExt.visibility = visable
}
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
Logger.d("CKEY" + event)
return super.dispatchKeyEvent(event)
}
override fun dispatchKeyShortcutEvent(event: KeyEvent?): Boolean {
Logger.d("CKEY" + event)
return super.dispatchKeyShortcutEvent(event)
}
override fun dispatchGenericMotionEvent(ev: MotionEvent?): Boolean {
Logger.d("CKEY" + ev)
return super.dispatchGenericMotionEvent(ev)
}
override fun dispatchTrackballEvent(ev: MotionEvent?): Boolean {
Logger.d("CKEY" + ev)
return super.dispatchTrackballEvent(ev)
}
fun View.radioSelect(select: Boolean) {
val radioBg = if (select) R.mipmap.key_radio_select else R.mipmap.key_radio_normal
val keyBg = if (select) colorSelectExt else colorNormal
this.setBackgroundResource(radioBg)
val tag = this.tag
if (tag is ArrayList<*>) {
layoutSwitch.removeAllViews()
val inflater = LayoutInflater.from(context)
tag.forEach {
if (it is View) {
it.setBackgroundColor(keyBg)
val keyItem = it.tag
if (keyItem is KeyItem) {
val button = inflater.inflate(R.layout.key_item_text, layoutSwitch, false)
button.setTag(keyItem)
if (button is TextView) {
button.setText(keyItem.text)
}
layoutSwitch.addView(button)
button.setOnClickListener(clickKeyButton)
}
}
}
}
}
}
| mit | f0ed5527fd455ce94fb355c307034063 | 32.760504 | 101 | 0.566273 | 4.875607 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/enums/CategoryLayoutType.kt | 1 | 695 | package ch.rmy.android.http_shortcuts.data.enums
enum class CategoryLayoutType(
val type: String,
val supportsHorizontalDragging: Boolean = false,
val legacyAlias: String? = null,
) {
LINEAR_LIST("linear_list"),
DENSE_GRID("dense_grid", supportsHorizontalDragging = true, legacyAlias = "grid"),
MEDIUM_GRID("medium_grid", supportsHorizontalDragging = true),
WIDE_GRID("wide_grid", supportsHorizontalDragging = true);
override fun toString() =
type
companion object {
fun parse(type: String?) =
values().firstOrNull { it.type == type || (it.legacyAlias != null && it.legacyAlias == type) }
?: LINEAR_LIST
}
}
| mit | 7861d7bf3606216c5bdea41b2842ddcb | 32.095238 | 106 | 0.65036 | 4.136905 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDirectiveFix.kt | 3 | 3077 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl.quickfix
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
abstract class AddModuleDirectiveFix(module: PsiJavaModule) : LocalQuickFixAndIntentionActionOnPsiElement(module) {
override fun getFamilyName() = QuickFixBundle.message("module.info.add.directive.family.name")
override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) =
startElement is PsiJavaModule && PsiUtil.isLanguageLevel9OrHigher(file) && startElement.getManager().isInProject(startElement)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) =
invoke(project, file, editor, startElement as PsiJavaModule)
protected abstract fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule)
}
class AddRequiresDirectiveFix(module: PsiJavaModule, private val requiredName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.requires.name", requiredName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
if (module.requires.find { requiredName == it.moduleName } == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.REQUIRES + ' ' + requiredName)
}
}
}
class AddExportsDirectiveFix(module: PsiJavaModule,
private val packageName: String,
private val targetName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.exports.name", packageName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
val existing = module.exports.find { packageName == it.packageName }
if (existing == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.EXPORTS + ' ' + packageName)
}
else if (!targetName.isEmpty()) {
val targets = existing.moduleReferences.map { it.referenceText }
if (!targets.isEmpty() && targetName !in targets) {
existing.add(PsiElementFactory.SERVICE.getInstance(project).createModuleReferenceFromText(targetName))
}
}
}
}
class AddUsesDirectiveFix(module: PsiJavaModule, private val svcName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.uses.name", svcName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
if (module.uses.find { svcName == it.classReference?.qualifiedName } == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.USES + ' ' + svcName)
}
}
} | apache-2.0 | 4185cc61edab5f77b72588ef131db288 | 50.3 | 140 | 0.749431 | 4.592537 | false | false | false | false |
jameshnsears/brexitsoundboard | app/src/androidTest/java/com/github/jameshnsears/brexitsoundboard/espresso/DavidTest.kt | 1 | 2894 | package com.github.jameshnsears.brexitsoundboard.espresso
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.matcher.ViewMatchers.withContentDescription
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.rule.ActivityTestRule
import com.github.jameshnsears.brexitsoundboard.ActivityBrexitSoundboard
import com.github.jameshnsears.brexitsoundboard.R
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4ClassRunner::class)
class DavidTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(ActivityBrexitSoundboard::class.java)
@Test
fun davidTest() {
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
Thread.sleep(1000)
val appCompatImageButton = onView(
allOf(
withId(R.id.imageButtonDavid00),
withContentDescription("David Davis"),
childAtPosition(
childAtPosition(
withId(R.id.linearLayout),
3
),
0
)
)
)
appCompatImageButton.perform(scrollTo(), click())
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
Thread.sleep(1000)
pressBack()
}
private fun childAtPosition(
parentMatcher: Matcher<View>,
position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent) &&
view == parent.getChildAt(position)
}
}
}
}
| apache-2.0 | 490b05f7c6f84b6eeee2482fdc03ebed | 35.175 | 108 | 0.680719 | 5.015598 | false | true | false | false |
sksamuel/ktest | kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/JUnitTestRunnerListenerTest.kt | 1 | 3014 | package com.sksamuel.kotest.runner.junit5
import io.kotest.core.sourceRef
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.toDescription
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestType
import io.kotest.engine.toTestResult
import io.kotest.matchers.shouldBe
import io.kotest.runner.junit.platform.JUnitTestEngineListener
import io.kotest.runner.junit.platform.KotestEngineDescriptor
import org.junit.platform.engine.EngineExecutionListener
import org.junit.platform.engine.TestDescriptor
import org.junit.platform.engine.TestExecutionResult
import org.junit.platform.engine.UniqueId
import org.junit.platform.engine.reporting.ReportEntry
class JUnitTestRunnerListenerTests : FunSpec({
test("a bad test should fail test but not parent or spec") {
val root = KotestEngineDescriptor(
UniqueId.forEngine("kotest"),
emptyList(),
emptyList(),
emptyList(),
null,
)
val finished = mutableMapOf<String, TestExecutionResult.Status>()
val engineListener = object : EngineExecutionListener {
override fun executionFinished(testDescriptor: TestDescriptor, testExecutionResult: TestExecutionResult) {
finished[testDescriptor.displayName] = testExecutionResult.status
}
override fun reportingEntryPublished(testDescriptor: TestDescriptor?, entry: ReportEntry?) {}
override fun executionSkipped(testDescriptor: TestDescriptor?, reason: String?) {}
override fun executionStarted(testDescriptor: TestDescriptor?) {}
override fun dynamicTestRegistered(testDescriptor: TestDescriptor?) {}
}
val test1 = TestCase(
JUnitTestRunnerListenerTests::class.toDescription().appendTest("test1"),
JUnitTestRunnerListenerTests(),
{ },
sourceRef(),
TestType.Container,
parent = null,
)
val test2 = TestCase(
test1.description.appendTest("test2"),
JUnitTestRunnerListenerTests(),
{ },
sourceRef(),
TestType.Container,
parent = null,
)
val listener = JUnitTestEngineListener(engineListener, root)
listener.engineStarted(emptyList())
listener.specStarted(JUnitTestRunnerListenerTests::class)
listener.testStarted(test1)
listener.testStarted(test2)
listener.testFinished(test2, toTestResult(AssertionError("boom"), 0))
listener.testFinished(test1, TestResult.success(0))
listener.specFinished(JUnitTestRunnerListenerTests::class, null, emptyMap())
listener.engineFinished(emptyList())
finished.toMap() shouldBe mapOf(
"test2" to TestExecutionResult.Status.FAILED,
"test1" to TestExecutionResult.Status.SUCCESSFUL,
"com.sksamuel.kotest.runner.junit5.JUnitTestRunnerListenerTests" to TestExecutionResult.Status.SUCCESSFUL,
"Kotest" to TestExecutionResult.Status.SUCCESSFUL
)
}
})
| mit | 1dfa836856140e42b1a807d9a9e9f95c | 36.675 | 115 | 0.720637 | 4.908795 | false | true | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/solver/query/result/DataSourceFactoryQueryResultBinder.kt | 1 | 2963 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.query.result
import androidx.room.ext.L
import androidx.room.ext.PagingTypeNames
import androidx.room.ext.typeName
import androidx.room.solver.CodeGenScope
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier
class DataSourceFactoryQueryResultBinder(
val positionalDataSourceQueryResultBinder: PositionalDataSourceQueryResultBinder)
: QueryResultBinder(positionalDataSourceQueryResultBinder.listAdapter) {
@Suppress("HasPlatformType")
val typeName = positionalDataSourceQueryResultBinder.itemTypeName
override fun convertAndReturn(
roomSQLiteQueryVar: String,
canReleaseQuery: Boolean,
dbField: FieldSpec,
inTransaction: Boolean,
scope: CodeGenScope
) {
scope.builder().apply {
val pagedListProvider = TypeSpec
.anonymousClassBuilder("").apply {
superclass(ParameterizedTypeName.get(PagingTypeNames.DATA_SOURCE_FACTORY,
Integer::class.typeName(), typeName))
addMethod(createCreateMethod(
roomSQLiteQueryVar = roomSQLiteQueryVar,
dbField = dbField,
inTransaction = inTransaction,
scope = scope))
}.build()
addStatement("return $L", pagedListProvider)
}
}
private fun createCreateMethod(
roomSQLiteQueryVar: String,
dbField: FieldSpec,
inTransaction: Boolean,
scope: CodeGenScope
): MethodSpec = MethodSpec.methodBuilder("create").apply {
addAnnotation(Override::class.java)
addModifiers(Modifier.PUBLIC)
returns(positionalDataSourceQueryResultBinder.typeName)
val countedBinderScope = scope.fork()
positionalDataSourceQueryResultBinder.convertAndReturn(
roomSQLiteQueryVar = roomSQLiteQueryVar,
canReleaseQuery = true,
dbField = dbField,
inTransaction = inTransaction,
scope = countedBinderScope)
addCode(countedBinderScope.builder().build())
}.build()
}
| apache-2.0 | faf5cc864dd974388d494c21d4ecbcf0 | 39.040541 | 89 | 0.677354 | 5.622391 | false | false | false | false |
intrigus/jtransc | jtransc-gen-js/src/com/jtransc/gen/js/JsTarget.kt | 1 | 19056 | package com.jtransc.gen.js
import com.jtransc.ConfigOutputFile
import com.jtransc.ConfigTargetDirectory
import com.jtransc.annotation.JTranscCustomMainList
import com.jtransc.ast.*
import com.jtransc.ast.feature.method.SwitchFeature
import com.jtransc.ds.Allocator
import com.jtransc.ds.getOrPut2
import com.jtransc.error.invalidOp
import com.jtransc.gen.GenTargetDescriptor
import com.jtransc.gen.TargetBuildTarget
import com.jtransc.gen.common.*
import com.jtransc.injector.Injector
import com.jtransc.injector.Singleton
import com.jtransc.io.ProcessResult2
import com.jtransc.log.log
import com.jtransc.sourcemaps.Sourcemaps
import com.jtransc.text.Indenter
import com.jtransc.text.Indenter.Companion
import com.jtransc.text.isLetterDigitOrUnderscore
import com.jtransc.text.quote
import com.jtransc.vfs.ExecOptions
import com.jtransc.vfs.LocalVfs
import com.jtransc.vfs.LocalVfsEnsureDirs
import com.jtransc.vfs.SyncVfsFile
import java.io.File
import java.util.*
class JsTarget() : GenTargetDescriptor() {
override val priority = 500
override val name = "js"
override val longName = "Javascript"
override val outputExtension = "js"
override val extraLibraries = listOf<String>()
override val extraClasses = listOf<String>()
override val runningAvailable: Boolean = true
override val buildTargets: List<TargetBuildTarget> = listOf(
TargetBuildTarget("js", "js", "program.js", minimizeNames = true),
TargetBuildTarget("plainJs", "js", "program.js", minimizeNames = true)
)
override fun getGenerator(injector: Injector): CommonGenerator {
val settings = injector.get<AstBuildSettings>()
val configTargetDirectory = injector.get<ConfigTargetDirectory>()
val configOutputFile = injector.get<ConfigOutputFile>()
val targetFolder = LocalVfsEnsureDirs(File("${configTargetDirectory.targetDirectory}/jtransc-js"))
injector.mapInstance(CommonGenFolders(settings.assets.map { LocalVfs(it) }))
injector.mapInstance(ConfigTargetFolder(targetFolder))
injector.mapInstance(ConfigSrcFolder(targetFolder))
injector.mapInstance(ConfigOutputFile2(targetFolder[configOutputFile.outputFileBaseName].realfile))
injector.mapImpl<IProgramTemplate, IProgramTemplate>()
return injector.get<JsGenerator>()
}
override fun getTargetByExtension(ext: String): String? = when (ext) {
"js" -> "js"
else -> null
}
}
data class ConfigJavascriptOutput(val javascriptOutput: SyncVfsFile)
fun hasSpecialChars(name: String): Boolean = !name.all(Char::isLetterDigitOrUnderscore)
@Suppress("ConvertLambdaToReference")
@Singleton
class JsGenerator(injector: Injector) : CommonGenerator(injector) {
override val SINGLE_FILE: Boolean = true
override val ADD_UTF8_BOM = true
override val GENERATE_LINE_NUMBERS = false
override val methodFeatures = super.methodFeatures + setOf(SwitchFeature::class.java)
override val keywords = super.keywords + setOf("name", "constructor", "prototype", "__proto__", "G", "N", "S", "SS", "IO")
override val stringPoolType = StringPool.Type.GLOBAL
override val floatHasFSuffix: Boolean = false
override fun compileAndRun(redirect: Boolean): ProcessResult2 = _compileRun(run = true, redirect = redirect)
override fun compile(): ProcessResult2 = _compileRun(run = false, redirect = false)
private fun commonAccess(name: String, field: Boolean): String = if (hasSpecialChars(name)) "[${name.quote()}]" else ".$name"
override fun staticAccess(name: String, field: Boolean): String = commonAccess(name, field)
override fun instanceAccess(name: String, field: Boolean): String = commonAccess(name, field)
val jsOutputFile by lazy { injector.get<ConfigJavascriptOutput>().javascriptOutput }
fun _compileRun(run: Boolean, redirect: Boolean): ProcessResult2 {
log.info("Generated javascript at..." + jsOutputFile.realpathOS)
if (run) {
val result = CommonGenCliCommands.runProgramCmd(
program,
target = "js",
default = listOf("node", "{{ outputFile }}"),
template = this,
options = ExecOptions(passthru = redirect)
)
return ProcessResult2(result)
} else {
return ProcessResult2(0)
}
}
override fun run(redirect: Boolean): ProcessResult2 = ProcessResult2(0)
@Suppress("UNCHECKED_CAST")
override fun writeClasses(output: SyncVfsFile) {
val concatFilesTrans = copyFiles(output)
val classesIndenter = arrayListOf<Indenter>()
classesIndenter += genSingleFileClassesWithoutAppends(output)
val SHOW_SIZE_REPORT = true
if (SHOW_SIZE_REPORT) {
for ((clazz, text) in indenterPerClass.toList().map { it.first to it.second.toString() }.sortedBy { it.second.length }) {
log.info("CLASS SIZE: ${clazz.fqname} : ${text.length}")
}
}
val mainClassFq = program.entrypoint
val mainClass = mainClassFq.targetClassFqName
//val mainMethod = program[mainClassFq].getMethod("main", AstType.build { METHOD(VOID, ARRAY(STRING)) }.desc)!!.jsName
val mainMethod = "main"
entryPointClass = FqName(mainClassFq.fqname + "_EntryPoint")
entryPointFilePath = entryPointClass.targetFilePath
val entryPointFqName = entryPointClass.targetGeneratedFqName
val entryPointSimpleName = entryPointClass.targetSimpleName
val entryPointPackage = entryPointFqName.packagePath
val customMain = program.allAnnotationsList.getTypedList(JTranscCustomMainList::value).firstOrNull { it.target == "js" }?.value
log("Using ... " + if (customMain != null) "customMain" else "plainMain")
setExtraData(mapOf(
"entryPointPackage" to entryPointPackage,
"entryPointSimpleName" to entryPointSimpleName,
"mainClass" to mainClass,
"mainClass2" to mainClassFq.fqname,
"mainMethod" to mainMethod
))
val strs = Indenter {
val strs = getGlobalStrings()
val maxId = strs.maxBy { it.id }?.id ?: 0
line("SS = new Array($maxId);")
for (e in strs) line("SS[${e.id}] = ${e.str.quote()};")
}
val out = Indenter {
if (settings.debug) line("//# sourceMappingURL=$outputFileBaseName.map")
line(concatFilesTrans.prepend)
line(strs.toString())
for (indent in classesIndenter) line(indent)
val mainClassClass = program[mainClassFq]
line("__createJavaArrays();")
line("__buildStrings();")
line("N.linit();")
line(genStaticConstructorsSorted())
//line(buildStaticInit(mainClassFq))
val mainMethod2 = mainClassClass[AstMethodRef(mainClassFq, "main", AstType.METHOD(AstType.VOID, listOf(ARRAY(AstType.STRING))))]
val mainCall = buildMethod(mainMethod2, static = true)
line("try {")
indent {
line("$mainCall(N.strArray(N.args()));")
}
line("} catch (e) {")
indent {
line("console.error(e);")
line("console.error(e.stack);")
}
line("}")
line(concatFilesTrans.append)
}
val sources = Allocator<String>()
val mappings = hashMapOf<Int, Sourcemaps.MappingItem>()
val source = out.toString { sb, line, data ->
if (settings.debug && data is AstStm.LINE) {
//println("MARKER: ${sb.length}, $line, $data, ${clazz.source}")
mappings[line] = Sourcemaps.MappingItem(
sourceIndex = sources.allocateOnce(data.file),
sourceLine = data.line,
sourceColumn = 0,
targetColumn = 0
)
//clazzName.internalFqname + ".java"
}
}
val sourceMap = if (settings.debug) Sourcemaps.encodeFile(sources.array, mappings) else null
// Generate source
//println("outputFileBaseName:$outputFileBaseName")
output[outputFileBaseName] = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + source.toByteArray(Charsets.UTF_8)
if (sourceMap != null) output[outputFileBaseName + ".map"] = sourceMap
injector.mapInstance(ConfigJavascriptOutput(output[outputFile]))
}
override fun genStmTryCatch(stm: AstStm.TRY_CATCH) = indent {
line("try") {
line(stm.trystm.genStm())
}
line("catch (J__i__exception__)") {
//line("J__exception__ = J__i__exception__.native || J__i__exception__;")
line("J__exception__ = J__i__exception__.javaThrowable || J__i__exception__;")
line(stm.catch.genStm())
}
}
override fun genStmRethrow(stm: AstStm.RETHROW, last: Boolean) = indent { line("throw J__i__exception__;") }
override fun genBodyLocals(locals: List<AstLocal>) = indent {
if (locals.isNotEmpty()) {
val vars = locals.map { local -> "${local.targetName} = ${local.type.nativeDefaultString}" }.joinToString(", ")
line("var $vars;")
}
}
override val AstLocal.decl: String get() = "var ${this.targetName} = ${this.type.nativeDefaultString};"
override fun genBodyTrapsPrefix() = indent { line("var J__exception__ = null;") }
override fun genBodyStaticInitPrefix(clazzRef: AstType.REF, reasons: ArrayList<String>) = indent {
line(buildStaticInit(clazzRef.name))
}
override fun N_AGET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String) = "($array.data[$index])"
override fun N_ASET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String, value: String) = "$array.data[$index] = $value;"
override fun N_is(a: String, b: AstType.Reference): String {
return when (b) {
is AstType.REF -> {
val clazz = program[b]!!
if (clazz.isInterface) {
"N.isClassId($a, ${clazz.classId})"
} else {
"($a instanceof ${b.targetName})"
}
}
else -> {
super.N_is(a, b)
}
}
}
override fun N_is(a: String, b: String) = "N.is($a, $b)"
override fun N_z2i(str: String) = "N.z2i($str)"
override fun N_i(str: String) = "(($str)|0)"
override fun N_i2z(str: String) = "(($str)!=0)"
override fun N_i2b(str: String) = "(($str)<<24>>24)" // shifts use 32-bit integers
override fun N_i2c(str: String) = "(($str)&0xFFFF)"
override fun N_i2s(str: String) = "(($str)<<16>>16)" // shifts use 32-bit integers
override fun N_f2i(str: String) = "(($str)|0)"
override fun N_i2i(str: String) = N_i(str)
override fun N_i2j(str: String) = "N.i2j($str)"
override fun N_i2f(str: String) = "Math.fround(+($str))"
override fun N_i2d(str: String) = "+($str)"
override fun N_f2f(str: String) = "Math.fround($str)"
override fun N_f2d(str: String) = "($str)"
override fun N_d2f(str: String) = "Math.fround(+($str))"
override fun N_d2i(str: String) = "(($str)|0)"
override fun N_d2d(str: String) = "+($str)"
override fun N_j2i(str: String) = "N.j2i($str)"
override fun N_j2j(str: String) = str
override fun N_j2f(str: String) = "Math.fround(N.j2d($str))"
override fun N_j2d(str: String) = "N.j2d($str)"
override fun N_getFunction(str: String) = "N.getFunction($str)"
override fun N_c(str: String, from: AstType, to: AstType) = "($str)"
override fun N_ineg(str: String) = "-($str)"
override fun N_iinv(str: String) = "~($str)"
override fun N_fneg(str: String) = "-($str)"
override fun N_dneg(str: String) = "-($str)"
override fun N_znot(str: String) = "!($str)"
override fun N_imul(l: String, r: String): String = "Math.imul($l, $r)"
override val String.escapeString: String get() = "S[" + allocString(context.clazz.name, this) + "]"
override fun genExprCallBaseSuper(e2: AstExpr.CALL_SUPER, clazz: AstType.REF, refMethodClass: AstClass, method: AstMethodRef, methodAccess: String, args: List<String>): String {
val superMethod = refMethodClass[method.withoutClass] ?: invalidOp("Can't find super for method : $method")
val base = superMethod.containingClass.name.targetName + ".prototype"
val argsString = (listOf(e2.obj.genExpr()) + args).joinToString(", ")
return "$base$methodAccess.call($argsString)"
}
private fun AstMethod.getJsNativeBodies(): Map<String, Indenter> = this.getNativeBodies(target = "js")
override fun genClass(clazz: AstClass): List<ClassResult> {
setCurrentClass(clazz)
val isAbstract = (clazz.classType == AstClassType.ABSTRACT)
refs._usedDependencies.clear()
if (!clazz.extending?.fqname.isNullOrEmpty()) refs.add(AstType.REF(clazz.extending!!))
for (impl in clazz.implementing) refs.add(AstType.REF(impl))
val classCodeIndenter = Indenter {
if (isAbstract) line("// ABSTRACT")
val classBase = clazz.name.targetName
val memberBaseStatic = classBase
val memberBaseInstance = "$classBase.prototype"
fun getMemberBase(isStatic: Boolean) = if (isStatic) memberBaseStatic else memberBaseInstance
val parentClassBase = if (clazz.extending != null) clazz.extending!!.targetName else "java_lang_Object_base";
val staticFields = clazz.fields.filter { it.isStatic }
//val instanceFields = clazz.fields.filter { !it.isStatic }
val allInstanceFields = (listOf(clazz) + clazz.parentClassList).flatMap { it.fields }.filter { !it.isStatic }
fun lateInitField(a: Any?) = (a is String)
val allInstanceFieldsThis = allInstanceFields.filter { lateInitField(it) }
val allInstanceFieldsProto = allInstanceFields.filter { !lateInitField(it) }
line("function $classBase()") {
for (field in allInstanceFieldsThis) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("this${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
}
line("$classBase.prototype = Object.create($parentClassBase.prototype);")
line("$classBase.prototype.constructor = $classBase;")
for (field in allInstanceFieldsProto) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("$classBase.prototype${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
// @TODO: Move to genSIMethodBody
//if (staticFields.isNotEmpty() || clazz.staticConstructor != null) {
// line("$classBase.SI = function()", after2 = ";") {
// line("$classBase.SI = N.EMPTY_FUNCTION;")
// for (field in staticFields) {
// val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
// line("${getMemberBase(field.isStatic)}${accessStr(nativeMemberName)} = ${field.escapedConstantValue};")
// }
// if (clazz.staticConstructor != null) {
// line("$classBase${getTargetMethodAccess(clazz.staticConstructor!!, true)}();")
// }
// }
//} else {
// line("$classBase.SI = N.EMPTY_FUNCTION;")
//}
//line("$classBase.SI = N.EMPTY_FUNCTION;")
if (staticFields.isNotEmpty() || clazz.staticConstructor != null) {
line("$classBase.SI = function()", after2 = ";") {
//line("$classBase.SI = N.EMPTY_FUNCTION;")
for (field in staticFields) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("${getMemberBase(field.isStatic)}${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
if (clazz.staticConstructor != null) {
line("$classBase${getTargetMethodAccess(clazz.staticConstructor!!, true)}();")
}
}
} else {
line("$classBase.SI = function(){};")
}
val relatedTypesIds = (clazz.getAllRelatedTypes() + listOf(JAVA_LANG_OBJECT_CLASS)).toSet().map { it.classId }
line("$classBase.prototype.__JT__CLASS_ID = $classBase.__JT__CLASS_ID = ${clazz.classId};")
line("$classBase.prototype.__JT__CLASS_IDS = $classBase.__JT__CLASS_IDS = [${relatedTypesIds.joinToString(",")}];")
//renderFields(clazz.fields);
fun writeMethod(method: AstMethod): Indenter {
setCurrentMethod(method)
return Indenter {
refs.add(method.methodType)
val margs = method.methodType.args.map { it.name }
//val defaultMethodName = if (method.isInstanceInit) "${method.ref.classRef.fqname}${method.name}${method.desc}" else "${method.name}${method.desc}"
//val methodName = if (method.targetName == defaultMethodName) null else method.targetName
val nativeMemberName = buildMethod(method, false, includeDot = false)
val prefix = "${getMemberBase(method.isStatic)}${instanceAccess(nativeMemberName, field = false)}"
val rbody = if (method.body != null) method.body else if (method.bodyRef != null) program[method.bodyRef!!]?.body else null
fun renderBranch(actualBody: Indenter?) = Indenter {
if (actualBody != null) {
line("$prefix = function(${margs.joinToString(", ")})", after2 = ";") {
line(actualBody)
if (method.methodVoidReturnThis) line("return this;")
}
} else {
line("$prefix = function() { N.methodWithoutBody('${clazz.name}.${method.name}') };")
}
}
fun renderBranches() = Indenter {
try {
val nativeBodies = method.getJsNativeBodies()
var javaBodyCacheDone: Boolean = false
var javaBodyCache: Indenter? = null
fun javaBody(): Indenter? {
if (!javaBodyCacheDone) {
javaBodyCacheDone = true
javaBodyCache = rbody?.genBodyWithFeatures(method)
}
return javaBodyCache
}
//val javaBody by lazy { }
// @TODO: Do not hardcode this!
if (nativeBodies.isEmpty() && javaBody() == null) {
line(renderBranch(null))
} else {
if (nativeBodies.isNotEmpty()) {
val default = if ("" in nativeBodies) nativeBodies[""]!! else javaBody() ?: Indenter.EMPTY
val options = nativeBodies.filter { it.key != "" }.map { it.key to it.value } + listOf("" to default)
if (options.size == 1) {
line(renderBranch(default))
} else {
for (opt in options.withIndex()) {
if (opt.index != options.size - 1) {
val iftype = if (opt.index == 0) "if" else "else if"
line("$iftype (${opt.value.first})") { line(renderBranch(opt.value.second)) }
} else {
line("else") { line(renderBranch(opt.value.second)) }
}
}
}
//line(nativeBodies ?: javaBody ?: Indenter.EMPTY)
} else {
line(renderBranch(javaBody()))
}
}
} catch (e: Throwable) {
log.printStackTrace(e)
log.warn("WARNING GenJsGen.writeMethod:" + e.message)
line("// Errored method: ${clazz.name}.${method.name} :: ${method.desc} :: ${e.message};")
line(renderBranch(null))
}
}
line(renderBranches())
}
}
for (method in clazz.methods.filter { it.isClassOrInstanceInit }) line(writeMethod(method))
for (method in clazz.methods.filter { !it.isClassOrInstanceInit }) line(writeMethod(method))
}
return listOf(ClassResult(SubClass(clazz, MemberTypes.ALL), classCodeIndenter))
}
override fun genStmSetArrayLiterals(stm: AstStm.SET_ARRAY_LITERALS) = Indenter {
line("${stm.array.genExpr()}.setArraySlice(${stm.startIndex}, [${stm.values.map { it.genExpr() }.joinToString(", ")}]);")
}
override fun buildStaticInit(clazzName: FqName): String? = null
override val FqName.targetName: String get() = classNames.getOrPut2(this) { if (minimize) allocClassName() else this.fqname.replace('.', '_') }
override fun cleanMethodName(name: String): String = name
override val AstType.localDeclType: String get() = "var"
override fun genStmThrow(stm: AstStm.THROW, last: Boolean) = Indenter("throw new WrappedError(${stm.exception.genExpr()});")
override fun genExprCastChecked(e: String, from: AstType.Reference, to: AstType.Reference): String {
return "N.checkCast($e, ${to.targetNameRef})"
}
} | apache-2.0 | 23b65bd3ddfe242b1d4be9c602464a72 | 39.375 | 178 | 0.689599 | 3.550587 | false | false | false | false |
sandy-8925/Checklist | app/src/androidTest/java/org/sanpra/checklist/activity/ItemsListFragmentTests.kt | 1 | 8645 | package org.sanpra.checklist.activity
import android.content.Intent
import android.graphics.drawable.Drawable
import android.view.ActionProvider
import android.view.ContextMenu
import android.view.MenuItem
import android.view.SubMenu
import android.view.View
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.apache.commons.collections4.Closure
import org.apache.commons.collections4.IterableUtils
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.sanpra.checklist.R
import org.sanpra.checklist.dbhelper.ChecklistItem
@RunWith(AndroidJUnit4::class)
class ItemsListFragmentTests : BaseTests() {
@Test
fun testDeleteCheckedItemsMenuOption() {
val prefilledItems = ArrayList<ChecklistItem>()
prefilledItems.add(ChecklistItem().apply {
id = 1
description = "Hello world"
isChecked = false
})
prefilledItems.add(ChecklistItem().apply {
id = 2
description = "Testing"
isChecked = true
})
prefilledItems.add(ChecklistItem().apply {
id = 3
description = "Yet again"
isChecked = false
})
mockItemsController.addItems(prefilledItems)
val fragmentScenario = launchFragment(ItemsListFragment::class.java, R.style.AppTheme_ActionBar)
fragmentScenario.onFragment {
it.onOptionsItemSelected(MockMenuItem(R.id.menu_delcheckeditems))
}
Thread.sleep(1000)
val itemCheckStatusClosure = ItemCheckStatusClosure()
IterableUtils.forEach(mockItemsController.listItems(), itemCheckStatusClosure)
Assert.assertFalse(itemCheckStatusClosure.isAnyChecked)
}
}
private class ItemCheckStatusClosure : Closure<ChecklistItem> {
var isAnyChecked : Boolean = false
private set
override fun execute(input: ChecklistItem) {
if(input.isChecked) isAnyChecked = true
}
}
private class MockMenuItem(private val itemId : Int) : MenuItem {
override fun expandActionView(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hasSubMenu(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMenuInfo(): ContextMenu.ContextMenuInfo {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemId(): Int = itemId
override fun getAlphabeticShortcut(): Char {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setEnabled(enabled: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitle(title: CharSequence?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitle(title: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setChecked(checked: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getActionView(): View {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTitle(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getOrder(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIntent(): Intent {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setVisible(visible: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEnabled() = true
override fun isCheckable()= false
override fun setShowAsAction(actionEnum: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getGroupId(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionProvider(actionProvider: ActionProvider?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitleCondensed(title: CharSequence?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getNumericShortcut(): Char {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isActionViewExpanded(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun collapseActionView(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isVisible(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setNumericShortcut(numericChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionView(view: View?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionView(resId: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setAlphabeticShortcut(alphaChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIcon(icon: Drawable?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIcon(iconRes: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isChecked(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIntent(intent: Intent?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIcon(): Drawable {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShowAsActionFlags(actionEnum: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setOnMenuItemClickListener(menuItemClickListener: MenuItem.OnMenuItemClickListener?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getActionProvider(): ActionProvider {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCheckable(checkable: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSubMenu(): SubMenu {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTitleCondensed(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | gpl-3.0 | 50ef1ab6265f2325f17bfa5998f72dc5 | 38.66055 | 113 | 0.692423 | 5.002894 | false | false | false | false |
willjgriff/android-skeleton | app/src/main/java/com/github/willjgriff/skeleton/ui/utils/UiUtils.kt | 1 | 844 | package com.github.willjgriff.skeleton.ui.utils
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
/**
* Created by Will on 15/01/2017.
*/
fun convertDpToPixel(dp: Float, context: Context): Float {
val resources = context.resources
val metrics = resources.displayMetrics
return dp * (metrics.densityDpi / 160f);
}
fun convertPixelsToDp(px: Float, context: Context): Float {
val resources = context.resources
val metrics = resources.displayMetrics
return px / (metrics.densityDpi / 160f)
}
fun hideSoftKeyboard(view: View, context: Context) {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE)
if (inputMethodManager is InputMethodManager) {
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| apache-2.0 | c8bb84c820da023d34e0f8b93d00ca99 | 30.259259 | 83 | 0.753555 | 4.241206 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/search/src/main/java/jp/hazuki/yuzubrowser/search/domain/usecase/SearchViewUseCase.kt | 1 | 3027 | /*
* 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.search.domain.usecase
import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager
import jp.hazuki.yuzubrowser.history.repository.BrowserHistoryManager
import jp.hazuki.yuzubrowser.search.domain.ISearchUrlRepository
import jp.hazuki.yuzubrowser.search.domain.ISuggestRepository
import jp.hazuki.yuzubrowser.search.model.SearchSuggestModel
import jp.hazuki.yuzubrowser.search.model.provider.SearchSuggestProviders
import jp.hazuki.yuzubrowser.ui.utils.isUrl
import java.util.*
internal class SearchViewUseCase(
private val bookmarkManager: BookmarkManager,
private val historyManager: BrowserHistoryManager,
private val suggestRepository: ISuggestRepository,
private val searchUrlRepository: ISearchUrlRepository
) {
var suggestType = 0
fun getSearchQuery(query: String): List<SearchSuggestModel> {
return suggestRepository.getSearchQuery(suggestType, query)
}
fun getHistoryQuery(query: String): List<SearchSuggestModel> {
if (query.isEmpty()) {
return listOf()
}
val histories = historyManager.search(query, 0, 5)
val list = ArrayList<SearchSuggestModel>(histories.size)
histories.forEach {
list.add(SearchSuggestModel.HistoryModel(it.title ?: "", it.url ?: ""))
}
return list
}
fun getBookmarkQuery(query: String): List<SearchSuggestModel> {
if (query.isEmpty()) {
return listOf()
}
val bookmarks = bookmarkManager.search(query)
val list = ArrayList<SearchSuggestModel>(if (bookmarks.size >= 5) 5 else bookmarks.size)
bookmarks.asSequence().take(5).forEach {
list.add(SearchSuggestModel.HistoryModel(it.title!!, it.url))
}
return list
}
fun saveQuery(query: String) {
if (query.isNotEmpty() && !query.isUrl() && suggestType != SUGGEST_TYPE_NONE) {
suggestRepository.insert(suggestType, query)
}
}
fun deleteQuery(query: String) {
suggestRepository.delete(suggestType, query)
}
fun loadSuggestProviders(): SearchSuggestProviders {
return SearchSuggestProviders(searchUrlRepository.load())
}
fun saveSuggestProviders(providers: SearchSuggestProviders) {
searchUrlRepository.save(providers.toSettings())
}
companion object {
private const val SUGGEST_TYPE_NONE = 3
}
}
| apache-2.0 | 267c3f69109010c66dbe7d3d2fc8146f | 33.793103 | 96 | 0.708622 | 4.497771 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/ticket/RPKTicketImpl.kt | 1 | 1782 | /*
* Copyright 2018 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.moderation.bukkit.ticket
import com.rpkit.moderation.bukkit.event.ticket.RPKBukkitTicketCloseEvent
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.Bukkit
import org.bukkit.Location
import java.time.LocalDateTime
class RPKTicketImpl(
override var id: Int = 0,
override val reason: String,
override val issuer: RPKProfile,
override var resolver: RPKProfile?,
override val location: Location?,
override val openDate: LocalDateTime,
override var closeDate: LocalDateTime?,
override var isClosed: Boolean
): RPKTicket {
constructor(reason: String, issuer: RPKProfile, location: Location): this(
0,
reason,
issuer,
null,
location,
LocalDateTime.now(),
null,
false
)
override fun close(resolver: RPKProfile) {
val event = RPKBukkitTicketCloseEvent(resolver, this)
Bukkit.getServer().pluginManager.callEvent(event)
if (event.isCancelled) return
isClosed = true
this.resolver = event.profile
closeDate = LocalDateTime.now()
}
} | apache-2.0 | c1f516077ef94f6df65f8ca8986216e9 | 30.839286 | 78 | 0.680696 | 4.701847 | false | false | false | false |
tadayosi/camel | dsl/camel-kotlin-dsl/src/main/kotlin/org/apache/camel/dsl/kotlin/model/ComponentsConfiguration.kt | 9 | 1857 | /*
* 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 org.apache.camel.dsl.kotlin.model
import org.apache.camel.CamelContext
import org.apache.camel.Component
class ComponentsConfiguration(val context: CamelContext) {
inline fun <reified T : Component> component(name: String, block: T.() -> Unit) : T {
var target = context.getComponent(name, true, false)
var bind = false
if (target != null && !T::class.java.isInstance(target)) {
throw IllegalArgumentException("Type mismatch, expected: ${T::class.java}, got: ${target.javaClass}")
}
// if the component is not found, let's create a new one. This is
// equivalent to create a new named component, useful to create
// multiple instances of the same component but with different setup
if (target == null) {
target = context.injector.newInstance(T::class.java)
bind = true
}
block.invoke(target as T)
if (bind) {
context.registry.bind(name, T::class.java, target)
}
return target
}
} | apache-2.0 | 06acd5ca3778db5011687c4d170f0322 | 38.531915 | 113 | 0.68336 | 4.369412 | false | false | false | false |
alt236/Under-the-Hood---Android | command_runner/src/main/java/uk/co/alt236/underthehood/commandrunner/ExecuteCallable.kt | 1 | 2815 | /*******************************************************************************
* Copyright 2010 Alexandros Schillings
*
* 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 uk.co.alt236.underthehood.commandrunner
import android.content.res.Resources
import android.os.Build
import android.util.Log
import uk.co.alt236.underthehood.commandrunner.groups.*
import uk.co.alt236.underthehood.commandrunner.model.Result
import java.util.concurrent.Callable
internal class ExecuteCallable(res: Resources) : Callable<Result> {
private val commandRunner = Cli()
private val hardwareCommands = HardwareCommands(res)
private val ipRouteCommands = IpRouteCommands(res)
private val netstatCommands = NetstatCommands(res)
private val otherCommands = OtherCommands(res)
private val procCommands = ProcCommands(res)
private val psCommands = PsCommands(res)
private val sysPropCommands = SysPropCommands(res)
private var isRooted = false
override fun call(): Result {
Log.d(TAG, "^ ExecuteThread: Thread Started")
isRooted = commandRunner.checkIfSu()
return try {
return collectResult(isRooted)
} catch (e: Exception) {
Log.e(TAG, "^ ExecuteThread: exception " + e.message)
Result.ERROR
}
}
private fun collectResult(isRooted: Boolean): Result {
val result = Result()
result.isRooted = isRooted
result.timestamp = System.currentTimeMillis()
result.deviceinfo = getDeviceInfo()
result.hardwareData = (hardwareCommands.execute(isRooted))
result.ipRouteData = (ipRouteCommands.execute(isRooted))
result.netstatData = (netstatCommands.execute(isRooted))
result.otherData = (otherCommands.execute(isRooted))
result.procData = (procCommands.execute(isRooted))
result.psData = (psCommands.execute(isRooted))
result.sysPropData = (sysPropCommands.execute(isRooted))
Log.d(TAG, "^ ExecuteThread: Returning result")
return result
}
private fun getDeviceInfo(): String {
return Build.MANUFACTURER + " " + Build.PRODUCT + " " + Build.DEVICE + ", API: ${Build.VERSION.SDK_INT}".trim()
}
companion object {
private val TAG = this::class.java.simpleName
}
} | apache-2.0 | 7b96db4e816fa06b73130b4fdabd9f0e | 36.052632 | 119 | 0.68206 | 4.454114 | false | false | false | false |
justDoji/TrackMeUp | trambu-app/src/main/kotlin/be/doji/productivity/trambuapp/styles/DefaultTrambuStyle.kt | 1 | 2772 | package be.doji.productivity.trambuapp.styles
import javafx.scene.layout.BackgroundPosition
import javafx.scene.text.FontPosture
import javafx.scene.text.FontWeight
import tornadofx.Stylesheet
import tornadofx.c
import tornadofx.cssclass
class DefaultTrambuStyle : Stylesheet() {
companion object {
val todo by cssclass()
val done by cssclass()
val alert by cssclass()
val separatorLabel by cssclass()
val warningLabel by cssclass()
val default by cssclass()
val buttonBold by cssclass()
val activityOverlay by cssclass()
val mainColor = c("#505050")
val defaultTextColor = c("#ffffff")
}
init {
root {
baseColor = mainColor
backgroundColor += c("transparent")
textFill = defaultTextColor
backgroundImage += this.javaClass.classLoader.getResource("images/repeating-pattern-rocks-opace.png").toURI()
backgroundPosition += BackgroundPosition.CENTER
}
todo {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#3598c1")
baseColor = c("#3598c1")
separatorLabel {
textFill = c("#820d98")
}
}
activityOverlay {
baseColor = mainColor
backgroundColor += c("#8598a6")
baseColor = c("#8598a6")
}
done {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#383f38")
baseColor = c("#383f38")
title { fontStyle = FontPosture.ITALIC }
}
alert {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#a8431a")
baseColor = c("#a8431a")
}
separatorLabel {
textFill = c("orange")
}
warningLabel {
textFill = c("#a8431a")
}
default {
baseColor = mainColor
backgroundColor += c(mainColor.toString(), 0.65)
}
splitPane {
backgroundColor += c(mainColor.toString(), 0.65)
}
scrollPane {
backgroundColor += c("transparent")
baseColor = c("transparent")
content {
backgroundColor += c("transparent")
}
}
accordion {
backgroundColor += c("transparent")
titledPane {
content {
backgroundColor += c("transparent")
}
}
}
}
} | mit | bd06a0961a50d517c50ef1152ae2970d | 25.663462 | 121 | 0.541847 | 5.142857 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-dessert-release | app/src/main/java/com/example/dessertrelease/ui/DessertReleaseApp.kt | 1 | 6346 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertrelease.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.dessertrelease.R
import com.example.dessertrelease.data.local.LocalDessertReleaseData
import com.example.dessertrelease.ui.theme.DessertReleaseTheme
/*
* Screen level composable
*/
@Composable
fun DessertReleaseApp(
modifier: Modifier = Modifier,
dessertReleaseViewModel: DessertReleaseViewModel = viewModel(
factory = DessertReleaseViewModel.Factory
)
) {
DessertReleaseApp(
uiState = dessertReleaseViewModel.uiState.collectAsState().value,
selectLayout = dessertReleaseViewModel::selectLayout,
modifier = modifier
)
}
@Composable
private fun DessertReleaseApp(
uiState: DessertReleaseUiState,
selectLayout: (Boolean) -> Unit,
modifier: Modifier = Modifier
) {
val isLinearLayout = uiState.isLinearLayout
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.top_bar_name)) },
actions = {
IconButton(
onClick = {
selectLayout(!isLinearLayout)
}
) {
Icon(
painter = painterResource(uiState.toggleIcon),
contentDescription = stringResource(uiState.toggleContentDescription),
tint = MaterialTheme.colors.onPrimary
)
}
}
)
}
) { innerPadding ->
if (isLinearLayout) {
DessertReleaseLinearLayout(modifier.padding(innerPadding))
} else {
DessertReleaseGridLayout(modifier.padding(innerPadding))
}
}
}
@Composable
fun DessertReleaseLinearLayout(modifier: Modifier = Modifier) {
LazyColumn(
modifier = modifier.fillMaxWidth(),
contentPadding = PaddingValues(vertical = 16.dp, horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(
items = LocalDessertReleaseData.dessertReleases.toList(),
key = { dessert -> dessert }
) { dessert ->
Card(
backgroundColor = MaterialTheme.colors.primary,
shape = MaterialTheme.shapes.small
) {
Text(
text = dessert,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center
)
}
}
}
}
@Composable
fun DessertReleaseGridLayout(modifier: Modifier = Modifier) {
LazyVerticalGrid(
modifier = modifier,
columns = GridCells.Fixed(3),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
items(
items = LocalDessertReleaseData.dessertReleases,
key = { dessert -> dessert }
) { dessert ->
Card(
backgroundColor = MaterialTheme.colors.primary,
modifier = Modifier.height(110.dp),
shape = MaterialTheme.shapes.medium
) {
Text(
text = dessert,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxHeight()
.wrapContentHeight(Alignment.CenterVertically)
.padding(8.dp),
textAlign = TextAlign.Center
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DessertReleaseLinearLayoutPreview() {
DessertReleaseTheme {
DessertReleaseLinearLayout()
}
}
@Preview(showBackground = true)
@Composable
fun DessertReleaseGridLayoutPreview() {
DessertReleaseTheme {
DessertReleaseGridLayout()
}
}
@Preview
@Composable
fun DessertReleaseAppPreview() {
DessertReleaseTheme {
DessertReleaseApp(
uiState = DessertReleaseUiState(),
selectLayout = {}
)
}
}
| apache-2.0 | a8755de2dc95291f590a9283b823de51 | 32.225131 | 98 | 0.648598 | 5.197379 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/utils/PagedListMock.kt | 5 | 2453 | package fr.free.nrw.commons.utils
import android.database.Cursor
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import androidx.room.InvalidationTracker
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.paging.LimitOffsetDataSource
import com.nhaarman.mockitokotlin2.whenever
import org.mockito.Mockito.mock
fun <T> List<T>.asPagedList(config: PagedList.Config? = null): LiveData<PagedList<T>> {
val defaultConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(size)
.setMaxSize(size + 2)
.setPrefetchDistance(1)
.build()
return LivePagedListBuilder<Int, T>(
createMockDataSourceFactory(this),
config ?: defaultConfig
).build()
}
/**
* Provides a mocked instance of the data source factory
*/
fun <T> createMockDataSourceFactory(itemList: List<T>): DataSource.Factory<Int, T> =
object : DataSource.Factory<Int, T>() {
override fun create(): DataSource<Int, T> = MockLimitDataSource(itemList)
}
/**
* Provides a mocked Room SQL query
*/
private fun mockQuery(): RoomSQLiteQuery {
val query = mock(RoomSQLiteQuery::class.java);
whenever(query.sql).thenReturn("");
return query;
}
/**
* Provides a mocked Room DB
*/
private fun mockDb(): RoomDatabase {
val roomDatabase = mock(RoomDatabase::class.java);
val invalidationTracker = mock(InvalidationTracker::class.java)
whenever(roomDatabase.invalidationTracker).thenReturn(invalidationTracker);
return roomDatabase;
}
/**
* Class that defines the mocked data source
*/
class MockLimitDataSource<T>(private val itemList: List<T>) :
LimitOffsetDataSource<T>(mockDb(), mockQuery(), false, "") {
override fun convertRows(cursor: Cursor): MutableList<T> {
return itemList.toMutableList()
}
override fun countItems(): Int = itemList.count()
override fun isInvalid(): Boolean = false
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) {
}
override fun loadRange(startPosition: Int, loadCount: Int): MutableList<T> {
return itemList.subList(startPosition, startPosition + loadCount).toMutableList()
}
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) {
callback.onResult(itemList, 0)
}
} | apache-2.0 | 265118ea25600e41d89c208c7940e818 | 31.289474 | 91 | 0.726457 | 4.435805 | false | true | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/ProductionBar.kt | 1 | 2783 | package org.luxons.sevenwonders.ui.components.game
import kotlinx.css.*
import kotlinx.css.properties.borderTop
import kotlinx.css.properties.boxShadow
import kotlinx.html.DIV
import org.luxons.sevenwonders.model.boards.Production
import org.luxons.sevenwonders.model.resources.CountedResource
import org.luxons.sevenwonders.model.resources.ResourceType
import react.RBuilder
import react.dom.key
import styled.StyledDOMBuilder
import styled.css
import styled.styledDiv
import styled.styledSpan
fun RBuilder.productionBar(gold: Int, production: Production) {
styledDiv {
css {
productionBarStyle()
}
goldIndicator(gold)
fixedResources(production.fixedResources)
alternativeResources(production.alternativeResources)
}
}
private fun RBuilder.fixedResources(resources: List<CountedResource>) {
styledDiv {
css {
margin = "auto"
display = Display.flex
}
resources.forEach {
resourceWithCount(resourceType = it.type, count = it.count, imgSize = 3.rem) {
attrs { key = it.type.toString() }
css { marginLeft = 1.rem }
}
}
}
}
private fun RBuilder.alternativeResources(resources: List<Set<ResourceType>>) {
styledDiv {
css {
margin = "auto"
display = Display.flex
}
resources.forEachIndexed { index, res ->
resourceChoice(types = res) {
attrs {
key = index.toString()
}
}
}
}
}
private fun RBuilder.resourceChoice(types: Set<ResourceType>, block: StyledDOMBuilder<DIV>.() -> Unit = {}) {
styledDiv {
css {
marginLeft = (1.5).rem
}
block()
for ((i, t) in types.withIndex()) {
resourceImage(resourceType = t, size = 3.rem) {
attrs { this.key = t.toString() }
}
if (i < types.indices.last) {
styledSpan {
css { choiceSeparatorStyle() }
+"/"
}
}
}
}
}
private fun CSSBuilder.productionBarStyle() {
alignItems = Align.center
background = "linear-gradient(#eaeaea, #888 7%)"
bottom = 0.px
borderTop(width = 1.px, color = Color("#8b8b8b"), style = BorderStyle.solid)
boxShadow(blurRadius = 15.px, color = Color("#747474"))
display = Display.flex
height = (3.5).rem
width = 100.vw
position = Position.fixed
zIndex = 99
}
private fun CSSBuilder.choiceSeparatorStyle() {
fontSize = 2.rem
verticalAlign = VerticalAlign.middle
margin(all = 5.px)
color = Color("#c29929")
declarations["text-shadow"] = "0 0 1px black"
}
| mit | 85d36cc4b630525ec6a874bcc506aa4b | 27.397959 | 109 | 0.594682 | 4.274962 | false | false | false | false |
salmans/razor-kotlin | src/main/java/chase/Selectors.kt | 1 | 2432 | package chase
import formula.TRUE
class TopDownSelector<out S : Sequent>(private val sequents: List<S>) : Selector<S> {
override fun iterator(): Iterator<S> = sequents.iterator()
override fun duplicate(): Selector<S> = this // because it always starts from the top, it's stateless and can be shared
}
class FairSelector<S : Sequent>(val sequents: Array<S>) : Selector<S> {
private var index = 0
inner class FairIterator(private val start: Int) : Iterator<S> {
var stop = false
override fun hasNext(): Boolean = !sequents.isEmpty() && (index != start || !stop)
override fun next(): S {
if (!hasNext())
throw NoSuchElementException()
stop = true
val sequent = sequents[index]
index = (index + 1) % sequents.size
return sequent
}
}
override fun iterator(): Iterator<S> = FairIterator(index)
private constructor(selector: FairSelector<S>) : this(selector.sequents) { // the array of sequents can be shared
this.index = index // the index cannot
}
override fun duplicate(): Selector<S> = FairSelector(this)
}
class OptimalSelector<out S : Sequent> : Selector<S> {
inner class OneTimeIterator : Iterator<S> {
override fun hasNext(): Boolean = index < allSequents.first.size
override fun next(): S {
if (!hasNext())
throw NoSuchElementException()
return allSequents.first[index++]
}
}
private val allSequents: Pair<List<S>, List<S>>
private val selector: Selector<S>
private var index: Int
private val iterator: Iterator<S>
constructor(sequents: List<S>, selectorFunction: (sequents: List<S>) -> Selector<S>) {
this.allSequents = sequents.partition { it.body == TRUE && it.head.freeVars.isEmpty() && it.head.freeVars.isEmpty() }
this.selector = selectorFunction(this.allSequents.second)
this.iterator = OneTimeIterator()
index = 0
}
private constructor(selector: OptimalSelector<S>) {
this.allSequents = selector.allSequents
this.selector = selector.selector.duplicate()
this.iterator = OneTimeIterator()
this.index = selector.index
}
override fun iterator(): Iterator<S> = if (iterator.hasNext()) iterator else selector.iterator()
override fun duplicate(): Selector<S> = OptimalSelector(this)
} | bsd-3-clause | 9d3ed08557bc9b233651185df4850e3c | 33.757143 | 125 | 0.63898 | 4.244328 | false | false | false | false |
owntracks/android | project/app/src/main/java/org/owntracks/android/geocoding/GeocoderProvider.kt | 1 | 7004 | package org.owntracks.android.geocoding
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_LOW
import androidx.core.app.NotificationManagerCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.*
import org.owntracks.android.R
import org.owntracks.android.model.messages.MessageLocation
import org.owntracks.android.services.BackgroundService
import org.owntracks.android.support.Preferences
import org.owntracks.android.ui.map.MapActivity
import org.threeten.bp.Instant
import org.threeten.bp.ZoneOffset.UTC
import org.threeten.bp.format.DateTimeFormatter
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GeocoderProvider @Inject constructor(
@ApplicationContext private val context: Context,
private val preferences: Preferences
) {
private val ioDispatcher = Dispatchers.IO
private var lastRateLimitedNotificationTime: Instant? = null
private var notificationManager: NotificationManagerCompat
private var geocoder: Geocoder = GeocoderNone()
private var job: Job? = null
private fun setGeocoderProvider(context: Context, preferences: Preferences) {
Timber.i("Setting geocoding provider to ${preferences.reverseGeocodeProvider}")
job = GlobalScope.launch {
withContext(ioDispatcher) {
geocoder = when (preferences.reverseGeocodeProvider) {
Preferences.REVERSE_GEOCODE_PROVIDER_OPENCAGE -> OpenCageGeocoder(
preferences.openCageGeocoderApiKey
)
Preferences.REVERSE_GEOCODE_PROVIDER_DEVICE -> DeviceGeocoder(context)
else -> GeocoderNone()
}
}
}
}
private suspend fun geocoderResolve(messageLocation: MessageLocation): GeocodeResult {
return withContext(ioDispatcher) {
job?.run { join() }
return@withContext geocoder.reverse(messageLocation.latitude, messageLocation.longitude)
}
}
suspend fun resolve(messageLocation: MessageLocation) {
if (messageLocation.hasGeocode) {
return
}
Timber.d("Resolving geocode for $messageLocation")
val result = geocoderResolve(messageLocation)
messageLocation.geocode = geocodeResultToText(result)
maybeCreateErrorNotification(result)
}
private fun maybeCreateErrorNotification(result: GeocodeResult) {
if (result is GeocodeResult.Formatted || result is GeocodeResult.Empty || !preferences.notificationGeocoderErrors) {
notificationManager.cancel(GEOCODE_ERROR_NOTIFICATION_TAG, 0)
return
}
val errorNotificationText = when (result) {
is GeocodeResult.Fault.Error -> context.getString(
R.string.geocoderError,
result.message
)
is GeocodeResult.Fault.ExceptionError -> context.getString(R.string.geocoderExceptionError)
is GeocodeResult.Fault.Disabled -> context.getString(R.string.geocoderDisabled)
is GeocodeResult.Fault.IPAddressRejected -> context.getString(R.string.geocoderIPAddressRejected)
is GeocodeResult.Fault.RateLimited -> context.getString(
R.string.geocoderRateLimited,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(UTC).format(result.until)
)
is GeocodeResult.Fault.Unavailable -> context.getString(R.string.geocoderUnavailable)
else -> ""
}
val until = when (result) {
is GeocodeResult.Fault -> result.until
else -> Instant.MIN
}
if (until == lastRateLimitedNotificationTime) {
return
} else {
lastRateLimitedNotificationTime = until
}
val activityLaunchIntent = Intent(this.context, MapActivity::class.java)
activityLaunchIntent.action = "android.intent.action.MAIN"
activityLaunchIntent.addCategory("android.intent.category.LAUNCHER")
activityLaunchIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
val notification = NotificationCompat.Builder(context, ERROR_NOTIFICATION_CHANNEL_ID)
.setContentTitle(context.getString(R.string.geocoderProblemNotificationTitle))
.setContentText(errorNotificationText)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_owntracks_80)
.setStyle(NotificationCompat.BigTextStyle().bigText(errorNotificationText))
.setContentIntent(
PendingIntent.getActivity(
context,
0,
activityLaunchIntent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_UPDATE_CURRENT
)
)
.setPriority(PRIORITY_LOW)
.setSilent(true)
.build()
notificationManager.notify(GEOCODE_ERROR_NOTIFICATION_TAG, 0, notification)
}
private fun geocodeResultToText(result: GeocodeResult) =
when (result) {
is GeocodeResult.Formatted -> result.text
else -> null
}
fun resolve(messageLocation: MessageLocation, backgroundService: BackgroundService) {
if (messageLocation.hasGeocode) {
backgroundService.onGeocodingProviderResult(messageLocation)
return
}
MainScope().launch {
val result = geocoderResolve(messageLocation)
messageLocation.geocode = geocodeResultToText(result)
backgroundService.onGeocodingProviderResult(messageLocation)
maybeCreateErrorNotification(result)
}
}
init {
setGeocoderProvider(context, preferences)
preferences.registerOnPreferenceChangedListener(object :
SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences?,
key: String?
) {
if (key == preferences.getPreferenceKey(R.string.preferenceKeyReverseGeocodeProvider) || key == preferences.getPreferenceKey(
R.string.preferenceKeyOpencageGeocoderApiKey
)
) {
setGeocoderProvider(context, preferences)
}
}
})
notificationManager = NotificationManagerCompat.from(context)
}
companion object {
const val ERROR_NOTIFICATION_CHANNEL_ID = "Errors"
const val GEOCODE_ERROR_NOTIFICATION_TAG = "GeocoderError"
}
}
| epl-1.0 | c34f150e5747eb455bf3607a4ff5256a | 40.94012 | 176 | 0.66462 | 5.493333 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/EditCollectionActivity.kt | 1 | 3343 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui
import android.accounts.Account
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.etesync.syncadapter.App
import com.etesync.syncadapter.R
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.syncadapter.resource.LocalCalendar
import com.etesync.syncadapter.resource.LocalTaskList
class EditCollectionActivity : CreateCollectionActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.edit_collection)
when (info.enumType) {
CollectionInfo.Type.CALENDAR -> {
val colorSquare = findViewById<View>(R.id.color)
colorSquare.setBackgroundColor(info.color ?: LocalCalendar.defaultColor)
}
CollectionInfo.Type.TASKS -> {
val colorSquare = findViewById<View>(R.id.color)
colorSquare.setBackgroundColor(info.color ?: LocalTaskList.defaultColor)
}
CollectionInfo.Type.ADDRESS_BOOK -> {
}
}
val edit = findViewById<View>(R.id.display_name) as EditText
edit.setText(info.displayName)
val desc = findViewById<View>(R.id.description) as EditText
desc.setText(info.description)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_edit_collection, menu)
return true
}
override fun onDestroy() {
super.onDestroy()
if (parent is Refreshable) {
(parent as Refreshable).refresh()
}
}
fun onDeleteCollection(item: MenuItem) {
val data = (application as App).data
val journalCount = data.count(JournalEntity::class.java).where(JournalEntity.SERVICE_MODEL.eq(info.getServiceEntity(data))).get().value()
if (journalCount < 2) {
AlertDialog.Builder(this)
.setIcon(R.drawable.ic_error_dark)
.setTitle(R.string.account_delete_collection_last_title)
.setMessage(R.string.account_delete_collection_last_text)
.setPositiveButton(android.R.string.ok, null)
.show()
} else {
DeleteCollectionFragment.ConfirmDeleteCollectionFragment.newInstance(account, info).show(supportFragmentManager, null)
}
}
companion object {
fun newIntent(context: Context, account: Account, info: CollectionInfo): Intent {
val intent = Intent(context, EditCollectionActivity::class.java)
intent.putExtra(CreateCollectionActivity.EXTRA_ACCOUNT, account)
intent.putExtra(CreateCollectionActivity.EXTRA_COLLECTION_INFO, info)
return intent
}
}
}
| gpl-3.0 | 5a516b4b07fb7b08783c3f794756e08c | 35.703297 | 145 | 0.678443 | 4.651811 | false | false | false | false |
luiqn2007/miaowo | app/src/main/java/org/miaowo/miaowo/handler/ListHandler.kt | 1 | 1432 | package org.miaowo.miaowo.handler
import android.app.Activity
import android.support.annotation.MenuRes
import android.support.annotation.StringRes
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import org.miaowo.miaowo.R
import org.miaowo.miaowo.base.ListAdapter
import org.miaowo.miaowo.other.BaseListTouchListener
class ListHandler(activity: Activity) {
private val mActivity = activity
fun setTitle(title: String, @MenuRes menuRes: Int? = null, menuClickListener: (MenuItem) -> Boolean = {false}) {
val bar = mActivity.findViewById<Toolbar>(R.id.toolBar)
bar.apply {
setTitle(title)
setOnMenuItemClickListener { menuClickListener.invoke(it) }
}
}
fun setTitle(@StringRes title: Int, @MenuRes menuRes: Int? = null, menuClickListener: (MenuItem) -> Boolean = {false}) {
setTitle(mActivity.getString(title), menuRes, menuClickListener)
}
fun <T> setList(manager: RecyclerView.LayoutManager, adapter: ListAdapter<T>, data: List<T>? = null, click: BaseListTouchListener? = null) {
val list = mActivity.findViewById<RecyclerView>(R.id.list)
list.apply {
this.layoutManager = manager
this.adapter = adapter
}
if (click != null) { list.addOnItemTouchListener(click) }
if (data != null) { adapter.update(data) }
}
} | apache-2.0 | e8e15f59f290b35ca53ad6d6dde4f842 | 37.72973 | 144 | 0.699721 | 4.211765 | false | false | false | false |
googlecodelabs/odml-pathways | product-search/codelab2/android/final/app/src/main/java/com/google/codelabs/productimagesearch/ProductSearchActivity.kt | 2 | 6043 | /**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.productimagesearch
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.codelabs.productimagesearch.api.ProductSearchAPIClient
import com.google.codelabs.productimagesearch.databinding.ActivityProductSearchBinding
import com.google.codelabs.productimagesearch.api.ProductSearchResult
class ProductSearchActivity : AppCompatActivity() {
companion object {
const val TAG = "ProductSearchActivity"
const val CROPPED_IMAGE_FILE_NAME = "MLKitCroppedFile_"
const val REQUEST_TARGET_IMAGE_PATH = "REQUEST_TARGET_IMAGE_PATH"
}
private lateinit var viewBinding: ActivityProductSearchBinding
private lateinit var apiClient: ProductSearchAPIClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityProductSearchBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initViews()
// Receive the query image and show it on the screen
intent.getStringExtra(REQUEST_TARGET_IMAGE_PATH)?.let { absolutePath ->
viewBinding.ivQueryImage.setImageBitmap(BitmapFactory.decodeFile(absolutePath))
}
// Initialize an API client for Vision API Product Search
apiClient = ProductSearchAPIClient(this)
}
private fun initViews() {
// Setup RecyclerView
with(viewBinding.recyclerView) {
setHasFixedSize(true)
adapter = ProductSearchAdapter()
layoutManager =
LinearLayoutManager(
this@ProductSearchActivity,
LinearLayoutManager.VERTICAL,
false
)
}
// Events
viewBinding.btnSearch.setOnClickListener {
// Display progress
viewBinding.progressBar.visibility = View.VISIBLE
(viewBinding.ivQueryImage.drawable as? BitmapDrawable)?.bitmap?.let {
searchByImage(it)
}
}
}
/**
* Use Product Search API to search with the given query image
*/
private fun searchByImage(queryImage: Bitmap) {
apiClient.annotateImage(queryImage)
.addOnSuccessListener { showSearchResult(it) }
.addOnFailureListener { error ->
Log.e(TAG, "Error calling Vision API Product Search.", error)
showErrorResponse(error.localizedMessage)
}
}
/**
* Show search result.
*/
private fun showSearchResult(result: List<ProductSearchResult>) {
viewBinding.progressBar.visibility = View.GONE
// Update the recycler view to display the search result.
(viewBinding.recyclerView.adapter as? ProductSearchAdapter)?.submitList(
result
)
}
/**
* Show Error Response
*/
private fun showErrorResponse(message: String?) {
viewBinding.progressBar.visibility = View.GONE
// Show the error when calling API.
Toast.makeText(this, "Error: $message", Toast.LENGTH_SHORT).show()
}
}
/**
* Adapter RecyclerView
*/
class ProductSearchAdapter :
ListAdapter<ProductSearchResult, ProductSearchAdapter.ProductViewHolder>(diffCallback) {
companion object {
val diffCallback = object : DiffUtil.ItemCallback<ProductSearchResult>() {
override fun areItemsTheSame(
oldItem: ProductSearchResult,
newItem: ProductSearchResult
) = oldItem.imageId == newItem.imageId && oldItem.imageUri == newItem.imageUri
override fun areContentsTheSame(
oldItem: ProductSearchResult,
newItem: ProductSearchResult
) = oldItem == newItem
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ProductViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false)
)
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
holder.bind(getItem(position))
}
/**
* ViewHolder to hold the data inside
*/
class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
/**
* Bind data to views
*/
@SuppressLint("SetTextI18n")
fun bind(product: ProductSearchResult) {
with(itemView) {
findViewById<TextView>(R.id.tvProductName).text = "Name: ${product.name}"
findViewById<TextView>(R.id.tvProductScore).text = "Similarity score: ${product.score}"
findViewById<TextView>(R.id.tvProductLabel).text = "Labels: ${product.label}"
// Show the image using Glide
Glide.with(itemView).load(product.imageUri).into(findViewById(R.id.ivProduct))
}
}
}
}
| apache-2.0 | 2e731fcadd5b80568e680063b12daf98 | 33.930636 | 103 | 0.677313 | 5.191581 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/items/detail/ItemLocationFragment.kt | 1 | 3338 | package com.ghstudios.android.features.items.detail
import androidx.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.ListFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.data.classes.Gathering
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.ClickListeners.LocationClickListener
import com.ghstudios.android.SectionArrayAdapter
/**
* Fragment used to display locations where you can gather a specific item
*/
class ItemLocationFragment : ListFragment() {
/**
* Returns the viewmodel of this subfragment, anchored to the parent activity
*/
private val viewModel by lazy {
ViewModelProvider(activity!!).get(ItemDetailViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_generic_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// todo: Refactor this class not to use a cursor. Returning a cursor from a viewmodel can be a source of bugs
viewModel.gatherData.observe(viewLifecycleOwner, Observer { data ->
if (data != null) {
val adapter = GatheringListCursorAdapter(this.context!!, data)
listAdapter = adapter
}
})
}
/**
* Internal adapter to render the list of item gather locations
*/
private class GatheringListCursorAdapter(
context: Context,
gatheringData: List<Gathering>
) : SectionArrayAdapter<Gathering>(context, gatheringData, R.layout.listview_generic_header) {
override fun getGroupName(item: Gathering): String {
return item.rank + " " + item.location?.name
}
override fun newView(context: Context, item: Gathering, parent: ViewGroup): View {
// Use a layout inflater to get a row view
val inflater = LayoutInflater.from(context)
return inflater.inflate(R.layout.fragment_item_location_listitem,
parent, false)
}
override fun bindView(view: View, context: Context, gathering: Gathering) {
val itemLayout = view.findViewById<View>(R.id.listitem)
val mapTextView = view.findViewById<TextView>(R.id.map)
val methodTextView = view.findViewById<TextView>(R.id.method)
val rateTextView = view.findViewById<TextView>(R.id.rate)
val amountTextView = view.findViewById<TextView>(R.id.amount)
mapTextView.text = gathering.area
methodTextView.text = AssetLoader.localizeGatherNodeFull(gathering)
rateTextView.text = gathering.rate.toInt().toString() + "%"
amountTextView.text = "x" + gathering.quantity
itemLayout.tag = gathering.location!!.id
itemLayout.setOnClickListener(LocationClickListener(context,
gathering.location!!.id))
}
}
}
| mit | 906da13ea3573963a8e5b5221588bb95 | 38.270588 | 117 | 0.682744 | 4.858806 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/incoming/DuplicateTermination.kt | 1 | 2016 | /*
* Copyright @ 2018 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node.incoming
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.node.TransformerNode
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.utils.LRUCache
import java.util.TreeMap
/**
* A node which drops packets with SSRC and sequence number pairs identical to ones
* that have previously been seen.
*
* (Since SRTP also has anti-replay protection, the normal case where duplicates
* will occur is after the [RtxHandler], since duplicate packets are sent over RTX for probing.)
*/
class DuplicateTermination() : TransformerNode("Duplicate termination") {
private val replayContexts: MutableMap<Long, MutableSet<Int>> = TreeMap()
private var numDuplicatePacketsDropped = 0
override fun transform(packetInfo: PacketInfo): PacketInfo? {
val rtpPacket = packetInfo.packetAs<RtpPacket>()
val replayContext = replayContexts.computeIfAbsent(rtpPacket.ssrc) {
LRUCache.lruSet(1500, true)
}
if (!replayContext.add(rtpPacket.sequenceNumber)) {
numDuplicatePacketsDropped++
return null
}
return packetInfo
}
override fun getNodeStats(): NodeStatsBlock = super.getNodeStats().apply {
addNumber("num_duplicate_packets_dropped", numDuplicatePacketsDropped)
}
override fun trace(f: () -> Unit) = f.invoke()
}
| apache-2.0 | 6c23548f344f57936d851eb29cf1e3f9 | 35.654545 | 96 | 0.725198 | 4.335484 | false | false | false | false |
ejeinc/Meganekko | library/src/main/java/org/meganekkovr/ovrjni/OVRApp.kt | 1 | 1191 | package org.meganekkovr.ovrjni
class OVRApp private constructor(private val appPtr: Long) {
fun recenterYaw(showBlack: Boolean) {
recenterYaw(appPtr, showBlack)
}
fun showSystemUI(type: Int) {
showSystemUI(appPtr, type)
}
fun setClockLevels(cpuLevel: Int, gpuLevel: Int) {
setClockLevels(appPtr, cpuLevel, gpuLevel)
}
private external fun recenterYaw(appPtr: Long, showBlack: Boolean)
private external fun showSystemUI(appPtr: Long, type: Int)
private external fun setClockLevels(appPtr: Long, cpuLevel: Int, gpuLevel: Int)
companion object {
//-----------------------------------------------------------------
// System Activity Commands
//-----------------------------------------------------------------
const val SYSTEM_UI_GLOBAL_MENU = 0
const val SYSTEM_UI_CONFIRM_QUIT_MENU = 1
const val SYSTEM_UI_KEYBOARD_MENU = 2
const val SYSTEM_UI_FILE_DIALOG_MENU = 3
@JvmStatic
lateinit var instance: OVRApp
@Synchronized
@JvmStatic
internal fun init(appPtr: Long) {
instance = OVRApp(appPtr)
}
}
}
| apache-2.0 | 0efaa1c8d9517b454af9bcc435b7e4de | 27.357143 | 83 | 0.565071 | 4.563218 | false | false | false | false |
koesie10/AdventOfCode-Solutions-Kotlin | 2016/src/main/kotlin/com/koenv/adventofcode/Day14.kt | 1 | 2048 | package com.koenv.adventofcode
import com.koenv.adventofcode.Day5.toHexString
import java.security.MessageDigest
object Day14 {
val md5 = MessageDigest.getInstance("MD5")
fun findIndexOfOneTimePadKey(salt: String, padKey: Int, part2: Boolean): Int {
val hashes = hashMapOf<Int, CharArray>()
val keys = arrayListOf<CharArray>()
var i = 0
while (keys.size < padKey) {
val digest: CharArray
if (i in hashes) {
digest = hashes[i]!!
} else {
digest = generateHash(salt, i, part2)
hashes[i] = digest
}
check@ for (j in 2..digest.size - 1) {
if (digest[j] == digest[j - 1] && digest[j] == digest[j - 2]) {
for (k in i + 1..i + 1000) {
val hash: CharArray
if (k in hashes) {
hash = hashes[k]!!
} else {
hash = generateHash(salt, k, part2)
hashes[k] = hash
}
for (l in 4..hash.size - 1) {
if (digest[j] == hash[l] && hash[l] == hash[l - 1] && hash[l] == hash[l - 2]
&& hash[l] == hash[l - 3] && hash[l] == hash[l - 4]) {
keys.add(digest)
break@check
}
}
}
break@check // only consider the first one
}
}
i++
}
return i - 1
}
private fun generateHash(salt: String, i: Int, part2: Boolean): CharArray {
var hashes = 1
if (part2) {
hashes = 2017
}
var digest = salt + i
for (j in 1..hashes) {
digest = md5.digest(digest.toByteArray()).toHexString().toLowerCase()
}
return digest.toCharArray()
}
} | mit | ad8f67a46b19f3f70359cba232ae3211 | 31.52381 | 104 | 0.413086 | 4.511013 | false | false | false | false |
k0shk0sh/FastHub | app/src/main/java/com/fastaccess/ui/modules/editor/EditorActivity.kt | 1 | 8902 | package com.fastaccess.ui.modules.editor
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.transition.TransitionManager
import androidx.fragment.app.FragmentManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import butterknife.BindView
import butterknife.OnClick
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.data.dao.EditReviewCommentModel
import com.fastaccess.data.dao.model.Comment
import com.fastaccess.helper.*
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.provider.markdown.MarkDownProvider
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.dialog.MessageDialogView
import com.fastaccess.ui.widgets.markdown.MarkDownLayout
import com.fastaccess.ui.widgets.markdown.MarkdownEditText
import java.util.*
/**
* Created by Kosh on 27 Nov 2016, 1:32 AM
*/
class EditorActivity : BaseActivity<EditorMvp.View, EditorPresenter>(), EditorMvp.View {
private var participants: ArrayList<String>? = null
private val sentFromFastHub: String by lazy {
"\n\n_" + getString(
R.string.sent_from_fasthub, AppHelper.getDeviceName(), "",
"[" + getString(R.string.app_name) + "](https://play.google.com/store/apps/details?id=com.fastaccess.github)"
) + "_"
}
@BindView(R.id.replyQuote) lateinit var replyQuote: LinearLayout
@BindView(R.id.replyQuoteText) lateinit var quote: FontTextView
@BindView(R.id.markDownLayout) lateinit var markDownLayout: MarkDownLayout
@BindView(R.id.editText) lateinit var editText: MarkdownEditText
@BindView(R.id.list_divider) lateinit var listDivider: View
@BindView(R.id.parentView) lateinit var parentView: View
@BindView(R.id.autocomplete) lateinit var mention: ListView
@State @BundleConstant.ExtraType var extraType: String? = null
@State var itemId: String? = null
@State var login: String? = null
@State var issueNumber: Int = 0
@State var commentId: Long = 0
@State var sha: String? = null
@State var reviewComment: EditReviewCommentModel? = null
override fun layout(): Int = R.layout.editor_layout
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun isSecured(): Boolean = false
override fun providePresenter(): EditorPresenter = EditorPresenter()
@OnClick(R.id.replyQuoteText) internal fun onToggleQuote() {
TransitionManager.beginDelayedTransition((parentView as ViewGroup))
if (quote.maxLines == 3) {
quote.maxLines = Integer.MAX_VALUE
} else {
quote.maxLines = 3
}
quote.setCompoundDrawablesWithIntrinsicBounds(
0, 0,
if (quote.maxLines == 3) R.drawable.ic_arrow_drop_down
else R.drawable.ic_arrow_drop_up, 0
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
markDownLayout.markdownListener = this
setToolbarIcon(R.drawable.ic_clear)
if (savedInstanceState == null) {
onCreate()
}
invalidateOptionsMenu()
editText.initListView(mention, listDivider, participants)
editText.requestFocus()
}
override fun onSendResultAndFinish(commentModel: Comment, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(
Bundler.start()
.put(BundleConstant.ITEM, commentModel)
.put(BundleConstant.EXTRA, isNew)
.end()
)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendMarkDownResult() {
val intent = Intent()
intent.putExtras(Bundler.start().put(BundleConstant.EXTRA, editText.savedText).end())
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendReviewResultAndFinish(comment: EditReviewCommentModel, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(
Bundler.start()
.put(BundleConstant.ITEM, comment)
.put(BundleConstant.EXTRA, isNew)
.end()
)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.done_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.submit) {
if (PrefGetter.isSentViaEnabled()) {
val temp = editText.savedText.toString()
if (!temp.contains(sentFromFastHub)) {
editText.savedText = editText.savedText.toString() + sentFromFastHub
}
}
presenter.onHandleSubmission(editText.savedText, extraType, itemId, commentId, login, issueNumber, sha, reviewComment)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
if (menu.findItem(R.id.submit) != null) {
menu.findItem(R.id.submit).isEnabled = true
}
if (BundleConstant.ExtraType.FOR_RESULT_EXTRA.equals(extraType, ignoreCase = true)) {
menu.findItem(R.id.submit).setIcon(R.drawable.ic_done)
}
return super.onPrepareOptionsMenu(menu)
}
override fun showProgress(@StringRes resId: Int) {
super.showProgress(resId)
invalidateOptionsMenu()
}
override fun hideProgress() {
invalidateOptionsMenu()
super.hideProgress()
}
override fun onBackPressed() {
if (!InputHelper.isEmpty(editText)) {
ViewHelper.hideKeyboard(editText)
MessageDialogView.newInstance(
getString(R.string.close), getString(R.string.unsaved_data_warning),
Bundler.start()
.put("primary_extra", getString(R.string.discard))
.put("secondary_extra", getString(R.string.cancel))
.put(BundleConstant.EXTRA, true)
.end()
)
.show(supportFragmentManager, MessageDialogView.TAG)
return
}
super.onBackPressed()
}
override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) {
super.onMessageDialogActionClicked(isOk, bundle)
if (isOk && bundle != null) {
finish()
}
}
override fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markDownLayout.onAppendLink(title, link, isLink)
}
override fun getEditText(): EditText = editText
override fun getSavedText(): CharSequence? = editText.savedText
override fun fragmentManager(): FragmentManager = supportFragmentManager
@SuppressLint("SetTextI18n")
override fun onEmojiAdded(emoji: Emoji?) {
markDownLayout.onEmojiAdded(emoji)
}
private fun onCreate() {
val intent = intent
if (intent != null && intent.extras != null) {
val bundle = intent.extras
extraType = bundle?.getString(BundleConstant.EXTRA_TYPE)
reviewComment = bundle?.getParcelable(BundleConstant.REVIEW_EXTRA)
itemId = bundle?.getString(BundleConstant.ID)
login = bundle?.getString(BundleConstant.EXTRA_TWO)
if (extraType.equals(BundleConstant.ExtraType.EDIT_COMMIT_COMMENT_EXTRA, ignoreCase = true)
|| extraType.equals(BundleConstant.ExtraType.NEW_COMMIT_COMMENT_EXTRA, ignoreCase = true)
) {
sha = bundle?.getString(BundleConstant.EXTRA_THREE)
} else {
issueNumber = bundle?.getInt(BundleConstant.EXTRA_THREE) ?: -1
}
commentId = bundle?.getLong(BundleConstant.EXTRA_FOUR) ?: -1
val textToUpdate = bundle?.getString(BundleConstant.EXTRA)
if (!InputHelper.isEmpty(textToUpdate)) {
editText.setText(String.format("%s ", textToUpdate))
editText.setSelection(InputHelper.toString(editText).length)
}
if (bundle?.getString("message", "").isNullOrEmpty()) {
replyQuote.visibility = GONE
} else {
MarkDownProvider.setMdText(quote, bundle?.getString("message", ""))
}
participants = bundle?.getStringArrayList("participants")
}
}
} | gpl-3.0 | dcaaf50fa24d9e0d332ee6171be97999 | 35.941909 | 130 | 0.653224 | 4.725053 | false | false | false | false |
ze-pequeno/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/Exchange.kt | 2 | 9354 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import java.net.ProtocolException
import java.net.SocketException
import okhttp3.EventListener
import okhttp3.Headers
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealResponseBody
import okhttp3.internal.ws.RealWebSocket
import okio.Buffer
import okio.ForwardingSink
import okio.ForwardingSource
import okio.Sink
import okio.Source
import okio.buffer
/**
* Transmits a single HTTP request and a response pair. This layers connection management and events
* on [ExchangeCodec], which handles the actual I/O.
*/
class Exchange(
internal val call: RealCall,
internal val eventListener: EventListener,
internal val finder: ExchangeFinder,
private val codec: ExchangeCodec
) {
/** True if the request body need not complete before the response body starts. */
internal var isDuplex: Boolean = false
private set
/** True if there was an exception on the connection to the peer. */
internal var hasFailure: Boolean = false
private set
internal val connection: RealConnection
get() = codec.carrier as? RealConnection ?: error("no connection for CONNECT tunnels")
internal val isCoalescedConnection: Boolean
get() = finder.routePlanner.address.url.host != codec.carrier.route.address.url.host
@Throws(IOException::class)
fun writeRequestHeaders(request: Request) {
try {
eventListener.requestHeadersStart(call)
codec.writeRequestHeaders(request)
eventListener.requestHeadersEnd(call, request)
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun createRequestBody(request: Request, duplex: Boolean): Sink {
this.isDuplex = duplex
val contentLength = request.body!!.contentLength()
eventListener.requestBodyStart(call)
val rawRequestBody = codec.createRequestBody(request, contentLength)
return RequestBodySink(rawRequestBody, contentLength)
}
@Throws(IOException::class)
fun flushRequest() {
try {
codec.flushRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun finishRequest() {
try {
codec.finishRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersStart() {
eventListener.responseHeadersStart(call)
}
@Throws(IOException::class)
fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {
try {
val result = codec.readResponseHeaders(expectContinue)
result?.initExchange(this)
return result
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersEnd(response: Response) {
eventListener.responseHeadersEnd(call, response)
}
@Throws(IOException::class)
fun openResponseBody(response: Response): ResponseBody {
try {
val contentType = response.header("Content-Type")
val contentLength = codec.reportedContentLength(response)
val rawSource = codec.openResponseBodySource(response)
val source = ResponseBodySource(rawSource, contentLength)
return RealResponseBody(contentType, contentLength, source.buffer())
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun trailers(): Headers = codec.trailers()
@Throws(SocketException::class)
fun newWebSocketStreams(): RealWebSocket.Streams {
call.timeoutEarlyExit()
return (codec.carrier as RealConnection).newWebSocketStreams(this)
}
fun webSocketUpgradeFailed() {
bodyComplete(-1L, responseDone = true, requestDone = true, e = null)
}
fun noNewExchangesOnConnection() {
codec.carrier.noNewExchanges()
}
fun cancel() {
codec.cancel()
}
/**
* Revoke this exchange's access to streams. This is necessary when a follow-up request is
* required but the preceding exchange hasn't completed yet.
*/
fun detachWithViolence() {
codec.cancel()
call.messageDone(this, requestDone = true, responseDone = true, e = null)
}
private fun trackFailure(e: IOException) {
hasFailure = true
codec.carrier.trackFailure(call, e)
}
fun <E : IOException?> bodyComplete(
bytesRead: Long,
responseDone: Boolean,
requestDone: Boolean,
e: E
): E {
if (e != null) {
trackFailure(e)
}
if (requestDone) {
if (e != null) {
eventListener.requestFailed(call, e)
} else {
eventListener.requestBodyEnd(call, bytesRead)
}
}
if (responseDone) {
if (e != null) {
eventListener.responseFailed(call, e)
} else {
eventListener.responseBodyEnd(call, bytesRead)
}
}
return call.messageDone(this, requestDone, responseDone, e)
}
fun noRequestBody() {
call.messageDone(this, requestDone = true, responseDone = false, e = null)
}
/** A request body that fires events when it completes. */
private inner class RequestBodySink(
delegate: Sink,
/** The exact number of bytes to be written, or -1L if that is unknown. */
private val contentLength: Long
) : ForwardingSink(delegate) {
private var completed = false
private var bytesReceived = 0L
private var closed = false
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
check(!closed) { "closed" }
if (contentLength != -1L && bytesReceived + byteCount > contentLength) {
throw ProtocolException(
"expected $contentLength bytes but received ${bytesReceived + byteCount}")
}
try {
super.write(source, byteCount)
this.bytesReceived += byteCount
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun flush() {
try {
super.flush()
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
if (contentLength != -1L && bytesReceived != contentLength) {
throw ProtocolException("unexpected end of stream")
}
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
private fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
return bodyComplete(bytesReceived, responseDone = false, requestDone = true, e = e)
}
}
/** A response body that fires events when it completes. */
internal inner class ResponseBodySource(
delegate: Source,
private val contentLength: Long
) : ForwardingSource(delegate) {
private var bytesReceived = 0L
private var invokeStartEvent = true
private var completed = false
private var closed = false
init {
if (contentLength == 0L) {
complete(null)
}
}
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
check(!closed) { "closed" }
try {
val read = delegate.read(sink, byteCount)
if (invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
if (read == -1L) {
complete(null)
return -1L
}
val newBytesReceived = bytesReceived + read
if (contentLength != -1L && newBytesReceived > contentLength) {
throw ProtocolException("expected $contentLength bytes but received $newBytesReceived")
}
bytesReceived = newBytesReceived
if (newBytesReceived == contentLength) {
complete(null)
}
return read
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
// If the body is closed without reading any bytes send a responseBodyStart() now.
if (e == null && invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
return bodyComplete(bytesReceived, responseDone = true, requestDone = false, e = e)
}
}
}
| apache-2.0 | a79de3bf01223fb971d0a762e11862fb | 27.174699 | 100 | 0.664422 | 4.397743 | false | false | false | false |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/AttacksInfoTest.kt | 1 | 1266 | package karballo
import karballo.bitboard.AttacksInfo
import karballo.bitboard.BitboardUtils
import karballo.util.JvmPlatformUtils
import karballo.util.Utils
import org.junit.Assert.assertEquals
import org.junit.Test
class AttacksInfoTest {
constructor() {
Utils.instance = JvmPlatformUtils()
}
@Test
fun testPinnedBishop() {
val b = Board()
b.fen = "3k4/3r4/8/3B4/2P5/8/8/3K4 b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.bishopAttacks[0]))
assertEquals(0, ai.bishopAttacks[0])
}
@Test
fun testPinnedRook() {
val b = Board()
b.fen = "3k4/3r4/8/3R4/2P5/8/8/3K4 b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.rookAttacks[0]))
assertEquals(5, BitboardUtils.popCount(ai.rookAttacks[0]).toLong())
}
@Test
fun testPinnedPawn() {
val b = Board()
b.fen = "3k4/8/2b5/3P4/8/8/8/7K b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.pawnAttacks[0]))
assertEquals(1, BitboardUtils.popCount(ai.pawnAttacks[0]).toLong())
}
} | mit | 248d225407e3c28b5d1f994666a8e3b6 | 25.395833 | 75 | 0.612164 | 3.188917 | false | true | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/management/food/ActionReceiver.kt | 1 | 1601 | package com.example.android.eyebody.management.food
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
/**
* Created by ytw11 on 2017-11-19.
*/
class ActionReceiver : BroadcastReceiver() {
var menu:String=""
override fun onReceive(context:Context , intent:Intent) {
val dbHelper = DbHelper(context, "bill.db", null, 1)
val menu = intent.getStringExtra("menu")
val time=intent.getStringExtra("time")
val price=intent.getIntExtra("price",0)
when (menu) {
"meal" -> mealClicked(context)
"beverage" -> beverageClicked(context)
"dessert" -> dessertClicked(context)
"cancel" ->cancelClicked(context)
}
putValuesInDb(dbHelper,time,menu,price)
}
private fun mealClicked(context: Context) {
menu="meal"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun beverageClicked(context: Context) {
menu="beverage"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun dessertClicked(context: Context){
menu="dessert"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun cancelClicked(context:Context){
menu="cancel"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun putValuesInDb(dbHelper: DbHelper, time:String, menu:String, price:Int){
if(menu!="cancel"){
dbHelper.insert(time,menu,price)
}
}
} | mit | 42f45b76440139b5c8c98341206a522f | 31.693878 | 87 | 0.651468 | 4.053165 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SearchableNucleusController.kt | 1 | 7350 | package eu.kanade.tachiyomi.ui.base.controller
import android.app.Activity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.annotation.StringRes
import androidx.appcompat.widget.SearchView
import androidx.viewbinding.ViewBinding
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import reactivecircus.flowbinding.appcompat.QueryTextEvent
import reactivecircus.flowbinding.appcompat.queryTextEvents
/**
* Implementation of the NucleusController that has a built-in ViewSearch
*/
abstract class SearchableNucleusController<VB : ViewBinding, P : BasePresenter<*>>
(bundle: Bundle? = null) : NucleusController<VB, P>(bundle) {
enum class SearchViewState { LOADING, LOADED, COLLAPSING, FOCUSED }
/**
* Used to bypass the initial searchView being set to empty string after an onResume
*/
private var currentSearchViewState: SearchViewState = SearchViewState.LOADING
/**
* Store the query text that has not been submitted to reassign it after an onResume, UI-only
*/
protected var nonSubmittedQuery: String = ""
/**
* To be called by classes that extend this subclass in onCreateOptionsMenu
*/
protected fun createOptionsMenu(
menu: Menu,
inflater: MenuInflater,
menuId: Int,
searchItemId: Int,
@StringRes queryHint: Int? = null,
restoreCurrentQuery: Boolean = true
) {
// Inflate menu
inflater.inflate(menuId, menu)
// Initialize search option.
val searchItem = menu.findItem(searchItemId)
val searchView = searchItem.actionView as SearchView
searchItem.fixExpand(onExpand = { invalidateMenuOnExpand() })
searchView.maxWidth = Int.MAX_VALUE
searchView.queryTextEvents()
.onEach {
val newText = it.queryText.toString()
if (newText.isNotBlank() or acceptEmptyQuery()) {
if (it is QueryTextEvent.QuerySubmitted) {
// Abstract function for implementation
// Run it first in case the old query data is needed (like BrowseSourceController)
onSearchViewQueryTextSubmit(newText)
presenter.query = newText
nonSubmittedQuery = ""
} else if ((it is QueryTextEvent.QueryChanged) && (presenter.query != newText)) {
nonSubmittedQuery = newText
// Abstract function for implementation
onSearchViewQueryTextChange(newText)
}
}
// clear the collapsing flag
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.COLLAPSING)
}
.launchIn(viewScope)
val query = presenter.query
// Restoring a query the user had not submitted
if (nonSubmittedQuery.isNotBlank() and (nonSubmittedQuery != query)) {
searchItem.expandActionView()
searchView.setQuery(nonSubmittedQuery, false)
onSearchViewQueryTextChange(nonSubmittedQuery)
} else {
if (queryHint != null) {
searchView.queryHint = applicationContext?.getString(queryHint)
}
if (restoreCurrentQuery) {
// Restoring a query the user had submitted
if (query.isNotBlank()) {
searchItem.expandActionView()
searchView.setQuery(query, true)
searchView.clearFocus()
onSearchViewQueryTextChange(query)
onSearchViewQueryTextSubmit(query)
}
}
}
// Workaround for weird behavior where searchView gets empty text change despite
// query being set already, prevents the query from being cleared
binding.root.post {
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.LOADING)
}
searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
if (hasFocus) {
setCurrentSearchViewState(SearchViewState.FOCUSED)
} else {
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.FOCUSED)
}
}
searchItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
onSearchMenuItemActionExpand(item)
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
val localSearchView = searchItem.actionView as SearchView
// if it is blank the flow event won't trigger so we would stay in a COLLAPSING state
if (localSearchView.toString().isNotBlank()) {
setCurrentSearchViewState(SearchViewState.COLLAPSING)
}
onSearchMenuItemActionCollapse(item)
return true
}
}
)
}
override fun onActivityResumed(activity: Activity) {
super.onActivityResumed(activity)
// Until everything is up and running don't accept empty queries
setCurrentSearchViewState(SearchViewState.LOADING)
}
private fun acceptEmptyQuery(): Boolean {
return when (currentSearchViewState) {
SearchViewState.COLLAPSING, SearchViewState.FOCUSED -> true
else -> false
}
}
private fun setCurrentSearchViewState(to: SearchViewState, from: SearchViewState? = null) {
// When loading ignore all requests other than loaded
if ((currentSearchViewState == SearchViewState.LOADING) && (to != SearchViewState.LOADED)) {
return
}
// Prevent changing back to an unwanted state when using async flows (ie onFocus event doing
// COLLAPSING -> LOADED)
if ((from != null) && (currentSearchViewState != from)) {
return
}
currentSearchViewState = to
}
/**
* Called by the SearchView since since the implementation of these can vary in subclasses
* Not abstract as they are optional
*/
protected open fun onSearchViewQueryTextChange(newText: String?) {
}
protected open fun onSearchViewQueryTextSubmit(query: String?) {
}
protected open fun onSearchMenuItemActionExpand(item: MenuItem?) {
}
protected open fun onSearchMenuItemActionCollapse(item: MenuItem?) {
}
/**
* During the conversion to SearchableNucleusController (after which I plan to merge its code
* into BaseController) this addresses an issue where the searchView.onTextFocus event is not
* triggered
*/
override fun invalidateMenuOnExpand(): Boolean {
return if (expandActionViewFromInteraction) {
activity?.invalidateOptionsMenu()
setCurrentSearchViewState(SearchViewState.FOCUSED) // we are technically focused here
false
} else {
true
}
}
}
| apache-2.0 | 628f5d36f81acf01695be7faca19af54 | 36.5 | 106 | 0.628707 | 5.903614 | false | false | false | false |
sensefly-sa/dynamodb-to-s3 | src/main/kotlin/io/sensefly/dynamodbtos3/commandline/RestoreCommand.kt | 1 | 789 | package io.sensefly.dynamodbtos3.commandline
import com.beust.jcommander.Parameter
import com.beust.jcommander.Parameters
import io.sensefly.dynamodbtos3.RestoreTable
import java.net.URI
@Parameters(commandDescription = "Restore DynamoDB table from json file hosted on S3.")
class RestoreCommand {
@Parameter(names = ["-t", "--table"], description = "Table to restore.", required = true, order = 0)
var table: String = ""
@Parameter(names = ["-s", "--source"], description = "S3 URI to a JSON backup file (s3://my-bucket/folder/my-table.json).", required = true, order = 1)
var source: URI? = null
@Parameter(names = ["-w", "--write-percentage"], description = "Write capacity percentage.", order = 3)
var writePercentage: Double = RestoreTable.DEFAULT_WRITE_PERCENTAGE
} | bsd-3-clause | fd92ed6da92e5660c8a39164cd1b0941 | 38.5 | 153 | 0.724968 | 3.77512 | false | false | false | false |
Zhuinden/simple-stack | samples/advanced-samples/mvvm-sample/src/main/java/com/zhuinden/simplestackexamplemvvm/data/Task.kt | 1 | 1977 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhuinden.simplestackexamplemvvm.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.util.*
/**
* Immutable model class for a Task.
*/
@Parcelize
data class Task(
val id: String?,
val title: String?,
val description: String?,
val completed: Boolean,
) : Parcelable {
val titleForList: String
get() = if (!title.isNullOrEmpty()) {
title
} else {
description
} ?: ""
val isCompleted: Boolean
get() = completed
val isActive: Boolean
get() = !completed
val isEmpty: Boolean
get() = title.isNullOrEmpty() && description.isNullOrEmpty()
companion object {
fun createNewActiveTask(title: String?, description: String?): Task {
return createTaskWithId(title, description, UUID.randomUUID().toString(), false)
}
fun createActiveTaskWithId(title: String?, description: String?, id: String?): Task {
return createTaskWithId(title, description, id, false)
}
fun createTaskWithId(title: String?, description: String?, id: String?, completed: Boolean): Task {
return Task(
id = id,
title = title,
description = description,
completed = completed
)
}
}
} | apache-2.0 | 28a123b6a6b4df8bd432dae3bbada705 | 29.430769 | 107 | 0.639858 | 4.684834 | false | false | false | false |
JavaEden/OrchidCore | OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/sass/SassCompiler.kt | 1 | 1801 | package com.eden.orchid.impl.compilers.sass
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.compilers.OrchidCompiler
import io.bit3.jsass.Compiler
import io.bit3.jsass.Options
import java.net.URI
import java.util.regex.Pattern
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SassCompiler
@Inject
constructor(
private val importer: SassImporter
) : OrchidCompiler(800) {
private val previousContextRegex = Pattern.compile("^//\\s*?CONTEXT=(.*?)$", Pattern.MULTILINE)
enum class CompilerSyntax(val ext: String) {
SASS("sass"), SCSS("scss"), UNSPECIFIED("")
}
override fun getSourceExtensions(): Array<String> {
return arrayOf(CompilerSyntax.SCSS.ext, CompilerSyntax.SASS.ext)
}
override fun getOutputExtension(): String {
return "css"
}
override fun compile(extension: String, input: String, data: Map<String, Any>): String {
val options = Options()
options.importers.add(importer)
var sourceContext = ""
val m = previousContextRegex.matcher(input)
if (m.find()) {
sourceContext = m.group(1)
}
if (extension == CompilerSyntax.SASS.ext) {
options.setIsIndentedSyntaxSrc(true)
} else {
options.setIsIndentedSyntaxSrc(false)
}
try {
return if (EdenUtils.isEmpty(sourceContext)) {
Compiler().compileString(input, options).css
} else {
Compiler().compileString(input, URI(sourceContext), URI(sourceContext), options).css
}
} catch (e: Exception) {
Clog.e("error compiling .{} content: {}", e, extension, e.message)
return ""
}
}
}
| mit | 536de8bb17e15f3b9f8581094f1b2752 | 27.587302 | 100 | 0.637424 | 4.130734 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/api/OpenSignInAuthenticator.kt | 2 | 2194 | package com.commit451.gitlab.api
import android.content.Intent
import android.widget.Toast
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.LoginActivity
import com.commit451.gitlab.data.Prefs
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.util.ThreadUtil
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import timber.log.Timber
import java.io.IOException
/**
* If it detects a 401, redirect the user to the login screen, clearing activity the stack.
* Kinda a weird global way of forcing the user to the login screen if their auth has expired
*/
class OpenSignInAuthenticator(private val account: Account) : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
val url = response.request.url
var cleanUrl = url.toString().toLowerCase()
cleanUrl = cleanUrl.substring(cleanUrl.indexOf(':'))
var cleanServerUrl = account.serverUrl.toString().toLowerCase()
cleanServerUrl = cleanServerUrl.substring(cleanServerUrl.indexOf(':'))
//Ensure that we only check urls of the gitlab instance
if (cleanUrl.startsWith(cleanServerUrl)) {
//Special case for if someone just put in their username or password wrong
if ("session" != url.pathSegments[url.pathSegments.size - 1]) {
//Off the background thread
Timber.wtf(RuntimeException("Got a 401 and showing sign in for url: " + response.request.url))
ThreadUtil.postOnMainThread(Runnable {
//Remove the account, so that the user can sign in again
Prefs.removeAccount(account)
Toast.makeText(App.get(), R.string.error_401, Toast.LENGTH_LONG)
.show()
val intent = LoginActivity.newIntent(App.get())
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
App.get().startActivity(intent)
})
}
}
return null
}
}
| apache-2.0 | 19f3dda5c57d1408055862dd5f31dc61 | 40.396226 | 110 | 0.670921 | 4.561331 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/utils/SampleUtilsKt.kt | 1 | 1374 | package io.noties.markwon.app.utils
import android.content.Context
import io.noties.markwon.app.sample.Sample
import io.noties.markwon.sample.annotations.MarkwonArtifact
import java.io.InputStream
val MarkwonArtifact.displayName: String
get() = "@${artifactName()}"
val String.tagDisplayName: String
get() = "#$this"
private const val SAMPLE_PREFIX = "io.noties.markwon.app."
fun Sample.readCode(context: Context): Sample.Code {
val assets = context.assets
// keep sample and nested directories
val path = javaClassName
.removePrefix(SAMPLE_PREFIX)
.replace('.', '/')
fun obtain(path: String): InputStream? {
return try {
assets.open(path)
} catch (t: Throwable) {
null
}
}
// now, we have 2 possibilities -> Kotlin or Java
var language: Sample.Language = Sample.Language.KOTLIN
var stream = obtain("$path.kt")
if (stream == null) {
language = Sample.Language.JAVA
stream = obtain("$path.java")
}
if (stream == null) {
throw IllegalStateException("Cannot obtain sample file at path: $path")
}
val code = stream.readStringAndClose()
return Sample.Code(language, code)
}
fun loadReadMe(context: Context): String {
val stream = context.assets.open("README.md")
return stream.readStringAndClose()
} | apache-2.0 | 9647a012cd55863ba720cf920e550786 | 25.442308 | 79 | 0.65575 | 4.176292 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/flex/intentions/FlexIntentionsBundle.kt | 1 | 1249 | // Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.intentions
import com.intellij.BundleBase
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.lang.ref.Reference
import java.lang.ref.SoftReference
import java.util.*
class FlexIntentionsBundle : BundleBase() {
companion object {
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String {
return BundleBase.message(bundle, key, *params)
}
private var ourBundle: Reference<ResourceBundle>? = null
@NonNls
internal const val BUNDLE = "com.vladsch.md.nav.flex.localization.intentions"
internal val bundle: ResourceBundle
get() {
var bundle = com.intellij.reference.SoftReference.dereference(ourBundle)
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE)
ourBundle = SoftReference(bundle)
}
return bundle as ResourceBundle
}
}
}
| apache-2.0 | 154948463a34df3f85d1aaa6d6afc6ff | 33.694444 | 177 | 0.663731 | 4.785441 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/samples/image/CoilRecyclerViewSample.kt | 1 | 2262 | package io.noties.markwon.app.samples.image
import androidx.recyclerview.widget.LinearLayoutManager
import coil.Coil
import coil.request.Disposable
import coil.request.ImageRequest
import coil.transform.RoundedCornersTransformation
import io.noties.markwon.Markwon
import io.noties.markwon.app.R
import io.noties.markwon.app.sample.ui.MarkwonRecyclerViewSample
import io.noties.markwon.image.AsyncDrawable
import io.noties.markwon.image.coil.CoilImagesPlugin
import io.noties.markwon.recycler.MarkwonAdapter
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
@MarkwonSampleInfo(
id = "20200803132053",
title = "Coil inside RecyclerView",
description = "Display images via Coil plugin in `RecyclerView`",
artifacts = [MarkwonArtifact.IMAGE_COIL, MarkwonArtifact.RECYCLER],
tags = [Tag.rendering, Tag.recyclerView, Tag.image]
)
class CoilRecyclerViewSample : MarkwonRecyclerViewSample() {
override fun render() {
val md = """
# H1
## H2
### H3
#### H4
##### H5
> a quote
+ one
- two
* three
1. one
1. two
1. three
---
# Images

""".trimIndent()
val markwon = Markwon.builder(context)
.usePlugin(CoilImagesPlugin.create(
object : CoilImagesPlugin.CoilStore {
override fun load(drawable: AsyncDrawable): ImageRequest {
return ImageRequest.Builder(context)
.transformations(
RoundedCornersTransformation(14F)
)
.data(drawable.destination)
.placeholder(R.drawable.ic_image_gray_24dp)
.build()
}
override fun cancel(disposable: Disposable) {
disposable.dispose()
}
},
Coil.imageLoader(context)))
.build()
val adapter = MarkwonAdapter.createTextViewIsRoot(R.layout.adapter_node)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
adapter.setMarkdown(markwon, md)
adapter.notifyDataSetChanged()
}
} | apache-2.0 | 88f9f9e413b4669a49197b678dd6875c | 27.64557 | 76 | 0.670645 | 4.51497 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/ide/template/RsLiveTemplatesTest.kt | 4 | 2633 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.template
import com.intellij.openapi.actionSystem.IdeActions
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
class RsLiveTemplatesTest : RsTestBase() {
override val dataPath = "org/rust/ide/template/fixtures"
fun testStructField() = expandSnippet("""
struct S {
f/*caret*/
}
""", """
struct S {
foo: u32,
}
""")
fun testPrint() = expandSnippet("""
fn main() {
p/*caret*/
}
""", """
fn main() {
println!("");
}
""")
fun testAttribute() = noSnippet("""
#[macro/*caret*/]
extern crate std;
fn main() { }
""")
fun testComment() = noSnippet("""
fn main() {
// p/*caret*/
}
""")
fun testDocComment() = noSnippet("""
/// p/*caret*/
fn f() {}
""")
fun testStringLiteral() = noSnippet("""
fn main() {
let _ = "p/*caret*/";
}
""")
fun testRawStringLiteral() = noSnippet("""
fn main() {
let _ = r##"p/*caret*/"##;
}
""")
fun testByteStringLiteral() = noSnippet("""
fn main() {
let _ = b"p/*caret*/";
}
""")
fun testFieldExpression() = noSnippet("""
fn main() {
let _ = foo.p/*caret*/
}
""")
fun testMethodExpression() = noSnippet("""
fn main() {
let _ = foo.p/*caret*/()
}
""")
fun testPath() = noSnippet("""
fn main() {
let _ = foo::p/*caret*/
}
""")
val indent = " "
fun `test module level context available in file`() = expandSnippet("""
tfn/*caret*/
""", """
#[test]
fn /*caret*/() {
$indent
}
""")
fun `test module level context not available in function`() = noSnippet("""
fn foo() {
x.tfn/*caret*/
}
""")
fun `test main is available in file`() = expandSnippet("""
main/*caret*/
""", """
fn main() {
$indent/*caret*/
}
""")
private fun expandSnippet(@Language("Rust") before: String, @Language("Rust") after: String) =
checkByText(before.trimIndent(), after.trimIndent()) {
myFixture.performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)
}
private fun noSnippet(@Language("Rust") code: String) = expandSnippet(code, code)
}
| mit | 7414805473c2035522ee304ebff3d413 | 21.12605 | 98 | 0.48082 | 4.388333 | false | true | false | false |
dirkraft/cartograph | cartograph/src/main/kotlin/com/github/dirkraft/cartograph/connection_ext.kt | 1 | 958 | package com.github.dirkraft.cartograph
import java.sql.Connection
import java.sql.Statement
internal fun <R> Connection.execute(
sql: String, args: Collection<Any> = emptyList<Any>(), result: Statement.() -> R): R {
if (args.isEmpty()) {
val st = createStatement()
st.execute(sql)
return result(st)
} else {
// I don't know about this. This ensures some jdbc drivers to set up the statement to return generated keys
// (e.g. postgresql JDBC driver). It is highly convenient to work this way by default so it gets to go here.
val isInsOrUpd = sql.trim().substring(0, 6).toLowerCase().let { it == "insert" || it == "update" }
val ps = if (isInsOrUpd) {
prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
} else {
prepareStatement(sql)
}
ps.mapIn(args)
ps.execute()
return result(ps)
}
} | mit | bc8df3ebe04c7b2109443cb32813c180 | 33.555556 | 116 | 0.597077 | 4.042194 | false | false | false | false |
http4k/http4k | http4k-core/src/test/kotlin/org/http4k/core/RequestContextTest.kt | 1 | 874 | package org.http4k.core
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import java.util.UUID
class RequestContextTest {
@Test
fun `can set and get a typed value from a RequestContext`() {
val requestContext = RequestContext(UUID.randomUUID())
requestContext["foo"] = 123
assertThat(requestContext.get<Int>("foo"), equalTo(123))
}
@Test
fun `updating a value to null removes it`() {
val requestContext = RequestContext(UUID.randomUUID())
requestContext["foo"] = 123
requestContext["foo"] = null
assertThat(requestContext["foo"], absent<Int>())
}
@Test
fun `returns null when missing`() {
assertThat(RequestContext(UUID.randomUUID())["foo"], absent<Int>())
}
}
| apache-2.0 | d4a0354b1f1911e092193cf720fb2854 | 28.133333 | 75 | 0.675057 | 4.39196 | false | true | false | false |
http4k/http4k | http4k-aws/src/main/kotlin/org/http4k/aws/AwsCanonicalRequest.kt | 1 | 1763 | package org.http4k.aws
import org.http4k.core.Request
import org.http4k.core.Uri
import org.http4k.core.toParameters
import org.http4k.filter.CanonicalPayload
import org.http4k.urlEncoded
import java.util.Locale.getDefault
internal data class AwsCanonicalRequest(val value: String, val signedHeaders: String, val payloadHash: String) {
companion object {
fun of(request: Request, payload: CanonicalPayload): AwsCanonicalRequest {
val signedHeaders = request.signedHeaders()
val canonical = request.method.name +
"\n" +
request.uri.normalisedPath() +
"\n" +
request.canonicalQueryString() +
"\n" +
request.canonicalHeaders() +
"\n\n" +
signedHeaders +
"\n" +
payload.hash
return AwsCanonicalRequest(canonical, signedHeaders, payload.hash)
}
private fun Request.signedHeaders(): String =
headers.map { it.first.lowercase(getDefault()) }.sorted().joinToString(";")
private fun Request.canonicalHeaders(): String = headers
.map { it.first.lowercase(getDefault()) to it.second?.replace("\\s+", " ")?.trim() }
.map { it.first + ":" + it.second }
.sorted()
.joinToString("\n")
private fun Request.canonicalQueryString(): String =
uri.query.toParameters()
.map { (first, second) -> first.urlEncoded() + "=" + second?.urlEncoded().orEmpty() }
.sorted()
.joinToString("&")
private fun Uri.normalisedPath() = if (path.isBlank()) "/" else path.split("/").joinToString("/") { it.urlEncoded() }
}
}
| apache-2.0 | 5116af8e17be48639e0b131cbaf1f00c | 38.177778 | 125 | 0.577992 | 4.627297 | false | false | false | false |
martinlschumann/mal | kotlin/src/mal/stepA_mal.kt | 4 | 7116 | package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
"try*" -> return try_catch(ast, env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG((first as ISeq).nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
private fun try_catch(ast: MalList, env: Env): MalType =
try {
eval(ast.nth(1), env)
} catch (e: Exception) {
val thrown = if (e is MalException) e else MalException(e.message)
val symbol = (ast.nth(2) as MalList).nth(1) as MalSymbol
val catchBody = (ast.nth(2) as MalList).nth(2)
val catchEnv = Env(env)
catchEnv.set(symbol, thrown)
eval(catchBody, catchEnv)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*host-language*"), MalString("kotlin"))
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| mpl-2.0 | 137d633fa55d6f7ef73f359e5e8ee409 | 36.0625 | 197 | 0.527122 | 3.791156 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.