repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
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
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/utils/WaveHelper.kt
2
2574
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.utils import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.view.animation.DecelerateInterpolator import android.view.animation.LinearInterpolator import com.gelitenight.waveview.library.WaveView import java.util.* class WaveHelper(private val mWaveView: WaveView, private val lastLevelRatio: Float = 0f, private var lastShiftRatio: Float = 0f) { private var mAnimatorSet: AnimatorSet? = null init { initAnimation() } fun start() { mWaveView.isShowWave = true mAnimatorSet?.start() } private fun initAnimation() { val animators = ArrayList<Animator>() // horizontal animation. // wave waves infinitely. val waveShiftAnim1 = ObjectAnimator.ofFloat( mWaveView, "waveShiftRatio", lastShiftRatio, 1f) waveShiftAnim1.repeatCount = 1 waveShiftAnim1.duration = (1000f * (1f - lastShiftRatio)).toLong() waveShiftAnim1.interpolator = LinearInterpolator() animators.add(waveShiftAnim1) val waveShiftAnim2 = ObjectAnimator.ofFloat( mWaveView, "waveShiftRatio", 0f, 1f) waveShiftAnim2.repeatCount = ValueAnimator.INFINITE waveShiftAnim2.duration = 1000 waveShiftAnim2.startDelay = waveShiftAnim1.duration waveShiftAnim2.interpolator = LinearInterpolator() animators.add(waveShiftAnim2) // vertical animation. // water level increases from 0 to center of WaveView val waterLevelAnim = ObjectAnimator.ofFloat( mWaveView, "waterLevelRatio", lastLevelRatio, mWaveView.waterLevelRatio) waterLevelAnim.duration = 1000 waterLevelAnim.interpolator = DecelerateInterpolator() animators.add(waterLevelAnim) // amplitude animation. // wave grows big then grows small, repeatedly val amplitudeAnim = ObjectAnimator.ofFloat( mWaveView, "amplitudeRatio", 0.03f, 0.03f) amplitudeAnim.repeatCount = ValueAnimator.INFINITE amplitudeAnim.repeatMode = ValueAnimator.REVERSE amplitudeAnim.duration = 1000 amplitudeAnim.interpolator = LinearInterpolator() animators.add(amplitudeAnim) mAnimatorSet = AnimatorSet() mAnimatorSet!!.playTogether(animators) } fun cancel() { if (mAnimatorSet != null) mAnimatorSet!!.end() } }
gpl-3.0
c9f2af219f749e1326a48fe74a45b6cc
32.428571
131
0.693085
4.56383
false
false
false
false
JetBrains/anko
anko/library/generated/appcompat-v7/src/main/java/Properties.kt
4
1415
@file:JvmName("AppcompatV7PropertiesKt") package org.jetbrains.anko.appcompat.v7 import org.jetbrains.anko.* import org.jetbrains.anko.internals.AnkoInternals import kotlin.DeprecationLevel var android.support.v7.widget.Toolbar.logoResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setLogo(v) var android.support.v7.widget.Toolbar.logoDescriptionResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setLogoDescription(v) var android.support.v7.widget.Toolbar.navigationContentDescriptionResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setNavigationContentDescription(v) var android.support.v7.widget.Toolbar.navigationIconResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setNavigationIcon(v) var android.support.v7.widget.Toolbar.subtitleResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setSubtitle(v) var android.support.v7.widget.Toolbar.titleResource: Int @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter() set(v) = setTitle(v)
apache-2.0
adec6c178ddcf0cd6af346e5f98007dc
43.21875
105
0.778799
3.90884
false
false
false
false
CarrotCodes/Pellet
logging/src/main/kotlin/dev.pellet/logging/PelletSLF4JBridge.kt
1
6911
package dev.pellet.logging import org.slf4j.helpers.FormattingTuple import org.slf4j.helpers.MarkerIgnoringBase import org.slf4j.helpers.MessageFormatter public class PelletSLF4JBridge( name: String, private val level: PelletLogLevel ) : MarkerIgnoringBase() { private val backingLogger = pelletLogger(name) override fun isTraceEnabled(): Boolean { return level.value >= PelletLogLevel.TRACE.value } override fun trace(msg: String?) { if (!isTraceEnabled) { return } backingLogger.log(PelletLogLevel.TRACE) { msg ?: "" } } override fun trace(format: String?, arg: Any?) { if (!isTraceEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg) logFormattingTuple(PelletLogLevel.TRACE, formattingTuple) } override fun trace(format: String?, arg1: Any?, arg2: Any?) { if (!isTraceEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg1, arg2) logFormattingTuple(PelletLogLevel.TRACE, formattingTuple) } override fun trace(format: String?, vararg arguments: Any?) { if (!isTraceEnabled) { return } val formattingTuple = MessageFormatter.format(format, arguments) logFormattingTuple(PelletLogLevel.TRACE, formattingTuple) } override fun trace(msg: String?, t: Throwable?) { if (!isTraceEnabled) { return } log(PelletLogLevel.TRACE, msg, t) } override fun isDebugEnabled(): Boolean { return level.value >= PelletLogLevel.DEBUG.value } override fun debug(msg: String?) { if (!isDebugEnabled) { return } log(PelletLogLevel.DEBUG, msg, null) } override fun debug(format: String?, arg: Any?) { if (!isDebugEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg) logFormattingTuple(PelletLogLevel.DEBUG, formattingTuple) } override fun debug(format: String?, arg1: Any?, arg2: Any?) { if (!isDebugEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg1, arg2) logFormattingTuple(PelletLogLevel.DEBUG, formattingTuple) } override fun debug(format: String?, vararg arguments: Any?) { if (!isDebugEnabled) { return } val formattingTuple = MessageFormatter.format(format, arguments) logFormattingTuple(PelletLogLevel.DEBUG, formattingTuple) } override fun debug(msg: String?, t: Throwable?) { if (!isDebugEnabled) { return } log(PelletLogLevel.DEBUG, msg, t) } override fun isInfoEnabled(): Boolean { return level.value >= PelletLogLevel.INFO.value } override fun info(msg: String?) { if (!isInfoEnabled) { return } log(PelletLogLevel.INFO, msg, null) } override fun info(format: String?, arg: Any?) { if (!isInfoEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg) logFormattingTuple(PelletLogLevel.INFO, formattingTuple) } override fun info(format: String?, arg1: Any?, arg2: Any?) { if (!isInfoEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg1, arg2) logFormattingTuple(PelletLogLevel.INFO, formattingTuple) } override fun info(format: String?, vararg arguments: Any?) { if (!isInfoEnabled) { return } val formattingTuple = MessageFormatter.format(format, arguments) logFormattingTuple(PelletLogLevel.INFO, formattingTuple) } override fun info(msg: String?, t: Throwable?) { if (!isInfoEnabled) { return } log(PelletLogLevel.INFO, msg, t) } override fun isWarnEnabled(): Boolean { return level.value >= PelletLogLevel.WARN.value } override fun warn(msg: String?) { if (!isWarnEnabled) { return } log(PelletLogLevel.WARN, msg, null) } override fun warn(format: String?, arg: Any?) { if (!isWarnEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg) logFormattingTuple(PelletLogLevel.WARN, formattingTuple) } override fun warn(format: String?, vararg arguments: Any?) { if (!isWarnEnabled) { return } val formattingTuple = MessageFormatter.format(format, arguments) logFormattingTuple(PelletLogLevel.WARN, formattingTuple) } override fun warn(format: String?, arg1: Any?, arg2: Any?) { if (!isWarnEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg1, arg2) logFormattingTuple(PelletLogLevel.WARN, formattingTuple) } override fun warn(msg: String?, t: Throwable?) { if (!isWarnEnabled) { return } log(PelletLogLevel.WARN, msg, t) } override fun isErrorEnabled(): Boolean { return level.value >= PelletLogLevel.ERROR.value } override fun error(msg: String?) { if (!isErrorEnabled) { return } log(PelletLogLevel.ERROR, msg, null) } override fun error(format: String?, arg: Any?) { if (!isErrorEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg) logFormattingTuple(PelletLogLevel.ERROR, formattingTuple) } override fun error(format: String?, arg1: Any?, arg2: Any?) { if (!isErrorEnabled) { return } val formattingTuple = MessageFormatter.format(format, arg1, arg2) logFormattingTuple(PelletLogLevel.ERROR, formattingTuple) } override fun error(format: String?, vararg arguments: Any?) { if (!isErrorEnabled) { return } val formattingTuple = MessageFormatter.format(format, arguments) logFormattingTuple(PelletLogLevel.ERROR, formattingTuple) } override fun error(msg: String?, t: Throwable?) { if (!isErrorEnabled) { return } log(PelletLogLevel.ERROR, msg, t) } private fun logFormattingTuple( level: PelletLogLevel, formattingTuple: FormattingTuple ) { log(level, formattingTuple.message, formattingTuple.throwable) } private fun log( level: PelletLogLevel, message: String?, throwable: Throwable? ) { if (throwable != null) { backingLogger.log(level, throwable) { message ?: "" } } else { backingLogger.log(level) { message ?: "" } } } }
apache-2.0
73ce673e2b3b6830983f883b01464475
27.557851
73
0.604399
4.514043
false
false
false
false
Mauin/detekt
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/console/ComplexityReportGenerator.kt
1
2026
package io.gitlab.arturbosch.detekt.cli.console import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.PREFIX import io.gitlab.arturbosch.detekt.api.format class ComplexityReportGenerator(private val complexityMetric: ComplexityMetric) { private var numberOfSmells = 0 private var smellPerThousandLines = 0 private var mccPerThousandLines = 0 private var commentSourceRatio = 0 companion object Factory { fun create(detektion: Detektion): ComplexityReportGenerator = ComplexityReportGenerator(ComplexityMetric(detektion)) } fun generate(): String? { if (cannotGenerate()) return null return with(StringBuilder()) { append("Complexity Report:".format()) append("${complexityMetric.loc} lines of code (loc)".format(PREFIX)) append("${complexityMetric.sloc} source lines of code (sloc)".format(PREFIX)) append("${complexityMetric.lloc} logical lines of code (lloc)".format(PREFIX)) append("${complexityMetric.cloc} comment lines of code (cloc)".format(PREFIX)) append("${complexityMetric.mcc} McCabe complexity (mcc)".format(PREFIX)) append("$numberOfSmells number of total code smells".format(PREFIX)) append("$commentSourceRatio % comment source ratio".format(PREFIX)) append("$mccPerThousandLines mcc per 1000 lloc".format(PREFIX)) append("$smellPerThousandLines code smells per 1000 lloc".format(PREFIX)) toString() } } private fun cannotGenerate(): Boolean { return when { complexityMetric.mcc == null -> true complexityMetric.lloc == null || complexityMetric.lloc == 0 -> true complexityMetric.sloc == null || complexityMetric.sloc == 0 -> true complexityMetric.cloc == null -> true else -> { numberOfSmells = complexityMetric.findings.sumBy { it.value.size } smellPerThousandLines = numberOfSmells * 1000 / complexityMetric.lloc mccPerThousandLines = complexityMetric.mcc * 1000 / complexityMetric.lloc commentSourceRatio = complexityMetric.cloc * 100 / complexityMetric.sloc false } } } }
apache-2.0
cefab709aae9550487f1f96cf3595813
39.52
118
0.750247
4.247379
false
false
false
false
dlew/android-architecture-counter-sample
app/src/main/java/net/danlew/counter/ui/CounterViewModel.kt
1
1223
package net.danlew.counter.ui import android.app.Application import android.arch.lifecycle.AndroidViewModel import net.danlew.counter.CounterApplication import net.danlew.counter.data.AppDatabase import net.danlew.counter.data.Counter import javax.inject.Inject class CounterViewModel constructor(application: Application) : AndroidViewModel(application) { @Inject lateinit var db: AppDatabase init { (application as CounterApplication).appComponent.inject(this) } fun hasCounters() = db.counterModel().count() != 0 fun counters() = db.counterModel().counters() fun createCounter(name: String = "") = db.counterModel().createCounter(name) fun undoDelete(counter: Counter) = db.counterModel().insertOrUpdate(counter) fun modifyCount(counterId: Long, difference: Long) = db.counterModel().modifyCount(counterId, difference) fun modifyName(counterId: Long, name: String) = db.counterModel().modifyName(counterId, name) fun move(fromCounterId: Long, toCounterId: Long) = db.counterModel().move(fromCounterId, toCounterId) fun delete(counterId: Long): Counter? { db.counterModel().counter(counterId)?.let { db.counterModel().delete(it) return it } return null } }
apache-2.0
59d42148458c48a588efe98391a1857a
29.6
107
0.753884
3.858044
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/java/za/org/grassroot2/view/adapter/GroupSelectionAdapter.kt
1
1886
package za.org.grassroot2.view.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.jakewharton.rxbinding2.view.RxView import butterknife.BindView import butterknife.ButterKnife import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.group_item_row.view.* import za.org.grassroot2.R import za.org.grassroot2.model.Group import za.org.grassroot2.model.SelectableItem /** * Created by luke on 2017/08/19. */ class GroupSelectionAdapter(private var data: List<SelectableItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val viewClickSubject = PublishSubject.create<Group>() val viewClickObservable: Observable<Group> get() = viewClickSubject override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = SelectableGroupViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.group_item_row, parent, false)) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = data[position] bindGroup(holder as SelectableGroupViewHolder, item) } private fun bindGroup(holder: SelectableGroupViewHolder, item: SelectableItem) { holder.name.text = item.name RxView.clicks(holder.name) .map { o -> item as Group } .subscribe(viewClickSubject) } override fun getItemCount(): Int { return data.size } fun updateData(data: List<SelectableItem>) { this.data = data notifyDataSetChanged() } internal class SelectableGroupViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { var name: TextView = itemView.text } }
bsd-3-clause
985c2d8397f06561feb6b3a3144bdc55
31.517241
122
0.73913
4.458629
false
false
false
false
arturbosch/detekt
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/suppressors/Builders.kt
1
1437
package io.gitlab.arturbosch.detekt.core.suppressors import io.github.detekt.psi.FilePath import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.ConfigAware import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Location import io.gitlab.arturbosch.detekt.api.RuleId import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.SourceLocation import io.gitlab.arturbosch.detekt.api.TextLocation import io.gitlab.arturbosch.detekt.test.TestConfig import org.jetbrains.kotlin.psi.KtElement import java.nio.file.Paths internal fun buildFinding(element: KtElement?): Finding = CodeSmell( issue = Issue("RuleName", Severity.CodeSmell, "", Debt.FIVE_MINS), entity = element?.let { Entity.from(element) } ?: buildEmptyEntity(), message = "", ) private fun buildEmptyEntity(): Entity = Entity( name = "", signature = "", location = Location(SourceLocation(0, 0), TextLocation(0, 0), FilePath.fromAbsolute(Paths.get("/"))), ktElement = null, ) internal fun buildConfigAware( vararg pairs: Pair<String, Any> ) = object : ConfigAware { override val ruleId: RuleId = "ruleId" override val ruleSetConfig: Config = TestConfig(*pairs) }
apache-2.0
3b0c4425a8202a6b9b05e5aa3a744f50
36.815789
105
0.771747
3.801587
false
true
false
false
rsiebert/TVHClient
htsp/src/main/java/org/tvheadend/api/ConnectionStateResult.kt
1
1270
package org.tvheadend.api import android.os.Parcelable import kotlinx.parcelize.Parcelize sealed class ConnectionStateResult : Parcelable { @Parcelize data class Idle(val message: String = "") : ConnectionStateResult(), Parcelable @Parcelize data class Closed(val message: String = "") : ConnectionStateResult(), Parcelable @Parcelize data class Connecting(val message: String = "") : ConnectionStateResult(), Parcelable @Parcelize data class Connected(val message: String = "") : ConnectionStateResult(), Parcelable @Parcelize data class Failed(val reason: ConnectionFailureReason) : ConnectionStateResult(), Parcelable } sealed class ConnectionFailureReason : Parcelable { @Parcelize data class Interrupted(val message: String = "") : ConnectionFailureReason(), Parcelable @Parcelize data class UnresolvedAddress(val message: String = "") : ConnectionFailureReason(), Parcelable @Parcelize data class ConnectingToServer(val message: String = "") : ConnectionFailureReason(), Parcelable @Parcelize data class SocketException(val message: String = "") : ConnectionFailureReason(), Parcelable @Parcelize data class Other(val message: String = "") : ConnectionFailureReason(), Parcelable }
gpl-3.0
3d16fc58b1f96dc095398fae928014aa
41.366667
99
0.740945
5.404255
false
false
false
false
material-components/material-components-android-examples
Owl/app/src/main/java/com/materialstudies/owl/ui/lessons/StepsAdapter.kt
1
2461
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.owl.ui.lessons import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.materialstudies.owl.R import com.materialstudies.owl.databinding.StepItemBinding import com.materialstudies.owl.model.Lesson class StepsAdapter( lessons: List<Lesson>, context: Context ) : ListAdapter<Step, StepViewHolder>(StepDiff) { init { val steps = lessons.mapIndexed { step, _ -> Step( context.getString(R.string.step_num, step + 1), when (step % 3) { 0 -> context.getString(R.string.step_0) 1 -> context.getString(R.string.step_1) else -> context.getString(R.string.step_2) } ) } submitList(steps) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StepViewHolder { val binding = StepItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return StepViewHolder(binding) } override fun onBindViewHolder(holder: StepViewHolder, position: Int) { holder.bind(getItem(position)) } } class StepViewHolder(private val binding: StepItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(step: Step) { binding.run { this.step = step executePendingBindings() } } } data class Step( val title: String, val body: String ) object StepDiff : DiffUtil.ItemCallback<Step>() { override fun areItemsTheSame(oldItem: Step, newItem: Step) = oldItem.title == newItem.title override fun areContentsTheSame(oldItem: Step, newItem: Step) = oldItem == newItem }
apache-2.0
5b710c20a4bed094b1b1d0912ef65ee1
31.381579
100
0.6859
4.363475
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/forge/reflection/reference/ReflectedMethodReference.kt
1
7064
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.reflection.reference import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findModule import com.demonwav.mcdev.util.qualifiedMemberReference import com.demonwav.mcdev.util.toTypedArray import com.intellij.codeInsight.completion.JavaLookupElementBuilder import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassObjectAccessExpression import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult import com.intellij.psi.PsiExpressionList import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceBase import com.intellij.psi.PsiReferenceProvider import com.intellij.psi.PsiSubstitutor import com.intellij.psi.ResolveResult import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.ProcessingContext object ReflectedMethodReference : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { // The pattern for this provider should only match method params, but better be safe if (element.parent !is PsiExpressionList) { return arrayOf() } return arrayOf(Reference(element as PsiLiteral)) } class Reference(element: PsiLiteral) : PsiReferenceBase.Poly<PsiLiteral>(element) { val methodName get() = element.constantStringValue ?: "" val expressionList get() = element.parent as PsiExpressionList override fun getVariants(): Array<Any> { val typeClass = findReferencedClass() ?: return arrayOf() return typeClass.allMethods .asSequence() .filter { !it.hasModifier(JvmModifier.PUBLIC) } .map { method -> JavaLookupElementBuilder.forMethod(method, PsiSubstitutor.EMPTY).withInsertHandler { context, _ -> val literal = context.file.findElementAt(context.startOffset)?.parent as? PsiLiteral ?: return@withInsertHandler val params = literal.parent as? PsiExpressionList ?: return@withInsertHandler val srgManager = literal.findModule()?.let { MinecraftFacet.getInstance(it) } ?.getModuleOfType(McpModuleType)?.srgManager val srgMap = srgManager?.srgMapNow val signature = method.getSignature(PsiSubstitutor.EMPTY) val returnType = method.returnType?.let { TypeConversionUtil.erasure(it).canonicalText } ?: return@withInsertHandler val paramTypes = MethodSignatureUtil.calcErasedParameterTypes(signature) .map { it.canonicalText } val memberRef = method.qualifiedMemberReference val srgMethod = srgMap?.getSrgMethod(memberRef) ?: memberRef context.setLaterRunnable { // Commit changes made by code completion context.commitDocument() // Run command to replace PsiElement CommandProcessor.getInstance().runUndoTransparentAction { runWriteAction { val elementFactory = JavaPsiFacade.getElementFactory(context.project) val srgLiteral = elementFactory.createExpressionFromText( "\"${srgMethod.name}\"", params ) if (params.expressionCount > 1) { params.expressions[1].replace(srgLiteral) } else { params.add(srgLiteral) } if (params.expressionCount > 2) { params.deleteChildRange(params.expressions[2], params.expressions.last()) } val returnTypeRef = elementFactory.createExpressionFromText( "$returnType.class", params ) params.add(returnTypeRef) for (paramType in paramTypes) { val paramTypeRef = elementFactory.createExpressionFromText( "$paramType.class", params ) params.add(paramTypeRef) } JavaCodeStyleManager.getInstance(context.project).shortenClassReferences(params) CodeStyleManager.getInstance(context.project).reformat(params, true) context.editor.caretModel.moveToOffset(params.textRange.endOffset) } } } } } .toTypedArray() } override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { val typeClass = findReferencedClass() ?: return arrayOf() val name = methodName val srgManager = element.findModule()?.let { MinecraftFacet.getInstance(it) } ?.getModuleOfType(McpModuleType)?.srgManager val srgMap = srgManager?.srgMapNow val mcpName = srgMap?.mapMcpToSrgName(name) ?: name return typeClass.allMethods.asSequence() .filter { it.name == mcpName } .map(::PsiElementResolveResult) .toTypedArray() } private fun findReferencedClass(): PsiClass? { val callParams = element.parent as? PsiExpressionList val classRef = callParams?.expressions?.first() as? PsiClassObjectAccessExpression val type = classRef?.operand?.type as? PsiClassType return type?.resolve() } } }
mit
c750c36fbd2b69ec4e6a1cf594db0be1
45.473684
118
0.570074
6.39276
false
false
false
false
Karumi/Shot
shot-android/src/main/java/com/karumi/shot/compose/ComposeScreenshotRunner.kt
1
679
package com.karumi.shot.compose import android.app.Instrumentation import com.karumi.shot.permissions.AndroidStoragePermissions class ComposeScreenshotRunner { companion object { var composeScreenshot: ComposeScreenshot? = null fun onCreate(instrumentation: Instrumentation) { composeScreenshot = ComposeScreenshot( session = ScreenshotTestSession(), saver = ScreenshotSaver(instrumentation.context.packageName, SemanticsNodeBitmapGenerator()), permissions = AndroidStoragePermissions(instrumentation) ) } fun onDestroy() = composeScreenshot?.saveMetadata() } }
apache-2.0
8fdb5e3d74f5778cf815afdbf9d4876e
31.333333
109
0.696613
5.904348
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/input/KeysEvents.kt
1
4993
package com.soywiz.korge.input import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.kmem.* import com.soywiz.korev.* import com.soywiz.korge.component.* import com.soywiz.korge.time.* import com.soywiz.korge.view.* import com.soywiz.korio.async.* import com.soywiz.korio.lang.* import kotlinx.coroutines.* import kotlin.reflect.* class KeysEvents(override val view: View) : KeyComponent { @PublishedApi internal lateinit var views: Views @PublishedApi internal val coroutineContext get() = views.coroutineContext private val onKeyDown = AsyncSignal<KeyEvent>() private val onKeyUp = AsyncSignal<KeyEvent>() private val onKeyTyped = AsyncSignal<KeyEvent>() fun KeyEvent.setFromKeys(key: Key, keys: InputKeys, dt: TimeSpan, type: KeyEvent.Type = KeyEvent.Type.DOWN): KeyEvent { this.type = type this.key = key this.keyCode = key.ordinal this.shift = keys.shift this.ctrl = keys.ctrl this.alt = keys.alt this.meta = keys.meta this.deltaTime = dt return this } /** Executes [callback] on each frame when [key] is being pressed. When [dt] is provided, the [callback] is executed at that [dt] steps. */ fun downFrame(key: Key, dt: TimeSpan = TimeSpan.NIL, callback: (ke: KeyEvent) -> Unit): Cancellable { val ke = KeyEvent() return view.addOptFixedUpdater(dt) { dt -> if (::views.isInitialized) { val keys = views.keys if (keys[key]) { callback(ke.setFromKeys(key, keys, dt)) } } //if (view.input) } } fun justDown(key: Key, callback: (ke: KeyEvent) -> Unit): Cancellable { val ke = KeyEvent() return view.addUpdaterWithViews { views, dt -> val keys = views.keys if (keys.justPressed(key)) { callback(ke.setFromKeys(key, keys, dt)) } //if (view.input) } } fun downRepeating(key: Key, maxDelay: TimeSpan = 500.milliseconds, minDelay: TimeSpan = 100.milliseconds, delaySteps: Int = 6, callback: suspend (ke: KeyEvent) -> Unit): Cancellable { val ke = KeyEvent() var currentStep = 0 var remainingTime = 0.milliseconds return view.addUpdaterWithViews { views, dt -> val keys = views.keys if (keys[key]) { remainingTime -= dt if (remainingTime < 0.milliseconds) { val ratio = (currentStep.toDouble() / delaySteps.toDouble()).clamp01() currentStep++ remainingTime += ratio.interpolate(maxDelay, minDelay) launchImmediately(views.coroutineContext) { callback(ke.setFromKeys(key, views.keys, dt)) } } } else { currentStep = 0 remainingTime = 0.milliseconds } } } fun down(callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyDown { e -> callback(e) } fun down(key: Key, callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyDown { e -> if (e.key == key) callback(e) } fun downWithModifiers(key: Key, ctrl: Boolean? = null, shift: Boolean? = null, alt: Boolean? = null, meta: Boolean? = null, callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyDown { e -> if (e.key == key && match(ctrl, e.ctrl) && match(shift, e.shift) && match(alt, e.alt) && match(meta, e.meta)) callback(e) } private fun match(pattern: Boolean?, value: Boolean) = (pattern == null || value == pattern) fun up(callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyUp { e -> callback(e) } fun up(key: Key, callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyUp { e -> if (e.key == key) callback(e) } fun typed(callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyTyped { e -> callback(e) } fun typed(key: Key, callback: suspend (key: KeyEvent) -> Unit): Closeable = onKeyTyped { e -> if (e.key == key) callback(e) } override fun Views.onKeyEvent(event: KeyEvent) { [email protected] = this@onKeyEvent when (event.type) { KeyEvent.Type.TYPE -> launchImmediately(views.coroutineContext) { onKeyTyped.invoke(event) } KeyEvent.Type.DOWN -> launchImmediately(views.coroutineContext) { onKeyDown.invoke(event) } KeyEvent.Type.UP -> launchImmediately(views.coroutineContext) { onKeyUp.invoke(event) } } } } val View.keys by Extra.PropertyThis<View, KeysEvents> { this.getOrCreateComponentKey<KeysEvents> { KeysEvents(this) } } inline fun <T> View.keys(callback: KeysEvents.() -> T): T = keys.run(callback) suspend fun KeysEvents.waitUp(key: Key): KeyEvent = waitUp { it.key == key } suspend fun KeysEvents.waitUp(filter: (key: KeyEvent) -> Boolean = { true }): KeyEvent = waitSubscriberCloseable { callback -> up { if (filter(it)) callback(it) } }
apache-2.0
cbb7e68cd8b693c1ecb46f61d6dd1f6c
42.417391
200
0.617064
3.978486
false
false
false
false
pr0ves/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/tasks/UpdateProfile.kt
2
5896
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import POGOProtos.Networking.Responses.LevelUpRewardsResponseOuterClass import ink.abb.pogo.api.request.CheckAwardedBadges import ink.abb.pogo.api.request.GetInventory import ink.abb.pogo.api.request.LevelUpRewards import ink.abb.pogo.scraper.* import ink.abb.pogo.scraper.util.Log import java.text.DecimalFormat import java.text.NumberFormat import java.time.LocalDateTime import java.time.temporal.ChronoUnit import java.util.* import java.util.concurrent.atomic.AtomicInteger class UpdateProfile : Task { var lastLevelCheck: Int = 0 override fun run(bot: Bot, ctx: Context, settings: Settings) { bot.api.queueRequest(GetInventory().withLastTimestampMs(0)).subscribe { val curLevelXP = bot.api.inventory.playerStats.experience - requiredXp[bot.api.inventory.playerStats.level - 1] val nextXP = if (bot.api.inventory.playerStats.level == requiredXp.size) { curLevelXP } else { (requiredXp[bot.api.inventory.playerStats.level] - requiredXp[bot.api.inventory.playerStats.level - 1]).toLong() } val ratio = DecimalFormat("#0.00").format(curLevelXP.toDouble() / nextXP.toDouble() * 100.0) val timeDiff = ChronoUnit.MINUTES.between(ctx.startTime, LocalDateTime.now()) val xpPerHour: Long = if (timeDiff != 0L) { (bot.api.inventory.playerStats.experience - ctx.startXp.get()) / timeDiff * 60 } else { 0 } val nextLevel: String = if (xpPerHour != 0L) { "${DecimalFormat("#0").format((nextXP.toDouble() - curLevelXP.toDouble()) / xpPerHour.toDouble())}h${Math.round(((nextXP.toDouble() - curLevelXP.toDouble()) / xpPerHour.toDouble()) % 1 * 60)}m" } else { "Unknown" } Log.magenta("Profile update: ${bot.api.inventory.playerStats.experience} XP on LVL ${bot.api.inventory.playerStats.level}; $curLevelXP/$nextXP ($ratio%) to LVL ${bot.api.inventory.playerStats.level + 1}") Log.magenta("XP gain: ${NumberFormat.getInstance().format(bot.api.inventory.playerStats.experience - ctx.startXp.get())} XP in ${ChronoUnit.MINUTES.between(ctx.startTime, LocalDateTime.now())} mins; " + "XP rate: ${NumberFormat.getInstance().format(xpPerHour)}/hr; Next level in: $nextLevel") Log.magenta("Pokemon caught/transferred: ${ctx.pokemonStats.first.get()}/${ctx.pokemonStats.second.get()}; " + "Pokemon caught from lures: ${ctx.luredPokemonStats.get()}; " + "Items caught/dropped: ${ctx.itemStats.first.get()}/${ctx.itemStats.second.get()};") Log.magenta("Pokebank ${bot.api.inventory.pokemon.size + bot.api.inventory.eggs.size}/${bot.api.playerData.maxPokemonStorage}; " + "Stardust ${bot.api.inventory.currencies.getOrPut("STARDUST", { AtomicInteger(0) }).get()}; " + "Inventory ${bot.api.inventory.size}/${bot.api.playerData.maxItemStorage}" ) if (bot.api.inventory.pokemon.size + bot.api.inventory.eggs.size < bot.api.playerData.maxPokemonStorage && ctx.pokemonInventoryFullStatus.get()) ctx.pokemonInventoryFullStatus.set(false) else if (bot.api.inventory.pokemon.size + bot.api.inventory.eggs.size >= bot.api.playerData.maxPokemonStorage && !ctx.pokemonInventoryFullStatus.get()) ctx.pokemonInventoryFullStatus.set(true) if (settings.catchPokemon && ctx.pokemonInventoryFullStatus.get()) Log.red("Pokemon inventory is full, not catching!") ctx.server.sendProfile() } for (i in (lastLevelCheck + 1)..bot.api.inventory.playerStats.level) { //Log.magenta("Accepting rewards for level $i...") bot.api.queueRequest(LevelUpRewards().withLevel(i)).subscribe { val result = it.response if (result.result == LevelUpRewardsResponseOuterClass.LevelUpRewardsResponse.Result.AWARDED_ALREADY) { if (i > lastLevelCheck) { //Log.magenta("Already accepted awards for level ${i}, updating $lastLevelCheck = $i") lastLevelCheck = i } return@subscribe } var message = "Accepting rewards for level $i" val sb_rewards = StringJoiner(", ") for (reward in result.itemsAwardedList) { sb_rewards.add("${reward.itemCount}x ${reward.itemId.name}") } message += "; Rewards: [$sb_rewards]" if (result.itemsUnlockedCount > 0) { val sb_unlocks = StringJoiner(", ") for (item in result.itemsUnlockedList) { sb_unlocks.add("${item.name}") } message += "; Unlocks: [$sb_unlocks]" } Log.magenta(message) if (i > lastLevelCheck) { lastLevelCheck = i } } } bot.api.queueRequest(CheckAwardedBadges()).subscribe { val result = it.response result.awardedBadgesList.forEach { // TODO: Does not work?! /*bot.api.queueRequest(EquipBadge().withBadgeType(it)).subscribe { println(it.response.toString()) }*/ } } } }
gpl-3.0
ea90941b5c9e262854c21b61a472ebef
50.269565
216
0.605665
4.238677
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/parser/SvnServerParser.kt
1
8681
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.parser import svnserver.parser.token.* import java.io.EOFException import java.io.IOException import java.io.InputStream import java.nio.charset.StandardCharsets import kotlin.math.max /** * Интерфейс для чтения токенов из потока. * * * http://svn.apache.org/repos/asf/subversion/trunk/subversion/libsvn_ra_svn/protocol * * @author Artem V. Navrotskiy <[email protected]> */ class SvnServerParser constructor(private val stream: InputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE) { var depth: Int = 0 private set private val buffer: ByteArray = ByteArray(max(1, bufferSize)) private var offset: Int = 0 private var limit: Int = 0 @Throws(IOException::class) fun readText(): String { return readToken(TextToken::class.java).text } @Throws(IOException::class) fun readNumber(): Int { return readToken(NumberToken::class.java).number } /** * Чтение элемента указанного типа из потока. * * @param tokenType Тип элемента. * @param <T> Тип элемента. * @return Прочитанный элемент. </T> */ @Throws(IOException::class) fun <T : SvnServerToken> readToken(tokenType: Class<T>): T { val token: SvnServerToken = readToken() if (!tokenType.isInstance(token)) { throw IOException("Unexpected token: " + token + " (expected: " + tokenType.name + ')') } return token as T } /** * Чтение элемента списка из потока. * * @param tokenType Тип элемента. * @param <T> Тип элемента. * @return Прочитанный элемент. </T> */ @Throws(IOException::class) fun <T : SvnServerToken> readItem(tokenType: Class<T>): T? { val token: SvnServerToken = readToken() if ((ListEndToken.instance == token)) { return null } if (!tokenType.isInstance(token)) { throw IOException("Unexpected token: " + token + " (expected: " + tokenType.name + ')') } return token as T } /** * Чтение элемента из потока. * * @return Возвращает элемент из потока. Если элемента нет - возвращает null. */ @Throws(IOException::class) fun readToken(): SvnServerToken { val read: Byte = skipSpaces() if (read == '('.code.toByte()) { depth++ return ListBeginToken.instance } if (read == ')'.code.toByte()) { depth-- if (depth < 0) { throw IOException("Unexpect end of list token.") } return ListEndToken.instance } // Чтение чисел и строк. if (isDigit(read.toInt())) { return readNumberToken(read) } // Обычная строчка. if (isAlpha(read.toInt())) { return readWord() } throw IOException("Unexpected character in stream: $read (need 'a'..'z', 'A'..'Z', '0'..'9', ' ' or '\\n')") } @Throws(IOException::class) private fun readNumberToken(first: Byte): SvnServerToken { var result: Int = first - '0'.code.toByte() while (true) { while (offset < limit) { val data: Byte = buffer[offset] offset++ if ((data < '0'.code.toByte()) || (data > '9'.code.toByte())) { if (data == ':'.code.toByte()) { return readString(result) } if (isSpace(data.toInt())) { return NumberToken(result) } throw IOException("Unexpected character in stream: $data (need ' ', '\\n' or ':')") } result = result * 10 + (data - '0'.code.toByte()) } if (limit < 0) { throw EOFException() } offset = 0 limit = stream.read(buffer) } } @Throws(IOException::class) private fun skipSpaces(): Byte { while (true) { while (offset < limit) { val data: Byte = buffer[offset] offset++ if (!isSpace(data.toInt())) { return data } } if (limit < 0) { throw EOFException() } offset = 0 limit = stream.read(buffer) } } @Throws(IOException::class) private fun readString(length: Int): StringToken { if (length >= MAX_BUFFER_SIZE) { throw IOException("Data is too long. Buffer overflow: " + buffer.size) } if (limit < 0) { throw EOFException() } val token = ByteArray(length) if (length <= limit - offset) { System.arraycopy(buffer, offset, token, 0, length) offset += length } else { var position: Int = limit - offset System.arraycopy(buffer, offset, token, 0, position) limit = 0 offset = 0 while (position < length) { val size: Int = stream.read(token, position, length - position) if (size < 0) { limit = -1 throw EOFException() } position += size } } return StringToken(token.copyOf(length)) } @Throws(IOException::class) private fun readWord(): WordToken { val begin: Int = offset - 1 while (offset < limit) { val data: Byte = buffer[offset] offset++ if (isSpace(data.toInt())) { return WordToken(String(buffer, begin, offset - begin - 1, StandardCharsets.US_ASCII)) } if (!(isAlpha(data.toInt()) || isDigit(data.toInt()) || (data == '-'.code.toByte()))) { throw IOException("Unexpected character in stream: $data (need 'a'..'z', 'A'..'Z', '0'..'9' or '-')") } } System.arraycopy(buffer, begin, buffer, 0, limit - begin) limit = offset - begin offset = limit while (limit < buffer.size) { val size: Int = stream.read(buffer, limit, buffer.size - limit) if (size < 0) { throw EOFException() } limit += size while (offset < limit) { val data: Byte = buffer[offset] offset++ if (isSpace(data.toInt())) { return WordToken(String(buffer, 0, offset - 1, StandardCharsets.US_ASCII)) } if (!(isAlpha(data.toInt()) || isDigit(data.toInt()) || (data == '-'.code.toByte()))) { throw IOException("Unexpected character in stream: $data (need 'a'..'z', 'A'..'Z', '0'..'9' or '-')") } } } throw IOException("Data is too long. Buffer overflow: " + buffer.size) } @Throws(IOException::class) fun skipItems() { var depth = 0 while (depth >= 0) { val token: SvnServerToken = readToken(SvnServerToken::class.java) if ((ListBeginToken.instance == token)) { depth++ } if ((ListEndToken.instance == token)) { depth-- } } } companion object { private const val DEFAULT_BUFFER_SIZE: Int = 32 * 1024 // Buffer size limit for out-of-memory prevention. private const val MAX_BUFFER_SIZE: Int = 10 * 1024 * 1024 private fun isSpace(data: Int): Boolean { return ((data == ' '.code) || (data == '\n'.code)) } private fun isDigit(data: Int): Boolean { return (data >= '0'.code && data <= '9'.code) } private fun isAlpha(data: Int): Boolean { return ((data >= 'a'.code && data <= 'z'.code) || (data >= 'A'.code && data <= 'Z'.code)) } } }
gpl-2.0
80e8b594c1d9e81686977fbda013885f
32.738956
121
0.515653
4.156853
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/intentions/IntroduceTableAliasIntention.kt
1
3210
package app.cash.sqldelight.intellij.intentions import app.cash.sqldelight.core.lang.util.findChildrenOfType import com.alecstrong.sql.psi.core.psi.SqlExpr import com.alecstrong.sql.psi.core.psi.SqlSelectStmt import com.alecstrong.sql.psi.core.psi.SqlTableAlias import com.alecstrong.sql.psi.core.psi.SqlTableName import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentOfType internal class IntroduceTableAliasIntention : BaseElementAtCaretIntentionAction() { private val regex = "(?=\\p{Upper})|(_)".toRegex() override fun getFamilyName(): String { return INTENTIONS_FAMILY_NAME_REFACTORINGS } override fun getText(): String { return "Introduce table alias" } override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { val tableName = element.parentOfType<SqlTableName>(true) ?: return false if (tableName.parent is SqlExpr) { return false } val columnAlias = PsiTreeUtil.getNextSiblingOfType(tableName, SqlTableAlias::class.java) if (columnAlias != null) { return false } val sqlSelectStmt = tableName.parentOfType<SqlSelectStmt>() ?: return false return sqlSelectStmt.resultColumnList.none { it.textMatches("*") } } override fun invoke(project: Project, editor: Editor, element: PsiElement) { val sqlTableName = element.parentOfType<SqlTableName>(true) ?: return val sqlSelectStmt = sqlTableName.parentOfType<SqlSelectStmt>() ?: return val tableName = sqlTableName.name val aliasVariants = listOf( tableName.first().toString(), tableName.split(regex) .filter(String::isNotBlank) .joinToString("") { it.first().toLowerCase().toString() }, ) .distinct() val document = editor.document val tableNameTextRange = sqlTableName.textRange val tableNameRangeMarker = document.createRangeMarker(tableNameTextRange) val tableReferenceMarkers = sqlSelectStmt.findChildrenOfType<SqlTableName>() .filter { it.textMatches(tableName) && !it.textRange.equals(tableNameTextRange) } .map { document.createRangeMarker(it.textRange) } val callback = { alias: String -> WriteCommandAction.runWriteCommandAction(project) { document.replaceString( tableNameRangeMarker.startOffset, tableNameRangeMarker.endOffset, "$tableName $alias", ) tableReferenceMarkers.forEach { rangeMarker -> document.replaceString(rangeMarker.startOffset, rangeMarker.endOffset, alias) } } } if (aliasVariants.size == 1) { callback(aliasVariants.first()) } else { JBPopupFactory.getInstance() .createPopupChooserBuilder(aliasVariants) .setMovable(true) .setResizable(true) .setItemChosenCallback(callback) .createPopup() .showInBestPositionFor(editor) } } }
apache-2.0
feb420ded82d18032a92063d21189dc2
35.477273
92
0.724611
4.605452
false
false
false
false
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/EmptyGroovyResolveResult.kt
13
1273
/* * 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.plugins.groovy.lang.psi.api import com.intellij.psi.PsiElement import com.intellij.psi.PsiSubstitutor object EmptyGroovyResolveResult : GroovyResolveResult { override fun getElement(): PsiElement? = null override fun isApplicable(): Boolean = false override fun isAccessible(): Boolean = false override fun getCurrentFileResolveContext(): PsiElement? = null override fun isStaticsOK(): Boolean = true override fun getSubstitutor(): PsiSubstitutor = PsiSubstitutor.EMPTY override fun isValidResult(): Boolean = false override fun isInvokedOnProperty(): Boolean = false override fun getSpreadState(): SpreadState? = null }
apache-2.0
9db69b744222b1997decc62d018111be
30.825
75
0.759623
4.546429
false
false
false
false
slartus/4pdaClient-plus
topic/topic-data/src/main/java/org/softeg/slartus/forpdaplus/topic/data/screens/attachments/RemoteTopicAttachmentsDataSource.kt
1
1095
package org.softeg.slartus.forpdaplus.topic.data.screens.attachments import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.softeg.slartus.forpdaplus.core.interfaces.ParseFactory import org.softeg.slartus.forpdaplus.core.services.AppHttpClient import org.softeg.slartus.forpdaplus.topic.data.screens.attachments.models.TopicAttachmentResponse import org.softeg.slartus.hosthelper.HostHelper.Companion.host import javax.inject.Inject class RemoteTopicAttachmentsDataSource @Inject constructor( private val httpClient: AppHttpClient, private val parseFactory: ParseFactory ) { suspend fun fetchTopicAttachments( topicId: String, resultParserId: String ): List<TopicAttachmentResponse>? = withContext(Dispatchers.IO) { val url = "https://${host}/forum/index.php?act=attach&code=showtopic&tid=$topicId" val response = httpClient.performGet(url) parseFactory.parse<List<TopicAttachmentResponse>>( url = url, body = response, resultParserId = resultParserId ) } }
apache-2.0
854746709becbb13d09f8fb821c50514
39.592593
98
0.757078
4.39759
false
false
false
false
hypercube1024/kotlin_test
src/main/kotlin/com/mykotlin/TestBuildSequence.kt
1
988
package com.mykotlin import kotlin.coroutines.experimental.buildSequence fun main(args: Array<String>) { val seq = buildSequence { for (i in 1..5) { // yield a square of i yield(i * i) } // yield a range yieldAll(26..28) } // print the sequence println(seq.map { "map -> $it" }.toList()) val lazySeq = buildSequence { print("START ") for (i in 1..5) { yield(i) print("STEP ") } print("END") } // Print the first three elements of the sequence lazySeq.take(3).forEach { print("$it ") } println() println(testFibonacci(8)) } fun testFibonacci(i: Int): List<Int> { val fibonacciSeq = buildSequence { var a = 0 var b = 1 yield(1) while (true) { yield(a + b) val tmp = a + b a = b b = tmp } } return fibonacciSeq.take(i).toList() }
apache-2.0
1b6c4075ca59fd56d800ec4f86d3327d
19.163265
53
0.491903
3.829457
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/setup/IntroFragment.kt
2
2659
package com.habitrpg.android.habitica.ui.fragments.setup import android.graphics.drawable.Drawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentIntroBinding import com.habitrpg.android.habitica.ui.fragments.BaseFragment class IntroFragment : BaseFragment<FragmentIntroBinding>() { override var binding: FragmentIntroBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentIntroBinding { return FragmentIntroBinding.inflate(inflater, container, false) } private var image: Drawable? = null private var titleImage: Drawable? = null private var subtitle: String? = null private var title: String? = null private var description: String? = null private var backgroundColor: Int? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (this.image != null) { binding?.imageView?.setImageDrawable(this.image) } if (this.titleImage != null) { binding?.titleImageView?.setImageDrawable(this.titleImage) } if (this.subtitle != null) { binding?.subtitleTextView?.text = this.subtitle } if (this.title != null) { binding?.titleTextView?.text = this.title } if (this.description != null) { binding?.descriptionTextView?.text = this.description } backgroundColor?.let { binding?.containerView?.setBackgroundColor(it) } } override fun injectFragment(component: UserComponent) { component.inject(this) } fun setImage(image: Drawable?) { this.image = image if (image != null) { binding?.imageView?.setImageDrawable(image) } } fun setTitleImage(image: Drawable?) { this.titleImage = image binding?.titleImageView?.setImageDrawable(image) } fun setSubtitle(text: String?) { this.subtitle = text binding?.subtitleTextView?.text = text } fun setTitle(text: String?) { this.title = text binding?.titleTextView?.text = text } fun setDescription(text: String?) { this.description = text binding?.descriptionTextView?.text = text } fun setBackgroundColor(color: Int) { this.backgroundColor = color binding?.containerView?.setBackgroundColor(color) } }
gpl-3.0
41cd0e57f1e642f196e75c9738c9f5c2
28.544444
103
0.664536
4.790991
false
false
false
false
androidx/androidx
core/core-ktx/src/main/java/androidx/core/view/ViewGroup.kt
3
5811
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") // Aliases to other public API. package androidx.core.view import android.annotation.SuppressLint import android.view.View import android.view.ViewGroup import androidx.annotation.Px import androidx.annotation.RequiresApi /** * Returns the view at [index]. * * @throws IndexOutOfBoundsException if index is less than 0 or greater than or equal to the count. */ public operator fun ViewGroup.get(index: Int): View = getChildAt(index) ?: throw IndexOutOfBoundsException("Index: $index, Size: $childCount") /** Returns `true` if [view] is found in this view group. */ public inline operator fun ViewGroup.contains(view: View): Boolean = indexOfChild(view) != -1 /** Adds [view] to this view group. */ public inline operator fun ViewGroup.plusAssign(view: View): Unit = addView(view) /** Removes [view] from this view group. */ public inline operator fun ViewGroup.minusAssign(view: View): Unit = removeView(view) /** Returns the number of views in this view group. */ public inline val ViewGroup.size: Int get() = childCount /** Returns true if this view group contains no views. */ public inline fun ViewGroup.isEmpty(): Boolean = childCount == 0 /** Returns true if this view group contains one or more views. */ public inline fun ViewGroup.isNotEmpty(): Boolean = childCount != 0 /** Performs the given action on each view in this view group. */ public inline fun ViewGroup.forEach(action: (view: View) -> Unit) { for (index in 0 until childCount) { action(getChildAt(index)) } } /** Performs the given action on each view in this view group, providing its sequential index. */ public inline fun ViewGroup.forEachIndexed(action: (index: Int, view: View) -> Unit) { for (index in 0 until childCount) { action(index, getChildAt(index)) } } /** * Returns an [IntRange] of the valid indices for the children of this view group. * * This can be used for looping: * ```kotlin * for (i in viewGroup.indices.reversed) { * if (viewGroup[i] is SomeView) { * viewGroup.removeViewAt(i) * } * } * ``` * * Or to determine if an index is valid: * ```kotlin * if (2 in viewGroup.indices) { * // Do something… * } * ``` */ public inline val ViewGroup.indices: IntRange get() = 0 until childCount /** Returns a [MutableIterator] over the views in this view group. */ public operator fun ViewGroup.iterator(): MutableIterator<View> = object : MutableIterator<View> { private var index = 0 override fun hasNext() = index < childCount override fun next() = getChildAt(index++) ?: throw IndexOutOfBoundsException() override fun remove() = removeViewAt(--index) } /** * Returns a [Sequence] over the immediate child views in this view group. * * @see View.allViews * @see ViewGroup.descendants */ public val ViewGroup.children: Sequence<View> get() = object : Sequence<View> { override fun iterator() = [email protected]() } /** * Returns a [Sequence] over the child views in this view group recursively. * This performs a depth-first traversal. * A view with no children will return a zero-element sequence. * * @see View.allViews * @see ViewGroup.children * @see View.ancestors */ public val ViewGroup.descendants: Sequence<View> get() = sequence { forEach { child -> yield(child) if (child is ViewGroup) { yieldAll(child.descendants) } } } /** * Sets the margins in the ViewGroup's MarginLayoutParams. This version of the method sets all axes * to the provided size. * * @see ViewGroup.MarginLayoutParams.setMargins */ public inline fun ViewGroup.MarginLayoutParams.setMargins(@Px size: Int) { setMargins(size, size, size, size) } /** * Updates the margins in the [ViewGroup]'s [ViewGroup.MarginLayoutParams]. * This version of the method allows using named parameters to just set one or more axes. * * @see ViewGroup.MarginLayoutParams.setMargins */ public inline fun ViewGroup.MarginLayoutParams.updateMargins( @Px left: Int = leftMargin, @Px top: Int = topMargin, @Px right: Int = rightMargin, @Px bottom: Int = bottomMargin ) { setMargins(left, top, right, bottom) } /** * Updates the relative margins in the ViewGroup's MarginLayoutParams. * This version of the method allows using named parameters to just set one or more axes. * * Note that this inline method references platform APIs added in API 17 and may raise runtime * verification warnings on earlier platforms. See Chromium's guide to * [Class Verification Failures](https://chromium.googlesource.com/chromium/src/+/HEAD/build/android/docs/class_verification_failures.md) * for more information. * * @see ViewGroup.MarginLayoutParams.setMargins */ @SuppressLint("ClassVerificationFailure") // Can't work around this for default arguments. @RequiresApi(17) public inline fun ViewGroup.MarginLayoutParams.updateMarginsRelative( @Px start: Int = marginStart, @Px top: Int = topMargin, @Px end: Int = marginEnd, @Px bottom: Int = bottomMargin ) { marginStart = start topMargin = top marginEnd = end bottomMargin = bottom }
apache-2.0
7813c588e72c27fb22218774cc407576
32.385057
137
0.708728
4.140413
false
false
false
false
jvalduvieco/blok
apps/Api/src/test/resources/com/blok/Webserver/WebServerInfrastructureStepDefinitions.kt
1
1323
package com.blok.Functional import cucumber.api.java.en.Given import cucumber.api.java.en.When import org.apache.http.HttpStatus import org.apache.http.client.methods.CloseableHttpResponse import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.junit.Assert class WebServerInfrastructureStepDefinitions { @Given("^I can connect to my test webserver$") fun iCanConnectToTheWebserver() { var exception: Throwable? = null try { val httpclient: CloseableHttpClient = HttpClients.createDefault() val request: HttpGet = HttpGet("http://localhost:4567/") // FIXME Use parametrized URL httpclient.execute(request) httpclient.close() } catch (e: Throwable) { exception = e } Assert.assertNull(exception) } @When("^I run alive check I get a 200$") fun iRunALiveCheckIGet200() { val httpclient: CloseableHttpClient = HttpClients.createDefault() val request: HttpGet = HttpGet("http://localhost:4567/alive") val response: CloseableHttpResponse = httpclient.execute(request) Assert.assertEquals(HttpStatus.SC_OK, response.statusLine.statusCode) httpclient.close() } }
mit
715987105a69989158e71eb921f5a875
39.121212
99
0.70446
4.380795
false
false
false
false
dkandalov/pomodoro-tm
src/pomodoro/widget/PomodoroWidget.kt
1
6107
package pomodoro.widget import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.impl.AsyncDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupFactory.ActionSelectionAid.SPEEDSEARCH import com.intellij.openapi.wm.CustomStatusBarWidget import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidgetFactory import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.UIUtil import pomodoro.PomodoroService import pomodoro.ResetPomodorosCounter import pomodoro.StartOrStopPomodoro import pomodoro.UIBundle import pomodoro.model.PomodoroModel import pomodoro.model.PomodoroState import pomodoro.model.PomodoroState.Mode.* import pomodoro.model.Settings import pomodoro.model.time.Duration import pomodoro.model.time.Time import java.awt.Point import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.ImageIcon import javax.swing.JComponent class PomodoroWidgetFactory : StatusBarWidgetFactory { override fun getId() = "Pomodoro" override fun getDisplayName() = "Pomodoro" override fun isAvailable(project: Project) = true override fun createWidget(project: Project) = PomodoroWidget() override fun disposeWidget(widget: StatusBarWidget) = widget.dispose() override fun canBeEnabledOn(statusBar: StatusBar) = true } class PomodoroWidget : CustomStatusBarWidget, StatusBarWidget.Multiframe, Settings.ChangeListener { private val panelWithIcon = TextPanelWithIcon() private lateinit var statusBar: StatusBar private val model = service<PomodoroService>().model init { val settings = service<Settings>() updateWidgetPanel(model, panelWithIcon, settings.isShowTimeInToolbarWidget) model.addListener(this, object : PomodoroModel.Listener { override fun onStateChange(state: PomodoroState, wasManuallyStopped: Boolean) { ApplicationManager.getApplication().invokeLater { updateWidgetPanel(model, panelWithIcon, settings.isShowTimeInToolbarWidget) } } }) panelWithIcon.addMouseListener(object : MouseAdapter() { override fun mouseClicked(event: MouseEvent?) { if (event == null) return if (event.isAltDown) { val popup = JBPopupFactory.getInstance().createActionGroupPopup( null, DefaultActionGroup(listOf(StartOrStopPomodoro(), ResetPomodorosCounter())), MapDataContext(mapOf(PlatformDataKeys.CONTEXT_COMPONENT.name to event.component)), SPEEDSEARCH, true ) val dimension = popup.content.preferredSize val point = Point(0, -dimension.height) popup.show(RelativePoint(event.component, point)) } else if (event.button == MouseEvent.BUTTON1) { model.onUserSwitchToNextState(Time.now()) } } override fun mouseEntered(e: MouseEvent?) { statusBar.info = UIBundle.message("statuspanel.tooltip", nextActionName(model), model.state.pomodorosAmount) } override fun mouseExited(e: MouseEvent?) { statusBar.info = "" } }) } override fun install(statusBar: StatusBar) { this.statusBar = statusBar } override fun getComponent(): JComponent = panelWithIcon override fun copy() = PomodoroWidget() private fun nextActionName(model: PomodoroModel) = when (model.state.mode) { Run -> UIBundle.message("statuspanel.stop") Break -> UIBundle.message("statuspanel.stop_break") Stop -> UIBundle.message("statuspanel.start") } private fun updateWidgetPanel(model: PomodoroModel, panelWithIcon: TextPanelWithIcon, showTimeInToolbarWidget: Boolean) { panelWithIcon.text = if (showTimeInToolbarWidget) model.timeLeft.formatted() else "" panelWithIcon.toolTipText = UIBundle.message("statuspanel.widget_tooltip", nextActionName(model)) panelWithIcon.icon = when (model.state.mode) { Run -> if (UIUtil.isUnderDarcula()) pomodoroDarculaIcon else pomodoroIcon Break -> if (UIUtil.isUnderDarcula()) pomodoroBreakDarculaIcon else pomodoroBreakIcon Stop -> if (UIUtil.isUnderDarcula()) pomodoroStoppedDarculaIcon else pomodoroStoppedIcon } panelWithIcon.repaint() } override fun dispose() { model.removeListener(this) } override fun ID() = "Pomodoro" override fun onChange(newSettings: Settings) { updateWidgetPanel(model, panelWithIcon, newSettings.isShowTimeInToolbarWidget) } private fun Duration.formatted(): String { val formattedMinutes = String.format("%02d", minutes) val formattedSeconds = String.format("%02d", (this - Duration(minutes)).seconds) return "$formattedMinutes:$formattedSeconds" } private class MapDataContext(private val map: Map<String, Any?> = HashMap()) : AsyncDataContext { override fun getData(dataId: String) = map[dataId] } companion object { private val pomodoroIcon = loadIcon("/pomodoro.png") private val pomodoroStoppedIcon = loadIcon("/pomodoroStopped.png") private val pomodoroBreakIcon = loadIcon("/pomodoroBreak.png") private val pomodoroDarculaIcon = loadIcon("/pomodoro_dark.png") private val pomodoroStoppedDarculaIcon = loadIcon("/pomodoroStopped_dark.png") private val pomodoroBreakDarculaIcon = loadIcon("/pomodoroBreak_dark.png") private fun loadIcon(filePath: String) = ImageIcon(PomodoroWidget::class.java.getResource(filePath)) } }
apache-2.0
eb65563607d8eca8feb6314d1070d030
42.621429
143
0.704274
4.925
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/util/simd/templates/SSE3.kt
1
1378
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.util.simd.templates import org.lwjgl.generator.* import org.lwjgl.util.simd.* val SSE3 = "SSE3".nativeClass("org.lwjgl.util.simd", prefix = "_MM", prefixMethod = "_MM_", library = SSE_LIBRARY) { nativeImport( "simd/intrinsics.h" ) documentation = "Bindings to SSE3 macros." val DenormalsZeroMode = IntConstant( "Denormals are zero mode.", "DENORMALS_ZERO_MASK"..0x0040, "DENORMALS_ZERO_ON"..0x0040, "DENORMALS_ZERO_OFF"..0x0000 ).javaDocLinks macro()..void( "SET_DENORMALS_ZERO_MODE", """ Causes the \"denormals are zero\" mode to be turned ON or OFF by setting the appropriate bit of the control register. DAZ treats denormal values used as input to floating-point instructions as zero. DAZ is very similar to FTZ in many ways. DAZ mode is a method of bypassing IEEE 754 methods of dealing with denormal floating-point numbers. This mode is less precise, but much faster and is typically used in applications like streaming media when minute differences in quality are essentially undetectable. """, unsigned_int.IN("mode", "the denormals are zero mode", DenormalsZeroMode) ) macro()..unsigned_int("GET_DENORMALS_ZERO_MODE", "Returns the current value of the \"denormals are zero mode\" bit of the control register.") }
bsd-3-clause
90d97b2d5831ca3e2eb7a019d8ad9e7f
34.358974
152
0.735123
3.34466
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/graphics/ImageCache.kt
1
12083
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.graphics import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Point import android.graphics.PorterDuff import android.graphics.Rect import android.graphics.RectF import android.graphics.Shader import android.media.MediaMetadataRetriever import android.media.ThumbnailUtils import android.net.Uri import android.os.Build import android.util.DisplayMetrics import android.util.LruCache import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.DbUtils.closeSilently import org.andstatus.app.data.MediaFile import org.andstatus.app.data.MyContentType import org.andstatus.app.util.MyLog import java.io.File import java.util.* import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentSkipListSet import java.util.concurrent.atomic.AtomicLong /** * @author [email protected] * On LruCache usage read http://developer.android.com/reference/android/util/LruCache.html */ class ImageCache(context: Context, name: CacheName, maxBitmapHeightWidthIn: Int, requestedCacheSizeIn: Int) : LruCache<String, CachedImage>(requestedCacheSizeIn) { val name: CacheName private val requestedCacheSize: Int private var currentCacheSize: Int @Volatile var maxBitmapHeight = 0 @Volatile private var maxBitmapWidth = 0 val hits: AtomicLong = AtomicLong() val misses: AtomicLong = AtomicLong() val brokenBitmaps: MutableSet<String> = ConcurrentSkipListSet() val recycledBitmaps: Queue<Bitmap> val displayMetrics: DisplayMetrics @Volatile var rounded = false val showImageInimations: Boolean override fun resize(maxSize: Int) { throw IllegalStateException("Cache cannot be resized") } private fun newBlankBitmap(): Bitmap? { return Bitmap.createBitmap(displayMetrics, maxBitmapWidth, maxBitmapHeight, CachedImage.BITMAP_CONFIG) } fun getCachedImage(mediaFile: MediaFile): CachedImage? { return getImage(mediaFile, true) } fun loadAndGetImage(mediaFile: MediaFile): CachedImage? { return getImage(mediaFile, false) } override fun entryRemoved(evicted: Boolean, key: String, oldValue: CachedImage, newValue: CachedImage?) { oldValue.makeExpired()?.let { if (oldValue.foreignBitmap) { it.recycle() } else { recycledBitmaps.add(it) } } } private fun getImage(mediaFile: MediaFile, fromCacheOnly: Boolean): CachedImage? { if (mediaFile.getPath().isEmpty()) { MyLog.v(mediaFile, "No path of id:${mediaFile.id}") return null } var image = get(mediaFile.getPath()) if (image != null) { hits.incrementAndGet() } else if (brokenBitmaps.contains(mediaFile.getPath())) { MyLog.v(mediaFile, "Known broken id:${mediaFile.id}") hits.incrementAndGet() return CachedImage.BROKEN } else { misses.incrementAndGet() if (!fromCacheOnly && File(mediaFile.getPath()).exists()) { image = loadImage(mediaFile) if (image != null) { if (currentCacheSize > 0) { put(mediaFile.getPath(), image) } } else { brokenBitmaps.add(mediaFile.getPath()) } } } return image } private fun loadImage(mediaFile: MediaFile): CachedImage? { return when (MyContentType.fromPathOfSavedFile(mediaFile.getPath())) { MyContentType.IMAGE, MyContentType.ANIMATED_IMAGE -> { if (showImageInimations && Build.VERSION.SDK_INT >= 28) { ImageCacheApi28Helper.animatedFileToCachedImage(this, mediaFile) } else imageFileToCachedImage(mediaFile) } MyContentType.VIDEO -> videoFileToBitmap(mediaFile)?.let { bitmapToCachedImage(mediaFile, it) } else -> null } } fun imageFileToCachedImage(mediaFile: MediaFile): CachedImage? { return imageFileToBitmap(mediaFile)?.let { bitmapToCachedImage(mediaFile, it) } } fun bitmapToCachedImage(mediaFile: MediaFile, bitmap: Bitmap): CachedImage { val srcRect = Rect(0, 0, bitmap.width, bitmap.height) var background = recycledBitmaps.poll() var foreignBitmap: Boolean = background == null if (background == null) { MyLog.w(mediaFile, "ForeignBitmap: No bitmap to cache id:${mediaFile.id}" + " ${srcRect.width()}x${srcRect.height()} '${mediaFile.getPath()}'") background = bitmap } else { val canvas = Canvas(background) canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) try { // On Android 8+ this may cause // java.lang.IllegalArgumentException: Software rendering doesn't support hardware bitmaps // See https://stackoverflow.com/questions/58314397/java-lang-illegalstateexception-software-rendering-doesnt-support-hardware-bit if (rounded) { drawRoundedBitmap(canvas, bitmap) } else { canvas.drawBitmap(bitmap, 0f, 0f, null) } bitmap.recycle() } catch (e: Exception) { recycledBitmaps.add(background) foreignBitmap = true background = bitmap MyLog.w(TAG, "ForeignBitmap: Drawing bitmap of $mediaFile", e) } } return CachedImage(mediaFile.id, background, srcRect, foreignBitmap) } /** * The solution is from http://evel.io/2013/07/21/rounded-avatars-in-android/ */ private fun drawRoundedBitmap(canvas: Canvas, bitmap: Bitmap) { val rectF = RectF(0f, 0f, bitmap.getWidth().toFloat(), bitmap.getHeight().toFloat()) val paint = Paint() paint.isAntiAlias = true paint.isDither = true val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader canvas.drawOval(rectF, paint) } private fun imageFileToBitmap(mediaFile: MediaFile): Bitmap? { return try { val options = calculateScaling(mediaFile, mediaFile.getSize()) val bitmap: Bitmap? = if (MyPreferences.isShowDebuggingInfoInUi()) { BitmapFactory.decodeFile(mediaFile.getPath(), options) } else { try { BitmapFactory.decodeFile(mediaFile.getPath(), options) } catch (e: OutOfMemoryError) { evictAll() MyLog.w(mediaFile, getInfo(), e) return null } } MyLog.v(mediaFile) { (if (bitmap == null) "Failed to load $name's bitmap" else "Loaded " + name + "'s bitmap " + bitmap.width + "x" + bitmap.height) + " id:${mediaFile.id} '" + mediaFile.getPath() + "' inSampleSize:" + options.inSampleSize } bitmap } catch (e: Exception) { MyLog.w(this, "Error loading id:${mediaFile.id} '" + mediaFile.getPath() + "'", e) null } } private fun videoFileToBitmap(mediaFile: MediaFile): Bitmap? { var retriever: MediaMetadataRetriever? = null return try { retriever = MediaMetadataRetriever() retriever.setDataSource( MyContextHolder.myContextHolder.getNow().context, Uri.parse(mediaFile.getPath())) val source = retriever.frameAtTime ?: return null val options = calculateScaling(mediaFile, mediaFile.getSize()) val bitmap = ThumbnailUtils.extractThumbnail(source, mediaFile.getSize().x / options.inSampleSize, mediaFile.getSize().y / options.inSampleSize) source.recycle() MyLog.v(mediaFile) { (if (bitmap == null) "Failed to load $name's bitmap" else "Loaded " + name + "'s bitmap " + bitmap.width + "x" + bitmap.height) + " '" + mediaFile.getPath() + "'" } bitmap } catch (e: Exception) { MyLog.w(this, "Error loading '" + mediaFile.getPath() + "'", e) null } finally { closeSilently(retriever) } } fun calculateScaling(anyTag: Any, imageSize: Point): BitmapFactory.Options { val options = BitmapFactory.Options() options.inSampleSize = 1 var x = maxBitmapWidth var y = maxBitmapHeight while (imageSize.y > y || imageSize.x > x) { options.inSampleSize = if (options.inSampleSize < 2) 2 else options.inSampleSize * 2 x *= 2 y *= 2 } if (options.inSampleSize > 1 && MyLog.isVerboseEnabled()) { MyLog.v(anyTag, "Large bitmap " + imageSize.x + "x" + imageSize.y + " scaling by " + options.inSampleSize + " times") } return options } fun getInfo(): String { val builder = StringBuilder(name.title) builder.append(": " + maxBitmapWidth + "x" + maxBitmapHeight + ", " + size() + " of " + currentCacheSize) if (requestedCacheSize != currentCacheSize) { builder.append(" (initially capacity was $requestedCacheSize)") } builder.append(", free: " + recycledBitmaps.size) if (!brokenBitmaps.isEmpty()) { builder.append(", broken: " + brokenBitmaps.size) } val accesses = hits.get() + misses.get() builder.append(", hits:" + hits.get() + ", misses:" + misses.get() + if (accesses == 0L) "" else ", hitRate:" + hits.get() * 100 / accesses + "%") return builder.toString() } fun getMaxBitmapWidth(): Int { return maxBitmapWidth } private fun setMaxBounds(x: Int, y: Int) { if (x < 1 || y < 1) { MyLog.e(this, IllegalArgumentException("setMaxBounds x=$x y=$y")) } else { maxBitmapWidth = x maxBitmapHeight = y } } companion object { val TAG: String = ImageCache::class.simpleName!! const val BYTES_PER_PIXEL = 4 } init { showImageInimations = MyPreferences.isShowImageAnimations() this.name = name displayMetrics = context.getResources().displayMetrics setMaxBounds(maxBitmapHeightWidthIn, maxBitmapHeightWidthIn) requestedCacheSize = requestedCacheSizeIn currentCacheSize = requestedCacheSize recycledBitmaps = ConcurrentLinkedQueue() try { for (i in 0 until currentCacheSize + 2) { recycledBitmaps.add(newBlankBitmap()) } } catch (e: OutOfMemoryError) { MyLog.w(this, getInfo(), e) currentCacheSize = recycledBitmaps.size - 2 if (currentCacheSize < 0) { currentCacheSize = 0 } super.resize(currentCacheSize) } } }
apache-2.0
83014564354d54c28a8719ccfdbe4397
38.10356
163
0.610941
4.658057
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/util/MyStringBuilder.kt
1
5801
/* * Copyright (C) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.util import java.util.* /** Adds convenience methods to [StringBuilder] */ class MyStringBuilder constructor(val builder: StringBuilder = StringBuilder()) : CharSequence, IsEmpty { private constructor(text: CharSequence) : this(StringBuilder(text)) fun <T> withCommaNonEmpty(label: CharSequence?, obj: T?): MyStringBuilder { return withComma(label, obj, { it -> nonEmptyObj(it) }) } fun <T> withComma(label: CharSequence?, obj: T?, predicate: (T) -> Boolean): MyStringBuilder { return if (obj == null || !predicate(obj)) this else withComma(label, obj) } fun withComma(label: CharSequence?, obj: Any?, filter: () -> Boolean): MyStringBuilder { return if (obj == null || !filter()) this else withComma(label, obj) } fun withComma(label: CharSequence?, obj: Any?): MyStringBuilder { return append(label, obj, ", ", false) } fun withCommaQuoted(label: CharSequence?, obj: Any?, quoted: Boolean): MyStringBuilder { return append(label, obj, ", ", quoted) } fun withComma(text: CharSequence?): MyStringBuilder { return append("", text, ", ", false) } fun withSpaceQuoted(text: CharSequence?): MyStringBuilder { return append("", text, " ", true) } fun withSpace(text: CharSequence?): MyStringBuilder { return append("", text, " ", false) } fun atNewLine(text: CharSequence?): MyStringBuilder { return atNewLine("", text) } fun atNewLine(label: CharSequence?, text: CharSequence?): MyStringBuilder { val separator = if (isEmpty) "" else { when(get(lastIndex-1)) { '\n' -> "" ',' -> "\n" else -> ",\n" } } return append(label, text, separator, false) } fun append(label: CharSequence?, obj: Any?, separator: String, quoted: Boolean): MyStringBuilder { if (obj == null) return this val text = obj.toString() if (text.isEmpty()) return this if (builder.isNotEmpty()) builder.append(separator) if (!label.isNullOrEmpty()) builder.append(label).append(": ") if (quoted) builder.append("\"") builder.append(text) if (quoted) builder.append("\"") return this } fun append(text: CharSequence?): MyStringBuilder { if (!text.isNullOrEmpty()) { builder.append(text) } return this } override val length: Int get() = builder.length override fun get(index: Int): Char = builder[index] override fun subSequence(startIndex: Int, endIndex: Int): CharSequence { return builder.subSequence(startIndex, endIndex) } override fun toString(): String { return builder.toString() } fun prependWithSeparator(text: CharSequence, separator: String): MyStringBuilder { if (text.isNotEmpty()) { builder.insert(0, separator) builder.insert(0, text) } return this } fun apply(unaryOperator: (MyStringBuilder) -> MyStringBuilder): MyStringBuilder { return unaryOperator(this) } override val isEmpty: Boolean get() = length == 0 fun toKeyValue(key: Any): String { return formatKeyValue(key, toString()) } companion object { const val COMMA: String = "," fun of(text: CharSequence?): MyStringBuilder { return MyStringBuilder(text ?: "") } fun of(content: Optional<String>): MyStringBuilder { return content.map { text: String -> of(text) }.orElse(MyStringBuilder()) } fun formatKeyValue(keyIn: Any?, valueIn: Any?): String { val key = Taggable.anyToTag(keyIn) if (keyIn == null) { return key } var value = "null" if (valueIn != null) { value = valueIn.toString() } return formatKeyValue(key, value) } /** Strips value from leading and trailing commas */ fun formatKeyValue(key: Any?, value: String?): String { var out = "" if (!value.isNullOrEmpty()) { out = value.trim { it <= ' ' } if (out.substring(0, 1) == COMMA) { out = out.substring(1) } val ind = out.lastIndexOf(COMMA) if (ind > 0 && ind == out.length - 1) { out = out.substring(0, ind) } } return Taggable.anyToTag(key) + ": {" + out + "}" } private fun <T> nonEmptyObj(obj: T?): Boolean { return !isEmptyObj(obj) } private fun <T> isEmptyObj(obj: T?): Boolean = when (obj) { null -> true is IsEmpty -> obj.isEmpty is Number -> obj.toLong() == 0L is String -> obj.isEmpty() else -> false } fun appendWithSpace(builder: StringBuilder, text: CharSequence?): StringBuilder { return MyStringBuilder(builder).withSpace(text).builder } } }
apache-2.0
7b25b80a4f54e508b92e7046f941c45b
32.148571
105
0.579555
4.431627
false
false
false
false
smichel17/simpletask-android
app/src/main/java/com/robobunny/SeekBarPreference.kt
2
6238
package com.robobunny import android.content.Context import android.content.res.TypedArray import android.preference.Preference import android.util.AttributeSet import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import nl.mpcjanssen.simpletask.R class SeekBarPreference : Preference, OnSeekBarChangeListener { private val TAG = javaClass.name private var mMaxValue = 100 private var mMinValue = 0 private var mInterval = 1 private var mCurrentValue: Int = 0 private var mUnitsRight = "" private var mSeekBar: SeekBar? = null private var mStatusText: TextView? = null constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initPreference(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { initPreference(context, attrs) } private fun initPreference(context: Context, attrs: AttributeSet) { setValuesFromXml(attrs) mSeekBar = SeekBar(context, attrs) mSeekBar!!.max = mMaxValue - mMinValue mSeekBar!!.setOnSeekBarChangeListener(this) layoutResource = R.layout.seek_bar_preference } private fun setValuesFromXml(attrs: AttributeSet) { mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100) mMinValue = attrs.getAttributeIntValue(APPLICATIONNS, "min", 0) val units = getAttributeStringValue(attrs, APPLICATIONNS, "units", "") mUnitsRight = getAttributeStringValue(attrs, APPLICATIONNS, "unitsRight", units) try { val newInterval = attrs.getAttributeValue(APPLICATIONNS, "interval") if (newInterval != null) mInterval = Integer.parseInt(newInterval) } catch (e: Exception) { Log.e(TAG, "Invalid interval value", e) } } private fun getAttributeStringValue(attrs: AttributeSet, namespace: String, name: String, defaultValue: String): String { return attrs.getAttributeValue(namespace, name) ?: defaultValue } public override fun onBindView(view: View) { super.onBindView(view) try { // move our seekbar to the new view we've been given val oldContainer = mSeekBar!!.parent val newContainer = view.findViewById(R.id.seekBarPrefBarContainer) as ViewGroup if (oldContainer !== newContainer) { // remove the seekbar from the old view if (oldContainer != null) { (oldContainer as ViewGroup).removeView(mSeekBar) } // remove the existing seekbar (there may not be one) and add ours newContainer.removeAllViews() newContainer.addView(mSeekBar, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } } catch (ex: Exception) { Log.e(TAG, "Error binding view: " + ex.toString()) } //if dependency is false from the beginning, disable the seek bar if (!view.isEnabled) { mSeekBar!!.isEnabled = false } updateView(view) } /** * Update a SeekBarPreference view with our current state * @param view */ protected fun updateView(view: View) { try { mStatusText = view.findViewById(R.id.seekBarPrefValue) as TextView mStatusText!!.text = mCurrentValue.toString() mStatusText!!.minimumWidth = 30 mSeekBar!!.progress = mCurrentValue - mMinValue val unitsRight = view.findViewById(R.id.seekBarPrefUnitsRight) as TextView unitsRight.text = mUnitsRight } catch (e: Exception) { Log.e(TAG, "Error updating seek bar preference", e) } } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { var newValue = progress + mMinValue if (newValue > mMaxValue) newValue = mMaxValue else if (newValue < mMinValue) newValue = mMinValue else if (mInterval != 1 && newValue % mInterval != 0) newValue = Math.round(newValue.toFloat() / mInterval) * mInterval // change rejected, revert to the previous value if (!callChangeListener(newValue)) { seekBar.progress = mCurrentValue - mMinValue return } // change accepted, store it mCurrentValue = newValue mStatusText!!.text = newValue.toString() persistInt(newValue) } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { notifyChanged() } override fun onGetDefaultValue(ta: TypedArray, index: Int): Any { return ta.getInt(index, DEFAULT_VALUE) } override fun onSetInitialValue(restoreValue: Boolean, defaultValue: Any?) { if (restoreValue) { mCurrentValue = getPersistedInt(mCurrentValue) } else { var temp = 0 try { temp = defaultValue as Int } catch (ex: Exception) { Log.e(TAG, "Invalid default value: " + defaultValue.toString()) } persistInt(temp) mCurrentValue = temp } } /** * make sure that the seekbar is disabled if the preference is disabled */ override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) mSeekBar!!.isEnabled = enabled } override fun onDependencyChanged(dependency: Preference, disableDependent: Boolean) { super.onDependencyChanged(dependency, disableDependent) //Disable movement of seek bar when dependency is false if (mSeekBar != null) { mSeekBar!!.isEnabled = !disableDependent } } companion object { private val ANDROIDNS = "http://schemas.android.com/apk/res/android" private val APPLICATIONNS = "http://robobunny.com" private val DEFAULT_VALUE = 50 } }
gpl-3.0
5849da66f71c249aca8f7d06111e62e7
30.826531
125
0.631933
4.791091
false
false
false
false
lehvolk/xodus-entity-browser
entity-browser-app/src/test/kotlin/jetbrains/xodus/browser/web/EncryptedDatabasesTest.kt
1
2794
package jetbrains.xodus.browser.web import jetbrains.exodus.crypto.streamciphers.CHACHA_CIPHER_ID import jetbrains.exodus.entitystore.PersistentEntityStores import jetbrains.exodus.entitystore.PersistentStoreTransaction import jetbrains.exodus.env.EnvironmentConfig import jetbrains.exodus.env.Environments import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.io.File class EncryptedDatabasesTest : TestSupport() { private val encStoreLocation = newLocation() private val encKey = "15e9d57c49098fb3a34763acb81c34c735f4f231f1fa7fa9b74be385269c9b81" private val encInit = -5842344510678812273L @Test fun `should be able to add new encrypted db`() { val db = newEncDB() newDB(db).let { assertTrue(it.isOpened) assertTrue(it.isEncrypted) assertEquals(encStoreLocation, it.location) assertEquals(key, it.key) assertNull(it.encryptionProvider) assertNull(it.encryptionKey) assertNull(it.encryptionIV) } } @Test fun `should not be able to add new encrypted db with incorrect params`() { val db = newEncDB().apply { encryptionKey = "15e9d57c49098fb3a34763acb81c34c735f4f231f1fa7fa9b74be385269c9b82" } val response = dbsResource.new(db).execute() assertEquals(400, response.code()) assertTrue(webApp.allServices.isEmpty()) } private fun newEncDB(): DBSummary { return DBSummary( location = encStoreLocation, key = key, isOpened = true, isEncrypted = true, isReadonly = false, isWatchReadonly = false, encryptionProvider = EncryptionProvider.CHACHA, encryptionKey = encKey, encryptionIV = encInit.toString() ) } @Before fun setup() { val config = EnvironmentConfig() .setCipherId(CHACHA_CIPHER_ID) .setCipherKey(encKey) .setCipherBasicIV(encInit) val store = PersistentEntityStores.newInstance(Environments.newInstance(encStoreLocation, config), key) store.executeInTransaction { val tr = it as PersistentStoreTransaction store.getEntityTypeId(tr, "Type1", true) repeat(100) { tr.newEntity("Type1").also { it.setProperty("type", "Band") } } } store.close() store.environment.close() } @After fun cleanup() { File(encStoreLocation).delete() } fun newDB(db: DBSummary): DBSummary { return dbsResource.new(db).execute().body()!! } }
apache-2.0
262dfcbe98406cc6cb251eee3231c7bd
30.055556
111
0.623121
4.207831
false
true
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/editor/surroundWith/LuaSurroundDescriptor.kt
2
3887
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.editor.surroundWith import com.intellij.lang.surroundWith.SurroundDescriptor import com.intellij.lang.surroundWith.Surrounder import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import com.tang.intellij.lua.lang.LuaLanguage import com.tang.intellij.lua.psi.LuaStatement import java.util.* /** * SurroundDescriptor * Created by tangzx on 2017/2/25. */ class LuaSurroundDescriptor : SurroundDescriptor { private val surrounders = arrayOf<Surrounder>( RegionSurrounder("Lua Region --region", "region", "endregion"), RegionSurrounder("Lua Region --{{{", "{{{", "}}}") ) override fun getElementsToSurround(psiFile: PsiFile, startOffset: Int, endOffset: Int): Array<PsiElement> { return findStatementsInRange(psiFile, startOffset, endOffset) } private fun findStatementsInRange(file: PsiFile, start: Int, end: Int): Array<PsiElement> { var startOffset = start var endOffset = end var element1 = file.viewProvider.findElementAt(startOffset, LuaLanguage.INSTANCE) var element2 = file.viewProvider.findElementAt(endOffset - 1, LuaLanguage.INSTANCE) if (element1 is PsiWhiteSpace) { startOffset = element1.textRange.endOffset element1 = file.findElementAt(startOffset) } if (element2 is PsiWhiteSpace) { endOffset = element2.textRange.startOffset element2 = file.findElementAt(endOffset - 1) } if (element1 == null || element2 == null) return PsiElement.EMPTY_ARRAY var parent = PsiTreeUtil.findCommonParent(element1, element2) ?: return PsiElement.EMPTY_ARRAY while (true) { if (parent is LuaStatement) { if (element1 !is PsiComment) { parent = parent.parent } break } if (parent is PsiFile) break parent = parent.parent } if (parent != element1) { while (parent != element1!!.parent) { element1 = element1.parent } } if (parent != element2) { while (parent != element2!!.parent) { element2 = element2.parent } } val children = parent.children val array = ArrayList<PsiElement>() var flag = false for (child in children) { if (child == element1) { flag = true } if (flag && child !is PsiWhiteSpace) { array.add(child) } if (child == element2) { break } } for (element in array) { if (!(element is LuaStatement || element is PsiWhiteSpace || element is PsiComment)) { return PsiElement.EMPTY_ARRAY } } return PsiUtilCore.toPsiElementArray(array) } override fun getSurrounders(): Array<Surrounder> { return surrounders } override fun isExclusive(): Boolean { return false } }
apache-2.0
3e78d4e8877dbe70985fd5aab94f4151
32.517241
111
0.623617
4.610913
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/db/model/ExportFile.kt
1
1780
package at.ac.tuwien.caa.docscan.db.model import android.net.Uri import androidx.annotation.Keep import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.* @Keep @Entity(tableName = ExportFile.TABLE_NAME_EXPORT_FILES) data class ExportFile( /** * A unique file name. The uniqueness of file names is automatically ensured by the android * system for a specific folder. */ @PrimaryKey @ColumnInfo(name = KEY_FILE_NAME) val fileName: String, /** * The corresponding documentId, this is not unique as there might be several different exports * for a single document. * - the default value is just an arbitrary id in order to prevent making the field nullable, * but for already created exports, this field doesn't matter anyway. */ @ColumnInfo(name = KEY_DOC_ID, defaultValue = "d0289e3b-f7f3-4e9b-8eb8-6f392c503f51") val docId: UUID, /** * The corresponding fileUri where the export is going to placed, this is only available for * a short period of time while the document is being exported. * * Please note that this fileUri should be only used for clean-ups if the export has been interrupted * in an unexpected way. */ @ColumnInfo(name = KEY_FILE_URI) val fileUri: Uri?, /** * A boolean flag that indicates if the export file is being processed. */ @ColumnInfo(name = KEY_IS_PROCESSING) val isProcessing: Boolean ) { companion object { const val TABLE_NAME_EXPORT_FILES = "export_files" const val KEY_DOC_ID = "doc_id" const val KEY_FILE_NAME = "file_name" const val KEY_FILE_URI = "file_uri" const val KEY_IS_PROCESSING = "is_processing" } }
lgpl-3.0
3e740f41abe3d13b4f8bd834cf605bbc
33.230769
105
0.684831
3.92936
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/newsfeed/dto/NewsfeedNewsfeedItem.kt
1
34075
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.newsfeed.dto import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.aliexpress.dto.AliexpressBlockPanel import com.vk.sdk.api.aliexpress.dto.AliexpressCarouselItem import com.vk.sdk.api.aliexpress.dto.AliexpressPromoCard import com.vk.sdk.api.aliexpress.dto.AliexpressSocialFooter import com.vk.sdk.api.apps.dto.AppsApp import com.vk.sdk.api.base.dto.BaseBoolInt import com.vk.sdk.api.base.dto.BaseCommentsInfo import com.vk.sdk.api.base.dto.BaseImage import com.vk.sdk.api.base.dto.BaseLikesInfo import com.vk.sdk.api.base.dto.BaseLinkButton import com.vk.sdk.api.base.dto.BaseRepostsInfo import com.vk.sdk.api.classifieds.dto.ClassifiedsWorkiCarouselItem import com.vk.sdk.api.classifieds.dto.ClassifiedsYoulaCarouselBlockGroup import com.vk.sdk.api.classifieds.dto.ClassifiedsYoulaGroupsBlock import com.vk.sdk.api.classifieds.dto.ClassifiedsYoulaItemExtended import com.vk.sdk.api.discover.dto.DiscoverCarouselButton import com.vk.sdk.api.discover.dto.DiscoverCarouselItem import com.vk.sdk.api.discover.dto.DiscoverCarouselObjectsType import com.vk.sdk.api.groups.dto.GroupsSuggestion import com.vk.sdk.api.messages.dto.MessagesChatSuggestion import com.vk.sdk.api.photos.dto.PhotosTagsSuggestionItem import com.vk.sdk.api.photos.dto.PhotosTagsSuggestionItemEndCard import com.vk.sdk.api.stories.dto.StoriesStory import com.vk.sdk.api.textlives.dto.TextlivesTextliveTextpostBlock import com.vk.sdk.api.video.dto.VideoVideo import com.vk.sdk.api.video.dto.VideoVideoFull import com.vk.sdk.api.wall.dto.WallGeo import com.vk.sdk.api.wall.dto.WallPostCopyright import com.vk.sdk.api.wall.dto.WallPostSource import com.vk.sdk.api.wall.dto.WallPostType import com.vk.sdk.api.wall.dto.WallViews import com.vk.sdk.api.wall.dto.WallWallpostAttachment import com.vk.sdk.api.wall.dto.WallWallpostDonut import com.vk.sdk.api.wall.dto.WallWallpostFull import java.lang.IllegalStateException import java.lang.reflect.Type import kotlin.Boolean import kotlin.Float import kotlin.Int import kotlin.String import kotlin.collections.List sealed class NewsfeedNewsfeedItem { /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param feedback * @param carouselOffset - Index of current carousel element * @param copyHistory * @param canEdit - Information whether current user can edit the post * @param createdBy - Post creator ID (if post still can be edited) * @param canDelete - Information whether current user can delete the post * @param canPin - Information whether current user can pin the post * @param donut * @param isPinned - Information whether the post is pinned * @param comments * @param markedAsAds - Information whether the post is marked as ads * @param topicId - Topic ID. Allowed values can be obtained from newsfeed.getPostTopics method * @param shortTextRate - Preview length control parameter * @param hash - Hash for sharing * @param accessKey - Access key to private object * @param isDeleted * @param attachments * @param copyright - Information about the source of the post * @param edited - Date of editing in Unixtime * @param fromId - Post author ID * @param geo * @param id - Post ID * @param isArchived - Is post archived, only for post owners * @param isFavorite - Information whether the post in favorites list * @param likes - Count of likes * @param ownerId - Wall owner's ID * @param postId - If post type 'reply', contains original post ID * @param parentsStack - If post type 'reply', contains original parent IDs stack * @param postSource * @param postType * @param reposts * @param signerId - Post signer ID * @param text - Post text * @param views - Count of views */ data class NewsfeedItemWallpost( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("feedback") val feedback: NewsfeedItemWallpostFeedback? = null, @SerializedName("carousel_offset") val carouselOffset: Int? = null, @SerializedName("copy_history") val copyHistory: List<WallWallpostFull>? = null, @SerializedName("can_edit") val canEdit: BaseBoolInt? = null, @SerializedName("created_by") val createdBy: UserId? = null, @SerializedName("can_delete") val canDelete: BaseBoolInt? = null, @SerializedName("can_pin") val canPin: BaseBoolInt? = null, @SerializedName("donut") val donut: WallWallpostDonut? = null, @SerializedName("is_pinned") val isPinned: Int? = null, @SerializedName("comments") val comments: BaseCommentsInfo? = null, @SerializedName("marked_as_ads") val markedAsAds: BaseBoolInt? = null, @SerializedName("topic_id") val topicId: NewsfeedItemWallpost.TopicId? = null, @SerializedName("short_text_rate") val shortTextRate: Float? = null, @SerializedName("hash") val hash: String? = null, @SerializedName("access_key") val accessKey: String? = null, @SerializedName("is_deleted") val isDeleted: Boolean? = null, @SerializedName("attachments") val attachments: List<WallWallpostAttachment>? = null, @SerializedName("copyright") val copyright: WallPostCopyright? = null, @SerializedName("edited") val edited: Int? = null, @SerializedName("from_id") val fromId: UserId? = null, @SerializedName("geo") val geo: WallGeo? = null, @SerializedName("id") val id: Int? = null, @SerializedName("is_archived") val isArchived: Boolean? = null, @SerializedName("is_favorite") val isFavorite: Boolean? = null, @SerializedName("likes") val likes: BaseLikesInfo? = null, @SerializedName("owner_id") val ownerId: UserId? = null, @SerializedName("post_id") val postId: Int? = null, @SerializedName("parents_stack") val parentsStack: List<Int>? = null, @SerializedName("post_source") val postSource: WallPostSource? = null, @SerializedName("post_type") val postType: WallPostType? = null, @SerializedName("reposts") val reposts: BaseRepostsInfo? = null, @SerializedName("signer_id") val signerId: UserId? = null, @SerializedName("text") val text: String? = null, @SerializedName("views") val views: WallViews? = null ) : NewsfeedNewsfeedItem() { enum class TopicId( val value: Int ) { @SerializedName("0") EMPTY_TOPIC(0), @SerializedName("1") ART(1), @SerializedName("7") IT(7), @SerializedName("12") GAMES(12), @SerializedName("16") MUSIC(16), @SerializedName("19") PHOTO(19), @SerializedName("21") SCIENCE_AND_TECH(21), @SerializedName("23") SPORT(23), @SerializedName("25") TRAVEL(25), @SerializedName("26") TV_AND_CINEMA(26), @SerializedName("32") HUMOR(32), @SerializedName("43") FASHION(43); } } /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param photos * @param postId - Post ID * @param carouselOffset - Index of current carousel element */ data class NewsfeedItemPhoto( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("photos") val photos: NewsfeedItemPhotoPhotos? = null, @SerializedName("post_id") val postId: Int? = null, @SerializedName("carousel_offset") val carouselOffset: Int? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param photoTags * @param postId - Post ID * @param carouselOffset - Index of current carousel element */ data class NewsfeedItemPhotoTag( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("photo_tags") val photoTags: NewsfeedItemPhotoTagPhotoTags? = null, @SerializedName("post_id") val postId: Int? = null, @SerializedName("carousel_offset") val carouselOffset: Int? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param friends */ data class NewsfeedItemFriend( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("friends") val friends: NewsfeedItemFriendFriends? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param audio * @param postId - Post ID */ data class NewsfeedItemAudio( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("audio") val audio: NewsfeedItemAudioAudio? = null, @SerializedName("post_id") val postId: Int? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param video * @param carouselOffset - Index of current carousel element */ data class NewsfeedItemVideo( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("video") val video: NewsfeedItemVideoVideo? = null, @SerializedName("carousel_offset") val carouselOffset: Int? = null ) : NewsfeedNewsfeedItem() /** * @param postId - Topic post ID * @param text - Post text * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param comments * @param likes */ data class NewsfeedItemTopic( @SerializedName("post_id") val postId: Int, @SerializedName("text") val text: String, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("comments") val comments: BaseCommentsInfo? = null, @SerializedName("likes") val likes: BaseLikesInfo? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param feedId - id of feed in digest * @param items * @param mainPostIds * @param template - type of digest * @param header * @param footer * @param trackCode */ data class NewsfeedItemDigest( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("feed_id") val feedId: String? = null, @SerializedName("items") val items: List<NewsfeedItemDigestItem>? = null, @SerializedName("main_post_ids") val mainPostIds: List<String>? = null, @SerializedName("template") val template: NewsfeedItemDigest.Template? = null, @SerializedName("header") val header: NewsfeedItemDigestHeader? = null, @SerializedName("footer") val footer: NewsfeedItemDigestFooter? = null, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() { enum class Template( val value: String ) { @SerializedName("list") LIST("list"), @SerializedName("grid") GRID("grid"), @SerializedName("single") SINGLE("single"); } } /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param text * @param title * @param action * @param images * @param trackCode */ data class NewsfeedItemPromoButton( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("text") val text: String? = null, @SerializedName("title") val title: String? = null, @SerializedName("action") val action: NewsfeedItemPromoButtonAction? = null, @SerializedName("images") val images: List<NewsfeedItemPromoButtonImage>? = null, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param blockType * @param stories * @param title * @param trackCode */ data class NewsfeedItemStoriesBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("block_type") val blockType: NewsfeedItemStoriesBlock.BlockType? = null, @SerializedName("stories") val stories: List<StoriesStory>? = null, @SerializedName("title") val title: String? = null, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() { enum class BlockType( val value: String ) { @SerializedName("local") LOCAL("local"), @SerializedName("remote") REMOTE("remote"); } } /** * @param banner * @param poll * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param trackCode */ data class NewsfeedItemFeedbackPoll( @SerializedName("banner") val banner: NewsfeedItemFeedbackPollBanner, @SerializedName("poll") val poll: NewsfeedItemFeedbackPollPoll, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param blockId * @param text * @param animation * @param trackCode * @param decoration - none - without background, background - with background, card - looks * like a card * @param subtitle * @param button */ data class NewsfeedItemAnimatedBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("block_id") val blockId: String? = null, @SerializedName("text") val text: String? = null, @SerializedName("animation") val animation: NewsfeedItemAnimatedBlockAnimation? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("decoration") val decoration: NewsfeedItemAnimatedBlock.Decoration? = null, @SerializedName("subtitle") val subtitle: String? = null, @SerializedName("button") val button: BaseLinkButton? = null ) : NewsfeedNewsfeedItem() { enum class Decoration( val value: String ) { @SerializedName("none") NONE("none"), @SerializedName("background") BACKGROUND("background"), @SerializedName("card") CARD("card"); } } /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param title * @param trackCode * @param items * @param nextFrom - Next from value * @param button */ data class NewsfeedItemClipsBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("title") val title: String? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("items") val items: List<VideoVideo>? = null, @SerializedName("next_from") val nextFrom: String? = null, @SerializedName("button") val button: BaseLinkButton? = null ) : NewsfeedNewsfeedItem() /** * @param title - Title of the block * @param items - Items of the block * @param count - Total count of recommendations * @param trackCode - Track code of the block * @param button * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param nextFrom - Encoded string for the next page */ data class NewsfeedItemRecommendedGroupsBlock( @SerializedName("title") val title: String, @SerializedName("items") val items: List<GroupsSuggestion>, @SerializedName("count") val count: Int, @SerializedName("track_code") val trackCode: String, @SerializedName("button") val button: BaseLinkButton, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("next_from") val nextFrom: String? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param endCard * @param recognitionArticleLink - help link * @param trackCode - Track code of the block * @param items */ data class NewsfeedItemRecognizeBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("end_card") val endCard: PhotosTagsSuggestionItemEndCard? = null, @SerializedName("recognition_article_link") val recognitionArticleLink: String? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("items") val items: List<PhotosTagsSuggestionItem>? = null ) : NewsfeedNewsfeedItem() /** * @param button * @param items * @param title * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param objects * @param objectsType * @param trackCode */ data class NewsfeedItemAppsCarousel( @SerializedName("button") val button: DiscoverCarouselButton, @SerializedName("items") val items: List<DiscoverCarouselItem>, @SerializedName("title") val title: String, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("objects") val objects: List<AppsApp>? = null, @SerializedName("objects_type") val objectsType: DiscoverCarouselObjectsType? = null, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() /** * @param textliveTextpostBlock * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param trackCode */ data class NewsfeedItemTextliveBlock( @SerializedName("textlive_textpost_block") val textliveTextpostBlock: TextlivesTextliveTextpostBlock, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() /** * @param type - type * @param items * @param createButtonUrl - Create button url * @param moreButtonUrl - More button url * @param blockTitle - Block title * @param blockDescription - Block description * @param trackCode * @param group * @param viewStyle */ data class NewsfeedItemYoulaCarouselBlock( @SerializedName("type") val type: NewsfeedItemYoulaCarouselBlock.Type, @SerializedName("items") val items: List<ClassifiedsYoulaItemExtended>, @SerializedName("create_button_url") val createButtonUrl: String, @SerializedName("more_button_url") val moreButtonUrl: String, @SerializedName("block_title") val blockTitle: String? = null, @SerializedName("block_description") val blockDescription: String? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("group") val group: ClassifiedsYoulaCarouselBlockGroup? = null, @SerializedName("view_style") val viewStyle: String? = null ) : NewsfeedNewsfeedItem() { enum class Type( val value: String ) { @SerializedName("youla_carousel") YOULA_CAROUSEL("youla_carousel"); } } /** * @param type - type * @param blockTitle - Block title * @param trackCode * @param goodsCarouselViewType - Display style of block * @param blockPanel - Block top panel * @param promoCard - Promo card item * @param items * @param moreButton - More button url * @param footer * @param useOnelineProductTitle - Show product title in one row * @param isAsync - Load products via API method */ data class NewsfeedItemAliexpressCarouselBlock( @SerializedName("type") val type: NewsfeedItemAliexpressCarouselBlock.Type, @SerializedName("block_title") val blockTitle: String, @SerializedName("track_code") val trackCode: String, @SerializedName("goods_carousel_view_type") val goodsCarouselViewType: String, @SerializedName("block_panel") val blockPanel: AliexpressBlockPanel? = null, @SerializedName("promo_card") val promoCard: AliexpressPromoCard? = null, @SerializedName("items") val items: List<AliexpressCarouselItem>? = null, @SerializedName("more_button") val moreButton: BaseLinkButton? = null, @SerializedName("footer") val footer: AliexpressSocialFooter? = null, @SerializedName("use_oneline_product_title") val useOnelineProductTitle: Boolean? = null, @SerializedName("is_async") val isAsync: Boolean? = null ) : NewsfeedNewsfeedItem() { enum class Type( val value: String ) { @SerializedName("aliexpress_carousel") ALIEXPRESS_CAROUSEL("aliexpress_carousel"); } } /** * @param app * @param title * @param buttonText * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param trackCode * @param friendsPlayingText * @param friendsAvatars * @param appCover */ data class NewsfeedItemRecommendedAppBlock( @SerializedName("app") val app: AppsApp, @SerializedName("title") val title: String, @SerializedName("button_text") val buttonText: String, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("friends_playing_text") val friendsPlayingText: String? = null, @SerializedName("friends_avatars") val friendsAvatars: List<List<BaseImage>>? = null, @SerializedName("app_cover") val appCover: List<BaseImage>? = null ) : NewsfeedNewsfeedItem() /** * @param type * @param expertCard */ data class NewsfeedItemExpertCardWidget( @SerializedName("type") val type: NewsfeedItemExpertCardWidget.Type? = null, @SerializedName("expert_card") val expertCard: NewsfeedExpertCardWidget? = null ) : NewsfeedNewsfeedItem() { enum class Type( val value: String ) { @SerializedName("expert_card") EXPERT_CARD("expert_card"); } } /** * @param type - type * @param items * @param blockTitle - Block title * @param moreButton - More button url * @param trackCode */ data class NewsfeedItemWorkiCarouselBlock( @SerializedName("type") val type: NewsfeedItemWorkiCarouselBlock.Type, @SerializedName("items") val items: List<ClassifiedsWorkiCarouselItem>, @SerializedName("block_title") val blockTitle: String? = null, @SerializedName("more_button") val moreButton: BaseLinkButton? = null, @SerializedName("track_code") val trackCode: String? = null ) : NewsfeedNewsfeedItem() { enum class Type( val value: String ) { @SerializedName("worki_carousel") WORKI_CAROUSEL("worki_carousel"); } } /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param title * @param trackCode * @param items * @param nextFrom - Next from value * @param button */ data class NewsfeedItemVideosForYouBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("title") val title: String? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("items") val items: List<VideoVideoFull>? = null, @SerializedName("next_from") val nextFrom: String? = null, @SerializedName("button") val button: BaseLinkButton? = null ) : NewsfeedNewsfeedItem() /** * @param type - type * @param title * @param trackCode * @param isAsync * @param data */ data class NewsfeedItemYoulaGroupsBlock( @SerializedName("type") val type: NewsfeedItemYoulaGroupsBlock.Type, @SerializedName("title") val title: String, @SerializedName("track_code") val trackCode: String, @SerializedName("is_async") val isAsync: Boolean, @SerializedName("data") val data: ClassifiedsYoulaGroupsBlock? = null ) : NewsfeedNewsfeedItem() { enum class Type( val value: String ) { @SerializedName("youla_groups_block") YOULA_GROUPS_BLOCK("youla_groups_block"); } } /** * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param title * @param description * @param privacyText * @param trackCode * @param item * @param buttons */ data class NewsfeedItemVideoPostcardBlock( @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("title") val title: String? = null, @SerializedName("description") val description: String? = null, @SerializedName("privacy_text") val privacyText: String? = null, @SerializedName("track_code") val trackCode: String? = null, @SerializedName("item") val item: VideoVideoFull? = null, @SerializedName("buttons") val buttons: List<BaseLinkButton>? = null ) : NewsfeedNewsfeedItem() /** * @param items - Items of the block * @param count - Total count of recommendations * @param trackCode - Track code of the block * @param button * @param type * @param sourceId - Item source ID * @param date - Date when item has been added in Unixtime * @param nextFrom - Encoded string for a next page */ data class NewsfeedItemRecommendedChatsBlock( @SerializedName("items") val items: List<MessagesChatSuggestion>, @SerializedName("count") val count: Int, @SerializedName("track_code") val trackCode: String, @SerializedName("button") val button: BaseLinkButton, @SerializedName("type") val type: NewsfeedNewsfeedItemType, @SerializedName("source_id") val sourceId: UserId, @SerializedName("date") val date: Int, @SerializedName("next_from") val nextFrom: String? = null ) : NewsfeedNewsfeedItem() class Deserializer : JsonDeserializer<NewsfeedNewsfeedItem> { override fun deserialize( json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext ): NewsfeedNewsfeedItem { val type = json.asJsonObject.get("type").asString return when(type) { "post" -> context.deserialize(json, NewsfeedItemWallpost::class.java) "photo" -> context.deserialize(json, NewsfeedItemPhoto::class.java) "wall_photo" -> context.deserialize(json, NewsfeedItemPhoto::class.java) "photo_tag" -> context.deserialize(json, NewsfeedItemPhotoTag::class.java) "friend" -> context.deserialize(json, NewsfeedItemFriend::class.java) "audio" -> context.deserialize(json, NewsfeedItemAudio::class.java) "video" -> context.deserialize(json, NewsfeedItemVideo::class.java) "topic" -> context.deserialize(json, NewsfeedItemTopic::class.java) "digest" -> context.deserialize(json, NewsfeedItemDigest::class.java) "promo_button" -> context.deserialize(json, NewsfeedItemPromoButton::class.java) else -> throw IllegalStateException("no mapping for the type:" + type) } } } }
mit
c8aa2268723618dbd7e8786de5a9264b
33.419192
99
0.617608
4.412146
false
false
false
false
hotmobmobile/hotmob-android-sdk
AndroidStudio/HotmobSDKShowcase/preloaddemo/src/main/java/com/hotmob/preloaddemo/MainActivity.kt
1
1625
package com.hotmob.preloaddemo import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.Menu import androidx.appcompat.app.AppCompatActivity import com.hotmob.preloaddemo.home.HomeFragment import com.hotmob.preloaddemo.home.dummy.DummyItem import com.hotmob.preloaddemo.MainFragment import com.hotmob.sdk.ad.HotmobInterstitial import com.hotmob.sdk.module.reload.HotmobReloadManager class MainActivity : AppCompatActivity(), HomeFragment.OnListFragmentInteractionListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Set Resume Interstitial here, so that this Interstitial will only show when resume app but not launch app val interstitial = HotmobInterstitial("ResumeApp", "hotmob_android_popup_inapp") HotmobReloadManager.instance.setResumeInterstitial(this, interstitial, false) // false for not showing ad immediately val action: String? = intent?.action val data: Uri? = intent?.data Log.d("MainActivity", "Intent action: $action, data: $data") supportFragmentManager.beginTransaction() .replace(R.id.content, MainFragment()) .commit() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val action: String? = intent?.action val data: Uri? = intent?.data Log.d("MainActivity", "New intent action: $action, data: $data") } override fun onListFragmentInteraction(item: DummyItem?) { } }
mit
3ee821d12f88e1e86126a6ef052db868
35.931818
127
0.729231
4.403794
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/ScriptValidationForm.kt
1
1332
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.endpoints import com.cognifide.apm.core.endpoints.params.RequestParameter import org.apache.sling.api.SlingHttpServletRequest import org.apache.sling.models.annotations.Model import javax.inject.Inject @Model(adaptables = [SlingHttpServletRequest::class]) class ScriptValidationForm @Inject constructor( @param:RequestParameter("path", optional = false) val path: String, @param:RequestParameter("content", optional = false) val content: String )
apache-2.0
6f1eb9ab59ffe9ee9c23696e4fe46b2c
39.6875
80
0.673423
4.57732
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/model/api/Label.kt
2
689
package com.commit451.gitlab.model.api import android.os.Parcelable import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize /** * A label */ @Parcelize data class Label( @Json(name = "color") var color: String? = null, @Json(name = "name") var name: String? = null, @Json(name = "description") var description: String? = null, @Json(name = "open_issues_count") var openIssuesCount: Int = 0, @Json(name = "closed_issues_count") var closedIssuesCount: Int = 0, @Json(name = "open_merge_requests_count") var openMergeRequestsCount: Int = 0, @Json(name = "subscribed") var isSubscribed: Boolean = false ) : Parcelable
apache-2.0
12607f597c790d48eaa174db368111d0
25.5
45
0.666183
3.445
false
false
false
false
wesamhaboush/kotlin-algorithms
src/main/kotlin/algorithms/champerownes-constant.kt
1
2429
package algorithms /* Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.12345678910>1<112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 Solution: There are, 9 numbers with 1 digit,=9 digits of your sequence; 90 with 2 digits,=90*2=180 digits of your sequence; 900 with 3 digits, =900*3=2700 digits of your sequence; 9000 with 4 digits,=9000*4=36000 digits of your sequence. 90000 with 5 digits,.....so on For finding nth digit, (explained by an example) Let's take n=578, Now there are 9+180=189 digits due to single and double digit numbers. Remaining digits=578-189=389 . Now you to just count 3 digit numbers starting from 100 (the first 3 digits number, cz 99 is the last 2 digits number). 389%3=129 remainder 2. Current number (for nth digit)=100+129=229 So 578th digit is 2. */ fun champerownesDigitAtIndex(targetDigitIndex: Long): Int { var currentNumberOfDigits = 1L var currentIndex = 1L var nextBatchOfDigits = countNumbersWithDigitCount(currentNumberOfDigits) * currentNumberOfDigits while( (currentIndex + nextBatchOfDigits) < targetDigitIndex) { currentIndex += nextBatchOfDigits currentNumberOfDigits++ nextBatchOfDigits = countNumbersWithDigitCount(currentNumberOfDigits) * currentNumberOfDigits } // once we are here, we are stopped at the step where the target index exists // let us find the first number in that step, which is 10^(currentNumberOfDigits) val firstNumberInCurrentStep = countNumbersWithDigitCount(currentNumberOfDigits) / 9 // also find remaining digits to cover val remainingDigits = targetDigitIndex - currentIndex // let's find how many we need to count of the current number of digits: val numberOfCounts = remainingDigits / currentNumberOfDigits val indexOfTargetDigitWithinTargetNumber = remainingDigits % currentNumberOfDigits val targetNumber = firstNumberInCurrentStep + numberOfCounts return numberToDigits(targetNumber)[indexOfTargetDigitWithinTargetNumber.toInt()] } private fun countNumbersWithDigitCount(currentNumberOfDigits: Long) = 9 * Math.pow(10.0, (currentNumberOfDigits - 1).toDouble()).toLong()
gpl-3.0
0468eeb0358b81a950e5a9831da5d61a
36.859375
119
0.766818
4.018242
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt
1
5852
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.R import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class DanaRSPacketBolusGetBolusOption( injector: HasAndroidInjector ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { var dataIndex = DATA_START var dataSize = 1 danaPump.isExtendedBolusEnabled = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 1 dataIndex += dataSize dataSize = 1 danaPump.bolusCalculationOption = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.missedBolusConfig = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus01StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus01StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus01EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus01EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus02StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus02StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus02EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus02EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus03StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus03StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus03EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus03EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus04StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus04StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus04EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val missedBolus04EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) if (!danaPump.isExtendedBolusEnabled) { val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, rh.gs(R.string.danar_enableextendedbolus), Notification.URGENT) rxBus.send(EventNewNotification(notification)) failed = true } else { rxBus.send(EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)) } aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus enabled: " + danaPump.isExtendedBolusEnabled) aapsLogger.debug(LTag.PUMPCOMM, "Missed bolus config: " + danaPump.missedBolusConfig) aapsLogger.debug(LTag.PUMPCOMM, "missedBolus01StartHour: $missedBolus01StartHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus01StartMin: $missedBolus01StartMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus01EndHour: $missedBolus01EndHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus01EndMin: $missedBolus01EndMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus02StartHour: $missedBolus02StartHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus02StartMin: $missedBolus02StartMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus02EndHour: $missedBolus02EndHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus02EndMin: $missedBolus02EndMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus03StartHour: $missedBolus03StartHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus03StartMin: $missedBolus03StartMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus03EndHour: $missedBolus03EndHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus03EndMin: $missedBolus03EndMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus04StartHour: $missedBolus04StartHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus04StartMin: $missedBolus04StartMin") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus04EndHour: $missedBolus04EndHour") aapsLogger.debug(LTag.PUMPCOMM, "missedBolus04EndMin: $missedBolus04EndMin") } override val friendlyName: String = "BOLUS__GET_BOLUS_OPTION" }
agpl-3.0
f835ed6594481d2543fd06a1d2c9942e
50.342105
145
0.725906
4.629747
false
false
false
false
A-Zaiats/Kotlinextensions
kotlinextensions/src/main/java/io/github/azaiats/kotlinextensions/Fragment.kt
1
2097
@file:Suppress("unused") package io.github.azaiats.kotlinextensions import android.app.Fragment import android.support.annotation.StringRes import android.support.v4.app.NotificationCompat import android.widget.Toast import android.support.v4.app.Fragment as SupportFragment /** * @author Andrei Zaiats * @since 10/03/2016 */ fun Fragment?.toast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = this?.let { activity.toast(text, duration) } fun Fragment?.toast(@StringRes textId: Int, duration: Int = Toast.LENGTH_LONG) = this?.let { activity.toast(textId, duration) } fun SupportFragment?.toast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = this?.let { activity.toast(text, duration) } fun SupportFragment?.toast(@StringRes textId: Int, duration: Int = Toast.LENGTH_LONG) = this?.let { activity.toast(textId, duration) } inline fun Fragment.notification(body: NotificationCompat.Builder.() -> Unit) = activity.notification(body) inline fun SupportFragment.notification(body: NotificationCompat.Builder.() -> Unit) = activity.notification(body) fun Fragment.browse(url: String, newTask: Boolean = false) = activity.browse(url, newTask) fun SupportFragment.browse(url: String, newTask: Boolean = false) = activity.browse(url, newTask) fun Fragment.share(text: String, subject: String = "") = activity.share(text, subject) fun SupportFragment.share(text: String, subject: String = "") = activity.share(text, subject) fun Fragment.email(email: String, subject: String = "", text: String = "") = activity.email(email, subject, text) fun SupportFragment.email(email: String, subject: String = "", text: String = "") = activity.email(email, subject, text) fun Fragment.makeCall(number: String) = activity.makeCall(number) fun SupportFragment.makeCall(number: String) = activity.makeCall(number) fun Fragment.sendSms(number: String, text: String = "") = activity.sendSms(number, text) fun SupportFragment.sendSms(number: String, text: String = "") = activity.sendSms(number, text) fun Fragment.rate() = activity.rate() fun SupportFragment.rate() = activity.rate()
apache-2.0
6e797bb36b15fe78bcda55b1ed5e83a5
41.816327
134
0.754411
3.718085
false
false
false
false
square/wire
wire-library/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/ProtoParserTest.kt
1
88879
/* * Copyright (C) 2013 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 com.squareup.wire.schema.internal.parser import com.squareup.wire.Syntax.PROTO_3 import com.squareup.wire.schema.Field.Label.OPTIONAL import com.squareup.wire.schema.Field.Label.REPEATED import com.squareup.wire.schema.Field.Label.REQUIRED import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.MAX_TAG_VALUE import com.squareup.wire.schema.internal.parser.OptionElement.Kind import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test import java.util.Arrays import java.util.LinkedHashMap class ProtoParserTest { internal var location = Location.get("file.proto") @Test fun typeParsing() { val proto = """ |message Types { | required any f1 = 1; | required bool f2 = 2; | required bytes f3 = 3; | required double f4 = 4; | required float f5 = 5; | required fixed32 f6 = 6; | required fixed64 f7 = 7; | required int32 f8 = 8; | required int64 f9 = 9; | required sfixed32 f10 = 10; | required sfixed64 f11 = 11; | required sint32 f12 = 12; | required sint64 f13 = 13; | required string f14 = 14; | required uint32 f15 = 15; | required uint64 f16 = 16; | map<string, bool> f17 = 17; | map<arbitrary, nested.nested> f18 = 18; | required arbitrary f19 = 19; | required nested.nested f20 = 20; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Types", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "any", name = "f1", tag = 1 ), FieldElement( location = location.at(3, 3), label = REQUIRED, type = "bool", name = "f2", tag = 2 ), FieldElement( location = location.at(4, 3), label = REQUIRED, type = "bytes", name = "f3", tag = 3 ), FieldElement( location = location.at(5, 3), label = REQUIRED, type = "double", name = "f4", tag = 4 ), FieldElement( location = location.at(6, 3), label = REQUIRED, type = "float", name = "f5", tag = 5 ), FieldElement( location = location.at(7, 3), label = REQUIRED, type = "fixed32", name = "f6", tag = 6 ), FieldElement( location = location.at(8, 3), label = REQUIRED, type = "fixed64", name = "f7", tag = 7 ), FieldElement( location = location.at(9, 3), label = REQUIRED, type = "int32", name = "f8", tag = 8 ), FieldElement( location = location.at(10, 3), label = REQUIRED, type = "int64", name = "f9", tag = 9 ), FieldElement( location = location.at(11, 3), label = REQUIRED, type = "sfixed32", name = "f10", tag = 10 ), FieldElement( location = location.at(12, 3), label = REQUIRED, type = "sfixed64", name = "f11", tag = 11 ), FieldElement( location = location.at(13, 3), label = REQUIRED, type = "sint32", name = "f12", tag = 12 ), FieldElement( location = location.at(14, 3), label = REQUIRED, type = "sint64", name = "f13", tag = 13 ), FieldElement( location = location.at(15, 3), label = REQUIRED, type = "string", name = "f14", tag = 14 ), FieldElement( location = location.at(16, 3), label = REQUIRED, type = "uint32", name = "f15", tag = 15 ), FieldElement( location = location.at(17, 3), label = REQUIRED, type = "uint64", name = "f16", tag = 16 ), FieldElement( location = location.at(18, 3), type = "map<string, bool>", name = "f17", tag = 17 ), FieldElement( location = location.at(19, 3), type = "map<arbitrary, nested.nested>", name = "f18", tag = 18 ), FieldElement( location = location.at(20, 3), label = REQUIRED, type = "arbitrary", name = "f19", tag = 19 ), FieldElement( location = location.at(21, 3), label = REQUIRED, type = "nested.nested", name = "f20", tag = 20 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun mapWithLabelThrows() { try { ProtoParser.parse(location, "message Hey { required map<string, string> a = 1; }") fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:1:15: 'map' type cannot have label" ) } try { ProtoParser.parse(location, "message Hey { optional map<string, string> a = 1; }") fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:1:15: 'map' type cannot have label" ) } try { ProtoParser.parse(location, "message Hey { repeated map<string, string> a = 1; }") fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:1:15: 'map' type cannot have label" ) } } /** It looks like an option, but 'default' is special. It's not defined as an option. */ @Test fun defaultFieldOptionIsSpecial() { val proto = """ |message Message { | required string a = 1 [default = "b", faulted = "c"]; |} |""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Message", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "a", defaultValue = "b", options = listOf(OptionElement.create("faulted", Kind.STRING, "c")), tag = 1 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } /** It looks like an option, but 'json_name' is special. It's not defined as an option. */ @Test fun jsonNameOptionIsSpecial() { val proto = """ |message Message { | required string a = 1 [json_name = "b", faulted = "c"]; |} |""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Message", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "a", jsonName = "b", tag = 1, options = listOf(OptionElement.create("faulted", Kind.STRING, "c")) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun singleLineComment() { val proto = """ |// Test all the things! |message Test {} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo("Test all the things!") } @Test fun multipleSingleLineComments() { val proto = """ |// Test all |// the things! |message Test {} """.trimMargin() val expected = """ |Test all |the things! """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo(expected) } @Test fun singleLineJavadocComment() { val proto = """ |/** Test */ |message Test {} |""".trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo("Test") } @Test fun multilineJavadocComment() { val proto = """ |/** | * Test | * | * Foo | */ |message Test {} |""".trimMargin() val expected = """ |Test | |Foo """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo(expected) } @Test fun multipleSingleLineCommentsWithLeadingWhitespace() { val proto = """ |// Test |// All |// The |// Things! |message Test {} """.trimMargin() val expected = """ |Test | All | The | Things! """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo(expected) } @Test fun multilineJavadocCommentWithLeadingWhitespace() { val proto = """ |/** | * Test | * All | * The | * Things! | */ |message Test {} """.trimMargin() val expected = """ |Test | All | The | Things! """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo(expected) } @Test fun multilineJavadocCommentWithoutLeadingAsterisks() { // We do not honor leading whitespace when the comment lacks leading asterisks. val proto = """ |/** | Test | All | The | Things! | */ |message Test {} """.trimMargin() val expected = """ |Test |All |The |Things! """.trimMargin() val parsed = ProtoParser.parse(location, proto) val type = parsed.types[0] assertThat(type.documentation).isEqualTo(expected) } @Test fun messageFieldTrailingComment() { // Trailing message field comment. val proto = """ |message Test { | optional string name = 1; // Test all the things! |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val message = parsed.types[0] as MessageElement val field = message.fields[0] assertThat(field.documentation).isEqualTo("Test all the things!") } @Test fun messageFieldLeadingAndTrailingCommentAreCombined() { val proto = """ |message Test { | // Test all... | optional string name = 1; // ...the things! |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val message = parsed.types[0] as MessageElement val field = message.fields[0] assertThat(field.documentation).isEqualTo("Test all...\n...the things!") } @Test fun trailingCommentNotAssignedToFollowingField() { val proto = """ |message Test { | optional string first_name = 1; // Testing! | optional string last_name = 2; |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val message = parsed.types[0] as MessageElement val field1 = message.fields[0] assertThat(field1.documentation).isEqualTo("Testing!") val field2 = message.fields[1] assertThat(field2.documentation).isEqualTo("") } @Test fun enumValueTrailingComment() { val proto = """ |enum Test { | FOO = 1; // Test all the things! |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val enumElement = parsed.types[0] as EnumElement val value = enumElement.constants[0] assertThat(value.documentation).isEqualTo("Test all the things!") } @Test fun trailingSinglelineComment() { val proto = """ |enum Test { | FOO = 1; /* Test all the things! */ | BAR = 2;/*Test all the things!*/ |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val enumElement = parsed.types[0] as EnumElement val foo = enumElement.constants[0] assertThat(foo.documentation).isEqualTo("Test all the things!") val bar = enumElement.constants[1] assertThat(bar.documentation).isEqualTo("Test all the things!") } @Test fun trailingMultilineComment() { val proto = """ |enum Test { | FOO = 1; /* Test all the |things! */ |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val enumElement = parsed.types[0] as EnumElement val value = enumElement.constants[0] assertThat(value.documentation).isEqualTo("Test all the\nthings!") } @Test fun trailingMultilineCommentMustBeLastOnLineThrows() { val proto = """ |enum Test { | FOO = 1; /* Test all the things! */ BAR = 2; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:2:40: no syntax may follow trailing comment" ) } } @Test fun fieldCannotStartWithDigits() { val proto = """ |message Test { | optional string 3DS = 1; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:2:18: field and constant names cannot start with a digit" ) } } @Test fun constantCannotStartWithDigits() { val proto = """ |enum Test { | 3DS = 1; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:2:2: field and constant names cannot start with a digit" ) } } @Test fun invalidTrailingComment() { val proto = """ |enum Test { | FOO = 1; / |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage( "Syntax error in file.proto:2:13: expected '//' or '/*'" ) } } @Test fun enumValueLeadingAndTrailingCommentsAreCombined() { val proto = """ |enum Test { | // Test all... | FOO = 1; // ...the things! |} """.trimMargin() val parsed = ProtoParser.parse(location, proto) val enumElement = parsed.types[0] as EnumElement val value = enumElement.constants[0] assertThat(value.documentation).isEqualTo("Test all...\n...the things!") } @Test fun trailingCommentNotCombinedWhenEmpty() { // Can't use raw strings here; otherwise, the formatter removes the trailing whitespace on line 3. val proto = "enum Test {\n" + " // Test all...\n" + " FOO = 1; // \n" + "}" val parsed = ProtoParser.parse(location, proto) val enumElement = parsed.types[0] as EnumElement val value = enumElement.constants[0] assertThat(value.documentation).isEqualTo("Test all...") } @Test fun syntaxNotRequired() { val proto = "message Foo {}" val parsed = ProtoParser.parse(location, proto) assertThat(parsed.syntax).isNull() } @Test fun syntaxSpecified() { val proto = """ |syntax = "proto3"; |message Foo {} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Foo" ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun invalidSyntaxValueThrows() { val proto = """ |syntax = "proto4"; |message Foo {} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage("Syntax error in file.proto:1:1: unexpected syntax: proto4") } } @Test fun syntaxNotFirstDeclarationThrows() { val proto = """ |message Foo {} |syntax = "proto3"; """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (expected: IllegalStateException) { assertThat(expected).hasMessage( "Syntax error in file.proto:2:1: 'syntax' element must be the first declaration in a file" ) } } @Test fun syntaxMayFollowCommentsAndEmptyLines() { val proto = """ |/* comment 1 */ |// comment 2 | |syntax = "proto3"; |message Foo {} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(5, 1), name = "Foo" ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3MessageFieldsDoNotRequireLabels() { val proto = """ |syntax = "proto3"; |message Message { | string a = 1; | int32 b = 2; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message", fields = listOf( FieldElement( location = location.at(3, 3), type = "string", name = "a", tag = 1 ), FieldElement( location = location.at(4, 3), type = "int32", name = "b", tag = 2 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3ExtensionFieldsDoNotRequireLabels() { val proto = """ |syntax = "proto3"; |message Message { |} |extend Message { | string a = 1; | int32 b = 2; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message" ) ), extendDeclarations = listOf( ExtendElement( location = location.at(4, 1), name = "Message", fields = listOf( FieldElement( location = location.at(5, 3), type = "string", name = "a", tag = 1 ), FieldElement( location = location.at(6, 3), type = "int32", name = "b", tag = 2 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3MessageFieldsAllowOptional() { val proto = """ |syntax = "proto3"; |message Message { | optional string a = 1; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message", fields = listOf( FieldElement( location = location.at(3, 3), type = "string", name = "a", tag = 1, label = OPTIONAL ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3MessageFieldsForbidRequired() { val proto = """ |syntax = "proto3"; |message Message { | required string a = 1; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (expected: IllegalStateException) { assertThat(expected).hasMessage( "Syntax error in file.proto:3:3: 'required' label forbidden in proto3 field declarations" ) } } @Test fun proto3ExtensionFieldsAllowOptional() { val proto = """ |syntax = "proto3"; |message Message { |} |extend Message { | optional string a = 1; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message" ) ), extendDeclarations = listOf( ExtendElement( location = location.at(4, 1), name = "Message", fields = listOf( FieldElement( location = location.at(5, 3), type = "string", name = "a", tag = 1, label = OPTIONAL ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3ExtensionFieldsForbidsRequired() { val proto = """ |syntax = "proto3"; |message Message { |} |extend Message { | required string a = 1; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (expected: IllegalStateException) { assertThat(expected).hasMessage( "Syntax error in file.proto:5:3: 'required' label forbidden in proto3 field declarations" ) } } @Test fun proto3MessageFieldsPermitRepeated() { val proto = """ |syntax = "proto3"; |message Message { | repeated string a = 1; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message", fields = listOf( FieldElement( location = location.at(3, 3), label = REPEATED, type = "string", name = "a", tag = 1 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun proto3ExtensionFieldsPermitRepeated() { val proto = """ |syntax = "proto3"; |message Message { |} |extend Message { | repeated string a = 1; |} """.trimMargin() val expected = ProtoFileElement( location = location, syntax = PROTO_3, types = listOf( MessageElement( location = location.at(2, 1), name = "Message" ) ), extendDeclarations = listOf( ExtendElement( location = location.at(4, 1), name = "Message", fields = listOf( FieldElement( location = location.at(5, 3), label = REPEATED, type = "string", name = "a", tag = 1 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun parseMessageAndFields() { val proto = """ |message SearchRequest { | required string query = 1; | optional int32 page_number = 2; | optional int32 result_per_page = 3; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "SearchRequest", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "query", tag = 1 ), FieldElement( location = location.at(3, 3), label = OPTIONAL, type = "int32", name = "page_number", tag = 2 ), FieldElement( location = location.at(4, 3), label = OPTIONAL, type = "int32", name = "result_per_page", tag = 3 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun group() { val proto = """ |message SearchResponse { | repeated group Result = 1 { | required string url = 2; | optional string title = 3; | repeated string snippets = 4; | } |} """.trimMargin() val message = MessageElement( location = location.at(1, 1), name = "SearchResponse", groups = listOf( GroupElement( location = location.at(2, 3), label = REPEATED, name = "Result", tag = 1, fields = listOf( FieldElement( location = location.at(3, 5), label = REQUIRED, type = "string", name = "url", tag = 2 ), FieldElement( location = location.at(4, 5), label = OPTIONAL, type = "string", name = "title", tag = 3 ), FieldElement( location = location.at(5, 5), label = REPEATED, type = "string", name = "snippets", tag = 4 ) ) ) ) ) val expected = ProtoFileElement( location = location, types = listOf(message) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun parseMessageAndOneOf() { val proto = """ |message SearchRequest { | required string query = 1; | oneof page_info { | int32 page_number = 2; | int32 result_per_page = 3; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "SearchRequest", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "query", tag = 1 ) ), oneOfs = listOf( OneOfElement( name = "page_info", fields = listOf( FieldElement( location = location.at(4, 5), type = "int32", name = "page_number", tag = 2 ), FieldElement( location = location.at(5, 5), type = "int32", name = "result_per_page", tag = 3 ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun parseMessageAndOneOfWithGroup() { val proto = """ |message SearchRequest { | required string query = 1; | oneof page_info { | int32 page_number = 2; | group Stuff = 3 { | optional int32 result_per_page = 4; | optional int32 page_count = 5; | } | } |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "SearchRequest", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "query", tag = 1 ) ), oneOfs = listOf( OneOfElement( name = "page_info", fields = listOf( FieldElement( location = location.at(4, 5), type = "int32", name = "page_number", tag = 2 ) ), groups = listOf( GroupElement( location = location.at(5, 5), name = "Stuff", tag = 3, fields = listOf( FieldElement( location = location.at(6, 7), label = OPTIONAL, type = "int32", name = "result_per_page", tag = 4 ), FieldElement( location = location.at(7, 7), label = OPTIONAL, type = "int32", name = "page_count", tag = 5 ) ) ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun parseEnum() { val proto = """ |/** | * What's on my waffles. | * Also works on pancakes. | */ |enum Topping { | FRUIT = 1; | /** Yummy, yummy cream. */ | CREAM = 2; | | // Quebec Maple syrup | SYRUP = 3; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( EnumElement( location = location.at(5, 1), name = "Topping", documentation = "What's on my waffles.\nAlso works on pancakes.", constants = listOf( EnumConstantElement( location = location.at(6, 3), name = "FRUIT", tag = 1 ), EnumConstantElement( location = location.at(8, 3), name = "CREAM", tag = 2, documentation = "Yummy, yummy cream." ), EnumConstantElement( location = location.at(11, 3), name = "SYRUP", tag = 3, documentation = "Quebec Maple syrup" ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun parseEnumWithOptions() { val proto = """ |/** | * What's on my waffles. | * Also works on pancakes. | */ |enum Topping { | option(max_choices) = 2; | | FRUIT = 1[(healthy) = true]; | /** Yummy, yummy cream. */ | CREAM = 2; | | // Quebec Maple syrup | SYRUP = 3; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( EnumElement( location = location.at(5, 1), name = "Topping", documentation = "What's on my waffles.\nAlso works on pancakes.", options = listOf(OptionElement.create("max_choices", Kind.NUMBER, "2", true)), constants = listOf( EnumConstantElement( location = location.at(8, 3), name = "FRUIT", tag = 1, options = listOf( OptionElement.create("healthy", Kind.BOOLEAN, "true", true) ) ), EnumConstantElement( location = location.at(10, 3), name = "CREAM", tag = 2, documentation = "Yummy, yummy cream." ), EnumConstantElement( location = location.at(13, 3), name = "SYRUP", tag = 3, documentation = "Quebec Maple syrup" ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun packageDeclaration() { val proto = """ |package google.protobuf; |option java_package = "com.google.protobuf"; | |// The protocol compiler can output a FileDescriptorSet containing the .proto |// files it parses. |message FileDescriptorSet { |} """.trimMargin() val expected = ProtoFileElement( location = location, packageName = "google.protobuf", types = listOf( MessageElement( location = location.at(6, 1), name = "FileDescriptorSet", documentation = "The protocol compiler can output a FileDescriptorSet containing the .proto\nfiles it parses." ) ), options = listOf(OptionElement.create("java_package", Kind.STRING, "com.google.protobuf")) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun nestingInMessage() { val proto = """ |message FieldOptions { | optional CType ctype = 1[old_default = STRING, deprecated = true]; | enum CType { | STRING = 0[(opt_a) = 1, (opt_b) = 2]; | }; | // Clients can define custom options in extensions of this message. See above. | extensions 500; | extensions 1000 to max; |} """.trimMargin() val enumElement = EnumElement( location = location.at(3, 3), name = "CType", constants = listOf( EnumConstantElement( location = location.at(4, 5), name = "STRING", tag = 0, options = listOf( OptionElement.create("opt_a", Kind.NUMBER, "1", true), OptionElement.create("opt_b", Kind.NUMBER, "2", true) ) ) ) ) val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "CType", name = "ctype", tag = 1, options = listOf( OptionElement.create("old_default", Kind.ENUM, "STRING"), OptionElement.create("deprecated", Kind.BOOLEAN, "true") ) ) assertThat(field.options) .containsOnly( OptionElement.create("old_default", Kind.ENUM, "STRING"), OptionElement.create("deprecated", Kind.BOOLEAN, "true") ) val messageElement = MessageElement( location = location.at(1, 1), name = "FieldOptions", fields = listOf(field), nestedTypes = listOf(enumElement), extensions = listOf( ExtensionsElement( location = location.at(7, 3), documentation = "Clients can define custom options in extensions of this message. See above.", values = listOf(500) ), ExtensionsElement(location.at(8, 3), "", listOf(1000..MAX_TAG_VALUE)) ) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) val actual = ProtoParser.parse(location, proto) assertThat(actual).isEqualTo(expected) } @Test fun multiRangesExtensions() { val proto = """ |message MeGustaExtensions { | extensions 1, 5 to 200, 500, 1000 to max; |} """.trimMargin() val messageElement = MessageElement( location = location.at(1, 1), name = "MeGustaExtensions", fields = emptyList(), nestedTypes = emptyList(), extensions = listOf( ExtensionsElement( location = location.at(2, 3), values = listOf(1, 5..200, 500, 1000..MAX_TAG_VALUE) ) ) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) val actual = ProtoParser.parse(location, proto) assertThat(actual).isEqualTo(expected) } @Test fun optionParentheses() { val proto = """ |message Chickens { | optional bool koka_ko_koka_ko = 1[old_default = true]; | optional bool coodle_doodle_do = 2[(delay) = 100, old_default = false]; | optional bool coo_coo_ca_cha = 3[old_default = true, (delay) = 200]; | optional bool cha_chee_cha = 4; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Chickens", fields = listOf( FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "bool", name = "koka_ko_koka_ko", tag = 1, options = listOf( OptionElement.create("old_default", Kind.BOOLEAN, "true") ) ), FieldElement( location = location.at(3, 3), label = OPTIONAL, type = "bool", name = "coodle_doodle_do", tag = 2, options = listOf( OptionElement.create("delay", Kind.NUMBER, "100", true), OptionElement.create("old_default", Kind.BOOLEAN, "false") ) ), FieldElement( location = location.at(4, 3), label = OPTIONAL, type = "bool", name = "coo_coo_ca_cha", tag = 3, options = listOf( OptionElement.create("old_default", Kind.BOOLEAN, "true"), OptionElement.create("delay", Kind.NUMBER, "200", true) ) ), FieldElement( location = location.at(5, 3), label = OPTIONAL, type = "bool", name = "cha_chee_cha", tag = 4 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun imports() { val proto = "import \"src/test/resources/unittest_import.proto\";\n" val expected = ProtoFileElement( location = location, imports = listOf("src/test/resources/unittest_import.proto") ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun publicImports() { val proto = "import public \"src/test/resources/unittest_import.proto\";\n" val expected = ProtoFileElement( location = location, publicImports = listOf("src/test/resources/unittest_import.proto") ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun extend() { val proto = """ |// Extends Foo |extend Foo { | optional int32 bar = 126; |} """.trimMargin() val expected = ProtoFileElement( location = location, extendDeclarations = listOf( ExtendElement( location = location.at(2, 1), name = "Foo", documentation = "Extends Foo", fields = listOf( FieldElement( location = location.at(3, 3), label = OPTIONAL, type = "int32", name = "bar", tag = 126 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun extendInMessage() { val proto = """ |message Bar { | extend Foo { | optional Bar bar = 126; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Bar", extendDeclarations = listOf( ExtendElement( location = location.at(2, 3), name = "Foo", fields = listOf( FieldElement( location = location.at(3, 5), label = OPTIONAL, type = "Bar", name = "bar", tag = 126 ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun extendInMessageWithPackage() { val proto = """ |package kit.kat; | |message Bar { | extend Foo { | optional Bar bar = 126; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, packageName = "kit.kat", types = listOf( MessageElement( location = location.at(3, 1), name = "Bar", extendDeclarations = listOf( ExtendElement( location = location.at(4, 3), name = "Foo", fields = listOf( FieldElement( location = location.at(5, 5), label = OPTIONAL, type = "Bar", name = "bar", tag = 126 ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun fqcnExtendInMessage() { val proto = """ |message Bar { | extend example.Foo { | optional Bar bar = 126; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Bar", extendDeclarations = listOf( ExtendElement( location = location.at(2, 3), name = "example.Foo", fields = listOf( FieldElement( location = location.at(3, 5), label = OPTIONAL, type = "Bar", name = "bar", tag = 126 ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun fqcnExtendInMessageWithPackage() { val proto = """ |package kit.kat; | |message Bar { | extend example.Foo { | optional Bar bar = 126; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, packageName = "kit.kat", types = listOf( MessageElement( location = location.at(3, 1), name = "Bar", extendDeclarations = listOf( ExtendElement( location = location.at(4, 3), name = "example.Foo", fields = listOf( FieldElement( location = location.at(5, 5), label = OPTIONAL, type = "Bar", name = "bar", tag = 126 ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun defaultFieldWithParen() { val proto = """ |message Foo { | optional string claim_token = 2[(squareup.redacted) = true]; |} """.trimMargin() val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "claim_token", tag = 2, options = listOf(OptionElement.create("squareup.redacted", Kind.BOOLEAN, "true", true)) ) assertThat(field.options) .containsOnly(OptionElement.create("squareup.redacted", Kind.BOOLEAN, "true", true)) val messageElement = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf(field) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) assertThat(ProtoParser.parse(location, proto)) .isEqualTo(expected) } // Parse \a, \b, \f, \n, \r, \t, \v, \[0-7]{1-3}, and \[xX]{0-9a-fA-F]{1,2} @Test fun defaultFieldWithStringEscapes() { val proto = """ |message Foo { | optional string name = 1 [ | x = "\a\b\f\n\r\t\v\1f\01\001\11\011\111\xe\Xe\xE\xE\x41\X41" | ]; |} """.trimMargin() val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "name", tag = 1, options = listOf( OptionElement.create( "x", Kind.STRING, "\u0007\b\u000C\n\r\t\u000b\u0001f\u0001\u0001\u0009\u0009I\u000e\u000e\u000e\u000eAA" ) ) ) assertThat(field.options) .containsOnly( OptionElement.create( "x", Kind.STRING, "\u0007\b\u000C\n\r\t\u000b\u0001f\u0001\u0001\u0009\u0009I\u000e\u000e\u000e\u000eAA" ) ) val messageElement = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf(field) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) assertThat(ProtoParser.parse(location, proto)) .isEqualTo(expected) } @Test fun stringWithSingleQuotes() { val proto = """ |message Foo { | optional string name = 1[default = 'single\"quotes']; |} """.trimMargin() val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "name", tag = 1, defaultValue = "single\"quotes" ) val messageElement = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf(field) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun adjacentStringsConcatenated() { val proto = """ |message Foo { | optional string name = 1 [ | default = "concat " | 'these ' | "please" | ]; |} """.trimMargin() val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "name", tag = 1, defaultValue = "concat these please" ) val messageElement = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf(field) ) val expected = ProtoFileElement( location = location, types = listOf(messageElement) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun invalidHexStringEscape() { val proto = """ |message Foo { | optional string name = 1 [default = "\xW"]; |} """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (e: IllegalStateException) { assertThat(e.message!!.contains("expected a digit after \\x or \\X")) } } @Test fun service() { val proto = """ |service SearchService { | option (default_timeout) = 30; | | rpc Search (SearchRequest) returns (SearchResponse); | rpc Purchase (PurchaseRequest) returns (PurchaseResponse) { | option (squareup.sake.timeout) = 15; | option (squareup.a.b) = { | value: [ | FOO, | BAR | ] | }; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, services = listOf( ServiceElement( location = location.at(1, 1), name = "SearchService", options = listOf( OptionElement.create("default_timeout", Kind.NUMBER, "30", true) ), rpcs = listOf( RpcElement( location = location.at(4, 3), name = "Search", requestType = "SearchRequest", responseType = "SearchResponse" ), RpcElement( location = location.at(5, 3), name = "Purchase", requestType = "PurchaseRequest", responseType = "PurchaseResponse", options = listOf( OptionElement.create("squareup.sake.timeout", Kind.NUMBER, "15", true), OptionElement.create( "squareup.a.b", Kind.MAP, mapOf("value" to listOf(OptionElement.OptionPrimitive(Kind.ENUM, "FOO"), OptionElement.OptionPrimitive(Kind.ENUM, "BAR"))), true ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun streamingService() { val proto = """ |service RouteGuide { | rpc GetFeature (Point) returns (Feature) {} | rpc ListFeatures (Rectangle) returns (stream Feature) {} | rpc RecordRoute (stream Point) returns (RouteSummary) {} | rpc RouteChat (stream RouteNote) returns (stream RouteNote) {} |} """.trimMargin() val expected = ProtoFileElement( location = location, services = listOf( ServiceElement( location = location.at(1, 1), name = "RouteGuide", rpcs = listOf( RpcElement( location = location.at(2, 3), name = "GetFeature", requestType = "Point", responseType = "Feature" ), RpcElement( location = location.at(3, 3), name = "ListFeatures", requestType = "Rectangle", responseType = "Feature", responseStreaming = true ), RpcElement( location = location.at(4, 3), name = "RecordRoute", requestType = "Point", responseType = "RouteSummary", requestStreaming = true ), RpcElement( location = location.at(5, 3), name = "RouteChat", requestType = "RouteNote", responseType = "RouteNote", requestStreaming = true, responseStreaming = true ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun hexTag() { val proto = """ |message HexTag { | required string hex = 0x10; | required string uppercase_x_hex = 0X11; |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "HexTag", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "hex", tag = 16 ), FieldElement( location = location.at(3, 3), label = REQUIRED, type = "string", name = "uppercase_x_hex", tag = 17 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun structuredOption() { val proto = """ |message ExoticOptions { | option (squareup.one) = {name: "Name", class_name:"ClassName"}; | option (squareup.two.a) = {[squareup.options.type]: EXOTIC}; | option (squareup.two.b) = {names: ["Foo", "Bar"]}; | option (squareup.three) = {x: {y: 1 y: 2 } }; // NOTE: Omitted optional comma | option (squareup.four) = {x: {y: {z: 1 }, y: {z: 2 }}}; |} """.trimMargin() val option_one_map = LinkedHashMap<String, String>() option_one_map["name"] = "Name" option_one_map["class_name"] = "ClassName" val option_two_a_map = LinkedHashMap<String, Any>() option_two_a_map["[squareup.options.type]"] = OptionElement.OptionPrimitive(Kind.ENUM, "EXOTIC") val option_two_b_map = LinkedHashMap<String, List<String>>() option_two_b_map["names"] = Arrays.asList("Foo", "Bar") val option_three_map = LinkedHashMap<String, Map<String, *>>() val option_three_nested_map = LinkedHashMap<String, Any>() option_three_nested_map["y"] = Arrays.asList(OptionElement.OptionPrimitive(Kind.NUMBER, "1"), OptionElement.OptionPrimitive(Kind.NUMBER, "2")) option_three_map["x"] = option_three_nested_map val option_four_map = LinkedHashMap<String, Map<String, *>>() val option_four_map_1 = LinkedHashMap<String, Any>() val option_four_map_2_a = LinkedHashMap<String, Any>() option_four_map_2_a["z"] = OptionElement.OptionPrimitive(Kind.NUMBER, "1") val option_four_map_2_b = LinkedHashMap<String, Any>() option_four_map_2_b["z"] = OptionElement.OptionPrimitive(Kind.NUMBER, "2") option_four_map_1["y"] = listOf(option_four_map_2_a, option_four_map_2_b) option_four_map["x"] = option_four_map_1 val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "ExoticOptions", options = listOf( OptionElement.create("squareup.one", Kind.MAP, option_one_map, true), OptionElement.create( "squareup.two.a", Kind.MAP, option_two_a_map, true ), OptionElement.create( "squareup.two.b", Kind.MAP, option_two_b_map, true ), OptionElement.create( "squareup.three", Kind.MAP, option_three_map, true ), OptionElement.create("squareup.four", Kind.MAP, option_four_map, true) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun optionsWithNestedMapsAndTrailingCommas() { val proto = """ |message StructuredOption { | optional field.type has_options = 3 [ | (option_map) = { | nested_map: {key:"value", key2:["value2a","value2b"]}, | }, | (option_string) = ["string1","string2"] | ]; |} """.trimMargin() val field = FieldElement( location = location.at(2, 5), label = OPTIONAL, type = "field.type", name = "has_options", tag = 3, options = listOf( OptionElement.create( "option_map", Kind.MAP, mapOf( "nested_map" to mapOf("key" to "value", "key2" to listOf("value2a", "value2b")) ), true ), OptionElement.create("option_string", Kind.LIST, listOf("string1", "string2"), true) ) ) assertThat(field.options) .containsOnly( OptionElement.create( "option_map", Kind.MAP, mapOf( "nested_map" to mapOf("key" to "value", "key2" to listOf("value2a", "value2b")) ), true ), OptionElement.create("option_string", Kind.LIST, listOf("string1", "string2"), true) ) val expected = MessageElement( location = location.at(1, 1), name = "StructuredOption", fields = listOf(field) ) val protoFile = ProtoFileElement( location = location, types = listOf(expected) ) assertThat(ProtoParser.parse(location, proto)) .isEqualTo(protoFile) } @Test fun optionNumericalBounds() { val proto = """ |message Test { | optional int32 default_int32 = 401 [x = 2147483647]; | optional uint32 default_uint32 = 402 [x = 4294967295]; | optional sint32 default_sint32 = 403 [x = -2147483648]; | optional fixed32 default_fixed32 = 404 [x = 4294967295]; | optional sfixed32 default_sfixed32 = 405 [x = -2147483648]; | optional int64 default_int64 = 406 [x = 9223372036854775807]; | optional uint64 default_uint64 = 407 [x = 18446744073709551615]; | optional sint64 default_sint64 = 408 [x = -9223372036854775808]; | optional fixed64 default_fixed64 = 409 [x = 18446744073709551615]; | optional sfixed64 default_sfixed64 = 410 [x = -9223372036854775808]; | optional bool default_bool = 411 [x = true]; | optional float default_float = 412 [x = 123.456e7]; | optional double default_double = 413 [x = 123.456e78]; | optional string default_string = 414 [x = "çok\a\b\f\n\r\t\v\1\01\001\17\017\176\x1\x01\x11\X1\X01\X11güzel" ]; | optional bytes default_bytes = 415 [x = "çok\a\b\f\n\r\t\v\1\01\001\17\017\176\x1\x01\x11\X1\X01\X11güzel" ]; | optional NestedEnum default_nested_enum = 416 [x = A ]; |}""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Test", fields = listOf( FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "int32", name = "default_int32", tag = 401, options = listOf(OptionElement.create("x", Kind.NUMBER, "2147483647")) ), FieldElement( location = location.at(3, 3), label = OPTIONAL, type = "uint32", name = "default_uint32", tag = 402, options = listOf(OptionElement.create("x", Kind.NUMBER, "4294967295")) ), FieldElement( location = location.at(4, 3), label = OPTIONAL, type = "sint32", name = "default_sint32", tag = 403, options = listOf(OptionElement.create("x", Kind.NUMBER, "-2147483648")) ), FieldElement( location = location.at(5, 3), label = OPTIONAL, type = "fixed32", name = "default_fixed32", tag = 404, options = listOf(OptionElement.create("x", Kind.NUMBER, "4294967295")) ), FieldElement( location = location.at(6, 3), label = OPTIONAL, type = "sfixed32", name = "default_sfixed32", tag = 405, options = listOf(OptionElement.create("x", Kind.NUMBER, "-2147483648")) ), FieldElement( location = location.at(7, 3), label = OPTIONAL, type = "int64", name = "default_int64", tag = 406, options = listOf( OptionElement.create("x", Kind.NUMBER, "9223372036854775807") ) ), FieldElement( location = location.at(8, 3), label = OPTIONAL, type = "uint64", name = "default_uint64", tag = 407, options = listOf( OptionElement.create("x", Kind.NUMBER, "18446744073709551615") ) ), FieldElement( location = location.at(9, 3), label = OPTIONAL, type = "sint64", name = "default_sint64", tag = 408, options = listOf( OptionElement.create("x", Kind.NUMBER, "-9223372036854775808") ) ), FieldElement( location = location.at(10, 3), label = OPTIONAL, type = "fixed64", name = "default_fixed64", tag = 409, options = listOf( OptionElement.create("x", Kind.NUMBER, "18446744073709551615") ) ), FieldElement( location = location.at(11, 3), label = OPTIONAL, type = "sfixed64", name = "default_sfixed64", tag = 410, options = listOf( OptionElement.create("x", Kind.NUMBER, "-9223372036854775808") ) ), FieldElement( location = location.at(12, 3), label = OPTIONAL, type = "bool", name = "default_bool", tag = 411, options = listOf(OptionElement.create("x", Kind.BOOLEAN, "true")) ), FieldElement( location = location.at(13, 3), label = OPTIONAL, type = "float", name = "default_float", tag = 412, options = listOf(OptionElement.create("x", Kind.NUMBER, "123.456e7")) ), FieldElement( location = location.at(14, 3), label = OPTIONAL, type = "double", name = "default_double", tag = 413, options = listOf(OptionElement.create("x", Kind.NUMBER, "123.456e78")) ), FieldElement( location = location.at(15, 3), label = OPTIONAL, type = "string", name = "default_string", tag = 414, options = listOf( OptionElement.create( "x", Kind.STRING, "çok\u0007\b\u000C\n\r\t\u000b\u0001\u0001\u0001\u000f\u000f~\u0001\u0001\u0011\u0001\u0001\u0011güzel" ) ) ), FieldElement( location = location.at(17, 3), label = OPTIONAL, type = "bytes", name = "default_bytes", tag = 415, options = listOf( OptionElement.create( "x", Kind.STRING, "çok\u0007\b\u000C\n\r\t\u000b\u0001\u0001\u0001\u000f\u000f~\u0001\u0001\u0011\u0001\u0001\u0011güzel" ) ) ), FieldElement( location = location.at(19, 3), label = OPTIONAL, type = "NestedEnum", name = "default_nested_enum", tag = 416, options = listOf(OptionElement.create("x", Kind.ENUM, "A")) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun extensionWithNestedMessage() { val proto = """ |message Foo { | optional int32 bar = 1[ | (validation.range).min = 1, | (validation.range).max = 100, | old_default = 20 | ]; |} """.trimMargin() val field = FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "int32", name = "bar", tag = 1, options = listOf( OptionElement.create( "validation.range", Kind.OPTION, OptionElement.create("min", Kind.NUMBER, "1"), true ), OptionElement.create( "validation.range", Kind.OPTION, OptionElement.create("max", Kind.NUMBER, "100"), true ), OptionElement.create("old_default", Kind.NUMBER, "20") ) ) assertThat(field.options) .containsOnly( OptionElement.create( "validation.range", Kind.OPTION, OptionElement.create("min", Kind.NUMBER, "1"), true ), OptionElement.create( "validation.range", Kind.OPTION, OptionElement.create("max", Kind.NUMBER, "100"), true ), OptionElement.create("old_default", Kind.NUMBER, "20") ) val expected = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf(field) ) val protoFile = ProtoFileElement( location = location, types = listOf(expected) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(protoFile) } @Test fun reservedMessage() { val proto = """ |message Foo { | reserved 10, 12 to 14, 23 to max, 'foo', "bar"; |} """.trimMargin() val message = MessageElement( location = location.at(1, 1), name = "Foo", reserveds = listOf( ReservedElement( location = location.at(2, 3), values = listOf(10, 12..14, 23..MAX_TAG_VALUE, "foo", "bar") ) ) ) val expected = ProtoFileElement( location = location, types = listOf(message) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } // Reserved are not supported yet for enums, this test asserts that we don't crash parsing them. // See https://github.com/square/wire/issues/797 @Test fun reservedEnum() { val proto = """ |enum Foo { | reserved 10, 12 to 14, 23 to max, 'FOO', "BAR"; | reserved 3; |} """.trimMargin() val message = EnumElement( location = location.at(1, 1), name = "Foo", reserveds = listOf( ReservedElement( location = location.at(2, 3), values = listOf(10, 12..14, 23..MAX_TAG_VALUE, "FOO", "BAR") ), ReservedElement( location = location.at(3, 3), values = listOf(3) ), ), ) val expected = ProtoFileElement( location = location, types = listOf(message) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun reservedWithComments() { val proto = """ |message Foo { | optional string a = 1; // This is A. | reserved 2; // This is reserved. | optional string c = 3; // This is C. |} """.trimMargin() val message = MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf( FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "a", tag = 1, documentation = "This is A." ), FieldElement( location = location.at(4, 3), label = OPTIONAL, type = "string", name = "c", tag = 3, documentation = "This is C." ) ), reserveds = listOf( ReservedElement( location = location.at(3, 3), values = listOf(2), documentation = "This is reserved." ) ) ) val expected = ProtoFileElement( location = location, types = listOf(message) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun noWhitespace() { val proto = "message C {optional A.B ab = 1;}" val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "C", fields = listOf( FieldElement( location = location.at(1, 12), label = OPTIONAL, type = "A.B", name = "ab", tag = 1 ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun deepOptionAssignments() { val proto = """ |message Foo { | optional string a = 1 [(wire.my_field_option).baz.value = "a"]; |} |""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "Foo", fields = listOf( FieldElement( location = location.at(2, 3), label = OPTIONAL, type = "string", name = "a", tag = 1, options = listOf( OptionElement( name = "wire.my_field_option", kind = Kind.OPTION, isParenthesized = true, value = OptionElement( name = "baz", kind = Kind.OPTION, isParenthesized = false, value = OptionElement( name = "value", kind = Kind.STRING, isParenthesized = false, value = "a" ) ) ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun protoKeywordAsEnumConstants() { // Note: this is consistent with protoc. val proto = """ |enum Foo { | syntax = 0; | import = 1; | package = 2; | // option = 3; | // reserved = 4; | message = 5; | enum = 6; | service = 7; | extend = 8; | rpc = 9; | oneof = 10; | extensions = 11; |} |""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( EnumElement( location = location.at(1, 1), name = "Foo", constants = listOf( EnumConstantElement(location.at(2, 3), "syntax", 0), EnumConstantElement(location.at(3, 3), "import", 1), EnumConstantElement(location.at(4, 3), "package", 2), EnumConstantElement( location.at(7, 3), "message", 5, documentation = "option = 3;\nreserved = 4;" ), EnumConstantElement(location.at(8, 3), "enum", 6), EnumConstantElement(location.at(9, 3), "service", 7), EnumConstantElement(location.at(10, 3), "extend", 8), EnumConstantElement(location.at(11, 3), "rpc", 9), EnumConstantElement(location.at(12, 3), "oneof", 10), EnumConstantElement(location.at(13, 3), "extensions", 11), ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun protoKeywordAsMessageNameAndFieldProto2() { // Note: this is consistent with protoc. val proto = """ |message syntax { | optional syntax syntax = 1; |} |message import { | optional import import = 1; |} |message package { | optional package package = 1; |} |message option { | optional option option = 1; |} |message reserved { | optional reserved reserved = 1; |} |message message { | optional message message = 1; |} |message enum { | optional enum enum = 1; |} |message service { | optional service service = 1; |} |message extend { | optional extend extend = 1; |} |message rpc { | optional rpc rpc = 1; |} |message oneof { | optional oneof oneof = 1; |} |message extensions { | optional extensions extensions = 1; |} |""".trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "syntax", fields = listOf( FieldElement( location.at(2, 3), label = OPTIONAL, type = "syntax", name = "syntax", tag = 1 ) ) ), MessageElement( location = location.at(4, 1), name = "import", fields = listOf( FieldElement( location.at(5, 3), label = OPTIONAL, type = "import", name = "import", tag = 1 ) ) ), MessageElement( location = location.at(7, 1), name = "package", fields = listOf( FieldElement( location.at(8, 3), label = OPTIONAL, type = "package", name = "package", tag = 1 ) ) ), MessageElement( location = location.at(10, 1), name = "option", fields = listOf( FieldElement( location.at(11, 3), label = OPTIONAL, type = "option", name = "option", tag = 1 ) ) ), MessageElement( location = location.at(13, 1), name = "reserved", fields = listOf( FieldElement( location.at(14, 3), label = OPTIONAL, type = "reserved", name = "reserved", tag = 1 ) ) ), MessageElement( location = location.at(16, 1), name = "message", fields = listOf( FieldElement( location.at(17, 3), label = OPTIONAL, type = "message", name = "message", tag = 1 ) ) ), MessageElement( location = location.at(19, 1), name = "enum", fields = listOf( FieldElement( location.at(20, 3), label = OPTIONAL, type = "enum", name = "enum", tag = 1 ) ) ), MessageElement( location = location.at(22, 1), name = "service", fields = listOf( FieldElement( location.at(23, 3), label = OPTIONAL, type = "service", name = "service", tag = 1 ) ) ), MessageElement( location = location.at(25, 1), name = "extend", fields = listOf( FieldElement( location.at(26, 3), label = OPTIONAL, type = "extend", name = "extend", tag = 1 ) ) ), MessageElement( location = location.at(28, 1), name = "rpc", fields = listOf( FieldElement( location.at(29, 3), label = OPTIONAL, type = "rpc", name = "rpc", tag = 1 ) ) ), MessageElement( location = location.at(31, 1), name = "oneof", fields = listOf( FieldElement( location.at(32, 3), label = OPTIONAL, type = "oneof", name = "oneof", tag = 1 ) ) ), MessageElement( location = location.at(34, 1), name = "extensions", fields = listOf( FieldElement( location.at(35, 3), label = OPTIONAL, type = "extensions", name = "extensions", tag = 1 ) ) ), ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun protoKeywordAsMessageNameAndFieldProto3() { // Note: this is consistent with protoc. val proto = """ |syntax = "proto3"; |message syntax { | syntax syntax = 1; |} |message import { | import import = 1; |} |message package { | package package = 1; |} |message option { | option option = 1; |} |message reserved { | // reserved reserved = 1; |} |message message { | // message message = 1; |} |message enum { | // enum enum = 1; |} |message service { | service service = 1; |} |message extend { | // extend extend = 1; |} |message rpc { | rpc rpc = 1; |} |message oneof { | // oneof oneof = 1; |} |message extensions { | // extensions extensions = 1; |} |""".trimMargin() val expected = ProtoFileElement( syntax = PROTO_3, location = location, types = listOf( MessageElement( location = location.at(2, 1), name = "syntax", fields = listOf( FieldElement(location.at(3, 3), type = "syntax", name = "syntax", tag = 1) ) ), MessageElement( location = location.at(5, 1), name = "import", fields = listOf( FieldElement(location.at(6, 3), type = "import", name = "import", tag = 1) ) ), MessageElement( location = location.at(8, 1), name = "package", fields = listOf( FieldElement(location.at(9, 3), type = "package", name = "package", tag = 1) ) ), MessageElement( location = location.at(11, 1), name = "option", options = listOf( OptionElement( name = "option", kind = Kind.NUMBER, value = "1", isParenthesized = false ) ), ), MessageElement( location = location.at(14, 1), name = "reserved", ), MessageElement( location = location.at(17, 1), name = "message", ), MessageElement( location = location.at(20, 1), name = "enum", ), MessageElement( location = location.at(23, 1), name = "service", fields = listOf( FieldElement(location.at(24, 3), type = "service", name = "service", tag = 1) ) ), MessageElement( location = location.at(26, 1), name = "extend", ), MessageElement( location = location.at(29, 1), name = "rpc", fields = listOf( FieldElement(location.at(30, 3), type = "rpc", name = "rpc", tag = 1) ) ), MessageElement( location = location.at(32, 1), name = "oneof", ), MessageElement( location = location.at(35, 1), name = "extensions", ), ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun protoKeywordAsServiceNameAndRpc() { // Note: this is consistent with protoc. val proto = """ |service syntax { | rpc syntax (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service import { | rpc import (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service package { | rpc package (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service option { | rpc option (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service reserved { | rpc reserved (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service message { | rpc message (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service enum { | rpc enum (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service service { | rpc service (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service extend { | rpc extend (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service rpc { | rpc rpc (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service oneof { | rpc oneof (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |service extensions { | rpc extensions (google.protobuf.StringValue) returns (google.protobuf.StringValue); |} |""".trimMargin() val expected = ProtoFileElement( location = location, services = listOf( ServiceElement( location = location.at(1, 1), name = "syntax", rpcs = listOf( RpcElement( location.at(2, 3), name = "syntax", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(4, 1), name = "import", rpcs = listOf( RpcElement( location.at(5, 3), name = "import", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(7, 1), name = "package", rpcs = listOf( RpcElement( location.at(8, 3), name = "package", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(10, 1), name = "option", rpcs = listOf( RpcElement( location.at(11, 3), name = "option", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(13, 1), name = "reserved", rpcs = listOf( RpcElement( location.at(14, 3), name = "reserved", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(16, 1), name = "message", rpcs = listOf( RpcElement( location.at(17, 3), name = "message", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(19, 1), name = "enum", rpcs = listOf( RpcElement( location.at(20, 3), name = "enum", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(22, 1), name = "service", rpcs = listOf( RpcElement( location.at(23, 3), name = "service", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(25, 1), name = "extend", rpcs = listOf( RpcElement( location.at(26, 3), name = "extend", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(28, 1), name = "rpc", rpcs = listOf( RpcElement( location.at(29, 3), name = "rpc", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(31, 1), name = "oneof", rpcs = listOf( RpcElement( location.at(32, 3), name = "oneof", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ServiceElement( location = location.at(34, 1), name = "extensions", rpcs = listOf( RpcElement( location.at(35, 3), name = "extensions", requestType = "google.protobuf.StringValue", responseType = "google.protobuf.StringValue" ) ) ), ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun forbidMultipleSyntaxDefinitions() { val proto = """ | syntax = "proto2"; | syntax = "proto2"; """.trimMargin() try { ProtoParser.parse(location, proto) fail() } catch (expected: IllegalStateException) { assertThat(expected) .hasMessageContaining("Syntax error in file.proto:2:3: too many syntax definitions") } } @Test fun oneOfOptions() { val proto = """ |message SearchRequest { | required string query = 1; | oneof page_info { | option (my_option) = true; | int32 page_number = 2; | int32 result_per_page = 3; | } |} """.trimMargin() val expected = ProtoFileElement( location = location, types = listOf( MessageElement( location = location.at(1, 1), name = "SearchRequest", fields = listOf( FieldElement( location = location.at(2, 3), label = REQUIRED, type = "string", name = "query", tag = 1 ) ), oneOfs = listOf( OneOfElement( name = "page_info", fields = listOf( FieldElement( location = location.at(5, 5), type = "int32", name = "page_number", tag = 2 ), FieldElement( location = location.at(6, 5), type = "int32", name = "result_per_page", tag = 3 ) ), options = listOf( OptionElement.create( "my_option", Kind.BOOLEAN, value = "true", isParenthesized = true ) ) ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } @Test fun semiColonAsOptionsDelimiters() { val proto = """ |service MyService { | option (custom_rule) = { | my_string: "abc"; my_int: 3; | my_list: ["a", "b", "c"]; | }; |} """.trimMargin() val expected = ProtoFileElement( location = location, services = listOf( ServiceElement( location = location.at(1, 1), name = "MyService", options = listOf( OptionElement( "custom_rule", Kind.MAP, mapOf( "my_string" to "abc", "my_int" to OptionElement.OptionPrimitive(Kind.NUMBER, "3"), "my_list" to listOf("a", "b", "c") ), isParenthesized = true ) ) ) ) ) assertThat(ProtoParser.parse(location, proto)).isEqualTo(expected) } }
apache-2.0
db7b50ced9b25d167f83d730ecc449c6
27.844856
146
0.491634
4.386742
false
false
false
false
chengpo/number-speller
translator/src/test/java/com/monkeyapp/numbers/translators/NumberComposerTest.kt
1
8861
/* MIT License Copyright (c) 2017 - 2021 Po Cheng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.monkeyapp.numbers.translators import com.monkeyapp.numbers.testhelpers.shouldEqual import org.junit.Test class NumberComposerTest { @Test fun `NumberComposer should append digit correctly`() { data class TestSample(var number: String = "", var numberText: String = "", var wholeNumber: Long = 0, var fraction: Float = 0.0F) fun testSample(action: TestSample.() -> Unit) = TestSample().apply(action) fun verifySpeller(vararg samples: TestSample) { samples.forEach { sample -> var numberText = "" sample.number.forEach { digit -> numberText = appendDigit(numberText, digit) } val number = Number(numberText) val formattedNumberText = formatNumber(numberText, delimiter = ',', delimiterWidth = 3) formattedNumberText shouldEqual sample.numberText number.wholeNumber.value() shouldEqual sample.wholeNumber number.fraction.value() shouldEqual sample.fraction } } verifySpeller( testSample { number = "1000" numberText = "1,000" wholeNumber = 1000 fraction = 0F }, testSample { number = "1000.00" numberText = "1,000.00" wholeNumber = 1000 fraction = 0F }, testSample { number = "1000.1" numberText = "1,000.1" wholeNumber = 1000 fraction = 0.1F }, testSample { number = "1000.10" numberText = "1,000.10" wholeNumber = 1000 fraction = 0.1F }, testSample { number = "1000.101" numberText = "1,000.101" wholeNumber = 1000 fraction = 0.101F }, testSample { number = "1000.106" numberText = "1,000.106" wholeNumber = 1000 fraction = 0.106F }, testSample { number = "1000.1001" numberText = "1,000.100" wholeNumber = 1000 fraction = 0.10F }, testSample { number = "1000.1016" numberText = "1,000.101" wholeNumber = 1000 fraction = 0.101F }, testSample { number = "1000000.1016" numberText = "1,000,000.101" wholeNumber = 1000000 fraction = 0.101F } ) } @Test fun `EnglishNumberComposer should append and backspace correctly`() { data class Expected(var numberText: String = "", var wholeNumber: Long = 0, var fraction: Float = 0.0F) fun expected(action: Expected.() -> Unit) =Expected().apply(action) class TestSample(var number: String = "", var expected: List<Expected> = emptyList()) fun testSample(action: TestSample.() -> Unit) = TestSample().apply(action) fun verifySpeller(vararg samples: TestSample) { samples.forEach { sample -> var numberText = "" var expectedCount = 0 // append digits sample.number.forEach { digit -> numberText = appendDigit(numberText, digit) val number = Number(numberText) val formattedNumberText = formatNumber(numberText, delimiter = ',', delimiterWidth = 3) val expected = sample.expected[expectedCount++] formattedNumberText shouldEqual expected.numberText number.wholeNumber.value() shouldEqual expected.wholeNumber number.fraction.value() shouldEqual expected.fraction } // backspace digits var count = sample.number.length while (count-- > 0) { numberText = deleteDigit(numberText) val formattedNumberText = formatNumber(numberText, delimiter = ',', delimiterWidth = 3) val number = Number(numberText) val expected = sample.expected[expectedCount++] formattedNumberText shouldEqual expected.numberText number.wholeNumber.value() shouldEqual expected.wholeNumber number.fraction.value() shouldEqual expected.fraction } } } verifySpeller( testSample { number = "12.03" expected = listOf( expected { numberText = "1" wholeNumber = 1 fraction = 0.0F }, expected { numberText = "12" wholeNumber = 12 fraction = 0.0F }, expected { numberText = "12." wholeNumber = 12 fraction = 0.0F }, expected { numberText = "12.0" wholeNumber = 12 fraction = 0.0F }, expected { numberText = "12.03" wholeNumber = 12 fraction = 0.03F }, expected { numberText = "12.0" wholeNumber = 12 fraction = 0.0F }, expected { numberText = "12." wholeNumber = 12 fraction = 0.0F }, expected { numberText = "12" wholeNumber = 12 fraction = 0.0F }, expected { numberText = "1" wholeNumber = 1 fraction = 0.0F }, expected { numberText = "" wholeNumber = 0 fraction = 0.0F } ) } ) } @Test fun `EnglishNumberComposer should ignore duplicated dot`() { var numberText = "" "1000..".forEach { digit -> numberText = appendDigit(numberText, digit) } val number = Number(numberText) val formattedNumberText = formatNumber(numberText, delimiter = ',', delimiterWidth = 3) formattedNumberText shouldEqual "1,000." number.wholeNumber.value() shouldEqual 1000 number.fraction.value() shouldEqual 0.0F } }
mit
4c465dda757aca599a6960dfaf004e2e
37.359307
138
0.457285
5.98312
false
true
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/signIn/SignInActivity.kt
1
9856
/* * VoIP.ms SMS * Copyright (C) 2019 Michael Kourlas * * 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 net.kourlas.voipms_sms.signIn import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.view.MenuItem import android.view.View import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText import kotlinx.coroutines.runBlocking import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.preferences.* import net.kourlas.voipms_sms.preferences.activities.AccountPreferencesActivity import net.kourlas.voipms_sms.sms.workers.RetrieveDidsWorker import net.kourlas.voipms_sms.sms.workers.VerifyCredentialsWorker import net.kourlas.voipms_sms.utils.safeUnregisterReceiver import net.kourlas.voipms_sms.utils.showSnackbar /** * Activity used to sign-in to VoIP.ms SMS. */ class SignInActivity : AppCompatActivity() { // Broadcast receivers private val verifyCredentialsCompleteReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val valid = intent?.getBooleanExtra( getString( R.string.verify_credentials_complete_valid ), false ) val error = intent?.getStringExtra( getString( R.string.verify_credentials_complete_error ) ) when { error != null -> { // Show error if one occurred toggleControls(enabled = true) showSnackbar( this@SignInActivity, R.id.coordinator_layout, error ) } valid == false -> { // If valid is false, then some error occurred toggleControls(enabled = true) showSnackbar( this@SignInActivity, R.id.coordinator_layout, getString( R.string.verify_credentials_error_unknown ) ) } valid == true -> { // If we managed to verify the credentials, then we // save them and try to enable all of the DIDs in the // account val username = findViewById<TextInputEditText>( R.id.username ) val password = findViewById<TextInputEditText>( R.id.password ) setEmail( applicationContext, username.text?.toString() ?: "" ) setPassword( applicationContext, password.text?.toString() ?: "" ) setFirstSyncAfterSignIn(this@SignInActivity, true) RetrieveDidsWorker.retrieveDids( this@SignInActivity, autoAdd = true ) } } } } private val didRetrievalCompleteReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // Regardless of whether this succeeded, we've successfully // signed in, so we exit this activity toggleControls(enabled = true) setFirstRun(applicationContext, false) finish() } } private var hasDids: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.sign_in) onNewIntent(intent) } override fun onResume() { super.onResume() // If an account is already configured, then go to the account screen // instead if (accountConfigured(this)) { startActivity(Intent(this, AccountPreferencesActivity::class.java)) setFirstRun(applicationContext, false) finish() return } // Register dynamic receivers for this fragment registerReceiver( verifyCredentialsCompleteReceiver, IntentFilter( getString( R.string.verify_credentials_complete_action ) ) ) registerReceiver( didRetrievalCompleteReceiver, IntentFilter( getString( R.string.retrieve_dids_complete_action ) ) ) } override fun onPause() { super.onPause() // Unregister dynamic receivers for this fragment safeUnregisterReceiver( this, verifyCredentialsCompleteReceiver ) safeUnregisterReceiver( this, didRetrievalCompleteReceiver ) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) hasDids = runBlocking { Database.getInstance(applicationContext).getDids().isNotEmpty() } setupToolbar() setupTextView() setupButton() } /** * Sets up the activity toolbar. */ private fun setupToolbar() { // Set up toolbar setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar?.let { if (!blockFinish()) { it.setHomeButtonEnabled(true) it.setDisplayHomeAsUpEnabled(true) } } } /** * Sets up the info text view. */ private fun setupTextView() { val textView = findViewById<TextView>(R.id.text_view) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { textView.text = Html.fromHtml( getString(R.string.sign_in_info), 0 ) } else { @Suppress("DEPRECATION") textView.text = Html.fromHtml( getString(R.string.sign_in_info) ) } textView.movementMethod = LinkMovementMethod.getInstance() } /** * Sets up the sign-in button. */ private fun setupButton() { val button = findViewById<MaterialButton>(R.id.sign_in_button) button.setOnClickListener { toggleControls(enabled = false) val username = findViewById<TextInputEditText>(R.id.username) val password = findViewById<TextInputEditText>(R.id.password) VerifyCredentialsWorker.verifyCredentials( applicationContext, username.text?.toString() ?: "", password.text?.toString() ?: "" ) } val skipButton = findViewById<MaterialButton>(R.id.skip_button) skipButton.setOnClickListener { setFirstRun(applicationContext, false) finish() } if (!blockFinish()) { skipButton.visibility = View.GONE } } /** * Enables and disables the controls during sign-in. */ fun toggleControls(enabled: Boolean) { val button = findViewById<MaterialButton>(R.id.sign_in_button) button.isEnabled = enabled val progressBar = findViewById<ProgressBar>(R.id.progress_bar) progressBar.visibility = if (enabled) View.INVISIBLE else View.VISIBLE val username = findViewById<TextInputEditText>(R.id.username) username.isEnabled = enabled val password = findViewById<TextInputEditText>(R.id.password) password.isEnabled = enabled } override fun onBackPressed() { // Block the back button if appropriate if (blockFinish()) { return } super.onBackPressed() } /** * Returns true if the user should not be allowed to leave this activity. */ private fun blockFinish(): Boolean { return !didsConfigured(applicationContext) && !hasDids && !accountConfigured(applicationContext) && firstRun(applicationContext) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { // Block the back button if appropriate if (blockFinish()) { return true } return super.onOptionsItemSelected(item) } else -> super.onOptionsItemSelected(item) } } }
apache-2.0
44db2c8fc783eefe52c4585f0ce89a72
32.52381
79
0.557528
5.571509
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/preset/add/habit/AddPresetChallengeHabitDialogController.kt
1
11314
package io.ipoli.android.challenge.preset.add.habit import android.annotation.SuppressLint import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import io.ipoli.android.R import io.ipoli.android.challenge.preset.PresetChallenge import io.ipoli.android.challenge.preset.add.habit.AddPresetChallengeHabitViewState.StateType.* import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.ReduxDialogController import io.ipoli.android.common.view.colorRes import io.ipoli.android.common.view.navigate import io.ipoli.android.common.view.stringRes import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.PetAvatar import io.ipoli.android.quest.Color import io.ipoli.android.quest.Icon import kotlinx.android.synthetic.main.dialog_add_preset_challenge_habit.view.* import kotlinx.android.synthetic.main.view_dialog_header.view.* sealed class AddPresetChallengeHabitAction : Action { data class ChangeIcon(val icon: Icon) : AddPresetChallengeHabitAction() data class ChangeColor(val color: Color) : AddPresetChallengeHabitAction() data class ChangeTimesADay(val timesADay: Int) : AddPresetChallengeHabitAction() data class ChangeType(val isGood: Boolean) : AddPresetChallengeHabitAction() data class Validate(val name: String) : AddPresetChallengeHabitAction() data class Load(val habit: PresetChallenge.Habit?) : AddPresetChallengeHabitAction() } object AddPresetChallengeHabitReducer : BaseViewStateReducer<AddPresetChallengeHabitViewState>() { override fun reduce( state: AppState, subState: AddPresetChallengeHabitViewState, action: Action ) = when (action) { is AddPresetChallengeHabitAction.Load -> { val h = action.habit val newState = subState.copy( name = h?.name ?: subState.name, color = h?.color ?: subState.color, icon = h?.icon ?: subState.icon, isGood = h?.isGood ?: subState.isGood, timesADay = h?.timesADay ?: subState.timesADay ) if (state.dataState.player == null) newState.copy( type = LOADING ) else newState.copy( type = DATA_LOADED, petAvatar = state.dataState.player.pet.avatar ) } is DataLoadedAction.PlayerChanged -> { if (subState.type == LOADING) subState.copy( type = DATA_LOADED, petAvatar = action.player.pet.avatar ) else subState } is AddPresetChallengeHabitAction.ChangeColor -> subState.copy( type = COLOR_CHANGED, color = action.color ) is AddPresetChallengeHabitAction.ChangeIcon -> subState.copy( type = ICON_CHANGED, icon = action.icon ) is AddPresetChallengeHabitAction.ChangeTimesADay -> subState.copy( type = TIMES_A_DAY_CHANGED, timesADay = action.timesADay ) is AddPresetChallengeHabitAction.ChangeType -> subState.copy( type = TYPE_CHANGED, isGood = action.isGood ) is AddPresetChallengeHabitAction.Validate -> { if (action.name.isBlank()) { subState.copy( type = ERROR_EMPTY_NAME ) } else { subState.copy( type = HABIT_PICKED, habit = PresetChallenge.Habit( name = action.name, color = subState.color, icon = subState.icon, timesADay = if (subState.isGood) subState.timesADay else 1, isGood = subState.isGood, isSelected = true ) ) } } else -> subState } override fun defaultState() = AddPresetChallengeHabitViewState( type = LOADING, petAvatar = PetAvatar.BEAR, name = "", color = Color.GREEN, icon = Icon.FLOWER, timesADay = 1, isGood = true, habit = null ) override val stateKey = key<AddPresetChallengeHabitViewState>() } data class AddPresetChallengeHabitViewState( val type: StateType, val petAvatar: PetAvatar, val name: String, val color: Color, val icon: Icon, val timesADay: Int, val isGood: Boolean, val habit: PresetChallenge.Habit? ) : BaseViewState() { enum class StateType { LOADING, DATA_LOADED, ICON_CHANGED, COLOR_CHANGED, TIMES_A_DAY_CHANGED, TYPE_CHANGED, ERROR_EMPTY_NAME, HABIT_PICKED } } class AddPresetChallengeHabitDialogController(args: Bundle? = null) : ReduxDialogController<AddPresetChallengeHabitAction, AddPresetChallengeHabitViewState, AddPresetChallengeHabitReducer>( args ) { override val reducer = AddPresetChallengeHabitReducer private var habit: PresetChallenge.Habit? = null private var listener: (PresetChallenge.Habit) -> Unit = { _ -> } constructor( habit: PresetChallenge.Habit? = null, listener: (PresetChallenge.Habit) -> Unit = { _ -> } ) : this() { this.habit = habit this.listener = listener } override fun onHeaderViewCreated(headerView: View) { headerView.dialogHeaderTitle.setText(R.string.habit_for_preset_challenge_title) } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View = inflater.inflate(R.layout.dialog_add_preset_challenge_habit, null) override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog { return dialogBuilder .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.dialog_ok, null) .create() } override fun onCreateLoadAction() = AddPresetChallengeHabitAction.Load(habit) override fun onDialogCreated(dialog: AlertDialog, contentView: View) { dialog.setOnShowListener { setPositiveButtonListener { dispatch( AddPresetChallengeHabitAction.Validate( contentView.habitName.text.toString() ) ) } } } override fun render(state: AddPresetChallengeHabitViewState, view: View) { when (state.type) { DATA_LOADED -> { changeIcon(AndroidPetAvatar.valueOf(state.petAvatar.name).headImage) view.habitName.setText(state.name) renderColor(view, state) renderIcon(view, state) renderTimesADay(view) renderType(view, state) } COLOR_CHANGED -> renderColor(view, state) ICON_CHANGED -> renderIcon(view, state) TYPE_CHANGED -> renderType(view, state) ERROR_EMPTY_NAME -> view.habitName.error = stringRes(R.string.think_of_a_name) HABIT_PICKED -> { listener(state.habit!!) dismiss() } else -> { } } } private fun renderType( view: View, state: AddPresetChallengeHabitViewState ) { view.habitType.setOnCheckedChangeListener(null) view.habitType.isChecked = state.isGood view.habitTimesADay.isEnabled = state.isGood view.habitType.setOnCheckedChangeListener { _, isChecked -> dispatch( AddPresetChallengeHabitAction.ChangeType( isChecked ) ) } } private fun renderTimesADay( view: View ) { val timesADay = (1..8).toList() view.habitTimesADay.adapter = ArrayAdapter<Int>( view.context, R.layout.item_dropdown_number_spinner, timesADay ) view.habitTimesADay.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, v: View?, position: Int, id: Long ) { dispatch( AddPresetChallengeHabitAction.ChangeTimesADay( timesADay[position] ) ) } } } private fun renderIcon( view: View, state: AddPresetChallengeHabitViewState ) { val icon = listItemIcon(state.icon.androidIcon.icon) .colorRes(state.color.androidColor.color500).paddingDp(0) view.habitIcon.setCompoundDrawablesRelativeWithIntrinsicBounds( icon, null, null, null ) view.habitIcon.onDebounceClick { navigate().toIconPicker({ i -> if (i != null) dispatch( AddPresetChallengeHabitAction.ChangeIcon( i ) ) }) } } private fun renderColor( view: View, state: AddPresetChallengeHabitViewState ) { val allDrawables = view.habitColor.compoundDrawablesRelative val drawableStart = allDrawables[0] as GradientDrawable val size = ViewUtils.dpToPx(24f, view.context).toInt() drawableStart.setSize(size, size) drawableStart.setColor(colorRes(state.color.androidColor.color500)) view.habitColor.setCompoundDrawablesRelativeWithIntrinsicBounds( drawableStart, null, null, null ) view.habitColor.onDebounceClick { navigate().toColorPicker({ c -> dispatch( AddPresetChallengeHabitAction.ChangeColor( c ) ) }) } } }
gpl-3.0
eb31684bbc5033e5f43b9f69597937e5
31.421203
123
0.562577
5.316729
false
false
false
false
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/projectWizard/generators/AssetsNewProjectWizardStep.kt
1
4533
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.projectWizard.generators import com.intellij.codeInsight.actions.ReformatCodeProcessor import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.projectView.ProjectView import com.intellij.ide.starters.local.GeneratorAsset import com.intellij.ide.starters.local.GeneratorTemplateFile import com.intellij.ide.starters.local.generator.AssetsProcessor import com.intellij.ide.wizard.AbstractNewProjectWizardStep import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.ide.wizard.setupProjectSafe import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.ui.UIBundle import org.jetbrains.annotations.ApiStatus import java.util.StringJoiner @ApiStatus.Experimental abstract class AssetsNewProjectWizardStep(parent: NewProjectWizardStep) : AbstractNewProjectWizardStep(parent) { lateinit var outputDirectory: String private val assets = ArrayList<GeneratorAsset>() private val templateProperties = HashMap<String, Any>() private val filesToOpen = HashSet<String>() fun addAssets(vararg assets: GeneratorAsset) = addAssets(assets.toList()) fun addAssets(assets: Iterable<GeneratorAsset>) { this.assets.addAll(assets) } fun addTemplateProperties(vararg properties: Pair<String, Any>) = addTemplateProperties(properties.toMap()) private fun addTemplateProperties(properties: Map<String, Any>) { templateProperties.putAll(properties) } fun addFilesToOpen(vararg relativeCanonicalPaths: String) = addFilesToOpen(relativeCanonicalPaths.toList()) private fun addFilesToOpen(relativeCanonicalPaths: Iterable<String>) { filesToOpen.addAll(relativeCanonicalPaths.map { "$outputDirectory/$it" }) } abstract fun setupAssets(project: Project) override fun setupProject(project: Project) { setupProjectSafe(project, UIBundle.message("error.project.wizard.new.project.sample.code", context.isCreatingNewProjectInt)) { setupAssets(project) val generatedFiles = invokeAndWaitIfNeeded { runWriteAction { AssetsProcessor().generateSources(outputDirectory, assets, templateProperties) } } runWhenCreated(project) { //IDEA-244863 reformatCode(project, generatedFiles) openFilesInEditor(project, generatedFiles.filter { it.path in filesToOpen }) } } } private fun runWhenCreated(project: Project, action: () -> Unit) { if (ApplicationManager.getApplication().isUnitTestMode) { action() } else { StartupManager.getInstance(project).runAfterOpened { ApplicationManager.getApplication().invokeLater(action, project.disposed) } } } private fun reformatCode(project: Project, files: List<VirtualFile>) { val psiManager = PsiManager.getInstance(project) val generatedPsiFiles = files.mapNotNull { psiManager.findFile(it) } ReformatCodeProcessor(project, generatedPsiFiles.toTypedArray(), null, false).run() } private fun openFilesInEditor(project: Project, files: List<VirtualFile>) { val fileEditorManager = FileEditorManager.getInstance(project) val projectView = ProjectView.getInstance(project) for (file in files) { fileEditorManager.openFile(file, true) projectView.select(null, file, false) } } companion object { fun AssetsNewProjectWizardStep.withJavaSampleCodeAsset(sourceRootPath: String, aPackage: String) { val templateManager = FileTemplateManager.getDefaultInstance() val template = templateManager.getInternalTemplate("SampleCode") val packageDirectory = aPackage.replace('.', '/') val pathJoiner = StringJoiner("/") if (sourceRootPath.isNotEmpty()) { pathJoiner.add(sourceRootPath) } if (packageDirectory.isNotEmpty()) { pathJoiner.add(packageDirectory) } pathJoiner.add("Main.java") val path = pathJoiner.toString() addAssets(GeneratorTemplateFile(path, template)) addFilesToOpen(path) addTemplateProperties("PACKAGE_NAME" to aPackage) } } }
apache-2.0
9537af196e8e0df6fc258f713fb6c099
37.423729
130
0.763733
4.731733
false
false
false
false
GunoH/intellij-community
platform/lang-core/src/com/intellij/openapi/projectRoots/JdkCommandLineSetup.kt
2
38752
// 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.projectRoots import com.intellij.execution.CantRunException import com.intellij.execution.CommandLineWrapperUtil import com.intellij.execution.ExecutionBundle import com.intellij.execution.Platform import com.intellij.execution.configurations.CompositeParameterTargetedValue import com.intellij.execution.configurations.GeneralCommandLine.ParentEnvironmentType import com.intellij.execution.configurations.ParameterTargetValuePart import com.intellij.execution.configurations.ParametersList import com.intellij.execution.configurations.SimpleJavaParameters import com.intellij.execution.target.LanguageRuntimeType.VolumeDescriptor import com.intellij.execution.target.LanguageRuntimeType.VolumeType import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.TargetedCommandLineBuilder import com.intellij.execution.target.java.JavaLanguageRuntimeConfiguration import com.intellij.execution.target.java.JavaLanguageRuntimeType import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.execution.target.value.DeferredTargetValue import com.intellij.execution.target.value.TargetValue import com.intellij.lang.LangCoreBundle import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.encoding.EncodingManager import com.intellij.util.PathUtil import com.intellij.util.PathsList import com.intellij.util.SystemProperties import com.intellij.util.containers.ContainerUtil import com.intellij.util.execution.ParametersListUtil import com.intellij.util.io.URLUtil import com.intellij.util.io.isDirectory import com.intellij.util.lang.JavaVersion import com.intellij.util.lang.UrlClassLoader import org.jetbrains.annotations.NonNls import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.collectResults import java.io.File import java.io.IOException import java.net.MalformedURLException import java.net.URI import java.net.URL import java.nio.charset.Charset import java.nio.charset.IllegalCharsetNameException import java.nio.charset.StandardCharsets import java.nio.charset.UnsupportedCharsetException import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeoutException import java.util.jar.Manifest import kotlin.math.abs class JdkCommandLineSetup(private val request: TargetEnvironmentRequest) { init { request.onEnvironmentPrepared { environment, progressIndicator -> provideEnvironment(environment, progressIndicator) } } val commandLine = TargetedCommandLineBuilder(request) val platform = request.targetPlatform.platform private val languageRuntime: JavaLanguageRuntimeConfiguration? = request.configuration?.runtimes?.findByType( JavaLanguageRuntimeConfiguration::class.java) private val environmentPromise = AsyncPromise<Pair<TargetEnvironment, TargetProgressIndicator>>() private val dependingOnEnvironmentPromise = mutableListOf<Promise<Unit>>() private val uploads = mutableListOf<Upload>() private val projectHomeOnTarget = VolumeDescriptor(VolumeType(JdkCommandLineSetup::class.java.simpleName + ":projectHomeOnTarget"), "", "", "", request.projectPathOnTarget) /** * @param uploadPathIsFile * * true: [uploadPathString] points to a file, the volume should be created for the file's directory. * * false: [uploadPathString] points to a directory, the volume should be created for the path. * * null: Determine whether [uploadPathString] is a file or a directory. If [uploadPathString] does not exist, it is treated as file. */ private fun requestUploadIntoTarget(volumeDescriptor: VolumeDescriptor, uploadPathString: String, uploadPathIsFile: Boolean? = null, afterUploadResolved: (String) -> Unit = {}): TargetValue<String> { val uploadPath = Paths.get(FileUtil.toSystemDependentName(uploadPathString)) val isDir = uploadPathIsFile?.not() ?: uploadPath.isDirectory() val localRootPath = if (isDir) uploadPath else (uploadPath.parent ?: Paths.get(".")) // Normally, paths should be absolute, but there are tests that check relative paths. val uploadRoot = createUploadRoot(volumeDescriptor, localRootPath) request.uploadVolumes += uploadRoot val result = DeferredTargetValue(uploadPathString) dependingOnEnvironmentPromise += environmentPromise.then { (environment, targetProgressIndicator) -> if (targetProgressIndicator.isCanceled || targetProgressIndicator.isStopped) { result.stopProceeding() return@then } val volume = environment.uploadVolumes.getValue(uploadRoot) try { val relativePath = if (isDir) "." else uploadPath.fileName.toString() val resolvedTargetPath = volume.resolveTargetPath(relativePath) uploads.add(Upload(volume, relativePath)) result.resolve(resolvedTargetPath) afterUploadResolved(resolvedTargetPath) } catch (t: Throwable) { LOG.warn(t) targetProgressIndicator.stopWithErrorMessage(LangCoreBundle.message("progress.message.failed.to.resolve.0.1", volume.localRoot, t.localizedMessage)) result.resolveFailure(t) } } return result } @Suppress("SameParameterValue") private fun requestDownloadFromTarget(downloadPathString: String, downloadPathIsFile: Boolean? = null, afterDownloadResolved: (String) -> Unit = {}): TargetValue<String> { val downloadPath = Paths.get(FileUtil.toSystemDependentName(downloadPathString)) val isDir = downloadPathIsFile?.not() ?: downloadPath.isDirectory() val localRootPath = if (isDir) downloadPath else (downloadPath.parent ?: Paths.get(".")) // Normally, paths should be absolute, but there are tests that check relative paths. val downloadRoot = TargetEnvironment.DownloadRoot(localRootPath = localRootPath, targetRootPath = TargetEnvironment.TargetPath.Temporary()) request.downloadVolumes += downloadRoot val result = DeferredTargetValue(downloadPathString) dependingOnEnvironmentPromise += environmentPromise.then { (environment, targetProgressIndicator) -> if (targetProgressIndicator.isCanceled || targetProgressIndicator.isStopped) { result.stopProceeding() return@then } val volume = environment.downloadVolumes.getValue(downloadRoot) try { val relativePath = if (isDir) "." else downloadPath.fileName.toString() val resolvedTargetPath = volume.resolveTargetPath(relativePath) result.resolve(resolvedTargetPath) afterDownloadResolved(resolvedTargetPath) } catch (t: Throwable) { LOG.warn(t) targetProgressIndicator.stopWithErrorMessage(LangCoreBundle.message("progress.message.failed.to.resolve.0.1", volume.localRoot, t.localizedMessage)) result.resolveFailure(t) } } return result } private class Upload(val volume: TargetEnvironment.UploadableVolume, val relativePath: String) private fun createUploadRoot(volumeDescriptor: VolumeDescriptor, localRootPath: Path): TargetEnvironment.UploadRoot { return languageRuntime?.createUploadRoot(volumeDescriptor, localRootPath) ?: TargetEnvironment.UploadRoot(localRootPath = localRootPath, targetRootPath = TargetEnvironment.TargetPath.Temporary()) } private val commandLineContent by lazy { mutableMapOf<String, String>().also { commandLine.putUserData(JdkUtil.COMMAND_LINE_CONTENT, it) } } private fun provideEnvironment(environment: TargetEnvironment, targetProgressIndicator: TargetProgressIndicator) { environmentPromise.setResult(environment to targetProgressIndicator) if (environment is TargetEnvironment.BatchUploader) { environment.runBatchUpload(uploads = ContainerUtil.map(uploads) { Pair(it.volume, it.relativePath) }, targetProgressIndicator = targetProgressIndicator) } else { for (upload in uploads) { upload.volume.upload(upload.relativePath, targetProgressIndicator) } } for (promise in dependingOnEnvironmentPromise) { promise.blockingGet(0) // Just rethrows errors. } } @Throws(CantRunException::class) fun setupCommandLine(javaParameters: SimpleJavaParameters) { setupWorkingDirectory(javaParameters) setupEnvironment(javaParameters) setupClasspathAndParameters(javaParameters) commandLine.setRedirectErrorStreamFromRegistry() } @Throws(CantRunException::class) fun setupJavaExePath(javaParameters: SimpleJavaParameters) { if (request is LocalTargetEnvironmentRequest || request.configuration == null) { val jdk = javaParameters.jdk ?: throw CantRunException(ExecutionBundle.message("run.configuration.error.no.jdk.specified")) val type = jdk.sdkType if (type !is JavaSdkType) throw CantRunException(ExecutionBundle.message("run.configuration.error.no.jdk.specified")) val exePath = (type as JavaSdkType).getVMExecutablePath(jdk) ?: throw CantRunException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable")) commandLine.setExePath(exePath) } else { if (languageRuntime == null) { throw CantRunException(LangCoreBundle.message("error.message.cannot.find.java.configuration.in.0.target", request.configuration?.displayName)) } val java = if (platform == Platform.WINDOWS) "java.exe" else "java" commandLine.setExePath(joinPath(arrayOf(languageRuntime.homePath, "bin", java))) } } private fun setupWorkingDirectory(javaParameters: SimpleJavaParameters) { val workingDirectory = javaParameters.workingDirectory if (workingDirectory != null) { val targetWorkingDirectory = requestUploadIntoTarget(projectHomeOnTarget, workingDirectory, uploadPathIsFile = false) commandLine.setWorkingDirectory(targetWorkingDirectory) } } @Throws(CantRunException::class) private fun setupEnvironment(javaParameters: SimpleJavaParameters) { javaParameters.env.forEach { (key: String, value: String?) -> commandLine.addEnvironmentVariable(key, value) } if (request is LocalTargetEnvironmentRequest) { val type = if (javaParameters.isPassParentEnvs) ParentEnvironmentType.CONSOLE else ParentEnvironmentType.NONE request.setParentEnvironmentType(type) } } @Throws(CantRunException::class) private fun setupClasspathAndParameters(javaParameters: SimpleJavaParameters) { val vmParameters = javaParameters.vmParametersList var dynamicClasspath = javaParameters.isDynamicClasspath val dynamicVMOptions = dynamicClasspath && javaParameters.isDynamicVMOptions && JdkUtil.useDynamicVMOptions() var dynamicParameters = dynamicClasspath && javaParameters.isDynamicParameters && JdkUtil.useDynamicParameters() var dynamicMainClass = false // copies agent .jar files to the beginning of the classpath to load agent classes faster if (isUrlClassloader(vmParameters)) { if (request !is LocalTargetEnvironmentRequest) { throw CantRunException(LangCoreBundle.message("error.message.cannot.run.application.with.urlclasspath.on.the.remote.target")) } for (parameter in vmParameters.parameters) { if (parameter.startsWith(JAVAAGENT)) { val jar = parameter.substring(JAVAAGENT.length + 1).substringBefore('=') javaParameters.classPath.addFirst(jar) } } } val commandLineWrapperClass = commandLineWrapperClass() if (dynamicClasspath) { val cs = StandardCharsets.UTF_8 // todo detect JNU charset from VM options? if (javaParameters.isArgFile) { setArgFileParams(javaParameters, vmParameters, dynamicVMOptions, dynamicParameters, cs) dynamicMainClass = dynamicParameters } else if (!vmParameters.isExplicitClassPath() && javaParameters.jarPath == null && commandLineWrapperClass != null) { if (javaParameters.isUseClasspathJar) { setClasspathJarParams(javaParameters, vmParameters, commandLineWrapperClass, dynamicVMOptions, dynamicParameters) } else if (javaParameters.isClasspathFile) { setCommandLineWrapperParams(javaParameters, vmParameters, commandLineWrapperClass, dynamicVMOptions, dynamicParameters, cs) } } else { dynamicParameters = false dynamicClasspath = dynamicParameters } } if (!dynamicClasspath) { appendParamsEncodingClasspath(javaParameters, vmParameters) } if (!dynamicMainClass) { for (parameter in getMainClassParams(javaParameters)) { commandLine.addParameter(parameter) } } if (!dynamicParameters) { for (value in mapTargetValues(javaParameters.programParametersList.targetedList)) { commandLine.addParameter(value) } } } private fun mapTargetValues(parameterValues: Collection<CompositeParameterTargetedValue>): List<TargetValue<String>> { return parameterValues.map { parameter -> val values = mutableListOf<TargetValue<String>>() for (part in parameter.parts) { when (part) { is ParameterTargetValuePart.Const -> TargetValue.fixed(part.localValue) is ParameterTargetValuePart.Path -> requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, part.pathToUpload, null) is ParameterTargetValuePart.PathSeparator -> TargetValue.fixed(platform.pathSeparator.toString()) is ParameterTargetValuePart.PromiseValue -> TargetValue.create(part.localValue, part.targetValue) else -> throw IllegalStateException("Unexpected parameter list part " + part.javaClass) }.let { values.add(it) } } TargetValue.composite(values) { it.joinToString(separator = "") } } } @Throws(CantRunException::class) private fun setArgFileParams(javaParameters: SimpleJavaParameters, vmParameters: ParametersList, dynamicVMOptions: Boolean, dynamicParameters: Boolean, cs: Charset) { try { val argFile = ArgFile(dynamicVMOptions, cs, platform) commandLine.addFileToDeleteOnTermination(argFile.file) val classPath = javaParameters.classPath if (!classPath.isEmpty && !vmParameters.isExplicitClassPath()) { argFile.addPromisedParameter("-classpath", composeClassPathValues(javaParameters, classPath)) } val modulePath = javaParameters.modulePath if (!modulePath.isEmpty && !vmParameters.isExplicitModulePath()) { argFile.addPromisedParameter("-p", composeClassPathValues(javaParameters, modulePath)) } if (dynamicParameters) { for (nextMainClassParam in getMainClassParams(javaParameters)) { argFile.addPromisedParameter(nextMainClassParam) } } if (!dynamicVMOptions) { // dynamic options will be handled later by ArgFile appendVmParameters(javaParameters, vmParameters) } appendEncoding(javaParameters, vmParameters) if (dynamicParameters) { val targetValues = mapTargetValues(javaParameters.programParametersList.targetedList) for (targetValue in targetValues) { argFile.addPromisedParameter(targetValue) } } val argFileParameter = requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, argFile.file.absolutePath, uploadPathIsFile = true) commandLine.addParameter(TargetValue.map(argFileParameter) { s -> "@$s" }) argFile.scheduleWriteFileWhenReady(vmParameters) { rememberFileContentAfterUpload(argFile.file, argFileParameter) } } catch (e: IOException) { throwUnableToCreateTempFile(e) } } @Throws(CantRunException::class) private fun setClasspathJarParams(javaParameters: SimpleJavaParameters, vmParameters: ParametersList, commandLineWrapper: Class<*>, dynamicVMOptions: Boolean, dynamicParameters: Boolean) { try { val jarFile = ClasspathJar(this, vmParameters.hasParameter(JdkUtil.PROPERTY_DO_NOT_ESCAPE_CLASSPATH_URL)) commandLine.addFileToDeleteOnTermination(jarFile.file) jarFile.addToManifest("Created-By", ApplicationNamesInfo.getInstance().fullProductName, true) if (dynamicVMOptions) { val properties: MutableList<String> = ArrayList() for (param in vmParameters.list) { if (isUserDefinedProperty(param)) { properties.add(param) } else { appendVmParameter(param) } } jarFile.addToManifest("VM-Options", ParametersListUtil.join(properties)) } else { appendVmParameters(javaParameters, vmParameters) } appendEncoding(javaParameters, vmParameters) if (dynamicParameters) { jarFile.addToManifest("Program-Parameters", ParametersListUtil.join(javaParameters.programParametersList.list)) } val targetJarFile = requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, jarFile.file.absolutePath, uploadPathIsFile = true) if (dynamicVMOptions || dynamicParameters) { // -classpath path1:path2 CommandLineWrapper path2 commandLine.addParameter("-classpath") commandLine.addParameter(composePathsList(listOf( requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, PathUtil.getJarPathForClass(commandLineWrapper)), targetJarFile ))) commandLine.addParameter(TargetValue.fixed(commandLineWrapper.name)) commandLine.addParameter(targetJarFile) } else { // -classpath path2 commandLine.addParameter("-classpath") commandLine.addParameter(targetJarFile) } val classPathParameters = getClassPathValues(javaParameters, javaParameters.classPath) jarFile.scheduleWriteFileWhenClassPathReady(classPathParameters, targetJarFile) } catch (e: IOException) { throwUnableToCreateTempFile(e) } appendModulePath(javaParameters, vmParameters) } @Throws(CantRunException::class) private fun setCommandLineWrapperParams(javaParameters: SimpleJavaParameters, vmParameters: ParametersList, commandLineWrapper: Class<*>, dynamicVMOptions: Boolean, dynamicParameters: Boolean, cs: Charset) { try { val pseudoUniquePrefix = Random().nextInt(Int.MAX_VALUE) var vmParamsFile: File? = null if (dynamicVMOptions) { val toWrite: MutableList<String> = ArrayList() for (param in vmParameters.list) { if (isUserDefinedProperty(param)) { toWrite.add(param) } else { appendVmParameter(param) } } if (toWrite.isNotEmpty()) { vmParamsFile = FileUtil.createTempFile("idea_vm_params$pseudoUniquePrefix", null) commandLine.addFileToDeleteOnTermination(vmParamsFile) CommandLineWrapperUtil.writeWrapperFile(vmParamsFile, toWrite, platform.lineSeparator, cs) } } else { appendVmParameters(javaParameters, vmParameters) } appendEncoding(javaParameters, vmParameters) var appParamsFile: File? = null if (dynamicParameters) { appParamsFile = FileUtil.createTempFile("idea_app_params$pseudoUniquePrefix", null) commandLine.addFileToDeleteOnTermination(appParamsFile) CommandLineWrapperUtil.writeWrapperFile(appParamsFile, javaParameters.programParametersList.list, platform.lineSeparator, cs) } val classpathFile = FileUtil.createTempFile("idea_classpath$pseudoUniquePrefix", null) commandLine.addFileToDeleteOnTermination(classpathFile) val classPathParameters = getClassPathValues(javaParameters, javaParameters.classPath) classPathParameters.map { it.targetValue }.collectResults().onSuccess { pathList -> CommandLineWrapperUtil.writeWrapperFile(classpathFile, pathList, platform.lineSeparator, cs) } val classpath: MutableSet<TargetValue<String>> = LinkedHashSet() classpath.add(requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, PathUtil.getJarPathForClass(commandLineWrapper))) // If kotlin agent starts it needs kotlin-stdlib in the classpath. javaParameters.classPath.rootDirs.forEach { rootDir -> rootDir.getUserData(JdkUtil.AGENT_RUNTIME_CLASSPATH)?.let { classpath.add(requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, it)) } } if (isUrlClassloader(vmParameters)) { if (request !is LocalTargetEnvironmentRequest) { throw CantRunException(LangCoreBundle.message("error.message.cannot.run.application.with.urlclasspath.on.the.remote.target")) } // since request is known to be local we will simplify to TargetValue.fixed below classpath.add(TargetValue.fixed(PathUtil.getJarPathForClass(UrlClassLoader::class.java))) classpath.add(TargetValue.fixed(PathUtil.getJarPathForClass(StringUtilRt::class.java))) classpath.add(TargetValue.fixed(PathUtil.getJarPathForClass(Class.forName("gnu.trove.THashMap")))) //explicitly enumerate jdk classes as UrlClassLoader doesn't delegate to parent classloader when loading resources //which leads to exceptions when coverage instrumentation tries to instrument loader class and its dependencies javaParameters.jdk?.rootProvider?.getFiles(OrderRootType.CLASSES)?.forEach { val path = PathUtil.getLocalPath(it) if (StringUtil.isNotEmpty(path)) { classpath.add(TargetValue.fixed(path)) } } } commandLine.addParameter("-classpath") commandLine.addParameter(composePathsList(classpath)) commandLine.addParameter(commandLineWrapper.name) val classPathParameter = requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, classpathFile.absolutePath, uploadPathIsFile = true) commandLine.addParameter(classPathParameter) rememberFileContentAfterUpload(classpathFile, classPathParameter) if (vmParamsFile != null) { commandLine.addParameter("@vm_params") val vmParamsParameter = requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, vmParamsFile.absolutePath, uploadPathIsFile = true) commandLine.addParameter(vmParamsParameter) rememberFileContentAfterUpload(vmParamsFile, vmParamsParameter) } if (appParamsFile != null) { commandLine.addParameter("@app_params") val appParamsParameter = requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, appParamsFile.absolutePath, uploadPathIsFile = true) commandLine.addParameter(appParamsParameter) rememberFileContentAfterUpload(appParamsFile, appParamsParameter) } } catch (e: IOException) { throwUnableToCreateTempFile(e) } } @Throws(CantRunException::class) private fun getMainClassParams(javaParameters: SimpleJavaParameters): List<TargetValue<String>> { val mainClass = javaParameters.mainClass val moduleName = javaParameters.moduleName val jarPath = javaParameters.jarPath return if (mainClass != null && moduleName != null) { listOf(TargetValue.fixed("-m"), TargetValue.fixed("$moduleName/$mainClass")) } else if (mainClass != null) { listOf(TargetValue.fixed(mainClass)) } else if (jarPath != null) { listOf(TargetValue.fixed("-jar"), requestUploadIntoTarget(projectHomeOnTarget, jarPath, uploadPathIsFile = true)) } else { throw CantRunException(ExecutionBundle.message("main.class.is.not.specified.error.message")) } } private fun rememberFileContentAfterUpload(localFile: File, fileUpload: TargetValue<String>) { fileUpload.targetValue.onSuccess { resolvedTargetPath: String -> try { commandLineContent[resolvedTargetPath] = FileUtil.loadFile(localFile) } catch (e: IOException) { LOG.error("Cannot add command line content for $resolvedTargetPath from $localFile", e) } } } private fun appendVmParameters(javaParameters: SimpleJavaParameters, vmParameters: ParametersList) { vmParameters.list.forEach { appendVmParameter(it) } val targetDependentParameters = javaParameters.targetDependentParameters targetDependentParameters.asTargetParameters().forEach { javaParameterFunction -> val value = javaParameterFunction.apply(request) value.resolvePaths( uploadPathsResolver = { path -> path.beforeUploadOrDownloadResolved(path.localPath) requestUploadIntoTarget(JavaLanguageRuntimeType.AGENTS_VOLUME, path.localPath, uploadPathIsFile = true) { path.afterUploadOrDownloadResolved(it) } }, downloadPathsResolver = { path -> path.beforeUploadOrDownloadResolved(path.localPath) requestDownloadFromTarget(path.localPath, true) { path.afterUploadOrDownloadResolved(it) } } ) commandLine.addParameter(value.parameter) } dependingOnEnvironmentPromise += environmentPromise.then { (environment, _) -> targetDependentParameters.setTargetEnvironment(environment) } } private fun appendVmParameter(vmParameter: String) { if (request is LocalTargetEnvironmentRequest || SystemProperties.getBooleanProperty("run.targets.ignore.vm.parameter", false)) { commandLine.addParameter(vmParameter) return } when { vmParameter.startsWith("-agentpath:") -> { appendVmAgentParameter(vmParameter, "-agentpath:") } vmParameter.startsWith("-javaagent:") -> { appendVmAgentParameter(vmParameter, "-javaagent:") } else -> { commandLine.addParameter(vmParameter) } } } private fun appendVmAgentParameter(vmParameter: String, prefix: String) { val value = StringUtil.trimStart(vmParameter, prefix) val equalsSign = value.indexOf('=') val path = if (equalsSign > -1) value.substring(0, equalsSign) else value if (!path.endsWith(".jar")) { // ignore non-cross-platform agents return } val suffix = if (equalsSign > -1) value.substring(equalsSign) else "" commandLine.addParameter( TargetValue.map(requestUploadIntoTarget(JavaLanguageRuntimeType.AGENTS_VOLUME, path, uploadPathIsFile = true)) { v: String -> prefix + v + suffix }) } private fun appendEncoding(javaParameters: SimpleJavaParameters, parametersList: ParametersList) { // for correct handling of process's input and output, values of file.encoding and charset of CommandLine object should be in sync val encoding = parametersList.getPropertyValue("file.encoding") if (encoding == null) { val charset = javaParameters.charset ?: EncodingManager.getInstance().defaultCharset commandLine.addParameter("-Dfile.encoding=" + charset.name()) commandLine.charset = charset } else { try { commandLine.charset = Charset.forName(encoding) } catch (ignore: UnsupportedCharsetException) { } catch (ignore: IllegalCharsetNameException) { } } if (!parametersList.hasProperty("sun.stdout.encoding") && !parametersList.hasProperty("sun.stderr.encoding")) { try { val versionString = javaParameters.jdk?.versionString if (versionString != null && JavaVersion.parse(versionString).isAtLeast(18)) { val charset = javaParameters.charset ?: EncodingManager.getInstance().defaultCharset commandLine.addParameter("-Dsun.stdout.encoding=" + charset.name()) commandLine.addParameter("-Dsun.stderr.encoding=" + charset.name()) } } catch (_: IllegalArgumentException) { } } } private fun appendModulePath(javaParameters: SimpleJavaParameters, vmParameters: ParametersList) { val modulePath = javaParameters.modulePath if (!modulePath.isEmpty && !vmParameters.isExplicitModulePath()) { commandLine.addParameter("-p") commandLine.addParameter(composeClassPathValues(javaParameters, modulePath)) } } private fun appendParamsEncodingClasspath(javaParameters: SimpleJavaParameters, vmParameters: ParametersList) { appendVmParameters(javaParameters, vmParameters) appendEncoding(javaParameters, vmParameters) val classPath = javaParameters.classPath if (!classPath.isEmpty && !vmParameters.isExplicitClassPath()) { commandLine.addParameter("-classpath") commandLine.addParameter(composeClassPathValues(javaParameters, classPath)) } appendModulePath(javaParameters, vmParameters) } private fun composeClassPathValues(javaParameters: SimpleJavaParameters, classPath: PathsList): TargetValue<String> { val pathValues = getClassPathValues(javaParameters, classPath) val separator = platform.pathSeparator.toString() return TargetValue.composite(pathValues) { values -> values.joinTo(StringBuilder(), separator).toString() } } private fun getClassPathValues(javaParameters: SimpleJavaParameters, classPath: PathsList): List<TargetValue<String>> { val localJdkPath = javaParameters.jdk?.homePath val remoteJdkPath = languageRuntime?.homePath val result = ArrayList<TargetValue<String>>() for (path in classPath.pathList) { if (localJdkPath == null || remoteJdkPath == null || !path.startsWith(localJdkPath)) { result.add(requestUploadIntoTarget(JavaLanguageRuntimeType.CLASS_PATH_VOLUME, path)) } else { //todo[remoteServers]: revisit with "provided" volume (?) val separator = platform.fileSeparator result.add(TargetValue.fixed(FileUtil.toCanonicalPath( remoteJdkPath + separator + StringUtil.trimStart(path, localJdkPath), separator))) } } return result } private fun composePathsList(targetPaths: Collection<TargetValue<String>>): TargetValue<String> { return TargetValue.composite(targetPaths) { it.joinTo(StringBuilder(), platform.pathSeparator.toString()).toString() } } private fun joinPath(segments: Array<String>) = segments.joinTo(StringBuilder(), platform.fileSeparator.toString()).toString() companion object { private const val JAVAAGENT = "-javaagent" private val LOG by lazy { Logger.getInstance(JdkCommandLineSetup::class.java) } private fun commandLineWrapperClass(): Class<*>? { try { return Class.forName("com.intellij.rt.execution.CommandLineWrapper") } catch (e: ClassNotFoundException) { return null } } private fun ParametersList.isExplicitClassPath(): Boolean { return this.hasParameter("-cp") || this.hasParameter("-classpath") || this.hasParameter("--class-path") } private fun isUrlClassloader(parametersList: ParametersList): Boolean { return (parametersList.getPropertyValue("java.system.class.loader") ?: "").startsWith("com.intellij.util.lang.") } private fun ParametersList.isExplicitModulePath(): Boolean { return this.hasParameter("-p") || this.hasParameter("--module-path") } private fun isUserDefinedProperty(param: String): Boolean { return param.startsWith("-D") && !(param.startsWith("-Dsun.") || param.startsWith("-Djava.")) } @Throws(CantRunException::class) private fun throwUnableToCreateTempFile(cause: IOException?) { throw CantRunException(LangCoreBundle.message("error.message.failed.to.create.a.temporary.file.in.0", FileUtil.getTempDirectory()), cause) } } private class ArgFile @Throws(IOException::class) constructor(private val dynamicVMOptions: Boolean, private val charset: Charset, private val platform: Platform) { val file = FileUtil.createTempFile("idea_arg_file" + Random().nextInt(Int.MAX_VALUE), null) private val myPromisedOptionValues: MutableMap<String, TargetValue<String>> = LinkedHashMap() private val myPromisedParameters = mutableListOf<TargetValue<String>>() private val myAllPromises = mutableListOf<Promise<String>>() fun addPromisedParameter(@NonNls optionName: String, promisedValue: TargetValue<String>) { myPromisedOptionValues[optionName] = promisedValue registerPromise(promisedValue) } fun addPromisedParameter(promisedValue: TargetValue<String>) { myPromisedParameters.add(promisedValue) registerPromise(promisedValue) } fun scheduleWriteFileWhenReady(vmParameters: ParametersList, rememberContent: () -> Unit) { myAllPromises.collectResults().onSuccess { try { writeArgFileNow(vmParameters) rememberContent.invoke() } catch (e: IOException) { //todo[remoteServers]: interrupt preparing environment } catch (e: ExecutionException) { LOG.error("Couldn't resolve target value", e) } catch (e: TimeoutException) { LOG.error("Couldn't resolve target value", e) } } } @Throws(IOException::class, ExecutionException::class, TimeoutException::class) private fun writeArgFileNow(vmParameters: ParametersList) { val fileArgs: MutableList<String?> = ArrayList() if (dynamicVMOptions) { fileArgs.addAll(vmParameters.list) } for ((nextOption, nextResolvedValue) in myPromisedOptionValues) { fileArgs.add(nextOption) fileArgs.add(nextResolvedValue.targetValue.blockingGet(0)) } for (nextResolvedParameter in myPromisedParameters) { fileArgs.add(nextResolvedParameter.targetValue.blockingGet(0)) } CommandLineWrapperUtil.writeArgumentsFile(file, fileArgs, platform.lineSeparator, charset) } private fun registerPromise(value: TargetValue<String>) { myAllPromises.add(value.targetValue) } } internal class ClasspathJar @Throws(IOException::class) constructor(private val setup: JdkCommandLineSetup, private val notEscapeClassPathUrl: Boolean) { private val manifest = Manifest() private val manifestText = StringBuilder() internal val file = FileUtil.createTempFile( CommandLineWrapperUtil.CLASSPATH_JAR_FILE_NAME_PREFIX + abs(Random().nextInt()), ".jar", true) fun addToManifest(key: String, value: String, skipInCommandLineContent: Boolean = false) { manifest.mainAttributes.putValue(key, value) if (!skipInCommandLineContent) { manifestText.append(key).append(": ").append(value).append("\n") } } fun scheduleWriteFileWhenClassPathReady(classpath: List<TargetValue<String>>, selfUpload: TargetValue<String>) { classpath.map { it.targetValue }.collectResults().onSuccess { try { writeFileNow(classpath, selfUpload) } catch (e: IOException) { //todo[remoteServers]: interrupt preparing environment } catch (e: ExecutionException) { LOG.error("Couldn't resolve target value", e) } catch (e: TimeoutException) { LOG.error("Couldn't resolve target value", e) } } } @Throws(ExecutionException::class, TimeoutException::class, IOException::class) private fun writeFileNow(resolvedTargetClasspath: List<TargetValue<String>>, selfUpload: TargetValue<String>) { val classPath = StringBuilder() for (parameter in resolvedTargetClasspath) { if (classPath.isNotEmpty()) classPath.append(' ') val localValue = parameter.localValue.blockingGet(0) val targetValue = parameter.targetValue.blockingGet(0) if (targetValue == null || localValue == null) { throw ExecutionException("Couldn't resolve target value", null) } val targetUrl = pathToUrl(targetValue) classPath.append(targetUrl) if (!StringUtil.endsWithChar(targetUrl, '/') && File(localValue).isDirectory) { classPath.append('/') } } // todo[remoteServers]: race condition here (?), it has to be called after classpath upload BUT before selfUpload CommandLineWrapperUtil.fillClasspathJarFile(manifest, classPath.toString(), file) selfUpload.targetValue.onSuccess { value: String -> val fullManifestText = manifestText.toString() + "Class-Path: " + classPath.toString() setup.commandLineContent[value] = fullManifestText } } @Throws(MalformedURLException::class) private fun pathToUrl(targetPath: String): String { val url : URL = if (notEscapeClassPathUrl) { // repeat login of `File(path).toURL()` without using system-dependent java.io.File URL(URLUtil.FILE_PROTOCOL, "", slashify(targetPath)) } else { // repeat logic of `File(path).toURI().toURL()` without using system-dependent java.io.File val p = slashify(targetPath) URI(URLUtil.FILE_PROTOCOL, null, if (p.startsWith("//")) "//$p" else p, null).toURL() } return url.toString() } // counterpart of java.io.File#slashify private fun slashify(path: String): String { return FileUtil.toSystemIndependentName(path).let { if (it.startsWith("/")) it else "/$it" } } } }
apache-2.0
dd66bc4a2326234ed49110c9a3975e57
42.738149
156
0.706725
5.004132
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt
4
2153
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.refactoring.rename.RenameProcessor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RenameParameterToMatchOverriddenMethodFix( parameter: KtParameter, private val newName: String ) : KotlinQuickFixAction<KtParameter>(parameter) { override fun getFamilyName() = KotlinBundle.message("rename.identifier.fix.text") override fun getText() = KotlinBundle.message("rename.parameter.to.match.overridden.method") override fun startInWriteAction(): Boolean = false public override fun invoke(project: Project, editor: Editor?, file: KtFile) { RenameProcessor(project, element ?: return, newName, false, false).run() } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val parameter = diagnostic.psiElement.getNonStrictParentOfType<KtParameter>() ?: return null val parameterDescriptor = parameter.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL) ?: return null val parameterFromSuperclassName = parameterDescriptor.overriddenDescriptors .map { it.name.asString() } .distinct() .singleOrNull() ?: return null return RenameParameterToMatchOverriddenMethodFix(parameter, parameterFromSuperclassName) } } }
apache-2.0
4416cbb2d834ff8a876c102168317e60
49.069767
158
0.774268
5.053991
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/Md5.kt
1
2624
package com.beust.kobalt.maven import com.beust.kobalt.misc.KFiles import com.beust.kobalt.misc.log import java.io.File import java.security.MessageDigest import javax.xml.bind.DatatypeConverter public class Md5 { companion object { // private fun md5(file: File) : String { // if (file.isDirectory) { // println("PROBLEM") // } // val md5 = MessageDigest.getInstance("MD5") // val bytes = file.readBytes() // md5.update(bytes, 0, bytes.size) // return DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() // } fun toMd5Directories(directories: List<File>) : String? { val ds = directories.filter { it.exists() } if (ds.size > 0) { MessageDigest.getInstance("MD5").let { md5 -> var fileCount = 0 directories.filter { it.exists() }.forEach { file -> if (file.isFile) { val bytes = file.readBytes() md5.update(bytes, 0, bytes.size) fileCount++ } else { val files = KFiles.findRecursively(file) // , { f -> f.endsWith("java")}) log(2, " Calculating checksum of ${files.size} files in $file") files.map { File(file, it) }.filter { it.isFile }.forEach { fileCount++ val bytes = it.readBytes() md5.update(bytes, 0, bytes.size) } } } // The output directory might exist but with no files in it, in which case // we must run the task if (fileCount > 0) { val result = DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() return result } else { return null } } } else { return null } } fun toMd5(file: File) = MessageDigest.getInstance("MD5").let { md5 -> file.forEachBlock { bytes, size -> md5.update(bytes, 0, size) } DatatypeConverter.printHexBinary(md5.digest()).toLowerCase() } } }
apache-2.0
f448aa367ae7a7342b758381e3739f0f
37.588235
101
0.432165
5.095146
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/descriptions/DescriptionEditView.kt
1
17802
package org.wikipedia.descriptions import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.PorterDuff import android.util.AttributeSet import android.view.LayoutInflater import android.view.inputmethod.EditorInfo import android.widget.* import androidx.core.content.ContextCompat import androidx.core.widget.ImageViewCompat import androidx.core.widget.addTextChangedListener import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.databinding.ViewDescriptionEditBinding import org.wikipedia.language.LanguageUtil import org.wikipedia.mlkit.MlKitLanguageDetector import org.wikipedia.page.PageTitle import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.util.* import java.util.* class DescriptionEditView : LinearLayout, MlKitLanguageDetector.Callback { interface Callback { fun onSaveClick() fun onHelpClick() fun onCancelClick() fun onBottomBarClick() fun onVoiceInputClick() } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private lateinit var pageTitle: PageTitle private lateinit var pageSummaryForEdit: PageSummaryForEdit private lateinit var action: DescriptionEditActivity.Action private val binding = ViewDescriptionEditBinding.inflate(LayoutInflater.from(context), this) private val mlKitLanguageDetector = MlKitLanguageDetector() private val textValidateRunnable = Runnable { validateText() } private var originalDescription: String? = null private var isTranslationEdit = false private var isLanguageWrong = false private var isTextValid = false var callback: Callback? = null var description: String? get() = binding.viewDescriptionEditText.text.toString().trim() set(text) { binding.viewDescriptionEditText.setText(text) } init { FeedbackUtil.setButtonLongPressToast(binding.viewDescriptionEditSaveButton, binding.viewDescriptionEditCancelButton, binding.viewDescriptionEditHelpButton) orientation = VERTICAL mlKitLanguageDetector.callback = this binding.viewDescriptionEditSaveButton.setOnClickListener { validateText() if (it.isEnabled) { callback?.onSaveClick() } } binding.viewDescriptionEditHelpButton.setOnClickListener { callback?.onHelpClick() } binding.viewDescriptionEditCancelButton.setOnClickListener { callback?.onCancelClick() } binding.viewDescriptionEditPageSummaryContainer.setOnClickListener { performReadArticleClick() } binding.viewDescriptionEditText.addTextChangedListener { enqueueValidateText() isLanguageWrong = false mlKitLanguageDetector.detectLanguageFromText(binding.viewDescriptionEditText.text.toString()) } binding.viewDescriptionEditText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { if (binding.viewDescriptionEditSaveButton.isEnabled) { callback?.onSaveClick() } return@setOnEditorActionListener true } false } } fun setPageTitle(pageTitle: PageTitle) { this.pageTitle = pageTitle originalDescription = pageTitle.description setVoiceInput() setHintText() description = originalDescription setReviewHeaderText(false) } private fun setVoiceInput() { binding.viewDescriptionEditTextLayout.setEndIconOnClickListener { callback?.onVoiceInputClick() } } private fun setHintText() { binding.viewDescriptionEditTextLayout.setHintTextAppearance(R.style.DescriptionEditViewHintTextStyle) binding.viewDescriptionEditTextLayout.hint = getHintText(pageTitle.wikiSite.languageCode()) } private fun getHeaderTextRes(inReview: Boolean): Int { if (inReview) { return if (action == DescriptionEditActivity.Action.ADD_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_CAPTION) { R.string.suggested_edits_review_image_caption } else { R.string.suggested_edits_review_description } } return if (originalDescription.isNullOrEmpty()) { when (action) { DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION -> R.string.description_edit_translate_description DescriptionEditActivity.Action.ADD_CAPTION -> R.string.description_edit_add_image_caption DescriptionEditActivity.Action.TRANSLATE_CAPTION -> R.string.description_edit_translate_image_caption else -> R.string.description_edit_add_description } } else { if (action == DescriptionEditActivity.Action.ADD_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_CAPTION) { R.string.description_edit_edit_image_caption } else { R.string.description_edit_edit_description } } } private fun getLabelText(lang: String): CharSequence { return when (action) { DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION -> { context.getString(R.string.description_edit_translate_article_description_label_per_language, WikipediaApp.getInstance().language().getAppLanguageLocalizedName(lang)) } DescriptionEditActivity.Action.TRANSLATE_CAPTION -> { context.getString(R.string.description_edit_translate_caption_label_per_language, WikipediaApp.getInstance().language().getAppLanguageLocalizedName(lang)) } DescriptionEditActivity.Action.ADD_CAPTION -> context.getString(R.string.description_edit_add_caption_label) else -> context.getString(R.string.description_edit_article_description_label) } } private fun getHintText(lang: String): CharSequence { return if (action == DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION) { context.getString(R.string.description_edit_translate_article_description_hint_per_language, WikipediaApp.getInstance().language().getAppLanguageLocalizedName(lang)) } else if (action == DescriptionEditActivity.Action.ADD_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_CAPTION) { context.getString(R.string.description_edit_translate_caption_hint_per_language, WikipediaApp.getInstance().language().getAppLanguageLocalizedName(lang)) } else { context.getString(R.string.description_edit_text_hint) } } private fun setReviewHeaderText(inReview: Boolean) { binding.viewDescriptionEditHeader.text = context.getString(getHeaderTextRes(inReview)) } private fun setDarkReviewScreen(enabled: Boolean) { if (context is DescriptionEditActivity && (action == DescriptionEditActivity.Action.ADD_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_CAPTION)) { binding.viewDescriptionEditToolbarContainer.setBackgroundResource(if (enabled) android.R.color.black else ResourceUtil.getThemedAttributeId(context, R.attr.paper_color)) binding.viewDescriptionEditSaveButton.setColorFilter(if (enabled) Color.WHITE else ResourceUtil.getThemedColor(context, R.attr.themed_icon_color), PorterDuff.Mode.SRC_IN) binding.viewDescriptionEditCancelButton.setColorFilter(if (enabled) Color.WHITE else ResourceUtil.getThemedColor(context, R.attr.toolbar_icon_color), PorterDuff.Mode.SRC_IN) binding.viewDescriptionEditHeader.setTextColor(if (enabled) Color.WHITE else ResourceUtil.getThemedColor(context, R.attr.material_theme_primary_color)) (context as DescriptionEditActivity).updateStatusBarColor(if (enabled) Color.BLACK else ResourceUtil.getThemedColor(context, R.attr.paper_color)) DeviceUtil.updateStatusBarTheme(context as DescriptionEditActivity, null, enabled) (context as DescriptionEditActivity).updateNavigationBarColor(if (enabled) Color.BLACK else ResourceUtil.getThemedColor(context, R.attr.paper_color)) } } fun setSummaries(sourceSummary: PageSummaryForEdit, targetSummary: PageSummaryForEdit?) { // the summary data that will bring to the review screen pageSummaryForEdit = if (isTranslationEdit) targetSummary!! else sourceSummary binding.viewDescriptionEditPageSummaryContainer.visibility = VISIBLE binding.viewDescriptionEditPageSummaryLabel.text = getLabelText(sourceSummary.lang) binding.viewDescriptionEditPageSummary.text = StringUtil.strip(StringUtil.removeHTMLTags(if (isTranslationEdit || action == DescriptionEditActivity.Action.ADD_CAPTION) sourceSummary.description else sourceSummary.extractHtml)) if (binding.viewDescriptionEditPageSummary.text.toString().isEmpty() || action == DescriptionEditActivity.Action.ADD_CAPTION && !sourceSummary.pageTitle.description.isNullOrEmpty()) { binding.viewDescriptionEditPageSummaryContainer.visibility = GONE } L10nUtil.setConditionalLayoutDirection(this, if (isTranslationEdit) sourceSummary.lang else pageTitle.wikiSite.languageCode()) binding.viewDescriptionEditReadArticleBarContainer.setSummary(pageSummaryForEdit) binding.viewDescriptionEditReadArticleBarContainer.setOnClickListener { performReadArticleClick() } } fun setSaveState(saving: Boolean) { showProgressBar(saving) if (saving) { enableSaveButton(enabled = false, saveInProgress = true) } else { updateSaveButtonEnabled() } } fun loadReviewContent(enabled: Boolean) { if (enabled) { binding.viewDescriptionEditReviewContainer.setSummary(pageSummaryForEdit, description.orEmpty(), action == DescriptionEditActivity.Action.ADD_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_CAPTION) binding.viewDescriptionEditReviewContainer.show() binding.viewDescriptionEditReadArticleBarContainer.hide() binding.viewDescriptionEditContainer.visibility = GONE binding.viewDescriptionEditHelpButton.visibility = GONE DeviceUtil.hideSoftKeyboard(binding.viewDescriptionEditReviewContainer) } else { binding.viewDescriptionEditReviewContainer.hide() binding.viewDescriptionEditReadArticleBarContainer.show() binding.viewDescriptionEditContainer.visibility = VISIBLE binding.viewDescriptionEditHelpButton.visibility = VISIBLE } setReviewHeaderText(enabled) setDarkReviewScreen(enabled) } fun showingReviewContent(): Boolean { return binding.viewDescriptionEditReviewContainer.isShowing } fun setError(text: CharSequence?) { binding.viewDescriptionEditTextLayout.setErrorIconDrawable(R.drawable.ic_error_black_24dp) val colorStateList = ColorStateList.valueOf(ResourceUtil.getThemedColor(context, R.attr.colorError)) binding.viewDescriptionEditTextLayout.setErrorIconTintList(colorStateList) binding.viewDescriptionEditTextLayout.setErrorTextColor(colorStateList) binding.viewDescriptionEditTextLayout.boxStrokeErrorColor = colorStateList layoutErrorState(text) } private fun setWarning(text: CharSequence?) { binding.viewDescriptionEditTextLayout.setErrorIconDrawable(R.drawable.ic_warning_24) val colorStateList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yellow30)) binding.viewDescriptionEditTextLayout.setErrorIconTintList(colorStateList) binding.viewDescriptionEditTextLayout.setErrorTextColor(colorStateList) binding.viewDescriptionEditTextLayout.boxStrokeErrorColor = colorStateList layoutErrorState(text) } private fun clearError() { binding.viewDescriptionEditTextLayout.error = null } private fun layoutErrorState(text: CharSequence?) { // explicitly clear the error, to prevent a glitch in the Material library. clearError() binding.viewDescriptionEditTextLayout.error = text if (!text.isNullOrEmpty()) { post { if (isAttachedToWindow) { binding.viewDescriptionEditScrollview.fullScroll(FOCUS_DOWN) } } } } private fun enqueueValidateText() { removeCallbacks(textValidateRunnable) postDelayed(textValidateRunnable, TEXT_VALIDATE_DELAY_MILLIS) } private fun validateText() { isTextValid = true val text = binding.viewDescriptionEditText.text.toString().toLowerCase(Locale.getDefault()).trim() if (text.isEmpty()) { isTextValid = false clearError() } else if (text.length < 2) { isTextValid = false setError(context.getString(R.string.description_too_short)) } else if ((action == DescriptionEditActivity.Action.ADD_DESCRIPTION || action == DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION) && (listOf(".", ",", "!", "?").filter { text.endsWith(it) }).isNotEmpty()) { isTextValid = false setError(context.getString(R.string.description_ends_with_punctuation)) } else if ((action == DescriptionEditActivity.Action.ADD_DESCRIPTION || action == DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION) && LanguageUtil.startsWithArticle(text, pageTitle.wikiSite.languageCode())) { setWarning(context.getString(R.string.description_starts_with_article)) } else if ((action == DescriptionEditActivity.Action.ADD_DESCRIPTION || action == DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION) && pageTitle.wikiSite.languageCode() == "en" && Character.isLowerCase(binding.viewDescriptionEditText.text.toString()[0])) { setWarning(context.getString(R.string.description_starts_with_lowercase)) } else if (isLanguageWrong) { setWarning(context.getString(R.string.description_is_in_different_language, WikipediaApp.getInstance().language().getAppLanguageLocalizedName(pageSummaryForEdit.lang))) } else { clearError() } updateSaveButtonEnabled() } fun setHighlightText(text: String?) { if (text != null && originalDescription != null) { postDelayed({ StringUtil.highlightEditText(binding.viewDescriptionEditText, originalDescription!!, text) }, 500) } } private fun updateSaveButtonEnabled() { if (!binding.viewDescriptionEditText.text.isNullOrEmpty() && originalDescription.orEmpty() != binding.viewDescriptionEditText.text.toString() && isTextValid) { enableSaveButton(enabled = true, saveInProgress = false) } else { enableSaveButton(enabled = false, saveInProgress = false) } } private fun enableSaveButton(enabled: Boolean, saveInProgress: Boolean) { if (saveInProgress) { binding.viewDescriptionEditSaveButton.setImageResource(R.drawable.ic_check_circle_black_24dp) ImageViewCompat.setImageTintList(binding.viewDescriptionEditSaveButton, ColorStateList.valueOf(ResourceUtil.getThemedColor(context, R.attr.themed_icon_color))) binding.viewDescriptionEditSaveButton.isEnabled = false binding.viewDescriptionEditSaveButton.alpha = 1 / 2f } else { binding.viewDescriptionEditSaveButton.alpha = 1f if (enabled) { binding.viewDescriptionEditSaveButton.setImageResource(R.drawable.ic_check_circle_black_24dp) ImageViewCompat.setImageTintList(binding.viewDescriptionEditSaveButton, ColorStateList.valueOf(ResourceUtil.getThemedColor(context, R.attr.themed_icon_color))) binding.viewDescriptionEditSaveButton.isEnabled = true } else { binding.viewDescriptionEditSaveButton.setImageResource(R.drawable.ic_check_black_24dp) ImageViewCompat.setImageTintList(binding.viewDescriptionEditSaveButton, ColorStateList.valueOf(ResourceUtil.getThemedColor(context, R.attr.material_theme_de_emphasised_color))) binding.viewDescriptionEditSaveButton.isEnabled = false } } } fun showProgressBar(show: Boolean) { binding.viewDescriptionEditProgressBar.visibility = if (show) VISIBLE else GONE } fun setAction(action: DescriptionEditActivity.Action) { this.action = action isTranslationEdit = action == DescriptionEditActivity.Action.TRANSLATE_CAPTION || action == DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION } private fun performReadArticleClick() { callback?.onBottomBarClick() } override fun onLanguageDetectionSuccess(languageCode: String) { if (languageCode != pageSummaryForEdit.lang && languageCode != WikipediaApp.getInstance().language().getDefaultLanguageCode(pageSummaryForEdit.lang)) { isLanguageWrong = true enqueueValidateText() } } companion object { private const val TEXT_VALIDATE_DELAY_MILLIS = 1000L } }
apache-2.0
120c419953d03eb2c44e55ac6b4ce5f9
48.45
234
0.704696
5.197664
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/LinkPreviewFunnel.kt
1
1096
package org.wikipedia.analytics import org.json.JSONObject import org.wikipedia.WikipediaApp import org.wikipedia.settings.Prefs class LinkPreviewFunnel(app: WikipediaApp, private val source: Int) : TimedFunnel(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_ALL) { private var pageId = 0 override fun preprocessData(eventData: JSONObject): JSONObject { preprocessData(eventData, "version", PROD_LINK_PREVIEW_VERSION) preprocessData(eventData, "source", source) preprocessData(eventData, "page_id", pageId) return super.preprocessData(eventData) } fun setPageId(pageId: Int) { this.pageId = pageId } fun logLinkClick() { log("action", "linkclick") } fun logNavigate() { log("action", if (Prefs.isLinkPreviewEnabled()) "navigate" else "disabled") } fun logCancel() { log("action", "cancel") } companion object { private const val SCHEMA_NAME = "MobileWikiAppLinkPreview" private const val REV_ID = 18531254 private const val PROD_LINK_PREVIEW_VERSION = 3 } }
apache-2.0
669e41110cb8731bd576777f08519c96
27.102564
125
0.668796
4.135849
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RoundNumberFix.kt
2
2731
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.isDouble import org.jetbrains.kotlin.types.typeUtil.isFloat import org.jetbrains.kotlin.types.typeUtil.isInt import org.jetbrains.kotlin.types.typeUtil.isLong class RoundNumberFix( element: KtExpression, type: KotlinType, private val disableIfAvailable: IntentionAction? = null ) : KotlinQuickFixAction<KtExpression>(element), LowPriorityAction { private val isTarget = type.isLongOrInt() && element.analyze(BodyResolveMode.PARTIAL).getType(element)?.isDoubleOrFloat() == true private val roundFunction = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type).let { "roundTo$it" } override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = disableIfAvailable?.isAvailable(project, editor, file) != true && isTarget override fun getText() = KotlinBundle.message("round.using.0", roundFunction) override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val replaced = element.replaced(KtPsiFactory(file).createExpressionByPattern("$0.$roundFunction()", element)) file.resolveImportReference(FqName("kotlin.math.$roundFunction")).firstOrNull()?.also { ImportInsertHelper.getInstance(project).importDescriptor(file, it) } editor?.caretModel?.moveToOffset(replaced.endOffset) } private fun KotlinType.isLongOrInt() = this.isLong() || this.isInt() private fun KotlinType.isDoubleOrFloat() = this.isDouble() || this.isFloat() }
apache-2.0
dc1a0e8a51210c3e044b8ad6c0e65f7b
46.929825
158
0.78799
4.455139
false
false
false
false
GreenJoey/My-Simple-Programs
Examples And Tutorials/Kotlin Koans Solutions/Introduction/task7.kt
1
657
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) { if (client == null || message == null) return // Since `client` and `message` have already been null checked, no need for safe-call. // We know they are not null val info: PersonalInfo = client.personalInfo ?: return // Since we used the elvis-operator to null check, we also don't need a safe call here val email:String = info.email ?: return mailer.sendMessage(email, message) } class Client (val personalInfo: PersonalInfo?) class PersonalInfo (val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
gpl-2.0
5e9ab1d51eb2611bcebe9868fe79e1d1
37.647059
90
0.700152
4.266234
false
false
false
false
dahlstrom-g/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/PropertyMethodReferenceSearchExecutor.kt
19
2008
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.findUsages import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.PsiSubstitutor import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.util.Processor import org.jetbrains.plugins.groovy.findUsages.GroovyScopeUtil.restrictScopeToGroovyFiles import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrGdkMethodImpl import org.jetbrains.plugins.groovy.lang.psi.util.GdkMethodUtil import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils /** * author ven */ class PropertyMethodReferenceSearchExecutor : QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters>(true) { override fun processQuery(queryParameters: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { val method = queryParameters.method val propertyName: String? = if (GdkMethodUtil.isCategoryMethod(method, null, null, PsiSubstitutor.EMPTY)) { val cat = GrGdkMethodImpl.createGdkMethod(method, false, null) GroovyPropertyUtils.getPropertyName(cat as PsiMethod) } else { GroovyPropertyUtils.getPropertyName(method) } if (propertyName == null) return val onlyGroovyFiles = restrictScopeToGroovyFiles(queryParameters.effectiveSearchScope, GroovyScopeUtil.getEffectiveScope(method)) queryParameters.optimizer.searchWord(propertyName, onlyGroovyFiles, UsageSearchContext.IN_CODE, true, method) if (!GroovyPropertyUtils.isPropertyName(propertyName)) { queryParameters.optimizer.searchWord( StringUtil.decapitalize(propertyName)!!, onlyGroovyFiles, UsageSearchContext.IN_CODE, true, method ) } } }
apache-2.0
b8f38cc339903bfd5e7029ce58efc670
43.622222
140
0.806773
4.542986
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/utils/MatrixEvaluator.kt
1
1318
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.shared.utils import android.animation.TypeEvaluator import android.graphics.Matrix /** * This class is passed to ValueAnimator in order to animate matrix changes */ class MatrixEvaluator : TypeEvaluator<Matrix> { private val tempStartValues = FloatArray(9) private val tempEndValues = FloatArray(9) private val tempMatrix = Matrix() override fun evaluate(fraction: Float, startValue: Matrix, endValue: Matrix): Matrix { startValue.getValues(tempStartValues) endValue.getValues(tempEndValues) for (i in 0..8) { val diff = tempEndValues[i] - tempStartValues[i] tempEndValues[i] = tempStartValues[i] + fraction * diff } tempMatrix.setValues(tempEndValues) return tempMatrix } }
gpl-2.0
823cce5cc7984f29cbc59e942c32b9ca
31.146341
90
0.716237
4.251613
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/CompareHistActivity.kt
1
1454
package com.cv4j.app.activity import android.os.Bundle import androidx.fragment.app.Fragment import com.cv4j.app.R import com.cv4j.app.adapter.CompareHistAdapter import com.cv4j.app.app.BaseActivity import com.cv4j.app.fragment.CompareHist1Fragment import com.cv4j.app.fragment.CompareHist2Fragment import com.cv4j.app.fragment.CompareHist3Fragment import kotlinx.android.synthetic.main.activity_compare_hist.* import java.util.* /** * * @FileName: * com.cv4j.app.activity.CompareHistActivity * @author: Tony Shen * @date: 2020-05-05 11:40 * @version: V1.0 <描述当前版本功能> */ class CompareHistActivity : BaseActivity() { var title: String? = null private val mList: MutableList<Fragment> = ArrayList<Fragment>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_compare_hist) intent.extras?.let { title = it.getString("Title","") }?:{ title = "" }() toolbar.setOnClickListener { finish() } initData() } private fun initData() { toolbar.title = "< $title" mList.add(CompareHist1Fragment()) mList.add(CompareHist2Fragment()) mList.add(CompareHist3Fragment()) viewpager.adapter = CompareHistAdapter(this.supportFragmentManager, mList) tablayout.setupWithViewPager(viewpager) } }
apache-2.0
07168da1c79e514f17453a754de85478
26.150943
82
0.680111
3.855228
false
false
false
false
paplorinc/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/rest.kt
1
1466
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images.sync import org.apache.http.HttpEntity import org.apache.http.HttpHeaders import org.apache.http.HttpStatus import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpRequestBase import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClients import org.apache.http.util.EntityUtils import java.util.* internal fun get(path: String, conf: HttpRequestBase.() -> Unit = {}) = rest(HttpGet(path).apply { conf() }) internal fun post(path: String, body: String, conf: HttpRequestBase.() -> Unit = {}) = rest(HttpPost(path).apply { entity = StringEntity(body, Charsets.UTF_8) conf() }) private fun rest(request: HttpRequestBase) = HttpClients.createDefault().use { val response = it.execute(request) val entity = response.entity.asString() if (response.statusLine.statusCode != HttpStatus.SC_OK) error("${response.statusLine.statusCode} ${response.statusLine.reasonPhrase} $entity") entity } internal fun HttpRequestBase.basicAuth(login: String, password: String) { addHeader(HttpHeaders.AUTHORIZATION, "Basic ${Base64.getEncoder().encodeToString("$login:$password".toByteArray())}") } internal fun HttpEntity.asString() = EntityUtils.toString(this, Charsets.UTF_8)
apache-2.0
2b9b0ab3fa674ab13b5036da99c192d8
43.454545
144
0.772851
3.847769
false
false
false
false
antlr/grammars-v4
kotlin/kotlin-formal/examples/Test.kt
1
14700
/** * Made of test data from https://github.com/JetBrains/kotlin/tree/master/compiler/testData/psi */ //AnonymousInitializer.kt class Foo { init { foo() val c = f } } //BabySteps.kt class Runnable<a,a>(a : doo = 0) : foo(d=0), bar by x, bar { } //ByClauses.kt class A : b by a { companion object {} } class A : b by a + b() * 5 { companion object {} } class A : b by (a) { companion object {} } class A : b by (a {}) { companion object {} } class A : b by a[a {}] { companion object {} } class A : b by a(a {}) { companion object {} } class A : b by object { fun f() = a {} } { companion object {} } //CallsInWhen.kt fun foo() { when (a) { a.foo -> a a.foo() -> a a.foo<T> -> a a.foo<T>(a) -> a a.foo<T>(a, d) -> a else -> a } } //CallWithManyClosures.kt val a = f() {} {} {} val a = f {} {} {} val a = f {} val a = f() {} val a = (f) {} {} {} val a = (f)() {} {} {} val a = (f)<A>() {} {} {} //CollectionLiterals.kt fun test() { [] [1] [1, 2] [[]] [[1]] [1, []] [[], 1] [[], [1, []]] [1, 2] [1, [2]] } //CommentsBindingInLambda.kt val la1 = { // start // start 1 foo() // middle foo() // end } val la2 = { /**/ } val la3 = { /** */ } val la4 = { /** Should be under block */ /** Should be under property */ val some = 1 } val la5 = { /** */ /** */ } val la6 = /*1*/ {/*2*/ a /*3*/ -> /*4*/ } val la7 = {/**/} fun foo() {} //CommentsBindingInStatementBlock.kt fun test() { if (true) {/*start-end*/} if (true) { /*start-end*/ } if (true) { /*start*/ /*end*/ } if (true) { /*start*/ /** doc */ val a = 12 /*end*/ } } //Constructors.kt class foo { } public class foo() : Bar private class foo<T>() : Bar //destructuringInLambdas.kt fun foo() { a1.filter { (x, y) -> } a2.filter { (x) -> } a3.filter { z, (x, y) -> } a4.filter { (x, y), z -> } a5.filter { q, (x, y), z -> } a6.filter { (x, y), (z, w) -> } a7.filter { (x, y): Type, (z: Type), (w, u: T) : V -> foo7() } } //DoubleColonWhitespaces.kt fun tests() { a:: b a ::b a :: b a?:: b a ?::b a ?:: b a? ::b a ? :: b a ? ? :: b } fun breakLine() { a? ::b } //DynamicReceiver.kt fun dynamic.foo() fun dynamic?.foo() val dynamic.foo: Int val dynamic?.foo: Int val foo: dynamic.() -> Unit // testing look-ahead with comments and whitespace fun dynamic . foo() fun dynamic .foo() fun dynamic// line-comment .foo() fun dynamic/* */.foo() //DynamicTypes.kt fun foo( p1: dynamic, p2: @a dynamic, p3: foo.dynamic, p4: dynamic.foo, p5: dynamic<T>, p6: Foo<dynamic>, p7: dynamic?, p8: (dynamic) -> dynamic ): dynamic //EnumCommas.kt enum class Color { NORTH, SOUTH, WEST, EAST, ; } //EnumEntrySemicolonInlineMember.kt enum class My { FIRST; inline fun foo() {} } //EnumEntrySemicolonMember.kt enum class My { FIRST; fun foo() {} } //EnumIn.kt enum class Foo { `in` } //EnumInline.kt enum class My { inline } //Enums.kt enum class Color(val rgb : Int) { RED(0xFF000), GREEN(0x00FF00), BLUE(0x0000FF) // the end } //EnumShortCommas.kt enum class Color(val rgb : Int) { RED(0xFF000), GREEN(0x00FF00), BLUE(0x0000FF), ; } //EnumShortWithOverload.kt enum class Color(val rgb : Int) { RED(0xFF000) { override fun foo(): Int { return 1 } }, GREEN(0x00FF00) { override fun foo(): Int { return 2 } }, BLUE(0x0000FF) { override fun foo(): Int { return 3 } }; abstract fun foo(): Int } //EOLsInComments.kt fun foo() { a + b a /** */+ b a /* */+ b a /* */ + b a /* */ + b a /** */ + b a // + b a // + b } //EOLsOnRollback.kt fun foo() { class foo fun foo() class foo typealias x = t var r @a var foo = 4 1 @a val f } //ExtensionsWithQNReceiver.kt val java.util.Map<*,*>.size : Int fun java.util.Map<*,*>.size() : Int = 1 //FloatingPointLiteral.kt val array = array<Any>( 1, 1.0, 1e1, 1.0e1, 1e-1, 1.0e-1, 1F, 1.0F, 1e1F, 1.0e1F, 1e-1F, 1.0e-1F, 1f, 1.0f, 1e1f, 1.0e1f, 1e-1f, 1.0e-1f, .1_1, 3.141_592, 1e1__3_7, 1_0f, 1e1_2f, 2_2.0f, .3_3f, 3.14_16f, 6.022___137e+2_3f ) //FunctionCalls.kt fun foo() { f(a) g<bar>(a) h<baz> (a) i {s} j; {s} k { s } l(a) { s } m(a); { s } n<a>(a) { s } o<a>(a); { s } p(qux<a, b>) q(quux<a, b>(a)) r(corge<a, 1, b>(a)) s(grault<a, (1 + 2), b>(a)) t(garply<a, 1 + 2, b>(a)) u(waldo<a, 1 * 2, b>(a)) v(fred<a, *, b>(a)) w(plugh<a, "", b>(a)) xyzzy<*>() 1._foo() 1.__foo() 1_1._foo() 1._1foo() 1._1_foo() } //FunctionLiterals.kt fun foo() { {} {foo} {a -> a} {x, y -> 1} {a: b -> f} {a: b, c -> f} {a: b, c: d -> f} {a: (Int) -> Unit, c: (Int) -> Unit -> f} //{a: ((Int) -> Unit) ->} todo //{[a] a: A -> } } //FunctionTypes.kt typealias f = (@[a] a) -> b typealias f = (a) -> b typealias f = () -> @[x] b typealias f = () -> Unit typealias f = (a : @[a] a) -> b typealias f = (a : a) -> b typealias f = () -> b typealias f = () -> Unit typealias f = (a : @[a] a, foo, x : bar) -> b typealias f = (foo, a : a) -> b typealias f = (foo, a : (a) -> b) -> b typealias f = (foo, a : (a) -> b) -> () -> Unit typealias f = T.() -> Unit typealias f = @[a] T.() -> Unit //IfWithPropery.kt val a = if(1) {var f = a;a} else {null} val a = if(1) { var f = a; a } else {null} //Inner.kt class Outer { inner class Inner } //Interface.kt interface Foo { fun f() val a } //LocalDeclarations.kt fun foo() { out 1 @a abstract class foof {} abstract @a class foof {} val foo = 5 @a var foo = 4 typealias f = T.() -> Unit } //ModifierAsSelector.kt // JET-1 val z = System.out fun foo() { throw Exception(); } //NamedClassObject.kt class A { companion object Companion companion object B companion object C {} companion object object C } //NewLinesValidOperations.kt fun test() { val str = "" str .length str ?.length str as String str as? String str ?: foo true || false false && true } //NotIsAndNotIn.kt fun test() { a !is B a !in B !isBoolean(a) !inRange(a) } //ObjectLiteralAsStatement.kt fun main(args : Array<String>) { object : Thread() { }.run() object { } } //PropertyInvokes.kt fun foo() { 1._some 1.__some 1_1._some 1._1some 1._1_some } //QuotedIdentifiers.kt @`return` fun `package`() { `class`() } class `$` class `$$` class ` ` class `1` //SemicolonAfterIf.kt fun foo(a: Int): Int { var x = a; var y = x++; if (y+1 != x) return -1; return x; } //SimpleClassMembers.kt class foo { class foo { object foo { } class Bar {} fun foo() val x var f typealias foo = bar } class Bar { object foo { companion object { } private companion object { } private companion object : Fooo { } private companion object : Fooo, Bar by foo { } private companion object : Fooo, Bar by foo, Goo() } class Bar {} fun foo() val x var f typealias foo = bar } fun foo() val x var f typealias foo = bar companion object { } private companion object { } private companion object : Fooo { } private companion object : Fooo, Bar by foo { } private companion object : Fooo, Bar by foo, Goo() } //SimpleExpressions.kt fun a( a : foo = Unit, a : foo = 10, a : foo = 0x10, a : foo = '1', a : foo = "dsf", a : foo = """dsf""", a : foo = 10.0, a : foo = 10.dbl, a : foo = 10.flt, a : foo = 10.0.dbl, a : foo = 10.lng, a : foo = true, a : foo = false, a : foo = null, a : foo = this, a : foo = super<sdf>, a : foo = (10), a : foo = Triple(10, "A", 0xf), a : foo = Foo(bar), a : foo = Foo<A>(bar), a : foo = Foo(), a : foo = Foo<bar>(), a : foo = object : Foo{}, a : foo = throw Foo(), a : foo = return 10, a : foo = break, a : foo = break@la, a : foo = continue, a : foo = continue@la, a : foo = 10, a : foo = 10, a : foo = 10, a : foo = 10, a : foo = 0xffffffff.lng ) { return 10 return 10 break la@ break@la continue la@ continue@la } //SimpleModifiers.kt abstract open open annotation override open abstract private protected public internal class Bar< in out T> { val abstract val open val enum val open val annotation val override val open val abstract val private val protected val public val internal val lazy } //SoftKeywords.kt public protected private internal abstract open open annotation override open abstract private protected public internal suspend class Bar<abstract, in enum : T, out open > (a : B) : A by b { public protected private internal val abstract val open val enum val open val annotation val override val open val abstract val private val protected val public val internal val lazy val wraps val import val where val by val get val set val public val private val protected val internal val field val property val receiver val param val setparam val lateinit val const val suspend val coroutine get() = a set(S : s) {} public protected private internal fun abstract () : abstract fun open () : open fun enum () : enum fun open () : open fun annotation () : annotation fun override () : override fun open () : open fun abstract () : abstract fun private () : private fun protected () : protected fun public () : public fun internal () : internal fun lazy () : lazy fun wraps () : wraps fun import () : import fun where () : where fun by () : by fun get () : get fun set () : set fun public () : public fun private () : private fun protected () : protected fun internal () : internal fun field () : field fun property () : property fun receiver () : receiver fun param () : param fun setparam () : setparam fun lateinit () : lateinit fun const () : const fun test( abstract : t, open : t, enum : t, open : t, annotation : t, override : t, open : t, abstract : t, private : t, protected : t, public : t, internal : t, lazy : t, wraps : t, import : t, where : t, by : t, get : t, set : t, public : t, private : t, protected : t, internal : t, field : t, property : t, receiver : t, param : t, setparam : t, lateinit : t, const : t, public protected private internal abstract open enum open annotation override open abstract private protected public internal open : t ) } class F(val foo : bar, abstract : t, open : t, enum : t, open : t, annotation : t, override : t, open : t, abstract : t, private : t, protected : t, public : t, internal : t, lazy : t, wraps : t, import : t, where : t, by : t, get : t, set : t, public : t, private : t, protected : t, internal : t, field : t, property : t, receiver : t, param : t, setparam : t, lateinit : t, const : t, public protected private internal abstract open enum open annotation override open abstract private protected public internal open : b ) { } //SoftKeywordsInTypeArguments.kt class Foo<out abstract, out out> {} fun f() { // Foo<out out> Foo<out Int> } //TraitConstructor.kt interface TestTrait(val a: Int, var b: String, c: Double) interface TestTrait() //TypeAlias.kt typealias foo = bar typealias foo<T> = bar typealias foo<T : foo> = bar typealias foo<A, B> = bar typealias foo<A, B : A> = bar typealias foo = bar ; typealias foo<T> = bar ; typealias foo<T : foo> = bar ; typealias foo<A, B> = bar ; typealias foo<A, B : A> = bar ; //TypeConstraints.kt class foo<T> where T : T { } //TypeModifiers.kt val p1: suspend a val p2: suspend (a) -> a val p3: suspend (a) -> suspend a val p4: suspend a.() -> a val p4a: @a a.() -> a val p5: (suspend a).() -> a val p5a: (@a a).() -> a val p6: a<in suspend a> val p7: a<out suspend @a a> val p8: a<out @a suspend @a a> val p9: a<out @[a] suspend @[a] a> val p10: suspend a<a> val p11: suspend @a a val p12: @a suspend a val p13: @a suspend @a a val p14: @[a] suspend @[a] a val p15: suspend (suspend (() -> Unit)) -> Unit @a fun @a a.f1() {} fun (@a a.(a) -> a).f2() {}
mit
4800df2cb988e3fd576b3cdeedc50513
13.804632
95
0.461973
3.211009
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutRow.kt
1
13447
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout.migLayout import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.ui.laf.VisualPaddingsProvider import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.ui.SeparatorComponent import com.intellij.ui.TitledSeparator import com.intellij.ui.components.Label import com.intellij.ui.layout.* import com.intellij.util.SmartList import net.miginfocom.layout.CC import java.awt.Component import javax.swing.* import javax.swing.border.LineBorder import kotlin.reflect.KProperty0 private const val COMPONENT_ENABLED_STATE_KEY = "MigLayoutRow.enabled" internal class MigLayoutRow(private val parent: MigLayoutRow?, private val componentConstraints: MutableMap<Component, CC>, override val builder: MigLayoutBuilder, val labeled: Boolean = false, val noGrid: Boolean = false, private val buttonGroup: ButtonGroup? = null, private val indent: Int /* level number (nested rows) */) : Row() { companion object { // as static method to ensure that members of current row are not used private fun createCommentRow(parent: MigLayoutRow, comment: String, component: JComponent, isParentRowLabeled: Boolean) { val cc = CC() parent.createChildRow().addComponent(ComponentPanelBuilder.createCommentComponent(comment, true), lazyOf(cc)) cc.horizontal.gapBefore = gapToBoundSize(getCommentLeftInset(parent.spacing, component), true) if (isParentRowLabeled) { cc.skip() } } // as static method to ensure that members of current row are not used private fun configureSeparatorRow(row: MigLayoutRow, title: String?) { val separatorComponent = if (title == null) SeparatorComponent(0, OnePixelDivider.BACKGROUND, null) else TitledSeparator(title) val cc = CC() val spacing = row.spacing cc.vertical.gapBefore = gapToBoundSize(spacing.largeVerticalGap, false) if (title == null) { cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false) } else { cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap, false) // TitledSeparator doesn't grow by default opposite to SeparatorComponent cc.growX() } row.addComponent(separatorComponent, lazyOf(cc)) } } val components: MutableList<JComponent> = SmartList() var rightIndex = Int.MAX_VALUE private var lastComponentConstraintsWithSplit: CC? = null private var columnIndex = -1 internal var subRows: MutableList<MigLayoutRow>? = null private set var gapAfter: String? = null private set private var componentIndexWhenCellModeWasEnabled = -1 private val spacing: SpacingConfiguration get() = builder.spacing override var enabled = true set(value) { if (field == value) { return } field = value for (c in components) { if (!value) { if (!c.isEnabled) { // current state of component differs from current row state - preserve current state to apply it when row state will be changed c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, false) } } else { if (c.getClientProperty(COMPONENT_ENABLED_STATE_KEY) == false) { // remove because for active row component state can be changed and we don't want to add listener to update value accordingly c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, null) // do not set to true, preserve old component state continue } } c.isEnabled = value } } override var visible = true set(value) { if (field == value) { return } field = value for (c in components) { c.isVisible = value } } override var subRowsEnabled = true set(value) { if (field == value) { return } field = value subRows?.forEach { it.enabled = value } } override var subRowsVisible = true set(value) { if (field == value) { return } field = value subRows?.forEach { it.visible = value } } internal val isLabeledIncludingSubRows: Boolean get() = labeled || (subRows?.any { it.isLabeledIncludingSubRows } ?: false) internal val columnIndexIncludingSubRows: Int get() = Math.max(columnIndex, subRows?.maxBy { it.columnIndex }?.columnIndex ?: 0) fun createChildRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, isSeparated: Boolean = false, noGrid: Boolean = false, title: String? = null): MigLayoutRow { val subRows = getOrCreateSubRowsList() val row = MigLayoutRow(this, componentConstraints, builder, labeled = label != null, noGrid = noGrid, indent = indent + computeChildRowIndent(), buttonGroup = buttonGroup) if (isSeparated) { val separatorRow = MigLayoutRow(this, componentConstraints, builder, indent = indent, noGrid = true) configureSeparatorRow(separatorRow, title) separatorRow.enabled = subRowsEnabled separatorRow.visible = subRowsVisible row.getOrCreateSubRowsList().add(separatorRow) } subRows.add(row) row.enabled = subRowsEnabled row.visible = subRowsVisible if (label != null) { row.addComponent(label) } return row } private fun getOrCreateSubRowsList(): MutableList<MigLayoutRow> { var subRows = subRows if (subRows == null) { // subRows in most cases > 1 subRows = ArrayList() this.subRows = subRows } return subRows } // cell mode not tested with "gear" button, wait first user request override fun setCellMode(value: Boolean, isVerticalFlow: Boolean) { if (value) { assert(componentIndexWhenCellModeWasEnabled == -1) componentIndexWhenCellModeWasEnabled = components.size } else { val firstComponentIndex = componentIndexWhenCellModeWasEnabled componentIndexWhenCellModeWasEnabled = -1 // do not add split if cell empty or contains the only component if ((components.size - firstComponentIndex) > 1) { val component = components.get(firstComponentIndex) val cc = componentConstraints.getOrPut(component) { CC() } cc.split(components.size - firstComponentIndex) if (isVerticalFlow) { cc.flowY() // because when vertical buttons placed near scroll pane, it wil be centered by baseline (and baseline not applicable for grow elements, so, will be centered) cc.alignY("top") } } } } private fun computeChildRowIndent(): Int { val firstComponent = components.firstOrNull() ?: return 0 if (firstComponent is JRadioButton || firstComponent is JCheckBox) { return getCommentLeftInset(spacing, firstComponent) } else { return spacing.horizontalGap * 3 } } override operator fun <T : JComponent> T.invoke(vararg constraints: CCFlags, gapLeft: Int, growPolicy: GrowPolicy?, comment: String?): CellBuilder<T> { addComponent(this, constraints.create()?.let { lazyOf(it) } ?: lazy { CC() }, gapLeft, growPolicy, comment) return CellBuilderImpl(builder, this) } // separate method to avoid JComponent as a receiver internal fun addComponent(component: JComponent, cc: Lazy<CC> = lazy { CC() }, gapLeft: Int = 0, growPolicy: GrowPolicy? = null, comment: String? = null) { components.add(component) if (!visible) { component.isVisible = false } if (!enabled) { component.isEnabled = false } if (!shareCellWithPreviousComponentIfNeed(component, cc)) { // increase column index if cell mode not enabled or it is a first component of cell if (componentIndexWhenCellModeWasEnabled == -1 || componentIndexWhenCellModeWasEnabled == (components.size - 1)) { columnIndex++ } } if (labeled && components.size == 2 && component.border is LineBorder) { componentConstraints.get(components.first())?.vertical?.gapBefore = builder.defaultComponentConstraintCreator.vertical1pxGap } if (comment != null && comment.isNotEmpty()) { gapAfter = "${spacing.commentVerticalTopGap}px!" val isParentRowLabeled = labeled // create comment in a new sibling row (developer is still able to create sub rows because rows is not stored in a flat list) createCommentRow(parent!!, comment, component, isParentRowLabeled) } if (buttonGroup != null && component is JToggleButton) { buttonGroup.add(component) } builder.defaultComponentConstraintCreator.createComponentConstraints(cc, component, gapLeft = gapLeft, growPolicy = growPolicy) if (!noGrid && indent > 0 && components.size == 1) { cc.value.horizontal.gapBefore = gapToBoundSize(indent, true) } // if this row is not labeled and: // a. previous row is labeled and first component is a "Remember" checkbox, skip one column (since this row doesn't have a label) // b. some previous row is labeled and first component is a checkbox, span (since this checkbox should span across label and content cells) if (!labeled && components.size == 1 && component is JCheckBox) { val siblings = parent!!.subRows if (siblings != null && siblings.size > 1) { if (siblings.get(siblings.size - 2).labeled && component.text == CommonBundle.message("checkbox.remember.password")) { cc.value.skip(1) } else if (siblings.any { it.labeled }) { cc.value.spanX(2) } } } // MigLayout doesn't check baseline if component has grow if (labeled && component is JScrollPane && component.viewport.view is JTextArea) { val labelCC = componentConstraints.getOrPut(components.get(0)) { CC() } labelCC.alignY("top") val labelTop = component.border?.getBorderInsets(component)?.top ?: 0 if (labelTop != 0) { labelCC.vertical.gapBefore = gapToBoundSize(labelTop, false) } } if (cc.isInitialized()) { componentConstraints.put(component, cc.value) } } private fun shareCellWithPreviousComponentIfNeed(component: JComponent, componentCC: Lazy<CC>): Boolean { if (components.size > 1 && component is JLabel && component.icon === AllIcons.General.GearPlain) { componentCC.value.horizontal.gapBefore = builder.defaultComponentConstraintCreator.horizontalUnitSizeGap if (lastComponentConstraintsWithSplit == null) { val prevComponent = components.get(components.size - 2) var cc = componentConstraints.get(prevComponent) if (cc == null) { cc = CC() componentConstraints.put(prevComponent, cc) } cc.split++ lastComponentConstraintsWithSplit = cc } else { lastComponentConstraintsWithSplit!!.split++ } return true } else { lastComponentConstraintsWithSplit = null return false } } override fun alignRight() { if (rightIndex != Int.MAX_VALUE) { throw IllegalStateException("right allowed only once") } rightIndex = components.size } override fun createRow(label: String?): Row { return createChildRow(label = label?.let { Label(it) }) } } class CellBuilderImpl<T : JComponent> internal constructor( private val builder: MigLayoutBuilder, override val component: T ) : CellBuilder<T>, CheckboxCellBuilder { override fun focused(): CellBuilder<T> { builder.preferredFocusedComponent = component return this } override fun withValidation(callback: (T) -> ValidationInfo?): CellBuilder<T> { builder.validateCallbacks.add { callback(component) } return this } override fun onApply(callback: () -> Unit): CellBuilder<T> { builder.applyCallbacks.add(callback) return this } override fun enabled(isEnabled: Boolean) { component.isEnabled = isEnabled } override fun enableIfSelected(button: AbstractButton) { component.isEnabled = button.isSelected button.addChangeListener { component.isEnabled = button.isSelected } } override fun actsAsLabel() { builder.updateComponentConstraints(component) { spanX = 1 } } } private fun getCommentLeftInset(spacing: SpacingConfiguration, component: JComponent): Int { if (component is JTextField) { // 1px border, better to indent comment text return 1 } // as soon as ComponentPanelBuilder will also compensate visual paddings (instead of compensating on LaF level), // this logic will be moved into computeCommentInsets val componentBorderVisualLeftPadding = when { spacing.isCompensateVisualPaddings -> { val border = component.border if (border is VisualPaddingsProvider) { border.getVisualPaddings(component)?.left ?: 0 } else { 0 } } else -> 0 } val insets = ComponentPanelBuilder.computeCommentInsets(component, true) return insets.left - componentBorderVisualLeftPadding }
apache-2.0
8ba85cd183bc6fd4afd3ee268084b1c6
34.389474
171
0.672195
4.780306
false
false
false
false
Virtlink/aesi
paplj-lsp/src/main/kotlin/com/virtlink/paplj/lsp/Program.kt
1
1445
package com.virtlink.paplj.lsp import com.google.inject.Guice import com.virtlink.editorservices.lsp.CommandLineArgs import com.virtlink.editorservices.lsp.server.SocketLanguageServerLauncher import com.virtlink.editorservices.lsp.server.StdioLanguageServerLauncher import com.virtlink.logging.LogLevel import com.virtlink.logging.LogWriter import com.virtlink.logging.isLogEnabled import org.eclipse.lsp4j.services.LanguageServer import org.slf4j.LoggerFactory import java.io.PrintWriter /** * The main entry point of the language server. */ fun main(rawArgs: Array<String>) { val injector = Guice.createInjector(PapljLspModule()) val args = CommandLineArgs(rawArgs) val server = injector.getInstance(LanguageServer::class.java) val port = args.port val launcher = if (port != null) { SocketLanguageServerLauncher( port, server) } else { StdioLanguageServerLauncher( server) } val traceWriter = if (args.trace) createTraceWriter() else null launcher.launch(traceWriter) } private fun createTraceWriter(): PrintWriter? { val logger = LoggerFactory.getLogger("JSON") val logLevel = LogLevel.Trace if (!logger.isLogEnabled(logLevel)) { // If the logger isn't enabled to write our messages, // we don't even have to create the logger. return null } return PrintWriter(LogWriter(logger, logLevel)) }
apache-2.0
a939a6650b2f5878707ac1dec57e2969
31.863636
74
0.724567
4.237537
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/navbar/ui/NavBarPopup.kt
2
4971
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.navbar.ui import com.intellij.ide.navbar.ide.UiNavBarItem import com.intellij.ide.navbar.ui.PopupEvent.* import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.CollectionListModel import com.intellij.ui.LightweightHint import com.intellij.ui.ListActions import com.intellij.ui.ScrollingUtil import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import com.intellij.ui.popup.HintUpdateSupply import com.intellij.ui.speedSearch.ListWithFilter import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import kotlinx.coroutines.CancellableContinuation import org.jetbrains.annotations.NonNls import java.awt.event.* import javax.swing.* import kotlin.coroutines.resume internal sealed class PopupEvent { object PopupEventLeft : PopupEvent() object PopupEventRight : PopupEvent() object PopupEventCancel : PopupEvent() class PopupEventSelect(val item: UiNavBarItem) : PopupEvent() } private fun registerListActions(list: JList<UiNavBarItem>, popup: LightweightHint, continuation: CancellableContinuation<PopupEvent>) { list.actionMap.put(ListActions.Left.ID, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { continuation.resume(PopupEventLeft) popup.hide(true) } }) list.actionMap.put(ListActions.Right.ID, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { continuation.resume(PopupEventRight) popup.hide(true) } }) list.registerKeyboardAction(object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { continuation.resume(PopupEventSelect(list.selectedValue)) popup.hide(true) } }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED) list.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { continuation.resume(PopupEventSelect(list.selectedValue)) popup.hide(true) } }) } internal class NavigationBarPopup( items: List<UiNavBarItem>, selectedChild: UiNavBarItem?, private val continuation: CancellableContinuation<PopupEvent> ) : LightweightHint(createPopupContents(items, selectedChild)) { init { setFocusRequestor(component) setForceShowAsPopup(true) registerListActions((component as ListWithFilter<UiNavBarItem>).list, this, continuation) } override fun onPopupCancel() { if (continuation.isActive) { continuation.resume(PopupEventCancel) } } companion object { private fun createPopupContents(items: List<UiNavBarItem>, selectedChild: UiNavBarItem?): JComponent { val list = JBList<UiNavBarItem>() list.model = CollectionListModel(items) list.border = JBUI.Borders.empty(5) HintUpdateSupply.installSimpleHintUpdateSupply(list) list.installCellRenderer { item -> NavigationBarPopupItemComponent(item.presentation) } if (selectedChild != null) { list.setSelectedValue(selectedChild, /* shouldScroll = */ true) } else { list.selectedIndex = 0 } return ListWithFilter.wrap(list, NavBarListWrapper(list)) { item -> item.presentation.popupText ?: item.presentation.text } } } } private class NavBarListWrapper<T>(private val myList: JList<T>) : JBScrollPane(myList), DataProvider { init { myList.addMouseMotionListener(object : MouseMotionAdapter() { var myIsEngaged = false override fun mouseMoved(e: MouseEvent) { if (myIsEngaged && !UIUtil.isSelectionButtonDown(e)) { val point = e.point val index = myList.locationToIndex(point) myList.setSelectedIndex(index) } else { myIsEngaged = true } } }) ScrollingUtil.installActions(myList) val modelSize = myList.model.size border = BorderFactory.createEmptyBorder() if (modelSize in 1..MAX_SIZE) { myList.visibleRowCount = 0 getViewport().preferredSize = myList.preferredSize } else { myList.setVisibleRowCount(MAX_SIZE) } } override fun getData(@NonNls dataId: String): Any? = when { PlatformCoreDataKeys.SELECTED_ITEM.`is`(dataId) -> myList.selectedValue PlatformCoreDataKeys.SELECTED_ITEMS.`is`(dataId) -> myList.selectedValues else -> null } override fun requestFocus() { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown { IdeFocusManager.getGlobalInstance().requestFocus(myList, true) } } @Synchronized override fun addMouseListener(l: MouseListener) { myList.addMouseListener(l) } companion object { private const val MAX_SIZE = 20 } }
apache-2.0
6117a7e19dd16011875691c9f1ae0bca
30.462025
120
0.721988
4.387467
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/GitNewProjectWizardStep.kt
6
2223
// 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.ide.wizard import com.intellij.ide.IdeBundle import com.intellij.ide.projectWizard.NewProjectWizardCollector import com.intellij.openapi.GitRepositoryInitializer import com.intellij.openapi.observable.util.bindBooleanStorage import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.UIBundle import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.EMPTY_LABEL import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bindSelected import java.nio.file.Path class GitNewProjectWizardStep( parent: NewProjectWizardBaseStep ) : AbstractNewProjectWizardStep(parent), NewProjectWizardBaseData by parent, GitNewProjectWizardData { private val gitRepositoryInitializer = GitRepositoryInitializer.getInstance() private val gitProperty = propertyGraph.property(false) .bindBooleanStorage("NewProjectWizard.gitState") override val git get() = gitRepositoryInitializer != null && gitProperty.get() override fun setupUI(builder: Panel) { if (gitRepositoryInitializer != null) { with(builder) { row(EMPTY_LABEL) { checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox")) .bindSelected(gitProperty) }.bottomGap(BottomGap.SMALL) } } } override fun setupProject(project: Project) { if (git) { val projectBaseDirectory = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(path, name)) if (projectBaseDirectory != null) { runBackgroundableTask(IdeBundle.message("progress.title.creating.git.repository"), project) { gitRepositoryInitializer!!.initRepository(project, projectBaseDirectory, true) } } } NewProjectWizardCollector.logGitFinished(context, git) } init { data.putUserData(GitNewProjectWizardData.KEY, this) gitProperty.afterChange { NewProjectWizardCollector.logGitChanged(context) } } }
apache-2.0
50a641c4e0495fcbb0d9e38d4eb74675
36.066667
158
0.764732
4.602484
false
false
false
false
google/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflowHandler.kt
1
16910
// 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.vcs.commit import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.notification.SingletonNotificationManager import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.EDT import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.DumbService.DumbModeListener import com.intellij.openapi.project.DumbService.isDumb import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil.* import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.CommitExecutorWithRichDescription import com.intellij.openapi.vcs.changes.actions.DefaultCommitExecutorAction import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES import com.intellij.openapi.vcs.checkin.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.containers.nullize import com.intellij.vcs.commit.AbstractCommitWorkflow.Companion.getCommitExecutors import kotlinx.coroutines.* import org.jetbrains.annotations.Nls import java.lang.Runnable import kotlin.properties.Delegates.observable private val LOG = logger<NonModalCommitWorkflowHandler<*, *>>() abstract class NonModalCommitWorkflowHandler<W : NonModalCommitWorkflow, U : NonModalCommitWorkflowUi> : AbstractCommitWorkflowHandler<W, U>() { abstract override val amendCommitHandler: NonModalAmendCommitHandler private var areCommitOptionsCreated = false private val coroutineScope = CoroutineScope(CoroutineName("commit workflow") + Dispatchers.EDT + SupervisorJob()) private var isCommitChecksResultUpToDate: RecentCommitChecks by observable(RecentCommitChecks.UNKNOWN) { _, oldValue, newValue -> if (oldValue == newValue) return@observable updateDefaultCommitActionName() } private val checkinErrorNotifications = SingletonNotificationManager(VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.displayId, NotificationType.ERROR) protected fun setupCommitHandlersTracking() { CheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this) VcsCheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this) } private fun commitHandlersChanged() { if (workflow.isExecuting) return commitOptions.saveState() disposeCommitOptions() initCommitHandlers() } override fun vcsesChanged() { initCommitHandlers() workflow.initCommitExecutors(getCommitExecutors(project, workflow.vcses) + RunCommitChecksExecutor) updateDefaultCommitActionEnabled() updateDefaultCommitActionName() ui.setPrimaryCommitActions(createPrimaryCommitActions()) ui.setCustomCommitActions(createCommitExecutorActions()) } protected fun setupDumbModeTracking() { if (isDumb(project)) ui.commitProgressUi.isDumbMode = true project.messageBus.connect(this).subscribe(DumbService.DUMB_MODE, object : DumbModeListener { override fun enteredDumbMode() { ui.commitProgressUi.isDumbMode = true } override fun exitDumbMode() { ui.commitProgressUi.isDumbMode = false } }) } override fun executionStarted() = updateDefaultCommitActionEnabled() override fun executionEnded() = updateDefaultCommitActionEnabled() override fun updateDefaultCommitActionName() { val isAmend = amendCommitHandler.isAmendCommitMode val isSkipCommitChecks = isCommitChecksResultUpToDate == RecentCommitChecks.FAILED ui.defaultCommitActionName = getCommitActionName(isAmend, isSkipCommitChecks) } private fun getCommitActionName(isAmend: Boolean, isSkipCommitChecks: Boolean): @Nls String { val commitText = getCommitActionName() return when { isAmend && isSkipCommitChecks -> message("action.amend.commit.anyway.text") isAmend && !isSkipCommitChecks -> message("amend.action.name", commitText) !isAmend && isSkipCommitChecks -> message("action.commit.anyway.text", commitText) else -> commitText } } private fun getActionTextWithoutEllipsis(executor: CommitExecutor?, isAmend: Boolean, isSkipCommitChecks: Boolean): @Nls String { if (executor == null) { val actionText = getCommitActionName(isAmend, isSkipCommitChecks) return removeEllipsisSuffix(actionText) } if (executor is CommitExecutorWithRichDescription) { val state = CommitWorkflowHandlerState(isAmend, isSkipCommitChecks) val actionText = executor.getText(state) if (actionText != null) { return removeEllipsisSuffix(actionText) } } // We ignore 'isAmend == true' for now - unclear how to handle without CommitExecutorWithRichDescription. // Ex: executor might not support this flag. val actionText = executor.actionText if (isSkipCommitChecks) { return message("commit.checks.failed.notification.commit.anyway.action", removeEllipsisSuffix(actionText)) } else { return removeEllipsisSuffix(actionText) } } private fun getCommitActionTextForNotification( executor: CommitExecutor?, isSkipCommitChecks: Boolean ): @Nls(capitalization = Nls.Capitalization.Sentence) String { val isAmend = amendCommitHandler.isAmendCommitMode val actionText: @Nls String = getActionTextWithoutEllipsis(executor, isAmend, isSkipCommitChecks) return capitalize(toLowerCase(actionText)) } fun updateDefaultCommitActionEnabled() { ui.isDefaultCommitActionEnabled = isReady() } protected open fun isReady() = workflow.vcses.isNotEmpty() && !workflow.isExecuting && !amendCommitHandler.isLoading override fun isExecutorEnabled(executor: CommitExecutor): Boolean = super.isExecutorEnabled(executor) && isReady() private fun createPrimaryCommitActions(): List<AnAction> { val group = ActionManager.getInstance().getAction(VcsActions.PRIMARY_COMMIT_EXECUTORS_GROUP) as ActionGroup return group.getChildren(null).toList() } private fun createCommitExecutorActions(): List<AnAction> { val group = ActionManager.getInstance().getAction(VcsActions.COMMIT_EXECUTORS_GROUP) as ActionGroup val executors = workflow.commitExecutors.filter { it.useDefaultAction() } return group.getChildren(null).toList() + executors.map { DefaultCommitExecutorAction(it) } } override fun checkCommit(sessionInfo: CommitSessionInfo): Boolean { val superCheckResult = super.checkCommit(sessionInfo) val executorWithoutChangesAllowed = sessionInfo.executor?.areChangesRequired() == false ui.commitProgressUi.isEmptyChanges = !amendCommitHandler.isAmendWithoutChangesAllowed() && !executorWithoutChangesAllowed && isCommitEmpty() ui.commitProgressUi.isEmptyMessage = getCommitMessage().isBlank() return superCheckResult && !ui.commitProgressUi.isEmptyChanges && !ui.commitProgressUi.isEmptyMessage } /** * Subscribe to VFS and documents changes to reset commit checks results */ protected fun setupCommitChecksResultTracking() { fun areFilesAffectsCommitChecksResult(files: Collection<VirtualFile>): Boolean { val vcsManager = ProjectLevelVcsManager.getInstance(project) val filesFromVcs = files.filter { vcsManager.getVcsFor(it) != null }.nullize() ?: return false val changeListManager = ChangeListManager.getInstance(project) val fileIndex = ProjectRootManagerEx.getInstanceEx(project).fileIndex return filesFromVcs.any { fileIndex.isInContent(it) && changeListManager.getStatus(it) != FileStatus.IGNORED } } // reset commit checks on VFS updates project.messageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: MutableList<out VFileEvent>) { if (isCommitChecksResultUpToDate == RecentCommitChecks.UNKNOWN) { return } val updatedFiles = events.mapNotNull { it.file } if (areFilesAffectsCommitChecksResult(updatedFiles)) { resetCommitChecksResult() } } }) // reset commit checks on documents modification (e.g. user typed in the editor) EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { if (isCommitChecksResultUpToDate == RecentCommitChecks.UNKNOWN) { return } val file = FileDocumentManager.getInstance().getFile(event.document) if (file != null && areFilesAffectsCommitChecksResult(listOf(file))) { resetCommitChecksResult() } } }, this) } protected fun resetCommitChecksResult() { isCommitChecksResultUpToDate = RecentCommitChecks.UNKNOWN hideCommitChecksFailureNotification() } override fun beforeCommitChecksStarted(sessionInfo: CommitSessionInfo) { super.beforeCommitChecksStarted(sessionInfo) hideCommitChecksFailureNotification() } override fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) { hideCommitChecksFailureNotification() super.beforeCommitChecksEnded(sessionInfo, result) if (result.shouldCommit) { ui.commitProgressUi.clearCommitCheckFailures() } if (result is CommitChecksResult.Failed || result is CommitChecksResult.ExecutionError) { val executor = sessionInfo.executor val commitActionText = getCommitActionTextForNotification(executor, false) val commitAnywayActionText = getCommitActionTextForNotification(executor, true) val title = message("commit.checks.failed.notification.title", commitActionText) val description = getCommitCheckFailureDescription() checkinErrorNotifications.notify(title, description, project) { it.setDisplayId(VcsNotificationIdsHolder.COMMIT_CHECKS_FAILED) it.addAction( NotificationAction.createExpiring(commitAnywayActionText) { _, _ -> if (!workflow.isExecuting) { executorCalled(executor) } }) it.addAction(createShowDetailsNotificationAction()) } } if (result is CommitChecksResult.OnlyChecks && !result.checksPassed) { val commitActionText = getCommitActionTextForNotification(null, false) val title = message("commit.checks.failed.notification.title", commitActionText) val description = getCommitCheckFailureDescription() checkinErrorNotifications.notify(title, description, project) { it.setDisplayId(VcsNotificationIdsHolder.COMMIT_CHECKS_ONLY_FAILED) it.addAction(createShowDetailsNotificationAction()) } } } private fun getCommitCheckFailureDescription(): @NlsContexts.NotificationContent String { return ui.commitProgressUi.getCommitCheckFailures().mapNotNull { it.text }.joinToString() } private fun createShowDetailsNotificationAction(): NotificationAction { return NotificationAction.create(message("commit.checks.failed.notification.show.details.action")) { _, _ -> val detailsViewer = ui.commitProgressUi.getCommitCheckFailures().mapNotNull { it.detailsViewer }.singleOrNull() if (detailsViewer != null) { detailsViewer() } else { val toolWindow = ChangesViewContentManager.getToolWindowFor(project, LOCAL_CHANGES) toolWindow?.activate { ChangesViewContentManager.getInstance(project).selectContent(LOCAL_CHANGES) } } } } override fun doExecuteSession(sessionInfo: CommitSessionInfo): Boolean { val isAmend = amendCommitHandler.isAmendCommitMode val actionName = getActionTextWithoutEllipsis(sessionInfo.executor, isAmend, false) val commitInfo = CommitInfoImpl(actionName) if (!sessionInfo.isVcsCommit) { return workflow.executeSession(sessionInfo, commitInfo) } workflow.asyncSession(coroutineScope, sessionInfo) { val isOnlyRunCommitChecks = commitContext.isOnlyRunCommitChecks commitContext.isOnlyRunCommitChecks = false val isSkipCommitChecks = isCommitChecksResultUpToDate == RecentCommitChecks.FAILED if (isSkipCommitChecks && !isOnlyRunCommitChecks) { return@asyncSession CommitChecksResult.Passed } ui.commitProgressUi.runWithProgress(isOnlyRunCommitChecks) { val problem = workflow.runBackgroundBeforeCommitChecks(sessionInfo) handleCommitProblem(problem, isOnlyRunCommitChecks, commitInfo) } } return true } private fun handleCommitProblem(problem: CommitProblem?, isOnlyRunCommitChecks: Boolean, commitInfo: CommitInfo): CommitChecksResult { if (problem != null) { val checkFailure = when (problem) { is UnknownCommitProblem -> CommitCheckFailure(null, null) is CommitProblemWithDetails -> CommitCheckFailure(problem.text) { problem.showDetails(project, commitInfo) } else -> CommitCheckFailure(problem.text, null) } ui.commitProgressUi.addCommitCheckFailure(checkFailure) } val checksPassed = problem == null when { isOnlyRunCommitChecks -> { if (checksPassed) { isCommitChecksResultUpToDate = RecentCommitChecks.PASSED } else { isCommitChecksResultUpToDate = RecentCommitChecks.FAILED } return CommitChecksResult.OnlyChecks(checksPassed) } checksPassed -> { isCommitChecksResultUpToDate = RecentCommitChecks.UNKNOWN // We are going to commit, remembering the result is not needed. return CommitChecksResult.Passed } else -> { isCommitChecksResultUpToDate = RecentCommitChecks.FAILED return CommitChecksResult.Failed() } } } override fun dispose() { hideCommitChecksFailureNotification() coroutineScope.cancel() super.dispose() } fun hideCommitChecksFailureNotification() { checkinErrorNotifications.clear() } fun showCommitOptions(isFromToolbar: Boolean, dataContext: DataContext) = ui.showCommitOptions(ensureCommitOptions(), getCommitActionName(), isFromToolbar, dataContext) override fun saveCommitOptionsOnCommit(): Boolean { ensureCommitOptions() // restore state in case settings were changed via configurable commitOptions.allOptions .filter { it is UnnamedConfigurable } .forEach { it.restoreState() } return super.saveCommitOptionsOnCommit() } protected fun ensureCommitOptions(): CommitOptions { if (!areCommitOptionsCreated) { areCommitOptionsCreated = true workflow.initCommitOptions(createCommitOptions()) commitOptions.restoreState() commitOptionsCreated() } return commitOptions } protected open fun commitOptionsCreated() = Unit protected fun disposeCommitOptions() { workflow.disposeCommitOptions() areCommitOptionsCreated = false } override fun getState(): CommitWorkflowHandlerState { val isAmend = amendCommitHandler.isAmendCommitMode val isSkipCommitChecks = isCommitChecksResultUpToDate == RecentCommitChecks.FAILED return CommitWorkflowHandlerState(isAmend, isSkipCommitChecks) } protected open inner class CommitStateCleaner : CommitterResultHandler { override fun onSuccess() = resetState() override fun onCancel() = Unit override fun onFailure() = resetState() protected open fun resetState() { disposeCommitOptions() workflow.clearCommitContext() initCommitHandlers() resetCommitChecksResult() updateDefaultCommitActionName() } } } private enum class RecentCommitChecks { UNKNOWN, PASSED, FAILED }
apache-2.0
94288db07158138e32cd6c987cba7e03
39.357995
158
0.746541
5.164936
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/NanoClock.kt
1
1197
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Type import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Clock::class) class NanoClock : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Clock>() } .and { it.instanceFields.size == 1 } class lastTimeNano : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { true } } @MethodParameters() class mark : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == Type.VOID_TYPE } } @MethodParameters("cycleMs", "minSleepMs") class wait : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == Type.INT_TYPE } } }
mit
f7b763d74ac5c93d120b6bdad29f4d86
37.645161
89
0.748538
4.141869
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/SlideshowDialog.kt
1
5482
package com.simplemobiletools.gallery.pro.dialogs import android.view.View import androidx.appcompat.app.AlertDialog import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.RadioGroupDialog import com.simplemobiletools.commons.extensions.getAlertDialogBuilder import com.simplemobiletools.commons.extensions.hideKeyboard import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.extensions.value import com.simplemobiletools.commons.models.RadioItem import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_FADE import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_NONE import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_SLIDE import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_DEFAULT_INTERVAL import kotlinx.android.synthetic.main.dialog_slideshow.view.* class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit) { private val view: View init { view = activity.layoutInflater.inflate(R.layout.dialog_slideshow, null).apply { interval_hint.hint = activity.getString(R.string.seconds_raw).replaceFirstChar { it.uppercaseChar() } interval_value.setOnClickListener { interval_value.selectAll() } interval_value.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) activity.hideKeyboard(v) } animation_holder.setOnClickListener { val items = arrayListOf( RadioItem(SLIDESHOW_ANIMATION_NONE, activity.getString(R.string.no_animation)), RadioItem(SLIDESHOW_ANIMATION_SLIDE, activity.getString(R.string.slide)), RadioItem(SLIDESHOW_ANIMATION_FADE, activity.getString(R.string.fade)) ) RadioGroupDialog(activity, items, activity.config.slideshowAnimation) { activity.config.slideshowAnimation = it as Int animation_value.text = getAnimationText() } } include_videos_holder.setOnClickListener { interval_value.clearFocus() include_videos.toggle() } include_gifs_holder.setOnClickListener { interval_value.clearFocus() include_gifs.toggle() } random_order_holder.setOnClickListener { interval_value.clearFocus() random_order.toggle() } move_backwards_holder.setOnClickListener { interval_value.clearFocus() move_backwards.toggle() } loop_slideshow_holder.setOnClickListener { interval_value.clearFocus() loop_slideshow.toggle() } } setupValues() activity.getAlertDialogBuilder() .setPositiveButton(R.string.ok, null) .setNegativeButton(R.string.cancel, null) .apply { activity.setupDialogStuff(view, this) { alertDialog -> alertDialog.hideKeyboard() alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { storeValues() callback() alertDialog.dismiss() } } } } private fun setupValues() { val config = activity.config view.apply { interval_value.setText(config.slideshowInterval.toString()) animation_value.text = getAnimationText() include_videos.isChecked = config.slideshowIncludeVideos include_gifs.isChecked = config.slideshowIncludeGIFs random_order.isChecked = config.slideshowRandomOrder move_backwards.isChecked = config.slideshowMoveBackwards loop_slideshow.isChecked = config.loopSlideshow } } private fun storeValues() { var interval = view.interval_value.text.toString() if (interval.trim('0').isEmpty()) interval = SLIDESHOW_DEFAULT_INTERVAL.toString() activity.config.apply { slideshowAnimation = getAnimationValue(view.animation_value.value) slideshowInterval = interval.toInt() slideshowIncludeVideos = view.include_videos.isChecked slideshowIncludeGIFs = view.include_gifs.isChecked slideshowRandomOrder = view.random_order.isChecked slideshowMoveBackwards = view.move_backwards.isChecked loopSlideshow = view.loop_slideshow.isChecked } } private fun getAnimationText(): String { return when (activity.config.slideshowAnimation) { SLIDESHOW_ANIMATION_SLIDE -> activity.getString(R.string.slide) SLIDESHOW_ANIMATION_FADE -> activity.getString(R.string.fade) else -> activity.getString(R.string.no_animation) } } private fun getAnimationValue(text: String): Int { return when (text) { activity.getString(R.string.slide) -> SLIDESHOW_ANIMATION_SLIDE activity.getString(R.string.fade) -> SLIDESHOW_ANIMATION_FADE else -> SLIDESHOW_ANIMATION_NONE } } }
gpl-3.0
9cee20b966f4ce32170488e9630fc87d
39.910448
113
0.640825
5.230916
false
true
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/OptionsTopHitProvider.kt
1
8458
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui import com.intellij.diagnostic.runActivity import com.intellij.ide.IdeBundle import com.intellij.ide.SearchTopHitProvider import com.intellij.ide.ui.OptionsSearchTopHitProvider.ApplicationLevelProvider import com.intellij.ide.ui.OptionsSearchTopHitProvider.ProjectLevelProvider import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.codeStyle.WordPrefixMatcher import com.intellij.util.text.Matcher import kotlinx.coroutines.Job import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import org.jetbrains.annotations.Nls import org.jetbrains.annotations.PropertyKey import org.jetbrains.annotations.VisibleForTesting import java.util.concurrent.CancellationException import java.util.function.Consumer import kotlin.coroutines.coroutineContext abstract class OptionsTopHitProvider : OptionsSearchTopHitProvider, SearchTopHitProvider { companion object { // project level here means not that EP itself in project area, but that extensions applicable for project only val PROJECT_LEVEL_EP = ExtensionPointName<ProjectLevelProvider>("com.intellij.search.projectOptionsTopHitProvider") @JvmStatic fun consumeTopHits(provider: OptionsSearchTopHitProvider, rawPattern: String, collector: Consumer<Any>, project: Project?) { val pattern = checkPattern(rawPattern) ?: return val parts = pattern.split(' ') if (!parts.isEmpty()) { doConsumeTopHits(provider, pattern, parts[0], collector, project) } } @VisibleForTesting @JvmStatic fun buildMatcher(pattern: String?): Matcher = WordPrefixMatcher(pattern) @JvmStatic fun messageApp(property: @PropertyKey(resourceBundle = ApplicationBundle.BUNDLE) String): @Nls String { return StringUtil.stripHtml(ApplicationBundle.message(property), false) } @JvmStatic fun messageIde(property: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String): @Nls String { return StringUtil.stripHtml(IdeBundle.message(property), false) } } override fun consumeTopHits(pattern: String, collector: Consumer<Any>, project: Project?) { consumeTopHits(provider = this, rawPattern = pattern, collector = collector, project = project) } abstract override fun getId(): String /* * Marker interface for option provider containing only descriptors which are backed by toggle actions. * E.g. UiSettings.SHOW_STATUS_BAR is backed by View > Status Bar action. */ @Deprecated("") // for search everywhere only interface CoveredByToggleActions // ours ProjectLevelProvider registered in ours projectOptionsTopHitProvider extension point, // not in common topHitProvider, so, this adapter is required to expose ours project level providers. internal class ProjectLevelProvidersAdapter : SearchTopHitProvider { override fun consumeTopHits(pattern: String, collector: Consumer<Any>, project: Project?) { if (project == null) { return } val checkedPattern = checkPattern(pattern) ?: return val parts = checkedPattern.split(' ') if (parts.isEmpty()) { return } for (provider in PROJECT_LEVEL_EP.extensionList) { doConsumeTopHits(provider, checkedPattern, parts[0], collector, project) } } fun consumeAllTopHits(pattern: String, collector: Consumer<Any>, project: Project?) { val matcher = buildMatcher(pattern) for (provider in PROJECT_LEVEL_EP.extensionList) { consumeTopHitsForApplicableProvider(provider, matcher, collector, project) } } } internal class Activity : ProjectPostStartupActivity { private val appJob: Job init { val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { throw ExtensionNotApplicableException.create() } @Suppress("DEPRECATION") appJob = app.coroutineScope.launch { // for application runActivity("cache options in application") { val topHitCache = TopHitCache.getInstance() for (extension in SearchTopHitProvider.EP_NAME.filterableLazySequence()) { val aClass = extension.implementationClass ?: continue if (ApplicationLevelProvider::class.java.isAssignableFrom(aClass)) { kotlin.coroutines.coroutineContext.ensureActive() val provider = extension.instance as ApplicationLevelProvider? ?: continue if (provider.preloadNeeded()) { kotlin.coroutines.coroutineContext.ensureActive() topHitCache.getCachedOptions(provider = provider, project = null, pluginDescriptor = extension.pluginDescriptor) } } } } } } override suspend fun execute(project: Project) { appJob.join() // for given project runActivity("cache options in project") { val topHitCache = TopHitCache.getInstance(project) for (extension in SearchTopHitProvider.EP_NAME.filterableLazySequence()) { val aClass = extension.implementationClass ?: continue if (OptionsSearchTopHitProvider::class.java.isAssignableFrom(aClass) && !ApplicationLevelProvider::class.java.isAssignableFrom(aClass)) { coroutineContext.ensureActive() val provider = extension.instance as OptionsSearchTopHitProvider? ?: continue if (provider.preloadNeeded()) { coroutineContext.ensureActive() topHitCache.getCachedOptions(provider = provider, project = project, pluginDescriptor = extension.pluginDescriptor) } } } coroutineContext.ensureActive() val cache = TopHitCache.getInstance(project) PROJECT_LEVEL_EP.processExtensions { provider, pluginDescriptor -> coroutineContext.ensureActive() try { cache.getCachedOptions(provider, project, pluginDescriptor) } catch (e: CancellationException) { throw e } catch (e: Exception) { if (e is ControlFlowException) { throw e } logger<OptionsTopHitProvider>().error(e) } } } } } } private fun doConsumeTopHits(provider: OptionsSearchTopHitProvider, rawPattern: String, id: String, collector: Consumer<Any>, project: Project?) { var pattern = rawPattern if (provider.id.startsWith(id) || pattern.startsWith(" ")) { pattern = (if (pattern.startsWith(' ')) pattern else pattern.substring(id.length)).trim() consumeTopHitsForApplicableProvider(provider = provider, matcher = OptionsTopHitProvider.buildMatcher(pattern), collector = collector, project = project) } } private fun consumeTopHitsForApplicableProvider(provider: OptionsSearchTopHitProvider, matcher: Matcher, collector: Consumer<Any>, project: Project?) { val cache = if (project == null || provider is ApplicationLevelProvider) { TopHitCache.getInstance() } else { TopHitCache.getInstance(project = project) } for (option in cache.getCachedOptions(provider = provider, project = project, pluginDescriptor = null)) { if (matcher.matches(option.option)) { collector.accept(option) } } } private fun checkPattern(pattern: String): String? { return if (pattern.startsWith(SearchTopHitProvider.getTopHitAccelerator())) pattern.substring(1) else null }
apache-2.0
b8cf7f04b9a850ff5bdaf13310ae76cf
40.063107
129
0.681485
5.082933
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2018/Day01.kt
1
588
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceLines object Day01 : Day { private val numbers = resourceLines(2018, 1).map { it.toInt() } override fun part1() = numbers.sum() override fun part2() : Int { val set = mutableSetOf<Int>() var freq = 0 while(true) { for (i in numbers) { freq += i if (set.contains(freq)) { return freq } set += freq } } } }
mit
0ec99f750e18fcb61a39c26b29beccd1
20.814815
67
0.515306
4.2
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2016/Day18.kt
1
1387
package com.nibado.projects.advent.y2016 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.collect.Maze object Day18 : Day { private val input = "^..^^.^^^..^^.^...^^^^^....^.^..^^^.^.^.^^...^.^.^.^.^^.....^.^^.^.^.^.^.^.^^..^^^^^...^.....^....^." override fun part1() = solve(40) override fun part2() = solve(400000) private fun solve(height: Int): String { val maze = Maze(input.length, height) fun trap(point: Point) = if (!maze.inBound(point)) { false } else { maze.isWall(point) } fun left(point: Point) = trap(Point(point.x - 1, point.y - 1)) fun center(point: Point) = trap(Point(point.x, point.y - 1)) fun right(point: Point) = trap(Point(point.x + 1, point.y - 1)) input.forEachIndexed { i, c -> maze.set(i, 0, c == '^') } (1 until maze.height).forEach { y -> (0 until maze.width).forEach { x -> val it = Point(x, y) if (left(it) && center(it) && !right(it) || right(it) && center(it) && !left(it) || left(it) && !center(it) && !right(it) || right(it) && !center(it) && !left(it)) { maze.set(it.x, it.y, true) } } } return maze.count().toString() } }
mit
41e09a1221d04db49fb325c12ce5758a
34.589744
126
0.486662
3.225581
false
false
false
false
exercism/xkotlin
exercises/practice/scale-generator/.meta/src/reference/kotlin/Scale.kt
1
1060
class Scale(private val tonic: String) { companion object { private val sharps = listOf("A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#") private val flats = listOf("A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab") private val useFlats = listOf("F", "Bb", "Eb", "Ab", "Db", "Gb", "d", "g", "c", "f", "bb", "eb") private val intervalOffsets = mapOf('m' to 1, 'M' to 2, 'A' to 3) } private val orderedChromatic: List<String> init { val notes = if (useFlats.contains(tonic)) flats else sharps val start = notes.indexOfFirst { it.lowercase() == tonic.lowercase() } orderedChromatic = notes.subList(start, notes.size) + notes.subList(0, start) } fun chromatic(): List<String> = orderedChromatic fun interval(intervals: String): List<String> { var idx = 0 return intervals.map { val note = orderedChromatic[idx] idx += intervalOffsets[it] ?: error("Unkown interval $it!") note } } }
mit
c82303f88275fc8054c6104a00b9b459
36.857143
104
0.536792
3.202417
false
false
false
false
WeAthFoLD/Momentum
Runtime/src/test/kotlin/Texture2DTest.kt
1
2772
import momentum.rt.MomentumRuntime import momentum.rt.render.Material import momentum.rt.render.Material.* import momentum.rt.render.Pipeline import momentum.rt.render.ShaderProgram import momentum.rt.render.Texture2D import momentum.rt.resource.ClassPathResourceLoader import momentum.rt.resource.ResourceManager import org.lwjgl.BufferUtils import org.lwjgl.opengl.Display import org.lwjgl.opengl.DisplayMode import java.io.InputStream import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL30.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.* import java.nio.FloatBuffer fun main(args: Array<String>) { Display.setDisplayMode(DisplayMode(800, 600)) Display.create() MomentumRuntime.init() val manager = ResourceManager() manager.registerLoader(ClassPathResourceLoader()) val texture: Texture2D = manager.load("dlight.tex") val program: ShaderProgram = manager.load("dlight.shader") glUseProgram(program.programID) run { val uniformLoc = glGetUniformLocation(program.programID, "tex") glUniform1i(uniformLoc, 0) } class RenderContext() { val vao: Int val vbo: Int val ibo: Int init { vbo = glGenBuffers() ibo = glGenBuffers() vao = glGenVertexArrays() glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo) run { val arr = listOf( 0.5f, 0.5f, 0f, -0.5f, 0.5f, 0f, -0.5f, -0.5f, 0f, 0.5f, -0.5f, 0f ).toFloatArray() val buf = BufferUtils.createFloatBuffer(12) buf.put(arr).flip() glBufferData(GL_ARRAY_BUFFER, buf, GL_STATIC_DRAW) } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) run { val arr = listOf(0, 1, 2, 0, 2, 3).toIntArray() val buf = BufferUtils.createIntBuffer(6) buf.put(arr).flip() glBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW) } glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, false, 4 * 3, 0) glBindVertexArray(0) } } val ctx = RenderContext() glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.5f, 0.3f, 0.3f, 1.0f) while (!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) glBindTexture(GL_TEXTURE_2D, texture.textureID) glBindVertexArray(ctx.vao) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0) glBindVertexArray(0) Display.update() } Display.destroy() }
mit
2d832f6e91c7cb2b2031153cb3c7d39d
26.445545
74
0.613276
3.96
false
false
false
false
allotria/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/preContracts.kt
2
8618
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow.inference import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.NullableNotNullManager import com.intellij.codeInspection.dataFlow.ContractReturnValue import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil import com.intellij.codeInspection.dataFlow.NullabilityUtil import com.intellij.codeInspection.dataFlow.StandardMethodContract import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint.* import com.intellij.codeInspection.dataFlow.inference.ContractInferenceInterpreter.withConstraint import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import com.siyeh.ig.psiutils.SideEffectChecker /** * @author peter */ interface PreContract { fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> fun negate(): PreContract? = NegatingContract( this) } internal data class KnownContract(val contract: StandardMethodContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = listOf(contract) override fun negate() = negateContract(contract)?.let(::KnownContract) } internal data class DelegationContract(internal val expression: ExpressionRange, internal val negated: Boolean) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { val call : PsiMethodCallExpression = expression.restoreExpression(body()) val result = call.resolveMethodGenerics() val targetMethod = result.element as PsiMethod? ?: return emptyList() if (targetMethod == method) return emptyList() val parameters = targetMethod.parameterList.parameters val arguments = call.argumentList.expressions val qualifier = call.methodExpression.qualifierExpression val varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.substitutor, arguments, parameters) val methodContracts = StandardMethodContract.toNonIntersectingStandardContracts(JavaMethodContractUtil.getMethodContracts(targetMethod)) ?: return emptyList() val fromDelegate = methodContracts.mapNotNull { dc -> convertDelegatedMethodContract(method, parameters, qualifier, arguments, varArgCall, dc) }.toMutableList() while (fromDelegate.isNotEmpty() && fromDelegate[fromDelegate.size - 1].returnValue == ContractReturnValue.returnAny()) { fromDelegate.removeAt(fromDelegate.size - 1) } if (NullableNotNullManager.isNotNull(targetMethod)) { fromDelegate += listOf( StandardMethodContract(emptyConstraints(method), ContractReturnValue.returnNotNull())) } return StandardMethodContract.toNonIntersectingStandardContracts(fromDelegate) ?: emptyList() } private fun convertDelegatedMethodContract(callerMethod: PsiMethod, targetParameters: Array<PsiParameter>, qualifier: PsiExpression?, callArguments: Array<PsiExpression>, varArgCall: Boolean, targetContract: StandardMethodContract): StandardMethodContract? { var answer: Array<StandardMethodContract.ValueConstraint>? = emptyConstraints(callerMethod) for (i in 0 until targetContract.parameterCount) { if (i >= callArguments.size) return null val argConstraint = targetContract.getParameterConstraint(i) if (argConstraint != ANY_VALUE) { if (varArgCall && i >= targetParameters.size - 1) { if (argConstraint == NULL_VALUE) { return null } break } val argument = PsiUtil.skipParenthesizedExprDown(callArguments[i]) ?: return null val paramIndex = resolveParameter(callerMethod, argument) if (paramIndex >= 0) { answer = withConstraint(answer, paramIndex, argConstraint) ?: return null } else if (argConstraint != getLiteralConstraint(argument)) { return null } } } var returnValue = targetContract.returnValue returnValue = when (returnValue) { is ContractReturnValue.BooleanReturnValue -> { if (negated) returnValue.negate() else returnValue } is ContractReturnValue.ParameterReturnValue -> { mapReturnValue(callerMethod, callArguments[returnValue.parameterNumber]) } ContractReturnValue.returnThis() -> { mapReturnValue(callerMethod, qualifier) } else -> returnValue } return answer?.let { StandardMethodContract(it, returnValue) } } private fun mapReturnValue(callerMethod: PsiMethod, argument: PsiExpression?): ContractReturnValue? { val stripped = PsiUtil.skipParenthesizedExprDown(argument) val paramIndex = resolveParameter(callerMethod, stripped) return when { paramIndex >= 0 -> ContractReturnValue.returnParameter(paramIndex) stripped is PsiLiteralExpression -> when (stripped.value) { null -> ContractReturnValue.returnNull() true -> ContractReturnValue.returnTrue() false -> ContractReturnValue.returnFalse() else -> ContractReturnValue.returnNotNull() } stripped is PsiThisExpression && stripped.qualifier == null -> ContractReturnValue.returnThis() stripped is PsiNewExpression -> ContractReturnValue.returnNew() NullabilityUtil.getExpressionNullability(stripped) == Nullability.NOT_NULL -> ContractReturnValue.returnNotNull() else -> ContractReturnValue.returnAny() } } private fun emptyConstraints(method: PsiMethod) = StandardMethodContract.createConstraintArray( method.parameterList.parametersCount) private fun returnNotNull(mc: StandardMethodContract): StandardMethodContract { return if (mc.returnValue.isFail) mc else mc.withReturnValue(ContractReturnValue.returnNotNull()) } private fun getLiteralConstraint(argument: PsiExpression) = when (argument) { is PsiLiteralExpression -> ContractInferenceInterpreter.getLiteralConstraint( argument.getFirstChild().node.elementType) is PsiNewExpression, is PsiPolyadicExpression, is PsiFunctionalExpression -> NOT_NULL_VALUE else -> null } private fun resolveParameter(method: PsiMethod, expr: PsiExpression?): Int { val target = if (expr is PsiReferenceExpression && !expr.isQualified) expr.resolve() else null return if (target is PsiParameter && target.parent === method.parameterList) method.parameterList.getParameterIndex(target) else -1 } } internal data class SideEffectFilter(internal val expressionsToCheck: List<ExpressionRange>, internal val contracts: List<PreContract>) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { if (expressionsToCheck.any { d -> mayHaveSideEffects(body(), d) }) { return emptyList() } return contracts.flatMap { c -> c.toContracts(method, body) } } private fun mayHaveSideEffects(body: PsiCodeBlock, range: ExpressionRange) = range.restoreExpression<PsiExpression>(body).let { SideEffectChecker.mayHaveSideEffects(it) } } internal data class NegatingContract(internal val negated: PreContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = negated.toContracts(method, body).mapNotNull(::negateContract) } private fun negateContract(c: StandardMethodContract): StandardMethodContract? { val ret = c.returnValue return if (ret is ContractReturnValue.BooleanReturnValue) c.withReturnValue(ret.negate()) else null } @Suppress("EqualsOrHashCode") internal data class MethodCallContract(internal val call: ExpressionRange, internal val states: List<List<StandardMethodContract.ValueConstraint>>) : PreContract { override fun hashCode() = call.hashCode() * 31 + states.flatten().map { it.ordinal }.hashCode() override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> { val target = call.restoreExpression<PsiMethodCallExpression>(body()).resolveMethod() if (target != null && target != method && NullableNotNullManager.isNotNull(target)) { return ContractInferenceInterpreter.toContracts(states.map { it.toTypedArray() }, ContractReturnValue.returnNotNull()) } return emptyList() } }
apache-2.0
ec6be247768e44e58feb10bd0e7f3ee3
47.965909
163
0.735205
5.468274
false
false
false
false
square/okio
okio/src/appleTest/kotlin/okio/AppleByteStringTest.kt
1
1708
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import platform.Foundation.NSData import platform.Foundation.NSString import platform.Foundation.NSUTF8StringEncoding import platform.Foundation.dataUsingEncoding import kotlin.test.Test import kotlin.test.assertEquals class AppleByteStringTest { @Test fun nsDataToByteString() { val data = ("Hello" as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData @Suppress("DEPRECATION") // Ensure deprecated function continues to work. val byteStringDeprecated = data.toByteString() assertEquals("Hello", byteStringDeprecated.utf8()) val byteString = with(ByteString) { data.toByteString() } assertEquals("Hello", byteString.utf8()) } @Test fun emptyNsDataToByteString() { val data = ("" as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData @Suppress("DEPRECATION") // Ensure deprecated function continues to work. val byteStringDeprecated = data.toByteString() assertEquals(ByteString.EMPTY, byteStringDeprecated) val byteString = with(ByteString) { data.toByteString() } assertEquals(ByteString.EMPTY, byteString) } }
apache-2.0
dcbc769def5d5e98c19250c52a201330
35.340426
86
0.754684
4.357143
false
true
false
false
allotria/intellij-community
spellchecker/src/com/intellij/spellchecker/grazie/dictionary/EditableAggregatedWordList.kt
3
2017
// 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.spellchecker.grazie.dictionary import com.intellij.grazie.speller.lists.MetadataWordList import com.intellij.grazie.speller.lists.TraversableWordList import com.intellij.grazie.speller.lists.WordList import com.intellij.util.containers.BidirectionalMap class EditableAggregatedWordList : WordList { private var words = MetadataWordList.Default<Array<Int>>(emptyMap()) private val namesToIds = BidirectionalMap<String, Int>() val keys: Set<String> get() = namesToIds.keys override fun suggest(word: String, distance: Int): Sequence<String> = words.suggest(word, distance) override fun prefix(prefix: String): Sequence<String> = words.prefix(prefix) override fun contains(word: String): Boolean = words.contains(word) override fun isAlien(word: String): Boolean = words.isAlien(word) fun containsList(name: String): Boolean = name in keys @Synchronized fun addList(name: String, list: TraversableWordList) { //if list already loaded -- reload it if (containsList(name)) removeList(name) val current = words.all.map { it to words.getMetadata(it)!! }.toMap(HashMap()) val id = (namesToIds.values.max() ?: -1) + 1 namesToIds[name] = id for (word in list.all) { current[word] = current[word]?.plus(id) ?: arrayOf(id) } words = MetadataWordList.Default(current) } @Synchronized fun removeList(name: String) { if (!containsList(name)) return val id = namesToIds[name] ?: return val current = words.all.map { it to words.getMetadata(it)!! }.toMap(HashMap()) for ((value, ids) in current) { if (id in ids) { current[value] = ids.filter { it != id }.toTypedArray() } } words = MetadataWordList.Default(current.filterValues { it.isNotEmpty() }) } @Synchronized fun clear() { words = MetadataWordList.Default(emptyMap()) } }
apache-2.0
13a12321acbe2c95a3889b488adcc085
30.046154
140
0.705007
3.841905
false
false
false
false
zdary/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RefreshWorkingCopiesAction.kt
7
878
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.dialogs import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager private fun AnActionEvent.getWorkingCopiesPanel(): CopiesPanel? = project?.let { ChangesViewContentManager.getInstance(it) }?.getActiveComponent(CopiesPanel::class.java) class RefreshWorkingCopiesAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val panel = e.getWorkingCopiesPanel() e.presentation.apply { isVisible = panel != null isEnabled = panel?.isRefreshing == false } } override fun actionPerformed(e: AnActionEvent) = e.getWorkingCopiesPanel()!!.refresh() }
apache-2.0
fd579f2ebf463fde2e238c5d0b1b6263
38.954545
140
0.775626
4.39
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/favicon/FaviconModel.kt
1
5103
package acr.browser.lightning.favicon import acr.browser.lightning.R import acr.browser.lightning.extensions.pad import acr.browser.lightning.extensions.safeUse import acr.browser.lightning.log.Logger import acr.browser.lightning.utils.DrawableUtils import acr.browser.lightning.utils.FileUtils import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.LruCache import androidx.annotation.ColorInt import androidx.annotation.WorkerThread import androidx.core.net.toUri import io.reactivex.Completable import io.reactivex.Maybe import java.io.File import java.io.FileOutputStream import javax.inject.Inject import javax.inject.Singleton /** * Reactive model that can fetch favicons * from URLs and also cache them. */ @Singleton class FaviconModel @Inject constructor( private val application: Application, private val logger: Logger ) { private val loaderOptions = BitmapFactory.Options() private val bookmarkIconSize = application.resources.getDimensionPixelSize(R.dimen.material_grid_small_icon) private val faviconCache = object : LruCache<String, Bitmap>(FileUtils.megabytesToBytes(1).toInt()) { override fun sizeOf(key: String, value: Bitmap) = value.byteCount } /** * Retrieves a favicon from the memory cache.Bitmap may not be present if no bitmap has been * added for the URL or if it has been evicted from the memory cache. * * @param url the URL to retrieve the bitmap for. * @return the bitmap associated with the URL, may be null. */ private fun getFaviconFromMemCache(url: String): Bitmap? { synchronized(faviconCache) { return faviconCache.get(url) } } /** * Create the default favicon for a bookmark with the provided [title]. */ fun createDefaultBitmapForTitle(title: String?): Bitmap { val firstTitleCharacter = title?.takeIf(String::isNotBlank)?.let { it[0] } ?: '?' @ColorInt val defaultFaviconColor = DrawableUtils.characterToColorHash(firstTitleCharacter, application) return DrawableUtils.createRoundedLetterImage( firstTitleCharacter, bookmarkIconSize, bookmarkIconSize, defaultFaviconColor ) } /** * Adds a bitmap to the memory cache for the given URL. * * @param url the URL to map the bitmap to. * @param bitmap the bitmap to store. */ private fun addFaviconToMemCache(url: String, bitmap: Bitmap) { synchronized(faviconCache) { faviconCache.put(url, bitmap) } } /** * Retrieves the favicon for a URL, may be from network or cache. * * @param url The URL that we should retrieve the favicon for. * @param title The title for the web page. */ fun faviconForUrl(url: String, title: String): Maybe<Bitmap> = Maybe.create { val uri = url.toUri().toValidUri() ?: return@create it.onSuccess(createDefaultBitmapForTitle(title).pad()) val cachedFavicon = getFaviconFromMemCache(url) if (cachedFavicon != null) { return@create it.onSuccess(cachedFavicon.pad()) } val faviconCacheFile = getFaviconCacheFile(application, uri) if (faviconCacheFile.exists()) { val storedFavicon = BitmapFactory.decodeFile(faviconCacheFile.path, loaderOptions) if (storedFavicon != null) { addFaviconToMemCache(url, storedFavicon) return@create it.onSuccess(storedFavicon.pad()) } } return@create it.onSuccess(createDefaultBitmapForTitle(title).pad()) } /** * Caches a favicon for a particular URL. * * @param favicon the favicon to cache. * @param url the URL to cache the favicon for. * @return an observable that notifies the consumer when it is complete. */ fun cacheFaviconForUrl(favicon: Bitmap, url: String): Completable = Completable.create { emitter -> val uri = url.toUri().toValidUri() ?: return@create emitter.onComplete() logger.log(TAG, "Caching icon for ${uri.host}") FileOutputStream(getFaviconCacheFile(application, uri)).safeUse { favicon.compress(Bitmap.CompressFormat.PNG, 100, it) it.flush() emitter.onComplete() } } companion object { private const val TAG = "FaviconModel" /** * Creates the cache file for the favicon image. File name will be in the form of "hash of URI host".png * * @param app the context needed to retrieve the cache directory. * @param validUri the URI to use as a unique identifier. * @return a valid cache file. */ @WorkerThread fun getFaviconCacheFile(app: Application, validUri: ValidUri): File { val hash = validUri.host.hashCode().toString() return File(app.cacheDir, "$hash.png") } } }
mpl-2.0
c2f2d63d6e3ce9059f88648be005b7a5
32.794702
112
0.65824
4.544078
false
false
false
false
zdary/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/refactorings/ExtractMethodCocktailSortLesson.kt
1
3224
// 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.learn.lesson.general.refactorings import com.intellij.CommonBundle import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.ExtractMethodHelper import com.intellij.ui.UIBundle import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LessonsBundle import training.learn.course.KLesson import javax.swing.JDialog class ExtractMethodCocktailSortLesson(private val sample: LessonSample) : KLesson("Extract method", LessonsBundle.message("extract.method.lesson.name")) { override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(sample) val extractMethodDialogTitle = RefactoringBundle.message("extract.method.title") lateinit var startTaskId: TaskContext.TaskId task("ExtractMethod") { startTaskId = taskId text(LessonsBundle.message("extract.method.invoke.action", action(it))) triggerByUiComponentAndHighlight(false, false) { dialog: JDialog -> dialog.title == extractMethodDialogTitle } restoreIfModifiedOrMoved() test { actions(it) } } // Now will be open the first dialog val okButtonText = CommonBundle.getOkButtonText() val yesButtonText = CommonBundle.getYesButtonText().dropMnemonic() val replaceFragmentDialogTitle = RefactoringBundle.message("replace.fragment") task { text(LessonsBundle.message("extract.method.start.refactoring", strong(okButtonText))) // Wait until the first dialog will gone but we st stateCheck { val ui = previous.ui ?: return@stateCheck false !ui.isShowing && insideRefactoring() } restoreByUi(delayMillis = defaultRestoreDelay) test(waitEditorToBeReady = false) { dialog(extractMethodDialogTitle) { button(okButtonText).click() } } } task { text(LessonsBundle.message("extract.method.confirm.several.replaces", strong(yesButtonText))) // Wait until the third dialog triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { dialog: JDialog -> dialog.title == replaceFragmentDialogTitle } restoreState(restoreId = startTaskId, delayMillis = defaultRestoreDelay) { !insideRefactoring() } test(waitEditorToBeReady = false) { dialog(extractMethodDialogTitle) { button(yesButtonText).click() } } } task { text(LessonsBundle.message("extract.method.second.fragment")) stateCheck { previous.ui?.isShowing?.not() ?: true } test(waitEditorToBeReady = false) { dialog(replaceFragmentDialogTitle) { button(UIBundle.message("replace.prompt.replace.button").dropMnemonic()).click() } } } } private fun insideRefactoring() = Thread.currentThread().stackTrace.any { it.className.contains(ExtractMethodHelper::class.java.simpleName) } }
apache-2.0
0a4583b446d393f3ed518092df4fee43
36.057471
140
0.684243
5.18328
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/ListsEntriesAdapter.kt
1
2613
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.github.moko256.latte.client.base.entity.ListEntry import com.github.moko256.twitlatte.text.TwitterStringUtils.plusUserMarks import io.reactivex.subjects.PublishSubject /** * Created by moko256 on 2019/01/02. * * @author moko256 */ class ListsEntriesAdapter(private val context: Context, private val data: List<ListEntry>) : RecyclerView.Adapter<ListsEntriesAdapter.ViewHolder>() { init { setHasStableIds(true) } val onClickObservable = PublishSubject.create<ListEntry>() override fun getItemId(position: Int): Long { return data[position].listId } override fun getItemViewType(position: Int): Int { return if (data[position].description == null) { R.layout.layout_material_list_item_single_line } else { R.layout.layout_material_list_item_two_line } } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { return ViewHolder( LayoutInflater .from(context) .inflate(i, viewGroup, false) ) } override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) { val entry = data[i] viewHolder.title.text = plusUserMarks(entry.title, viewHolder.title, !entry.isPublic, false) viewHolder.description?.text = entry.description viewHolder.itemView.setOnClickListener { onClickObservable.onNext(entry) } } override fun getItemCount(): Int = data.size class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.primary_text) val description: TextView? = itemView.findViewById(R.id.secondary_text) } }
apache-2.0
fa3b0301bd42d7c1c90a08cb6bbbe489
31.675
149
0.700727
4.39899
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/adblock/source/AssetsHostsDataSource.kt
1
1903
package acr.browser.lightning.adblock.source import acr.browser.lightning.BuildConfig import acr.browser.lightning.adblock.parser.HostsFileParser import acr.browser.lightning.log.Logger import android.content.res.AssetManager import io.reactivex.Single import java.io.InputStreamReader import javax.inject.Inject import javax.inject.Provider /** * A [HostsDataSource] that reads from the hosts list in assets. * * @param assetManager The store for application assets. * @param hostsFileParserProvider The provider used to construct the parser. * @param logger The logger used to log status. */ class AssetsHostsDataSource @Inject constructor( private val assetManager: AssetManager, private val hostsFileParserProvider: Provider<HostsFileParser>, private val logger: Logger ) : HostsDataSource { /** * A [Single] that reads through a hosts file and extracts the domains that should be redirected * to localhost (a.k.a. IP address 127.0.0.1). It can handle files that simply have a list of * host names to block, or it can handle a full blown hosts file. It will strip out comments, * references to the base IP address and just extract the domains to be used. * * @see HostsDataSource.loadHosts */ override fun loadHosts(): Single<HostsResult> = Single.create { emitter -> val reader = InputStreamReader(assetManager.open(BLOCKED_DOMAINS_LIST_FILE_NAME)) val hostsFileParser = hostsFileParserProvider.get() val domains = hostsFileParser.parseInput(reader) logger.log(TAG, "Loaded ${domains.size} domains") emitter.onSuccess(HostsResult.Success(domains)) } override fun identifier(): String = "assets:${BuildConfig.VERSION_CODE}" companion object { private const val TAG = "AssetsHostsDataSource" private const val BLOCKED_DOMAINS_LIST_FILE_NAME = "hosts.txt" } }
mpl-2.0
74837541c86d5cc01ae1ed8be46f24b3
37.06
100
0.736731
4.344749
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/HintUtils.kt
1
2613
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.hints.filtering.MatcherConstructor import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.lang.Language import com.intellij.lang.LanguageExtensionPoint import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.text.StringUtil import java.util.* import java.util.stream.Collectors fun getHintProviders(): List<Pair<Language, InlayParameterHintsProvider>> { val name = ExtensionPointName<LanguageExtensionPoint<InlayParameterHintsProvider>>("com.intellij.codeInsight.parameterNameHints") val languages = name.extensionList.map { it.language } return languages .mapNotNull { Language.findLanguageByID(it) } .map { it to InlayParameterHintsExtension.forLanguage(it) } } fun getBlackListInvalidLineNumbers(text: String): List<Int> { val rules = StringUtil.split(text, "\n", true, false) return rules .asSequence() .mapIndexedNotNull { index, s -> index to s } .filter { it.second.isNotEmpty() } .map { it.first to MatcherConstructor.createMatcher(it.second) } .filter { it.second == null } .map { it.first } .toList() } fun getLanguageForSettingKey(language: Language): Language { val supportedLanguages = getBaseLanguagesWithProviders() var languageForSettings: Language? = language while (languageForSettings != null && !supportedLanguages.contains(languageForSettings)) { languageForSettings = languageForSettings.baseLanguage } if (languageForSettings == null) languageForSettings = language return languageForSettings } fun getBaseLanguagesWithProviders(): List<Language> { return getHintProviders() .stream() .map { (first) -> first } .sorted(Comparator.comparing<Language, String> { l -> l.displayName }) .collect(Collectors.toList()) } fun isParameterHintsEnabledForLanguage(language: Language): Boolean { if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return false if (!InlayHintsSettings.instance().hintsShouldBeShown(language)) return false return ParameterNameHintsSettings.getInstance().isEnabledForLanguage(getLanguageForSettingKey(language)) } fun setShowParameterHintsForLanguage(value: Boolean, language: Language) { ParameterNameHintsSettings.getInstance().setIsEnabledForLanguage(value, getLanguageForSettingKey(language)) }
apache-2.0
8bab4053aeefa249c28bba84b7e134f2
41.16129
140
0.787983
4.759563
false
false
false
false
JuliusKunze/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/Properties.kt
1
1994
/* * Copyright 2010-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.kotlin.konan.properties import org.jetbrains.kotlin.konan.file.* typealias Properties = java.util.Properties fun File.loadProperties(): Properties { val properties = java.util.Properties() this.bufferedReader().use { reader -> properties.load(reader) } return properties } fun loadProperties(path: String): Properties = File(path).loadProperties() fun File.saveProperties(properties: Properties) { this.outputStream().use { properties.store(it, null) } } fun Properties.saveToFile(file: File) = file.saveProperties(this) fun Properties.propertyString(key: String, suffix: String? = null): String? = getProperty(key.suffix(suffix)) ?: this.getProperty(key) /** * TODO: this method working with suffixes should be replaced with * functionality borrowed from def file parser and unified for interop tool * and kotlin compiler. */ fun Properties.propertyList(key: String, suffix: String? = null): List<String> { val value = this.getProperty(key.suffix(suffix)) ?: this.getProperty(key) if (value?.isBlank() == true) return emptyList() return value?.split(Regex("\\s+")) ?: emptyList() } fun Properties.hasProperty(key: String, suffix: String? = null): Boolean = this.getProperty(key.suffix(suffix)) != null fun String.suffix(suf: String?): String = if (suf == null) this else "${this}.$suf"
apache-2.0
3b73f3b39c249fc0d1df208d2d4776e3
31.16129
134
0.717653
3.995992
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/optimizations/kt20844.kt
2
579
// FILE: 1.kt //WITH_RUNTIME package test data class Address( val createdTimeMs: Long = 0, val firstName: String = "", val lastName: String = "" ) inline fun String.switchIfEmpty(provider: () -> String): String { return if (isEmpty()) provider() else this } // FILE: 2.kt import test.* fun box(): String { val address = Address() val result = address.copy( firstName = address.firstName.switchIfEmpty { "O" }, lastName = address.lastName.switchIfEmpty { "K" } ) return result.firstName + result.lastName }
apache-2.0
b610118e1466723a4cc0d63a7fa0e923
20.481481
65
0.61658
3.965753
false
true
false
false
smmribeiro/intellij-community
plugins/settings-repository/src/git/dirCacheEditor.kt
6
7298
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.settingsRepository.git import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.deleteWithParentsIfEmpty import com.intellij.util.io.exists import com.intellij.util.io.toByteArray import org.eclipse.jgit.dircache.BaseDirCacheEditor import org.eclipse.jgit.dircache.DirCache import org.eclipse.jgit.dircache.DirCacheEntry import org.eclipse.jgit.internal.JGitText import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.eclipse.jgit.lib.Repository import java.io.File import java.io.FileInputStream import java.text.MessageFormat import java.util.* private val EDIT_CMP = Comparator<PathEdit> { o1, o2 -> val a = o1.path val b = o2.path DirCache.cmp(a, a.size, b, b.size) } /** * Don't copy edits, * DeletePath (renamed to DeleteFile) accepts raw path * Pass repository to apply */ class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) { private val edits = edits.sortedWith(EDIT_CMP) override fun commit(): Boolean { if (edits.isEmpty()) { // No changes? Don't rewrite the index. // cache.unlock() return true } return super.commit() } override fun finish() { if (!edits.isEmpty()) { applyEdits() replace() } } private fun applyEdits() { val maxIndex = cache.entryCount var lastIndex = 0 for (edit in edits) { var entryIndex = cache.findEntry(edit.path, edit.path.size) val missing = entryIndex < 0 if (entryIndex < 0) { entryIndex = -(entryIndex + 1) } val count = Math.min(entryIndex, maxIndex) - lastIndex if (count > 0) { fastKeep(lastIndex, count) } lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex) if (edit is DeleteFile) { continue } if (edit is DeleteDirectory) { lastIndex = cache.nextEntry(edit.path, edit.path.size, entryIndex) continue } if (missing) { val entry = DirCacheEntry(edit.path) edit.apply(entry, repository) if (entry.rawMode == 0) { throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.pathString)) } fastAdd(entry) } else if (edit is AddFile || edit is AddLoadedFile) { // apply to first entry and remove others val firstEntry = cache.getEntry(entryIndex) val entry: DirCacheEntry if (firstEntry.isMerged) { entry = firstEntry } else { entry = DirCacheEntry(edit.path) entry.creationTime = firstEntry.creationTime } edit.apply(entry, repository) fastAdd(entry) } else { // apply to all entries of the current path (different stages) for (i in entryIndex until lastIndex) { val entry = cache.getEntry(i) edit.apply(entry, repository) fastAdd(entry) } } } val count = maxIndex - lastIndex if (count > 0) { fastKeep(lastIndex, count) } } } interface PathEdit { val path: ByteArray fun apply(entry: DirCacheEntry, repository: Repository) } abstract class PathEditBase(final override val path: ByteArray) : PathEdit private fun encodePath(path: String): ByteArray { val bytes = Charsets.UTF_8.encode(path).toByteArray() if (SystemInfo.isWindows) { for (i in 0 until bytes.size) { if (bytes[i].toChar() == '\\') { bytes[i] = '/'.toByte() } } } return bytes } class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) { override fun apply(entry: DirCacheEntry, repository: Repository) { val file = File(repository.workTree, pathString) entry.fileMode = FileMode.REGULAR_FILE val length = file.length() entry.setLength(length) entry.lastModified = file.lastModified() val input = FileInputStream(file) val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input)) inserter.flush() } finally { inserter.close() input.close() } } } class AddLoadedFile(path: String, private val content: ByteArray, private val size: Int = content.size, private val lastModified: Long = System.currentTimeMillis()) : PathEditBase( encodePath(path)) { override fun apply(entry: DirCacheEntry, repository: Repository) { entry.fileMode = FileMode.REGULAR_FILE entry.length = size entry.lastModified = lastModified val inserter = repository.newObjectInserter() inserter.use { entry.setObjectId(it.insert(Constants.OBJ_BLOB, content, 0, size)) it.flush() } } } @Suppress("FunctionName") fun DeleteFile(path: String): DeleteFile = DeleteFile(encodePath(path)) class DeleteFile(path: ByteArray) : PathEditBase(path) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } class DeleteDirectory(entryPath: String) : PathEditBase( encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } fun Repository.edit(edit: PathEdit) { edit(listOf(edit)) } fun Repository.edit(edits: List<PathEdit>) { if (edits.isEmpty()) { return } val dirCache = lockDirCache() try { DirCacheEditor(edits, this, dirCache, dirCache.entryCount + 4).commit() } finally { dirCache.unlock() } } private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) { override fun finish() { replace() } } fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) { val dirCache = lockDirCache() try { if (deletedSet != null) { for (i in 0 until dirCache.entryCount) { val entry = dirCache.getEntry(i) if (entry.fileMode == FileMode.REGULAR_FILE) { deletedSet.add(entry.pathString) } } } DirCacheTerminator(dirCache).commit() } finally { dirCache.unlock() } if (fromWorkingTree) { val files = workTree.listFiles { file -> file.name != Constants.DOT_GIT } if (files != null) { for (file in files) { FileUtil.delete(file) } } } } fun Repository.writePath(path: String, bytes: ByteArray, size: Int = bytes.size) { edit(AddLoadedFile(path, bytes, size)) FileUtil.writeToFile(File(workTree, path), bytes, 0, size) } fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) { edit((if (isFile) DeleteFile(path) else DeleteDirectory(path))) if (fromWorkingTree) { val workTree = workTree.toPath() val ioFile = workTree.resolve(path) if (ioFile.exists()) { ioFile.deleteWithParentsIfEmpty(workTree, isFile) } } }
apache-2.0
2b24324832222313e80d638fa7da35ec
28.431452
189
0.674979
4.029818
false
false
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/ide/util/scopeChooser/ScopeIdMapper.kt
1
2482
// 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.ide.util.scopeChooser import com.intellij.openapi.application.ApplicationManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls /** * Historically IDE used scope presentable name for serialization (like "Project Files"). * This approach doesn't work anymore because scope presentable names are different in different locales (different translation bundles). * This class helps to map scope serialization IDs to presentable scope name and vice versa. * For compatibility, scope serialization IDs are hardcoded in this class, and they are equal to scope presentable names in English locale. */ @ApiStatus.Internal abstract class ScopeIdMapper { companion object { @JvmStatic val instance: ScopeIdMapper get() = ApplicationManager.getApplication().getService(ScopeIdMapper::class.java) // Scope serialization ids are equal to English scope translations (for compatibility with 2020.2-) @NonNls const val ALL_PLACES_SCOPE_ID = "All Places" @NonNls const val PROJECT_AND_LIBRARIES_SCOPE_ID = "Project and Libraries" @NonNls const val PROJECT_FILES_SCOPE_ID = "Project Files" @NonNls const val PROJECT_PRODUCTION_FILES_SCOPE_ID = "Project Production Files" @NonNls const val PROJECT_TEST_FILES_SCOPE_ID = "Project Test Files" @NonNls const val SCRATCHES_AND_CONSOLES_SCOPE_ID = "Scratches and Consoles" @NonNls const val RECENTLY_VIEWED_FILES_SCOPE_ID = "Recently Viewed Files" @NonNls const val RECENTLY_CHANGED_FILES_SCOPE_ID = "Recently Changed Files" @NonNls const val OPEN_FILES_SCOPE_ID = "Open Files" @NonNls const val CURRENT_FILE_SCOPE_ID = "Current File" @JvmStatic val standardNames = setOf(ALL_PLACES_SCOPE_ID, PROJECT_AND_LIBRARIES_SCOPE_ID, PROJECT_FILES_SCOPE_ID, PROJECT_PRODUCTION_FILES_SCOPE_ID, PROJECT_TEST_FILES_SCOPE_ID, SCRATCHES_AND_CONSOLES_SCOPE_ID, RECENTLY_VIEWED_FILES_SCOPE_ID, RECENTLY_CHANGED_FILES_SCOPE_ID, RECENTLY_CHANGED_FILES_SCOPE_ID, OPEN_FILES_SCOPE_ID, CURRENT_FILE_SCOPE_ID) } @Nls abstract fun getPresentableScopeName(@NonNls scopeId: String): String @NonNls abstract fun getScopeSerializationId(@Nls presentableScopeName: String): String }
apache-2.0
e3a0cc4578dba1de53a3a85f62a5d274
37.2
158
0.754633
4.075534
false
false
false
false
smmribeiro/intellij-community
platform/util/ui/src/com/intellij/ui/svg/SvgCacheManager.kt
2
5859
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "ReplaceNegatedIsEmptyWithIsNotEmpty", "JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package com.intellij.ui.svg import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.diagnostic.Logger import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.ImageLoader import org.jetbrains.annotations.ApiStatus import org.jetbrains.mvstore.MVMap import org.jetbrains.mvstore.MVStore import org.jetbrains.mvstore.type.FixedByteArrayDataType import org.jetbrains.xxh3.Xxh3 import sun.awt.image.SunWritableRaster import java.awt.Image import java.awt.Point import java.awt.image.* import java.nio.ByteBuffer import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.function.BiConsumer private const val IMAGE_KEY_SIZE = java.lang.Long.BYTES + 3 private fun getLogger() = Logger.getInstance(SvgCacheManager::class.java) @ApiStatus.Internal class SvgCacheManager(dbFile: Path) { private val store: MVStore private val scaleToMap: MutableMap<Float, MVMap<ByteArray, ImageValue>> = ConcurrentHashMap(2, 0.75f, 2) private val mapBuilder: MVMap.Builder<ByteArray, ImageValue> companion object { fun <K, V> getMap(scale: Float, isDark: Boolean, scaleToMap: MutableMap<Float, MVMap<K, V>>, store: MVStore, mapBuilder: MVMap.MapBuilder<MVMap<K, V>, K, V>): MVMap<K, V> { return scaleToMap.computeIfAbsent(scale + if (isDark) 10000 else 0) { store.openMap("icons@" + scale + if (isDark) "_d" else "", mapBuilder) } } fun readImage(value: ImageValue): Image { val dataBuffer = DataBufferInt(value.data, value.data.size) SunWritableRaster.makeTrackable(dataBuffer) return createImage(value.w, value.h, dataBuffer) } fun readImage(buffer: ByteBuffer, w: Int, h: Int): Image { val dataBuffer = DataBufferInt(w * h) buffer.asIntBuffer().get(SunWritableRaster.stealData(dataBuffer, 0)) SunWritableRaster.makeTrackable(dataBuffer) return createImage(w, h, dataBuffer) } } init { val storeErrorHandler = StoreErrorHandler() val storeBuilder = MVStore.Builder() .backgroundExceptionHandler(storeErrorHandler) .autoCommitDelay(60000) .compressionLevel(1) store = storeBuilder.openOrNewOnIoError(dbFile, true) { getLogger().debug("Cannot open icon cache database", it) } storeErrorHandler.isStoreOpened = true val mapBuilder = MVMap.Builder<ByteArray, ImageValue>() mapBuilder.keyType(FixedByteArrayDataType(IMAGE_KEY_SIZE)) mapBuilder.valueType(ImageValue.ImageValueSerializer()) this.mapBuilder = mapBuilder } private class StoreErrorHandler : BiConsumer<Throwable, MVStore> { var isStoreOpened = false override fun accept(e: Throwable, store: MVStore) { val logger = getLogger() if (isStoreOpened) { logger.error("Icon cache error (db=$store)") } else { logger.warn("Icon cache will be recreated or previous version of data reused, (db=$store)") } logger.debug(e) } } fun close() { store.close() } fun save() { store.triggerAutoSave() } fun loadFromCache(themeDigest: ByteArray, imageBytes: ByteArray, scale: Float, isDark: Boolean, docSize: ImageLoader.Dimension2DDouble): Image? { val key = getCacheKey(themeDigest, imageBytes) val map = getMap(scale, isDark, scaleToMap, store, mapBuilder) try { val start = StartUpMeasurer.getCurrentTimeIfEnabled() val data = map.get(key) ?: return null val image = readImage(data) docSize.setSize((data.w / scale).toDouble(), (data.h / scale).toDouble()) IconLoadMeasurer.svgCacheRead.end(start) return image } catch (e: Throwable) { getLogger().error(e) try { map.remove(key) } catch (e1: Exception) { getLogger().error("Cannot remove invalid entry", e1) } return null } } fun storeLoadedImage(themeDigest: ByteArray, imageBytes: ByteArray, scale: Float, image: BufferedImage) { val key = getCacheKey(themeDigest, imageBytes) getMap(scale, false, scaleToMap, store, mapBuilder).put(key, writeImage(image)) } } private val ZERO_POINT = Point(0, 0) private fun getCacheKey(themeDigest: ByteArray, imageBytes: ByteArray): ByteArray { val contentDigest = Xxh3.hashLongs(longArrayOf( Xxh3.hash(imageBytes), Xxh3.hash(themeDigest))) val buffer = ByteBuffer.allocate(IMAGE_KEY_SIZE) // add content size to key to reduce chance of hash collision (write as medium int) buffer.put((imageBytes.size ushr 16).toByte()) buffer.put((imageBytes.size ushr 8).toByte()) buffer.put(imageBytes.size.toByte()) buffer.putLong(contentDigest) return buffer.array() } private fun createImage(w: Int, h: Int, dataBuffer: DataBufferInt): BufferedImage { val colorModel = ColorModel.getRGBdefault() as DirectColorModel val raster = Raster.createPackedRaster(dataBuffer, w, h, w, colorModel.masks, ZERO_POINT) @Suppress("UndesirableClassUsage") return BufferedImage(colorModel, raster, false, null) } private fun writeImage(image: BufferedImage): ImageValue { val w = image.width val h = image.height @Suppress("UndesirableClassUsage") val convertedImage = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g = convertedImage.createGraphics() g.drawImage(image, 0, 0, null) g.dispose() val dataBufferInt = convertedImage.raster.dataBuffer as DataBufferInt return ImageValue(dataBufferInt.data, w, h) }
apache-2.0
573f077c80524a7a4c60f0e8fa396dd4
35.17284
158
0.705581
3.908606
false
false
false
false
smmribeiro/intellij-community
plugins/configuration-script/src/schemaGenerators/componentStateProvider.kt
10
3752
package com.intellij.configurationScript.schemaGenerators import com.intellij.configurationScript.LOG import com.intellij.configurationScript.SchemaGenerator import com.intellij.configurationStore.ComponentSerializationUtil import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.util.ReflectionUtil import com.intellij.util.containers.CollectionFactory import org.jetbrains.io.JsonObjectBuilder internal class ComponentStateJsonSchemaGenerator : SchemaGenerator { private val pathToStateClass: MutableMap<String, Class<out BaseState>> = CollectionFactory.createSmallMemoryFootprintMap() private val objectSchemaGenerator = OptionClassJsonSchemaGenerator("classDefinitions") override val definitionNodeKey: CharSequence get() = objectSchemaGenerator.definitionNodeKey // schema is generated without project - we cannot rely on created component adapter for services override fun generate(rootBuilder: JsonObjectBuilder) { for (plugin in PluginManagerCore.getLoadedPlugins()) { for (serviceDescriptor in (plugin as IdeaPluginDescriptorImpl).projectContainerDescriptor.services ?: continue) { processServiceDescriptor(serviceDescriptor, plugin) } } doGenerate(rootBuilder, pathToStateClass) } override fun generateDefinitions() = objectSchemaGenerator.describe() internal fun doGenerate(rootBuilder: JsonObjectBuilder, pathToStateClass: Map<String, Class<out BaseState>>) { if (pathToStateClass.isEmpty()) { return } val pathToJsonObjectBuilder: MutableMap<String, JsonObjectBuilder> = CollectionFactory.createSmallMemoryFootprintMap() for (path in pathToStateClass.keys.sorted()) { val keys = path.split(".") val jsonObjectBuilder: JsonObjectBuilder LOG.assertTrue(keys.size < 3, "todo") if (keys.size == 1) { jsonObjectBuilder = rootBuilder } else { jsonObjectBuilder = pathToJsonObjectBuilder.getOrPut(keys.subList(0, keys.size - 1).joinToString(".")) { JsonObjectBuilder(StringBuilder(), indentLevel = 3) } } jsonObjectBuilder.map(keys.last()) { "type" to "object" map("properties") { buildJsonSchema(ReflectionUtil.newInstance(pathToStateClass.getValue(path)), this, objectSchemaGenerator) } "additionalProperties" to false } } for ((key, value) in pathToJsonObjectBuilder) { rootBuilder.map(key) { "type" to "object" rawBuilder("properties", value) "additionalProperties" to false } } } private fun processServiceDescriptor(serviceDescriptor: ServiceDescriptor, plugin: PluginDescriptor) { val schemaKeyPath = serviceDescriptor.configurationSchemaKey ?: return LOG.runAndLogException { val implClass = Class.forName(serviceDescriptor.implementation, /* initialize = */ false, plugin.pluginClassLoader) if (!PersistentStateComponent::class.java.isAssignableFrom(implClass)) { return } // must inherit from BaseState @Suppress("UNCHECKED_CAST") val stateClass = ComponentSerializationUtil.getStateClass<BaseState>(implClass as Class<out PersistentStateComponent<Any>>) val oldValue = pathToStateClass.put(schemaKeyPath, stateClass) if (oldValue != null) { LOG.error("duplicated configurationSchemaKey $schemaKeyPath in plugin $plugin") } } } }
apache-2.0
ececb030322bcd51cab0b0b58f83d659
40.241758
129
0.751599
5.125683
false
true
false
false
MilosKozak/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt
3
3593
package info.nightscout.androidaps.plugins.pump.virtual import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.virtualpump_fragment.* import org.slf4j.LoggerFactory class VirtualPumpFragment : Fragment() { private val disposable = CompositeDisposable() private val loopHandler = Handler() private lateinit var refreshLoop: Runnable init { refreshLoop = Runnable { activity?.runOnUiThread { updateGui() } loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.virtualpump_fragment, container, false) } @Synchronized override fun onResume() { super.onResume() disposable.add(RxBus .toObservable(EventVirtualPumpUpdateGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGui() }, { FabricPrivacy.logException(it) }) ) disposable.add(RxBus .toObservable(EventTempBasalChange::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGui() }, { FabricPrivacy.logException(it) }) ) disposable.add(RxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGui() }, { FabricPrivacy.logException(it) }) ) loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() loopHandler.removeCallbacks(refreshLoop) } @Synchronized private fun updateGui() { val virtualPump = VirtualPumpPlugin.getPlugin() virtualpump_basabasalrate?.text = MainApp.gs(R.string.pump_basebasalrate, virtualPump.baseBasalRate) virtualpump_tempbasal?.text = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" virtualpump_extendedbolus?.text = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis())?.toString() ?: "" virtualpump_battery?.text = MainApp.gs(R.string.format_percent, virtualPump.batteryPercent) virtualpump_reservoir?.text = MainApp.gs(R.string.formatinsulinunits, virtualPump.reservoirInUnits.toDouble()) virtualPump.refreshConfiguration() val pumpType = virtualPump.pumpType virtualpump_type?.text = pumpType.description virtualpump_type_def?.text = pumpType.getFullDescription(MainApp.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals()) } }
agpl-3.0
34a6678a0212bcdc3951f0f1defd45ca
41.270588
144
0.720568
4.803476
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingUserOptions.kt
1
2624
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import java.util.* class MsgSettingUserOptions( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x320B) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(packet: ByteArray) { val bytes = getDataBytes(packet, packet.size - 10) danaPump.userOptionsFrompump = Arrays.copyOf(bytes, bytes!!.size) // saving pumpDataBytes to use it in MsgSetUserOptions for (pos in bytes.indices) { aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos]) } danaPump.timeDisplayType24 = bytes[0].toInt() == 0 // 0 -> 24h 1 -> 12h danaPump.buttonScrollOnOff = bytes[1] == 1.toByte() // 1 -> ON, 0-> OFF danaPump.beepAndAlarm = bytes[2].toInt() // 1 -> Sound on alarm 2-> Vibrate on alarm 3-> Both on alarm 5-> Sound + beep 6-> vibrate + beep 7-> both + beep Beep adds 4 danaPump.lcdOnTimeSec = bytes[3].toInt() danaPump.backlightOnTimeSec = bytes[4].toInt() danaPump.selectedLanguage = bytes[5].toInt() // on DanaRv2 is that needed ? danaPump.units = bytes[8].toInt() danaPump.shutdownHour = bytes[9].toInt() danaPump.lowReservoirRate = bytes[32].toInt() /* int selectableLanguage1 = bytes[10]; int selectableLanguage2 = bytes[11]; int selectableLanguage3 = bytes[12]; int selectableLanguage4 = bytes[13]; int selectableLanguage5 = bytes[14]; */ aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType24: " + danaPump.timeDisplayType24) aapsLogger.debug(LTag.PUMPCOMM, "Button scroll: " + danaPump.buttonScrollOnOff) aapsLogger.debug(LTag.PUMPCOMM, "BeepAndAlarm: " + danaPump.beepAndAlarm) aapsLogger.debug(LTag.PUMPCOMM, "screen timeout: " + danaPump.lcdOnTimeSec) aapsLogger.debug(LTag.PUMPCOMM, "BackLight: " + danaPump.backlightOnTimeSec) aapsLogger.debug(LTag.PUMPCOMM, "Selected language: " + danaPump.selectedLanguage) aapsLogger.debug(LTag.PUMPCOMM, "Units: " + danaPump.getUnits()) aapsLogger.debug(LTag.PUMPCOMM, "Shutdown: " + danaPump.shutdownHour) aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaPump.lowReservoirRate) } private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? { if (bytes == null) { return null } val ret = ByteArray(len) System.arraycopy(bytes, 6, ret, 0, len) return ret } }
agpl-3.0
cb7cfc98703e16dd5f860bb0cfb6d96f
45.052632
174
0.658537
4.205128
false
false
false
false
alibaba/p3c
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt
2
2974
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.quickfix import com.alibaba.p3c.idea.i18n.P3cBundle import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.javadoc.PsiDocToken import com.siyeh.ig.InspectionGadgetsFix /** * * * @author caikang * @date 2017/02/27 */ object ClassMustHaveAuthorQuickFix : InspectionGadgetsFix(), AliQuickFix { val tag = "@author ${System.getProperty("user.name") ?: System.getenv("USER")}" override fun doFix(project: Project?, descriptor: ProblemDescriptor?) { descriptor ?: return val psiClass = descriptor.psiElement as? PsiClass ?: descriptor.psiElement?.parent as? PsiClass ?: return val document = psiClass.docComment val psiFacade = JavaPsiFacade.getInstance(project) val factory = psiFacade.elementFactory if (document == null) { val doc = factory.createDocCommentFromText(""" /** * $tag */ """) if (psiClass.isEnum) { psiClass.containingFile.addAfter(doc, psiClass.prevSibling) } else { psiClass.addBefore(doc, psiClass.firstChild) } return } val regex = Regex("Created by (.*) on (.*)\\.") for (line in document.descriptionElements) { if (line is PsiDocToken && line.text.contains(regex)) { val groups = regex.find(line.text)?.groups ?: continue val author = groups[1]?.value ?: continue val date = groups[2]?.value ?: continue document.addBefore(factory.createDocTagFromText("@date $date"), line) document.addBefore(factory.createDocTagFromText("@author $author"), line) line.delete() return } } if (document.tags.isNotEmpty()) { document.addBefore(factory.createDocTagFromText(tag), document.tags[0]) return } document.add(factory.createDocTagFromText(tag)) } override val ruleName: String get() = "ClassMustHaveAuthorRule" override val onlyOnThFly: Boolean get() = true override fun getName(): String { return P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.generate.author") } }
apache-2.0
5d1dc94d7731bc0da91c98aa662595ab
33.183908
113
0.652656
4.445441
false
false
false
false
devjn/GithubSearch
app/src/main/kotlin/com/github/devjn/githubsearch/view/SearchFragment.kt
1
9426
package com.github.devjn.githubsearch.view import android.app.SearchManager import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.databinding.ViewDataBinding import android.os.Bundle import android.provider.SearchRecentSuggestions import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.content.res.ResourcesCompat import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.View import com.arlib.floatingsearchview.FloatingSearchView import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion import com.github.devjn.githubsearch.R import com.github.devjn.githubsearch.databinding.FragmentMainBinding import com.github.devjn.githubsearch.databinding.ListItemRepositoryBinding import com.github.devjn.githubsearch.databinding.ListItemUserBinding import com.github.devjn.githubsearch.model.entities.GitObject import com.github.devjn.githubsearch.model.entities.Repository import com.github.devjn.githubsearch.model.entities.User import com.github.devjn.githubsearch.utils.* import com.github.devjn.githubsearch.viewmodel.SearchViewModel import com.github.devjn.githubsearch.widgets.EndlessRecyclerViewScrollListener import com.minimize.android.rxrecycleradapter.RxDataSource import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject /** * Created by @author Jahongir on 27-Apr-17 * [email protected] * SearchFragment */ class SearchFragment<T : GitObject> : BaseFragment<FragmentMainBinding, SearchViewModel<T>>() { private lateinit var mSearchView: FloatingSearchView private lateinit var rxDataSource: RxDataSource<T> private val onClickSubject = PublishSubject.create<ViewDataBinding>() private lateinit var scrollListener: EndlessRecyclerViewScrollListener private lateinit var suggestionAdapter: SuggestionAdapter private lateinit var suggestions: SearchRecentSuggestions private var isSearchIntent = false override fun provideViewModel(): SearchViewModel<T> = ViewModelProviders.of(this).get(SearchViewModel::class.java) as SearchViewModel<T> override fun provideLayoutId() = R.layout.fragment_main override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { args -> viewModel.type = args.getInt(KEY_TYPE, TYPE_USERS) args.getString(SearchManager.QUERY)?.let { viewModel.lastQuery = it isSearchIntent = true } } } override fun setupLayout() { mSearchView = binding.floatingSearchView val linearLayoutManager = LinearLayoutManager(activity) scrollListener = object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView) { viewModel.loadMore(page + 1, totalItemsCount, onError) } } binding.list.apply { layoutManager = linearLayoutManager itemAnimator = DefaultItemAnimator() addOnScrollListener(scrollListener) addItemDecoration(DividerItemDecoration(context, linearLayoutManager.orientation)) } setupSearchView() checkEmptyView() } private fun setupSearchView() { val searchManager = requireContext().getSystemService(Context.SEARCH_SERVICE) as SearchManager suggestionAdapter = SuggestionAdapter(activity!!, searchManager) mSearchView.setOnQueryChangeListener { oldQuery, newQuery -> if (oldQuery != "" && newQuery == "") { suggestionAdapter.getSuggestions("", 3)?.let { mSearchView.swapSuggestions(it) } } else { Single.fromCallable { suggestionAdapter.getSuggestions(newQuery, 5) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { mSearchView.showProgress() } //this shows the top left circular progress .doFinally { mSearchView.hideProgress() } //this will swap the data and render the collapse/expand animations as necessary .subscribe({ list -> mSearchView.swapSuggestions(list) }, { mSearchView.clearSuggestions(); } ).disp() } } mSearchView.setOnSearchListener(object : FloatingSearchView.OnSearchListener { override fun onSuggestionClicked(searchSuggestion: SearchSuggestion) { viewModel.lastQuery = searchSuggestion.body search(viewModel.lastQuery) } override fun onSearchAction(query: String) { viewModel.lastQuery = query search(query) Log.d(TAG, "onSearchAction, query: $query") } }) mSearchView.setOnFocusChangeListener(object : FloatingSearchView.OnFocusChangeListener { override fun onFocus() { //show history when search bar gains focus suggestionAdapter.getSuggestions("", 3)?.let { mSearchView.swapSuggestions(it) } } override fun onFocusCleared() { //set the title of the bar so that when focus is returned a new query begins mSearchView.setSearchText(viewModel.lastQuery) } }) mSearchView.setOnBindSuggestionCallback { _, leftIcon, _, _, _ -> leftIcon.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_history_black_24dp, null)) leftIcon.alpha = .36f } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) suggestions = SearchRecentSuggestions(context, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE) rxDataSource = RxDataSource(viewModel.data.value) val dataSource = if (viewModel.type == TYPE_USERS) rxDataSource.bindRecyclerView<ListItemUserBinding>(binding.list, R.layout.list_item_user) else rxDataSource.bindRecyclerView<ListItemRepositoryBinding>(binding.list, R.layout.list_item_repository) dataSource.subscribe { viewHolder -> val b: ViewDataBinding = viewHolder.viewDataBinding val data = viewHolder.item if (viewModel.type == TYPE_USERS) (b as ListItemUserBinding).user = data as User else (b as ListItemRepositoryBinding).repo = data as Repository b.root.setOnClickListener { onClickSubject.onNext(b) } }.disp() onClickSubject.subscribe { bind -> when (viewModel.type) { TYPE_REPOSITORIES -> AndroidUtils.startCustomTab(activity!!, (bind as ListItemRepositoryBinding).repo!!.html_url) TYPE_USERS -> UserDetailsActivity.start(baseActivity, (bind as ListItemUserBinding).imageUser, bind.user) } }.disp() viewModel.data.observe(this, Observer { if (it == null) return@Observer rxDataSource.updateDataSet(it).updateAdapter() checkEmptyView() }) if (isSearchIntent) { isSearchIntent = false search(viewModel.lastQuery) } } private fun search(query: String) { // reset infinite scroll scrollListener.resetState() suggestions.saveRecentQuery(query, null) viewModel.search(query, onError) } private fun checkEmptyView() { binding.emptyText.text = getString(if (viewModel.lastGitData != null) R.string.nothing_found else if (viewModel.type == TYPE_USERS) R.string.find_users else R.string.find_repos) binding.emptyText.visibility = if (viewModel.data.value!!.isEmpty()) View.VISIBLE else View.GONE } override fun onBackPressedCaptured(): Boolean { if (mSearchView.setSearchFocused(false)) { return true } return super.onBackPressedCaptured() } private val onError: Consumer<Throwable> by lazy { Consumer<Throwable> { e -> Snackbar.make(binding.root, R.string.connection_problem, SNACKBAR_LENGTH) .setAction(R.string.retry) { search(viewModel.lastQuery) }.show() Log.e(TAG, "Error while getting data", e) } } companion object { val TAG = SearchFragment::class.java.simpleName!! const val KEY_TYPE = "TYPE" const val TYPE_USERS = 0 const val TYPE_REPOSITORIES = 1 const val SNACKBAR_LENGTH = 6000 fun newInstance(type: Int): Fragment = newInstance(type, null) fun newInstance(type: Int, bundle: Bundle?) = (if (type == TYPE_USERS) SearchFragment<User>() else SearchFragment<Repository>()).withArgs { putInt(KEY_TYPE, type) putAllSafe(bundle) } } }
apache-2.0
29e363b0985d947bfe18a6c3e4d1653f
40.342105
140
0.675896
5.01383
false
false
false
false
siosio/intellij-community
platform/diff-impl/src/com/intellij/openapi/vcs/ex/LineStatusTrackerBase.kt
2
11303
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.ex import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.DiffUtil.executeWriteCommand import com.intellij.diff.util.Side import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.command.undo.UndoUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.ex.DocumentTracker.Block import com.intellij.openapi.vcs.ex.LineStatusTrackerBlockOperations.Companion.isSelectedByLine import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import java.util.* abstract class LineStatusTrackerBase<R : Range>( override val project: Project?, final override val document: Document ) : LineStatusTrackerI<R> { final override val vcsDocument: Document = createVcsDocument(document) final override val disposable: Disposable = Disposer.newDisposable() internal val LOCK: DocumentTracker.Lock = DocumentTracker.Lock() protected val blockOperations: LineStatusTrackerBlockOperations<R, Block> = MyBlockOperations(LOCK) protected val documentTracker: DocumentTracker protected abstract val renderer: LineStatusMarkerRenderer final override var isReleased: Boolean = false private set protected var isInitialized: Boolean = false private set protected val blocks: List<Block> get() = documentTracker.blocks init { documentTracker = DocumentTracker(vcsDocument, document, LOCK) Disposer.register(disposable, documentTracker) documentTracker.addHandler(MyDocumentTrackerHandler()) } @RequiresEdt protected open fun isDetectWhitespaceChangedLines(): Boolean = false /** * Prevent "trim trailing spaces for modified lines on save" from re-applying just reverted changes. */ protected open fun isClearLineModificationFlagOnRollback(): Boolean = false protected abstract fun toRange(block: Block): R override val virtualFile: VirtualFile? get() = null override fun getRanges(): List<R>? { ApplicationManager.getApplication().assertReadAccessAllowed() return blockOperations.getRanges() } @RequiresEdt protected fun setBaseRevision(vcsContent: CharSequence, beforeUnfreeze: (() -> Unit)?) { ApplicationManager.getApplication().assertIsDispatchThread() if (isReleased) return documentTracker.doFrozen(Side.LEFT) { updateDocument(Side.LEFT) { vcsDocument.setText(vcsContent) } beforeUnfreeze?.invoke() } if (!isInitialized) { isInitialized = true updateHighlighters() } } @RequiresEdt fun dropBaseRevision() { ApplicationManager.getApplication().assertIsDispatchThread() if (isReleased || !isInitialized) return isInitialized = false updateHighlighters() documentTracker.doFrozen { updateDocument(Side.LEFT) { vcsDocument.setText(document.immutableCharSequence) documentTracker.setFrozenState(emptyList()) } } } fun release() { val runnable = Runnable { if (isReleased) return@Runnable isReleased = true Disposer.dispose(disposable) } if (!ApplicationManager.getApplication().isDispatchThread || LOCK.isHeldByCurrentThread) { ApplicationManager.getApplication().invokeLater(runnable) } else { runnable.run() } } @RequiresEdt protected fun updateDocument(side: Side, task: (Document) -> Unit): Boolean { return updateDocument(side, null, task) } @RequiresEdt protected fun updateDocument(side: Side, commandName: String?, task: (Document) -> Unit): Boolean { val affectedDocument = if (side.isLeft) vcsDocument else document return updateDocument(project, affectedDocument, commandName, task) } @RequiresEdt override fun doFrozen(task: Runnable) { documentTracker.doFrozen({ task.run() }) } override fun <T> readLock(task: () -> T): T { return documentTracker.readLock(task) } private inner class MyBlockOperations(lock: DocumentTracker.Lock) : LineStatusTrackerBlockOperations<R, Block>(lock) { override fun getBlocks(): List<Block>? = if (isValid()) blocks else null override fun Block.toRange(): R = toRange(this) } private inner class MyDocumentTrackerHandler : DocumentTracker.Handler { override fun afterBulkRangeChange(isDirty: Boolean) { updateHighlighters() } override fun onUnfreeze(side: Side) { updateHighlighters() } } protected abstract inner class InnerRangesDocumentTrackerHandler : DocumentTracker.Handler { abstract var Block.innerRanges: List<Range.InnerRange>? abstract fun isDetectWhitespaceChangedLines(): Boolean override fun onRangeShifted(before: Block, after: Block) { after.innerRanges = before.innerRanges } override fun afterBulkRangeChange(isDirty: Boolean) { if (!isDirty) updateMissingInnerRanges() } override fun onUnfreeze(side: Side) { updateMissingInnerRanges() } private fun updateMissingInnerRanges() { if (!isDetectWhitespaceChangedLines()) return if (documentTracker.isFrozen()) return for (block in blocks) { if (block.innerRanges == null) { block.innerRanges = calcInnerRanges(block) } } } @RequiresEdt fun resetInnerRanges() { LOCK.write { if (isDetectWhitespaceChangedLines()) { for (block in blocks) { block.innerRanges = calcInnerRanges(block) } } else { for (block in blocks) { block.innerRanges = null } } } } private fun calcInnerRanges(block: Block): List<Range.InnerRange>? { if (block.start == block.end || block.vcsStart == block.vcsEnd) return null return createInnerRanges(block.range, vcsDocument.immutableCharSequence, document.immutableCharSequence, vcsDocument.lineOffsets, document.lineOffsets) } } protected fun updateHighlighters() { renderer.scheduleUpdate() } override fun isOperational(): Boolean = LOCK.read { return isInitialized && !isReleased } override fun isValid(): Boolean = LOCK.read { return isOperational() && !documentTracker.isFrozen() } override fun findRange(range: Range): R? = blockOperations.findRange(range) override fun getNextRange(line: Int): R? = blockOperations.getNextRange(line) override fun getPrevRange(line: Int): R? = blockOperations.getPrevRange(line) override fun getRangesForLines(lines: BitSet): List<R>? = blockOperations.getRangesForLines(lines) override fun getRangeForLine(line: Int): R? = blockOperations.getRangeForLine(line) override fun isLineModified(line: Int): Boolean = blockOperations.isLineModified(line) override fun isRangeModified(startLine: Int, endLine: Int): Boolean = blockOperations.isRangeModified(startLine, endLine) override fun transferLineFromVcs(line: Int, approximate: Boolean): Int = blockOperations.transferLineFromVcs(line, approximate) override fun transferLineToVcs(line: Int, approximate: Boolean): Int = blockOperations.transferLineToVcs(line, approximate) @RequiresEdt override fun rollbackChanges(range: Range) { val newRange = blockOperations.findBlock(range) if (newRange != null) { runBulkRollback { it == newRange } } } @RequiresEdt override fun rollbackChanges(lines: BitSet) { runBulkRollback { it.isSelectedByLine(lines) } } @RequiresEdt protected fun runBulkRollback(condition: (Block) -> Boolean) { if (!isValid()) return updateDocument(Side.RIGHT, DiffBundle.message("rollback.change.command.name")) { documentTracker.partiallyApplyBlocks(Side.RIGHT, condition) { block, shift -> fireLinesUnchanged(block.start + shift, block.start + shift + (block.vcsEnd - block.vcsStart)) } } } private fun fireLinesUnchanged(startLine: Int, endLine: Int) { if (!isClearLineModificationFlagOnRollback()) return if (document.textLength == 0) return // empty document has no lines if (startLine == endLine) return (document as DocumentImpl).clearLineModificationFlags(startLine, endLine) } companion object { @JvmStatic protected val LOG: Logger = Logger.getInstance(LineStatusTrackerBase::class.java) private val VCS_DOCUMENT_KEY: Key<Boolean> = Key.create("LineStatusTrackerBase.VCS_DOCUMENT_KEY") val SEPARATE_UNDO_STACK: Key<Boolean> = Key.create("LineStatusTrackerBase.SEPARATE_UNDO_STACK") fun createVcsDocument(originalDocument: Document): Document { val result = DocumentImpl(originalDocument.immutableCharSequence, true) UndoUtil.disableUndoFor(result) result.putUserData(VCS_DOCUMENT_KEY, true) result.setReadOnly(true) return result } @RequiresEdt fun updateDocument(project: Project?, document: Document, commandName: @NlsContexts.Command String?, task: (Document) -> Unit): Boolean { if (DiffUtil.isUserDataFlagSet(VCS_DOCUMENT_KEY, document)) { document.setReadOnly(false) try { CommandProcessor.getInstance().runUndoTransparentAction { task(document) } return true } finally { document.setReadOnly(true) } } else { val isSeparateUndoStack = DiffUtil.isUserDataFlagSet(SEPARATE_UNDO_STACK, document) return executeWriteCommand(project, document, commandName, null, UndoConfirmationPolicy.DEFAULT, false, !isSeparateUndoStack) { task(document) } } } } override fun toString(): String { return javaClass.name + "(" + "file=" + virtualFile?.let { file -> file.path + (if (!file.isInLocalFileSystem) "@$file" else "") + "@" + Integer.toHexString(file.hashCode()) } + ", document=" + document.let { doc -> doc.toString() + "@" + Integer.toHexString(doc.hashCode()) } + ", isReleased=$isReleased" + ")" + "@" + Integer.toHexString(hashCode()) } }
apache-2.0
0c79e81afc5dbec353977373e7edbe3d
32.146628
129
0.700964
4.680331
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaPropertyUsages/javaPropertySetterUsagesKJ.1.kt
8
284
open class A { open var p: Int = 1 } class AA : A() { override var p: Int = 1 } class B : J() { override var p: Int = 1 } fun test() { val t = A().p A().p = 1 val t = AA().p AA().p = 1 val t = J().p J().p = 1 val t = B().p B().p = 1 }
apache-2.0
ff9cd3edca255b033f925c6ff640fe48
10.4
27
0.401408
2.581818
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockMethod.kt
3
2977
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.test.mock import com.sun.jdi.Location import com.sun.jdi.Method class MockMethod : Method { override fun name() = "" override fun allLineLocations() = emptyList<Location>() override fun isSynthetic() = throw UnsupportedOperationException() override fun isFinal() = throw UnsupportedOperationException() override fun isStatic() = throw UnsupportedOperationException() override fun declaringType() = throw UnsupportedOperationException() override fun signature() = throw UnsupportedOperationException() override fun genericSignature() = throw UnsupportedOperationException() override fun variables() = throw UnsupportedOperationException() override fun variablesByName(name: String?) = throw UnsupportedOperationException() override fun bytecodes() = throw UnsupportedOperationException() override fun isBridge() = throw UnsupportedOperationException() override fun isObsolete() = throw UnsupportedOperationException() override fun isSynchronized() = throw UnsupportedOperationException() override fun allLineLocations(stratum: String?, sourceName: String?) = throw UnsupportedOperationException() override fun isNative() = throw UnsupportedOperationException() override fun locationOfCodeIndex(codeIndex: Long) = throw UnsupportedOperationException() override fun arguments() = throw UnsupportedOperationException() override fun isAbstract() = throw UnsupportedOperationException() override fun isVarArgs() = throw UnsupportedOperationException() override fun returnTypeName() = throw UnsupportedOperationException() override fun argumentTypes() = throw UnsupportedOperationException() override fun isConstructor() = throw UnsupportedOperationException() override fun locationsOfLine(lineNumber: Int) = throw UnsupportedOperationException() override fun locationsOfLine(stratum: String?, sourceName: String?, lineNumber: Int) = throw UnsupportedOperationException() override fun argumentTypeNames() = throw UnsupportedOperationException() override fun returnType() = throw UnsupportedOperationException() override fun isStaticInitializer() = throw UnsupportedOperationException() override fun location() = throw UnsupportedOperationException() override fun compareTo(other: Method?) = throw UnsupportedOperationException() override fun isPackagePrivate() = throw UnsupportedOperationException() override fun isPrivate() = throw UnsupportedOperationException() override fun isProtected() = throw UnsupportedOperationException() override fun isPublic() = throw UnsupportedOperationException() override fun modifiers() = throw UnsupportedOperationException() override fun virtualMachine() = throw UnsupportedOperationException() }
apache-2.0
652b7d020b25a1502b297085cda6cb44
63.717391
158
0.786026
6.528509
false
false
false
false
vqvu/euler-project
src/main/kotlin/com/github/vqvu/eulerproject/Problem5.kt
1
731
package com.github.vqvu.eulerproject import java.util.HashMap /** * @author victor */ fun main(args: Array<String>) { val maxPrimeFactors: MutableMap<Long, Int> = HashMap() for (i in 2..20) { val primeFactors = primeFactors(i.toLong()) for ((prime, count) in primeFactors) { var curCount = maxPrimeFactors[prime] if (curCount == null) { curCount = 0 } if (curCount < count) { maxPrimeFactors[prime] = count } } } val answer = maxPrimeFactors .map { entry -> pow(entry.key, entry.value) } .fold(1L, Long::times) assert(answer == 232792560L) println("answer = $answer") }
mit
f3ceedcea134c7b80573df81f9a397c4
24.241379
58
0.549932
3.748718
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/intentions/MarkdownInsertTableColumnIntention.kt
5
2257
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.hasCorrectBorders import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.insertColumn import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow import org.intellij.plugins.markdown.settings.MarkdownSettings internal abstract class MarkdownInsertTableColumnIntention(private val insertAfter: Boolean): PsiElementBaseIntentionAction() { override fun getFamilyName(): String { return MarkdownBundle.message("markdown.insert.table.column.intention.family") } override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean { if (!MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) { return false } val cell = TableUtils.findCell(element) return cell != null && editor != null && cell.parentTable?.hasCorrectBorders() == true } override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val cell = TableUtils.findCell(element) val table = cell?.parentTable if (cell == null || table == null || editor == null) { return } table.insertColumn(editor.document, cell.columnIndex, insertAfter, alignment = MarkdownTableSeparatorRow.CellAlignment.LEFT) } class InsertBefore: MarkdownInsertTableColumnIntention(insertAfter = false) { override fun getText(): String { return MarkdownBundle.message("markdown.insert.table.column.to.the.left.intention.text") } } class InsertAfter: MarkdownInsertTableColumnIntention(insertAfter = true) { override fun getText(): String { return MarkdownBundle.message("markdown.insert.table.column.to.the.right.intention.text") } } }
apache-2.0
3e79c3da463812d53945d879b1292afb
46.020833
158
0.781568
4.559596
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/validators/GitBranchValidator.kt
2
3901
// 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 git4idea.validators import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.text.StringUtil import git4idea.GitUtil.HEAD import git4idea.i18n.GitBundle import git4idea.i18n.GitBundle.BUNDLE import git4idea.repo.GitRepository import org.jetbrains.annotations.Nls import org.jetbrains.annotations.PropertyKey fun validateName(repositories: Collection<GitRepository>, inputString: String): ValidationInfo? = checkRefName(inputString) ?: checkBranchConflict(repositories, inputString) fun checkRefName(inputString: String?): ValidationInfo? = checkRefNameEmptyOrHead(inputString) ?: if (!GitRefNameValidator.getInstance().checkInput(inputString)) ValidationInfo(GitBundle.message("new.branch.dialog.error.branch.name.invalid", inputString)) else null fun checkRefNameEmptyOrHead(inputString: String?): ValidationInfo? = if (StringUtil.isEmptyOrSpaces(inputString)) ValidationInfo(GitBundle.message("new.branch.dialog.error.branch.name.empty")) else if (StringUtil.equalsIgnoreCase(inputString, HEAD)) ValidationInfo(GitBundle.message("new.branch.dialog.error.branch.name.head")) else null private fun checkBranchConflict(repositories: Collection<GitRepository>, inputString: String) = conflictsWithLocalBranch(repositories, inputString) ?: conflictsWithRemoteBranch(repositories, inputString) fun conflictsWithLocalBranch(repositories: Collection<GitRepository>, inputString: String): ValidationInfo? = conflictsWithLocalOrRemote(repositories, inputString, true, "new.branch.dialog.error.branch.already.exists") fun conflictsWithRemoteBranch(repositories: Collection<GitRepository>, inputString: String): ValidationInfo? = conflictsWithLocalOrRemote(repositories, inputString, false, "new.branch.dialog.error.branch.clashes.with.remote") fun conflictsWithLocalBranchDirectory(directories: Set<String>, inputString: String): ValidationInfo? { if (directories.contains(inputString)) { return ValidationInfo(GitBundle.message("new.branch.dialog.error.branch.clashes.with.directory", inputString)) } return null } private fun conflictsWithLocalOrRemote(repositories: Collection<GitRepository>, inputString: String, local: Boolean, @PropertyKey(resourceBundle = BUNDLE) message: String): ValidationInfo? { val reposWithConflictingBranch = getReposWithConflictingBranch(repositories, inputString, local) if (reposWithConflictingBranch.isEmpty()) return null var errorText = GitBundle.message(message, inputString) if (repositories.size > reposWithConflictingBranch.size) { errorText += getAdditionalDescription(reposWithConflictingBranch) if (local) return ValidationInfo(errorText).asWarning().withOKEnabled() } return ValidationInfo(errorText) } @Nls private fun getAdditionalDescription(repositories: List<GitRepository>) = " " + if (repositories.size > 1) GitBundle.message("common.suffix.in.several.repositories", repositories.size) else GitBundle.message("common.suffix.in.one.repository", getShortRepositoryName(repositories.first())) private fun getReposWithConflictingBranch(repositories: Collection<GitRepository>, inputString: String, local: Boolean): List<GitRepository> { return repositories.filter { repository -> findConflictingBranch(inputString, repository, local) != null } } private fun findConflictingBranch(inputString: String, repository: GitRepository, local: Boolean) = repository.branches.run { if (local) findLocalBranch(inputString) else findRemoteBranch(inputString) }
apache-2.0
d8632bb575f1bea2320cc51c528c5385
52.438356
140
0.771597
4.728485
false
false
false
false
cypressious/injekt
core/src/main/kotlin/uy/kohesive/injekt/registry/default/DefaultRegistrar.kt
1
7197
package uy.kohesive.injekt.registry.default import uy.kohesive.injekt.api.* import java.lang.reflect.Type import java.util.* import java.util.concurrent.ConcurrentHashMap /** * Default implementation of registry that uses ConcurrentHashMaps which have zero or few locks during reads, and work well * in a write little, read many model. Which is exactly our model. This stores the factories and the resulting instances * for cases that keep them around (Singletons, Per Key instances, Per Thread instances) */ public open class DefaultRegistrar : InjektRegistrar { private enum class FactoryType { SINGLETON, MULTI, MULTIKEYED, THREAD, THREADKEYED } private val NOKEY = object {} internal data class Instance(val forWhatType: Type, val forKey: Any) // Get with type checked key private fun <K: Any, V: Any> Map<K,V>.getByKey(key: K): V? = get(key) private val existingValues = ConcurrentHashMap<Instance, Any>() private val threadedValues = object : ThreadLocal<HashMap<Instance, Any>>() { override protected fun initialValue(): HashMap<Instance, Any> { return hashMapOf() } } private val factories = ConcurrentHashMap<Type, () -> Any>() private val keyedFactories = ConcurrentHashMap<Type, (Any) -> Any>() private val metadataForAddons = ConcurrentHashMap<String, Any>() internal data class LoggerInfo(val forWhatType: Type, val nameFactory: (String) -> Any, val classFactory: (Class<Any>) -> Any) private @Volatile var loggerFactory: LoggerInfo? = null // ==== Registry Methods by TypeReference ==================================================== override public fun <T : Any> addSingleton(forType: TypeReference<T>, singleInstance: T) { addSingletonFactory(forType, { singleInstance }) get<T>(forType) // load value into front cache } override public fun <R: Any> addSingletonFactory(forType: TypeReference<R>, factoryCalledOnce: () -> R) { factories.put(forType.type, { existingValues.concurrentGetOrPut(Instance(forType.type, NOKEY), { factoryCalledOnce() }) }) } override public fun <R: Any> addFactory(forType: TypeReference<R>, factoryCalledEveryTime: () -> R) { factories.put(forType.type, factoryCalledEveryTime) } override public fun <R: Any> addPerThreadFactory(forType: TypeReference<R>, factoryCalledOncePerThread: () -> R) { factories.put(forType.type, { threadedValues.get().getOrPut(Instance(forType.type, NOKEY), { factoryCalledOncePerThread() }) }) } @Suppress("UNCHECKED_CAST") override public fun <R: Any, K: Any> addPerKeyFactory(forType: TypeReference<R>, factoryCalledPerKey: (K) -> R) { keyedFactories.put(forType.type, { key -> existingValues.concurrentGetOrPut(Instance(forType.type, key), { factoryCalledPerKey(key as K) }) }) } @Suppress("UNCHECKED_CAST") override public fun <R: Any, K: Any> addPerThreadPerKeyFactory(forType: TypeReference<R>, factoryCalledPerKeyPerThread: (K) -> R) { keyedFactories.put(forType.type, { key -> threadedValues.get().getOrPut(Instance(forType.type, key), { factoryCalledPerKeyPerThread(key as K) }) }) } override public fun <R : Any> addLoggerFactory(forLoggerType: TypeReference<R>, factoryByName: (String) -> R, factoryByClass: (Class<Any>) -> R) { loggerFactory = LoggerInfo(forLoggerType.type, factoryByName, factoryByClass) } override public fun <O: Any, T: O> addAlias(existingRegisteredType: TypeReference<T>, otherAncestorOrInterface: TypeReference<O>) { // factories existing or not, and data type compatibility is checked in the InjektRegistrar interface default methods val existingFactory = factories.getByKey(existingRegisteredType.type) val existingKeyedFactory = keyedFactories.getByKey(existingRegisteredType.type) if (existingFactory != null) { factories.put(otherAncestorOrInterface.type, existingFactory) } if (existingKeyedFactory != null) { keyedFactories.put(otherAncestorOrInterface.type, existingKeyedFactory) } } override public fun <T: Any> hasFactory(forType: TypeReference<T>): Boolean { return factories.getByKey(forType.type) != null || keyedFactories.getByKey(forType.type) != null } // ==== Factory Methods ====================================================================== @Suppress("UNCHECKED_CAST") override public fun <R: Any> getInstance(forType: Type): R { val factory = factories.getByKey(forType) ?: throw InjektionException("No registered instance or factory for type ${forType}") return factory.invoke() as R } @Suppress("UNCHECKED_CAST") override public fun <R: Any> getInstanceOrElse(forType: Type, default: R): R { val factory = factories.getByKey(forType) ?: return default return factory.invoke() as R } @Suppress("UNCHECKED_CAST") override public fun <R: Any> getInstanceOrElse(forType: Type, default: ()->R): R { val factory = factories.getByKey(forType) ?: return default() return factory.invoke() as R } @Suppress("UNCHECKED_CAST") override public fun <R: Any, K: Any> getKeyedInstance(forType: Type, key: K): R { val factory = keyedFactories.getByKey(forType) ?: throw InjektionException("No registered keyed factory for type ${forType}") return factory.invoke(key) as R } @Suppress("UNCHECKED_CAST") override public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: R): R { val factory = keyedFactories.getByKey(forType) ?: return default return factory.invoke(key) as R } @Suppress("UNCHECKED_CAST") override public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: ()->R): R { val factory = keyedFactories.getByKey(forType) ?: return default() return factory.invoke(key) as R } private fun assertLogger(expectedLoggerType: Type) { if (loggerFactory == null) { throw InjektionException("Cannot call getLogger() -- A logger factory has not been registered with Injekt") } else if (!loggerFactory!!.forWhatType.erasedType().isAssignableFrom(expectedLoggerType.erasedType())) { throw InjektionException("Logger factories registered with Injekt indicate they return type ${loggerFactory!!.forWhatType} but current injekt target is expecting type ${expectedLoggerType}") } } @Suppress("UNCHECKED_CAST") override public fun <R: Any> getLogger(expectedLoggerType: Type, byName: String): R { assertLogger(expectedLoggerType) return loggerFactory!!.nameFactory(byName) as R // if casting to wrong type, let it die with casting exception } @Suppress("UNCHECKED_CAST") override public fun <R: Any, T: Any> getLogger(expectedLoggerType: Type, forClass: Class<T>): R { assertLogger(expectedLoggerType) return loggerFactory!!.classFactory(forClass.erasedType()) as R // if casting to wrong type, let it die with casting exception } }
mit
3fb977938ca88260bb413392dd4cbb29
45.134615
202
0.679589
4.396457
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/core/gui/common/UICheckbox.kt
1
2380
package com.replaymod.core.gui.common import com.replaymod.core.gui.utils.Resources import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.dsl.* import gg.essential.elementa.state.BasicState import gg.essential.elementa.state.toConstraint import gg.essential.elementa.utils.invisible import gg.essential.elementa.utils.withAlpha import gg.essential.universal.UMatrixStack import java.awt.Color class UICheckbox : UIComponent() { private val hovered = BasicState(false) private val enabled = BasicState(true) val checked = BasicState(false) var isChecked: Boolean get() = checked.get() set(value) = checked.set(value) private val checkmark by UITexture(Resources.icon("checkmark"), UITexture.TextureData.full()).constrain { x = CenterConstraint() y = CenterConstraint() width = 9.pixels height = 9.pixels color = checked.zip(enabled).map { (checked, enabled) -> if (enabled) { Color.WHITE.withAlpha(if (checked) 1f else 0f) } else { if (checked) Color.GRAY else Color.DARK_GRAY } }.toConstraint() } childOf this init { onMouseEnter { hovered.set(true) } onMouseLeave { hovered.set(false) } onMouseClick { if (!enabled.get()) return@onMouseClick UIButton.playClickSound() checked.set { !it } } constrain { width = 9.pixels height = 9.pixels color = Color.WHITE.invisible().toConstraint() } } override fun draw(matrixStack: UMatrixStack) { beforeDraw(matrixStack) val left = getLeft().toDouble() val right = getRight().toDouble() val top = getTop().toDouble() val bottom = getBottom().toDouble() // Outline val outlineColor = if (hovered.get() && enabled.get()) Color.WHITE else Color.BLACK UIBlock.drawBlock(matrixStack, outlineColor, left, top, right, bottom) // Background val backgroundColor = Color.DARK_GRAY.darker() UIBlock.drawBlock(matrixStack, backgroundColor, left + 1, top + 1, right - 1, bottom - 1) // Checkmark super.draw(matrixStack) } }
gpl-3.0
c3fd6938c481a2a3b5f3453b6b04b402
30.746667
109
0.639916
4.280576
false
false
false
false
JetBrains/xodus
entity-store/src/main/kotlin/jetbrains/exodus/entitystore/EntityIdCache.kt
1
1724
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.entitystore import jetbrains.exodus.core.dataStructures.ConcurrentObjectCache import java.util.regex.Pattern internal object EntityIdCache { private val ID_SPLIT_PATTERN = Pattern.compile("-") private val theCache = ConcurrentObjectCache<CharSequence, PersistentEntityId>( Integer.getInteger("jetbrains.exodus.entitystore.entityIdCacheSize", 997 * 3)) @JvmStatic fun getEntityId(representation: CharSequence): PersistentEntityId { var result = theCache.tryKey(representation) if (result == null) { val idParts = ID_SPLIT_PATTERN.split(representation) val partsCount = idParts.size if (partsCount != 2) { throw IllegalArgumentException("Invalid structure of entity id: $representation") } val entityTypeId = Integer.parseInt(idParts[0]) val entityLocalId = java.lang.Long.parseLong(idParts[1]) result = PersistentEntityId(entityTypeId, entityLocalId) theCache.cacheObject(representation, result) } return result } }
apache-2.0
ba973ca12bfa7f83fbea846056655afa
39.116279
97
0.702436
4.684783
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FlattenWhenIntention.kt
3
2795
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class FlattenWhenIntention : SelfTargetingIntention<KtWhenExpression>( KtWhenExpression::class.java, KotlinBundle.lazyMessage("flatten.when.expression") ) { override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean { val subject = element.subjectExpression if (subject != null && subject !is KtNameReferenceExpression) return false if (!KtPsiUtil.checkWhenExpressionHasSingleElse(element)) return false val elseEntry = element.entries.singleOrNull { it.isElse } ?: return false val innerWhen = elseEntry.expression as? KtWhenExpression ?: return false if (!subject.matches(innerWhen.subjectExpression)) return false if (!KtPsiUtil.checkWhenExpressionHasSingleElse(innerWhen)) return false return elseEntry.startOffset <= caretOffset && caretOffset <= innerWhen.whenKeyword.endOffset } override fun applyTo(element: KtWhenExpression, editor: Editor?) { val subjectExpression = element.subjectExpression val nestedWhen = element.elseExpression as KtWhenExpression val outerEntries = element.entries val innerEntries = nestedWhen.entries val whenExpression = KtPsiFactory(element).buildExpression { appendFixedText("when") if (subjectExpression != null) { appendFixedText("(").appendExpression(subjectExpression).appendFixedText(")") } appendFixedText("{\n") for (entry in outerEntries) { if (entry.isElse) continue appendNonFormattedText(entry.text) appendFixedText("\n") } for (entry in innerEntries) { appendNonFormattedText(entry.text) appendFixedText("\n") } appendFixedText("}") } as KtWhenExpression val newWhen = element.replaced(whenExpression) val firstNewEntry = newWhen.entries[outerEntries.size - 1] editor?.moveCaret(firstNewEntry.textOffset) } }
apache-2.0
d094c2d6f745eff1c8187114fe704815
40.716418
158
0.709481
5.14733
false
false
false
false
smmribeiro/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/EditorTabPainterAdapter.kt
1
2720
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ExperimentalUI import com.intellij.ui.tabs.JBTabPainter import java.awt.Graphics import java.awt.Graphics2D import java.awt.Rectangle class EditorTabPainterAdapter : TabPainterAdapter { private val magicOffset = 1 private val painter = JBEditorTabPainter() override val tabPainter: JBTabPainter get() = painter override fun paintBackground(label: TabLabel, g: Graphics, tabs: JBTabsImpl) { val info = label.info val isSelected = info == tabs.selectedInfo val isHovered = tabs.isHoveredTab(label) val rect = Rectangle(0, 0, label.width, label.height) val g2d = g as Graphics2D if (isSelected) { painter.paintSelectedTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), isHovered) paintBorders(g2d, label, tabs) } else { if (ExperimentalUI.isNewEditorTabs() && isHovered) { rect.height -= 1 } painter.paintTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), isHovered) paintBorders(g2d, label, tabs) } } private fun paintBorders(g: Graphics2D, label: TabLabel, tabs: JBTabsImpl) { val paintStandardBorder = !tabs.isSingleRow || (!tabs.position.isSide && Registry.`is`("ide.new.editor.tabs.vertical.borders")) val lastPinned = label.isLastPinned val nextToLastPinned = label.isNextToLastPinned val rect = Rectangle(0, 0, label.width, label.height) if (paintStandardBorder || lastPinned || nextToLastPinned) { val bounds = label.bounds if (bounds.x > magicOffset && (paintStandardBorder || nextToLastPinned)) { painter.paintLeftGap(tabs.position, g, rect, tabs.borderThickness) } if (bounds.x + bounds.width < tabs.width - magicOffset && (paintStandardBorder || lastPinned)) { painter.paintRightGap(tabs.position, g, rect, tabs.borderThickness) } } if (tabs.position.isSide && lastPinned) { val bounds = label.bounds if (bounds.y + bounds.height < tabs.height - magicOffset) { painter.paintBottomGap(tabs.position, g, rect, tabs.borderThickness) } } if (tabs.position.isSide && nextToLastPinned) { val bounds = label.bounds if (bounds.y + bounds.height < tabs.height - magicOffset) { painter.paintTopGap(tabs.position, g, rect, tabs.borderThickness) } } } }
apache-2.0
e9a85633bb873d6a5b553ff8ce702c87
36.273973
140
0.677206
3.959243
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinSourceFilterScope.kt
2
8599
// 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.stubindex import com.intellij.ide.highlighter.JavaClassFileType import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.DelegatingGlobalSearchScope import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.load.java.AbstractJavaClassFinder @Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode() class KotlinSourceFilterScope private constructor( delegate: GlobalSearchScope, private val includeProjectSourceFiles: Boolean, private val includeLibrarySourceFiles: Boolean, private val includeClassFiles: Boolean, private val includeScriptDependencies: Boolean, private val includeScriptsOutsideSourceRoots: Boolean, private val project: Project ) : DelegatingGlobalSearchScope(delegate) { private val index = ProjectRootManager.getInstance(project).fileIndex override fun getProject() = project override fun contains(file: VirtualFile): Boolean { if (myBaseScope is AbstractJavaClassFinder.FilterOutKotlinSourceFilesScope) { // KTIJ-20095: FilterOutKotlinSourceFilesScope optimization to avoid heavy file.fileType calculation val extension = file.extension val ktFile = when { file.isDirectory -> false extension == KotlinFileType.EXTENSION -> true extension == JavaFileType.DEFAULT_EXTENSION || extension == JavaClassFileType.INSTANCE.defaultExtension -> false else -> { val fileTypeByFileName = FileTypeRegistry.getInstance().getFileTypeByFileName(file.name) fileTypeByFileName == KotlinFileType.INSTANCE || fileTypeByFileName == FileTypes.UNKNOWN && FileTypeRegistry.getInstance().isFileOfType(file, KotlinFileType.INSTANCE) } } if (ktFile || !myBaseScope.base.contains(file)) return false } else if (!super.contains(file)) return false return ProjectRootsUtil.isInContent( project, file, includeProjectSourceFiles, includeLibrarySourceFiles, includeClassFiles, includeScriptDependencies, includeScriptsOutsideSourceRoots, index ) } override fun toString(): String { return "KotlinSourceFilterScope(delegate=$myBaseScope src=$includeProjectSourceFiles libSrc=$includeLibrarySourceFiles " + "cls=$includeClassFiles scriptDeps=$includeScriptDependencies scripts=$includeScriptsOutsideSourceRoots)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as KotlinSourceFilterScope if (includeProjectSourceFiles != other.includeProjectSourceFiles) return false if (includeLibrarySourceFiles != other.includeLibrarySourceFiles) return false if (includeClassFiles != other.includeClassFiles) return false if (includeScriptDependencies != other.includeScriptDependencies) return false if (project != other.project) return false return true } override fun calcHashCode(): Int { var result = super.calcHashCode() result = 31 * result + includeProjectSourceFiles.hashCode() result = 31 * result + includeLibrarySourceFiles.hashCode() result = 31 * result + includeClassFiles.hashCode() result = 31 * result + includeScriptDependencies.hashCode() result = 31 * result + project.hashCode() return result } companion object { @JvmStatic fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = true, includeLibrarySourceFiles = true, includeClassFiles = true, includeScriptDependencies = true, includeScriptsOutsideSourceRoots = true, project = project ) @JvmStatic fun sourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = true, includeLibrarySourceFiles = false, includeClassFiles = true, includeScriptDependencies = true, includeScriptsOutsideSourceRoots = true, project = project ) @JvmStatic fun projectSourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = true, includeLibrarySourceFiles = false, includeClassFiles = true, includeScriptDependencies = false, includeScriptsOutsideSourceRoots = true, project = project ) @JvmStatic fun projectSources(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = true, includeLibrarySourceFiles = false, includeClassFiles = false, includeScriptDependencies = false, includeScriptsOutsideSourceRoots = true, project = project ) @JvmStatic fun librarySources(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = false, includeLibrarySourceFiles = true, includeClassFiles = false, includeScriptDependencies = true, includeScriptsOutsideSourceRoots = false, project = project ) @JvmStatic fun libraryClassFiles(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = false, includeLibrarySourceFiles = false, includeClassFiles = true, includeScriptDependencies = true, includeScriptsOutsideSourceRoots = false, project = project ) @JvmStatic fun projectAndLibrariesSources(delegate: GlobalSearchScope, project: Project) = create( delegate, includeProjectSourceFiles = true, includeLibrarySourceFiles = true, includeClassFiles = false, includeScriptDependencies = true, includeScriptsOutsideSourceRoots = true, project = project ) private fun create( delegate: GlobalSearchScope, includeProjectSourceFiles: Boolean, includeLibrarySourceFiles: Boolean, includeClassFiles: Boolean, includeScriptDependencies: Boolean, includeScriptsOutsideSourceRoots: Boolean, project: Project ): GlobalSearchScope { if (delegate === GlobalSearchScope.EMPTY_SCOPE) return delegate if (delegate is KotlinSourceFilterScope) { return KotlinSourceFilterScope( delegate.myBaseScope, includeProjectSourceFiles = delegate.includeProjectSourceFiles && includeProjectSourceFiles, includeLibrarySourceFiles = delegate.includeLibrarySourceFiles && includeLibrarySourceFiles, includeClassFiles = delegate.includeClassFiles && includeClassFiles, includeScriptDependencies = delegate.includeScriptDependencies && includeScriptDependencies, includeScriptsOutsideSourceRoots = delegate.includeScriptsOutsideSourceRoots && includeScriptsOutsideSourceRoots, project = project ) } return KotlinSourceFilterScope( delegate, includeProjectSourceFiles, includeLibrarySourceFiles, includeClassFiles, includeScriptDependencies, includeScriptsOutsideSourceRoots, project ) } } }
apache-2.0
346254db14a55e06d917770cb9fb5a97
41.359606
158
0.662635
6.37908
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KDocRenderer.kt
2
28387
// 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.kdoc import com.intellij.codeInsight.documentation.DocumentationManagerUtil import com.intellij.lang.Language import com.intellij.lang.documentation.DocumentationMarkup.* import com.intellij.lang.documentation.DocumentationSettings import com.intellij.lang.documentation.DocumentationSettings.InlineCodeHighlightingMode import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.editor.richcopy.HtmlSyntaxInfoUtil import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.flavours.gfm.GFMElementTypes import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.flavours.gfm.GFMTokenTypes import org.intellij.markdown.parser.MarkdownParser import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors import org.jetbrains.kotlin.idea.highlighter.textAttributesKeyForKtElement import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.wrapTag import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink import org.jetbrains.kotlin.kdoc.psi.impl.KDocName import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType object KDocRenderer { fun StringBuilder.appendKDocContent(docComment: KDocTag): StringBuilder = append(markdownToHtml(docComment, allowSingleParagraph = true)) fun StringBuilder.appendKDocSections(sections: List<KDocSection>) { fun findTagsByName(name: String) = sequence { sections.forEach { yieldAll(it.findTagsByName(name)) } } fun findTagByName(name: String) = findTagsByName(name).firstOrNull() appendTag(findTagByName("receiver"), KotlinBundle.message("kdoc.section.title.receiver")) val paramTags = findTagsByName("param").filter { it.getSubjectName() != null } appendTagList(paramTags, KotlinBundle.message("kdoc.section.title.parameters"), KotlinHighlightingColors.PARAMETER) val propertyTags = findTagsByName("property").filter { it.getSubjectName() != null } appendTagList( propertyTags, KotlinBundle.message("kdoc.section.title.properties"), KotlinHighlightingColors.INSTANCE_PROPERTY ) appendTag(findTagByName("constructor"), KotlinBundle.message("kdoc.section.title.constructor")) appendTag(findTagByName("return"), KotlinBundle.message("kdoc.section.title.returns")) val throwTags = findTagsByName("throws").filter { it.getSubjectName() != null } val exceptionTags = findTagsByName("exception").filter { it.getSubjectName() != null } appendThrows(throwTags, exceptionTags) appendAuthors(findTagsByName("author")) appendTag(findTagByName("since"), KotlinBundle.message("kdoc.section.title.since")) appendTag(findTagByName("suppress"), KotlinBundle.message("kdoc.section.title.suppress")) appendSeeAlso(findTagsByName("see")) val sampleTags = findTagsByName("sample").filter { it.getSubjectLink() != null } appendSamplesList(sampleTags) } private fun StringBuilder.appendHyperlink(kDocLink: KDocLink) { if (DumbService.isDumb(kDocLink.project)) { append(kDocLink.getLinkText()) } else { DocumentationManagerUtil.createHyperlink( this, kDocLink.getLinkText(), highlightQualifiedName(kDocLink.getLinkText(), getTargetLinkElementAttributes(kDocLink.getTargetElement())), false, true ) } } private fun getTargetLinkElementAttributes(element: PsiElement?): TextAttributes { return element ?.let { textAttributesKeyForKtElement(it) } ?.let { getTargetLinkElementAttributes(it) } ?: TextAttributes().apply { foregroundColor = EditorColorsManager.getInstance().globalScheme.getColor(DefaultLanguageHighlighterColors.DOC_COMMENT_LINK) } } private fun getTargetLinkElementAttributes(key: TextAttributesKey): TextAttributes { return tuneAttributesForLink(EditorColorsManager.getInstance().globalScheme.getAttributes(key)) } private fun highlightQualifiedName(qualifiedName: String, lastSegmentAttributes: TextAttributes): String { val linkComponents = qualifiedName.split(".") val qualifiedPath = linkComponents.subList(0, linkComponents.lastIndex) val elementName = linkComponents.last() return buildString { for (pathSegment in qualifiedPath) { val segmentAttributes = when { pathSegment.isEmpty() || pathSegment.first().isLowerCase() -> DefaultLanguageHighlighterColors.IDENTIFIER else -> KotlinHighlightingColors.CLASS } appendStyledSpan(DocumentationSettings.isSemanticHighlightingOfLinksEnabled(), segmentAttributes, pathSegment) appendStyledSpan(DocumentationSettings.isSemanticHighlightingOfLinksEnabled(), KotlinHighlightingColors.DOT, ".") } appendStyledSpan(DocumentationSettings.isSemanticHighlightingOfLinksEnabled(), lastSegmentAttributes, elementName) } } private fun KDocLink.getTargetElement(): PsiElement? { return getChildrenOfType<KDocName>().last().mainReference.resolve() } private fun PsiElement.extractExampleText() = when (this) { is KtDeclarationWithBody -> { when (val bodyExpression = bodyExpression) { is KtBlockExpression -> bodyExpression.text.removeSurrounding("{", "}") else -> bodyExpression!!.text } } else -> text } private fun trimCommonIndent(text: String): String { fun String.leadingIndent() = indexOfFirst { !it.isWhitespace() } val lines = text.split('\n') val minIndent = lines.filter { it.trim().isNotEmpty() }.minOfOrNull(String::leadingIndent) ?: 0 return lines.joinToString("\n") { it.drop(minIndent) } } private fun StringBuilder.appendSection(title: String, content: StringBuilder.() -> Unit) { append(SECTION_HEADER_START, title, ":", SECTION_SEPARATOR) content() append(SECTION_END) } private fun StringBuilder.appendSamplesList(sampleTags: Sequence<KDocTag>) { if (!sampleTags.any()) return appendSection(KotlinBundle.message("kdoc.section.title.samples")) { sampleTags.forEach { it.getSubjectLink()?.let { subjectLink -> append("<p>") [email protected](subjectLink) wrapTag("pre") { wrapTag("code") { if (DumbService.isDumb(subjectLink.project)) { append("// " + KotlinBundle.message("kdoc.comment.unresolved")) } else { val codeSnippet = when (val target = subjectLink.getTargetElement()) { null -> "// " + KotlinBundle.message("kdoc.comment.unresolved") else -> trimCommonIndent(target.extractExampleText()).htmlEscape() } this@appendSamplesList.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( when (DocumentationSettings.isHighlightingOfCodeBlocksEnabled()) { true -> InlineCodeHighlightingMode.SEMANTIC_HIGHLIGHTING false -> InlineCodeHighlightingMode.NO_HIGHLIGHTING }, subjectLink.project, KotlinLanguage.INSTANCE, codeSnippet ) } } } } } } } private fun StringBuilder.appendSeeAlso(seeTags: Sequence<KDocTag>) { if (!seeTags.any()) return val iterator = seeTags.iterator() appendSection(KotlinBundle.message("kdoc.section.title.see.also")) { while (iterator.hasNext()) { val tag = iterator.next() val subjectName = tag.getSubjectName() val link = tag.getChildrenOfType<KDocLink>().lastOrNull() when { link != null -> this.appendHyperlink(link) subjectName != null -> DocumentationManagerUtil.createHyperlink(this, subjectName, subjectName, false, true) else -> append(tag.getContent()) } if (iterator.hasNext()) { append(",<br>") } } } } private fun StringBuilder.appendAuthors(authorTags: Sequence<KDocTag>) { if (!authorTags.any()) return val iterator = authorTags.iterator() appendSection(KotlinBundle.message("kdoc.section.title.author")) { while (iterator.hasNext()) { append(iterator.next().getContent()) if (iterator.hasNext()) { append(", ") } } } } private fun StringBuilder.appendThrows(throwsTags: Sequence<KDocTag>, exceptionsTags: Sequence<KDocTag>) { if (!throwsTags.any() && !exceptionsTags.any()) return appendSection(KotlinBundle.message("kdoc.section.title.throws")) { fun KDocTag.append() { val subjectName = getSubjectName() if (subjectName != null) { append("<p><code>") val highlightedLinkLabel = highlightQualifiedName(subjectName, getTargetLinkElementAttributes(KotlinHighlightingColors.CLASS)) DocumentationManagerUtil.createHyperlink(this@appendSection, subjectName, highlightedLinkLabel, false, true) append("</code>") val exceptionDescription = markdownToHtml(this) if (exceptionDescription.isNotBlank()) { append(" - $exceptionDescription") } } } throwsTags.forEach { it.append() } exceptionsTags.forEach { it.append() } } } private fun StringBuilder.appendTagList(tags: Sequence<KDocTag>, title: String, titleAttributes: TextAttributesKey) { if (!tags.any()) { return } appendSection(title) { tags.forEach { val subjectName = it.getSubjectName() if (subjectName != null) { append("<p><code>") when (val link = it.getChildrenOfType<KDocLink>().firstOrNull()) { null -> appendStyledSpan(DocumentationSettings.isSemanticHighlightingOfLinksEnabled(), titleAttributes, subjectName) else -> appendHyperlink(link) } append("</code>") val elementDescription = markdownToHtml(it) if (elementDescription.isNotBlank()) { append(" - $elementDescription") } } } } } private fun StringBuilder.appendTag(tag: KDocTag?, title: String) { if (tag != null) { appendSection(title) { append(markdownToHtml(tag)) } } } private fun markdownToHtml(comment: KDocTag, allowSingleParagraph: Boolean = false): String { val markdownTree = MarkdownParser(GFMFlavourDescriptor()).buildMarkdownTreeFromString(comment.getContent()) val markdownNode = MarkdownNode(markdownTree, null, comment) // Avoid wrapping the entire converted contents in a <p> tag if it's just a single paragraph val maybeSingleParagraph = markdownNode.children.singleOrNull { it.type != MarkdownTokenTypes.EOL } val firstParagraphOmitted = when { maybeSingleParagraph != null && !allowSingleParagraph -> { maybeSingleParagraph.children.joinToString("") { if (it.text == "\n") " " else it.toHtml() } } else -> markdownNode.toHtml() } val topMarginOmitted = when { firstParagraphOmitted.startsWith("<p>") -> firstParagraphOmitted.replaceFirst("<p>", "<p style='margin-top:0;padding-top:0;'>") else -> firstParagraphOmitted } return topMarginOmitted } class MarkdownNode(val node: ASTNode, val parent: MarkdownNode?, val comment: KDocTag) { val children: List<MarkdownNode> = node.children.map { MarkdownNode(it, this, comment) } val endOffset: Int get() = node.endOffset val startOffset: Int get() = node.startOffset val type: IElementType get() = node.type val text: String get() = comment.getContent().substring(startOffset, endOffset) fun child(type: IElementType): MarkdownNode? = children.firstOrNull { it.type == type } } private fun MarkdownNode.visit(action: (MarkdownNode, () -> Unit) -> Unit) { action(this) { for (child in children) { child.visit(action) } } } private fun MarkdownNode.toHtml(): String { if (node.type == MarkdownTokenTypes.WHITE_SPACE) { return text // do not trim trailing whitespace } var currentCodeFenceLang = "kotlin" val sb = StringBuilder() visit { node, processChildren -> fun wrapChildren(tag: String, newline: Boolean = false) { sb.append("<$tag>") processChildren() sb.append("</$tag>") if (newline) sb.appendLine() } val nodeType = node.type val nodeText = node.text when (nodeType) { MarkdownElementTypes.UNORDERED_LIST -> wrapChildren("ul", newline = true) MarkdownElementTypes.ORDERED_LIST -> wrapChildren("ol", newline = true) MarkdownElementTypes.LIST_ITEM -> wrapChildren("li") MarkdownElementTypes.EMPH -> wrapChildren("em") MarkdownElementTypes.STRONG -> wrapChildren("strong") GFMElementTypes.STRIKETHROUGH -> wrapChildren("del") MarkdownElementTypes.ATX_1 -> wrapChildren("h1") MarkdownElementTypes.ATX_2 -> wrapChildren("h2") MarkdownElementTypes.ATX_3 -> wrapChildren("h3") MarkdownElementTypes.ATX_4 -> wrapChildren("h4") MarkdownElementTypes.ATX_5 -> wrapChildren("h5") MarkdownElementTypes.ATX_6 -> wrapChildren("h6") MarkdownElementTypes.BLOCK_QUOTE -> wrapChildren("blockquote") MarkdownElementTypes.PARAGRAPH -> { sb.trimEnd() wrapChildren("p", newline = true) } MarkdownElementTypes.CODE_SPAN -> { val startDelimiter = node.child(MarkdownTokenTypes.BACKTICK)?.text if (startDelimiter != null) { val text = node.text.substring(startDelimiter.length).removeSuffix(startDelimiter) sb.append("<code style='font-size:${DocumentationSettings.getMonospaceFontSizeCorrection(true)}%;'>") sb.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( DocumentationSettings.getInlineCodeHighlightingMode(), comment.project, KotlinLanguage.INSTANCE, text ) sb.append("</code>") } } MarkdownElementTypes.CODE_BLOCK, MarkdownElementTypes.CODE_FENCE -> { sb.trimEnd() sb.append("<pre><code style='font-size:${DocumentationSettings.getMonospaceFontSizeCorrection(true)}%;'>") processChildren() sb.append("</code></pre>") } MarkdownTokenTypes.FENCE_LANG -> { currentCodeFenceLang = nodeText } MarkdownElementTypes.SHORT_REFERENCE_LINK, MarkdownElementTypes.FULL_REFERENCE_LINK -> { val linkLabelNode = node.child(MarkdownElementTypes.LINK_LABEL) val linkLabelContent = linkLabelNode?.children ?.dropWhile { it.type == MarkdownTokenTypes.LBRACKET } ?.dropLastWhile { it.type == MarkdownTokenTypes.RBRACKET } if (linkLabelContent != null) { val label = linkLabelContent.joinToString(separator = "") { it.text } val linkText = node.child(MarkdownElementTypes.LINK_TEXT)?.toHtml() ?: label if (DumbService.isDumb(comment.project)) { sb.append(linkText) } else { comment.findDescendantOfType<KDocName> { it.text == label } ?.mainReference ?.resolve() ?.let { resolvedLinkElement -> DocumentationManagerUtil.createHyperlink( sb, label, highlightQualifiedName(linkText, getTargetLinkElementAttributes(resolvedLinkElement)), false, true ) } ?: sb.appendStyledSpan(true, KotlinHighlightingColors.RESOLVED_TO_ERROR, label) } } else { sb.append(node.text) } } MarkdownElementTypes.INLINE_LINK -> { val label = node.child(MarkdownElementTypes.LINK_TEXT)?.toHtml() val destination = node.child(MarkdownElementTypes.LINK_DESTINATION)?.text if (label != null && destination != null) { sb.append("<a href=\"$destination\">$label</a>") } else { sb.append(node.text) } } MarkdownTokenTypes.TEXT, MarkdownTokenTypes.WHITE_SPACE, MarkdownTokenTypes.COLON, MarkdownTokenTypes.SINGLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.LPAREN, MarkdownTokenTypes.RPAREN, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET, MarkdownTokenTypes.EXCLAMATION_MARK, GFMTokenTypes.CHECK_BOX, GFMTokenTypes.GFM_AUTOLINK -> { sb.append(nodeText) } MarkdownTokenTypes.CODE_LINE, MarkdownTokenTypes.CODE_FENCE_CONTENT -> { sb.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( when (DocumentationSettings.isHighlightingOfCodeBlocksEnabled()) { true -> InlineCodeHighlightingMode.SEMANTIC_HIGHLIGHTING false -> InlineCodeHighlightingMode.NO_HIGHLIGHTING }, comment.project, guessLanguage(currentCodeFenceLang) ?: KotlinLanguage.INSTANCE, nodeText ) } MarkdownTokenTypes.EOL -> { val parentType = node.parent?.type if (parentType == MarkdownElementTypes.CODE_BLOCK || parentType == MarkdownElementTypes.CODE_FENCE) { sb.append("\n") } else { sb.append(" ") } } MarkdownTokenTypes.GT -> sb.append("&gt;") MarkdownTokenTypes.LT -> sb.append("&lt;") MarkdownElementTypes.LINK_TEXT -> { val childrenWithoutBrackets = node.children.drop(1).dropLast(1) for (child in childrenWithoutBrackets) { sb.append(child.toHtml()) } } MarkdownTokenTypes.EMPH -> { val parentNodeType = node.parent?.type if (parentNodeType != MarkdownElementTypes.EMPH && parentNodeType != MarkdownElementTypes.STRONG) { sb.append(node.text) } } GFMTokenTypes.TILDE -> { if (node.parent?.type != GFMElementTypes.STRIKETHROUGH) { sb.append(node.text) } } GFMElementTypes.TABLE -> { val alignment: List<String> = getTableAlignment(node) var addedBody = false sb.append("<table>") for (child in node.children) { if (child.type == GFMElementTypes.HEADER) { sb.append("<thead>") processTableRow(sb, child, "th", alignment) sb.append("</thead>") } else if (child.type == GFMElementTypes.ROW) { if (!addedBody) { sb.append("<tbody>") addedBody = true } processTableRow(sb, child, "td", alignment) } } if (addedBody) { sb.append("</tbody>") } sb.append("</table>") } else -> { processChildren() } } } return sb.toString().trimEnd() } private fun StringBuilder.trimEnd() { while (length > 0 && this[length - 1] == ' ') { deleteCharAt(length - 1) } } private fun String.htmlEscape(): String = replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") private fun processTableRow(sb: StringBuilder, node: MarkdownNode, cellTag: String, alignment: List<String>) { sb.append("<tr>") for ((i, child) in node.children.filter { it.type == GFMTokenTypes.CELL }.withIndex()) { val alignValue = alignment.getOrElse(i) { "" } val alignTag = if (alignValue.isEmpty()) "" else " align=\"$alignValue\"" sb.append("<$cellTag$alignTag>") sb.append(child.toHtml()) sb.append("</$cellTag>") } sb.append("</tr>") } private fun getTableAlignment(node: MarkdownNode): List<String> { val separatorRow = node.child(GFMTokenTypes.TABLE_SEPARATOR) ?: return emptyList() return separatorRow.text.split('|').filterNot { it.isBlank() }.map { val trimmed = it.trim() val left = trimmed.startsWith(':') val right = trimmed.endsWith(':') if (left && right) "center" else if (right) "right" else if (left) "left" else "" } } private fun StringBuilder.appendStyledSpan(doHighlighting: Boolean, attributesKey: TextAttributesKey, value: String?): StringBuilder { if (doHighlighting) { HtmlSyntaxInfoUtil.appendStyledSpan(this, attributesKey, value, DocumentationSettings.getHighlightingSaturation(true)) } else { append(value) } return this } private fun StringBuilder.appendStyledSpan(doHighlighting: Boolean, attributes: TextAttributes, value: String?): StringBuilder { if (doHighlighting) { HtmlSyntaxInfoUtil.appendStyledSpan(this, attributes, value, DocumentationSettings.getHighlightingSaturation(true)) } else { append(value) } return this } private fun StringBuilder.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( highlightingMode: InlineCodeHighlightingMode, project: Project, language: Language, codeSnippet: String ): StringBuilder { val codeSnippetBuilder = StringBuilder() if (highlightingMode == InlineCodeHighlightingMode.SEMANTIC_HIGHLIGHTING) { // highlight code by lexer HtmlSyntaxInfoUtil.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( codeSnippetBuilder, project, language, codeSnippet, false, DocumentationSettings.getHighlightingSaturation(true) ) } else { codeSnippetBuilder.append(StringUtil.escapeXmlEntities(codeSnippet)) } if (highlightingMode != InlineCodeHighlightingMode.NO_HIGHLIGHTING) { // set code text color as editor default code color instead of doc component text color val codeAttributes = EditorColorsManager.getInstance().globalScheme.getAttributes(HighlighterColors.TEXT).clone() codeAttributes.backgroundColor = null appendStyledSpan(true, codeAttributes, codeSnippetBuilder.toString()) } else { append(codeSnippetBuilder.toString()) } return this } /** * If highlighted links has the same color as highlighted inline code blocks they will be indistinguishable. * In this case we should change link color to standard hyperlink color which we believe is apriori different. */ private fun tuneAttributesForLink(attributes: TextAttributes): TextAttributes { val globalScheme = EditorColorsManager.getInstance().globalScheme if (attributes.foregroundColor == globalScheme.getAttributes(HighlighterColors.TEXT).foregroundColor || attributes.foregroundColor == globalScheme.getAttributes(DefaultLanguageHighlighterColors.IDENTIFIER).foregroundColor ) { val tuned = attributes.clone() if (ApplicationManager.getApplication().isUnitTestMode) { tuned.foregroundColor = globalScheme.getAttributes(CodeInsightColors.HYPERLINK_ATTRIBUTES).foregroundColor } else { tuned.foregroundColor = globalScheme.getColor(DefaultLanguageHighlighterColors.DOC_COMMENT_LINK) } return tuned } return attributes } private fun guessLanguage(name: String): Language? { val lower = StringUtil.toLowerCase(name) return Language.findLanguageByID(lower) ?: Language.getRegisteredLanguages().firstOrNull { StringUtil.toLowerCase(it.id) == lower } } }
apache-2.0
434cfab46237d6c2467c69d0f7be7c56
44.933657
158
0.582978
5.515252
false
false
false
false
milkcan/effortless-prefs
sample/src/main/java/io/milkcan/effortlessprefs/sample/MainActivity.kt
1
2893
package io.milkcan.effortlessprefs.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.TextUtils import com.pixplicity.easyprefs.sample.R import io.milkcan.effortlessandroid.toast import io.milkcan.effortlessprefs.library.Prefs import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object { private const val SAVED_TEXT: String = "saved_text" private const val SAVED_NUMBER: String = "saved_number" private const val FROM_INSTANCE_STATE: String = " : from instance state" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get the saved String from the preference by key, and give a default value // if Prefs does not contain the key. val s = Prefs.getString(SAVED_TEXT, getString(R.string.not_found)) val d = Prefs.getDouble(SAVED_NUMBER, -1.0) updateText(s) updateNumber(d, false) bt_save_text.setOnClickListener { val text = et_text?.text.toString() if (!TextUtils.isEmpty(text)) { // one liner to save the String. Prefs.putString(SAVED_TEXT, text) updateText(text) } else { toast("Trying to save a text with length 0") } } bt_save_number.setOnClickListener { val d = java.lang.Double.parseDouble(et_number?.text.toString()) Prefs.putDouble(SAVED_NUMBER, d) updateNumber(d, false) } bt_force_close.setOnClickListener { finish() } } private fun updateText(s: String?) { val text = String.format(getString(R.string.saved_text), s) tv_saved_text?.text = text } private fun updateNumber(d: Double, fromInstanceState: Boolean) { val text = String.format(getString(R.string.saved_number), d.toString(), if (fromInstanceState) FROM_INSTANCE_STATE else "") tv_saved_number?.text = text } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val text = et_text?.text.toString() if (!TextUtils.isEmpty(text)) { outState.putString(SAVED_TEXT, text) } val d = java.lang.Double.parseDouble(et_number?.text.toString()) outState.putDouble(SAVED_NUMBER, d) } override fun onRestoreInstanceState(state: Bundle) { super.onRestoreInstanceState(state) if (state.containsKey(SAVED_TEXT)) { val text = state.getString(SAVED_TEXT)!! + FROM_INSTANCE_STATE updateText(text) } if (state.containsKey(SAVED_NUMBER)) { val d = state.getDouble(SAVED_NUMBER) updateNumber(d, true) } } }
apache-2.0
6af4f26ccf6f302d8a252ab476dbf3ae
34.292683
132
0.636018
4.223358
false
false
false
false
mr-max/anko
dsl/src/org/jetbrains/android/anko/utils/ClassTree.kt
2
4170
/* * 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.utils import org.objectweb.asm.tree.ClassNode import java.util.* class NoSuchClassException : Exception() class ClassTreeNode(parent: ClassTreeNode?, val data: ClassNode, val fromPlatformJar: Boolean) { var parent = parent var children: MutableList<ClassTreeNode> = ArrayList() } class ClassTree : Iterable<ClassNode>{ private val root = ClassTreeNode(null, ClassNode(), true) override fun iterator(): ClassTreeIterator { return ClassTreeIterator(root) } public fun add(clazz: ClassNode, fromMainJar: Boolean) { val parent = findNode(root, clazz.superName) val orphans = getOrphansOf(clazz.name) val newNode: ClassTreeNode if (parent != null) { newNode = ClassTreeNode(parent, clazz, fromMainJar) parent.children.add(newNode) } else { newNode = ClassTreeNode(root, clazz, fromMainJar) root.children.add(newNode) } newNode.children.addAll(orphans) orphans.forEach { it.parent = newNode } } public fun isChildOf(clazz: ClassNode, ancestorName: String): Boolean { val treeNode = findNode(root, clazz) ?: throw NoSuchClassException() return treeNode.parent?.data?.name == ancestorName } public fun isSuccessorOf(clazz: ClassNode, ancestorName: String): Boolean { val parent = findNode(ancestorName) ?: throw NoSuchClassException() val child = findNode(parent, clazz.name) return child != null && child != parent } private fun getOrphansOf(parentClassName: String): List<ClassTreeNode> { val res = root.children.partition { it.data.superName == parentClassName } root.children = res.second as MutableList<ClassTreeNode> return res.first } private fun findNode(node: ClassTreeNode, name: String?): ClassTreeNode? { for (child in node.children) { if (child.data.name == name) { return child } else { val ret = findNode(child, name) if (ret != null) return ret } } return null } private fun findNode(node: ClassTreeNode, parentPackage: String, className: String): ClassTreeNode? { for (child in node.children) { val childName = child.data.name if (childName.startsWith(parentPackage) && childName.endsWith(className)) { return child } else { val ret = findNode(child, parentPackage, className) if (ret != null) return ret } } return null } public fun findNode(parentPackage: String, className: String): ClassTreeNode? { return findNode(root, "$parentPackage/", "/$className") } public fun findNode(name: String): ClassTreeNode? { return findNode(root, name) } public fun findNode(clazz: ClassNode): ClassTreeNode? { return findNode(root, clazz.name) } private fun findNode(node: ClassTreeNode, clazz: ClassNode): ClassTreeNode? { return findNode(node, clazz.name) } } class ClassTreeIterator(var next: ClassTreeNode) : Iterator<ClassNode> { var nodeQueue: Queue<ClassTreeNode> = ArrayDeque(next.children) override fun next(): ClassNode { val node: ClassTreeNode = nodeQueue.element() nodeQueue.remove() nodeQueue.addAll(node.children) return node.data } override fun hasNext(): Boolean { return !nodeQueue.isEmpty() } }
apache-2.0
78b610469290e68dcb162434619d1d81
31.585938
105
0.648681
4.56736
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/testFramework/src/com/intellij/util/io/impl/DirectoryContentSpecImpl.kt
3
5726
/* * 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.util.io.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.io.DirectoryContentBuilder import com.intellij.util.io.DirectoryContentSpec import com.intellij.util.io.ZipUtil import org.junit.Assert.* import java.io.BufferedOutputStream import java.io.File import java.io.IOException import java.util.* import java.util.zip.ZipOutputStream /** * @author nik */ sealed class DirectoryContentSpecImpl : DirectoryContentSpec { } abstract class DirectorySpecBase : DirectoryContentSpecImpl() { protected val children = LinkedHashMap<String, DirectoryContentSpecImpl>() fun addChild(name: String, spec: DirectoryContentSpecImpl) { if (name in children) { val existing = children[name] if (spec is DirectorySpecBase && existing is DirectorySpecBase) { existing.children += spec.children return } throw IllegalArgumentException("'$name' already exists") } children[name] = spec } protected fun generateInDirectory(target: File) { for ((name, child) in children) { child.generate(File(target, name)) } } override fun generateInTempDir(): File { val target = FileUtil.createTempDirectory("directory-by-spec", null, true) generate(target) return target } fun getChildren() : Map<String, DirectoryContentSpecImpl> = Collections.unmodifiableMap(children) } class DirectorySpec : DirectorySpecBase() { override fun generate(target: File) { if (!FileUtil.createDirectory(target)) { throw IOException("Cannot create directory $target") } generateInDirectory(target) } } class ZipSpec : DirectorySpecBase() { override fun generate(target: File) { val contentDir = FileUtil.createTempDirectory("zip-content", null, false) try { generateInDirectory(contentDir) ZipOutputStream(BufferedOutputStream(target.outputStream())).use { ZipUtil.addDirToZipRecursively(it, null, contentDir, "", null, null) } } finally { FileUtil.delete(contentDir) } } } class FileSpec(val content: ByteArray?) : DirectoryContentSpecImpl() { override fun generate(target: File) { FileUtil.writeToFile(target, content ?: ByteArray(0)) } override fun generateInTempDir(): File { val target = FileUtil.createTempFile("file-by-spec", null, true) generate(target) return target } } class DirectoryContentBuilderImpl(val result: DirectorySpecBase) : DirectoryContentBuilder() { override fun addChild(name: String, spec: DirectoryContentSpecImpl) { result.addChild(name, spec) } override fun file(name: String) { addChild(name, FileSpec(null)) } override fun file(name: String, text: String) { file(name, text.toByteArray()) } override fun file(name: String, content: ByteArray) { addChild(name, FileSpec(content)) } } fun assertDirectoryContentMatches(file: File, spec: DirectoryContentSpecImpl, relativePath: String) { when (spec) { is DirectorySpec -> { assertDirectoryMatches(file, spec, relativePath) } is ZipSpec -> { val dirForExtracted = FileUtil.createTempDirectory("extracted-${file.name}", null, false) ZipUtil.extract(file, dirForExtracted, null) assertDirectoryMatches(dirForExtracted, spec, relativePath) FileUtil.delete(dirForExtracted) } is FileSpec -> { assertTrue("$file is not a file", file.isFile) if (spec.content != null) { val actualBytes = FileUtil.loadFileBytes(file) if (!Arrays.equals(actualBytes, spec.content)) { val actualString = actualBytes.convertToText() val expectedString = spec.content.convertToText() val place = if (relativePath != "") " at $relativePath" else "" if (actualString != null && expectedString != null) { assertEquals("File content mismatch$place:", expectedString, actualString) } else { fail("Binary file content mismatch$place") } } } } } } private fun ByteArray.convertToText(): String? { val encoding = CharsetToolkit(this, Charsets.UTF_8).guessFromContent(size) val charset = when (encoding) { CharsetToolkit.GuessedEncoding.SEVEN_BIT -> Charsets.US_ASCII CharsetToolkit.GuessedEncoding.VALID_UTF8 -> Charsets.UTF_8 else -> return null } return String(this, charset) } private fun assertDirectoryMatches(file: File, spec: DirectorySpecBase, relativePath: String) { assertTrue("$file is not a directory", file.isDirectory) val actualChildrenNames = file.list().sortedWith(String.CASE_INSENSITIVE_ORDER) val children = spec.getChildren() val expectedChildrenNames = children.keys.sortedWith(String.CASE_INSENSITIVE_ORDER) assertEquals("Directory content mismatch${if (relativePath != "") " at $relativePath" else ""}:", expectedChildrenNames.joinToString("\n"), actualChildrenNames.joinToString("\n")) actualChildrenNames.forEach { child -> assertDirectoryContentMatches(File(file, child), children[child]!!, "$relativePath/$child") } }
apache-2.0
f747a5dd3ee2424d1ed2a62e8eefdb50
32.48538
101
0.709046
4.469945
false
false
false
false