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
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/overview/LawnchairOverviewActionsView.kt
1
3214
package app.lawnchair.overview import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.Button import android.widget.LinearLayout import android.widget.Space import androidx.core.view.ViewCompat import androidx.core.view.isVisible import app.lawnchair.preferences.PreferenceManager import app.lawnchair.util.isOnePlusStock import com.android.launcher3.R import com.android.quickstep.views.OverviewActionsView class LawnchairOverviewActionsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : OverviewActionsView<TaskOverlayFactoryImpl.OverlayUICallbacks>(context, attrs, defStyleAttr) { private val prefs = PreferenceManager.getInstance(context) private lateinit var container: LinearLayout private lateinit var screenshotAction: Button private lateinit var shareAction: Button private lateinit var lensAction: Button private lateinit var clearAllAction: Button override fun onFinishInflate() { super.onFinishInflate() container = ViewCompat.requireViewById(this, R.id.action_buttons) clearAllAction = ViewCompat.requireViewById(this, R.id.action_clear_all) shareAction = ViewCompat.requireViewById(this, R.id.action_share) lensAction = ViewCompat.requireViewById(this, R.id.action_lens) screenshotAction = ViewCompat.requireViewById(this, R.id.action_screenshot) shareAction.setOnClickListener { mCallbacks?.onShare() } lensAction.setOnClickListener { mCallbacks?.onLens() } prefs.recentsActionClearAll.subscribeChanges(this, ::updateVisibilities) prefs.recentsActionLens.subscribeChanges(this, ::updateVisibilities) prefs.recentsActionScreenshot.subscribeChanges(this, ::updateVisibilities) prefs.recentsActionShare.subscribeChanges(this, ::updateVisibilities) updateVisibilities() } private fun updateVisibilities() { val buttons = mutableListOf<View>() if (prefs.recentsActionScreenshot.get() && !isOnePlusStock) { buttons.add(screenshotAction) } if (prefs.recentsActionShare.get()) { buttons.add(shareAction) } if (prefs.recentsActionLens.get()) { val lensIntent = context.packageManager.getLaunchIntentForPackage("com.google.ar.lens") val lensAvailable = lensIntent != null if (lensAvailable) { buttons.add(lensAction) } } if (prefs.recentsActionClearAll.get()) { buttons.add(clearAllAction) } container.removeAllViews() container.addView(createSpace()) buttons.forEach { view -> view.isVisible = true container.addView(view) container.addView(createSpace()) } } private fun createSpace(): View { return Space(context).apply { layoutParams = LinearLayout.LayoutParams(0, 1).apply { weight = 1f } } } override fun setClearAllClickListener(clearAllClickListener: OnClickListener?) { clearAllAction.setOnClickListener(clearAllClickListener) } }
gpl-3.0
2ac5589497b22da273f11b2893d94f9e
36.372093
99
0.706907
4.891933
false
false
false
false
JimSeker/ui
RecyclerViews/CallBacksDemo_kt/app/src/main/java/edu/cs4730/callbacksdemo_kt/MainActivity.kt
1
2153
package edu.cs4730.callbacksdemo_kt import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar /* * This is a simple demo of how to get data from an recyclerview demo all the way back to the * mainactivity. * * Another interesting idea would be to just use a handler that is sent to * the adapter and then calls it (where it is declared here). It's not implemented here, just * stated as another possibility. */ class MainActivity : AppCompatActivity(), MainFragment.OntransInteractionCallback { var TAG = "MainActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val fab = findViewById<FloatingActionButton>(R.id.fab) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId return if (id == R.id.action_settings) { true } else super.onOptionsItemSelected(item) } override fun ontransInteraction(item: String) { Log.v(TAG, "Callback at $TAG") Toast.makeText(this, "MainActivity Received $item", Toast.LENGTH_LONG).show() } }
apache-2.0
9f4e324b9158c5cee6dbce827cc31fd2
38.145455
94
0.706456
4.504184
false
false
false
false
google/evergreen-checker
evergreen/src/main/java/app/evergreen/config/EvergreenConfig.kt
1
1847
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 app.evergreen.config import app.evergreen.config.Kind.APK import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter import java.util.* @JsonClass(generateAdapter = true) data class EvergreenConfig( val updatables: List<Updatable> ) { fun toCompactString() = updatables.joinToString(separator = "\n") { "${it.id ?: it.kind}: ${it.latestProd?.versionName}" } companion object { fun moshiAdapter(): JsonAdapter<EvergreenConfig> = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .build() .adapter(EvergreenConfig::class.java) .indent(" ") .lenient() } } @JsonClass(generateAdapter = true) data class Updatable( /** Nullable because Kind.OTA and Kind.REMOTE_FIRMWARE do not need an ID. */ var id: String? = null, var kind: Kind = APK, var latestAlpha: Version? = null, var latestBeta: Version? = null, var latestProd: Version? = null, ) enum class Kind { APK, SYSTEM_BUILD, REMOTE_FIRMWARE } @JsonClass(generateAdapter = true) data class Version( val versionName: String? = null, val releaseDate: Date? = null, val minSdkVersion: Int? = null )
apache-2.0
4c2a6a9d61568ee479003032757128f9
28.790323
102
0.721711
3.808247
false
true
false
false
msebire/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/lValueUtil.kt
1
1857
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("GroovyLValueUtil") package org.jetbrains.plugins.groovy.lang.psi.util import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.POSTFIX_UNARY_OP_SET import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.api.UnknownArgument /** * The expression is a rValue when it is in rValue position or it's a lValue of operator assignment. */ fun GrExpression.isRValue(): Boolean { val (parent, lastParent) = skipParentsOfType<GrParenthesizedExpression>() ?: return true return parent !is GrAssignmentExpression || lastParent != parent.lValue || parent.isOperatorAssignment } /** * The expression is a lValue when it's on the left of whatever assignment. */ fun GrExpression.isLValue(): Boolean { val parent = parent return when (parent) { is GrTuple -> true is GrAssignmentExpression -> this == parent.lValue is GrUnaryExpression -> parent.operationTokenType in POSTFIX_UNARY_OP_SET else -> false } } /** * @return non-null result iff this expression is an l-value */ fun GrExpression.getRValue(): Argument? { val parent = parent return when { parent is GrTuple -> UnknownArgument parent is GrAssignmentExpression && parent.lValue === this -> { if (parent.isOperatorAssignment) { ExpressionArgument(parent) } else { parent.rValue?.let(::ExpressionArgument) ?: UnknownArgument } } parent is GrUnaryExpression && parent.operationTokenType in POSTFIX_UNARY_OP_SET -> ExpressionArgument(parent) else -> null } }
apache-2.0
c15a8300f395604edfd5464c8359d9dd
35.411765
140
0.738288
4.308585
false
false
false
false
wseemann/RoMote
app/src/main/kotlin/wseemann/media/remote/fragment/SearchDialog.kt
1
1845
package wseemann.media.romote.fragment import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import androidx.fragment.app.DialogFragment import wseemann.media.romote.R class SearchDialog : DialogFragment() { companion object { var listener: SearchDialogListener? = null fun newInstance(activity: Activity): SearchDialog { listener = activity as SearchDialogListener return SearchDialog() } } interface SearchDialogListener { fun onSearch(searchText: String) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreateDialog(savedInstanceState) val inflater = activity!!.layoutInflater var view: View = inflater.inflate(R.layout.dialog_fragment_search, null) var searchEditText: EditText = view.findViewById<EditText>(R.id.ip_address_text) var cancelButton: Button = view.findViewById<Button>(R.id.cancel_button) var searchButton: Button = view.findViewById<Button>(R.id.connect_button) cancelButton.setOnClickListener { dismiss() } searchButton.setOnClickListener { var searchText: EditText = searchEditText var searchListener: SearchDialogListener? = listener if (searchListener != null) { searchListener.onSearch(searchText.text.toString()) } dismiss() } var builder: AlertDialog.Builder = AlertDialog.Builder(activity) builder.setView(view) builder.setTitle(getString(R.string.action_search)) //builder.setMessage(getString(R.string.search_help)) return builder.create() } }
apache-2.0
2650f8e0f6b37f4cd940bfc950644ea7
29.75
88
0.682927
4.92
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/util/ExtensionFuncs.kt
1
21988
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.util import android.app.PendingIntent import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Configuration import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.net.ConnectivityManager import android.net.Network import android.net.Uri import android.net.wifi.WifiManager import android.os.Build import android.util.DisplayMetrics import android.util.Log import android.util.TypedValue import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.StringRes import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.preference.PreferenceManager import com.caverock.androidsvg.SVG import es.dmoral.toasty.Toasty import java.io.EOFException import java.io.IOException import java.io.InputStream import java.net.ConnectException import java.net.Socket import java.net.SocketTimeoutException import java.net.UnknownHostException import java.security.cert.CertPathValidatorException import java.security.cert.CertificateExpiredException import java.security.cert.CertificateNotYetValidException import java.security.cert.CertificateRevokedException import javax.jmdns.ServiceInfo import javax.net.ssl.SSLException import javax.net.ssl.SSLHandshakeException import javax.net.ssl.SSLPeerUnverifiedException import kotlin.math.max import kotlin.math.round import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.MediaType import okhttp3.ResponseBody import org.json.JSONArray import org.json.JSONObject import org.openhab.habdroid.R import org.openhab.habdroid.core.OpenHabApplication import org.openhab.habdroid.model.ServerConfiguration import org.openhab.habdroid.model.ServerPath import org.openhab.habdroid.model.ServerProperties import org.openhab.habdroid.util.Util.TAG import org.w3c.dom.Node import org.w3c.dom.NodeList fun Throwable?.hasCause(cause: Class<out Throwable>): Boolean { var error = this while (error != null) { if (error::class.java == cause) { return true } error = error.cause } return false } /** * Replaces everything after the first clearTextCharCount chars with asterisks * @param clearTextCharCount leave the first clearTextCharCount in clear text * @return obfuscated string */ fun String.obfuscate(clearTextCharCount: Int = 3): String { if (length < clearTextCharCount) { return this } return substring(0, clearTextCharCount) + "*".repeat(length - clearTextCharCount) } fun String?.toNormalizedUrl(): String? { if (isNullOrEmpty()) { return null } return try { val url = this .replace("\n", "") .replace(" ", "") .toHttpUrl() .toString() if (url.endsWith("/")) url else "$url/" } catch (e: IllegalArgumentException) { Log.d(TAG, "toNormalizedUrl(): Invalid URL '$this'") null } } fun String?.orDefaultIfEmpty(defaultValue: String) = if (isNullOrEmpty()) defaultValue else this fun Uri?.openInBrowser(context: Context) { if (this == null) { return } val intent = Intent(Intent.ACTION_VIEW, this) try { context.startActivity(intent) } catch (e: ActivityNotFoundException) { Log.d(TAG, "Unable to open url in browser: $intent") context.showToast(R.string.error_no_browser_found, ToastType.ERROR) } } fun HttpUrl.toRelativeUrl(): String { val base = resolve("/") return this.toString().substring(base.toString().length - 1) } /** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into * pixels * @return A float value to represent px equivalent to dp depending on device density * @author https://stackoverflow.com/a/9563438 */ fun Resources.dpToPixel(dp: Float): Float { return dp * displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT } enum class ImageConversionPolicy { PreferSourceSize, PreferTargetSize, ForceTargetSize } @Throws(IOException::class) fun ResponseBody.toBitmap(targetSize: Int, conversionPolicy: ImageConversionPolicy): Bitmap { if (!contentType().isSvg()) { val bitmap = BitmapFactory.decodeStream(byteStream()) ?: throw IOException( "Bitmap with decoding failed: content type: ${contentType()}, length: ${contentLength()}" ) // Avoid overly huge bitmaps, as we both do not want their memory consumption and drawing those bitmaps // to a canvas will fail later anyway. The actual limitation threshold is more or less arbitrary; as of // Android 10 the OS side limit is 100 MB. return if (bitmap.byteCount > 20000000 && bitmap.width > targetSize) { val scaler = bitmap.width.toFloat() / targetSize.toFloat() val scaledHeight = bitmap.height.toFloat() / scaler Bitmap.createScaledBitmap(bitmap, targetSize, scaledHeight.toInt(), true) } else if (conversionPolicy == ImageConversionPolicy.ForceTargetSize) { Bitmap.createScaledBitmap(bitmap, targetSize, targetSize, true) } else { bitmap } } return byteStream().svgToBitmap(targetSize, conversionPolicy) } fun MediaType?.isSvg(): Boolean { return this != null && this.type == "image" && this.subtype.contains("svg") } @Throws(IOException::class) fun InputStream.svgToBitmap(targetSize: Int, conversionPolicy: ImageConversionPolicy): Bitmap { return try { val svg = SVG.getFromInputStream(this) val displayMetrics = Resources.getSystem().displayMetrics var density: Float? = displayMetrics.density val targetSizeFloat = targetSize.toFloat() if (svg.documentViewBox == null && svg.documentWidth > 0 && svg.documentHeight > 0) { svg.setDocumentViewBox(0F, 0F, svg.documentWidth, svg.documentHeight) } if (conversionPolicy == ImageConversionPolicy.ForceTargetSize || (conversionPolicy == ImageConversionPolicy.PreferTargetSize && svg.documentViewBox != null) ) { svg.setDocumentWidth("100%") svg.setDocumentHeight("100%") } svg.renderDPI = DisplayMetrics.DENSITY_DEFAULT.toFloat() var docWidth = svg.documentWidth * displayMetrics.density var docHeight = svg.documentHeight * displayMetrics.density if (docWidth < 0 || docHeight < 0) { val aspectRatio = svg.documentAspectRatio if (aspectRatio > 0) { val heightForAspect = targetSizeFloat / aspectRatio val widthForAspect = targetSizeFloat * aspectRatio if (widthForAspect < heightForAspect) { docWidth = widthForAspect docHeight = targetSizeFloat } else { docWidth = targetSizeFloat docHeight = heightForAspect } } else { docWidth = targetSizeFloat docHeight = targetSizeFloat } // we didn't take density into account anymore when calculating docWidth // and docHeight, so don't scale with it and just let the renderer // figure out the scaling density = null } if (docWidth > targetSizeFloat || docHeight > targetSizeFloat) { val widthScaler = max(1F, docWidth / targetSizeFloat) val heightScaler = max(1F, docHeight / targetSizeFloat) val scaler = max(widthScaler, heightScaler) docWidth /= scaler docHeight /= scaler if (density != null) { density /= scaler } } val bitmap = Bitmap.createBitmap(round(docWidth).toInt(), round(docHeight).toInt(), Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) if (density != null) { canvas.scale(density, density) } svg.renderToCanvas(canvas) bitmap } catch (e: Exception) { throw IOException("SVG decoding failed", e) } } fun NodeList.forEach(action: (Node) -> Unit) = (0 until length).forEach { index -> action(item(index)) } fun JSONArray.forEach(action: (JSONObject) -> Unit) = (0 until length()).forEach { index -> action(getJSONObject(index)) } inline fun <T> JSONArray.map(transform: (JSONObject) -> T): List<T> { return (0 until length()).map { index -> transform(getJSONObject(index)) } } inline fun <T> JSONArray.mapString(transform: (String) -> T): List<T> { return (0 until length()).map { index -> transform(getString(index)) } } fun JSONObject.optDoubleOrNull(key: String): Double? { return if (has(key)) getDouble(key) else null } fun JSONObject.optBooleanOrNull(key: String): Boolean? { return if (has(key)) getBoolean(key) else null } fun JSONObject.optStringOrNull(key: String): String? { return optStringOrFallback(key, null) } fun JSONObject.optStringOrFallback(key: String, fallback: String?): String? { return if (has(key)) getString(key) else fallback } fun Context.getPrefs(): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(this) } fun Context.getSecretPrefs(): SharedPreferences { return (applicationContext as OpenHabApplication).secretPrefs } enum class ToastType { NORMAL, SUCCESS, ERROR } /** * Shows an Toast with the openHAB icon. Can be called from the background. */ fun Context.showToast(message: CharSequence, type: ToastType = ToastType.NORMAL) { val color = when (type) { ToastType.SUCCESS -> R.color.pref_icon_green ToastType.ERROR -> R.color.pref_icon_red else -> R.color.openhab_orange } val length = if (type == ToastType.ERROR) Toast.LENGTH_LONG else Toast.LENGTH_SHORT GlobalScope.launch(Dispatchers.Main) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Toast.makeText(this@showToast, message, length).show() } else { Toasty.custom( applicationContext, message, R.drawable.ic_openhab_appicon_24dp, color, length, true, true ).show() } } } /** * Shows an Toast with the openHAB icon. Can be called from the background. */ fun Context.showToast(@StringRes message: Int, type: ToastType = ToastType.NORMAL) { showToast(getString(message), type) } fun Context.hasPermissions(permissions: Array<String>) = permissions.firstOrNull { ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED } == null fun Context.getHumanReadableErrorMessage(url: String, httpCode: Int, error: Throwable?, short: Boolean): CharSequence { return if (error.hasCause(UnknownHostException::class.java)) { getString( if (short) R.string.error_short_unable_to_resolve_hostname else R.string.error_unable_to_resolve_hostname) } else if (error.hasCause(CertificateExpiredException::class.java)) { getString(if (short) R.string.error_short_certificate_expired else R.string.error_certificate_expired) } else if (error.hasCause(CertificateNotYetValidException::class.java)) { getString( if (short) R.string.error_short_certificate_not_valid_yet else R.string.error_certificate_not_valid_yet) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && error.hasCause(CertificateRevokedException::class.java)) { getString(if (short) R.string.error_short_certificate_revoked else R.string.error_certificate_revoked) } else if (error.hasCause(SSLPeerUnverifiedException::class.java)) { getString( if (short) R.string.error_short_certificate_wrong_host else R.string.error_certificate_wrong_host, url.toHttpUrlOrNull()?.host ) } else if (error.hasCause(CertPathValidatorException::class.java)) { getString(if (short) R.string.error_short_certificate_not_trusted else R.string.error_certificate_not_trusted) } else if (error.hasCause(SSLException::class.java) || error.hasCause(SSLHandshakeException::class.java)) { getString(if (short) R.string.error_short_connection_sslhandshake_failed else R.string.error_connection_sslhandshake_failed) } else if (error.hasCause(ConnectException::class.java) || error.hasCause(SocketTimeoutException::class.java)) { getString(if (short) R.string.error_short_connection_failed else R.string.error_connection_failed) } else if (error.hasCause(IOException::class.java) && error.hasCause(EOFException::class.java)) { getString(if (short) R.string.error_short_http_to_https_port else R.string.error_http_to_https_port) } else if (httpCode >= 400) { if (error?.message == "openHAB is offline") { getString(if (short) R.string.error_short_openhab_offline else R.string.error_openhab_offline) } else { try { val resName = if (short) "error_short_http_code_$httpCode" else "error_http_code_$httpCode" getString(resources.getIdentifier(resName, "string", packageName), httpCode) } catch (e: Resources.NotFoundException) { getString( if (short) R.string.error_short_http_connection_failed else R.string.error_http_connection_failed, httpCode ) } } } else { error.let { Log.e(TAG, "REST call to $url failed", it) } getString(if (short) R.string.error_short_unknown else R.string.error_unknown, error?.localizedMessage) } } fun Context.openInAppStore(app: String) { val intent = Intent(Intent.ACTION_VIEW, "market://details?id=$app".toUri()) try { startActivity(intent) } catch (e: ActivityNotFoundException) { "http://play.google.com/store/apps/details?id=$app".toUri().openInBrowser(this) } } data class DataUsagePolicy( val canDoLargeTransfers: Boolean, val loadIconsWithState: Boolean, val autoPlayVideos: Boolean, val canDoRefreshes: Boolean ) fun Context.determineDataUsagePolicy(): DataUsagePolicy { val isBatterySaverActive = (applicationContext as OpenHabApplication).batterySaverActive fun getDataUsagePolicyForBatterySaver() = DataUsagePolicy( canDoLargeTransfers = true, loadIconsWithState = true, autoPlayVideos = false, canDoRefreshes = false ) val dataSaverPref = getPrefs().getBoolean(PrefKeys.DATA_SAVER, false) if (dataSaverPref || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return if (isBatterySaverActive) { getDataUsagePolicyForBatterySaver() } else { DataUsagePolicy(!dataSaverPref, !dataSaverPref, !dataSaverPref, !dataSaverPref) } } return when ((applicationContext as OpenHabApplication).systemDataSaverStatus) { ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED -> DataUsagePolicy( canDoLargeTransfers = false, loadIconsWithState = false, autoPlayVideos = false, canDoRefreshes = false ) ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED -> { if (isBatterySaverActive) { getDataUsagePolicyForBatterySaver() } else { DataUsagePolicy( canDoLargeTransfers = true, loadIconsWithState = true, autoPlayVideos = false, canDoRefreshes = true ) } } else -> { if (isBatterySaverActive) { getDataUsagePolicyForBatterySaver() } else { DataUsagePolicy( canDoLargeTransfers = true, loadIconsWithState = true, autoPlayVideos = true, canDoRefreshes = true ) } } } } @ColorInt fun Context.resolveThemedColor(@AttrRes colorAttr: Int, @ColorInt fallbackColor: Int = 0): Int { val tv = TypedValue() theme.resolveAttribute(colorAttr, tv, true) return if (tv.type >= TypedValue.TYPE_FIRST_COLOR_INT && tv.type <= TypedValue.TYPE_LAST_COLOR_INT) { tv.data } else { fallbackColor } } @ColorRes fun Context.resolveThemedColorToResource(@AttrRes colorAttr: Int, @ColorRes fallbackColorRes: Int = 0): Int { val ta = obtainStyledAttributes(intArrayOf(colorAttr)) return ta.getResourceId(0, fallbackColorRes).also { ta.recycle() } } fun Context.getChartTheme(serverFlags: Int): CharSequence { val tv = TypedValue() if (serverFlags and ServerProperties.SERVER_FLAG_TRANSPARENT_CHARTS == 0) { theme.resolveAttribute(R.attr.chartTheme, tv, true) } else { theme.resolveAttribute(R.attr.transparentChartTheme, tv, true) } return tv.string } fun Context.isDarkModeActive(): Boolean { return when (getPrefs().getDayNightMode(this)) { AppCompatDelegate.MODE_NIGHT_NO -> false AppCompatDelegate.MODE_NIGHT_YES -> true else -> { val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK currentNightMode != Configuration.UI_MODE_NIGHT_NO } } } @StyleRes fun Context.getActivityThemeId(): Int { val isBlackTheme = getPrefs().getStringOrNull(PrefKeys.THEME) == getString(R.string.theme_value_black) return when (getPrefs().getInt(PrefKeys.ACCENT_COLOR, 0)) { ContextCompat.getColor(this, R.color.indigo_500) -> if (isBlackTheme) R.style.openHAB_Black_basicui else R.style.openHAB_DayNight_basicui ContextCompat.getColor(this, R.color.blue_grey_700) -> if (isBlackTheme) R.style.openHAB_Black_grey else R.style.openHAB_DayNight_grey else -> if (isBlackTheme) R.style.openHAB_Black_orange else R.style.openHAB_DayNight_orange } } fun Context.getCurrentWifiSsid(attributionTag: String): String? { val wifiManager = getWifiManager(attributionTag) // TODO: Replace deprecated function @Suppress("DEPRECATION") return wifiManager.connectionInfo.let { info -> if (info.networkId == -1) null else info.ssid.removeSurrounding("\"") } } fun Context.withAttribution(tag: String): Context { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { createAttributionContext(tag) } else { this } } fun Context.getWifiManager(attributionTag: String): WifiManager { // Android < N requires applicationContext for getting WifiManager, otherwise leaks may occur val context = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { applicationContext } else { withAttribution(attributionTag) } return context.getSystemService(Context.WIFI_SERVICE) as WifiManager } fun Socket.bindToNetworkIfPossible(network: Network?) { try { network?.bindSocket(this) } catch (e: IOException) { Log.d(TAG, "Binding socket $this to network $network failed: $e") } } fun Uri.Builder.appendQueryParameter(key: String, value: Int): Uri.Builder { return appendQueryParameter(key, value.toString()) } fun Uri.Builder.appendQueryParameter(key: String, value: Boolean): Uri.Builder { return appendQueryParameter(key, value.toString()) } fun ServiceInfo.addToPrefs(context: Context) { val address = hostAddresses[0] val port = port.toString() Log.d(TAG, "Service resolved: $address port: $port") val config = ServerConfiguration( context.getPrefs().getNextAvailableServerId(), context.getString(R.string.openhab), ServerPath("https://$address:$port", null, null), null, null, null, null, false ) config.saveToPrefs(context.getPrefs(), context.getSecretPrefs()) } /** * Removes trailing `.0` from float */ fun Float.beautify() = if (this == this.toInt().toFloat()) this.toInt().toString() else this.toString() fun Menu.getGroupItems(groupId: Int): List<MenuItem> { return (0 until size()) .map { index -> getItem(index) } .filter { item -> item.groupId == groupId } } fun PackageManager.isInstalled(app: String): Boolean { return try { // Some devices return `null` for getApplicationInfo() @Suppress("UNNECESSARY_SAFE_CALL", "SAFE_CALL_WILL_CHANGE_NULLABILITY", "SimplifyBooleanWithConstants") getApplicationInfo(app, 0)?.enabled == true } catch (e: PackageManager.NameNotFoundException) { false } } val PendingIntent_Immutable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE } else { 0 } val PendingIntent_Mutable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_MUTABLE } else { 0 }
epl-1.0
a31f94aef8208fc94992a79b4aeedc84
35.769231
119
0.67696
4.409064
false
false
false
false
damien5314/HoldTheNarwhal
app/src/main/java/com/ddiehl/android/htn/subredditinfo/SubredditRulesAdapter.kt
1
3501
package com.ddiehl.android.htn.subredditinfo import android.text.Spannable import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView import com.ddiehl.android.htn.R import com.ddiehl.android.htn.subredditinfo.SubredditRulesAdapter.VH.Companion.LAYOUT_RES_ID import com.ddiehl.android.htn.view.markdown.HtmlParser import com.ddiehl.android.htn.view.text.CenteredRelativeSizeSpan import rxreddit.model.SubredditRule class SubredditRulesAdapter( private val htmlParser: HtmlParser ) : RecyclerView.Adapter<SubredditRulesAdapter.VH>() { private val rules: MutableList<SubredditRule> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(LAYOUT_RES_ID, parent, false) return VH(view, htmlParser) } override fun getItemCount() = rules.size override fun onBindViewHolder(holder: VH, position: Int) { val subredditRule = rules[position] holder.bind(subredditRule) } fun setRules(rules: List<SubredditRule>) { this.rules.addAll(rules) } class VH( itemView: View, private val htmlParser: HtmlParser ) : RecyclerView.ViewHolder(itemView) { companion object { @LayoutRes val LAYOUT_RES_ID = R.layout.subreddit_rule } private val shortNameView = itemView.findViewById<TextView>(R.id.short_name) private val categoryView = itemView.findViewById<TextView>(R.id.category) private val descriptionView = itemView.findViewById<TextView>(R.id.description) fun bind(rule: SubredditRule) { val positionString = " ${adapterPosition + 1} " val shortName = rule.shortName val ruleString = SpannableStringBuilder().apply { val positionSpannable = SpannableString(positionString).apply { val proportion = 0.60f setSpan(CenteredRelativeSizeSpan(proportion), 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } append(positionSpannable) append(shortName) } shortNameView.text = ruleString val category = rule.kind categoryView.setText(getTextForCategory(category)) val descriptionHtml = rule.descriptionHtml if (descriptionHtml != null) { val description = descriptionHtml.trim { it <= ' ' } val parsedDescription = htmlParser.convert(description) descriptionView.setText(parsedDescription) descriptionView.setMovementMethod(LinkMovementMethod.getInstance()) } } private fun getTextForCategory(category: String): String { return when (category) { "link" -> itemView.context.getString(R.string.subreddit_category_link) "comment" -> itemView.context.getString(R.string.subreddit_category_comment) "all" -> itemView.context.getString(R.string.subreddit_category_all) else -> itemView.context.getString(R.string.subreddit_category_all) } } } }
apache-2.0
ecfd77f9a9a57d60d51df92941d0005f
38.337079
112
0.67495
4.835635
false
false
false
false
rock3r/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/IteratorNotThrowingNoSuchElementException.kt
1
2974
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtThrowExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.findFunctionByName import org.jetbrains.kotlin.psi.psiUtil.getSuperNames /** * Reports implementations of the `Iterator` interface which do not throw a NoSuchElementException in the * implementation of the next() method. When there are no more elements to return an Iterator should throw a * NoSuchElementException. * * See: https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next() * * <noncompliant> * class MyIterator : Iterator<String> { * * override fun next(): String { * return "" * } * } * </noncompliant> * * <compliant> * class MyIterator : Iterator<String> { * * override fun next(): String { * if (!this.hasNext()) { * throw NoSuchElementException() * } * // ... * } * } * </compliant> * * @active since v1.2.0 */ class IteratorNotThrowingNoSuchElementException(config: Config = Config.empty) : Rule(config) { override val issue = Issue("IteratorNotThrowingNoSuchElementException", Severity.Defect, "The next() method of an Iterator implementation should throw a NoSuchElementException " + "when there are no more elements to return", Debt.TEN_MINS) override fun visitClassOrObject(classOrObject: KtClassOrObject) { if (classOrObject.getSuperNames().contains("Iterator")) { val nextMethod = classOrObject.findFunctionByName("next") if (nextMethod != null && !nextMethod.throwsNoSuchElementExceptionThrown()) { report(CodeSmell(issue, Entity.atName(classOrObject), "This implementation of Iterator does not correctly implement the next() method as " + "it doesn't throw a NoSuchElementException when no elements remain in the Iterator.")) } } super.visitClassOrObject(classOrObject) } private fun KtNamedDeclaration.throwsNoSuchElementExceptionThrown() = anyDescendantOfType<KtThrowExpression> { isNoSuchElementExpression(it) } private fun isNoSuchElementExpression(expression: KtThrowExpression): Boolean { val calleeExpression = (expression.thrownExpression as? KtCallExpression)?.calleeExpression return calleeExpression?.text == "NoSuchElementException" } }
apache-2.0
563fb465fe96d6e1734f0b3a9a26f8e8
39.189189
118
0.7115
4.654147
false
true
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/ui/events/EventEditActivity.kt
1
7530
/* * Copyright 2017 Farbod Salamat-Zadeh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.timetableapp.ui.events import android.app.Activity import android.content.Intent import android.support.design.widget.Snackbar import android.support.v4.app.ActivityCompat import android.support.v7.app.AlertDialog import android.widget.EditText import co.timetableapp.R import co.timetableapp.TimetableApplication import co.timetableapp.data.handler.EventHandler import co.timetableapp.model.Color import co.timetableapp.model.Event import co.timetableapp.model.Subject import co.timetableapp.ui.base.ItemEditActivity import co.timetableapp.ui.components.DateSelectorHelper import co.timetableapp.ui.components.SubjectSelectorHelper import co.timetableapp.ui.components.TimeSelectorHelper import co.timetableapp.ui.subjects.SubjectEditActivity import co.timetableapp.util.UiUtils import co.timetableapp.util.title import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime /** * Allows the user to edit an [Event] * * @see ItemEditActivity */ class EventEditActivity : ItemEditActivity<Event>() { companion object { private val REQUEST_CODE_SUBJECT_DETAIL = 2 } private val mDataHandler = EventHandler(this) private lateinit var mEditTextTitle: EditText private lateinit var mEditTextDetail: EditText private lateinit var mEditTextLocation: EditText private lateinit var mEventDate: LocalDate private lateinit var mDateHelper: DateSelectorHelper private lateinit var mStartTime: LocalTime private lateinit var mStartTimeHelper: TimeSelectorHelper private lateinit var mEndTime: LocalTime private lateinit var mEndTimeHelper: TimeSelectorHelper private var mSubject: Subject? = null private lateinit var mSubjectHelper: SubjectSelectorHelper override fun getLayoutResource() = R.layout.activity_event_edit override fun getTitleRes(isNewItem: Boolean) = if (isNewItem) { R.string.title_activity_event_new } else { R.string.title_activity_event_edit } override fun setupLayout() { mEditTextTitle = findViewById(R.id.editText_title) as EditText if (!mIsNew) { mEditTextTitle.setText(mItem!!.title) } mEditTextDetail = findViewById(R.id.editText_detail) as EditText if (!mIsNew) { mEditTextDetail.setText(mItem!!.notes) } mEditTextLocation = findViewById(R.id.editText_location) as EditText if (!mIsNew) { mEditTextLocation.setText(mItem!!.location) } setupSubjectHelper() setupDateText() setupTimeTexts() } private fun setupSubjectHelper() { mSubjectHelper = SubjectSelectorHelper(this, R.id.textView_subject) mSubjectHelper.onCreateNewSubject { _, _ -> val intent = Intent(this, SubjectEditActivity::class.java) ActivityCompat.startActivityForResult( this, intent, REQUEST_CODE_SUBJECT_DETAIL, null ) } mSubjectHelper.onSubjectChange { mSubject = it val color: Color if (it == null) { color = Event.DEFAULT_COLOR } else { color = Color(it.colorId) } UiUtils.setBarColors( color, this@EventEditActivity, mToolbar!!, findViewById(R.id.appBarLayout), findViewById(R.id.toolbar_container) ) } mSubjectHelper.setup(mItem?.getRelatedSubject(this), true) } private fun setupDateText() { mEventDate = mItem?.startDateTime?.toLocalDate() ?: LocalDate.now() mDateHelper = DateSelectorHelper(this, R.id.textView_date) mDateHelper.setup(mEventDate) { _, date -> mEventDate = date mDateHelper.updateDate(mEventDate) } } private fun setupTimeTexts() { val defaultStart = LocalTime.of(LocalTime.now().hour + 1, 0) // the next hour from now mStartTime = mItem?.startDateTime?.toLocalTime() ?: defaultStart mEndTime = mItem?.endDateTime?.toLocalTime() ?: defaultStart.plusHours(1) mStartTimeHelper = TimeSelectorHelper(this, R.id.textView_start_time) mStartTimeHelper.setup(mStartTime) { _, time -> mStartTime = time mStartTimeHelper.updateTime(mStartTime) } mEndTimeHelper = TimeSelectorHelper(this, R.id.textView_end_time) mEndTimeHelper.setup(mEndTime) { _, time -> mEndTime = time mEndTimeHelper.updateTime(mEndTime) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_SUBJECT_DETAIL) { if (resultCode == Activity.RESULT_OK) { mSubject = data.getParcelableExtra<Subject>(ItemEditActivity.EXTRA_ITEM) mSubjectHelper.updateSubject(mSubject) } } } override fun handleDoneAction() { var newTitle = mEditTextTitle.text.toString() newTitle = newTitle.title() val newDetail = mEditTextDetail.text.toString().trim { it <= ' ' } val newLocation = mEditTextLocation.text.toString().trim { it <= ' ' } if (newTitle.trim { it <= ' ' }.isEmpty()) { Snackbar.make(findViewById(R.id.rootView), R.string.message_title_required, Snackbar.LENGTH_SHORT).show() return } val id = if (mIsNew) mDataHandler.getHighestItemId() + 1 else mItem!!.id val timetableId = (application as TimetableApplication).currentTimetable!!.id mItem = Event( id, timetableId, newTitle, newDetail, LocalDateTime.of(mEventDate, mStartTime), LocalDateTime.of(mEventDate, mEndTime), newLocation, if (mSubject == null) 0 else mSubject!!.id ) if (mIsNew) { mDataHandler.addItem(mItem!!) } else { mDataHandler.replaceItem(mItem!!.id, mItem!!) } val intent = Intent() setResult(Activity.RESULT_OK, intent) supportFinishAfterTransition() } override fun handleDeleteAction() { AlertDialog.Builder(this) .setTitle(R.string.delete_exam) .setMessage(R.string.delete_confirmation) .setPositiveButton(R.string.action_delete) { _, _ -> mDataHandler.deleteItem(mItem!!.id) setResult(Activity.RESULT_OK) finish() } .setNegativeButton(R.string.action_cancel, null) .show() } }
apache-2.0
87755b323301e339aa4f9219e8a114f7
32.171806
94
0.638247
4.826923
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/data/MimeTypeHelper.kt
1
1014
package me.shkschneider.skeleton.data object MimeTypeHelper { const val FILE = "file/*" const val TEXT = "text/*" const val TEXT_PLAIN = "text/plain" const val TEXT_HTML = "text/html" const val TEXT_XML = "text/xml" const val APPLICATION = "application/*" const val APPLICATION_FORMURLENCODED = "application/x-www-form-urlencoded" const val APPLICATION_OCTETSTREAM = "application/octet-stream" const val APPLICATION_PDF = "application/pdf" const val APPLICATION_JSON = "application/json" const val APPLICATION_XML = "application/xml" const val APPLICATION_ZIP = "application/zip" const val IMAGE = "image/*" const val IMAGE_GIF = "image/gif" const val IMAGE_JPEG = "image/jpeg" const val IMAGE_PNG = "image/png" const val AUDIO = "audio/*" const val VIDEO = "video/*" // <https://stackoverflow.com/a/28652339/603270> @Deprecated("Do not send MIME type for unknown data.") const val UNKNOWN = "application/octet-stream" }
apache-2.0
b193e2385e28903ed661b9cad3ea582f
29.727273
78
0.679487
3.840909
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/pipeline/LegacyProtocolHandler.kt
1
9733
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.pipeline import io.netty.buffer.ByteBuf import io.netty.channel.ChannelFutureListener import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelInboundHandlerAdapter import org.apache.logging.log4j.Logger import org.lanternpowered.api.cause.causeOf import org.lanternpowered.server.event.LanternEventFactory import org.lanternpowered.api.text.serializer.LegacyTextSerializer import org.lanternpowered.api.text.toPlain import org.lanternpowered.api.text.toText import org.lanternpowered.api.text.translatableTextOf import org.lanternpowered.server.LanternServer import org.lanternpowered.server.game.Lantern import org.lanternpowered.server.game.version.LanternMinecraftVersion import org.lanternpowered.server.network.NetworkSession import org.lanternpowered.server.network.SimpleRemoteConnection import org.lanternpowered.server.network.status.LanternStatusClient import org.lanternpowered.server.network.status.LanternStatusHelper import org.lanternpowered.server.network.status.LanternStatusResponse import java.net.InetSocketAddress import java.nio.charset.StandardCharsets class LegacyProtocolHandler(private val session: NetworkSession) : ChannelInboundHandlerAdapter() { private val server: LanternServer get() = this.session.server private val logger: Logger get() = this.session.server.logger override fun channelRead(ctx: ChannelHandlerContext, buf: Any) { buf as ByteBuf val server = this.session.server buf.markReaderIndex() // Whether it was a valid legacy message var legacy = false try { val messageId = buf.readUnsignedByte().toInt() // Old client's are not so smart, make sure that // they don't attempt to login if (messageId == 0x02) { val protocol = buf.readByte().toInt() // Protocol version var value = buf.readShort().toInt() // Check the length if (value < 0 || value > 16) return buf.readBytes(value shl 1) // Username value = buf.readShort().toInt() // Check the length if (value < 0 || value > 255) return buf.readBytes(value shl 1) // Host address buf.readInt() // Port if (buf.readableBytes() > 0) return legacy = true ctx.disconnect(translatableTextOf("multiplayer.disconnect.outdated_client", this.server.platform.minecraftVersion.name.toText()).toPlain()) val clientVersion = this.server.game.minecraftVersionCache.getVersionOrUnknown(protocol, true) if (clientVersion === LanternMinecraftVersion.UNKNOWN_LEGACY) { this.logger.debug( "Client with unknown legacy protocol version $protocol attempted to join the server.") } else { this.logger.debug( "Client with legacy protocol version $protocol (mc-version ${clientVersion.name}) attempted to join the server.") } return } // Check for the ping message id. if (messageId != 0xfe) return var readable = buf.readableBytes() var full = false // The version used to ping the server var protocol = V1_3_2_PROTOCOL // Versions 1.4 - 1.5.x + 1.6 - Can request full data. if (readable > 0) { // Is always 1 if (buf.readUnsignedByte().toInt() != 1) return full = true protocol = V1_5_2_PROTOCOL } // The virtual address that was used to join the server var virtualAddress: InetSocketAddress? = null // Version 1.6 - Used extra data. if (readable > 1) { if (buf.readUnsignedByte().toInt() != 0xfa) return var bytes = ByteArray(buf.readShort().toInt() shl 1) buf.readBytes(bytes) if (String(bytes, StandardCharsets.UTF_16BE) != "MC|PingHost") return // Not used buf.readShort() // The protocol version is present protocol = buf.readUnsignedByte().toInt() // There is extra host and port data if (protocol >= 73) { bytes = ByteArray(buf.readShort().toInt() shl 1) buf.readBytes(bytes) val host = String(bytes, StandardCharsets.UTF_16BE) val port = buf.readInt() virtualAddress = InetSocketAddress.createUnresolved(host, port) } readable = buf.readableBytes() if (readable > 0) { this.logger.warn("Trailing bytes on a legacy ping message: {}b", readable) } } // The message was successfully decoded as a legacy one legacy = true val full1 = full val protocol1 = protocol val virtualAddress1 = virtualAddress // Call the event in the main thread Lantern.getSyncScheduler().submit { val clientVersion = this.server.game.minecraftVersionCache.getVersionOrUnknown(protocol1, true) if (clientVersion === LanternMinecraftVersion.UNKNOWN) this.logger.debug("Client with unknown legacy protocol version {} pinged the server.", protocol1) val serverVersion = this.server.platform.minecraftVersion var description = server.motd val address = ctx.channel().remoteAddress() as InetSocketAddress val client = LanternStatusClient(address, clientVersion, virtualAddress1) val players = LanternStatusHelper.createPlayers(server) val response = LanternStatusResponse(serverVersion, description, players, server.favicon) val connection = SimpleRemoteConnection.of(ctx.channel(), virtualAddress1) val cause = causeOf(connection) val event = LanternEventFactory.createClientPingServerEvent(cause, client, response) this.server.eventManager.post(event) // Cancelled, we are done here if (event.isCancelled) { ctx.channel().close() return@submit } description = response.description var online = players.online val max = players.max // The players should be hidden, this will replace the player count // with ??? if (!response.players.isPresent) { online = -1 } val data = if (full1) { val description0 = getFirstLine(LegacyTextSerializer.serialize(description)) // 1. This value is always 1. // 2. The protocol version, just use a value out of range // of the available ones. // 3. The version/name string of the server. // 4. The motd of the server. In legacy format. // 5. The online players // 6. The maximum amount of players String.format("\u00A7%s\u0000%s\u0000%s\u0000%s\u0000%s\u0000%s", 1, 127, response.version.name, description0, online, max) } else { val description0 = getFirstLine(description.toPlain()) // 1. The motd of the server. In legacy format. // 2. The online players // 3. The maximum amount of players String.format("%s\u00A7%s\u00A7%s", description0, online, max) } ctx.disconnect(data) } } catch (ignore: Exception) { } finally { if (legacy) { buf.release() } else { buf.resetReaderIndex() ctx.channel().pipeline().remove(this) ctx.fireChannelRead(buf) } } } /** * Sends a disconnect message to a legacy client and closes the connection. * * @param message The message */ private fun ChannelHandlerContext.disconnect(message: String) { val data = message.toByteArray(StandardCharsets.UTF_16BE) val output = alloc().buffer() output.writeByte(0xff) output.writeShort(data.size shr 1) output.writeBytes(data) val firstContext: ChannelHandlerContext? = channel().pipeline().firstContext() firstContext?.writeAndFlush(output)?.addListener(ChannelFutureListener.CLOSE) } private fun getFirstLine(value: String): String { val i = value.indexOf('\n') return if (i == -1) value else value.substring(0, i) } companion object { private const val V1_3_2_PROTOCOL = 39 private const val V1_5_2_PROTOCOL = 61 } }
mit
6986057618c8adbf1af8de8b7588a6ab
41.876652
141
0.577417
5.119937
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/value/ValueConstructorFactory.kt
1
3288
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data.value import org.lanternpowered.api.util.uncheckedCast import org.lanternpowered.server.data.key.ValueKey import org.spongepowered.api.data.value.ListValue import org.spongepowered.api.data.value.MapValue import org.spongepowered.api.data.value.SetValue import org.spongepowered.api.data.value.Value import org.spongepowered.api.data.value.WeightedCollectionValue import org.spongepowered.api.util.weighted.WeightedTable @Suppress("UNCHECKED_CAST") object ValueConstructorFactory { fun <V : Value<E>, E : Any> getConstructor(key: ValueKey<V, E>): ValueConstructor<V, E> { val valueType = key.valueToken.rawType var valueConstructor: ValueConstructor<V, E> if (ListValue::class.java.isAssignableFrom(valueType)) { valueConstructor = SimpleValueConstructor(key, { key1, value -> LanternMutableListValue(key1.uncheckedCast(), value as MutableList<*>) as V }, { key1, value -> LanternImmutableListValue(key1.uncheckedCast(), value as MutableList<*>) as V }) } else if (SetValue::class.java.isAssignableFrom(valueType)) { valueConstructor = SimpleValueConstructor(key, { key1, value -> LanternMutableSetValue(key1.uncheckedCast(), value as MutableSet<*>) as V }, { key1, value -> LanternImmutableSetValue(key1.uncheckedCast(), value as MutableSet<*>) as V }) } else if (MapValue::class.java.isAssignableFrom(valueType)) { valueConstructor = SimpleValueConstructor(key, { key1, value -> LanternMutableMapValue(key1.uncheckedCast(), value as MutableMap<*,*>) as V }, { key1, value -> LanternImmutableMapValue(key1.uncheckedCast(), value as MutableMap<*,*>) as V }) } else if (WeightedCollectionValue::class.java.isAssignableFrom(valueType)) { valueConstructor = SimpleValueConstructor(key, { key1, value -> LanternMutableWeightedCollectionValue(key1.uncheckedCast(), value as WeightedTable<*>) as V }, { key1, value -> LanternImmutableWeightedCollectionValue(key1.uncheckedCast(), value as WeightedTable<*>) as V }) } else { valueConstructor = SimpleValueConstructor(key, { key1, value -> LanternMutableValue(key1.uncheckedCast(), value) as V }, { key1, value -> LanternImmutableValue(key1.uncheckedCast(), value) as V }) val elementType = key.elementToken.rawType if (Enum::class.java.isAssignableFrom(elementType)) { valueConstructor = CachedEnumValueConstructor(valueConstructor.uncheckedCast(), elementType.uncheckedCast()) } else if (elementType == Boolean::class.java) { valueConstructor = CachedBooleanValueConstructor(valueConstructor.uncheckedCast()).uncheckedCast() } } return valueConstructor } }
mit
da132e689c9853d404262cb6633d4740
55.689655
133
0.678528
4.77907
false
false
false
false
OpenWeen/OpenWeen.Droid
app/src/main/java/moe/tlaster/openween/core/api/statuses/PostWeibo.kt
1
3839
package moe.tlaster.openween.core.api.statuses import android.text.TextUtils import java.io.File import android.support.v4.util.ArrayMap import moe.tlaster.openween.core.api.Constants import moe.tlaster.openween.core.model.status.MediaModel import moe.tlaster.openween.core.model.status.MessageModel import moe.tlaster.openween.core.model.status.PictureModel import moe.tlaster.openween.core.model.types.RepostType import moe.tlaster.openween.core.model.types.WeiboVisibility import moe.tlaster.openween.common.helpers.HttpHelper /** * Created by Tlaster on 2016/9/8. */ object PostWeibo { fun post(status: String, visible: WeiboVisibility = WeiboVisibility.All, list_id: String = "", plat: Float = 0f, plong: Float = 0f) : MessageModel { var param: MutableMap<String, String> = HashMap() param.put("status", status) param.put("visible", visible.value.toString()) param.put("lat", plat.toString()) param.put("long", plong.toString()) param = checkForVisibility(visible, list_id, param) return HttpHelper.postAsync(Constants.UPDATE, param) } fun postWithPic(status: String, pic: File, visible: WeiboVisibility, list_id: String, plat: Float, plong: Float) : MessageModel { var param: MutableMap<String, String> = HashMap() param.put("status", status) param.put("visible", visible.value.toString()) param.put("lat", plat.toString()) param.put("long", plong.toString()) param = checkForVisibility(visible, list_id, param) return HttpHelper.postAsync(Constants.UPLOAD, param, pic) } fun repost(id: Long, status: String, is_comment: RepostType = RepostType.None) : MessageModel { val param = ArrayMap<String, String>() param.put("status", if (TextUtils.isEmpty(status)) "转发微博" else status) param.put("id", id.toString()) param.put("is_comment", is_comment.value.toString()) return HttpHelper.postAsync(Constants.REPOST, param) } fun repostWithPic(id: Long, status: String, pid: String, is_comment: RepostType = RepostType.None) : MessageModel { val param = ArrayMap<String, String>() param.put("status", if (TextUtils.isEmpty(status)) "转发微博" else status) param.put("id", id.toString()) param.put("is_comment", is_comment.value.toString()) param.put("media", MediaModel(pid).toString()) param.put("source", "211160679") param.put("from", "1055095010") return HttpHelper.postAsync("https://api.weibo.cn/2/statuses/repost", param) } fun deletePost(id: Long) : MessageModel { val param = ArrayMap<String, String>() param.put("id", id.toString()) return HttpHelper.postAsync(Constants.DESTROY, param) } fun uploadPicture(file: File) : PictureModel { return HttpHelper.postAsync(Constants.UPLOAD_PIC, ArrayMap(), file) } fun postWithMultiPics(status: String, pics: String, visible: WeiboVisibility = WeiboVisibility.All, list_id: String = "", plat: Float = 0f, plong: Float = 0f) : MessageModel { var param: MutableMap<String, String> = HashMap() param.put("status", status) param.put("pic_id", pics) param.put("visible", visible.value.toString()) param.put("lat", plat.toString()) param.put("long", plong.toString()) param = checkForVisibility(visible, list_id, param) return HttpHelper.postAsync(Constants.UPLOAD_URL_TEXT, param) } private fun checkForVisibility(visible: WeiboVisibility, list_id: String, param: MutableMap<String, String>): MutableMap<String, String> { if (visible === WeiboVisibility.SpecifiedGroup) if (!TextUtils.isEmpty(list_id)) param.put("list_id", list_id) return param } }
mit
d8f5e3739eb686e5729a3e919f51c96e
42.942529
179
0.673293
3.912999
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/search/SearchEngineListPreference.kt
1
4691
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.search import android.content.Context import android.content.res.Resources import android.graphics.drawable.BitmapDrawable import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.CompoundButton import android.widget.RadioGroup import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Job import kotlinx.coroutines.launch import mozilla.components.browser.search.SearchEngine import org.mozilla.focus.R import org.mozilla.focus.ext.components import org.mozilla.focus.utils.Settings import kotlin.coroutines.CoroutineContext abstract class SearchEngineListPreference : Preference, CoroutineScope { private val job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main protected var searchEngines: List<SearchEngine> = emptyList() protected var searchEngineGroup: RadioGroup? = null protected abstract val itemResId: Int constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { layoutResource = R.layout.preference_search_engine_chooser } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { layoutResource = R.layout.preference_search_engine_chooser } override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) searchEngineGroup = holder!!.itemView.findViewById(R.id.search_engine_group) val context = searchEngineGroup!!.context searchEngines = context.components.searchEngineManager.getSearchEngines(context) .sortedBy { it.name } refreshSearchEngineViews(context) } override fun onDetached() { job.cancel() super.onDetached() } protected abstract fun updateDefaultItem(defaultButton: CompoundButton) fun refetchSearchEngines() { launch(Main) { searchEngines = context.components.searchEngineManager .load([email protected]) .await() .sortedBy { it.name } refreshSearchEngineViews([email protected]) } } private fun refreshSearchEngineViews(context: Context) { if (searchEngineGroup == null) { // We want to refresh the search engine list of this preference in onResume, // but the first time this preference is created onResume is called before onCreateView // so searchEngineGroup is not set yet. return } val defaultSearchEngine = context.components.searchEngineManager.getDefaultSearchEngine( context, Settings.getInstance(context).defaultSearchEngineName ).identifier searchEngineGroup!!.removeAllViews() val layoutInflater = LayoutInflater.from(context) val layoutParams = RecyclerView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) for (i in searchEngines.indices) { val engine = searchEngines[i] val engineId = engine.identifier val engineItem = makeButtonFromSearchEngine(engine, layoutInflater, context.resources) engineItem.id = i engineItem.tag = engineId if (engineId == defaultSearchEngine) { updateDefaultItem(engineItem) } searchEngineGroup!!.addView(engineItem, layoutParams) } } private fun makeButtonFromSearchEngine( engine: SearchEngine, layoutInflater: LayoutInflater, res: Resources ): CompoundButton { val buttonItem = layoutInflater.inflate(itemResId, null) as CompoundButton buttonItem.text = engine.name val iconSize = res.getDimension(R.dimen.preference_icon_drawable_size).toInt() val engineIcon = BitmapDrawable(res, engine.icon) engineIcon.setBounds(0, 0, iconSize, iconSize) val drawables = buttonItem.compoundDrawables buttonItem.setCompoundDrawables(engineIcon, null, drawables[2], null) return buttonItem } }
mpl-2.0
c49fdf421e701e3a085a0bc1175e40b4
37.768595
113
0.706033
5.14364
false
false
false
false
hubme/WorkHelperApp
app/src/test/java/com/king/app/workhelper/coroutine/CoroutineSample.kt
1
8690
package com.king.app.workhelper.coroutine import kotlinx.coroutines.* import org.junit.Test import kotlin.system.measureTimeMillis class CoroutineSample { @Test fun aaa() = runBlocking { val job = launch { // 启动一个新协程并保持对这个作业的引用 delay(1000L) println("World!") } print("Hello ") job.join() // 等待直到子协程执行结束 println("Done!") } @Test fun coroutineScope() = runBlocking { coroutineScope { // 创建一个协程作用域 launch { delay(1000L) println("Task from nested launch") } delay(500L) println("Task from coroutine scope") // 这一行会在内嵌 launch 之前输出 } println("Done") /* output: Task from coroutine scope Task from nested launch Done */ } @Test fun coroutineScope2() = runBlocking { launch { delay(200L) println("Task from runBlocking") } //CoroutineScope() coroutineScope { launch { delay(500L) println("Task from nested launch") } delay(100L) println("Task from coroutine scope") // 这一行会在内嵌 launch 之前输出 } println("Coroutine scope is over") // 这一行在内嵌 launch 执行完毕后才输出 /* output: Task from coroutine scope Task from runBlocking Task from nested launch Coroutine scope is over */ } @Test fun globalScopeTest() = runBlocking { //在 GlobalScope 中启动的活动协程并不会使进程保活。它们就像守护线程。 GlobalScope.launch { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } delay(1300L) // 在延迟后退出 } @Test fun cancelCoroutine() = runBlocking { val job = launch { repeat(1000) { i -> println("job: I'm sleeping $i ...") //delay 是挂起函数 ,它不会造成线程阻塞,但是会挂起协程 delay(500L) } } delay(1300L) // 延迟一段时间 println("main: I'm tired of waiting!") job.cancel() // 取消该作业 job.join() // 等待作业执行结束 //job.cancelAndJoin() //job.cancel() 和 job.join() 的合并方法 println("main: Now I can quit.") } @Test fun withTimeoutSample() = runBlocking { // 超时抛出 TimeoutCancellationException 异常 withTimeout(1300L) { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } } @Test fun withTimeoutOrNullSample() = runBlocking { // 超时,返回 null val result = withTimeoutOrNull(1300L) { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } "Done" // 在它运行得到结果之前取消它 } println("Result is $result") } @Test fun measureTimeMillisSample() = runBlocking { val result = measureTimeMillis { val async1 = async(start = CoroutineStart.LAZY) { println("async1 start.") val value = heavyWorkOne() println("async1 end.") value } val async2 = async(start = CoroutineStart.LAZY) { println("async2 start.") val value = heavyWorkTwo() println("async2 end.") value } delay(100L) println("aaa") // 如果不调用 start(),后面调用 await() 会按顺序执行 async1.start() async2.start() println("The answer is ${async1.await() + async2.await()}") } println("Result is $result") } private suspend fun heavyWorkOne(): Int { delay(500) return 500 } private suspend fun heavyWorkTwo(): Int { delay(400) return 400 } private fun heavyWorkOneAsync() = GlobalScope.async { heavyWorkOne() } private fun heavyWorkTwoAsync() = GlobalScope.async { heavyWorkTwo() } private suspend fun failedConcurrentSum(): Int = coroutineScope { val one = async { try { delay(Long.MAX_VALUE) // 模拟一个长时间的运算 42 } finally { println("First child was cancelled") } } val two = async<Int> { println("Second child throws an exception") throw ArithmeticException() } one.await() + two.await() } @Test fun failedConcurrentSumTest() = runBlocking<Unit> { try { failedConcurrentSum() } catch (e: ArithmeticException) { println("Computation failed with ArithmeticException") } } @Test fun dispatchersSample() = runBlocking<Unit> { launch { // 运行在父协程的上下文中,即 runBlocking 主协程 println("runBlocking: ${Thread.currentThread().name}") } launch(Dispatchers.Unconfined) { // 不受限的——将工作在主线程中 println("Unconfined: ${Thread.currentThread().name}") } launch(Dispatchers.Default) { // 将会获取默认调度器 println("Default: ${Thread.currentThread().name}") } launch(Dispatchers.IO) { println("IO: ${Thread.currentThread().name}") } SupervisorJob() } //https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html @Test fun coroutineScopeSample() = runBlocking { val request = launch { // GlobalScope 不受父协程的影响 GlobalScope.launch { println("job1: I run in GlobalScope and execute independently!") delay(1000) println("job1: I am not affected by cancellation of the request") } // 继承父协程的上下文 launch { delay(100) println("job2: I am a child of the request coroutine") delay(1000) println("job2: I will not execute this line if my parent request is cancelled") } } delay(500) request.cancel() delay(1000) println("main: Who has survived request cancellation?") } @Test fun testDispatchersUnconfined() = runBlocking<Unit> { GlobalScope.launch(Dispatchers.Unconfined) { log("") withContext(Dispatchers.IO) { log("") } //恢复 log("") //挂起 withContext(Dispatchers.Default) { log("") } //恢复 log("") } } @Test fun asdfsdf() = runBlocking<Unit> { val handler = CoroutineExceptionHandler { _, throwable -> log("my coroutineExceptionHandler catch exception, msg = ${throwable.message}") } val parentJob = GlobalScope.launch(handler) { val childJob = launch { try { delay(Long.MAX_VALUE) } catch (e: CancellationException) { log("catch cancellationException thrown from child launch") log("rethrow cancellationException") throw CancellationException() } finally { log("child was canceled") } } //取消子协程 childJob.cancelAndJoin() log("parent is still running") } parentJob.start() Thread.sleep(1000) } @Test fun coroutineNameSample() = runBlocking(CoroutineName("main-coroutine")) { log("") launch(CoroutineName("launch-coroutine")) { log("launch") } val v1 = async(CoroutineName("async-coroutine")) { log("async") } } suspend fun performRequest(request: Int): String { delay(1000) // 模仿长时间运行的异步任务 return "response $request" } private fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") }
apache-2.0
0cec29c804e7f24ab1c744a78fb1548d
26.723549
117
0.509234
4.730344
false
true
false
false
lightem90/Sismic
app/src/main/java/com/polito/sismic/Interactors/Helpers/UploadHelper.kt
1
7448
package com.polito.sismic.Interactors.Helpers import android.app.NotificationManager import android.content.Context import android.os.AsyncTask import android.support.v4.app.NotificationCompat import android.util.Log import com.polito.sismic.Domain.Report import com.polito.sismic.R import java.net.HttpURLConnection import java.net.URL import android.app.PendingIntent import android.content.Intent import android.support.v4.app.TaskStackBuilder import com.google.gson.GsonBuilder import com.polito.sismic.Extensions.toast import com.polito.sismic.Presenters.PresenterActivity.PresenterActivity import java.io.DataOutputStream /** * Created by it0003971 on 22/09/2017. */ class UploadHelper { fun upload(context: Context, report : Report) { //one-line string val gSon = GsonBuilder().create() // for pretty print feature (the string become veeeery long with .setPrettyPrinting(). UploadReportTask(context, LoginSharedPreferences.getLoggedUser(context).email).execute(gSon.toJson(report)) } inner class UploadReportTask internal constructor(val mContext : Context, val mEmail : String): AsyncTask<String, Double, Pair<Int, String>>() { private val SERVER_ADDR_REPORT_UPLOAD = "http://natasha.polito.it/seismic/upload_report?" private val SERVER_ADDR_REPORT_FILE_UPLOAD = "http://natasha.polito.it/seismic/upload_report_files" private val NOTIFICATION_CHANNEL = "default" private val mId : Int = 1 private var mBuilder: NotificationCompat.Builder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL) private var mNotifyManager: NotificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private val mTitle: String = mContext.getString(R.string.upload_notification_title) override fun doInBackground(vararg reportGson: String): Pair<Int, String> { try { val sb = StringBuilder(SERVER_ADDR_REPORT_UPLOAD) sb.append("email=") sb.append(mEmail) val urlUse = URL(sb.toString()) val conn: HttpURLConnection? conn = urlUse.openConnection() as HttpURLConnection conn.requestMethod = "POST" conn.setRequestProperty("Content-Type", "application/json") conn.setRequestProperty("Accept", "application/json") conn.connectTimeout = 5000 publishProgress(0.0) val os = conn.outputStream val osw = DataOutputStream(os) publishProgress(20.0) osw.writeBytes(reportGson.first()) publishProgress(80.0) osw.flush() osw.close() os.close() return (conn.responseCode to conn.responseMessage) } catch (e: Exception) { Log.d("Upload", e.toString()) return e.message?.let { 400 to it} ?: 400 to "Impossibile inviare il report" } } override fun onPostExecute(result: Pair<Int, String>) { Log.d("UploadReportTask", "onPostExecute") super.onPostExecute(result) // createNotification("completed") publishProgress(100.0) if (!result.second.isEmpty()) mContext.toast(result.second) setCompletedNotification() } override fun onPreExecute() { Log.d("UploadReportTask", "onPreExecute") super.onPreExecute() setStartedNotification() } override fun onProgressUpdate(vararg values: Double?) { Log.d("UploadReportTask", "onProgressUpdate with argument = " + values[0]) super.onProgressUpdate(*values) values[0]?.let { val incr = it.toInt() if (incr == 0) setProgressNotification() updateProgressNotification(incr) } } /** * the progress notification * * * @param incr */ private fun updateProgressNotification(incr: Int) { // Sets the progress indicator to a max value, the // current completion percentage, and "determinate" // state mBuilder.setProgress(100, incr, false) // Displays the progress bar for the first time. mNotifyManager.notify(mId, mBuilder.build()) // Sleeps the thread, simulating an operation // that takes time } /** * the last notification */ private fun setCompletedNotification() { mBuilder.setSmallIcon(R.drawable.ic_file_upload_black_24dp).setContentTitle(mTitle) .setContentText("Completato") // Creates an explicit intent for an Activity in your app val resultIntent = Intent(mContext, PresenterActivity::class.java) // The stack builder object will contain an artificial back stack for // the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. val stackBuilder = TaskStackBuilder.create(mContext) // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(PresenterActivity::class.java) // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent) val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) mBuilder.setContentIntent(resultPendingIntent) mNotifyManager.notify(mId, mBuilder.build()) } /** * the progress notification * * * called only once */ private fun setProgressNotification() { mBuilder.setContentTitle(mTitle).setContentText("In corso...") .setSmallIcon(R.drawable.ic_file_upload_black_24dp) } /** * the first notification */ private fun setStartedNotification() { mBuilder.setSmallIcon(R.drawable.ic_file_upload_black_24dp).setContentTitle(mTitle) .setContentText("Started") // Creates an explicit intent for an Activity in your app val resultIntent = Intent(mContext, PresenterActivity::class.java) // The stack builder object will contain an artificial back stack for // the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. val stackBuilder = TaskStackBuilder.create(mContext) // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(PresenterActivity::class.java) // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent) val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) mBuilder.setContentIntent(resultPendingIntent) mNotifyManager.notify(mId, mBuilder.build()) } } }
mit
f7c3c7caf67066a98ba77397fe5af419
39.264865
148
0.624329
5.208392
false
false
false
false
damien5314/RxReddit
library/src/test/java/rxreddit/api/InitializationTests.kt
1
2255
package rxreddit.api import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import java.net.URI class InitializationTests : _RedditServiceTests() { @Test fun testInitialization() { val service = RedditService.Builder() .appId("") .redirectUri("") .deviceId("") .userAgent("") .build() assertNotNull("service == null", service) } @Test(expected = IllegalStateException::class) fun testInitializationError_noAppId() { val service = RedditService.Builder() // .appId("") .redirectUri("") .deviceId("") .userAgent("") .build() } @Test(expected = IllegalStateException::class) fun testInitializationError_noRedirectUri() { val service = RedditService.Builder() .appId("") // .redirectUri("") .deviceId("") .userAgent("") .build() } @Test(expected = IllegalStateException::class) fun testInitializationError_noDeviceId() { val service = RedditService.Builder() .appId("") .redirectUri("") // .deviceId("") .userAgent("") .build() } @Test(expected = IllegalStateException::class) fun testInitializationError_noUserAgent() { val service = RedditService.Builder() .appId("") .redirectUri("") .deviceId("") // .userAgent("") .build() } @Test fun testGetRedirectUri() { val redirectUri = service.redirectUri assertEquals("unexpected redirectUri", "http://127.0.0.1/", redirectUri) } @Test fun testGetAuthorizationUrl() { val authUrl = service.authorizationUrl val uri = URI(authUrl) assertNotNull("uri == null", uri) } @Test fun testGetOkHttpClient() { val userAgent = "sample-user-agent" val client = service.getOkHttpClient(userAgent, 0, null, false) assertNotNull("okhttpclient == null", client) } @Test fun testGetGson() { val gson = service.getGson() assertNotNull("gson == null", gson) } }
apache-2.0
b5f12edc2af73d779d83e39d8a1321fe
24.91954
80
0.561863
4.945175
false
true
false
false
clappr/clappr-android
clappr/src/main/kotlin/io/clappr/player/base/UIObject.kt
1
762
package io.clappr.player.base import android.content.Context import android.view.View import android.view.ViewManager open class UIObject: BaseObject() { var view : View? = null open val viewClass: Class<*> = View::class.java init { ensureView() } open fun render() : UIObject { return this } fun remove() : UIObject { (view?.parent as? ViewManager)?.removeView(view) return this } private fun ensureView() { if (view == null) { val constructor = viewClass.getConstructor(Context::class.java) ?: throw IllegalStateException("No constructor was found for parameters (Context)") view = constructor.newInstance(applicationContext) as? View } } }
bsd-3-clause
f9f853d9b257750756a3d47b2dec5fe0
23.580645
159
0.637795
4.45614
false
false
false
false
hartwigmedical/hmftools
cider/src/test/java/com/hartwig/hmftools/cider/CiderReadScreenerTest.kt
1
25676
package com.hartwig.hmftools.cider import com.hartwig.hmftools.common.genome.region.GenomeRegions import com.hartwig.hmftools.common.genome.region.Strand import htsjdk.samtools.SAMRecord import junit.framework.TestCase import org.junit.Test class CiderReadScreenerTest { companion object { const val MAX_FRAGMENT_LENGTH = 1000 } @Test fun testExtrapolateReadOffsetAtRefPosition() { // 50 bases alignment val alignmentStart = 1001 val alignmentEnd = 1050 // create a SAM record with soft clip on both sides val record = SAMRecord(null) record.alignmentStart = alignmentStart // soft clips on both sides record.cigarString = "30S50M20S" // 100 bases here record.readString = "GACAACGCCAAGAACTCACTGTCTCTGCAAATGAATGACCTGCGAGTCGAAGACACGGCTGTGTATTACTGTGCGAGACCGAAATTTTATAGTAATGGCT" record.readNegativeStrandFlag = false //record.setBaseQualityString(qualities); record.mappingQuality = 20 record.duplicateReadFlag = false record.readUnmappedFlag = false record.properPairFlag = true record.readPairedFlag = true // make sure we set it up correctly TestCase.assertEquals(31, record.getReadPositionAtReferencePosition(alignmentStart)) TestCase.assertEquals(80, record.getReadPositionAtReferencePosition(alignmentEnd)) var readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentStart) // start offset is 30, due to 30 left soft clip TestCase.assertEquals(30, readOffset) readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentEnd) TestCase.assertEquals(79, readOffset) readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentStart - 30) // start offset is 0, due to 30 left soft clip TestCase.assertEquals(0, readOffset) readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentEnd + 20) // start offset is 99, due to 20 right soft clip TestCase.assertEquals(99, readOffset) readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentEnd + 30) // out of range TestCase.assertEquals(-1, readOffset) // test out of range readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentStart - 31) TestCase.assertEquals(-1, readOffset) // this is over the end, so should get -1 readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentEnd + 30) TestCase.assertEquals(-1, readOffset) } @Test fun testExtrapolateReadOffsetAtRefPositionSplice() { val alignmentStart = 100000 val alignmentEnd = 108099 // based on a RNA read we have come across val record = SAMRecord(null) record.referenceName = "X" record.alignmentStart = alignmentStart record.readString = "GAATTCTCACAGGAGACGAGGGGGAAAAGGGTTGGGGCGGATGCACTCCCGGAAGAGACGGTGACCGTGGTCCCTTGGCCCCAGACGTCCATACCCGCCA" + "GAATTCTCACAGGAGACGAGGGGGAAAAGGGTTGGGGCGGATGCACTCCCGGAAGAGACGGTGACCGTGGTCCCTTGGCCCCAGACGTCCATACCCGCCA" record.baseQualityString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" record.readNegativeStrandFlag = false record.mappingQuality = 20 record.duplicateReadFlag = false record.readUnmappedFlag = false record.properPairFlag = true record.firstOfPairFlag = true record.readPairedFlag = true // following sets up multiple blocks // 1. 100000-10049 (50) // 2. 107050-107069 (20) // 3. 108070-108099 (30) record.cigarString = "20S50M7000N20M1000N30M80S" // there are multiple align blocks within TestCase.assertEquals(21, record.getReadPositionAtReferencePosition(alignmentStart)) TestCase.assertEquals(120, record.getReadPositionAtReferencePosition(alignmentEnd)) // try a point 30 bases before first alignment block var readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentStart - 30) TestCase.assertEquals(-1, readOffset) // 20S only so 30 bases is too many // try a point 20 bases before first alignment block, i.e. within the soft clipped region readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, alignmentStart - 20) TestCase.assertEquals(0, readOffset) // 20S - 20 // try a point within the first match block of 50 bases readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 100020) TestCase.assertEquals(40, readOffset) // 40 since it is 20 after the 20 soft clip // try a point 100 bases after first match block readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 100150) TestCase.assertEquals(170, readOffset) // 20 soft clip + 150 // 200 bases after first block, should get nothing since it will be outside range readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 100250) TestCase.assertEquals(-1, readOffset) // match 50 bases before second block readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 107000) TestCase.assertEquals(20, readOffset) // 20S + 50M - 50 bases // this will match 10 bases into second block readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 107060) TestCase.assertEquals(80, readOffset) // 20S + 50M + 10 bases // this will match 30 after second block readOffset = CiderReadScreener.extrapolateReadOffsetAtRefPosition(record, 107100) TestCase.assertEquals(120, readOffset) // 20S + 50M + 20M + 30 } @Test fun testIsRelevantToAnchorLocation1() { val readLength = 150 val mappedLength = 100 // positive strand val anchorRefStart = 10000 val anchorRefEnd = 10030 // this tests the function to work out if a read is potentially near and on the // correct side of the anchor genome location val anchorLocations = arrayOf( VJAnchorGenomeLocation(VJGeneType.IGHV, GenomeRegionStrand("1", anchorRefStart, anchorRefEnd, Strand.FORWARD)), VJAnchorGenomeLocation(VJGeneType.IGHJ, GenomeRegionStrand("1", anchorRefStart, anchorRefEnd, Strand.REVERSE)) ) for (anchorLocation in anchorLocations) { // we should only allow reads that are mapped at lower genome location, i.e. // read ------ anchor ----CDR3 // or reads that overlap the anchor by at least 15 bases // first try reads that are lower var mappedEnd = anchorRefEnd - readLength + 15 var mappedStart = mappedEnd - mappedLength var mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertTrue(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) // reads with coords above and not overlapping anchor are not relevant mappedStart = anchorRefEnd + anchorLocation.baseLength() mappedEnd = mappedStart + mappedLength mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertFalse(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) // reads that overlap with anchor by 15 bases or more are relevant mappedEnd = anchorRefEnd + anchorLocation.baseLength() / 2 mappedStart = mappedEnd - mappedLength mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertTrue(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) } } @Test fun testIsRelevantToAnchorLocation2() { val readLength = 150 val mappedLength = 100 // positive strand val anchorRefStart = 10000 val anchorRefEnd = 10030 // this tests the function to work out if a read is potentially near and on the // correct side of the anchor genome location val anchorLocations = arrayOf( VJAnchorGenomeLocation(VJGeneType.TRAV, GenomeRegionStrand("1", anchorRefStart, anchorRefEnd, Strand.REVERSE)), VJAnchorGenomeLocation(VJGeneType.TRAJ, GenomeRegionStrand("1", anchorRefStart, anchorRefEnd, Strand.FORWARD)) ) for (anchorLocation in anchorLocations) { // we should only allow reads that are mapped at higher genome location, i.e. // CDR3 ------ anchor ----read // or reads that overlap the anchor by at least 15 bases // first try reads that are mapped at higher coord var mappedStart = anchorRefStart + readLength - 15 var mappedEnd = mappedStart + mappedLength var mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertTrue(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) // reads with coords below and not overlapping anchor are not relevant mappedEnd = anchorRefStart - anchorLocation.baseLength() mappedStart = mappedEnd - mappedLength mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertFalse(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) // reads that overlap with anchor by 15 bases or more are relevant mappedStart = anchorRefStart - anchorLocation.baseLength() / 2 mappedEnd = mappedStart + mappedLength mapped = GenomeRegions.create(anchorLocation.chromosome, mappedStart, mappedEnd) TestCase.assertTrue(CiderReadScreener.isRelevantToAnchorLocation(readLength, mapped, anchorLocation)) } } @Test fun testFindAnchorPositionRNA() { // read: A00624:61:HVW7TDSXX:4:2344:18674:2018 1/2 151b aligned to 14:106322274-106330832., aligned: 121 // A00624:61:HVW7TDSXX:4:2344:18674:2018 99 14 106322274 255 49M7085N20M1389N16M66S = 106518456 196235 // GAATTCTCACAGGAGACGAGGGGGAAAAGGGTTGGGGCGGATGCACTCCCGGAAGAGACGGTGACCGTGGTCCCTTGGCCCCAGACGTCCATACCCGCCAAGCCATTACTATAAAATTTCGGTCTCGCACAGTAATACACAGCCGTGTCTT // FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF // NH:i:1 HI:i:1 AS:i:120 nM:i:3 NM:i:2 MD:Z:50T2G31 jM:B:c,2,0 jI:B:i,106322323,106329407,106329428,106330816 MC:Z:16S53M82S // 50 bases alignment val alignmentStart = 106322274 val alignmentEnd = 106330832 // based on a RNA read we have come across val record = SAMRecord(null) record.readName = "read1" record.referenceName = "14" record.alignmentStart = alignmentStart record.cigarString = "49M7085N20M1389N16M66S" record.readString = "GAATTCTCACAGGAGACGAGGGGGAAAAGGGTTGGGGCGGATGCACTCCCGGAAGAGACGGTGACCGTGGTCCCTTGGCCCCAGACGTCCATACCCGCCAAGCCATTACTATAAAATTTCGGTCTCGCACAGTAATACACAGCCGTGTCTT" record.baseQualityString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" record.readNegativeStrandFlag = false record.mappingQuality = 20 record.duplicateReadFlag = false record.readUnmappedFlag = false record.properPairFlag = true record.firstOfPairFlag = true record.readPairedFlag = true val ighJ1 = VJAnchorTemplate( VJGeneType.IGHJ, "IGHJ1", "01", GenomeRegionStrand("14", 106330701, 106330840, Strand.REVERSE), "GCTGAATACTTCCAGCACTGGGGCCAGGGCACCCTGGTCACCGTCTCCTCAG", "TGGGGCCAGGGCACCCTGGTCACCGTCTCC", GenomeRegionStrand("14", 106330801, 106330830, Strand.REVERSE) ) val vjGeneStore = TestCiderGeneDatastore(listOf(ighJ1)) val mockAnchorBlosumSearcher = MockAnchorBlosumSearcher() val ciderReadScreener = CiderReadScreener( vjGeneStore, mockAnchorBlosumSearcher, 6, MAX_FRAGMENT_LENGTH ) // make sure we set it up correctly TestCase.assertEquals(1, record.getReadPositionAtReferencePosition(alignmentStart)) TestCase.assertEquals(85, record.getReadPositionAtReferencePosition(alignmentEnd)) val mapped = if (record.readUnmappedFlag) null else GenomeRegions.create( record.referenceName, record.alignmentStart, record.alignmentEnd ) // template loc: 14:106330801-106330830(-) val anchorLocation = VJAnchorGenomeLocation( VJGeneType.IGHJ, GenomeRegionStrand("14", 106330801, 106330830, Strand.REVERSE) ) val readCandidate = ciderReadScreener.matchesAnchorLocation(record, mapped!!, anchorLocation, true) TestCase.assertNotNull(readCandidate) TestCase.assertEquals(68, readCandidate!!.anchorOffsetStart) TestCase.assertEquals(98, readCandidate.anchorOffsetEnd) } // we test unmapped read where the mate is mapped to upstream of V @Test fun isUnamppedReadRelevantToAnchorLocV() { val chr = "1" // positive strand val anchorRefStart = 10000 val anchorRefEnd = 10030 // create a SAM record with soft clip on both sides val read = SAMRecord(null) read.mateReferenceName = chr read.cigarString = "*" // 100 bases here read.readString = "GACAACGCCAAGAACTCACTGTCTCTGCAAATGAATGACCTGCGAGTCGAAGACACGGCTGTGTATTACTGTGCGAGACCGAAATTTTATAGTAATGGCT" read.readNegativeStrandFlag = false read.readUnmappedFlag = true read.mateUnmappedFlag = false read.properPairFlag = true read.readPairedFlag = true // first test forward strand // Here is what we want to test: // 1. the mapped mate must have coord below the V anchor coord, but not too far away (max 1000 bases) // 2. the anchor location is forward strand // 3. the mapped mate must be mapped to forward strand // >------------V--------D---------J---------> forward strand // ======> <===== // mate this // var anchorLocation = VJAnchorGenomeLocation(VJGeneType.TRAV, GenomeRegionStrand(chr, anchorRefStart, anchorRefEnd, Strand.FORWARD)) read.mateAlignmentStart = anchorRefStart - 500 read.mateNegativeStrandFlag = false TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = anchorRefStart - MAX_FRAGMENT_LENGTH - read.readLength TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if the mate is mapped to the other side of V, we do not accept read.mateAlignmentStart = anchorRefEnd + 500 TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if mate is negative strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = anchorRefStart - 500 read.mateNegativeStrandFlag = true TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // now test reverse strand // Here is what we want to test: // 1. the mapped mate must have coord higher the V anchor coord, but not too far away (max 1000 bases) // 2. the anchor location is reverse strand // 3. the mapped mate must be mapped to reverse strand // <-------J--------D--------V-------------< reverse strand // ======> <===== // this mate // anchorLocation = VJAnchorGenomeLocation(VJGeneType.TRAV, GenomeRegionStrand(chr, anchorRefStart, anchorRefEnd, Strand.REVERSE)) read.mateAlignmentStart = anchorRefEnd + 500 read.mateNegativeStrandFlag = true TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = anchorRefEnd + MAX_FRAGMENT_LENGTH TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if the mate is mapped to the other side of V, we do not accept read.mateAlignmentStart = anchorRefStart - 500 TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if mate is negative strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = anchorRefEnd + 500 read.mateNegativeStrandFlag = false TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) } // we test unmapped read where the mate is mapped to downstream of J @Test fun isUnamppedReadRelevantToAnchorLocJ() { val chr = "1" // positive strand val anchorRefStart = 10000 val anchorRefEnd = 10030 // create a SAM record with soft clip on both sides val read = SAMRecord(null) read.mateReferenceName = chr read.cigarString = "*" // 100 bases here read.readString = "GACAACGCCAAGAACTCACTGTCTCTGCAAATGAATGACCTGCGAGTCGAAGACACGGCTGTGTATTACTGTGCGAGACCGAAATTTTATAGTAATGGCT" read.readNegativeStrandFlag = false read.readUnmappedFlag = true read.mateUnmappedFlag = false read.properPairFlag = true read.readPairedFlag = true // first test forward strand // Here is what we want to test: // 1. the mapped mate must have coord above the J anchor coord, but not too far away (max 1000 bases) // 2. the anchor location is forward strand // 3. the mapped mate must be mapped to negative strand // >----V-------D---------J---------> forward strand // ======> <===== // this mate // var anchorLocation = VJAnchorGenomeLocation(VJGeneType.TRAJ, GenomeRegionStrand(chr, anchorRefStart, anchorRefEnd, Strand.FORWARD)) read.mateAlignmentStart = anchorRefEnd + 500 read.mateNegativeStrandFlag = true TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = anchorRefEnd + MAX_FRAGMENT_LENGTH TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if the mate is mapped to the other side of J, we do not accept read.mateAlignmentStart = anchorRefStart - 500 TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if mate is positive strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = anchorRefEnd + 500 read.mateNegativeStrandFlag = false TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // now test reverse strand // Here is what we want to test: // 1. the mapped mate must have coord higher the V anchor coord, but not too far away (max 1000 bases) // 2. the anchor location is reverse strand // 3. the mapped mate must be mapped to positive strand // <-----------J-------D----------V-------------< reverse strand // ======> <===== // mate this // anchorLocation = VJAnchorGenomeLocation(VJGeneType.TRAJ, GenomeRegionStrand(chr, anchorRefStart, anchorRefEnd, Strand.REVERSE)) read.mateAlignmentStart = anchorRefStart - 500 read.mateNegativeStrandFlag = false TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = anchorRefStart + MAX_FRAGMENT_LENGTH - read.readLength TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if the mate is mapped to the other side of J, we do not accept read.mateAlignmentStart = anchorRefEnd + 500 TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) // if mate is negative strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = anchorRefStart - 500 read.mateNegativeStrandFlag = true TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToAnchorLoc(read, anchorLocation, MAX_FRAGMENT_LENGTH)) } // we test unmapped read where the mate is mapped around constant region @Test fun isUnamppedReadRelevantToConstantRegion() { val chr = "1" // positive strand val constantRegionRefStart = 10000 val constantRegionRefEnd = 10030 // create a SAM record with soft clip on both sides val read = SAMRecord(null) read.mateReferenceName = chr read.cigarString = "*" // 100 bases here read.readString = "GACAACGCCAAGAACTCACTGTCTCTGCAAATGAATGACCTGCGAGTCGAAGACACGGCTGTGTATTACTGTGCGAGACCGAAATTTTATAGTAATGGCT" read.readNegativeStrandFlag = false read.readUnmappedFlag = true read.mateUnmappedFlag = false read.properPairFlag = true read.readPairedFlag = true // first test forward strand // Here is what we want to test: // 1. the mapped mate must have coord near constant region // 2. the constant region is on forward strand // 3. the mapped mate must be mapped to negative strand // >----V---D---J------C----> forward strand // ======> <===== // this mate // var constantRegion = GenomeRegionStrand(chr, constantRegionRefStart, constantRegionRefEnd, Strand.FORWARD) read.mateAlignmentStart = constantRegionRefEnd + 500 read.mateNegativeStrandFlag = true TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // the other side is also fine, we do not impose any rules for now read.mateAlignmentStart = constantRegionRefStart - 500 TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = constantRegionRefEnd + MAX_FRAGMENT_LENGTH TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // if mate is positive strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = constantRegionRefEnd + 500 read.mateNegativeStrandFlag = false TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // now test reverse strand // Here is what we want to test: // 1. the mapped mate must have coord near constant region // 2. the constant region is on reverse strand // 3. the mapped mate must be mapped to positive strand // <---C-------J---D---V------< reverse strand // ======> <===== // mate this // constantRegion = GenomeRegionStrand(chr, constantRegionRefStart, constantRegionRefEnd, Strand.REVERSE) read.mateAlignmentStart = constantRegionRefStart - 500 read.mateNegativeStrandFlag = false TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // the other side is also fine, we do not impose any rule for now read.mateAlignmentStart = constantRegionRefEnd + 500 TestCase.assertTrue(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // too far away read.mateAlignmentStart = constantRegionRefStart - MAX_FRAGMENT_LENGTH - read.readLength TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) // if mate is negative strand, it is pointing at wrong direction so also do not take it read.mateAlignmentStart = constantRegionRefStart - 500 read.mateNegativeStrandFlag = true TestCase.assertFalse(CiderReadScreener.isUnamppedReadRelevantToConstantRegion(read, constantRegion, MAX_FRAGMENT_LENGTH)) } }
gpl-3.0
4d608a60714038dc1d51d5a3561497ba
48.858252
165
0.695669
5.396385
false
true
false
false
Microsoft/vso-intellij
client/backend/src/main/kotlin/com/microsoft/tfs/TfsClient.kt
1
13903
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.tfs import com.jetbrains.rd.util.error import com.jetbrains.rd.util.info import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.lifetime.onTermination import com.jetbrains.rd.util.reactive.Property import com.jetbrains.rd.util.warn import com.microsoft.tfs.core.TFSTeamProjectCollection import com.microsoft.tfs.core.clients.versioncontrol.* import com.microsoft.tfs.core.clients.versioncontrol.events.NewPendingChangeListener import com.microsoft.tfs.core.clients.versioncontrol.events.NonFatalErrorListener import com.microsoft.tfs.core.clients.versioncontrol.events.PendingChangeEvent import com.microsoft.tfs.core.clients.versioncontrol.events.UndonePendingChangeListener import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.* import com.microsoft.tfs.core.clients.versioncontrol.specs.ItemSpec import com.microsoft.tfs.core.clients.versioncontrol.workspacecache.WorkspaceInfo import com.microsoft.tfs.core.config.persistence.DefaultPersistenceStoreProvider import com.microsoft.tfs.core.httpclient.Credentials import com.microsoft.tfs.core.httpclient.UsernamePasswordCredentials import com.microsoft.tfs.model.host.* import com.microsoft.tfs.sdk.* import com.microsoft.tfs.watcher.ExternallyControlledPathWatcherFactory import java.net.URI import java.nio.file.Paths class TfsClient(lifetime: Lifetime, serverUri: URI, credentials: Credentials) { companion object { private val logger = Logging.getLogger<TfsClient>() private fun tryLoadWorkspaceInfo(path: TfsLocalPath): WorkspaceInfo? { val workstation = Workstation.getCurrent(DefaultPersistenceStoreProvider.INSTANCE) val canonicalPathString = path.toCanonicalPathString() if (!workstation.isMapped(canonicalPathString)) { logger.info { "Path not mapped: \"$path\". Refreshing the cache." } workstation.reloadCache() if (!workstation.isMapped(canonicalPathString)) { logger.info { "Path still not mapped: \"$path\"." } return null } } return workstation.getLocalWorkspaceInfo(canonicalPathString) } private fun loadMappings(workspaceInfo: WorkspaceInfo, credentials: Credentials?): List<TfsWorkspaceMapping> { val serverUri = workspaceInfo.serverURI val workspaceName = workspaceInfo.name.orEmpty() if (serverUri == null) { logger.warn { "Server URI is null for workspace ${workspaceName}; no mappings will be available." } return emptyList() } else { val collection = TFSTeamProjectCollection(serverUri, credentials) try { val workspace = workspaceInfo.getWorkspace(collection) return workspace.folders?.map { workingFolder -> TfsWorkspaceMapping( TfsLocalPath(workingFolder.localItem), TfsServerPath(workspaceName, workingFolder.displayServerItem), workingFolder.type == WorkingFolderType.CLOAK ) }.orEmpty() } finally { collection.close() } } } fun getBasicWorkspaceInfo(path: TfsLocalPath): TfsWorkspaceInfo? { val workspaceInfo = tryLoadWorkspaceInfo(path) ?: return null val workspaceName = workspaceInfo.name.orEmpty() val serverUri = workspaceInfo.serverURI.toString() val mappings = try { loadMappings(workspaceInfo, null) } catch (e: Throwable) { logger.error("Cannot determine workspace mappings for workspace \"$path\".", e) return TfsBasicWorkspaceInfo(serverUri, workspaceName) } return TfsDetailedWorkspaceInfo(mappings, serverUri, workspaceName) } fun getDetailedWorkspaceInfo(path: TfsLocalPath, credentials: TfsCredentials): TfsDetailedWorkspaceInfo? { val workspaceInfo = tryLoadWorkspaceInfo(path) ?: return null val mappings = loadMappings( workspaceInfo, UsernamePasswordCredentials(credentials.login, credentials.password.contents)) return TfsDetailedWorkspaceInfo( mappings, workspaceInfo.serverURI?.toString().orEmpty(), workspaceInfo.name.orEmpty()) } } val client: VersionControlClient private val pathWatcherFactory = ExternallyControlledPathWatcherFactory(lifetime) init { val collection = TFSTeamProjectCollection(serverUri, credentials) lifetime.onTermination { collection.close() } client = collection.versionControlClient.also { it.pathWatcherFactory = pathWatcherFactory it.eventEngine.addNonFatalErrorListener { event -> logger.warn { event.message } } } } val workspaces = Property<List<Workspace>>(listOf()) private fun getWorkspaceFor(path: TfsPath): Workspace? { for (workspace in workspaces.value) { if (workspace.isPathMapped(path)) { return workspace } } return client.tryGetWorkspace(path)?.also { workspaces.value += it } } private fun enumeratePathsWithWorkspace(paths: Iterable<TfsPath>, action: (Workspace, List<TfsPath>) -> Unit) { for ((workspace, workspacePathList) in paths.groupBy(::getWorkspaceFor)) { if (workspace == null) { logger.warn { "Could not determine workspace for paths: " + paths.joinToString() } continue } action(workspace, workspacePathList) } } fun status(paths: List<TfsPath>): List<PendingSet> { val results = mutableListOf<PendingSet>() enumeratePathsWithWorkspace(paths) { workspace, workspacePaths -> val workspaceName = workspace.name val workspaceOwner = workspace.ownerName val itemSpecs = ItemSpec.fromStrings( workspacePaths.mapToArray { it.toCanonicalPathString() }, RecursionType.FULL ) val pendingSets = client.queryPendingSets(itemSpecs, false, workspaceName, workspaceOwner, true) results.addAll(pendingSets) } return results } private fun <TInfo>getLocalItemsInfo( paths: List<TfsLocalPath>, extended: Boolean, converter: (ExtendedItem) -> TInfo ): List<TInfo> { val infos = ArrayList<TInfo>(paths.size) enumeratePathsWithWorkspace(paths) { workspace, workspacePaths -> // Pass NONE to get lock info in extended mode. val downloadType = if (extended) GetItemsOptions.NONE else GetItemsOptions.LOCAL_ONLY val itemSpecs = workspacePaths.mapToArray { it.toCanonicalPathItemSpec(RecursionType.NONE) } val extendedItems = workspace.getExtendedItems(itemSpecs, DeletedState.ANY, ItemType.ANY, downloadType) .asSequence() .flatMap { it.asSequence() } for (extendedItem in extendedItems) { infos.add(converter(extendedItem)) } } return infos } fun getLocalItemsInfo(paths: List<TfsLocalPath>): List<TfsLocalItemInfo> = getLocalItemsInfo(paths, false) { it.toLocalItemInfo() } fun getExtendedLocalItemsInfo(paths: List<TfsLocalPath>): List<TfsExtendedItemInfo> = getLocalItemsInfo(paths, true) { it.toExtendedItemInfo() } fun invalidatePaths(paths: List<TfsLocalPath>) { pathWatcherFactory.pathsInvalidated.fire(paths.map { Paths.get(it.path) }) } private fun performLocalChanges( paths: List<TfsPath>, changeListener: NewPendingChangeListener, errorListener: NonFatalErrorListener, action: (Workspace, List<TfsPath>) -> Unit) { val eventEngine = client.eventEngine eventEngine.withNewPendingChangeListener(changeListener) { eventEngine.withNonFatalErrorListener(errorListener) { enumeratePathsWithWorkspace(paths) { workspace, workspacePaths -> action(workspace, workspacePaths) } } } } fun addFiles(paths: List<TfsLocalPath>): List<TfsLocalPath> { val addedEvents = mutableListOf<PendingChangeEvent>() val changeListener = NewPendingChangeListener { event -> if (event.pendingChange.changeType.contains(ChangeType.ADD)) { addedEvents.add(event) } } val errorListener = NonFatalErrorListener { logger.warn { "Non-fatal error detected: ${it.message}" } } performLocalChanges(paths, changeListener, errorListener) { workspace, workspacePaths -> workspace.pendAdd( workspacePaths.mapToArray { it.toCanonicalPathString() }, false, null, LockLevel.UNCHANGED, GetOptions.NONE, PendChangesOptions.APPLY_LOCAL_ITEM_EXCLUSIONS ) } return addedEvents.map { TfsLocalPath(it.pendingChange.localItem) } } fun deletePathsRecursively(paths: List<TfsPath>): TfsDeleteResult { val deletedEvents = mutableListOf<PendingChangeEvent>() val itemNotExistsFailures = mutableListOf<Failure>() val otherFailures = mutableListOf<Failure>() val changeListener = NewPendingChangeListener { event -> if (event.pendingChange.changeType.contains(ChangeType.DELETE)) { deletedEvents.add(event) } } val errorListener = NonFatalErrorListener { event -> event.failure?.let { when (event.failure.code) { FailureCodes.ITEM_NOT_FOUND_EXCEPTION -> itemNotExistsFailures.add(it) else -> otherFailures.add(it) } } } performLocalChanges(paths, changeListener, errorListener) { workspace, workspacePaths -> workspace.pendDelete( workspacePaths.mapToArray { it.toCanonicalPathString() }, RecursionType.FULL, LockLevel.UNCHANGED, GetOptions.NONE, PendChangesOptions.NONE ) } val deletedPaths = deletedEvents.map { TfsLocalPath(it.pendingChange.localItem) } val errorMessages = otherFailures.map { it.toString() } val notFoundPaths = itemNotExistsFailures.map { TfsLocalPath(it.localItem) } return TfsDeleteResult(deletedPaths, notFoundPaths, errorMessages) } fun undoLocalChanges(paths: List<TfsPath>): List<TfsLocalPath> { val undonePaths = mutableListOf<TfsLocalPath>() val listener = UndonePendingChangeListener { undonePaths.add(TfsLocalPath(it.pendingChange.localItem)) } client.eventEngine.withUndonePendingChangeListener(listener) { enumeratePathsWithWorkspace(paths) { workspace, workspacePaths -> val count = workspace.undo(workspacePaths.mapToArray { it.toCanonicalPathItemSpec(RecursionType.NONE) }) logger.info { "Undo result = $count" } } } return undonePaths } fun checkoutFilesForEdit(paths: List<TfsLocalPath>, recursive: Boolean): TfvcCheckoutResult { val editedEvents = mutableListOf<PendingChangeEvent>() val itemNotExistsFailures = mutableListOf<Failure>() val otherFailures = mutableListOf<Failure>() val changeListener = NewPendingChangeListener { event -> if (event.pendingChange.changeType.contains(ChangeType.EDIT)) { editedEvents.add(event) } } val errorListener = NonFatalErrorListener { event -> event.failure?.let { when (event.failure.code) { FailureCodes.ITEM_NOT_FOUND_EXCEPTION -> itemNotExistsFailures.add(it) else -> otherFailures.add(it) } } } val recursionType = if (recursive) RecursionType.FULL else RecursionType.NONE performLocalChanges(paths, changeListener, errorListener) { workspace, workspacePaths -> workspace.pendEdit( workspacePaths.mapToArray { it.toCanonicalPathString() }, recursionType, LockLevel.NONE, null, GetOptions.NONE, PendChangesOptions.NONE ) } val editedPaths = editedEvents.map { TfsLocalPath(it.pendingChange.localItem) } val errorMessages = otherFailures.map { it.toString() } val notFoundPaths = itemNotExistsFailures.map { TfsLocalPath(it.localItem) } return TfvcCheckoutResult(editedPaths, notFoundPaths, errorMessages) } fun renameFile(oldPath: TfsLocalPath, newPath: TfsLocalPath): Boolean { val workspace = getWorkspaceFor(oldPath) if (workspace == null) { logger.warn { "Could not determine workspace for path: \"$oldPath\"" } return false } val changedItems = workspace.pendRename( oldPath.path, newPath.path, LockLevel.NONE, GetOptions.NONE, true, PendChangesOptions.NONE ) logger.info { "pendRename result: $changedItems" } return changedItems == 1 } }
mit
da07a5afaf99ca445daf996008d12516
40.011799
120
0.633892
5.306489
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/gradle/publish/PublishingConfig.kt
2
6227
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle.publish import io.spine.internal.gradle.Repository import org.gradle.api.Project import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.bundling.Jar import org.gradle.kotlin.dsl.apply /** * Information, required to set up publishing of a project using `maven-publish` plugin. * * @param artifactId * a name that a project is known by. * @param destinations * set of repositories, to which the resulting artifacts will be sent. * @param includeProtoJar * tells whether [protoJar] artifact should be published. * @param includeTestJar * tells whether [testJar] artifact should be published. * @param includeDokkaJar * tells whether [dokkaJar] artifact should be published. * @param customPublishing * tells whether subproject declares own publishing and standard one * should not be applied. */ internal class PublishingConfig private constructor( val artifactId: String, val destinations: Set<Repository>, val customPublishing: Boolean, val includeTestJar: Boolean, val includeDokkaJar: Boolean, val includeProtoJar: Boolean ) { /** * Creates an instance for standard publishing of a project module, * specified under [SpinePublishing.modules]. */ constructor( artifactId: String, destinations: Set<Repository>, includeProtoJar: Boolean = true, includeTestJar: Boolean = false, includeDokkaJar: Boolean = false ) : this(artifactId, destinations, false, includeTestJar, includeDokkaJar, includeProtoJar) /** * Creates an instance for publishing a module specified * under [SpinePublishing.modulesWithCustomPublishing]. */ constructor(artifactId: String, destinations: Set<Repository>) : this(artifactId, destinations, customPublishing = true, includeTestJar = false, includeDokkaJar = false, includeProtoJar = false) } /** * Applies this configuration to the given project. * * This method does the following: * * 1. Applies `maven-publish` plugin to the project. * 2. Registers [MavenJavaPublication] in Gradle's * [PublicationContainer][org.gradle.api.publish.PublicationContainer]. * 4. Configures "publish" task. * * The actual list of resulted artifacts is determined by [registerArtifacts]. */ internal fun PublishingConfig.apply(project: Project) = with(project) { apply(plugin = "maven-publish") handlePublication(project) configurePublishTask(destinations) } private fun PublishingConfig.handlePublication(project: Project) { if (customPublishing) { handleCustomPublications(project) } else { createStandardPublication(project) } } private fun PublishingConfig.handleCustomPublications(project: Project) { project.logger.info("The project `${project.name}` is set to provide custom publishing.") val publications = CustomPublications( artifactId = artifactId, destinations = destinations ) publications.registerIn(project) } private fun PublishingConfig.createStandardPublication(project: Project) { val artifacts = project.registerArtifacts(includeProtoJar, includeTestJar, includeDokkaJar) val publication = MavenJavaPublication( artifactId = artifactId, jars = artifacts, destinations = destinations ) publication.registerIn(project) } /** * Registers [Jar] tasks, output of which is used as Maven artifacts. * * By default, only a jar with java compilation output is included into publication. This method * registers tasks which produce additional artifacts. * * The list of additional artifacts to be registered: * * 1. [sourcesJar] – Java, Kotlin and Proto source files. * 2. [protoJar] – only Proto source files. * 3. [javadocJar] – documentation, generated upon Java files. * 4. [testJar] – compilation output of "test" source set. * 5. [dokkaJar] - documentation generated by Dokka. * * Registration of [protoJar], [testJar] and [dokkaJar] is optional. It can be controlled by the * method's parameters. * * @return the list of the registered tasks. */ private fun Project.registerArtifacts( includeProtoJar: Boolean = true, includeTestJar: Boolean = false, includeDokkaJar: Boolean = false ): Set<TaskProvider<Jar>> { val artifacts = mutableSetOf( sourcesJar(), javadocJar(), ) // We don't want to have an empty "proto.jar" when a project doesn't have any Proto files. if (hasProto() && includeProtoJar) { artifacts.add(protoJar()) } // Here, we don't have the corresponding `hasTests()` check, since this artifact is disabled // by default. And turning it on means "We have tests and need them to be published." if (includeTestJar) { artifacts.add(testJar()) } if(includeDokkaJar) { artifacts.add(dokkaJar()) } return artifacts }
apache-2.0
876d17e0f985bd4fd4e7d424fa6b7098
35.368421
96
0.715871
4.496746
false
true
false
false
arturbosch/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/reporting/Colorizer.kt
1
786
package io.gitlab.arturbosch.detekt.core.reporting import org.jetbrains.kotlin.com.intellij.openapi.util.SystemInfo private const val ESC = "\u001B" private val RESET = Color(0) private val RED = Color(31) private val YELLOW = Color(33) private val escapeSequenceRegex = """$ESC\[\d+m""".toRegex() private data class Color(private val value: Byte) { val escapeSequence: String get() = "$ESC[${value}m" } private val isColoredOutputSupported: Boolean = !SystemInfo.isWindows private fun String.colorized(color: Color) = if (isColoredOutputSupported) { "${color.escapeSequence}$this${RESET.escapeSequence}" } else { this } fun String.red() = colorized(RED) fun String.yellow() = colorized(YELLOW) fun String.decolorized() = this.replace(escapeSequenceRegex, "")
apache-2.0
db05db56ed5badfbe35cb810e06f966d
29.230769
76
0.735369
3.524664
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/git/GitCommitTask.kt
1
1884
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.tools.git import uk.co.nickthecoder.paratask.AbstractCommandTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.parameters.BooleanParameter import uk.co.nickthecoder.paratask.parameters.FileParameter import uk.co.nickthecoder.paratask.parameters.StringParameter import uk.co.nickthecoder.paratask.util.HasDirectory import uk.co.nickthecoder.paratask.util.process.OSCommand import java.io.File class GitCommitTask() : AbstractCommandTask(), HasDirectory { override val taskD = TaskDescription("gitCommit") val messageP = StringParameter("message", columns = 60, rows = 10) val allP = BooleanParameter("all") val directoryP = FileParameter("directory", expectFile = false) override val directory by directoryP init { taskD.addParameters(messageP, allP, directoryP, outputP) } constructor(directory: File, all: Boolean = false) : this() { this.directoryP.value = directory this.allP.value = all } override fun createCommand() : OSCommand { return OSCommand("git", "commit", "-m", messageP.value, if (allP.value == true) "-a" else null).dir(directoryP.value!!) } }
gpl-3.0
4544ee24dc8da008ccd25cf56d2126b6
34.566038
127
0.756369
4.186667
false
false
false
false
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/LlvmModuleSpecificationImpl.kt
1
1860
/* * Copyright 2010-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.kotlin.backend.konan import org.jetbrains.kotlin.backend.konan.descriptors.konanLibrary import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.ir.declarations.IrDeclaration import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.util.module import org.jetbrains.kotlin.library.KotlinLibrary // TODO: consider making two implementations: for producing cache and anything else. internal class LlvmModuleSpecificationImpl( private val cachedLibraries: CachedLibraries, private val producingCache: Boolean, private val librariesToCache: Set<KotlinLibrary> ) : LlvmModuleSpecification { override val isFinal: Boolean get() = !producingCache override fun importsKotlinDeclarationsFromOtherObjectFiles(): Boolean = cachedLibraries.hasStaticCaches // A bit conservative but still valid. override fun importsKotlinDeclarationsFromOtherSharedLibraries(): Boolean = cachedLibraries.hasDynamicCaches // A bit conservative but still valid. override fun containsLibrary(library: KotlinLibrary): Boolean = if (producingCache) { library in librariesToCache } else { !cachedLibraries.isLibraryCached(library) } override fun containsModule(module: IrModuleFragment): Boolean = containsModule(module.descriptor) override fun containsModule(module: ModuleDescriptor): Boolean = module.konanLibrary.let { it == null || containsLibrary(it) } override fun containsDeclaration(declaration: IrDeclaration): Boolean = declaration.module.konanLibrary.let { it == null || containsLibrary(it) } }
apache-2.0
de11fa490939c63ce100bacfc7f0f8b2
41.272727
101
0.756989
4.986595
false
false
false
false
almibe/library-weasel-orientdb-admin
src/main/kotlin/org/libraryweasel/orientdb/developer/query/QueryManager.kt
1
1733
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.libraryweasel.orientdb.developer.query import com.google.gson.GsonBuilder import com.google.gson.JsonParser import com.orientechnologies.orient.core.sql.executor.OResultSet import org.libraryweasel.database.api.DatabasePool import org.libraryweasel.servo.Component import org.libraryweasel.servo.Service import java.util.stream.Collectors @Component(QueryManager::class) class QueryManager { @Service @Volatile private lateinit var databasePool: DatabasePool fun runScript(script: String): String { val database = databasePool.acquire() return try { database.activateOnCurrentThread() val result = database.command(script) resultToJson(result) } catch (ex: Exception) { exceptionMessage(ex) } finally { database.close() } } private fun resultToJson(o: OResultSet): String { var resultString = o.stream().map { it.toJSON() }.collect(Collectors.joining(",", "[", "]")) if (resultString.isBlank()) { resultString = """{"result":"okay"}""" } val gson = GsonBuilder().setPrettyPrinting().create() val json = JsonParser().parse(resultString).asJsonArray return gson.toJson(json) } private fun exceptionMessage(e: Exception): String { val sb = StringBuilder() sb.append(e.message) e.stackTrace.forEach { sb.append(" $it\n") } return sb.toString() } }
mpl-2.0
89ecb2f975e795ba66fa7953d6d73d99
31.698113
70
0.645701
4.354271
false
false
false
false
olonho/carkot
car_srv/clients/flash/src/main/java/Utils.kt
1
3210
import com.martiansoftware.jsap.FlaggedOption import com.martiansoftware.jsap.JSAP import com.martiansoftware.jsap.JSAPResult import java.io.File import java.io.IOException import java.io.PrintWriter import java.util.* fun saveFileConfig(actualValues: Map<String, String>) { var dataToFile = "" actualValues.forEach { e -> dataToFile += ("${e.key}:${e.value}\n") } val file = File(configFileName) if (!file.exists()) { try { file.createNewFile() } catch (e: IOException) { println("error creating config file. parameters don't saved") e.printStackTrace() return } } PrintWriter(file).use { printWriter -> printWriter.write(dataToFile) printWriter.flush() } } fun getActualValue(argName: String, commandLineConfig: JSAPResult, fileConfig: Map<String, String>, defaultValue: String = ""): String { return if (commandLineConfig.getString(argName) != null) { commandLineConfig.getString(argName) } else { fileConfig.getOrElse(argName, { defaultValue }) } } fun readFileConfig(): Map<String, String> { val result = mutableMapOf<String, String>() try { Scanner(File(configFileName)).use { scanner -> while (scanner.hasNext()) { val currentString = scanner.nextLine() val keyValuePair = currentString.split(":") if (keyValuePair.size != 2) { continue } else { result.put(keyValuePair[0], keyValuePair[1]) } } } } catch (e: IOException) { } return result } fun setOptions(jsap: JSAP) { val optHost = FlaggedOption("host").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('h').setLongFlag("host") optHost.help = "write here only ip address. domain name (e.g. vk.com is incorrect)" val optPort = FlaggedOption("port").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('p').setLongFlag("port") val optBinPath = FlaggedOption("flash").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('f').setLongFlag("flash") val optHelp = FlaggedOption("help").setStringParser(JSAP.BOOLEAN_PARSER).setRequired(false).setDefault("false").setLongFlag("help") jsap.registerParameter(optHost) jsap.registerParameter(optPort) jsap.registerParameter(optBinPath) jsap.registerParameter(optHelp) } fun isCorrectArguments(actualValues: Map<String, String>): Boolean { //host and flash file its required. val host = actualValues.getOrElse("host", { "" }) val flashFilePath = actualValues.getOrElse("flash", { "" }) if (host.equals("") || flashFilePath.equals("")) { println("incorrect args (host/flash file must be initialized)") return false } val file = File(flashFilePath) if (!file.exists()) { println("file ${file.absoluteFile} not exist") return false } val ipRegex = Regex("^(?:[0-9]{1,3}.){3}[0-9]{1,3}$") if (!ipRegex.matches(host)) { println("incorrect server address.") return false } return true }
mit
f3a386114f57970687ed783ba156cdcb
35.078652
137
0.637072
4.115385
false
true
false
false
nextcloud/android
app/src/androidTest/java/com/nextcloud/client/account/RegisteredUserTest.kt
1
3907
/* * Nextcloud Android client application * * @author Chris Narkiewicz <[email protected]> * Copyright (C) 2020 Chris Narkiewicz * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.account import android.accounts.Account import android.net.Uri import android.os.Parcel import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.lib.common.OwnCloudBasicCredentials import com.owncloud.android.lib.resources.status.OwnCloudVersion import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import java.net.URI class RegisteredUserTest { private companion object { fun buildTestUser(accountName: String): RegisteredUser { val uri = Uri.parse("https://nextcloud.localhost") val credentials = OwnCloudBasicCredentials("user", "pass") val account = Account(accountName, "test-type") val ownCloudAccount = OwnCloudAccount(uri, credentials) val server = Server( uri = URI(uri.toString()), version = OwnCloudVersion.nextcloud_17 ) return RegisteredUser( account = account, ownCloudAccount = ownCloudAccount, server = server ) } } private lateinit var user: RegisteredUser @Before fun setUp() { user = buildTestUser("[email protected]") } @Test fun registeredUserImplementsParcelable() { // GIVEN // registered user instance // WHEN // instance is serialized into Parcel // instance is retrieved from Parcel val parcel = Parcel.obtain() parcel.setDataPosition(0) parcel.writeParcelable(user, 0) parcel.setDataPosition(0) val deserialized = parcel.readParcelable<User>(User::class.java.classLoader) // THEN // retrieved instance in distinct // instances are equal assertNotSame(user, deserialized) assertTrue(deserialized is RegisteredUser) assertEquals(user, deserialized) } @Test fun accountNamesEquality() { // GIVEN // registered user instance with lower-case account name // registered user instance with mixed-case account name val user1 = buildTestUser("account_name") val user2 = buildTestUser("Account_Name") // WHEN // account names are checked for equality val equal = user1.nameEquals(user2) // THEN // account names are equal assertTrue(equal) } @Test fun accountNamesEqualityCheckIsNullSafe() { // GIVEN // registered user instance with lower-case account name // null account val user1 = buildTestUser("account_name") val user2: User? = null // WHEN // account names are checked for equality against null val equal = user1.nameEquals(user2) // THEN // account names are not equal assertFalse(equal) } }
gpl-2.0
eff81e0022994e534e43f0db316e82d3
31.831933
84
0.653443
4.88375
false
true
false
false
icapps/niddler-ui
client-lib/src/test/kotlin/com/icapps/niddler/lib/export/har/StreamingHarWriterTest.kt
1
2191
package com.icapps.niddler.lib.export.har import org.junit.Assert import org.junit.Test import java.io.ByteArrayOutputStream /** * @author Nicola Verbeeck * @date 09/11/2017. */ class StreamingHarWriterTest { @Test fun testEmpty() { val out = ByteArrayOutputStream() val writer = StreamingHarWriter(out, creator = Creator(name = "Niddler", version = "1.0")) writer.close() val string = out.toString(Charsets.UTF_8.name()) Assert.assertEquals("{\"log\":{\"version\":\"1.2\",\"creator\":{\"name\":\"Niddler\",\"version\":\"1.0\"},\"entries\":[]}}", string) } @Test fun testAdd() { val out = ByteArrayOutputStream() val writer = StreamingHarWriter(out, creator = Creator(name = "Niddler", version = "1.0")) val entry = Entry(startedDateTime = "2005-04-01T13:38:09-0800", time = 19200.0, request = Request(method = "POST", url = "http://www.test.com/bla", httpVersion = "HTTP/1.1", headers = emptyList(), queryString = emptyList(), postData = null), response = Response(status = 200, statusText = "OK", httpVersion = "HTTP/1.1", content = Content(13, "application/xml", "<>", null), headers = emptyList()), cache = Cache(), timings = Timings(send = 13.0, receive = 344.0, wait = 1213.0)) writer.addEntry(entry) writer.close() val string = out.toString(Charsets.UTF_8.name()) Assert.assertEquals("{\"log\":{\"version\":\"1.2\",\"creator\":{\"name\":\"Niddler\",\"version\":\"1.0\"},\"entries\":[{\"startedDateTime\":\"2005-04-01T13:38:09-0800\",\"time\":19200,\"request\":{\"method\":\"POST\",\"url\":\"http://www.test.com/bla\",\"httpVersion\":\"HTTP/1.1\",\"headers\":[],\"queryString\":[],\"cookies\":[],\"headersSize\":-1,\"bodySize\":-1},\"response\":{\"status\":200,\"statusText\":\"OK\",\"httpVersion\":\"HTTP/1.1\",\"content\":{\"size\":13,\"mimeType\":\"application/xml\",\"text\":\"\\u003c\\u003e\"},\"headers\":[],\"redirectURL\":\"\",\"cookies\":[],\"headersSize\":-1,\"bodySize\":-1},\"cache\":{},\"timings\":{\"send\":13,\"wait\":1213,\"receive\":344}}]}}", string) } }
apache-2.0
c8cb2b4750fc270029de94055ba51bcb
49.976744
711
0.5801
4.027574
false
true
false
false
oldergod/red
app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/match/MatchActivity.kt
1
4990
package com.benoitquenaudon.tvfoot.red.app.domain.match import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import com.benoitquenaudon.rxdatabinding.databinding.RxObservableBoolean import com.benoitquenaudon.tvfoot.red.AUTHORITIES import com.benoitquenaudon.tvfoot.red.PATH_MATCH import com.benoitquenaudon.tvfoot.red.R import com.benoitquenaudon.tvfoot.red.SCHEMES import com.benoitquenaudon.tvfoot.red.app.common.BaseActivity import com.benoitquenaudon.tvfoot.red.app.common.flowcontroller.FlowController import com.benoitquenaudon.tvfoot.red.app.common.notification.MINUTES_BEFORE_NOTIFICATION import com.benoitquenaudon.tvfoot.red.app.data.entity.Match import com.benoitquenaudon.tvfoot.red.app.data.entity.Match.Companion.MATCH_ID import com.benoitquenaudon.tvfoot.red.app.mvi.MviView import com.benoitquenaudon.tvfoot.red.databinding.ActivityMatchBinding import com.benoitquenaudon.tvfoot.red.util.errorHandlingSubscribe import com.google.android.material.snackbar.Snackbar import com.jakewharton.rxbinding2.view.RxView import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import timber.log.Timber import javax.inject.Inject import kotlin.LazyThreadSafetyMode.NONE class MatchActivity : BaseActivity(), MviView<MatchIntent, MatchViewState> { @Inject lateinit var matchBroadcastersAdapter: MatchBroadcastersAdapter @Inject lateinit var flowController: FlowController @Inject lateinit var disposables: CompositeDisposable @Inject lateinit var bindingModel: MatchBindingModel @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val viewModel: MatchViewModel by lazy(NONE) { ViewModelProviders.of(this, viewModelFactory).get(MatchViewModel::class.java) } private val binding: ActivityMatchBinding by lazy(NONE) { DataBindingUtil.setContentView<ActivityMatchBinding>(this, R.layout.activity_match) } private var matchId: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent matchId = intent.getStringExtra(MATCH_ID) val uri: Uri? = intent.data if (matchId == null && AUTHORITIES.contains(uri?.authority) && SCHEMES.contains(uri?.scheme)) { val segments = uri?.pathSegments if (segments?.size == 5 && PATH_MATCH == segments[0]) { matchId = segments[4] } } if (matchId == null) { Timber.w("matchDisplayable id is null %s", uri) Toast.makeText(this, "Cannot find any record for this match.", Toast.LENGTH_LONG) .show() flowController.toMatches() finish() return } setupView() Timber.d("matchDisplayable with load with id %s", matchId) bind() } private fun setupView() { binding.matchDetailBroadcasters.adapter = matchBroadcastersAdapter binding.bindingModel = bindingModel setSupportActionBar(binding.matchToolbar) supportActionBar?.run { setDisplayShowTitleEnabled(false) setDisplayHomeAsUpEnabled(true) } } private fun bind() { disposables.add(viewModel.states().errorHandlingSubscribe(this::render)) viewModel.processIntents(intents()) disposables.add(RxObservableBoolean.propertyChanges(bindingModel.shouldNotifyMatchStart) .errorHandlingSubscribe { shouldNotifyMatchStart -> if (shouldNotifyMatchStart) { Snackbar.make(binding.root, resources.getQuantityString( R.plurals.will_be_notify_desc, MINUTES_BEFORE_NOTIFICATION, MINUTES_BEFORE_NOTIFICATION), Snackbar.LENGTH_LONG).show() } }) } override fun onDestroy() { super.onDestroy() disposables.dispose() } override fun intents(): Observable<MatchIntent> { return Observable.merge(initialIntent(), fabClickIntent()) } private fun initialIntent(): Observable<MatchIntent.InitialIntent> { return Observable.just(MatchIntent.InitialIntent(checkNotNull(matchId, { "MatchId is null" }))) } private fun fabClickIntent(): Observable<MatchIntent.NotifyMatchStartIntent> { return RxView.clicks(binding.notifyMatchStartFab) .map { val match = bindingModel.match.get()!! MatchIntent.NotifyMatchStartIntent( match.matchId, match.startAt, !isMatchNotificationActivated ) } } private val isMatchNotificationActivated: Boolean get() = binding.notifyMatchStartFab.isActivated override fun render(state: MatchViewState) { bindingModel.updateFromState(state) if (state.match != null) { val intent = Intent("REFRESH_NOTIFICATION_STATUS") intent.putExtra(MATCH_ID, state.match.matchId) setResult(RESULT_OK, intent) } } }
apache-2.0
b348df30c3676fb5e8067f78fa7d0a46
33.413793
99
0.738277
4.663551
false
false
false
false
Xenoage/Zong
utils-kotlin/utils-kotlin-jvm/test/com/xenoage/utils/color/ColorTest.kt
1
681
package com.xenoage.utils.color import kotlin.test.Test import kotlin.test.assertEquals /** * Tests for [Color]. */ class ColorTest { @Test fun toColorTest() { var c = Color(0, 0, 1, 0) assertEquals(c, "#00000001".toColor()) c = Color(0, 0, 1, 0xFF) assertEquals(c, "#FF000001".toColor()) assertEquals(c, "#000001".toColor()) c = Color(0x21, 0x16, 0x0B, 0x2C) assertEquals(c, "#2C21160B".toColor()) assertEquals(c, "#2c21160b".toColor()) } @Test fun toHexTest() { var c = Color(0, 0, 1, 0) assertEquals("#00000001", c.toHex()) assertEquals("#000001", c.toHex(false)) c = Color(0x21, 0x16, 0x0B, 0x2C) assertEquals("#2C21160B", c.toHex()) } }
agpl-3.0
70967cef22eacbd26ce84fc023f85a04
20.28125
41
0.643172
2.56015
false
true
false
false
AndroidX/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/HeartRateVariabilitySdnnIndexRecord.kt
3
2105
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** * Captures user's heart rate variability (HRV) as measured by the mean of the standard deviations * of all NN intervals for all of the recording. * * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY) public class HeartRateVariabilitySdnnIndexRecord( override val time: Instant, override val zoneOffset: ZoneOffset?, /** Heart rate variability in milliseconds. Required field. */ public val heartRateVariabilityMillis: Double, override val metadata: Metadata = Metadata.EMPTY, ) : InstantaneousRecord { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HeartRateVariabilitySdnnIndexRecord) return false if (heartRateVariabilityMillis != other.heartRateVariabilityMillis) return false if (time != other.time) return false if (zoneOffset != other.zoneOffset) return false if (metadata != other.metadata) return false return true } override fun hashCode(): Int { var result = 0 result = 31 * result + heartRateVariabilityMillis.hashCode() result = 31 * result + time.hashCode() result = 31 * result + (zoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } }
apache-2.0
7cb48bb33bfa331cb98a23d9cb6429ed
35.929825
98
0.712589
4.431579
false
false
false
false
ryan652/EasyCrypt
easycrypt/src/main/java/com/pvryan/easycrypt/symmetric/performEncrypt.kt
1
3918
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycrypt.symmetric import com.pvryan.easycrypt.Constants import com.pvryan.easycrypt.ECResultListener import com.pvryan.easycrypt.extensions.handleSuccess import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.security.InvalidParameterException import javax.crypto.Cipher import javax.crypto.CipherOutputStream import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec @Suppress("ClassName") internal object performEncrypt { @JvmSynthetic internal fun <T> invoke(input: T, password: String, cipher: Cipher, getKey: (password: String, salt: ByteArray) -> SecretKeySpec, erl: ECResultListener, outputFile: File) { if (outputFile.exists() && outputFile.absolutePath != Constants.DEF_ENCRYPTED_FILE_PATH) { when (input) { is InputStream -> input.close() } erl.onFailure(Constants.ERR_OUTPUT_FILE_EXISTS, FileAlreadyExistsException(outputFile)) return } val salt = ByteArray(Constants.SALT_BYTES_LENGTH) Constants.random.nextBytes(salt) val keySpec = getKey(password, salt) val iv = ByteArray(cipher.blockSize) Constants.random.nextBytes(iv) val ivParams = IvParameterSpec(iv) cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParams) when (input) { is ByteArray -> (iv.plus(salt).plus(cipher.doFinal(input))) .handleSuccess(erl, outputFile, true) is FileInputStream -> { if (outputFile.exists()) { outputFile.delete() } outputFile.createNewFile() val fos = outputFile.outputStream() try { fos.write(iv) fos.write(salt) } catch (e: IOException) { fos.flush() fos.close() input.close() outputFile.delete() erl.onFailure(Constants.ERR_CANNOT_WRITE, e) return } val cos = CipherOutputStream(fos, cipher) try { val size = input.channel.size() val buffer = ByteArray(8192) var bytesCopied: Long = 0 var read = input.read(buffer) while (read > -1) { cos.write(buffer, 0, read) bytesCopied += read erl.onProgress(read, bytesCopied, size) read = input.read(buffer) } } catch (e: IOException) { outputFile.delete() erl.onFailure(Constants.ERR_CANNOT_WRITE, e) return } finally { cos.flush() cos.close() input.close() } erl.onSuccess(outputFile) } else -> erl.onFailure(Constants.ERR_INPUT_TYPE_NOT_SUPPORTED, InvalidParameterException()) } } }
apache-2.0
39fccd6e54317bedb7c184c4b00169f8
32.487179
102
0.55513
5.055484
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
old/old_weather-client/src/main/kotlin/org/tsdes/advanced/rest/weatherclient/MetNoMain.kt
1
1377
package org.tsdes.advanced.rest.weatherclient import javax.ws.rs.client.ClientBuilder import javax.ws.rs.core.UriBuilder /** * A list of Web Services * * http://www.programmableweb.com/ * * Example: Weather forecast * * http://www.yr.no/ * * http://api.met.no/weatherapi/documentation * * http://api.met.no/weatherapi/textforecast/1.6/schema * * Created by arcuri82 on 14-Jun-17. */ fun main(args: Array<String>) { /* We use JAX-RS to access/create RESTful web services. REST = Representational State Transfer JAX-RS is just a spec. Different implementations are for example RestEasy (from JBoss/Wildfly) and Jersey. This is the same concept of Hibernate being just an implementation of JPA. */ //http://api.met.no/weatherapi/textforecast/1.6/?forecast=land&language=nb val uri = UriBuilder.fromUri("https://api.met.no/weatherapi/textforecast/1.6") .port(443) // not necessary, as 443 is default anyway for https .queryParam("forecast", "land") // equivalent to "?forecast=land" .queryParam("language", "nb") // equivalent to "&language=nb" .build() val client = ClientBuilder.newClient() val response = client.target(uri).request("application/xml").get() val xml = response.readEntity(String::class.java) println("Result as string : $xml") }
lgpl-3.0
3814899f799bb24050c5cb98cb1c7186
28.297872
82
0.673929
3.585938
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/ShapeTokens.kt
3
2020
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.unit.dp internal object ShapeTokens { val CornerExtraLarge = RoundedCornerShape(28.0.dp) val CornerExtraLargeTop = RoundedCornerShape( topStart = 28.0.dp, topEnd = 28.0.dp, bottomEnd = 0.0.dp, bottomStart = 0.0.dp ) val CornerExtraSmall = RoundedCornerShape(4.0.dp) val CornerExtraSmallTop = RoundedCornerShape( topStart = 4.0.dp, topEnd = 4.0.dp, bottomEnd = 0.0.dp, bottomStart = 0.0.dp ) val CornerFull = CircleShape val CornerLarge = RoundedCornerShape(16.0.dp) val CornerLargeEnd = RoundedCornerShape( topStart = 0.0.dp, topEnd = 16.0.dp, bottomEnd = 16.0.dp, bottomStart = 0.0.dp ) val CornerLargeTop = RoundedCornerShape( topStart = 16.0.dp, topEnd = 16.0.dp, bottomEnd = 0.0.dp, bottomStart = 0.0.dp ) val CornerMedium = RoundedCornerShape(12.0.dp) val CornerNone = RectangleShape val CornerSmall = RoundedCornerShape(8.0.dp) }
apache-2.0
c29877624cef298709b9dfebdfde932b
32.131148
75
0.661386
4.080808
false
false
false
false
androidx/androidx
compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/gestures/TapPressureGestureDetectorDemo.kt
3
5825
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.demos.gestures import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** * Simple demonstration of subscribing to pressure changes. */ @OptIn(ExperimentalComposeUiApi::class) @Composable fun DetectTapPressureGesturesDemo() { val pressureBoxTextSize = 28.sp Column( modifier = Modifier .fillMaxSize() .padding(8.dp) ) { Text( modifier = Modifier .fillMaxWidth() .weight(1f), textAlign = TextAlign.Center, text = "Each box displays pressure (with and without gestures).\n" + "Use a stylus or finger to see pressure values.\n" + "For some pen supported devices, a finger touch pressure will equal 1.0." ) var gestureOffsetX by remember { mutableStateOf(0f) } var gestureOffsetY by remember { mutableStateOf(0f) } var gesturePressure by remember { mutableStateOf(0f) } // Gestures (detectDragGestures) with pressure. Box( modifier = Modifier .fillMaxWidth() .weight(3f) .background(Color.Blue) .wrapContentSize(Alignment.Center) .clipToBounds() .border(BorderStroke(2.dp, BorderColor)) // Resets x & y when a new press is detected (not necessarily needed for pressure). .pointerInput(Unit) { detectTapGestures( onPress = { gestureOffsetX = 0f gestureOffsetY = 0f } ) } // Retrieves pressure from [PointerInputChange]. .pointerInput(Unit) { detectDragGestures { change: PointerInputChange, dragAmount: Offset -> change.consume() gestureOffsetX += dragAmount.x gestureOffsetY += dragAmount.y gesturePressure = change.pressure } }, contentAlignment = Alignment.TopCenter ) { Text( modifier = Modifier.fillMaxSize(), fontSize = pressureBoxTextSize, textAlign = TextAlign.Center, color = Color.White, text = "detectDragGestures + pressure:\n" + "x: $gestureOffsetX, y: $gestureOffsetY,\n" + "pressure: $gesturePressure" ) } var awaitPointerEventScopePressureMessage by remember { mutableStateOf("Press for value") } // awaitPointerEventScope with pressure. Box( modifier = Modifier .fillMaxWidth() .weight(3f) .background(Color.Green) .wrapContentSize(Alignment.Center) .clipToBounds() .border(BorderStroke(2.dp, BorderColor)) // Retrieves pressure from [PointerInputChange]. .pointerInput(Unit) { awaitPointerEventScope { while (true) { val event = awaitPointerEvent() event.changes.forEach { awaitPointerEventScopePressureMessage = "${it.pressure}" it.consume() } } } }, contentAlignment = Alignment.TopCenter ) { Text( modifier = Modifier.fillMaxSize(), fontSize = pressureBoxTextSize, textAlign = TextAlign.Center, text = "awaitPointerEventScope + pressure:\n$awaitPointerEventScopePressureMessage" ) } } }
apache-2.0
c83d25521e98329850fd6b46b0a4384c
37.833333
99
0.604464
5.449018
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/draw/tools/Marker.kt
1
1941
package com.tomclaw.drawa.draw.tools import android.graphics.DashPathEffect import android.graphics.Paint import android.graphics.Path import java.util.Random class Marker : Tool() { private var startX: Int = 0 private var startY: Int = 0 private var prevX: Int = 0 private var prevY: Int = 0 private var path = Path() private var random = Random() override val alpha = 0x50 override val type = TYPE_MARKER override fun initPaint() = Paint().apply { isAntiAlias = true isDither = true style = Paint.Style.STROKE strokeJoin = Paint.Join.MITER strokeCap = Paint.Cap.BUTT pathEffect = DashPathEffect(floatArrayOf(2f, 0f), 0f) } override fun onTouchDown(x: Int, y: Int) { resetRadius() startX = x startY = y path.moveTo(x.toFloat(), y.toFloat()) path.lineTo(x.toFloat(), y.toFloat()) prevX = x prevY = y drawPath(path) } override fun onTouchMove(x: Int, y: Int) { if (path.isEmpty) { path.moveTo(prevX.toFloat(), prevY.toFloat()) } path.lineTo(x.toFloat(), y.toFloat()) prevX = x prevY = y drawPath(path) } override fun onTouchUp(x: Int, y: Int) { if (path.isEmpty) { path.moveTo(prevX.toFloat(), prevY.toFloat()) } if (x == startX && y == startY) { for (c in 0..2) { path.lineTo(randomizeCoordinate(x).toFloat(), randomizeCoordinate(y).toFloat()) drawPath(path) } } else { path.lineTo(x.toFloat(), y.toFloat()) } drawPath(path) prevX = 0 prevY = 0 } override fun onDraw() = path.reset() private fun randomizeCoordinate(value: Int) = value + random.nextInt(DOT_RADIUS + 1) - DOT_RADIUS / 2 } private const val DOT_RADIUS = 4
apache-2.0
27cb10c450405e31854f7497bc72aa85
22.670732
95
0.563112
4.026971
false
false
false
false
msmoljan/coordinate-logger
src/main/kotlin/com/matkosmoljan/coordinate_logger/CoordinateLoggerApplication.kt
1
1519
package com.matkosmoljan.coordinate_logger import javafx.application.Application import javafx.stage.Stage import javafx.scene.Scene import javafx.fxml.FXMLLoader import javafx.scene.Parent import java.util.* class CoordinateLoggerApplication : Application(), CoordinateLoggerController.Listener { val initialWidth = 640.0 val initialHeight = 480.0 val minStageWidth = 460.0 val minStageHeight = 300.0 val resBundle = "strings" val initialFxml = "/main.fxml" var appName: String? = null var stage: Stage? = null companion object { @JvmStatic fun main(args: Array<String>) { launch(CoordinateLoggerApplication::class.java) } } override fun start(stage: Stage?) { val languageBundle = ResourceBundle.getBundle(resBundle) val fxmlLoader = FXMLLoader(javaClass.getResource(initialFxml)).apply { resources = languageBundle } val root = fxmlLoader.load<Parent>() val scene = Scene(root, initialWidth, initialHeight) appName = languageBundle.getString("app_name") stage?.minWidth = minStageWidth stage?.minHeight = minStageHeight stage?.title = appName stage?.scene = scene stage?.show() this.stage = stage val controller: CoordinateLoggerController = fxmlLoader.getController() controller.listener = this } override fun onImageHoverCoordinatesReceived(x: Int, y: Int) { stage?.title = "$appName ($x, $y)" } }
mit
9f2596e6f8ecb456ecb73281956265f0
27.660377
108
0.676103
4.390173
false
false
false
false
jguerinet/form-generator
library/src/main/java/SwitchItem.kt
1
2421
/* * Copyright 2015-2019 Julien Guerinet * * 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.guerinet.morf import android.graphics.Typeface import android.widget.CompoundButton import androidx.appcompat.widget.SwitchCompat import com.guerinet.morf.base.BaseTextViewItem /** * Form item with a [SwitchCompat] * @author Julien Guerinet * @since 2.0.0 */ class SwitchItem(morf: Morf) : BaseTextViewItem<SwitchItem, SwitchCompat>(morf, SwitchCompat(morf.context)) { init { view.showText = false } var isChecked: Boolean get() = view.isChecked set(value) { view.isChecked = value } /** * @return Item with the switch on if [isChecked] */ fun checked(isChecked: Boolean): SwitchItem = setAndReturn { this.isChecked = isChecked } /** * Sets this [listener] on this [SwitchItem] */ fun onCheckChanged(listener: (item: SwitchItem, isChecked: Boolean) -> Unit) = view.setOnCheckedChangeListener { _, isChecked -> listener(this, isChecked) } /** * @return Item with the [listener] set on the switch */ fun onCheckChanged(listener: CompoundButton.OnCheckedChangeListener?): SwitchItem { view.setOnCheckedChangeListener(listener) return this } /** * Sets the [textOn] and [textOff] texts if not null (both default to null) on the returned item */ fun switchText(textOn: String? = null, textOff: String? = null): SwitchItem { view.showText = true if (textOn != null) { view.textOn = textOn } if (textOff != null) { view.textOff = textOff } return this } override fun typeface(typeface: Typeface?): SwitchItem { // Set the typeface on the switch as well view.setSwitchTypeface(typeface) return super.typeface(typeface) } }
apache-2.0
1fb3878e5e0336ad13a0ffb77c1ecc02
29.2625
100
0.659232
4.42596
false
false
false
false
JavaEden/Orchid
languageExtensions/OrchidWritersBlocks/src/main/kotlin/com/eden/orchid/writersblocks/tags/YoutubeTag.kt
2
2511
package com.eden.orchid.writersblocks.tags import com.caseyjbrooks.clog.Clog import com.eden.orchid.api.compilers.TemplateTag import com.eden.orchid.api.options.annotations.AllOptions import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import java.time.format.DateTimeParseException import java.util.Locale @Description("Embed a YouTube video in your page.", name = "YouTube") class YoutubeTag : TemplateTag("youtube", Type.Simple, true) { @Option @Description("The Youtube video Id.") lateinit var id: String @Option @Description("The start time of the video, in MM:SS format.") lateinit var start: String @Option @StringDefault("560") @Description("The width of the embedded video.") lateinit var width: String @Option @StringDefault("315") @Description("The height of the embedded video.") lateinit var height: String @Option @Description("The aspect ratio of the video in W:L, defaults to 16:9.") @StringDefault("") lateinit var aspectRatio: String @Option @Description("Allowed video attributes.") @StringDefault("accelerometer", "autoplay", "encrypted-media", "gyroscope", "picture-in-picture") lateinit var allow: List<String> override fun parameters() = arrayOf(::id.name, ::start.name, ::aspectRatio.name) fun getStartSeconds(): Int { if (start.isNotBlank() && start.contains(":")) { try { val time = start.split(":") if (time.size == 2) { return (Integer.parseInt(time[0]) * (60)) + (Integer.parseInt(time[1])) } else if (time.size == 3) { return (Integer.parseInt(time[0]) * (60 * 60)) + (Integer.parseInt(time[1]) * (60)) + (Integer.parseInt( time[2] )) } } catch (e: DateTimeParseException) { Clog.e(e.message, e) } } return 0 } fun hasAspectRatio(): Boolean { return aspectRatio.isNotBlank() } fun getAspectRatioPercent(): String { if (aspectRatio.isNotBlank() && aspectRatio.contains(":")) { val (width, height) = aspectRatio.split(":").take(2).map { it.trim() } return "%.2f".format(Locale.ENGLISH, height.toDouble() / width.toDouble() * 100) } return "100" } }
lgpl-3.0
7470b1aee5ffdcd2bd4aaf56d8068ae6
31.61039
124
0.617682
4.255932
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/format/X/XFileHelper.kt
2
3334
package assimp.format.X import assimp.AiMatrix4x4 import assimp.AiVector3D import assimp.AiVector2D import assimp.AiColor3D import assimp.AiColor4D import assimp.AiVectorKey import assimp.AiQuatKey import assimp.ai_real data class Face( var mIndices: MutableList<Int> = mutableListOf() ) data class TexEntry( var mName: String? = null, var mIsNormalMap: Boolean = false ) data class Material( var mName: String? = null, var mIsReference: Boolean = false, var mDiffuse: AiColor4D = AiColor4D(), var mSpecularExponent: ai_real = 0.0.a, var mSpecular: AiColor3D = AiColor3D(), var mEmissive: AiColor3D = AiColor3D(), var mTextures: MutableList<TexEntry> = mutableListOf(), var sceneIndex: Int = Int.MAX_VALUE //TODO: Not sure if this is true ) data class BoneWeight( var mVertex: Int = 0, var mWeight: ai_real = 0.0.a ) data class Bone( var mName: String? = null, var mWeights: MutableList<BoneWeight> = mutableListOf(), var mOffsetMatrix: AiMatrix4x4 = AiMatrix4x4()) //TODO: Not sure if this is true data class Mesh( var mName: String = "", var mPositions: MutableList<AiVector3D> = mutableListOf(), var mPosFaces: MutableList<Face> = mutableListOf(), var mNormals: MutableList<AiVector3D> = mutableListOf(), var mNormFaces: MutableList<Face> = mutableListOf(), var mNumTextures: Int = 0, var mTexCoords: MutableList<MutableList<AiVector2D>> = mutableListOf(), var mNumColorSets: Int = 0, var mColors: MutableList<MutableList<AiColor4D>> = mutableListOf(), var mFaceMaterials: MutableList<Int> = mutableListOf(), var mMaterials: MutableList<Material> = mutableListOf(), var mBones: MutableList<Bone> = mutableListOf() ) data class Node( var mName: String = "", var mTrafoMatrix: AiMatrix4x4 = AiMatrix4x4(), //TODO: Not sure if this is true var mParent: Node?, var mChildren: MutableList<Node> = mutableListOf(), var mMeshes: MutableList<Mesh> = mutableListOf() ) data class MatrixKey( var mTime: Double = 0.0, var mMatrix: AiMatrix4x4 = AiMatrix4x4()) //TODO: Not sure if this is true data class AnimBone( var mBoneName: String? = null, var mPosKeys: MutableList<AiVectorKey> = mutableListOf(), var mRotKeys: MutableList<AiQuatKey> = mutableListOf(), var mScaleKeys: MutableList<AiVectorKey> = mutableListOf(), var mTrafoKeys: MutableList<MatrixKey> = mutableListOf() ) data class Animation( var mName: String? = null, var mAnims: MutableList<AnimBone> = mutableListOf() ) data class Scene( var mRootNode: Node? = null, var mGlobalMeshes: MutableList<Mesh> = mutableListOf(), var mGlobalMaterials: MutableList<Material> = mutableListOf(), var mAnims: MutableList<Animation> = mutableListOf(), var mAnimTicksPerSecond: Int = 0 )
mit
d134e23b46bf0c78af66b03b14d92bac
33.020408
92
0.602579
4.457219
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/settings/QueryProcessorSettingsModel.kt
1
2546
/* * Copyright (C) 2019 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.processor.query.settings import com.intellij.openapi.application.ModalityState import uk.co.reecedunn.intellij.plugin.core.async.executeOnPooledThread import uk.co.reecedunn.intellij.plugin.core.async.invokeLater import uk.co.reecedunn.intellij.plugin.processor.query.CachedQueryProcessorSettings import uk.co.reecedunn.intellij.plugin.processor.query.QueryProcessorSettings import javax.swing.DefaultComboBoxModel class QueryProcessorSettingsModel : DefaultComboBoxModel<CachedQueryProcessorSettings>(), QueryProcessorsListener { // region QueryProcessorsListener override fun onAddProcessor(processor: QueryProcessorSettings) { addElement(CachedQueryProcessorSettings(processor)) } override fun onEditProcessor(index: Int, processor: QueryProcessorSettings) { getElementAt(index)?.let { it.settings = processor it.presentation = null } } override fun onRemoveProcessor(index: Int) { removeElementAt(index) } // endregion override fun addElement(item: CachedQueryProcessorSettings?) { super.addElement(item) item?.let { updateElement(it) } } fun updateElement(item: CachedQueryProcessorSettings) { if (item.presentation != null) return executeOnPooledThread { try { val presentation = item.settings.session.presentation invokeLater(ModalityState.any()) { val index = getIndexOf(item) item.presentation = presentation fireContentsChanged(item, index, index) } } catch (e: Throwable) { invokeLater(ModalityState.any()) { val index = getIndexOf(item) item.presentation = e fireContentsChanged(item, index, index) } } } } }
apache-2.0
43a7bd3b93c6366847fdf61bd0f1c4a5
35.898551
115
0.677926
5.041584
false
false
false
false
heinika/MyGankio
app/src/main/java/lijin/heinika/cn/mygankio/ganhuodataview/GanHuoFragment.kt
1
4159
package lijin.heinika.cn.mygankio.ganhuodataview import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v4.view.ViewCompat import android.support.v4.view.animation.FastOutSlowInInterpolator import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import lijin.heinika.cn.mygankio.R import lijin.heinika.cn.mygankio.entiy.GanHuoBean import lijin.heinika.cn.mygankio.schedulers.SchedulerProvider class GanHuoFragment : Fragment(), GanHuoContract.View { private lateinit var mRecyclerView: RecyclerView private var mSwipeRefreshLayout: SwipeRefreshLayout? = null private var mGanHuoAdapter: GanHuoAdapter? = null private var mPresenter: GanHuoContract.Presenter? = null private var mPage = 1 private lateinit var mType: String override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_ganhuo, container, false) initView(view) mType = arguments!!.getString("type") mPresenter = GanHuoPresenter(this, SchedulerProvider.instance) (mPresenter as GanHuoPresenter).setType(arguments!!.getString("type")) return view } private fun initView(view: View) { mSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout_ganhuo) mRecyclerView = view.findViewById(R.id.recyclerview_android) val fab = view.findViewById<FloatingActionButton>(R.id.fab_to_top_ganhuo) mGanHuoAdapter = GanHuoAdapter(activity!!) mRecyclerView.adapter = mGanHuoAdapter val layoutManager = mRecyclerView.layoutManager as LinearLayoutManager fab.setOnClickListener { mRecyclerView.scrollToPosition(0) } mRecyclerView.setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { val totalItem = layoutManager.itemCount val lastItem = layoutManager.findLastVisibleItemPosition() if (lastItem > totalItem - 4) { mPage++ (mPresenter as GanHuoPresenter).loadGanHuoData(mType, mPage) } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy >= 0) { animateOut(fab) } else { animateIn(fab) } } }) mSwipeRefreshLayout!!.setOnRefreshListener { (mPresenter as GanHuoPresenter).loadGanHuoData(mType, 1) } } override fun setPresenter(presenter: GanHuoContract.Presenter) { mPresenter = presenter } override fun onResume() { super.onResume() mPresenter!!.subscribe() } override fun showLoadingData() { mSwipeRefreshLayout!!.isRefreshing = true } override fun showGanHuo(ganHuoBeanList: MutableList<GanHuoBean>) { mGanHuoAdapter!!.setGanHuoBeanList(ganHuoBeanList) } override fun hideLoadingData() { mSwipeRefreshLayout!!.isRefreshing = false } override fun onPause() { super.onPause() mPresenter!!.unsubscribe() } private fun animateOut(button: FloatingActionButton) { button.visibility = View.GONE ViewCompat.animate(button).scaleX(0.0f).scaleY(0.0f).alpha(0.0f) .setInterpolator(INTERPOLATOR).withLayer() .start() } private fun animateIn(button: FloatingActionButton) { button.visibility = View.VISIBLE ViewCompat.animate(button).scaleX(1.0f).scaleY(1.0f).alpha(1.0f) .setInterpolator(INTERPOLATOR).withLayer() .start() } companion object { private val INTERPOLATOR = FastOutSlowInInterpolator() } }
apache-2.0
9a7b9c2a606819abe313f6665872a867
34.862069
116
0.67949
4.992797
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_reviews/analytic/CreateCourseReviewPressedAnalyticEvent.kt
2
671
package org.stepik.android.domain.course_reviews.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class CreateCourseReviewPressedAnalyticEvent( courseId: Long, title: String, source: String ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_TITLE = "title" private const val PARAM_SOURCE = "source" } override val name: String = "Create course review pressed" override val params: Map<String, Any> = mapOf( PARAM_COURSE to courseId, PARAM_TITLE to title, PARAM_SOURCE to source ) }
apache-2.0
827bcd2afc967ae6a8e95970cfe41ee2
27
60
0.655738
4.503356
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/preference/composables/ListPreference.kt
1
6692
package wangdaye.com.geometricweather.settings.preference.composables import android.content.Context import androidx.annotation.ArrayRes import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.ContentAlpha import androidx.compose.material.RadioButtonDefaults import androidx.compose.material.Text import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.ui.widgets.Material3CardListItem import wangdaye.com.geometricweather.common.ui.widgets.defaultCardListItemElevation import wangdaye.com.geometricweather.theme.compose.DayNightTheme import wangdaye.com.geometricweather.theme.compose.rememberThemeRipple @Composable fun ListPreferenceView( @StringRes titleId: Int, @ArrayRes valueArrayId: Int, @ArrayRes nameArrayId: Int, selectedKey: String, enabled: Boolean = true, onValueChanged: (String) -> Unit, ) { val values = stringArrayResource(valueArrayId) val names = stringArrayResource(nameArrayId) ListPreferenceView( title = stringResource(titleId), summary = { _, value -> names[values.indexOfFirst { it == value }] }, selectedKey = selectedKey, valueArray = values, nameArray = names, enabled = enabled, onValueChanged = onValueChanged, ) } @Composable fun ListPreferenceView( title: String, summary: (Context, String) -> String?, // value -> summary. selectedKey: String, valueArray: Array<String>, nameArray: Array<String>, enabled: Boolean = true, onValueChanged: (String) -> Unit, ) { val listSelectedState = remember { mutableStateOf(selectedKey) } val dialogOpenState = remember { mutableStateOf(false) } Material3CardListItem( elevation = if (enabled) defaultCardListItemElevation else 0.dp ) { Column( modifier = Modifier .fillMaxWidth() .alpha(if (enabled) 1f else 0.5f) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberThemeRipple(), onClick = { dialogOpenState.value = true }, enabled = enabled, ) .padding(dimensionResource(R.dimen.normal_margin)), verticalArrangement = Arrangement.Center, ) { Column { Text( text = title, color = DayNightTheme.colors.titleColor, style = MaterialTheme.typography.titleMedium, ) val currentSummary = summary(LocalContext.current, listSelectedState.value) if (currentSummary?.isNotEmpty() == true) { Spacer(modifier = Modifier.height(dimensionResource(R.dimen.little_margin))) Text( text = currentSummary, color = DayNightTheme.colors.bodyColor, style = MaterialTheme.typography.bodyMedium, ) } } } } if (dialogOpenState.value) { AlertDialog( onDismissRequest = { dialogOpenState.value = false }, title = { Text( text = title, color = MaterialTheme.colorScheme.onSurface, style = MaterialTheme.typography.headlineSmall, ) }, text = { LazyColumn( modifier = Modifier.fillMaxWidth() ) { items(valueArray.zip(nameArray)) { RadioButton( selected = listSelectedState.value == it.first, onClick = { listSelectedState.value = it.first dialogOpenState.value = false onValueChanged(it.first) }, text = it.second, ) } } }, confirmButton = { TextButton( onClick = { dialogOpenState.value = false } ) { Text( text = stringResource(R.string.cancel), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.labelLarge, ) } } ) } } @Composable private fun RadioButton( selected: Boolean, onClick: () -> Unit, text: String, ) { Row( modifier = Modifier .fillMaxWidth() .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberThemeRipple(), onClick = onClick, ) .padding( horizontal = dimensionResource(R.dimen.little_margin), ), verticalAlignment = Alignment.CenterVertically, ) { androidx.compose.material.RadioButton( selected = selected, onClick = onClick, colors = RadioButtonDefaults.colors( selectedColor = MaterialTheme.colorScheme.secondary, unselectedColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f), disabledColor = MaterialTheme.colorScheme.onSurface.copy(alpha = ContentAlpha.disabled) ) ) Spacer(modifier = Modifier.width(dimensionResource(R.dimen.little_margin))) Text( text = text, color = DayNightTheme.colors.titleColor, style = MaterialTheme.typography.titleMedium, ) } }
lgpl-3.0
71b483793a7d8c9cd69c779ca57d4d7e
35.977901
103
0.594292
5.476268
false
false
false
false
anrelic/Anci-OSS
geography/src/api/kotlin/su/jfdev/anci/geography/IntRegion.kt
1
905
package su.jfdev.anci.geography import su.jfdev.anci.geography.services.* import java.lang.Math.* data class IntRegion internal constructor(val from: Vec3i, val to: Vec3i): Collection<Vec3i> { private inline fun sizeOf(getter: Vec3i.() -> Int) = max(to.getter() - from.getter() + 1, 0) override val size = sizeOf { x } * sizeOf { y } * sizeOf { z } override fun contains(element: Vec3i): Boolean { val (fromX, fromY, fromZ) = from val (toX, toY, toZ) = to val (x, y, z) = element return x in fromX..toX && y in fromY..toY && z in fromZ..toZ } operator fun contains(locations: Collection<Vec3i>) = locations.all { it in this } override fun containsAll(elements: Collection<Vec3i>) = contains(elements) override fun isEmpty() = size <= 0 override fun iterator(): Iterator<Vec3i> = GeographyService.intRegion.iterator(this) }
mit
5d65aa78f74b0e5f1b9586028c70ea9d
35.24
94
0.651934
3.535156
false
false
false
false
szaboa/ShowTrackerMVP
app/src/main/java/com/cdev/showtracker/ui/category/CategoryViewGroup.kt
1
1280
package com.cdev.showtracker.ui.category import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import com.cdev.showtracker.R import com.cdev.showtracker.model.Category import com.cdev.showtracker.model.TvShow import kotlinx.android.synthetic.main.layout_category.view.* class CategoryViewGroup(context: Context?) : LinearLayout(context) { private var itemSelectionListener: ((View, TvShow) -> Unit)? = null private val categoryAdapter: CategoryAdapter = CategoryAdapter() init { LayoutInflater.from(context).inflate(R.layout.layout_category, this) recyclerView.adapter = categoryAdapter // callback to CategoryFragment categoryAdapter.setOnItemSelectionListener { i, tvShow -> itemSelectionListener?.let { it(i, tvShow) } } recyclerView.layoutManager = LinearLayoutManager(context, HORIZONTAL, false) } fun setData(category: Category) { tvCategoryName.text = category.name categoryAdapter.addData(category.tvShows) } fun setOnItemSelectionListener(itemSelectionListener: (View, TvShow) -> Unit) { this.itemSelectionListener = itemSelectionListener } }
mit
ccc2ab12baf247eefd542caf098b7476
34.583333
112
0.757813
4.705882
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/ClassBytecodeFinder.kt
2
5039
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger import com.intellij.openapi.compiler.CompilerPaths import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.isFile import com.intellij.util.io.readBytes import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.resolve.jvm.JvmClassName import java.io.IOException import java.nio.file.Path class ClassBytecodeFinder(private val project: Project, private val jvmName: JvmClassName, private val file: VirtualFile) { private companion object { private val LOG = Logger.getInstance(ClassBytecodeFinder::class.java) } private val module = ProjectFileIndex.getInstance(project).getModuleForFile(file) fun find(): ByteArray? = findInCompilerOutput() ?: findInLibraries() private fun findInLibraries(): ByteArray? { if (!RootKindFilter.librarySources.matches(project, file)) { return null } val classFileName = jvmName.internalName.substringAfterLast('/') val fileFinder = getFinderForLibrary() for (variant in findTopLevelClassNameVariants()) { val variantClassFile = fileFinder.findVirtualFileWithHeader(ClassId.fromString(variant)) if (variantClassFile != null && variant == jvmName.internalName) { return readFile(variantClassFile) } val packageDir = variantClassFile?.parent if (packageDir != null) { val classFile = packageDir.findChild("$classFileName.class") if (classFile != null) { return readFile(classFile) } } } return null } private fun readFile(file: VirtualFile): ByteArray? { try { return file.contentsToByteArray(false) } catch (e: IOException) { // Ensure results are consistent LOG.debug("Can't read class file $jvmName", e) return null } } private fun getFinderForLibrary(): VirtualFileFinder { val fileFinderFactory = VirtualFileFinderFactory.getInstance(project) val fileFinders = mutableListOf<VirtualFileFinder>() if (module != null) { // Prioritize libraries from current module and its dependencies fileFinders += fileFinderFactory.create(GlobalSearchScope.moduleWithLibrariesScope(module)) fileFinders += fileFinderFactory.create(GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) } fileFinders += fileFinderFactory.create(GlobalSearchScope.allScope(project)) return CompoundVirtualFileFinder(fileFinders) } // User may have classes with dollars in names (e.g. `class Foo$Bar {}`). We have to find them as well. private fun findTopLevelClassNameVariants(): List<String> { val result = mutableListOf<String>() val jdiName = jvmName.internalName.replace('/', '.') var index = jdiName.indexOf('$', startIndex = 1) while (index >= 0) { result += jdiName.take(index) index = jdiName.indexOf('$', startIndex = index + 1) } result += jvmName.internalName return result } private fun findInCompilerOutput(): ByteArray? { if (!RootKindFilter.projectSources.matches(project, file)) { return null } if (module != null) { return findInModuleOutput(module) } return null } private fun findInModuleOutput(module: Module): ByteArray? { findInSingleModuleOutput(module)?.let { return it } for (implementing in module.implementingModules) { findInSingleModuleOutput(implementing)?.let { return it } } return null } private fun findInSingleModuleOutput(module: Module): ByteArray? { for (outputRoot in CompilerPaths.getOutputPaths(arrayOf(module)).toList()) { val path = Path.of(outputRoot, jvmName.internalName + ".class") if (path.isFile()) { try { return path.readBytes() } catch (e: IOException) { // Ensure results are consistent LOG.debug("Can't read class file $jvmName", e) return null } } } return null } }
apache-2.0
cd179415308b6e90fb727e7d1183173e
36.058824
123
0.660647
5.069416
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/DistributionJARsBuilder.kt
1
50090
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.createTask import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.util.io.NioFiles import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.MultiMap import com.intellij.util.io.Compressor import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.jetbrains.annotations.TestOnly import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.fus.createStatisticsRecorderBundledMetadataProviderTask import org.jetbrains.intellij.build.impl.JarPackager.Companion.getSearchableOptionsDir import org.jetbrains.intellij.build.impl.JarPackager.Companion.pack import org.jetbrains.intellij.build.impl.PlatformModules.collectPlatformModules import org.jetbrains.intellij.build.impl.SVGPreBuilder.createPrebuildSvgIconsTask import org.jetbrains.intellij.build.impl.projectStructureMapping.* import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.copyFile import org.jetbrains.intellij.build.io.copyFileToDir import org.jetbrains.intellij.build.io.zip import org.jetbrains.intellij.build.tasks.* import org.jetbrains.jps.model.artifact.JpsArtifact import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.artifact.elements.JpsLibraryFilesPackagingElement import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.java.JpsProductionModuleOutputPackagingElement import org.jetbrains.jps.model.java.JpsTestModuleOutputPackagingElement import org.jetbrains.jps.model.library.JpsLibrary import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleReference import org.jetbrains.jps.util.JpsPathUtil import java.nio.file.Files import java.nio.file.Path import java.time.ZonedDateTime import java.util.* import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ForkJoinTask import java.util.function.Predicate import java.util.stream.Collectors import kotlin.io.path.isRegularFile /** * Assembles output of modules to platform JARs (in [BuildPaths.distAllDir]/lib directory), * bundled plugins' JARs (in [distAll][BuildPaths.distAllDir]/plugins directory) and zip archives with * non-bundled plugins (in [artifacts][BuildPaths.artifactDir]/plugins directory). */ class DistributionJARsBuilder { val state: DistributionBuilderState @JvmOverloads constructor(context: BuildContext, pluginsToPublish: Set<PluginLayout> = emptySet()) { state = DistributionBuilderState(pluginsToPublish, context) } constructor(state: DistributionBuilderState) { this.state = state } companion object { fun getPluginAutoUploadFile(communityRoot: BuildDependenciesCommunityRoot): Path { val autoUploadFile = communityRoot.communityRoot.resolve("../build/plugins-autoupload.txt") require(autoUploadFile.isRegularFile()) { "File '$autoUploadFile' must exist" } return autoUploadFile } fun readPluginAutoUploadFile(autoUploadFile: Path): Collection<String> { val config = Files.lines(autoUploadFile).use { lines -> lines .map { StringUtil.split(it, "//", true, false)[0] } .map { StringUtil.split(it, "#", true, false)[0].trim() } .filter { !it.isEmpty() } .collect(Collectors.toCollection { TreeSet(String.CASE_INSENSITIVE_ORDER) }) } return config } private fun scramble(context: BuildContext) { val tool = context.proprietaryBuildTools.scrambleTool val actualModuleJars = if (tool == null) emptyMap() else mapOf("internalUtilities.jar" to listOf("intellij.tools.internalUtilities")) pack(actualModuleJars = actualModuleJars, outputDir = context.paths.buildOutputDir.resolve("internal"), context = context) tool?.scramble(context.productProperties.productLayout.mainJarName, context) ?: Span.current().addEvent("skip scrambling because `scrambleTool` isn't defined") // e.g. JetBrainsGateway doesn't have a main jar with license code if (Files.exists(context.paths.distAllDir.resolve("lib/${context.productProperties.productLayout.mainJarName}"))) { packInternalUtilities(context) } } private fun copyAnt(antDir: Path, antTargetFile: Path, context: BuildContext): ForkJoinTask<List<DistributionFileEntry>> { return createTask(spanBuilder("copy Ant lib").setAttribute("antDir", antDir.toString())) { val sources = ArrayList<ZipSource>() val result = ArrayList<DistributionFileEntry>() val libraryData = ProjectLibraryData("Ant", LibraryPackMode.MERGED) copyDir(sourceDir = context.paths.communityHomeDir.communityRoot.resolve("lib/ant"), targetDir = antDir, dirFilter = { !it.endsWith("src") }, fileFilter = Predicate { file -> if (file.toString().endsWith(".jar")) { sources.add(createZipSource(file) { result.add(ProjectLibraryEntry(antTargetFile, libraryData, file, it)) }) false } else { true } }) sources.sort() // path in class log - empty, do not reorder, doesn't matter buildJars(listOf(Triple(antTargetFile, "", sources)), false) result } } private fun packInternalUtilities(context: BuildContext) { val sources = ArrayList<Path>() for (file in context.project.libraryCollection.findLibrary("JUnit4")!!.getFiles(JpsOrderRootType.COMPILED)) { sources.add(file.toPath()) } sources.add(context.paths.buildOutputDir.resolve("internal/internalUtilities.jar")) packInternalUtilities(context.paths.artifactDir.resolve("internalUtilities.zip"), sources) } private fun createBuildBrokenPluginListTask(context: BuildContext): ForkJoinTask<*>? { val buildString = context.fullBuildNumber val targetFile = context.paths.tempDir.resolve("brokenPlugins.db") return createSkippableTask(spanBuilder("build broken plugin list") .setAttribute("buildNumber", buildString) .setAttribute("path", targetFile.toString()), BuildOptions.BROKEN_PLUGINS_LIST_STEP, context) { buildBrokenPlugins(targetFile, buildString, context.options.isInDevelopmentMode) if (Files.exists(targetFile)) { context.addDistFile(java.util.Map.entry(targetFile, "bin")) } } } fun getModulesToCompile(buildContext: BuildContext): Set<String> { val productLayout = buildContext.productProperties.productLayout val result = LinkedHashSet<String>() result.addAll(productLayout.getIncludedPluginModules(java.util.Set.copyOf(productLayout.bundledPluginModules))) collectPlatformModules(result) result.addAll(productLayout.productApiModules) result.addAll(productLayout.productImplementationModules) result.addAll(productLayout.additionalPlatformJars.values()) result.addAll(getToolModules()) result.addAll(buildContext.productProperties.additionalModulesToCompile) result.add("intellij.idea.community.build.tasks") result.add("intellij.platform.images.build") result.removeAll(productLayout.excludedModuleNames) return result } private fun buildThirdPartyLibrariesList(projectStructureMapping: ProjectStructureMapping, context: BuildContext): ForkJoinTask<*>? { return createSkippableTask(spanBuilder("generate table of licenses for used third-party libraries"), BuildOptions.THIRD_PARTY_LIBRARIES_LIST_STEP, context) { val generator = LibraryLicensesListGenerator.create(project = context.project, licensesList = context.productProperties.allLibraryLicenses, usedModulesNames = projectStructureMapping.includedModules) generator.generateHtml(getThirdPartyLibrariesHtmlFilePath(context)) generator.generateJson(getThirdPartyLibrariesJsonFilePath(context)) } } private fun satisfiesBundlingRequirements(plugin: PluginLayout, osFamily: OsFamily?, arch: JvmArchitecture?, context: BuildContext): Boolean { val bundlingRestrictions = plugin.bundlingRestrictions if (bundlingRestrictions.includeInEapOnly && !context.applicationInfo.isEAP) { return false } if (osFamily == null && bundlingRestrictions.supportedOs != OsFamily.ALL) { return false } else if (osFamily != null && (bundlingRestrictions.supportedOs == OsFamily.ALL || !bundlingRestrictions.supportedOs.contains(osFamily))) { return false } else if (arch == null && bundlingRestrictions.supportedArch != JvmArchitecture.ALL) { return false } else{ return arch == null || bundlingRestrictions.supportedArch.contains(arch) } } /** * @return predicate to test if a given plugin should be auto-published */ private fun loadPluginAutoPublishList(buildContext: BuildContext): Predicate<PluginLayout> { val file = getPluginAutoUploadFile(buildContext.paths.communityHomeDir) val config = readPluginAutoUploadFile(file) val productCode = buildContext.applicationInfo.productCode return Predicate<PluginLayout> { plugin -> //see the specification in the plugins-autoupload.txt. Supported rules: // <plugin main module name> ## include the plugin // +<product code>:<plugin main module name> ## include the plugin // -<product code>:<plugin main module name> ## exclude the plugin val module = plugin.mainModule val excludeRule = "-$productCode:$module" val includeRule = "+$productCode:$module" if (config.contains(excludeRule)) false else config.contains(module) || config.contains(includeRule) } } private fun buildKeymapPlugins(targetDir: Path, context: BuildContext): ForkJoinTask<List<Pair<Path, ByteArray>>> { val keymapDir = context.paths.communityHomeDir.communityRoot.resolve("platform/platform-resources/src/keymaps") return buildKeymapPlugins(context.buildNumber, targetDir, keymapDir) } fun checkOutputOfPluginModules(mainPluginModule: String, moduleJars: MultiMap<String, String>, moduleExcludes: MultiMap<String, String>, context: BuildContext) { // don't check modules which are not direct children of lib/ directory val modulesWithPluginXml = ArrayList<String>() for (entry in moduleJars.entrySet()) { if (!entry.key.contains('/')) { for (moduleName in entry.value) { if (containsFileInOutput(moduleName, "META-INF/plugin.xml", moduleExcludes.get(moduleName), context)) { modulesWithPluginXml.add(moduleName) } } } } if (modulesWithPluginXml.size > 1) { context.messages.error("Multiple modules (${modulesWithPluginXml.joinToString()}) from \'$mainPluginModule\' plugin " + "contain plugin.xml files so the plugin won\'t work properly") } if (modulesWithPluginXml.isEmpty()) { context.messages.error("No module from \'$mainPluginModule\' plugin contains plugin.xml") } for (moduleJar in moduleJars.values()) { if (moduleJar != "intellij.java.guiForms.rt" && containsFileInOutput(moduleJar, "com/intellij/uiDesigner/core/GridLayoutManager.class", moduleExcludes.get(moduleJar), context)) { context.messages.error("Runtime classes of GUI designer must not be packaged to \'$moduleJar\' module in" + " \'$mainPluginModule\' plugin, because they are included into a platform JAR. " + "Make sure that 'Automatically copy form runtime classes " + "to the output directory' is disabled in Settings | Editor | GUI Designer.") } } } private fun containsFileInOutput(moduleName: String, filePath: String, excludes: Collection<String>, buildContext: BuildContext): Boolean { val moduleOutput = buildContext.getModuleOutputDir(buildContext.findRequiredModule(moduleName)) val fileInOutput = moduleOutput.resolve(filePath) if (!Files.exists(fileInOutput)) { return false } val set = FileSet(moduleOutput).include(filePath) for (it in excludes) { set.exclude(it) } return !set.isEmpty() } fun layout(layout: BaseLayout, targetDirectory: Path, copyFiles: Boolean, moduleOutputPatcher: ModuleOutputPatcher, moduleJars: MultiMap<String, String>, context: BuildContext): List<DistributionFileEntry> { if (copyFiles) { checkModuleExcludes(layout.moduleExcludes, context) } // patchers must be executed _before_ pack because patcher patches module output if (copyFiles && layout is PluginLayout && !layout.patchers.isEmpty()) { val patchers = layout.patchers spanBuilder("execute custom patchers").setAttribute("count", patchers.size.toLong()).useWithScope { for (patcher in patchers) { patcher.accept(moduleOutputPatcher, context) } } } val tasks = ArrayList<ForkJoinTask<Collection<DistributionFileEntry>>>(3) tasks.add(createTask(spanBuilder("pack")) { val actualModuleJars = TreeMap<String, MutableList<String>>() for (entry in moduleJars.entrySet()) { val modules = entry.value val jarPath = getActualModuleJarPath(entry.key, modules, layout.explicitlySetJarPaths, context) actualModuleJars.computeIfAbsent(jarPath) { mutableListOf() }.addAll(modules) } pack(actualModuleJars, targetDirectory.resolve("lib"), layout, moduleOutputPatcher, !copyFiles, context) }) if (copyFiles && (!layout.resourcePaths.isEmpty() || (layout is PluginLayout && !layout.resourceGenerators.isEmpty()))) { tasks.add(createTask(spanBuilder("pack additional resources")) { layoutAdditionalResources(layout, context, targetDirectory) emptyList() }) } if (!layout.includedArtifacts.isEmpty()) { tasks.add(createTask(spanBuilder("pack artifacts")) { layoutArtifacts(layout, context, copyFiles, targetDirectory) }) } return ForkJoinTask.invokeAll(tasks).flatMap { it.rawResult } } private fun layoutAdditionalResources(layout: BaseLayout, context: BuildContext, targetDirectory: Path) { for (resourceData in layout.resourcePaths) { val source = basePath(context, resourceData.moduleName).resolve(resourceData.resourcePath).normalize() var target = targetDirectory.resolve(resourceData.relativeOutputPath) if (resourceData.packToZip) { if (Files.isDirectory(source)) { // do not compress - doesn't make sense as it is a part of distribution zip(target, mapOf(source to ""), compress = false) } else { target = target.resolve(source.fileName) Compressor.Zip(target).use { it.addFile(target.fileName.toString(), source) } } } else { if (Files.isRegularFile(source)) { copyFileToDir(source, target) } else { copyDir(source, target) } } } if (layout !is PluginLayout) { return } val resourceGenerators = layout.resourceGenerators if (!resourceGenerators.isEmpty()) { spanBuilder("generate and pack resources").useWithScope { for (item in resourceGenerators) { val resourceFile = item.apply(targetDirectory, context) ?: continue if (Files.isRegularFile(resourceFile)) { copyFileToDir(resourceFile, targetDirectory) } else { copyDir(resourceFile, targetDirectory) } } } } } private fun layoutArtifacts(layout: BaseLayout, context: BuildContext, copyFiles: Boolean, targetDirectory: Path): Collection<DistributionFileEntry> { val span = Span.current() val entries = ArrayList<DistributionFileEntry>() for (entry in layout.includedArtifacts.entries) { val artifactName = entry.key val relativePath = entry.value span.addEvent("include artifact", Attributes.of(AttributeKey.stringKey("artifactName"), artifactName)) val artifact = JpsArtifactService.getInstance().getArtifacts(context.project).find { it.name == artifactName } ?: throw IllegalArgumentException("Cannot find artifact $artifactName in the project") var artifactFile: Path if (artifact.outputFilePath == artifact.outputPath) { val source = Path.of(artifact.outputPath!!) artifactFile = targetDirectory.resolve("lib").resolve(relativePath) if (copyFiles) { copyDir(source, targetDirectory.resolve("lib").resolve(relativePath)) } } else { val source = Path.of(artifact.outputFilePath!!) artifactFile = targetDirectory.resolve("lib").resolve(relativePath).resolve(source.fileName) if (copyFiles) { copyFile(source, artifactFile) } } addArtifactMapping(artifact, entries, artifactFile) } return entries } private fun addArtifactMapping(artifact: JpsArtifact, entries: MutableCollection<DistributionFileEntry>, artifactFile: Path) { val rootElement = artifact.rootElement for (element in rootElement.children) { if (element is JpsProductionModuleOutputPackagingElement) { entries.add(ModuleOutputEntry(artifactFile, element.moduleReference.moduleName, 0, "artifact: ${artifact.name}")) } else if (element is JpsTestModuleOutputPackagingElement) { entries.add(ModuleTestOutputEntry(artifactFile, element.moduleReference.moduleName)) } else if (element is JpsLibraryFilesPackagingElement) { val library = element.libraryReference.resolve() val parentReference = library!!.createReference().parentReference if (parentReference is JpsModuleReference) { entries.add(ModuleLibraryFileEntry(artifactFile, parentReference.moduleName, null, 0)) } else { val libraryData = ProjectLibraryData(library.name, LibraryPackMode.MERGED) entries.add(ProjectLibraryEntry(artifactFile, libraryData, null, 0)) } } } } private fun checkModuleExcludes(moduleExcludes: MultiMap<String, String>, context: BuildContext) { for ((module, value) in moduleExcludes.entrySet()) { for (pattern in value) { if (Files.notExists(context.getModuleOutputDir(context.findRequiredModule(module)))) { context.messages.error("There are excludes defined for module `$module`, but the module wasn't compiled;" + " most probably it means that \'$module\' isn\'t include into the product distribution " + "so it makes no sense to define excludes for it.") } } } } } @JvmOverloads fun buildJARs(context: BuildContext, isUpdateFromSources: Boolean = false): ProjectStructureMapping { validateModuleStructure(context) val svgPrebuildTask = createPrebuildSvgIconsTask(context)?.fork() val brokenPluginsTask = createBuildBrokenPluginListTask(context)?.fork() createSkippableTask(spanBuilder("build searchable options index"), BuildOptions.SEARCHABLE_OPTIONS_INDEX_STEP, context) { buildSearchableOptions(context) }?.fork()?.join() val pluginLayouts = getPluginsByModules(context.productProperties.productLayout.bundledPluginModules, context) val antDir = if (context.productProperties.isAntRequired) context.paths.distAllDir.resolve("lib/ant") else null val antTargetFile = antDir?.resolve("lib/ant.jar") val moduleOutputPatcher = ModuleOutputPatcher() val buildPlatformTask = createTask(spanBuilder("build platform lib")) { ForkJoinTask.invokeAll(listOfNotNull( createStatisticsRecorderBundledMetadataProviderTask(moduleOutputPatcher, context), createTask(spanBuilder("write patched app info")) { val moduleOutDir = context.getModuleOutputDir(context.findRequiredModule("intellij.platform.core")) val relativePath = "com/intellij/openapi/application/ApplicationNamesInfo.class" val result = injectAppInfo(moduleOutDir.resolve(relativePath), context.applicationInfo.appInfoXml) moduleOutputPatcher.patchModuleOutput("intellij.platform.core", relativePath, result) } )) val result = buildLib(moduleOutputPatcher, state.platform, context) if (!isUpdateFromSources && context.productProperties.scrambleMainJar) { scramble(context) } context.bootClassPathJarNames = generateClasspath(homeDir = context.paths.distAllDir, mainJarName = context.productProperties.productLayout.mainJarName, antTargetFile = antTargetFile) result } val entries = ForkJoinTask.invokeAll(listOfNotNull( buildPlatformTask, createBuildBundledPluginTask(pluginLayouts, buildPlatformTask, context), createBuildOsSpecificBundledPluginsTask(pluginLayouts, isUpdateFromSources, buildPlatformTask, context), createBuildNonBundledPluginsTask(pluginsToPublish = state.pluginsToPublish, compressPluginArchive = !isUpdateFromSources && context.options.compressNonBundledPluginArchive, buildPlatformLibTask = buildPlatformTask, context = context), if (antDir == null) null else copyAnt(antDir, (antTargetFile)!!, context) )).flatMap { it.rawResult ?: emptyList() } // must be before reorderJars as these additional plugins maybe required for IDE start-up val additionalPluginPaths = context.productProperties.getAdditionalPluginPaths(context) if (!additionalPluginPaths.isEmpty()) { val pluginDir = context.paths.distAllDir.resolve("plugins") for (sourceDir in additionalPluginPaths) { copyDir(sourceDir, pluginDir.resolve(sourceDir.fileName)) } } val projectStructureMapping = ProjectStructureMapping(entries) ForkJoinTask.invokeAll(listOfNotNull( createTask(spanBuilder("generate content report")) { Files.createDirectories(context.paths.artifactDir) ProjectStructureMapping.writeReport(entries, context.paths.artifactDir.resolve("content-mapping.json"), context.paths) Files.newOutputStream(context.paths.artifactDir.resolve("content.json")).use { ProjectStructureMapping.buildJarContentReport(entries, it, context.paths) } }, buildThirdPartyLibrariesList(projectStructureMapping, context) )) // inversed order of join - better for FJP (https://shipilev.net/talks/jeeconf-May2012-forkjoin.pdf, slide 32) brokenPluginsTask?.join() svgPrebuildTask?.join() return projectStructureMapping } /** * Validates module structure to be ensure all module dependencies are included */ fun validateModuleStructure(context: BuildContext) { if (context.options.validateModuleStructure) { ModuleStructureValidator(context, state.platform.moduleJars).validate() } } // Filter out jars with relative paths in name val productModules: List<String> get() { val result = ArrayList<String>() for (moduleJar in state.platform.getJarToIncludedModuleNames()) { // Filter out jars with relative paths in name if (moduleJar.key.contains('\\') || moduleJar.key.contains('/')) { continue } result.addAll((moduleJar.value)) } return result } /** * Build index which is used to search options in the Settings dialog. */ @JvmOverloads fun buildSearchableOptions(context: BuildContext, classpathCustomizer: ((MutableSet<String>) -> Unit)? = null, systemProperties: Map<String, Any> = emptyMap()): Path? { val span = Span.current() if (context.options.buildStepsToSkip.contains(BuildOptions.SEARCHABLE_OPTIONS_INDEX_STEP)) { span.addEvent("skip building searchable options index") return null } val ideClasspath = createIdeClassPath(context) val targetDirectory = getSearchableOptionsDir(context) val messages = context.messages NioFiles.deleteRecursively(targetDirectory) // Start the product in headless mode using com.intellij.ide.ui.search.TraverseUIStarter. // It'll process all UI elements in Settings dialog and build index for them. runApplicationStarter(context = context, tempDir = context.paths.tempDir.resolve("searchableOptions"), ideClasspath = ideClasspath, arguments = listOf("traverseUI", targetDirectory.toString(), "true"), systemProperties = systemProperties, classpathCustomizer = classpathCustomizer) if (!Files.isDirectory(targetDirectory)) { messages.error("Failed to build searchable options index: $targetDirectory does not exist. " + "See log above for error output from traverseUI run.") } val modules = Files.newDirectoryStream(targetDirectory).use { it.toList() } if (modules.isEmpty()) { messages.error("Failed to build searchable options index: $targetDirectory is empty. " + "See log above for error output from traverseUI run.") } else { span.setAttribute(AttributeKey.longKey("moduleCountWithSearchableOptions"), modules.size) span.setAttribute(AttributeKey.stringArrayKey("modulesWithSearchableOptions"), modules.map { targetDirectory.relativize(it).toString() }) } return targetDirectory } fun createIdeClassPath(context: BuildContext): LinkedHashSet<String> { // for some reasons maybe duplicated paths - use set val classPath = LinkedHashSet<String>() Files.createDirectories(context.paths.tempDir) val pluginLayoutRoot = Files.createTempDirectory(context.paths.tempDir, "pluginLayoutRoot") val nonPluginsEntries: MutableList<DistributionFileEntry> = ArrayList() val pluginsEntries: MutableList<DistributionFileEntry> = ArrayList() for (e: DistributionFileEntry in (generateProjectStructureMapping(context, pluginLayoutRoot))) { if (e.path.startsWith(pluginLayoutRoot)) { val relPath = pluginLayoutRoot.relativize(e.path) // For plugins our classloader load jars only from lib folder val parent = relPath.parent if ((parent?.parent) == null && (relPath.parent.toString() == "lib")) { pluginsEntries.add(e) } } else { nonPluginsEntries.add(e) } } for (entry in (nonPluginsEntries + pluginsEntries)) { when (entry) { is ModuleOutputEntry -> classPath.add(context.getModuleOutputDir(context.findRequiredModule(entry.moduleName)).toString()) is LibraryFileEntry -> classPath.add((entry as LibraryFileEntry).libraryFile.toString()) else -> throw UnsupportedOperationException("Entry $entry is not supported") } } return classPath } internal fun generateProjectStructureMapping(context: BuildContext, pluginLayoutRoot: Path): List<DistributionFileEntry> { val moduleOutputPatcher = ModuleOutputPatcher() val libDirLayout = processLibDirectoryLayout(moduleOutputPatcher = moduleOutputPatcher, platform = state.platform, context = context, copyFiles = false).fork() val allPlugins = getPluginsByModules(context.productProperties.productLayout.bundledPluginModules, context) val entries = ArrayList<DistributionFileEntry>() for (plugin in allPlugins) { if (satisfiesBundlingRequirements(plugin, null, null, context)) { entries.addAll(layout(layout = plugin, targetDirectory = pluginLayoutRoot, copyFiles = false, moduleOutputPatcher = moduleOutputPatcher, moduleJars = plugin.moduleJars, context = context)) } } entries.addAll(libDirLayout.join()) return entries } fun createBuildBundledPluginTask(plugins: Collection<PluginLayout>, buildPlatformTask: ForkJoinTask<*>?, context: BuildContext): ForkJoinTask<List<DistributionFileEntry>> { val pluginDirectoriesToSkip = context.options.bundledPluginDirectoriesToSkip return createTask(spanBuilder("build bundled plugins") .setAttribute(AttributeKey.stringArrayKey("pluginDirectoriesToSkip"), pluginDirectoriesToSkip.toList()) .setAttribute("count", plugins.size.toLong())) { val pluginsToBundle = ArrayList<PluginLayout>(plugins.size) plugins.filterTo(pluginsToBundle) { satisfiesBundlingRequirements(it, null, null, context) && !pluginDirectoriesToSkip.contains(it.directoryName) } // Doesn't make sense to require passing here a list with a stable order - unnecessary complication. Just sort by main module. pluginsToBundle.sortWith(PLUGIN_LAYOUT_COMPARATOR_BY_MAIN_MODULE) Span.current().setAttribute("satisfiableCount", pluginsToBundle.size.toLong()) buildPlugins(moduleOutputPatcher = ModuleOutputPatcher(), plugins = pluginsToBundle, targetDirectory = context.paths.distAllDir.resolve(PLUGINS_DIRECTORY), state = state, context = context, buildPlatformTask = buildPlatformTask) } } private fun createBuildOsSpecificBundledPluginsTask(pluginLayouts: Set<PluginLayout>, isUpdateFromSources: Boolean, buildPlatformTask: ForkJoinTask<*>?, context: BuildContext): ForkJoinTask<List<DistributionFileEntry>> { return createTask(spanBuilder("build os-specific bundled plugins").setAttribute("isUpdateFromSources", isUpdateFromSources)) { val platforms = if (isUpdateFromSources) { listOf(SupportedDistribution(os = OsFamily.currentOs, arch = JvmArchitecture.currentJvmArch)) } else { SUPPORTED_DISTRIBUTIONS } ForkJoinTask.invokeAll(platforms.mapNotNull { (osFamily, arch) -> if (!context.shouldBuildDistributionForOS(osFamily, arch)) { return@mapNotNull null } val osSpecificPlugins = pluginLayouts.filter { satisfiesBundlingRequirements(it, osFamily, arch, context) } if (osSpecificPlugins.isEmpty()) { return@mapNotNull null } val outDir = if (isUpdateFromSources) { context.paths.distAllDir.resolve("plugins") } else { getOsAndArchSpecificDistDirectory(osFamily, arch, context).resolve("plugins") } createTask( spanBuilder("build bundled plugins") .setAttribute("os", osFamily.osName) .setAttribute("arch", arch.name) .setAttribute("count", osSpecificPlugins.size.toLong()) .setAttribute("outDir", outDir.toString()) ) { buildPlugins(moduleOutputPatcher = ModuleOutputPatcher(), plugins = osSpecificPlugins, targetDirectory = outDir, state = state, context = context, buildPlatformTask = buildPlatformTask) } }).flatMap { it.rawResult } } } fun createBuildNonBundledPluginsTask(pluginsToPublish: Set<PluginLayout>, compressPluginArchive: Boolean, buildPlatformLibTask: ForkJoinTask<*>?, context: BuildContext): ForkJoinTask<List<DistributionFileEntry>>? { if (pluginsToPublish.isEmpty()) { return null } return createTask(spanBuilder("build non-bundled plugins").setAttribute("count", pluginsToPublish.size.toLong())) { if (context.options.buildStepsToSkip.contains(BuildOptions.NON_BUNDLED_PLUGINS_STEP)) { Span.current().addEvent("skip") return@createTask emptyList() } val nonBundledPluginsArtifacts = context.paths.artifactDir.resolve("${context.applicationInfo.productCode}-plugins") val autoUploadingDir = nonBundledPluginsArtifacts.resolve("auto-uploading") val buildKeymapPluginsTask = buildKeymapPlugins(autoUploadingDir, context).fork() val moduleOutputPatcher = ModuleOutputPatcher() val stageDir = context.paths.tempDir.resolve("non-bundled-plugins-" + context.applicationInfo.productCode) NioFiles.deleteRecursively(stageDir) val dirToJar = ConcurrentLinkedQueue<Map.Entry<String, Path>>() val defaultPluginVersion = if (context.buildNumber.endsWith(".SNAPSHOT")) { "${context.buildNumber}.${pluginDateFormat.format(ZonedDateTime.now())}" } else { context.buildNumber } // buildPlugins pluginBuilt listener is called concurrently val pluginsToIncludeInCustomRepository = ConcurrentLinkedQueue<PluginRepositorySpec>() val autoPublishPluginChecker = loadPluginAutoPublishList(context) val prepareCustomPluginRepositoryForPublishedPlugins = context.productProperties.productLayout.prepareCustomPluginRepositoryForPublishedPlugins val mappings = buildPlugins(moduleOutputPatcher = moduleOutputPatcher, plugins = pluginsToPublish.sortedWith(PLUGIN_LAYOUT_COMPARATOR_BY_MAIN_MODULE), targetDirectory = stageDir, state = state, context = context, buildPlatformTask = buildPlatformLibTask) { plugin, pluginDir -> val targetDirectory = if (autoPublishPluginChecker.test(plugin)) autoUploadingDir else nonBundledPluginsArtifacts val pluginDirName = pluginDir.fileName.toString() val moduleOutput = context.getModuleOutputDir(context.findRequiredModule(plugin.mainModule)) val pluginXmlPath = moduleOutput.resolve("META-INF/plugin.xml") val pluginVersion = if (Files.exists(pluginXmlPath)) { plugin.versionEvaluator.evaluate(pluginXmlPath, defaultPluginVersion, context) } else { defaultPluginVersion } val destFile = targetDirectory.resolve("$pluginDirName-$pluginVersion.zip") if (prepareCustomPluginRepositoryForPublishedPlugins) { val pluginXml = moduleOutputPatcher.getPatchedPluginXml(plugin.mainModule) pluginsToIncludeInCustomRepository.add(PluginRepositorySpec(destFile, pluginXml)) } dirToJar.add(java.util.Map.entry(pluginDirName, destFile)) } bulkZipWithPrefix(commonSourceDir = stageDir, items = dirToJar, compress = compressPluginArchive) buildHelpPlugin(pluginVersion = defaultPluginVersion, context = context)?.let { helpPlugin -> val spec = buildHelpPlugin(helpPlugin = helpPlugin, pluginsToPublishDir = stageDir, targetDir = autoUploadingDir, moduleOutputPatcher = moduleOutputPatcher, context = context) if (prepareCustomPluginRepositoryForPublishedPlugins) { pluginsToIncludeInCustomRepository.add(spec) } } for (item in buildKeymapPluginsTask.join()) { if (prepareCustomPluginRepositoryForPublishedPlugins) { pluginsToIncludeInCustomRepository.add(PluginRepositorySpec(item.first, item.second)) } } if (prepareCustomPluginRepositoryForPublishedPlugins) { val list = pluginsToIncludeInCustomRepository.sortedBy { it.pluginZip } generatePluginRepositoryMetaFile(list, nonBundledPluginsArtifacts, context) generatePluginRepositoryMetaFile(list.filter { it.pluginZip.startsWith(autoUploadingDir) }, autoUploadingDir, context) } mappings } } private fun buildHelpPlugin(helpPlugin: PluginLayout, pluginsToPublishDir: Path, targetDir: Path, moduleOutputPatcher: ModuleOutputPatcher, context: BuildContext): PluginRepositorySpec { val directory = getActualPluginDirectoryName(helpPlugin, context) val destFile = targetDir.resolve("$directory.zip") spanBuilder("build help plugin").setAttribute("dir", directory).useWithScope { buildPlugins(moduleOutputPatcher = moduleOutputPatcher, plugins = listOf(helpPlugin), targetDirectory = pluginsToPublishDir, state = state, context = context, buildPlatformTask = null) zip(targetFile = destFile, dirs = mapOf(pluginsToPublishDir.resolve(directory) to ""), compress = true) null } return PluginRepositorySpec(destFile, moduleOutputPatcher.getPatchedPluginXml(helpPlugin.mainModule)) } } private fun buildPlugins(moduleOutputPatcher: ModuleOutputPatcher, plugins: Collection<PluginLayout>, targetDirectory: Path, state: DistributionBuilderState, context: BuildContext, buildPlatformTask: ForkJoinTask<*>?, pluginBuilt: ((PluginLayout, Path) -> Unit)? = null): List<DistributionFileEntry> { val scrambleTool = context.proprietaryBuildTools.scrambleTool val isScramblingSkipped = context.options.buildStepsToSkip.contains(BuildOptions.SCRAMBLING_STEP) val scrambleTasks = ArrayList<ForkJoinTask<*>>() val releaseVersion = "${context.applicationInfo.majorVersion}${context.applicationInfo.minorVersionMainPart}00" val tasks = plugins.map { plugin -> val isHelpPlugin = "intellij.platform.builtInHelp" == plugin.mainModule if (!isHelpPlugin) { DistributionJARsBuilder.checkOutputOfPluginModules(plugin.mainModule, plugin.moduleJars, plugin.moduleExcludes, context) patchPluginXml(moduleOutputPatcher = moduleOutputPatcher, plugin = plugin, releaseDate = context.applicationInfo.majorReleaseDate, releaseVersion = releaseVersion, pluginsToPublish = state.pluginsToPublish, context = context) } val directoryName = getActualPluginDirectoryName(plugin, context) val pluginDir = targetDirectory.resolve(directoryName) createTask(spanBuilder("plugin").setAttribute("path", context.paths.buildOutputDir.relativize(pluginDir).toString())) { val result = DistributionJARsBuilder.layout(layout = plugin, targetDirectory = pluginDir, copyFiles = true, moduleOutputPatcher = moduleOutputPatcher, moduleJars = plugin.moduleJars, context = context) if (!plugin.pathsToScramble.isEmpty()) { val attributes = Attributes.of(AttributeKey.stringKey("plugin"), directoryName) if (scrambleTool == null) { Span.current() .addEvent("skip scrambling plugin because scrambleTool isn't defined, but plugin defines paths to be scrambled", attributes) } else if (isScramblingSkipped) { Span.current().addEvent("skip scrambling plugin because step is disabled", attributes) } else { scrambleTool.scramblePlugin(context, plugin, pluginDir, targetDirectory)?.let { // we can not start executing right now because the plugin can use other plugins in a scramble classpath scrambleTasks.add(it) } } } pluginBuilt?.invoke(plugin, pluginDir) result } } val entries = ForkJoinTask.invokeAll(tasks).flatMap { it.rawResult } if (!scrambleTasks.isEmpty()) { // scrambling can require classes from platform buildPlatformTask?.let { task -> spanBuilder("wait for platform lib for scrambling").useWithScope { task.join() } } invokeAllSettled(scrambleTasks) } return entries } private const val PLUGINS_DIRECTORY = "plugins" private val PLUGIN_LAYOUT_COMPARATOR_BY_MAIN_MODULE: Comparator<PluginLayout> = compareBy { it.mainModule } internal class PluginRepositorySpec(@JvmField val pluginZip: Path, @JvmField val pluginXml: ByteArray /* content of plugin.xml */) fun getPluginsByModules(modules: Collection<String>, context: BuildContext): Set<PluginLayout> { if (modules.isEmpty()) { return emptySet() } val pluginLayouts = context.productProperties.productLayout.pluginLayouts val pluginLayoutsByMainModule = pluginLayouts.groupBy { it.mainModule } val result = createPluginLayoutSet(modules.size) for (moduleName in modules) { var customLayouts = pluginLayoutsByMainModule.get(moduleName) if (customLayouts == null) { val alternativeModuleName = context.findModule(moduleName)?.name if (alternativeModuleName != moduleName) { customLayouts = pluginLayoutsByMainModule.get(alternativeModuleName) } } if (customLayouts == null) { if (!(moduleName == "kotlin-ultimate.kmm-plugin" || result.add(PluginLayout.simplePlugin(moduleName)))) { throw IllegalStateException("Plugin layout for module $moduleName is already added (duplicated module name?)") } } else { for (layout in customLayouts) { if (layout.mainModule != "kotlin-ultimate.kmm-plugin" && !result.add(layout)) { throw IllegalStateException("Plugin layout for module $moduleName is already added (duplicated module name?)") } } } } return result } @TestOnly fun collectProjectLibrariesWhichShouldBeProvidedByPlatform(plugin: BaseLayout, result: MultiMap<JpsLibrary, JpsModule>, context: BuildContext) { val libsToUnpack = plugin.projectLibrariesToUnpack.values() for (moduleName in plugin.getIncludedModuleNames()) { val module = context.findRequiredModule((moduleName)) val dependencies = JpsJavaExtensionService.dependencies(module) for (library in dependencies.includedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME).libraries) { if (isProjectLibraryUsedByPlugin(library, plugin, libsToUnpack)) { result.putValue(library, module) } } } } internal fun getThirdPartyLibrariesHtmlFilePath(context: BuildContext): Path { return context.paths.distAllDir.resolve("license/third-party-libraries.html") } internal fun getThirdPartyLibrariesJsonFilePath(context: BuildContext): Path { return context.paths.tempDir.resolve("third-party-libraries.json") } /** * Returns path to a JAR file in the product distribution where platform/plugin classes will be placed. If the JAR name corresponds to * a module name and the module was renamed, return the old name to temporary keep the product layout unchanged. */ private fun getActualModuleJarPath(relativeJarPath: String, moduleNames: Collection<String>, explicitlySetJarPaths: Set<String>, context: BuildContext): String { if (explicitlySetJarPaths.contains(relativeJarPath)) { return relativeJarPath } for (moduleName in moduleNames) { if (relativeJarPath == "${convertModuleNameToFileName(moduleName)}.jar" && context.getOldModuleName(moduleName) != null) { return "${context.getOldModuleName(moduleName)}.jar" } } return relativeJarPath } /** * Returns name of directory in the product distribution where plugin will be placed. For plugins which use the main module name as the * directory name return the old module name to temporary keep layout of plugins unchanged. */ fun getActualPluginDirectoryName(plugin: PluginLayout, context: BuildContext): String { if (!plugin.directoryNameSetExplicitly && (plugin.directoryName == convertModuleNameToFileName(plugin.mainModule))) { context.getOldModuleName(plugin.mainModule)?.let { return it } } return plugin.directoryName } private fun basePath(buildContext: BuildContext, moduleName: String): Path { return Path.of(JpsPathUtil.urlToPath(buildContext.findRequiredModule(moduleName).contentRootsList.urls.first())) } fun buildLib(moduleOutputPatcher: ModuleOutputPatcher, platform: PlatformLayout, context: BuildContext): List<DistributionFileEntry> { patchKeyMapWithAltClickReassignedToMultipleCarets(moduleOutputPatcher, context) val libDirMappings = processLibDirectoryLayout(moduleOutputPatcher = moduleOutputPatcher, platform = platform, context = context, copyFiles = true).fork().join() val scrambleTool = context.proprietaryBuildTools.scrambleTool ?: return libDirMappings val libDir = context.paths.distAllDir.resolve("lib") for (forbiddenJarName in scrambleTool.getNamesOfJarsRequiredToBeScrambled()) { check (!Files.exists(libDir.resolve(forbiddenJarName))) { "The following JAR cannot be included into the product 'lib' directory, it need to be scrambled with the main jar: $forbiddenJarName" } } val modulesToBeScrambled = scrambleTool.getNamesOfModulesRequiredToBeScrambled() val productLayout = context.productProperties.productLayout for (jarName in platform.moduleJars.keySet()) { if (jarName != productLayout.mainJarName && jarName != PlatformModules.PRODUCT_JAR) { @Suppress("ConvertArgumentToSet") val notScrambled = platform.moduleJars.get(jarName).intersect(modulesToBeScrambled) if (!notScrambled.isEmpty()) { context.messages.error("Module \'${notScrambled.first()}\' is included into $jarName which is not scrambled.") } } } return libDirMappings } fun processLibDirectoryLayout(moduleOutputPatcher: ModuleOutputPatcher, platform: PlatformLayout, context: BuildContext, copyFiles: Boolean): ForkJoinTask<List<DistributionFileEntry>> { return createTask(spanBuilder("layout").setAttribute("path", context.paths.buildOutputDir.relativize(context.paths.distAllDir).toString())) { DistributionJARsBuilder.layout(platform, context.paths.distAllDir, copyFiles, moduleOutputPatcher, platform.moduleJars, context) } } private fun patchKeyMapWithAltClickReassignedToMultipleCarets(moduleOutputPatcher: ModuleOutputPatcher, context: BuildContext) { if (!context.productProperties.reassignAltClickToMultipleCarets) { return } val moduleName = "intellij.platform.resources" val sourceFile = context.getModuleOutputDir((context.findModule(moduleName))!!).resolve("keymaps/\$default.xml") var text = Files.readString(sourceFile) text = text.replace("<mouse-shortcut keystroke=\"alt button1\"/>", "<mouse-shortcut keystroke=\"to be alt shift button1\"/>") text = text.replace("<mouse-shortcut keystroke=\"alt shift button1\"/>", "<mouse-shortcut keystroke=\"alt button1\"/>") text = text.replace("<mouse-shortcut keystroke=\"to be alt shift button1\"/>", "<mouse-shortcut keystroke=\"alt shift button1\"/>") moduleOutputPatcher.patchModuleOutput(moduleName, "keymaps/\$default.xml", text) } internal fun getOsAndArchSpecificDistDirectory(osFamily: OsFamily, arch: JvmArchitecture, context: BuildContext): Path { return context.paths.buildOutputDir.resolve("dist.${osFamily.distSuffix}.${arch.name}") }
apache-2.0
01f256a058a42dc41211dd67a4695b0f
48.253687
149
0.669854
5.500769
false
false
false
false
SirWellington/alchemy-http-mock
src/test/java/tech/sirwellington/alchemy/http/mock/ActionsTest.kt
1
4237
/* * Copyright © 2019. Sir Wellington. * 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 tech.sirwellington.alchemy.http.mock import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings import tech.sirwellington.alchemy.http.HttpResponse import tech.sirwellington.alchemy.test.hamcrest.isNull import tech.sirwellington.alchemy.test.hamcrest.notNull import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner import tech.sirwellington.alchemy.test.junit.runners.GenerateDate import tech.sirwellington.alchemy.test.junit.runners.Repeat import java.util.Date /** * * @author SirWellington */ @Repeat(20) @RunWith(AlchemyTestRunner::class) class ActionsTest { @Mock private lateinit var httpResponse: HttpResponse @GenerateDate private lateinit var date: Date private lateinit var json: JsonObject private lateinit var gson: Gson @Before fun setUp() { json = JsonObject() gson = Gson() } @Test @Throws(Exception::class) fun testReturnPojo() { val action = Actions.returnPojo(date) assertThat(action, notNull) val result = action.call() assertThat(result, notNull) assertThat(result, equalTo(date)) } @Test @Throws(Exception::class) fun testReturnPojoAsJSON() { val action = Actions.returnPojoAsJSON(date, gson) assertThat(action, notNull) val result = action.call() assertThat(result, notNull) assertThat(result, equalTo(gson.toJsonTree(date))) } @Test @Throws(Exception::class) fun testReturnNullPojo() { val action = Actions.returnPojo(null) assertThat(action, notNull) val result = action.call() assertThat(result, isNull) } @Test @Throws(Exception::class) fun testReturnNullPojoAsJSON() { val action = Actions.returnPojoAsJSON(null, gson) assertThat(action, notNull) val result = action.call() assertThat(result, notNull) assertThat(result, equalTo<JsonElement>(JsonNull.INSTANCE)) } @Test @Throws(Exception::class) fun testReturnNull() { val action = Actions.returnNull<Any>() assertThat(action, notNull) val result = action.call() assertThat(result, isNull) } @Test @Throws(Exception::class) fun testReturnJson() { val action = Actions.returnJson(json) assertThat(action, notNull) val result = action.call() assertThat(result, equalTo<JsonElement>(json)) } @Test @Throws(Exception::class) fun testReturnResponse() { val action = Actions.returnResponse(httpResponse) assertThat(action, notNull) val result = action.call() assertThat(result, equalTo(httpResponse)) } @Test fun testThrowException() { val message = one(alphabeticStrings()) val ex = RuntimeException(message) val action = Actions.throwException<Any>(ex) assertThat(action, notNull) assertThrows { action.call() } .isInstanceOf(RuntimeException::class.java) .hasMessage(message) } }
apache-2.0
1fa97e47bde1e8658df5cd5fbd0b10c9
25.310559
88
0.687677
4.403326
false
true
false
false
Hexworks/zircon
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/components/PanelsExample.kt
1
4372
package org.hexworks.zircon.examples.components import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.ComponentDecorations.halfBlock import org.hexworks.zircon.api.ComponentAlignments.positionalAlignment import org.hexworks.zircon.api.ComponentDecorations.shadow import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.SwingApplications import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.graphics.BoxType import org.hexworks.zircon.api.screen.Screen import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer object PanelsExample { private val theme = ColorThemes.techLight() private val tileset = CP437TilesetResources.rexPaint20x20() @JvmStatic fun main(args: Array<String>) { val tileGrid = SwingApplications.startTileGrid( AppConfig.newBuilder() .withDefaultTileset(tileset) .withSize(Size.create(60, 30)) .build() ) val screen = Screen.create(tileGrid) screen.addComponent( Components.panel() .withDecorations(box(title = "No Render")) .withPreferredSize(18, 5) .withComponentRenderer(NoOpComponentRenderer()) .withAlignment(positionalAlignment(1, 1)) ) screen.addComponent( Components.panel() .withDecorations(shadow()) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(1, 8)) ) screen.addComponent( Components.panel() .withDecorations(box(), shadow()) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(1, 15)) ) screen.addComponent( Components.panel() .withDecorations(box(boxType = BoxType.DOUBLE)) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(1, 22)) ) screen.addComponent( Components.panel() .withDecorations(box(boxType = BoxType.BASIC)) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(21, 1)) ) val disabledPanel = Components.panel() .withDecorations(box(title = "Disabled")) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(21, 8)) .build() screen.addComponent(disabledPanel) disabledPanel.isDisabled = true screen.addComponent( Components.panel() .withDecorations( halfBlock(), shadow() ) .withPreferredSize(18, 5) .withAlignment(positionalAlignment(21, 15)) ) screen.addComponent( Components.panel() .withPreferredSize(18, 5) .withDecorations(box(title = "Wombat", boxType = BoxType.TOP_BOTTOM_DOUBLE)) .withAlignment(positionalAlignment(21, 22)) ) screen.addComponent( Components.panel() .withPreferredSize(18, 5) .withDecorations(box(boxType = BoxType.LEFT_RIGHT_DOUBLE)) .withAlignment(positionalAlignment(41, 1)) ) val panel = Components.panel() .withPreferredSize(Size.create(18, 19)) .withDecorations(box(title = "Parent")) .withAlignment(positionalAlignment(41, 8)) .build() screen.addComponent(panel) val nested0 = Components.panel() .withPreferredSize(14, 15) .withAlignment(positionalAlignment(1, 1)) .withDecorations(box(title = "Nested 0", boxType = BoxType.DOUBLE)) .build() val nested1 = Components.panel() .withPreferredSize(10, 11) .withAlignment(positionalAlignment(1, 1)) .withDecorations(box(title = "Nested 1", boxType = BoxType.DOUBLE)) .build() panel.addComponent(nested0) nested0.addComponent(nested1) screen.display() screen.theme = theme } }
apache-2.0
f4d9daa4d8956059625b59e67a8c4bd5
32.121212
92
0.603156
5.008018
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/extension/replacewithregister/ReplaceWithRegister.kt
1
7517
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.extension.replacewithregister import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.getLineEndOffset import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.SelectionType import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.command.isLine import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.extension.VimExtension import com.maddyhome.idea.vim.extension.VimExtensionFacade import com.maddyhome.idea.vim.extension.VimExtensionFacade.executeNormalWithoutMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing import com.maddyhome.idea.vim.extension.VimExtensionFacade.setOperatorFunction import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.helper.EditorDataContext import com.maddyhome.idea.vim.helper.editorMode import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.mode import com.maddyhome.idea.vim.helper.subMode import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.newapi.IjExecutionContext import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper import com.maddyhome.idea.vim.put.PutData import org.jetbrains.annotations.NonNls class ReplaceWithRegister : VimExtension { override fun getName(): String = "ReplaceWithRegister" override fun init() { VimExtensionFacade.putExtensionHandlerMapping(MappingMode.N, injector.parser.parseKeys(RWR_OPERATOR), owner, RwrMotion(), false) VimExtensionFacade.putExtensionHandlerMapping(MappingMode.N, injector.parser.parseKeys(RWR_LINE), owner, RwrLine(), false) VimExtensionFacade.putExtensionHandlerMapping(MappingMode.X, injector.parser.parseKeys(RWR_VISUAL), owner, RwrVisual(), false) putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("gr"), owner, injector.parser.parseKeys(RWR_OPERATOR), true) putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("grr"), owner, injector.parser.parseKeys(RWR_LINE), true) putKeyMappingIfMissing(MappingMode.X, injector.parser.parseKeys("gr"), owner, injector.parser.parseKeys(RWR_VISUAL), true) } private class RwrVisual : ExtensionHandler { override fun execute(editor: VimEditor, context: ExecutionContext) { val typeInEditor = SelectionType.fromSubMode(editor.subMode) editor.forEachCaret { caret -> val selectionStart = caret.selectionStart val selectionEnd = caret.selectionEnd val visualSelection = caret to VimSelection.create(selectionStart, selectionEnd - 1, typeInEditor, editor) doReplace(editor.ij, caret, PutData.VisualSelection(mapOf(visualSelection), typeInEditor)) } editor.exitVisualMode() } } private class RwrMotion : ExtensionHandler { override val isRepeatable: Boolean = true override fun execute(editor: VimEditor, context: ExecutionContext) { setOperatorFunction(Operator()) executeNormalWithoutMapping(injector.parser.parseKeys("g@"), editor.ij) } } private class RwrLine : ExtensionHandler { override val isRepeatable: Boolean = true override fun execute(editor: VimEditor, context: ExecutionContext) { val caretsAndSelections = mutableMapOf<VimCaret, VimSelection>() editor.forEachCaret { caret -> val logicalLine = caret.getBufferPosition().line val lineStart = editor.getLineStartOffset(logicalLine) val lineEnd = editor.getLineEndOffset(logicalLine, true) val visualSelection = caret to VimSelection.create(lineStart, lineEnd, SelectionType.LINE_WISE, editor) caretsAndSelections += visualSelection doReplace(editor.ij, caret, PutData.VisualSelection(mapOf(visualSelection), SelectionType.LINE_WISE)) } editor.forEachCaret { caret -> val vimStart = caretsAndSelections[caret]?.vimStart if (vimStart != null) { caret.moveToOffset(vimStart) } } } } private class Operator : OperatorFunction { override fun apply(vimEditor: VimEditor, context: ExecutionContext, selectionType: SelectionType): Boolean { val editor = (vimEditor as IjVimEditor).editor val range = getRange(editor) ?: return false val visualSelection = PutData.VisualSelection( mapOf( vimEditor.primaryCaret() to VimSelection.create( range.startOffset, range.endOffset - 1, selectionType, vimEditor ) ), selectionType ) // todo multicaret doReplace(editor, vimEditor.primaryCaret(), visualSelection) return true } private fun getRange(editor: Editor): TextRange? = when (editor.vim.mode) { VimStateMachine.Mode.COMMAND -> VimPlugin.getMark().getChangeMarks(editor.vim) VimStateMachine.Mode.VISUAL -> editor.caretModel.primaryCaret.run { TextRange(selectionStart, selectionEnd) } else -> null } } companion object { @NonNls private const val RWR_OPERATOR = "<Plug>ReplaceWithRegisterOperator" @NonNls private const val RWR_LINE = "<Plug>ReplaceWithRegisterLine" @NonNls private const val RWR_VISUAL = "<Plug>ReplaceWithRegisterVisual" private fun doReplace(editor: Editor, caret: VimCaret, visualSelection: PutData.VisualSelection) { val lastRegisterChar = injector.registerGroup.lastRegisterChar val savedRegister = caret.registerStorage.getRegister(caret, lastRegisterChar) ?: return var usedType = savedRegister.type var usedText = savedRegister.text if (usedType.isLine && usedText?.endsWith('\n') == true) { // Code from original plugin implementation. Correct text for linewise selected text usedText = usedText.dropLast(1) usedType = SelectionType.CHARACTER_WISE } val textData = PutData.TextData(usedText, usedType, savedRegister.transferableData) val putData = PutData( textData, visualSelection, 1, insertTextBeforeCaret = true, rawIndent = true, caretAfterInsertedText = false, putToLine = -1 ) ClipboardOptionHelper.IdeaputDisabler().use { VimPlugin.getPut().putText( IjVimEditor(editor), IjExecutionContext(EditorDataContext.init(editor)), putData, operatorArguments = OperatorArguments( editor.vimStateMachine?.isOperatorPending ?: false, 0, editor.editorMode, editor.subMode ) ) } caret.registerStorage.saveRegister(caret, savedRegister.name, savedRegister) caret.registerStorage.saveRegister(caret, VimPlugin.getRegister().defaultRegister, savedRegister) } } }
mit
8be042ed36d9912f9e9b847ace61bc95
39.853261
132
0.741386
4.55852
false
false
false
false
NCBSinfo/NCBSinfo
app/src/main/java/com/rohitsuratekar/NCBSinfo/database/DatabaseUpdates.kt
2
1551
package com.rohitsuratekar.NCBSinfo.database import android.content.Context import com.rohitsuratekar.NCBSinfo.R import com.rohitsuratekar.NCBSinfo.common.Constants import com.rohitsuratekar.NCBSinfo.common.convertToList import com.rohitsuratekar.NCBSinfo.models.DataUpdateModel import java.text.SimpleDateFormat import java.util.* fun convertToServerTimeStamp(modifiedDate: String): String { val readableFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH) val serverFormat = SimpleDateFormat(Constants.FORMAT_SERVER_TIMESTAMP, Locale.ENGLISH) val cal = Calendar.getInstance().apply { timeInMillis = readableFormat.parse(modifiedDate)?.time!! } return serverFormat.format(Date(cal.timeInMillis)) } // Test function to update or modify database without disturbing user preference fun testUpdate1(context: Context): List<DataUpdateModel> { val tripList = mutableListOf<TripData>() tripList.add( TripData().apply { day = Calendar.MONDAY trips = convertToList(context.getString(R.string.def_ncbs_iisc_week)) } ) val list = mutableListOf<DataUpdateModel>() list.add( DataUpdateModel( "ncbs", "iisc", "shuttle", replaceAll = false, createNew = false, tripList = tripList, deleteRoute = false, updateDate = convertToServerTimeStamp("2019-05-03 14:06:00") ) ) return list }
mit
8c99978622ac4b1259e1cbecfab03b0d
31.717391
98
0.664088
4.685801
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinColorSettingsPage.kt
1
16503
// 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.highlighter import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import com.intellij.openapi.options.colors.RainbowColorSettingsPage import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension import java.lang.reflect.Modifier class KotlinColorSettingsPage : ColorSettingsPage, RainbowColorSettingsPage { override fun getLanguage() = KotlinLanguage.INSTANCE override fun getIcon() = KotlinIcons.SMALL_LOGO override fun getHighlighter(): SyntaxHighlighter = KotlinHighlighter() override fun getDemoText(): String { return """/* Block comment */ <KEYWORD>package</KEYWORD> hello <KEYWORD>import</KEYWORD> kotlin.collections.* // line comment /** * Doc comment here for `SomeClass` * @see <KDOC_LINK>Iterator#next()</KDOC_LINK> */ <ANNOTATION>@Deprecated</ANNOTATION>(<ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES>message</ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES> = "Deprecated class") <BUILTIN_ANNOTATION>private</BUILTIN_ANNOTATION> class <CLASS>MyClass</CLASS><<BUILTIN_ANNOTATION>out</BUILTIN_ANNOTATION> <TYPE_PARAMETER>T</TYPE_PARAMETER> : <TRAIT>Iterable</TRAIT><<TYPE_PARAMETER>T</TYPE_PARAMETER>>>(var <PARAMETER><MUTABLE_VARIABLE><INSTANCE_PROPERTY>prop1</INSTANCE_PROPERTY></MUTABLE_VARIABLE></PARAMETER> : Int) { fun <FUNCTION_DECLARATION>foo</FUNCTION_DECLARATION>(<PARAMETER>nullable</PARAMETER> : String<QUEST>?</QUEST>, <PARAMETER>r</PARAMETER> : <TRAIT>Runnable</TRAIT>, <PARAMETER>f</PARAMETER> : () -> Int, <PARAMETER>fl</PARAMETER> : <TRAIT>FunctionLike</TRAIT>, dyn: <KEYWORD>dynamic</KEYWORD>) { <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>("length\nis ${"$"}{<PARAMETER>nullable</PARAMETER><SAFE_ACCESS>?.</SAFE_ACCESS><INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>} <STRING_ESCAPE><INVALID_STRING_ESCAPE>\e</INVALID_STRING_ESCAPE></STRING_ESCAPE>") <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<PARAMETER>nullable</PARAMETER><EXCLEXCL>!!</EXCLEXCL>.<INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>) val <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = java.util.<CONSTRUCTOR_CALL>ArrayList</CONSTRUCTOR_CALL><Int?>(2) <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER><VARIABLE_AS_FUNCTION_CALL>f</VARIABLE_AS_FUNCTION_CALL></PARAMETER>() + <PARAMETER><VARIABLE_AS_FUNCTION_LIKE_CALL>fl</VARIABLE_AS_FUNCTION_LIKE_CALL></PARAMETER>() val <LOCAL_VARIABLE>myFun</LOCAL_VARIABLE> = <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <FUNCTION_LITERAL_BRACES_AND_ARROW>-></FUNCTION_LITERAL_BRACES_AND_ARROW> "" <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>; var <LOCAL_VARIABLE><MUTABLE_VARIABLE>ref</MUTABLE_VARIABLE></LOCAL_VARIABLE> = <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<INSTANCE_PROPERTY>size</INSTANCE_PROPERTY> ints.<EXTENSION_PROPERTY>lastIndex</EXTENSION_PROPERTY> + <PACKAGE_PROPERTY>globalCounter</PACKAGE_PROPERTY> <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<EXTENSION_FUNCTION_CALL>forEach</EXTENSION_FUNCTION_CALL> <LABEL>lit@</LABEL> <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <KEYWORD>if</KEYWORD> (<FUNCTION_LITERAL_DEFAULT_PARAMETER>it</FUNCTION_LITERAL_DEFAULT_PARAMETER> == null) return<LABEL>@lit</LABEL> <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<FUNCTION_LITERAL_DEFAULT_PARAMETER><SMART_CAST_VALUE>it</SMART_CAST_VALUE></FUNCTION_LITERAL_DEFAULT_PARAMETER> + <LOCAL_VARIABLE><MUTABLE_VARIABLE><WRAPPED_INTO_REF>ref</WRAPPED_INTO_REF></MUTABLE_VARIABLE></LOCAL_VARIABLE>) <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW> dyn.<DYNAMIC_FUNCTION_CALL>dynamicCall</DYNAMIC_FUNCTION_CALL>() dyn.<DYNAMIC_PROPERTY_CALL>dynamicProp</DYNAMIC_PROPERTY_CALL> = 5 val <LOCAL_VARIABLE>klass</LOCAL_VARIABLE> = <CLASS>MyClass</CLASS>::<KEYWORD>class</KEYWORD> val year = java.time.LocalDate.now().<SYNTHETIC_EXTENSION_PROPERTY>year</SYNTHETIC_EXTENSION_PROPERTY> } <BUILTIN_ANNOTATION>override</BUILTIN_ANNOTATION> fun hashCode(): Int { return <KEYWORD>super</KEYWORD>.<FUNCTION_CALL>hashCode</FUNCTION_CALL>() * 31 } } fun Int?.bar() { <KEYWORD>if</KEYWORD> (this != null) { println(<NAMED_ARGUMENT>message =</NAMED_ARGUMENT> <SMART_CAST_RECEIVER>toString</SMART_CAST_RECEIVER>()) } else { println(<SMART_CONSTANT>this</SMART_CONSTANT>.toString()) } } var <PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION><MUTABLE_VARIABLE>globalCounter</MUTABLE_VARIABLE></PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> : Int = <NUMBER>5</NUMBER> <KEYWORD>get</KEYWORD>() = <LOCAL_VARIABLE><MUTABLE_VARIABLE><BACKING_FIELD_VARIABLE>field</BACKING_FIELD_VARIABLE></MUTABLE_VARIABLE></LOCAL_VARIABLE> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS> { val <INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> <KEYWORD>get</KEYWORD>() = 1 fun <FUNCTION_DECLARATION>test</FUNCTION_DECLARATION>() { <INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> } } <KEYWORD>object</KEYWORD> <OBJECT>Obj</OBJECT> <KEYWORD>enum</KEYWORD> <KEYWORD>class</KEYWORD> <ENUM>E</ENUM> { <ENUM_ENTRY>A</ENUM_ENTRY>, <ENUM_ENTRY>B</ENUM_ENTRY> } <KEYWORD>interface</KEYWORD> <TRAIT>FunctionLike</TRAIT> { <BUILTIN_ANNOTATION>operator</BUILTIN_ANNOTATION> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>invoke</FUNCTION_DECLARATION>() = <NUMBER>1</NUMBER> } <KEYWORD>typealias</KEYWORD> <TYPE_ALIAS>Predicate</TYPE_ALIAS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> = (<TYPE_PARAMETER>T</TYPE_PARAMETER>) -> <CLASS>Boolean</CLASS> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>baz</FUNCTION_DECLARATION>(<PARAMETER>p</PARAMETER>: <TYPE_ALIAS>Predicate</TYPE_ALIAS><<CLASS>Int</CLASS>>) = <PARAMETER><VARIABLE_AS_FUNCTION_CALL>p</VARIABLE_AS_FUNCTION_CALL></PARAMETER>(<NUMBER>42</NUMBER>) <KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendCall</FUNCTION_DECLARATION>() = <SUSPEND_FUNCTION_CALL>suspendFn</SUSPEND_FUNCTION_CALL>() <KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendFn</FUNCTION_DECLARATION>() {} """ } override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> { val map = HashMap<String, TextAttributesKey>() for (field in KotlinHighlightingColors::class.java.fields) { if (Modifier.isStatic(field.modifiers)) { try { map.put(field.name, field.get(null) as TextAttributesKey) } catch (e: IllegalAccessException) { assert(false) } } } map.putAll(DslKotlinHighlightingVisitorExtension.descriptionsToStyles) return map } override fun getAttributeDescriptors(): Array<AttributesDescriptor> { infix fun String.to(key: TextAttributesKey) = AttributesDescriptor(this, key) return arrayOf( KotlinBundle.message("highlighter.descriptor.text.builtin.keyword") to KotlinHighlightingColors.KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.val") to KotlinHighlightingColors.VAL_KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.var") to KotlinHighlightingColors.VAR_KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.annotation") to KotlinHighlightingColors.BUILTIN_ANNOTATION, OptionsBundle.message("options.java.attribute.descriptor.number") to KotlinHighlightingColors.NUMBER, OptionsBundle.message("options.java.attribute.descriptor.string") to KotlinHighlightingColors.STRING, KotlinBundle.message("highlighter.descriptor.text.string.escape") to KotlinHighlightingColors.STRING_ESCAPE, OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string") to KotlinHighlightingColors.INVALID_STRING_ESCAPE, OptionsBundle.message("options.java.attribute.descriptor.operator.sign") to KotlinHighlightingColors.OPERATOR_SIGN, OptionsBundle.message("options.java.attribute.descriptor.parentheses") to KotlinHighlightingColors.PARENTHESIS, OptionsBundle.message("options.java.attribute.descriptor.braces") to KotlinHighlightingColors.BRACES, KotlinBundle.message("highlighter.descriptor.text.closure.braces") to KotlinHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW, KotlinBundle.message("highlighter.descriptor.text.arrow") to KotlinHighlightingColors.ARROW, OptionsBundle.message("options.java.attribute.descriptor.brackets") to KotlinHighlightingColors.BRACKETS, OptionsBundle.message("options.java.attribute.descriptor.comma") to KotlinHighlightingColors.COMMA, OptionsBundle.message("options.java.attribute.descriptor.semicolon") to KotlinHighlightingColors.SEMICOLON, KotlinBundle.message("highlighter.descriptor.text.colon") to KotlinHighlightingColors.COLON, KotlinBundle.message("highlighter.descriptor.text.double.colon") to KotlinHighlightingColors.DOUBLE_COLON, OptionsBundle.message("options.java.attribute.descriptor.dot") to KotlinHighlightingColors.DOT, KotlinBundle.message("highlighter.descriptor.text.safe.access") to KotlinHighlightingColors.SAFE_ACCESS, KotlinBundle.message("highlighter.descriptor.text.quest") to KotlinHighlightingColors.QUEST, KotlinBundle.message("highlighter.descriptor.text.exclexcl") to KotlinHighlightingColors.EXCLEXCL, OptionsBundle.message("options.java.attribute.descriptor.line.comment") to KotlinHighlightingColors.LINE_COMMENT, OptionsBundle.message("options.java.attribute.descriptor.block.comment") to KotlinHighlightingColors.BLOCK_COMMENT, KotlinBundle.message("highlighter.descriptor.text.kdoc.comment") to KotlinHighlightingColors.DOC_COMMENT, KotlinBundle.message("highlighter.descriptor.text.kdoc.tag") to KotlinHighlightingColors.KDOC_TAG, KotlinBundle.message("highlighter.descriptor.text.kdoc.value") to KotlinHighlightingColors.KDOC_LINK, OptionsBundle.message("options.java.attribute.descriptor.class") to KotlinHighlightingColors.CLASS, OptionsBundle.message("options.java.attribute.descriptor.type.parameter") to KotlinHighlightingColors.TYPE_PARAMETER, OptionsBundle.message("options.java.attribute.descriptor.abstract.class") to KotlinHighlightingColors.ABSTRACT_CLASS, OptionsBundle.message("options.java.attribute.descriptor.interface") to KotlinHighlightingColors.TRAIT, KotlinBundle.message("highlighter.descriptor.text.annotation") to KotlinHighlightingColors.ANNOTATION, KotlinBundle.message("highlighter.descriptor.text.annotation.attribute.name") to KotlinHighlightingColors.ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES, KotlinBundle.message("highlighter.descriptor.text.object") to KotlinHighlightingColors.OBJECT, KotlinBundle.message("highlighter.descriptor.text.enum") to KotlinHighlightingColors.ENUM, KotlinBundle.message("highlighter.descriptor.text.enumEntry") to KotlinHighlightingColors.ENUM_ENTRY, KotlinBundle.message("highlighter.descriptor.text.typeAlias") to KotlinHighlightingColors.TYPE_ALIAS, KotlinBundle.message("highlighter.descriptor.text.var") to KotlinHighlightingColors.MUTABLE_VARIABLE, KotlinBundle.message("highlighter.descriptor.text.local.variable") to KotlinHighlightingColors.LOCAL_VARIABLE, OptionsBundle.message("options.java.attribute.descriptor.parameter") to KotlinHighlightingColors.PARAMETER, KotlinBundle.message("highlighter.descriptor.text.captured.variable") to KotlinHighlightingColors.WRAPPED_INTO_REF, KotlinBundle.message("highlighter.descriptor.text.instance.property") to KotlinHighlightingColors.INSTANCE_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.instance.property.custom.property.declaration") to KotlinHighlightingColors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.package.property.custom.property.declaration") to KotlinHighlightingColors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.package.property") to KotlinHighlightingColors.PACKAGE_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.field") to KotlinHighlightingColors.BACKING_FIELD_VARIABLE, KotlinBundle.message("highlighter.descriptor.text.extension.property") to KotlinHighlightingColors.EXTENSION_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.synthetic.extension.property") to KotlinHighlightingColors.SYNTHETIC_EXTENSION_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.dynamic.property") to KotlinHighlightingColors.DYNAMIC_PROPERTY_CALL, KotlinBundle.message("highlighter.descriptor.text.android.extensions.property") to KotlinHighlightingColors.ANDROID_EXTENSIONS_PROPERTY_CALL, KotlinBundle.message("highlighter.descriptor.text.it") to KotlinHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER, KotlinBundle.message("highlighter.descriptor.text.fun") to KotlinHighlightingColors.FUNCTION_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.fun.call") to KotlinHighlightingColors.FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.dynamic.fun.call") to KotlinHighlightingColors.DYNAMIC_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.suspend.fun.call") to KotlinHighlightingColors.SUSPEND_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.package.fun.call") to KotlinHighlightingColors.PACKAGE_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.extension.fun.call") to KotlinHighlightingColors.EXTENSION_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.constructor.call") to KotlinHighlightingColors.CONSTRUCTOR_CALL, KotlinBundle.message("highlighter.descriptor.text.variable.as.function.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.variable.as.function.like.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_LIKE_CALL, KotlinBundle.message("highlighter.descriptor.text.smart.cast") to KotlinHighlightingColors.SMART_CAST_VALUE, KotlinBundle.message("highlighter.descriptor.text.smart.constant") to KotlinHighlightingColors.SMART_CONSTANT, KotlinBundle.message("highlighter.descriptor.text.smart.cast.receiver") to KotlinHighlightingColors.SMART_CAST_RECEIVER, KotlinBundle.message("highlighter.descriptor.text.label") to KotlinHighlightingColors.LABEL, KotlinBundle.message("highlighter.descriptor.text.named.argument") to KotlinHighlightingColors.NAMED_ARGUMENT ) + DslKotlinHighlightingVisitorExtension.descriptionsToStyles.map { (description, key) -> description to key }.toTypedArray() } override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY override fun getDisplayName(): String { @Suppress("UnnecessaryVariable") @NlsSafe val name = KotlinLanguage.NAME return name } override fun isRainbowType(type: TextAttributesKey): Boolean { return type == KotlinHighlightingColors.LOCAL_VARIABLE || type == KotlinHighlightingColors.PARAMETER } }
apache-2.0
9e2db7199107c7b174293c653b103bd9
82.348485
338
0.757983
4.708417
false
false
false
false
Emberwalker/Forgelin
src/dev/kotlin/io/drakon/forgelin/debug/ForgelinWorkbench.kt
1
1145
package io.drakon.forgelin.debug import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import org.apache.logging.log4j.LogManager import net.minecraftforge.fml.common.Mod as mod import net.minecraftforge.fml.common.Mod.EventHandler as handler import net.minecraftforge.fml.common.SidedProxy as proxy /** * Test mod (object-style) */ mod(modid = "Forgelin-Workbench-Obj", name = "Forgelin Debug - Object", modLanguageAdapter = "KotlinAdapter") public object ForgelinWorkbench { private val log = LogManager.getLogger("Workbench/Obj") proxy(clientSide = "io.drakon.forgelin.debug.ProxyClient", serverSide = "io.drakon.forgelin.debug.ProxyServer") private var proxy: Proxy? = null public handler fun preinit(evt:FMLPreInitializationEvent) { log.info("Preinit.") } public handler fun init(evt: FMLInitializationEvent) { log.info("Init.") } public handler fun postinit(evt: FMLPostInitializationEvent) { log.info("Postinit.") } }
isc
8c1f715675429683a57caafff8fbaec9
32.705882
115
0.758952
4.118705
false
false
false
false
Carighan/kotlin-koans
src/ii_collections/n15AllAnyAndOtherPredicates.kt
3
1038
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { // Return true if the customer is from the given city todoCollectionTask() } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city todoCollectionTask() } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city todoCollectionTask() } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city todoCollectionTask() } fun Shop.findFirstCustomerFrom(city: City): Customer? { // Return the first customer who lives in the given city, or null if there is none todoCollectionTask() }
mit
c551da5a1d08078edb5b792310444c1f
25.615385
86
0.702312
4.054688
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/iso7816/ISO7816Selector.kt
1
4766
/* * ISO7816Selector.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.iso7816 import au.id.micolous.metrodroid.util.ImmutableByteArray import kotlinx.serialization.* import kotlinx.serialization.internal.StringDescriptor @Serializable(with = ISO7816Selector.Companion::class) data class ISO7816Selector (private val path: List<ISO7816SelectorElement>) { fun formatString(): String { val ret = StringBuilder() for (it in path) { ret.append(it.formatString()) } return ret.toString() } suspend fun select(tag: ISO7816Protocol): ImmutableByteArray? { var fci: ImmutableByteArray? = null for (sel in path) { fci = sel.select(tag) } return fci } /** * If this selector starts with (or is the same as) {@param other}, return true. * * @param other The other selector to compare with. * @return True if this starts with {@param other}. */ fun startsWith(other: ISO7816Selector): Boolean { val a = path.iterator() val b = other.path.iterator() while (true) { if (!b.hasNext()) return true // "other" is shorter or equal length to this if (!a.hasNext()) return false // "other" is longer if (a.next() != b.next()) return false } } fun appendPath(vararg addPath: Int) = ISO7816Selector(path + addPath.map {ISO7816SelectorById(it)} ) /** * Returns the number of [ISO7816SelectorElement]s in this [ISO7816Selector]. */ fun size() = path.size /** * Returns the parent selector, or `null` if at the root (or 1 level from the root). * * @return The parent of the path selector represented by this [ISO7816Selector]. */ fun parent(): ISO7816Selector? { if (path.size <= 1) { return null } return ISO7816Selector(path.dropLast(1)) } override fun toString() = formatString() @Serializer(forClass = ISO7816Selector::class) companion object : KSerializer<ISO7816Selector> { fun makeSelector(vararg path: Int) = ISO7816Selector(path.map {ISO7816SelectorById(it)}) fun makeSelector(name: ImmutableByteArray): ISO7816Selector = ISO7816Selector(listOf<ISO7816SelectorElement>(ISO7816SelectorByName(name))) fun makeSelector(folder: ImmutableByteArray, file: Int): ISO7816Selector = ISO7816Selector(listOf(ISO7816SelectorByName(folder), ISO7816SelectorById(file))) override val descriptor: SerialDescriptor = StringDescriptor.withName("ISO7816Selector") override fun serialize(encoder: Encoder, obj: ISO7816Selector) { encoder.encodeString(obj.formatString()) } override fun deserialize(decoder: Decoder): ISO7816Selector = fromString(decoder.decodeString()) private fun fromString(input: String): ISO7816Selector { val path = mutableListOf<ISO7816SelectorElement>() var off = 0 while (off < input.length) { when (input[off]) { ':' -> { val startOff = off + 1 off++ while (off < input.length && input[off] in listOf('0'..'9', 'a'..'f', 'A'..'F').flatten()) off++ path.add(ISO7816SelectorById(input.substring(startOff, off).toInt(16))) } '#' -> { val startOff = off + 1 off++ while (off < input.length && input[off] in listOf('0'..'9', 'a'..'f', 'A'..'F').flatten()) off++ path.add(ISO7816SelectorByName(ImmutableByteArray.fromHex(input.substring(startOff, off)))) } else -> throw IllegalArgumentException("Bad path $input") } } return ISO7816Selector(path) } } }
gpl-3.0
844e928b354da623edee82fe649386e3
35.381679
115
0.595048
4.609284
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPlugins.kt
1
56757
// 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.plugins import com.fasterxml.jackson.databind.type.TypeFactory import com.intellij.configurationStore.jdomSerializer import com.intellij.configurationStore.runInAutoSaveDisabledMode import com.intellij.configurationStore.saveProjectsAndApp import com.intellij.diagnostic.MessagePool import com.intellij.diagnostic.PerformanceWatcher import com.intellij.diagnostic.hprof.action.SystemTempFilenameSupplier import com.intellij.diagnostic.hprof.analysis.AnalyzeClassloaderReferencesGraph import com.intellij.diagnostic.hprof.analysis.HProfAnalysis import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.IdeEventQueue import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.actions.RevealFileAction import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.runBlockingUnderModalProgress import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.ide.ui.TopHitCache import com.intellij.ide.ui.UIThemeProvider import com.intellij.ide.util.TipAndTrickManager import com.intellij.idea.IdeaLogger import com.intellij.lang.Language import com.intellij.notification.NotificationType import com.intellij.notification.NotificationsManager import com.intellij.notification.impl.NotificationsManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.impl.ActionManagerImpl import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.actionSystem.impl.PresentationFactory import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionDescriptor import com.intellij.openapi.extensions.ExtensionPointDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.keymap.impl.BundledKeymapBean import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.PotemkinProgress import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.updateSettings.impl.UpdateChecker import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.objectTree.ThrowableInterner import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryManager import com.intellij.openapi.vfs.newvfs.FileAttribute import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ProjectFrameHelper import com.intellij.psi.util.CachedValuesManager import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.ui.IconDeferrer import com.intellij.ui.mac.touchbar.TouchbarSupport import com.intellij.util.CachedValuesManagerImpl import com.intellij.util.MemoryDumpHelper import com.intellij.util.ReflectionUtil import com.intellij.util.SystemProperties import com.intellij.util.containers.WeakList import com.intellij.util.messages.impl.MessageBusEx import com.intellij.util.ref.GCWatcher import net.sf.cglib.core.ClassNameReader import java.awt.KeyboardFocusManager import java.awt.Window import java.nio.channels.FileChannel import java.nio.file.Paths import java.nio.file.StandardOpenOption import java.text.SimpleDateFormat import java.util.* import java.util.function.Predicate import javax.swing.JComponent import javax.swing.ToolTipManager import kotlin.collections.component1 import kotlin.collections.component2 private val LOG = logger<DynamicPlugins>() private val classloadersFromUnloadedPlugins = mutableMapOf<PluginId, WeakList<PluginClassLoader>>() object DynamicPlugins { @JvmStatic @JvmOverloads fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl, baseDescriptor: IdeaPluginDescriptorImpl? = null, context: List<IdeaPluginDescriptorImpl> = emptyList()): Boolean { val reason = checkCanUnloadWithoutRestart(module = descriptor, parentModule = baseDescriptor, context = context) if (reason != null) { LOG.info(reason) } return reason == null } /** * @return true if the requested enabled state was applied without restart, false if restart is required */ fun loadPlugins(descriptors: Collection<IdeaPluginDescriptorImpl>): Boolean { return updateDescriptorsWithoutRestart(descriptors, load = true) { loadPlugin(it, checkImplementationDetailDependencies = true) } } /** * @return true if the requested enabled state was applied without restart, false if restart is required */ fun unloadPlugins( descriptors: Collection<IdeaPluginDescriptorImpl>, project: Project? = null, parentComponent: JComponent? = null, options: UnloadPluginOptions = UnloadPluginOptions(disable = true), ): Boolean { return updateDescriptorsWithoutRestart(descriptors, load = false) { unloadPluginWithProgress(project, parentComponent, it, options) } } private fun updateDescriptorsWithoutRestart( plugins: Collection<IdeaPluginDescriptorImpl>, load: Boolean, executor: (IdeaPluginDescriptorImpl) -> Boolean, ): Boolean { if (plugins.isEmpty()) { return true } val pluginSet = PluginManagerCore.getPluginSet() val descriptors = plugins .asSequence() .distinctBy { it.pluginId } .filter { pluginSet.isPluginEnabled(it.pluginId) != load } .toList() val operationText = if (load) "load" else "unload" val message = descriptors.joinToString(prefix = "Plugins to $operationText: [", postfix = "]") LOG.info(message) if (!descriptors.all { allowLoadUnloadWithoutRestart(it, context = descriptors) }) { return false } // todo plugin installation should be done not in this method var allPlugins = pluginSet.allPlugins for (descriptor in descriptors) { if (!allPlugins.contains(descriptor)) { allPlugins = allPlugins + descriptor } } // todo make internal: // 1) ModuleGraphBase; // 2) SortedModuleGraph; // 3) SortedModuleGraph.topologicalComparator; // 4) PluginSetBuilder.sortedModuleGraph. var comparator = PluginSetBuilder(allPlugins) .moduleGraph .topologicalComparator if (!load) { comparator = comparator.reversed() } for (descriptor in descriptors.sortedWith(comparator)) { descriptor.isEnabled = load if (!executor.invoke(descriptor)) { LOG.info("Failed to $operationText: $descriptor, restart required") InstalledPluginsState.getInstance().isRestartRequired = true return false } } return true } fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl): String? { return checkCanUnloadWithoutRestart(module, parentModule = null) } /** * @param context Plugins which are being loaded at the same time as [module] */ private fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl, parentModule: IdeaPluginDescriptorImpl?, optionalDependencyPluginId: PluginId? = null, context: List<IdeaPluginDescriptorImpl> = emptyList(), checkImplementationDetailDependencies: Boolean = true): String? { if (parentModule == null) { if (module.isRequireRestart) { return "Plugin ${module.pluginId} is explicitly marked as requiring restart" } if (module.productCode != null && !module.isBundled && !PluginManagerCore.isDevelopedByJetBrains(module)) { return "Plugin ${module.pluginId} is a paid plugin" } if (InstalledPluginsState.getInstance().isRestartRequired) { return InstalledPluginsState.RESTART_REQUIRED_MESSAGE } } val pluginSet = PluginManagerCore.getPluginSet() if (classloadersFromUnloadedPlugins[module.pluginId]?.isEmpty() == false) { return "Not allowing load/unload of ${module.pluginId} because of incomplete previous unload operation for that plugin" } findMissingRequiredDependency(module, context, pluginSet)?.let { pluginDependency -> return "Required dependency ${pluginDependency} of plugin ${module.pluginId} is not currently loaded" } val app = ApplicationManager.getApplication() if (parentModule == null) { if (!RegistryManager.getInstance().`is`("ide.plugins.allow.unload")) { if (!allowLoadUnloadSynchronously(module)) { return "ide.plugins.allow.unload is disabled and synchronous load/unload is not possible for ${module.pluginId}" } return null } try { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(module) } catch (e: CannotUnloadPluginException) { return e.cause?.localizedMessage ?: "checkUnloadPlugin listener blocked plugin unload" } } if (!Registry.`is`("ide.plugins.allow.unload.from.sources")) { if (pluginSet.findEnabledPlugin(module.pluginId) != null && module === parentModule && !module.isUseIdeaClassLoader) { val pluginClassLoader = module.pluginClassLoader if (pluginClassLoader != null && pluginClassLoader !is PluginClassLoader && !app.isUnitTestMode) { return "Plugin ${module.pluginId} is not unload-safe because of use of ${pluginClassLoader.javaClass.name} as the default class loader. " + "For example, the IDE is started from the sources with the plugin." } } } val epNameToExtensions = module.epNameToExtensions if (epNameToExtensions != null) { doCheckExtensionsCanUnloadWithoutRestart( extensions = epNameToExtensions, descriptor = module, baseDescriptor = parentModule, app = app, optionalDependencyPluginId = optionalDependencyPluginId, context = context, pluginSet = pluginSet, )?.let { return it } } checkNoComponentsOrServiceOverrides(module)?.let { return it } ActionManagerImpl.checkUnloadActions(module)?.let { return it } for (moduleRef in module.content.modules) { if (pluginSet.isModuleEnabled(moduleRef.name)) { val subModule = moduleRef.requireDescriptor() checkCanUnloadWithoutRestart(module = subModule, parentModule = module, optionalDependencyPluginId = null, context = context)?.let { return "$it in optional dependency on ${subModule.pluginId}" } } } for (dependency in module.pluginDependencies) { if (pluginSet.isPluginEnabled(dependency.pluginId)) { checkCanUnloadWithoutRestart(dependency.subDescriptor ?: continue, parentModule ?: module, null, context)?.let { return "$it in optional dependency on ${dependency.pluginId}" } } } // if not a sub plugin descriptor, then check that any dependent plugin also reloadable if (parentModule != null && module !== parentModule) { return null } var dependencyMessage: String? = null processOptionalDependenciesOnPlugin(module, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor -> if (subDescriptor.packagePrefix == null || mainDescriptor.pluginId.idString == "org.jetbrains.kotlin" || mainDescriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID) { dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId}" + " does not have a separate classloader for the dependency" return@processOptionalDependenciesOnPlugin false } dependencyMessage = checkCanUnloadWithoutRestart(subDescriptor, mainDescriptor, subDescriptor.pluginId, context) if (dependencyMessage == null) { true } else { dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId} requires restart: $dependencyMessage" false } } if (dependencyMessage == null && checkImplementationDetailDependencies) { val contextWithImplementationDetails = context.toMutableList() contextWithImplementationDetails.add(module) processImplementationDetailDependenciesOnPlugin(module, pluginSet, contextWithImplementationDetails::add) processImplementationDetailDependenciesOnPlugin(module, pluginSet) { dependentDescriptor -> // don't check a plugin that is an implementation-detail dependency on the current plugin if it has other disabled dependencies // and won't be loaded anyway if (findMissingRequiredDependency(dependentDescriptor, contextWithImplementationDetails, pluginSet) == null) { dependencyMessage = checkCanUnloadWithoutRestart(module = dependentDescriptor, parentModule = null, context = contextWithImplementationDetails, checkImplementationDetailDependencies = false) if (dependencyMessage != null) { dependencyMessage = "implementation-detail plugin ${dependentDescriptor.pluginId} which depends on ${module.pluginId}" + " requires restart: $dependencyMessage" } } dependencyMessage == null } } return dependencyMessage } private fun findMissingRequiredDependency(descriptor: IdeaPluginDescriptorImpl, context: List<IdeaPluginDescriptorImpl>, pluginSet: PluginSet): PluginId? { for (dependency in descriptor.pluginDependencies) { if (!dependency.isOptional && !PluginManagerCore.isModuleDependency(dependency.pluginId) && !pluginSet.isPluginEnabled(dependency.pluginId) && context.none { it.pluginId == dependency.pluginId }) { return dependency.pluginId } } return null } /** * Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the * plugins settings, without pressing the Apply button. */ @JvmStatic fun allowLoadUnloadSynchronously(module: IdeaPluginDescriptorImpl): Boolean { val extensions = (module.unsortedEpNameToExtensionElements.takeIf { it.isNotEmpty() } ?: module.appContainerDescriptor.extensions) if (extensions != null && !extensions.all { it.key == UIThemeProvider.EP_NAME.name || it.key == BundledKeymapBean.EP_NAME.name }) { return false } return checkNoComponentsOrServiceOverrides(module) == null && module.actions.isEmpty() } private fun checkNoComponentsOrServiceOverrides(module: IdeaPluginDescriptorImpl): String? { val id = module.pluginId return checkNoComponentsOrServiceOverrides(id, module.appContainerDescriptor) ?: checkNoComponentsOrServiceOverrides(id, module.projectContainerDescriptor) ?: checkNoComponentsOrServiceOverrides(id, module.moduleContainerDescriptor) } private fun checkNoComponentsOrServiceOverrides(pluginId: PluginId?, containerDescriptor: ContainerDescriptor): String? { if (!containerDescriptor.components.isNullOrEmpty()) { return "Plugin $pluginId is not unload-safe because it declares components" } if (containerDescriptor.services.any { it.overrides }) { return "Plugin $pluginId is not unload-safe because it overrides services" } return null } fun unloadPluginWithProgress(project: Project? = null, parentComponent: JComponent?, pluginDescriptor: IdeaPluginDescriptorImpl, options: UnloadPluginOptions): Boolean { var result = false if (!allowLoadUnloadSynchronously(pluginDescriptor)) { runInAutoSaveDisabledMode { val saveAndSyncHandler = SaveAndSyncHandler.getInstance() saveAndSyncHandler.saveSettingsUnderModalProgress(ApplicationManager.getApplication()) for (openProject in ProjectUtil.getOpenProjects()) { saveAndSyncHandler.saveSettingsUnderModalProgress(openProject) } } } val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.unloading.plugin.title", pluginDescriptor.name), project, parentComponent, null) indicator.runInSwingThread { result = unloadPlugin(pluginDescriptor, options.withSave(false)) } return result } data class UnloadPluginOptions( var disable: Boolean = true, var isUpdate: Boolean = false, var save: Boolean = true, var requireMemorySnapshot: Boolean = false, var waitForClassloaderUnload: Boolean = false, var checkImplementationDetailDependencies: Boolean = true, var unloadWaitTimeout: Int? = null, ) { fun withUpdate(isUpdate: Boolean): UnloadPluginOptions = also { this.isUpdate = isUpdate } fun withWaitForClassloaderUnload(waitForClassloaderUnload: Boolean) = also { this.waitForClassloaderUnload = waitForClassloaderUnload } fun withDisable(disable: Boolean) = also { this.disable = disable } fun withRequireMemorySnapshot(requireMemorySnapshot: Boolean) = also { this.requireMemorySnapshot = requireMemorySnapshot } fun withUnloadWaitTimeout(unloadWaitTimeout: Int) = also { this.unloadWaitTimeout = unloadWaitTimeout } fun withSave(save: Boolean) = also { this.save = save } fun withCheckImplementationDetailDependencies(checkImplementationDetailDependencies: Boolean) = also { this.checkImplementationDetailDependencies = checkImplementationDetailDependencies } } @JvmOverloads fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean { val app = ApplicationManager.getApplication() as ApplicationImpl val pluginId = pluginDescriptor.pluginId val pluginSet = PluginManagerCore.getPluginSet() if (options.checkImplementationDetailDependencies) { processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor -> dependentDescriptor.isEnabled = false unloadPlugin(dependentDescriptor, UnloadPluginOptions(save = false, waitForClassloaderUnload = false, checkImplementationDetailDependencies = false)) true } } try { if (options.save) { runInAutoSaveDisabledMode { FileDocumentManager.getInstance().saveAllDocuments() runBlockingUnderModalProgress { saveProjectsAndApp(true) } } } TipAndTrickManager.getInstance().closeTipDialog() app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, options.isUpdate) IdeEventQueue.getInstance().flushQueue() } catch (e: Exception) { logger<DynamicPlugins>().error(e) logDescriptorUnload(pluginDescriptor, success = false) return false } var classLoaderUnloaded: Boolean val classLoaders = WeakList<PluginClassLoader>() try { app.runWriteAction { // must be after flushQueue (e.g. https://youtrack.jetbrains.com/issue/IDEA-252010) val forbidGettingServicesToken = app.forbidGettingServices("Plugin $pluginId being unloaded.") try { (pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.let { classLoaders.add(it) } // https://youtrack.jetbrains.com/issue/IDEA-245031 // mark plugin classloaders as being unloaded to ensure that new extension instances will be not created during unload setClassLoaderState(pluginDescriptor, PluginClassLoader.UNLOAD_IN_PROGRESS) unloadLoadedOptionalDependenciesOnPlugin(pluginDescriptor, pluginSet = pluginSet, classLoaders = classLoaders) unloadDependencyDescriptors(pluginDescriptor, pluginSet, classLoaders) unloadModuleDescriptorNotRecursively(pluginDescriptor) clearPluginClassLoaderParentListCache(pluginSet) app.extensionArea.clearUserCache() for (project in ProjectUtil.getOpenProjects()) { (project.extensionArea as ExtensionsAreaImpl).clearUserCache() } clearCachedValues() jdomSerializer.clearSerializationCaches() TypeFactory.defaultInstance().clearCache() app.getServiceIfCreated(TopHitCache::class.java)?.clear() ActionToolbarImpl.resetAllToolbars() PresentationFactory.clearPresentationCaches() TouchbarSupport.reloadAllActions() (serviceIfCreated<NotificationsManager>() as? NotificationsManagerImpl)?.expireAll() MessagePool.getInstance().clearErrors() LaterInvocator.purgeExpiredItems() FileAttribute.resetRegisteredIds() resetFocusCycleRoot() clearNewFocusOwner() hideTooltip() PerformanceWatcher.getInstance().clearFreezeStacktraces() for (classLoader in classLoaders) { IconLoader.detachClassLoader(classLoader) Language.unregisterAllLanguagesIn(classLoader, pluginDescriptor) } serviceIfCreated<IconDeferrer>()?.clearCache() (ApplicationManager.getApplication().messageBus as MessageBusEx).clearPublisherCache() @Suppress("TestOnlyProblems") (ProjectManager.getInstanceIfCreated() as? ProjectManagerImpl)?.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests() val newPluginSet = pluginSet.withoutModule( module = pluginDescriptor, disable = options.disable, ).createPluginSetWithEnabledModulesMap() PluginManagerCore.setPluginSet(newPluginSet) } finally { try { forbidGettingServicesToken.finish() } finally { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, options.isUpdate) } } } } catch (e: Exception) { logger<DynamicPlugins>().error(e) } finally { IdeEventQueue.getInstance().flushQueue() // do it after IdeEventQueue.flushQueue() to ensure that Disposer.isDisposed(...) works as expected in flushed tasks. Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces ThrowableInterner.clearInternedBacktraces() IdeaLogger.ourErrorsOccurred = null // ensure we don't have references to plugin classes in exception stacktraces clearTemporaryLostComponent() clearCglibStopBacktrace() if (app.isUnitTestMode && pluginDescriptor.pluginClassLoader !is PluginClassLoader) { classLoaderUnloaded = true } else { classloadersFromUnloadedPlugins[pluginId] = classLoaders ClassLoaderTreeChecker(pluginDescriptor, classLoaders).checkThatClassLoaderNotReferencedByPluginClassLoader() val checkClassLoaderUnload = options.waitForClassloaderUnload || options.requireMemorySnapshot || Registry.`is`("ide.plugins.snapshot.on.unload.fail") val timeout = if (checkClassLoaderUnload) { options.unloadWaitTimeout ?: Registry.intValue("ide.plugins.unload.timeout", 5000) } else { 0 } classLoaderUnloaded = unloadClassLoader(pluginDescriptor, timeout) if (classLoaderUnloaded) { LOG.info("Successfully unloaded plugin $pluginId (classloader unload checked=$checkClassLoaderUnload)") classloadersFromUnloadedPlugins.remove(pluginId) } else { if ((options.requireMemorySnapshot || (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && !app.isUnitTestMode)) && MemoryDumpHelper.memoryDumpAvailable()) { classLoaderUnloaded = saveMemorySnapshot(pluginId) } else { LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded") } } if (!classLoaderUnloaded) { InstalledPluginsState.getInstance().isRestartRequired = true } logDescriptorUnload(pluginDescriptor, success = classLoaderUnloaded) } } if (!classLoaderUnloaded) { setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.ACTIVE) } ActionToolbarImpl.updateAllToolbarsImmediately(true) return classLoaderUnloaded } private fun resetFocusCycleRoot() { val focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager() var focusCycleRoot = focusManager.currentFocusCycleRoot if (focusCycleRoot != null) { while (focusCycleRoot != null && focusCycleRoot !is IdeFrameImpl) { focusCycleRoot = focusCycleRoot.parent } if (focusCycleRoot is IdeFrameImpl) { focusManager.setGlobalCurrentFocusCycleRoot(focusCycleRoot) } else { focusCycleRoot = focusManager.currentFocusCycleRoot val dataContext = DataManager.getInstance().getDataContext(focusCycleRoot) val project = CommonDataKeys.PROJECT.getData(dataContext) if (project != null) { val projectFrame = WindowManager.getInstance().getFrame(project) if (projectFrame != null) { focusManager.setGlobalCurrentFocusCycleRoot(projectFrame) } } } } } private fun unloadLoadedOptionalDependenciesOnPlugin(dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, classLoaders: WeakList<PluginClassLoader>) { val dependencyClassloader = dependencyPlugin.classLoader processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor -> val classLoader = subDescriptor.classLoader unloadModuleDescriptorNotRecursively(subDescriptor) // this additional code is required because in unit tests PluginClassLoader is not used if (mainDescriptor !== subDescriptor) { subDescriptor.pluginClassLoader = null } if (dependencyClassloader is PluginClassLoader && classLoader is PluginClassLoader) { LOG.info("Detach classloader $dependencyClassloader from $classLoader") if (mainDescriptor !== subDescriptor && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) classLoader.state = PluginClassLoader.UNLOAD_IN_PROGRESS } } true } } private fun unloadDependencyDescriptors(plugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, classLoaders: WeakList<PluginClassLoader>) { for (dependency in plugin.pluginDependencies) { val subDescriptor = dependency.subDescriptor ?: continue val classLoader = subDescriptor.pluginClassLoader if (!pluginSet.isPluginEnabled(dependency.pluginId)) { LOG.assertTrue(classLoader == null, "Expected not to have any sub descriptor classloader when dependency ${dependency.pluginId} is not loaded") continue } if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) } unloadDependencyDescriptors(subDescriptor, pluginSet, classLoaders) unloadModuleDescriptorNotRecursively(subDescriptor) subDescriptor.pluginClassLoader = null } for (module in plugin.content.modules) { val subDescriptor = module.requireDescriptor() val classLoader = subDescriptor.pluginClassLoader ?: continue if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) { classLoaders.add(classLoader) } unloadModuleDescriptorNotRecursively(subDescriptor) subDescriptor.pluginClassLoader = null } } internal fun notify(@NlsContexts.NotificationContent text: String, notificationType: NotificationType, vararg actions: AnAction) { val notification = UpdateChecker.getNotificationGroupForPluginUpdateResults().createNotification(text, notificationType) for (action in actions) { notification.addAction(action) } notification.notify(null) } // PluginId cannot be used to unload related resources because one plugin descriptor may consist of several sub descriptors, // each of them depends on presense of another plugin, here not the whole plugin is unloaded, but only one part. private fun unloadModuleDescriptorNotRecursively(module: IdeaPluginDescriptorImpl) { val app = ApplicationManager.getApplication() as ApplicationImpl (ActionManager.getInstance() as ActionManagerImpl).unloadActions(module) val openedProjects = ProjectUtil.getOpenProjects().asList() val appExtensionArea = app.extensionArea val priorityUnloadListeners = mutableListOf<Runnable>() val unloadListeners = mutableListOf<Runnable>() unregisterUnknownLevelExtensions(module.unsortedEpNameToExtensionElements, module, appExtensionArea, openedProjects, priorityUnloadListeners, unloadListeners) for (epName in (module.appContainerDescriptor.extensions?.keys ?: emptySet())) { appExtensionArea.unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners) } for (epName in (module.projectContainerDescriptor.extensions?.keys ?: emptySet())) { for (project in openedProjects) { (project.extensionArea as ExtensionsAreaImpl).unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners) } } // not an error - unsorted goes to module level, see registerExtensions unregisterUnknownLevelExtensions(module.moduleContainerDescriptor.extensions, module, appExtensionArea, openedProjects, priorityUnloadListeners, unloadListeners) for (priorityUnloadListener in priorityUnloadListeners) { priorityUnloadListener.run() } for (unloadListener in unloadListeners) { unloadListener.run() } // first, reset all plugin extension points before unregistering, so that listeners don't see plugin in semi-torn-down state processExtensionPoints(module, openedProjects) { points, area -> area.resetExtensionPoints(points, module) } // unregister plugin extension points processExtensionPoints(module, openedProjects) { points, area -> area.unregisterExtensionPoints(points, module) } val pluginId = module.pluginId app.unloadServices(module.appContainerDescriptor.services, pluginId) val appMessageBus = app.messageBus as MessageBusEx module.appContainerDescriptor.listeners?.let { appMessageBus.unsubscribeLazyListeners(module, it) } for (project in openedProjects) { (project as ComponentManagerImpl).unloadServices(module.projectContainerDescriptor.services, pluginId) module.projectContainerDescriptor.listeners?.let { ((project as ComponentManagerImpl).messageBus as MessageBusEx).unsubscribeLazyListeners(module, it) } val moduleServices = module.moduleContainerDescriptor.services for (ideaModule in ModuleManager.getInstance(project).modules) { (ideaModule as ComponentManagerImpl).unloadServices(moduleServices, pluginId) createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ideaModule, it) } } createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(project, it) } } appMessageBus.disconnectPluginConnections(Predicate { aClass -> (aClass.classLoader as? PluginClassLoader)?.pluginDescriptor === module }) createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ApplicationManager.getApplication(), it) } } private fun unregisterUnknownLevelExtensions(extensionMap: Map<String, List<ExtensionDescriptor>>?, pluginDescriptor: IdeaPluginDescriptorImpl, appExtensionArea: ExtensionsAreaImpl, openedProjects: List<Project>, priorityUnloadListeners: MutableList<Runnable>, unloadListeners: MutableList<Runnable>) { for (epName in (extensionMap?.keys ?: return)) { val isAppLevelEp = appExtensionArea.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) if (isAppLevelEp) { continue } for (project in openedProjects) { val isProjectLevelEp = (project.extensionArea as ExtensionsAreaImpl) .unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) if (!isProjectLevelEp) { for (module in ModuleManager.getInstance(project).modules) { (module.extensionArea as ExtensionsAreaImpl) .unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners) } } } } } private inline fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl, projects: List<Project>, processor: (points: List<ExtensionPointDescriptor>, area: ExtensionsAreaImpl) -> Unit) { pluginDescriptor.appContainerDescriptor.extensionPoints?.let { processor(it, ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl) } pluginDescriptor.projectContainerDescriptor.extensionPoints?.let { extensionPoints -> for (project in projects) { processor(extensionPoints, project.extensionArea as ExtensionsAreaImpl) } } pluginDescriptor.moduleContainerDescriptor.extensionPoints?.let { extensionPoints -> for (project in projects) { for (module in ModuleManager.getInstance(project).modules) { processor(extensionPoints, module.extensionArea as ExtensionsAreaImpl) } } } } fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean { return loadPlugin(pluginDescriptor, checkImplementationDetailDependencies = true) } private fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, checkImplementationDetailDependencies: Boolean = true): Boolean { if (classloadersFromUnloadedPlugins[pluginDescriptor.pluginId]?.isEmpty() == false) { LOG.info("Requiring restart for loading plugin ${pluginDescriptor.pluginId}" + " because previous version of the plugin wasn't fully unloaded") return false } val loadStartTime = System.currentTimeMillis() val pluginSet = PluginManagerCore.getPluginSet() .withModule(pluginDescriptor) .createPluginSetWithEnabledModulesMap() val classLoaderConfigurator = ClassLoaderConfigurator(pluginSet) // todo loadPlugin should be called per each module, temporary solution val pluginWithContentModules = pluginSet.getEnabledModules() .filter { it.pluginId == pluginDescriptor.pluginId } .filter(classLoaderConfigurator::configureModule) .toList() val app = ApplicationManager.getApplication() as ApplicationImpl app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor) app.runWriteAction { try { PluginManagerCore.setPluginSet(pluginSet) val listenerCallbacks = mutableListOf<Runnable>() // 4. load into service container loadModules(pluginWithContentModules, app, listenerCallbacks) loadModules( optionalDependenciesOnPlugin(pluginDescriptor, classLoaderConfigurator, pluginSet), app, listenerCallbacks, ) clearPluginClassLoaderParentListCache(pluginSet) clearCachedValues() listenerCallbacks.forEach(Runnable::run) logDescriptorLoad(pluginDescriptor) LOG.info("Plugin ${pluginDescriptor.pluginId} loaded without restart in ${System.currentTimeMillis() - loadStartTime} ms") } finally { app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor) } } if (checkImplementationDetailDependencies) { var implementationDetailsLoadedWithoutRestart = true processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor -> val dependencies = dependentDescriptor.pluginDependencies if (dependencies.all { it.isOptional || PluginManagerCore.getPlugin(it.pluginId) != null }) { if (!loadPlugin(dependentDescriptor, checkImplementationDetailDependencies = false)) { implementationDetailsLoadedWithoutRestart = false } } implementationDetailsLoadedWithoutRestart } return implementationDetailsLoadedWithoutRestart } return true } fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) { ApplicationManager.getApplication().messageBus.connect(parentDisposable) .subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { callback.run() } }) } } private fun clearTemporaryLostComponent() { try { val clearMethod = Window::class.java.declaredMethods.find { it.name == "setTemporaryLostComponent" } if (clearMethod == null) { LOG.info("setTemporaryLostComponent method not found") return } clearMethod.isAccessible = true loop@ for (frame in WindowManager.getInstance().allProjectFrames) { val window = when (frame) { is ProjectFrameHelper -> frame.frameOrNull is Window -> frame else -> continue@loop } clearMethod.invoke(window, null) } } catch (e: Throwable) { LOG.info("Failed to clear Window.temporaryLostComponent", e) } } private fun hideTooltip() { try { val showMethod = ToolTipManager::class.java.declaredMethods.find { it.name == "show" } if (showMethod == null) { LOG.info("ToolTipManager.show method not found") return } showMethod.isAccessible = true showMethod.invoke(ToolTipManager.sharedInstance(), null) } catch (e: Throwable) { LOG.info("Failed to hide tooltip", e) } } private fun clearCglibStopBacktrace() { val field = ReflectionUtil.getDeclaredField(ClassNameReader::class.java, "EARLY_EXIT") if (field != null) { try { ThrowableInterner.clearBacktrace((field[null] as Throwable)) } catch (e: Throwable) { LOG.info(e) } } } private fun clearNewFocusOwner() { val field = ReflectionUtil.getDeclaredField(KeyboardFocusManager::class.java, "newFocusOwner") if (field != null) { try { field.set(null, null) } catch (e: Throwable) { LOG.info(e) } } } private fun saveMemorySnapshot(pluginId: PluginId): Boolean { val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date()) val snapshotFileName = "unload-$pluginId-$snapshotDate.hprof" val snapshotPath = System.getProperty("memory.snapshots.path", SystemProperties.getUserHome()) + "/" + snapshotFileName MemoryDumpHelper.captureMemoryDump(snapshotPath) if (classloadersFromUnloadedPlugins[pluginId]?.isEmpty() != false) { LOG.info("Successfully unloaded plugin $pluginId (classloader collected during memory snapshot generation)") return true } if (Registry.`is`("ide.plugins.analyze.snapshot")) { val analysisResult = analyzeSnapshot(snapshotPath, pluginId) @Suppress("ReplaceSizeZeroCheckWithIsEmpty") if (analysisResult.length == 0) { LOG.info("Successfully unloaded plugin $pluginId (no strong references to classloader in .hprof file)") classloadersFromUnloadedPlugins.remove(pluginId) return true } else { LOG.info("Snapshot analysis result: $analysisResult") } } DynamicPlugins.notify( IdeBundle.message("memory.snapshot.captured.text", snapshotPath, snapshotFileName), NotificationType.WARNING, object : AnAction(IdeBundle.message("ide.restart.action")), DumbAware { override fun actionPerformed(e: AnActionEvent) = ApplicationManager.getApplication().restart() }, object : AnAction( IdeBundle.message("memory.snapshot.captured.action.text", snapshotFileName, RevealFileAction.getFileManagerName())), DumbAware { override fun actionPerformed(e: AnActionEvent) = RevealFileAction.openFile(Paths.get(snapshotPath)) } ) LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded. Memory snapshot created at $snapshotPath") return false } private fun processImplementationDetailDependenciesOnPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, pluginSet: PluginSet, processor: (descriptor: IdeaPluginDescriptorImpl) -> Boolean) { processDependenciesOnPlugin(dependencyPlugin = pluginDescriptor, pluginSet = pluginSet, loadStateFilter = LoadStateFilter.ANY, onlyOptional = false) { _, module -> if (module.isImplementationDetail) { processor(module) } else { true } } } /** * Load all sub plugins that depend on specified [dependencyPlugin]. */ private fun optionalDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, classLoaderConfigurator: ClassLoaderConfigurator, pluginSet: PluginSet, ): Set<IdeaPluginDescriptorImpl> { // 1. collect optional descriptors val modulesToMain = LinkedHashMap<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>() processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = false) { main, module -> modulesToMain[module] = main true } if (modulesToMain.isEmpty()) { return emptySet() } // 2. sort topologically val topologicalComparator = PluginSetBuilder(modulesToMain.values) .moduleGraph .topologicalComparator return modulesToMain.toSortedMap(topologicalComparator) .filter { (moduleDescriptor, mainDescriptor) -> // 3. setup classloaders classLoaderConfigurator.configureDependency(mainDescriptor, moduleDescriptor) }.keys } private fun loadModules( modules: Collection<IdeaPluginDescriptorImpl>, app: ApplicationImpl, listenerCallbacks: MutableList<in Runnable>, ) { fun registerComponents(componentManager: ComponentManager) { (componentManager as ComponentManagerImpl).registerComponents(modules.toList(), app, null, listenerCallbacks) } registerComponents(app) for (openProject in ProjectUtil.getOpenProjects()) { registerComponents(openProject) for (module in ModuleManager.getInstance(openProject).modules) { registerComponents(module) } } (ActionManager.getInstance() as ActionManagerImpl).registerActions(modules) } private fun analyzeSnapshot(hprofPath: String, pluginId: PluginId): String { FileChannel.open(Paths.get(hprofPath), StandardOpenOption.READ).use { channel -> val analysis = HProfAnalysis(channel, SystemTempFilenameSupplier()) { analysisContext, listProvider, progressIndicator -> AnalyzeClassloaderReferencesGraph(analysisContext, listProvider, pluginId.idString).analyze(progressIndicator).mainReport.toString() } analysis.onlyStrongReferences = true analysis.includeClassesAsRoots = false analysis.setIncludeMetaInfo(false) return analysis.analyze(ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()) } } private fun createDisposeTreePredicate(pluginDescriptor: IdeaPluginDescriptorImpl): Predicate<Disposable>? { val classLoader = pluginDescriptor.pluginClassLoader as? PluginClassLoader ?: return null return Predicate { if (it is PluginManager.PluginAwareDisposable) { it.classLoaderId == classLoader.instanceId } else { it::class.java.classLoader === classLoader } } } private fun processOptionalDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, isLoaded: Boolean, processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean, ) { processDependenciesOnPlugin( dependencyPlugin = dependencyPlugin, pluginSet = pluginSet, onlyOptional = true, loadStateFilter = if (isLoaded) LoadStateFilter.LOADED else LoadStateFilter.NOT_LOADED, processor = processor, ) } private fun processDependenciesOnPlugin( dependencyPlugin: IdeaPluginDescriptorImpl, pluginSet: PluginSet, loadStateFilter: LoadStateFilter, onlyOptional: Boolean, processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean, ) { val wantedIds = HashSet<String>(1 + dependencyPlugin.content.modules.size) wantedIds.add(dependencyPlugin.pluginId.idString) for (module in dependencyPlugin.content.modules) { wantedIds.add(module.name) } for (plugin in pluginSet.enabledPlugins) { if (plugin === dependencyPlugin) { continue } if (!processOptionalDependenciesInOldFormatOnPlugin(dependencyPluginId = dependencyPlugin.pluginId, mainDescriptor = plugin, loadStateFilter = loadStateFilter, onlyOptional = onlyOptional, processor = processor)) { return } for (moduleItem in plugin.content.modules) { val module = moduleItem.requireDescriptor() if (loadStateFilter != LoadStateFilter.ANY) { val isModuleLoaded = module.pluginClassLoader != null if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) { continue } } for (item in module.dependencies.modules) { if (wantedIds.contains(item.name) && !processor(plugin, module)) { return } } for (item in module.dependencies.plugins) { if (dependencyPlugin.pluginId == item.id && !processor(plugin, module)) { return } } } } } private enum class LoadStateFilter { LOADED, NOT_LOADED, ANY } private fun processOptionalDependenciesInOldFormatOnPlugin( dependencyPluginId: PluginId, mainDescriptor: IdeaPluginDescriptorImpl, loadStateFilter: LoadStateFilter, onlyOptional: Boolean, processor: (main: IdeaPluginDescriptorImpl, sub: IdeaPluginDescriptorImpl) -> Boolean ): Boolean { for (dependency in mainDescriptor.pluginDependencies) { if (!dependency.isOptional) { if (!onlyOptional && dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, mainDescriptor)) { return false } continue } val subDescriptor = dependency.subDescriptor ?: continue if (loadStateFilter != LoadStateFilter.ANY) { val isModuleLoaded = subDescriptor.pluginClassLoader != null if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) { continue } } if (dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, subDescriptor)) { return false } if (!processOptionalDependenciesInOldFormatOnPlugin( dependencyPluginId = dependencyPluginId, mainDescriptor = subDescriptor, loadStateFilter = loadStateFilter, onlyOptional = onlyOptional, processor = processor)) { return false } } return true } private fun doCheckExtensionsCanUnloadWithoutRestart( extensions: Map<String, List<ExtensionDescriptor>>, descriptor: IdeaPluginDescriptorImpl, baseDescriptor: IdeaPluginDescriptorImpl?, app: Application, optionalDependencyPluginId: PluginId?, context: List<IdeaPluginDescriptorImpl>, pluginSet: PluginSet, ): String? { val firstProject = ProjectUtil.getOpenProjects().firstOrNull() val anyProject = firstProject ?: ProjectManager.getInstance().defaultProject val anyModule = firstProject?.let { ModuleManager.getInstance(it).modules.firstOrNull() } val seenPlugins: MutableSet<IdeaPluginDescriptorImpl> = Collections.newSetFromMap(IdentityHashMap()) epLoop@ for (epName in extensions.keys) { seenPlugins.clear() fun getNonDynamicUnloadError(optionalDependencyPluginId: PluginId?): String = optionalDependencyPluginId?.let { "Plugin ${baseDescriptor?.pluginId} is not unload-safe because of use of non-dynamic EP $epName in plugin $it that optionally depends on it" } ?: "Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName" val result = findLoadedPluginExtensionPointRecursive( pluginDescriptor = baseDescriptor ?: descriptor, epName = epName, pluginSet = pluginSet, context = context, seenPlugins = seenPlugins, ) if (result != null) { val (pluginExtensionPoint, foundInDependencies) = result // descriptor.pluginId is null when we check the optional dependencies of the plugin which is being loaded // if an optional dependency of a plugin extends a non-dynamic EP of that plugin, it shouldn't prevent plugin loading if (!pluginExtensionPoint.isDynamic) { if (baseDescriptor == null || foundInDependencies) { return getNonDynamicUnloadError(null) } else if (descriptor === baseDescriptor) { return getNonDynamicUnloadError(descriptor.pluginId) } } continue } val ep = app.extensionArea.getExtensionPointIfRegistered<Any>(epName) ?: anyProject.extensionArea.getExtensionPointIfRegistered<Any>(epName) ?: anyModule?.extensionArea?.getExtensionPointIfRegistered<Any>(epName) if (ep != null) { if (!ep.isDynamic) { return getNonDynamicUnloadError(optionalDependencyPluginId) } continue } if (anyModule == null) { val corePlugin = pluginSet.findEnabledPlugin(PluginManagerCore.CORE_ID) if (corePlugin != null) { val coreEP = findPluginExtensionPoint(corePlugin, epName) if (coreEP != null) { if (!coreEP.isDynamic) { return getNonDynamicUnloadError(optionalDependencyPluginId) } continue } } } for (contextPlugin in context) { val contextEp = findPluginExtensionPoint(contextPlugin, epName) ?: continue if (!contextEp.isDynamic) { return getNonDynamicUnloadError(null) } continue@epLoop } // special case Kotlin EPs registered via code in Kotlin compiler if (epName.startsWith("org.jetbrains.kotlin") && descriptor.pluginId.idString == "org.jetbrains.kotlin") { continue } return "Plugin ${descriptor.pluginId} is not unload-safe because of unresolved extension $epName" } return null } private fun findPluginExtensionPoint(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String): ExtensionPointDescriptor? { fun findContainerExtensionPoint(containerDescriptor: ContainerDescriptor): ExtensionPointDescriptor? { return containerDescriptor.extensionPoints?.find { it.nameEquals(epName, pluginDescriptor) } } return findContainerExtensionPoint(pluginDescriptor.appContainerDescriptor) ?: findContainerExtensionPoint(pluginDescriptor.projectContainerDescriptor) ?: findContainerExtensionPoint(pluginDescriptor.moduleContainerDescriptor) } private fun findLoadedPluginExtensionPointRecursive(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String, pluginSet: PluginSet, context: List<IdeaPluginDescriptorImpl>, seenPlugins: MutableSet<IdeaPluginDescriptorImpl>): Pair<ExtensionPointDescriptor, Boolean>? { if (!seenPlugins.add(pluginDescriptor)) { return null } findPluginExtensionPoint(pluginDescriptor, epName)?.let { return it to false } for (dependency in pluginDescriptor.pluginDependencies) { if (pluginSet.isPluginEnabled(dependency.pluginId) || context.any { it.pluginId == dependency.pluginId }) { dependency.subDescriptor?.let { subDescriptor -> findLoadedPluginExtensionPointRecursive(subDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it } } pluginSet.findEnabledPlugin(dependency.pluginId)?.let { dependencyDescriptor -> findLoadedPluginExtensionPointRecursive(dependencyDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it.first to true } } } } processDirectDependencies(pluginDescriptor, pluginSet) { dependency -> findLoadedPluginExtensionPointRecursive(dependency, epName, pluginSet, context, seenPlugins)?.let { return it.first to true } } return null } private inline fun processDirectDependencies(module: IdeaPluginDescriptorImpl, pluginSet: PluginSet, processor: (IdeaPluginDescriptorImpl) -> Unit) { for (item in module.dependencies.modules) { val descriptor = pluginSet.findEnabledModule(item.name) if (descriptor != null) { processor(descriptor) } } for (item in module.dependencies.plugins) { val descriptor = pluginSet.findEnabledPlugin(item.id) if (descriptor != null) { processor(descriptor) } } } private fun unloadClassLoader(pluginDescriptor: IdeaPluginDescriptorImpl, timeoutMs: Int): Boolean { if (timeoutMs == 0) { pluginDescriptor.pluginClassLoader = null return true } val watcher = GCWatcher.tracking(pluginDescriptor.pluginClassLoader) pluginDescriptor.pluginClassLoader = null return watcher.tryCollect(timeoutMs) } private fun setClassLoaderState(pluginDescriptor: IdeaPluginDescriptorImpl, state: Int) { (pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.state = state for (dependency in pluginDescriptor.pluginDependencies) { dependency.subDescriptor?.let { setClassLoaderState(it, state) } } } private fun clearPluginClassLoaderParentListCache(pluginSet: PluginSet) { // yes, clear not only enabled plugins, but all, just to be sure; it's a cheap operation for (descriptor in pluginSet.allPlugins) { (descriptor.pluginClassLoader as? PluginClassLoader)?.clearParentListCache() } } private fun clearCachedValues() { for (project in ProjectUtil.getOpenProjects()) { (CachedValuesManager.getManager(project) as? CachedValuesManagerImpl)?.clearCachedValues() } }
apache-2.0
418c2fad4265c91fa48e5f803597675b
40.54978
169
0.70453
5.826609
false
false
false
false
jk1/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCaseExt.kt
1
8870
// 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.testGuiFramework.impl import com.intellij.testGuiFramework.fixtures.GutterFixture import com.intellij.testGuiFramework.fixtures.JDialogFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture import com.intellij.testGuiFramework.util.* import org.fest.swing.exception.ComponentLookupException import org.fest.swing.timing.Pause import org.hamcrest.Matcher import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.rules.ErrorCollector import org.junit.rules.TemporaryFolder import org.junit.rules.TestName import java.nio.file.Files import java.nio.file.Path open class GuiTestCaseExt : GuiTestCase() { @Rule @JvmField val testMethod = TestName() @Rule @JvmField val screenshotsDuringTest = ScreenshotsDuringTest(1000) // = 1 sec @Rule @JvmField val logActionsDuringTest = LogActionsDuringTest() @get:Rule val testRootPath: TemporaryFolder by lazy { TemporaryFolder() } val projectFolder: String by lazy { testRootPath.newFolder(testMethod.methodName).canonicalPath } // @Rule // @JvmField // val collector = object : ErrorCollector() { // override fun addError(error: Throwable?) { // val screenshotName = testName + "." + testMethod.methodName // takeScreenshotOnFailure(error, screenshotName) // super.addError(error) // } // } @Before open fun setUp() { guiTestRule.IdeHandling().setUp() logStartTest(testMethod.methodName) } @After fun tearDown() { logEndTest(testMethod.methodName) guiTestRule.IdeHandling().tearDown() } open fun isIdeFrameRun(): Boolean = true } fun <T> ErrorCollector.checkThat(value: T, matcher: Matcher<T>, reason: () -> String) { checkThat(reason(), value, matcher) } /** * Closes the current project * */ fun GuiTestCase.closeProject() { ideFrame { logUIStep("Close the project") waitAMoment() closeProject() } } /** * Wrapper for [waitForBackgroundTasksToFinish] * adds an extra pause * This function should be used instead of [waitForBackgroundTasksToFinish] * because sometimes it doesn't wait enough time * After [waitForBackgroundTasksToFinish] fixing this function should be removed * @param extraTimeOut time of additional waiting * */ fun GuiTestCase.waitAMoment(extraTimeOut: Long = 2000L) { ideFrame { this.waitForBackgroundTasksToFinish() } Pause.pause(extraTimeOut) } /** * Performs test whether the specified item exists in a tree * Note: the dialog with the investigated tree must be open * before using this test * @param expectedItem - expected exact item * @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message * */ fun GuiTestCase.testTreeItemExist(name: String, vararg expectedItem: String) { ideFrame { logInfo("Check that $name -> ${expectedItem.joinToString(" -> ")} exists in a tree element") kotlin.assert(exists { jTree(*expectedItem) }) { "$name '${expectedItem.joinToString(", ")}' not found" } } } /** * Selects specified [path] in the tree by keyboard searching * @param path in string form * @param testCase - test case is required only because of keyboard related functions * * TODO: remove [testCase] parameter (so move [shortcut] and [typeText] functions * out of GuiTestCase) * */ fun ExtendedJTreePathFixture.selectWithKeyboard(testCase: GuiTestCase, vararg path: String) { fun currentValue(): String { val selectedRow = target().selectionRows.first() return valueAt(selectedRow) ?: throw IllegalStateException("Nothing is selected in the tree") } click() testCase.shortcut(Key.HOME) // select the top row for((index, step) in path.withIndex()){ if(currentValue() != step) { testCase.typeText(step) while (currentValue() != step) testCase.shortcut(Key.DOWN) } if(index < path.size -1) testCase.shortcut(Key.RIGHT) } } fun GuiTestCase.gradleReimport() { logTestStep("Reimport gradle project") ideFrame { toolwindow(id = "Gradle") { content(tabName = "") { // waitAMoment() actionButton("Refresh all external projects").click() } } } } fun GuiTestCase.mavenReimport() { logTestStep("Reimport maven project") ideFrame { toolwindow(id = "Maven") { content(tabName = "") { actionButton("Reimport All Maven Projects").click() } } } } fun GuiTestCase.checkProjectIsCompiled(expectedStatus: String) { val textEventLog = "Event Log" ideFrame { logTestStep("Going to check how the project compiles") invokeMainMenu("CompileProject") shortcut(Modifier.CONTROL + Modifier.SHIFT + Key.A) waitAMoment() typeText(textEventLog) waitAMoment() shortcut(Key.ENTER) toolwindow(id = textEventLog) { content(tabName = "") { editor{ val lastLine = this.getCurrentFileContents(false)?.lines()?.last { it.trim().isNotEmpty() } ?: "" assert(lastLine.contains(expectedStatus)) { "Line `$lastLine` doesn't contain expected status `$expectedStatus`" } } } } } } fun GuiTestCase.checkRunConfiguration(expectedValues: Map<String, String>, vararg configuration: String) { val cfgName = configuration.last() val runDebugConfigurations = "Run/Debug Configurations" ideFrame { logTestStep("Going to check presence of Run/Debug configuration `$cfgName`") navigationBar { assert(exists { button(cfgName) }) { "Button `$cfgName` not found on Navigation bar" } button(cfgName).click() popupClick("Edit Configurations...") } dialog(runDebugConfigurations) { assert(exists { jTree(*configuration) }) jTree(*configuration).clickPath() for ((field, expectedValue) in expectedValues) { logTestStep("Field `$field`has a value = `$expectedValue`") checkOneValue(this@checkRunConfiguration, field, expectedValue) } button("Cancel").click() } } } fun JDialogFixture.checkOneValue(guiTestCase: GuiTestCase, expectedField: String, expectedValue: String){ val actualValue = when { guiTestCase.exists {textfield(expectedField)} -> textfield(expectedField).text() guiTestCase.exists { combobox(expectedField) } -> combobox(expectedField).selectedItem() else -> throw ComponentLookupException("Cannot find component with label `$expectedField`") } assert(actualValue == expectedValue) { "Field `$expectedField`: actual value = `$actualValue`, expected value = `$expectedValue`" } } fun GuiTestCase.checkProjectIsRun(configuration: String, message: String) { val buttonRun = "Run" logTestStep("Going to run configuration `$configuration`") ideFrame { navigationBar { actionButton(buttonRun).click() } waitAMoment() toolwindow(id = buttonRun) { content(tabName = configuration) { editor { GuiTestUtilKt.waitUntil("Wait for '$message' appears") { val output = this.getCurrentFileContents(false)?.lines()?.filter { it.trim().isNotEmpty() } ?: listOf() logInfo("output: ${output.map { "\n\t$it" }}") logInfo("expected message = '$message'") output.firstOrNull { it.contains(message) } != null } } } } } } fun GuiTestCase.checkRunGutterIcons(expectedNumberOfRunIcons: Int, expectedRunLines: List<String>) { ideFrame { logTestStep("Going to check whether $expectedNumberOfRunIcons `Run` gutter icons are present") editor { waitUntilFileIsLoaded() waitUntilErrorAnalysisFinishes() gutter.waitUntilIconsShown(mapOf(GutterFixture.GutterIcon.RUN_SCRIPT to expectedNumberOfRunIcons)) val gutterRunLines = gutter.linesWithGutterIcon(GutterFixture.GutterIcon.RUN_SCRIPT) val contents = [email protected](false)?.lines() ?: listOf() for ((index, line) in gutterRunLines.withIndex()) { // line numbers start with 1, but index in the contents list starts with 0 val currentLine = contents[line - 1] val expectedLine = expectedRunLines[index] assert(currentLine.contains(expectedLine)) { "At line #$line the actual text is `$currentLine`, but it was expected `$expectedLine`" } } } } } fun GuiTestCase.checkFileExists(filePath: Path) { logTestStep("Going to check whether file `$filePath` created") assert(filePath.toFile().exists()) { "Can't find a file `$filePath`" } } fun GuiTestCase.checkFileContainsLine(filePath: Path, line: String) { logTestStep("Going to check whether ${filePath.fileName} contains line `$line`") assert(Files.readAllLines(filePath).contains(line)) { "Line `$line` not found" } }
apache-2.0
ea6e6434b410f2f3557ac91dffd0c7b2
32.100746
140
0.698534
4.386746
false
true
false
false
jk1/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/MethodCandidate.kt
1
2730
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.openapi.util.Pair import com.intellij.psi.* import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.mapParametersToArguments import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil class MethodCandidate(val method: PsiMethod, val siteSubstitutor: PsiSubstitutor, val qualifier: Argument?, val arguments: List<Argument>, val context: GroovyPsiElement) { private val typeComputer: (Argument) -> PsiType? = { it -> val type = if (it.expression != null) getTopLevelType(it.expression) else it.type type ?: TypesUtil.getJavaLangObject(context) } private val completionTypeComputer: (Argument) -> PsiType? = { it -> if (it.expression != null) { var type = getTopLevelType(it.expression) if (it.expression is GrNewExpression && com.intellij.psi.util.PsiUtil.resolveClassInType(type) == null) { type = null } type } else it.type } fun mapArguments(): Map<Argument, Pair<PsiParameter, PsiType?>> { return mapArguments(typeComputer) } fun completionMapArguments(): Map<Argument, Pair<PsiParameter, PsiType?>> { return mapArguments(completionTypeComputer) } private fun mapArguments(typeComputer:(Argument) -> PsiType?): Map<Argument, Pair<PsiParameter, PsiType?>> { val erasedSignature = GrClosureSignatureUtil.createSignature(method, siteSubstitutor, true) // check it val argInfos = mapParametersToArguments(erasedSignature, arguments.toTypedArray(), typeComputer, context, true) ?: return emptyMap() val params = method.parameterList.parameters val map = HashMap<Argument, Pair<PsiParameter, PsiType?>>() argInfos.forEachIndexed { index, argInfo -> argInfo ?: return@forEachIndexed val param = if (index < params.size) params[index] else null ?: return@forEachIndexed var paramType = param.type if (argInfo.isMultiArg && paramType is PsiArrayType) paramType = paramType.componentType argInfo.args.forEach { map[it] = Pair(param, paramType) } } return map } fun getArgumentTypes(): Array<PsiType?> { return arguments.map(typeComputer).toTypedArray() } }
apache-2.0
85450252b82e0e59d5ee23568e93d1e2
38.57971
140
0.717949
4.497529
false
false
false
false
marius-m/wt4
credits/src/main/kotlin/lt/markmerkk/repositories/CreditsRepository.kt
1
3973
package lt.markmerkk.repositories import com.google.gson.FieldNamingPolicy import com.google.gson.GsonBuilder import com.google.gson.JsonSyntaxException import com.google.gson.stream.MalformedJsonException import lt.markmerkk.entities.Credit import org.apache.commons.io.FileUtils import org.apache.commons.io.IOUtils import org.slf4j.LoggerFactory import rx.Single import java.io.File import java.io.IOException import java.net.URISyntaxException import java.util.jar.JarFile class CreditsRepository { private val gson = GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() private val creditPath: String = "credits" private var credits: List<Credit> = emptyList() fun creditEntries(): Single<List<Credit>> { return if (credits.isEmpty()) { Single.defer { val jarFile = File(javaClass.protectionDomain.codeSource.location.path) if (jarFile.isFile) { readFromJsonResource(jarFile) } else { readFromLocalResource() } }.doOnSuccess { this.credits = it } } else { Single.just(credits) } } private fun readFromLocalResource(): Single<List<Credit>> { return Single.defer<List<Credit>> { val url = CreditsRepository::class.java.getResource("/$creditPath") if (url == null) Single.error<List<Credit>>(IllegalStateException("Cannot figure URL")) try { val credits = File(url.toURI()).listFiles() .mapNotNull { try { val contents = FileUtils.readFileToString(it) Pair(it.name, contents) } catch (e: IOException) { logger.warn("Cannot read ${it.name}", e) null } } .mapNotNull { (fileName, fileContents) -> toCredit(fileName, fileContents) } Single.just(credits) } catch (ex: URISyntaxException) { ex.printStackTrace() Single.error<List<Credit>>(IllegalArgumentException("Error reading local resource")) } } } private fun readFromJsonResource( jarFile: File ): Single<List<Credit>> { return Single.defer { val jar = JarFile(jarFile) val entries = jar.entries() val jarEntries = entries.toList() .filter { it.name.startsWith("$creditPath/") } .mapNotNull { try { val contents = jarFileToString(it.name) Pair(it.name, contents) } catch (e: IOException) { logger.warn("Cannot read ${it.name}", e) null } }.mapNotNull { (name, contents) -> toCredit(name, contents) } jar.close() Single.just(jarEntries) } } @Throws(IOException::class) private fun jarFileToString(inputPath: String): String { val fileIs = javaClass.classLoader.getResourceAsStream(inputPath) return IOUtils.toString(fileIs, "UTF-8") } private fun toCredit(source: String, input: String): Credit? { return try { gson.fromJson(input, Credit::class.java) } catch (e: JsonSyntaxException) { logger.warn("Error trying to parse out json from $source", e) null } catch (e: MalformedJsonException) { logger.warn("Error trying to parse out json from $source", e) null } } companion object { val logger = LoggerFactory.getLogger(CreditsRepository::class.java)!! } }
apache-2.0
02d90b7bd600448217932420552f3ae6
34.482143
100
0.549962
5.061146
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/atomicsimulations/DFTParser.kt
2
9792
package graphics.scenery.atomicsimulations import org.joml.Vector3f import org.joml.Vector3i import org.lwjgl.system.MemoryUtil import java.io.File import java.nio.ByteBuffer /** * This class parses density functional theory (common simulation method in solid state physics and theoretical * chemistry) calculation. Can be used to visualize single DFT calculation or DFT-MD (=DFT molecular dynamics). * [normalizeDensityTo] Defines to which value the density is scaled. This is useful when visualizing more then one DFT * calculation at the same time, in order to keep the density visualization consistent. Negative * values mean the density is scaled per snapshot. Default is -1.0f. * * @author Lenz Fiedler <[email protected]> */ class DFTParser (private val normalizeDensityTo: Float = -1.0f): AutoCloseable{ /** Number of Atoms.*/ var numberOfAtoms: Int = 0 /** Distance between two grid points in either direction in Bohr.*/ var gridSpacings = Vector3f( 0.0f, 0.0f, 0.0f) /** Number of gridpoints in 3D grid.*/ var gridDimensions = Vector3i( 0, 0, 0) /** Positions of the atoms in Bohr.*/ var atomicPositions = Array(0){ Vector3f()} /** Electronic density as float values.*/ private var electronicDensity = FloatArray(0) /** Electronic density as scaled bytes, in scaled(1/Bohr).*/ lateinit var electronicDensityUByte: ByteBuffer protected set /** Indicates whether memory was allocated for electronic density */ private var electronicDensityMemory: Int = -1 /** Origin of the unit cell, usually 0,0,0. */ var unitCellOrigin = Vector3f( 0.0f, 0.0f, 0.0f) /** Dimensions of the unit cell, in Bohr.*/ var unitCellDimensions = Vector3f( 0.0f, 0.0f, 0.0f) /** Closes this buffer, freeing all allocated resources on host and device. */ override fun close() { // Only free memory if we allocated some during parsing. if (electronicDensityMemory > 0){ MemoryUtil.memFree(electronicDensityUByte) } } /** * Parse information as .cube file. * [filename] Name of the file that is parsed. * [cubeStyle] Name of the software with which cube file was created (or comparable software). .cube is * actually a very loosely defined standard. If we don't know anything about the cube file, we * have no choice but to use Regex parsing, which impacts performance. If we know the source * of the cube file, other assumptions can be made. */ fun parseCube(filename: String, cubeStyle: String="unknown"){ // Read entire file content val cubeFile = File(filename).bufferedReader().readLines() var counter = 0 var xcounter = 0 var ycounter = 0 var zcounter = 0 var minDensity = 1000.0f var maxDensity = 0.0f // Iterate through file. We know what is were with a cube file. // 0-1: Comments. // 2: Number of atoms + origin. // 3,4,5: Grid spacing in x,y,z direction (in Bohr) // 6 - (number_of_atoms+6): One line for each atom with position and species // Everything thereafter: the volumetric data, here the density. val whiteSpaceRegex = Regex("\\s+") for (line in cubeFile){ when (counter){ 0,1 ->{} 2 -> { val lineContent = (line.trim().split(whiteSpaceRegex)) numberOfAtoms = lineContent[0].toInt() unitCellOrigin.x = lineContent[1].toFloat() unitCellOrigin.y = lineContent[2].toFloat() unitCellOrigin.z = lineContent[3].toFloat() // Now we know how many atoms we have. atomicPositions = Array(numberOfAtoms){ Vector3f()} } 3 -> { val lineContent = (line.trim().split(whiteSpaceRegex)) gridDimensions.x = lineContent[0].toInt() gridSpacings.x = lineContent[1].toFloat() } 4 -> { val lineContent = (line.trim().split(whiteSpaceRegex)) gridDimensions.y = lineContent[0].toInt() gridSpacings.y = lineContent[2].toFloat() } 5 -> { val lineContent = (line.trim().split(whiteSpaceRegex)) gridDimensions.z = lineContent[0].toInt() gridSpacings.z = lineContent[3].toFloat() } else-> { if (counter == 6) { unitCellDimensions.x = (gridSpacings[0]*gridDimensions[0])+unitCellOrigin[0] unitCellDimensions.y = (gridSpacings[1]*gridDimensions[1])+unitCellOrigin[1] unitCellDimensions.z = (gridSpacings[2]*gridDimensions[2])+unitCellOrigin[2] electronicDensity = FloatArray(gridDimensions[0]*gridDimensions[1]*gridDimensions[2]) } // Parsing atomic positions. if (counter < 6+numberOfAtoms){ val lineContent = (line.trim().split(whiteSpaceRegex)) atomicPositions[counter-6] = Vector3f(lineContent[2].toFloat(), lineContent[3].toFloat(), lineContent[4].toFloat()) } // Parsing volumetric data. // A possible optimization here would be to read this into a 1D array. We cannot directly // read it into the byte buffer, because we don't know max/min values a-priori. if (counter >= 6+numberOfAtoms) { if (cubeStyle == "QE") { val lineContent = line.trim().split(" ") for (i in 0..lineContent.size step 2){ // Cube files should be in Fortran (z-fastest ordering). // Kotlin is x-fastest ordering, so we have to convert that. val floatVal = lineContent[i].toFloat() electronicDensity[xcounter + ycounter * gridDimensions[0] + zcounter*gridDimensions[1] * gridDimensions[0]] = floatVal if (floatVal > maxDensity) { maxDensity = floatVal } if (floatVal < minDensity) { minDensity = floatVal } zcounter++ if (zcounter == gridDimensions[2]) { zcounter = 0 ycounter++ if (ycounter == gridDimensions[1]) { ycounter = 0 xcounter++ } } } } else { val lineContent = (line.trim().split(whiteSpaceRegex)) for (value in lineContent) { // Cube files should be in Fortran (z-fastest ordering). // Kotlin is x-fastest ordering, so we have to convert that. val floatVal = value.toFloat() electronicDensity[xcounter + ycounter * gridDimensions[0] + zcounter*gridDimensions[1] * gridDimensions[0]] = floatVal if (floatVal > maxDensity) { maxDensity = floatVal } if (floatVal < minDensity) { minDensity = floatVal } zcounter++ if (zcounter == gridDimensions[2]) { zcounter = 0 ycounter++ if (ycounter == gridDimensions[1]) { ycounter = 0 xcounter++ } } } } } } } counter++ } // Converting to byte buffer. counter = 0 if (normalizeDensityTo > 0.0f){ maxDensity = normalizeDensityTo } // Working on a temporary buffer, in case someone is accessing the buffer while we are still parsing. electronicDensityMemory = gridDimensions[0]* gridDimensions[1]*gridDimensions[2]*1 electronicDensityUByte = MemoryUtil.memAlloc((electronicDensityMemory)) val tmpElectronicDensityUByte: ByteBuffer = electronicDensityUByte.duplicate() for (z in 0 until gridDimensions[2]){ for (y in 0 until gridDimensions[1]){ for (x in 0 until gridDimensions[0]){ val value = (((electronicDensity[x+y*gridDimensions[0]+z*gridDimensions[1]*gridDimensions[0]] - minDensity) / (maxDensity - minDensity)) * 255.0f).toInt() tmpElectronicDensityUByte.put(value.toByte()) counter++ } } } } }
lgpl-3.0
0cfbbdcf3154ee2e2193c828fb6bf0d6
47.716418
120
0.501838
5.38022
false
false
false
false
ayatk/biblio
app/src/main/kotlin/com/ayatk/biblio/ui/ranking/RankingListFragment.kt
1
3149
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.ui.ranking import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.ayatk.biblio.databinding.FragmentRankingListBinding import com.ayatk.biblio.model.Novel import com.ayatk.biblio.model.enums.RankingType import com.ayatk.biblio.ui.ranking.item.RankingItem import com.ayatk.biblio.ui.util.helper.navigateToDetail import com.ayatk.biblio.ui.util.init import com.ayatk.biblio.util.Result import com.ayatk.biblio.util.ext.observe import com.ayatk.biblio.util.ext.setVisible import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import dagger.android.support.DaggerFragment import timber.log.Timber import javax.inject.Inject class RankingListFragment : DaggerFragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var binding: FragmentRankingListBinding private val viewModel: RankingViewModel by lazy { ViewModelProvider(this, viewModelFactory).get(RankingViewModel::class.java) } private val rankingType: RankingType by lazy { arguments?.getSerializable(BUNDLE_ARGS_RANKING_TYPE)!! as RankingType } private val groupAdapter = GroupAdapter<ViewHolder>() private val onClickListener = { novel: Novel -> requireContext().navigateToDetail(novel) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentRankingListBinding.inflate(inflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.list.init(groupAdapter) viewModel.rankings(rankingType).observe(this) { result -> when (result) { is Result.Success -> { val rankings = result.data groupAdapter.update(rankings.map { RankingItem(it, onClickListener) }) binding.progress.setVisible(rankings.isEmpty()) binding.list.setVisible(rankings.isNotEmpty()) } is Result.Failure -> Timber.e(result.e) } } } companion object { private const val BUNDLE_ARGS_RANKING_TYPE = "ranking_type" fun newInstance(rankingType: RankingType): Fragment = RankingListFragment().apply { arguments = bundleOf(BUNDLE_ARGS_RANKING_TYPE to rankingType) } } }
apache-2.0
421bb36ac102be2334a796cdfc26d455
30.808081
79
0.748174
4.410364
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/controls/SwingMouseAndKeyHandler.kt
2
17856
/*- * #%L * Configurable key and mouse event handling * %% * Copyright (C) 2015 - 2017 Max Planck Institute of Molecular Cell Biology * and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package graphics.scenery.controls import org.joml.Vector3f import com.jogamp.newt.awt.NewtCanvasAWT import gnu.trove.set.TIntSet import graphics.scenery.Hub import graphics.scenery.Settings import graphics.scenery.backends.SceneryWindow import org.joml.Vector2f import org.scijava.ui.behaviour.* import org.scijava.ui.behaviour.KeyPressedManager.KeyPressedReceiver import java.awt.Component import java.awt.Toolkit import java.awt.event.* import java.util.* /** * Input handling class for Swing-based windows * * TODO: Includes a bit of old AWT code, e.g. for getModifiers. Needs to be replaced with newer getModifiersEx() code, and Suppress removed. * * @author Ulrik Günther <[email protected]> */ @Suppress("DEPRECATION") @CanHandleInputFor([SceneryWindow.SwingWindow::class]) class SwingMouseAndKeyHandler(var hub: Hub? = null) : MouseAndKeyHandlerBase(), KeyListener, MouseListener, MouseWheelListener, MouseMotionListener, FocusListener { /* * Event handling. Forwards to registered behaviours. */ private val globalKeys = GlobalKeyEventDispatcher.getInstance() /** * If non-null, [.keyPressed] events are forwarded to the * [KeyPressedManager] which in turn forwards to the * [KeyPressedReceiver] of the component currently under the mouse. * (This requires that the other component is also registered with the * [KeyPressedManager]. */ private var keypressManager: KeyPressedManager? = null /** * Represents this [MouseAndKeyHandler] to the [.keypressManager]. */ private var receiver: KeyPressedReceiver? = null private fun getMask(e: InputEvent): Int { val modifiers = e.modifiers val modifiersEx = e.modifiersEx var mask = modifiersEx /* * For scrolling AWT uses the SHIFT_DOWN_MASK to indicate horizontal scrolling. * We keep track of whether the SHIFT key was actually pressed for disambiguation. */ if (globalKeys.shiftPressed()) mask = mask or InputEvent.SHIFT_DOWN_MASK else mask = mask and InputEvent.SHIFT_DOWN_MASK.inv() /* * On OS X AWT sets the META_DOWN_MASK to for right clicks. We keep * track of whether the META key was actually pressed for * disambiguation. */ if (globalKeys.metaPressed()) mask = mask or InputEvent.META_DOWN_MASK else mask = mask and InputEvent.META_DOWN_MASK.inv() if (globalKeys.winPressed()) mask = mask or InputTrigger.WIN_DOWN_MASK /* * We add the button modifiers to modifiersEx such that the * XXX_DOWN_MASK can be used as the canonical flag. E.g. we adapt * modifiersEx such that BUTTON1_DOWN_MASK is also present in * mouseClicked() when BUTTON1 was clicked (although the button is no * longer down at this point). * * ...but only if its not a MOUSE_WHEEL because OS X sets button * modifiers if ALT or META modifiers are pressed. * * ...and also only if its not a MOUSE_RELEASED. Otherwise we will not * be able to detect drag-end because the mask would still match the * drag trigger. */ if (e.id != MouseEvent.MOUSE_WHEEL && e.id != MouseEvent.MOUSE_RELEASED) { if (modifiers and InputEvent.BUTTON1_MASK != 0) mask = mask or InputEvent.BUTTON1_DOWN_MASK if (modifiers and InputEvent.BUTTON2_MASK != 0) mask = mask or InputEvent.BUTTON2_DOWN_MASK if (modifiers and InputEvent.BUTTON3_MASK != 0) mask = mask or InputEvent.BUTTON3_DOWN_MASK } /* * On OS X AWT sets the BUTTON3_DOWN_MASK for meta+left clicks. Fix * that. */ if (modifiers == OSX_META_LEFT_CLICK) mask = mask and InputEvent.BUTTON3_DOWN_MASK.inv() /* * On OS X AWT sets the BUTTON2_DOWN_MASK for alt+left clicks. Fix * that. */ if (modifiers == OSX_ALT_LEFT_CLICK) mask = mask and InputEvent.BUTTON2_DOWN_MASK.inv() /* * On OS X AWT sets the BUTTON2_DOWN_MASK for alt+right clicks. Fix * that. */ if (modifiers == OSX_ALT_RIGHT_CLICK) mask = mask and InputEvent.BUTTON2_DOWN_MASK.inv() /* * Deal with mouse double-clicks. */ if (e is MouseEvent && e.clickCount > 1) mask = mask or InputTrigger.DOUBLE_CLICK_MASK // mouse if (e is MouseWheelEvent) mask = mask or InputTrigger.SCROLL_MASK return mask } /* * KeyListener, MouseListener, MouseWheelListener, MouseMotionListener. */ override fun mouseDragged(e: MouseEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mouseDragged()" ); // logger.trace( e ); update() val x = (e.x * surfaceScale.x()).toInt() val y = (e.y * surfaceScale.y()).toInt() for (drag in activeButtonDrags) drag.behaviour.drag(x, y) } override fun mouseMoved(e: MouseEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mouseMoved()" ); update() mouseX = (e.x * surfaceScale.x()).toInt() mouseY = (e.y * surfaceScale.y()).toInt() for (drag in activeKeyDrags) drag.behaviour.drag(mouseX, mouseY) } override fun mouseWheelMoved(e: MouseWheelEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mouseWheelMoved()" ); // logger.trace( e ); update() val mask = getMask(e) val x = (e.x * surfaceScale.x()).toInt() val y = (e.y * surfaceScale.y()).toInt() val wheelRotation = e.preciseWheelRotation /* * AWT uses the SHIFT_DOWN_MASK to indicate horizontal scrolling. We * keep track of whether the SHIFT key was actually pressed for * disambiguation. However, we can only detect horizontal scrolling if * the SHIFT key is not pressed. With SHIFT pressed, everything is * treated as vertical scrolling. */ val exShiftMask = e.modifiersEx and InputEvent.SHIFT_DOWN_MASK != 0 val isHorizontal = !globalKeys.shiftPressed() && exShiftMask for (scroll in scrolls) { if (scroll.buttons.matches(mask, globalKeys.pressedKeys())) { scroll.behaviour.scroll(wheelRotation, isHorizontal, x, y) } } } override fun mouseClicked(e: MouseEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mouseClicked()" ); // logger.trace( e ); update() val mask = getMask(e) val x = (e.x * surfaceScale.x()).toInt() val y = (e.y * surfaceScale.y()).toInt() val clickMask = mask and InputTrigger.DOUBLE_CLICK_MASK.inv() for (click in buttonClicks) { if (click.buttons.matches(mask, pressedKeys) || clickMask != mask && click.buttons.matches(clickMask, pressedKeys)) { click.behaviour.click(x, y) } } } override fun mousePressed(e: MouseEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mousePressed()" ) // logger.trace( e ); update() val mask = getMask(e) val x = (e.x * surfaceScale.x()).toInt() val y = (e.y * surfaceScale.y()).toInt() for (drag in buttonDrags) { if (drag.buttons.matches(mask, globalKeys.pressedKeys())) { drag.behaviour.init(x, y) activeButtonDrags.add(drag) } } } override fun mouseReleased(e: MouseEvent) { val surfaceScale = hub?.get<Settings>()?.get("Renderer.SurfaceScale", Vector2f(1.0f, 1.0f)) ?: Vector2f(1.0f, 1.0f) logger.trace( "MouseAndKeyHandler.mouseReleased()" ) // logger.trace( e ); update() val x = (e.x * surfaceScale.x()).toInt() val y = (e.y * surfaceScale.y()).toInt() val mask = getMask(e) val ended = ArrayList<BehaviourEntry<*>>() for (drag in activeButtonDrags) if (!drag.buttons.matchesSubset(mask, globalKeys.pressedKeys())) { drag.behaviour.end(x, y) ended.add(drag) } activeButtonDrags.removeAll(ended) } override fun mouseEntered(e: MouseEvent) { logger.trace( "MouseAndKeyHandler.mouseEntered()" ) update() keypressManager?.activate(receiver) } override fun mouseExited(e: MouseEvent) { logger.trace( "MouseAndKeyHandler.mouseExited()" ) update() keypressManager?.deactivate(receiver) } override fun keyPressed(e: KeyEvent) { logger.trace( "MouseAndKeyHandler.keyPressed()" ) // logger.trace( e ); update() if (e.keyCode != 0 && e.keyCode != KeyEvent.VK_SHIFT && e.keyCode != KeyEvent.VK_META && e.keyCode != KeyEvent.VK_WINDOWS && e.keyCode != KeyEvent.VK_ALT && e.keyCode != KeyEvent.VK_CONTROL && e.keyCode != KeyEvent.VK_ALT_GRAPH) { val inserted = pressedKeys.add(e.keyCode) /* * Create mask and deal with double-click on keys. */ val mask = getMask(e) var doubleClick = false if (inserted) { // double-click on keys. val lastPressTime = keyPressTimes.get(e.keyCode) if (lastPressTime != -1L && e.getWhen() - lastPressTime < DOUBLE_CLICK_INTERVAL) doubleClick = true keyPressTimes.put(e.keyCode, e.getWhen()) } keypressManager?.handleKeyPressed(receiver, mask, doubleClick, pressedKeys) ?: handleKeyPressed(mask, doubleClick, pressedKeys, false) } } /** * @param keypressManager * @param focus * function that ensures that the component associated to this * [MouseAndKeyHandler] is focused. */ fun setKeypressManager( keypressManager: KeyPressedManager, focus: Runnable) { this.keypressManager = keypressManager this.receiver = KeyPressedReceiver { _, mask, doubleClick, pressedKeys -> if ([email protected](mask, doubleClick, pressedKeys, true)) focus.run() [email protected](mask, doubleClick, pressedKeys, false) } } /** * @param keypressManager * @param focusableOwner * container of this [MouseAndKeyHandler]. If key presses * are forwarded from the [KeyPressedManager] while the * component does not have focus, then * [Component.requestFocus]. */ fun setKeypressManager( keypressManager: KeyPressedManager, focusableOwner: Component) { setKeypressManager(keypressManager, Runnable { if (!focusableOwner.isFocusOwner) { // focusableOwner.requestFocusInWindow(); focusableOwner.requestFocus() } }) } private fun handleKeyPressed(mask: Int, doubleClick: Boolean, pressedKeys: TIntSet, dryRun: Boolean): Boolean { update() val doubleClickMask = mask or InputTrigger.DOUBLE_CLICK_MASK var triggered = false for (drag in keyDrags) { if (!activeKeyDrags.contains(drag) && (drag.buttons.matches(mask, pressedKeys) || doubleClick && drag.buttons.matches(doubleClickMask, pressedKeys))) { if (dryRun) return true triggered = true drag.behaviour.init(mouseX, mouseY) activeKeyDrags.add(drag) } } for (click in keyClicks) { if (click.buttons.matches(mask, pressedKeys) || doubleClick && click.buttons.matches(doubleClickMask, pressedKeys)) { if (dryRun) return true triggered = true click.behaviour.click(mouseX, mouseY) } } return triggered } override fun keyReleased(e: KeyEvent) { // logger.trace( "MouseAndKeyHandler.keyReleased()" ); // logger.trace( e ); update() if (e.keyCode != 0 && e.keyCode != KeyEvent.VK_SHIFT && e.keyCode != KeyEvent.VK_META && e.keyCode != KeyEvent.VK_WINDOWS && e.keyCode != KeyEvent.VK_ALT && e.keyCode != KeyEvent.VK_CONTROL && e.keyCode != KeyEvent.VK_ALT_GRAPH) { pressedKeys.remove(e.keyCode) val mask = getMask(e) val ended = ArrayList<BehaviourEntry<*>>() for (drag in activeKeyDrags) if (!drag.buttons.matchesSubset(mask, pressedKeys)) { drag.behaviour.end(mouseX, mouseY) ended.add(drag) } activeKeyDrags.removeAll(ended) } } override fun keyTyped(e: KeyEvent) { // logger.trace( "MouseAndKeyHandler.keyTyped()" ); // logger.trace( e ); } override fun focusGained(e: FocusEvent) { // logger.trace( "MouseAndKeyHandler.focusGained()" ); pressedKeys.clear() pressedKeys.addAll(globalKeys.pressedKeys()) } override fun focusLost(e: FocusEvent) { // logger.trace( "MouseAndKeyHandler.focusLost()" ); pressedKeys.clear() } override fun attach(hub: Hub?, window: SceneryWindow, inputMap: InputTriggerMap, behaviourMap: BehaviourMap): MouseAndKeyHandlerBase { val handler: MouseAndKeyHandlerBase when (window) { is SceneryWindow.SwingWindow -> { val component = window.panel.component val cglWindow = window.panel.cglWindow if (component is NewtCanvasAWT && cglWindow != null) { handler = JOGLMouseAndKeyHandler(hub) handler.setInputMap(inputMap) handler.setBehaviourMap(behaviourMap) cglWindow.addKeyListener(handler) cglWindow.addMouseListener(handler) } else { handler = SwingMouseAndKeyHandler(hub) handler.setInputMap(inputMap) handler.setBehaviourMap(behaviourMap) val ancestor = window.panel.component ancestor?.addKeyListener(handler) ancestor?.addMouseListener(handler) ancestor?.addMouseMotionListener(handler) ancestor?.addMouseWheelListener(handler) ancestor?.addFocusListener(handler) } } is SceneryWindow.HeadlessWindow -> { handler = this handler.setInputMap(inputMap) handler.setBehaviourMap(behaviourMap) } else -> throw UnsupportedOperationException("Don't know how to handle window of type $window. Supported types are: ${(this.javaClass.annotations.find { it is CanHandleInputFor } as? CanHandleInputFor)?.windowTypes?.joinToString(", ")}") } return handler } companion object { private val DOUBLE_CLICK_INTERVAL = doubleClickInterval private val OSX_META_LEFT_CLICK = InputEvent.BUTTON1_MASK or InputEvent.BUTTON3_MASK or InputEvent.META_MASK private val OSX_ALT_LEFT_CLICK = InputEvent.BUTTON1_MASK or InputEvent.BUTTON2_MASK or InputEvent.ALT_MASK private val OSX_ALT_RIGHT_CLICK = InputEvent.BUTTON3_MASK or InputEvent.BUTTON2_MASK or InputEvent.ALT_MASK or InputEvent.META_MASK private val doubleClickInterval: Int get() { val prop = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval") return if (prop == null) 200 else prop as Int } } }
lgpl-3.0
19cb8d4d2614cd9b25b674bcaa407bf2
35.588115
248
0.619882
4.499748
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInTabComplete.kt
1
1892
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.packet import com.mcmoonlake.api.block.BlockPosition import com.mcmoonlake.api.isCombatOrLaterVer import com.mcmoonlake.api.notNull data class PacketInTabComplete( var message: String, var blockPosition: BlockPosition?, /** * * Whether it is selected as a command block, only valid at 1.9 or later. * * 是否选中的为命令方块, 仅在 1.9 或更高版本有效. */ var isCommandBlock: Boolean ) : PacketInBukkitAbstract("PacketPlayInTabComplete") { @Deprecated("") constructor() : this("", null, false) override fun read(data: PacketBuffer) { message = data.readString() if(isCombatOrLaterVer) isCommandBlock = data.readBoolean() if(data.readBoolean()) blockPosition = data.readBlockPosition() } override fun write(data: PacketBuffer) { data.writeString(message) if(isCombatOrLaterVer) data.writeBoolean(isCommandBlock) data.writeBoolean(blockPosition != null) if(blockPosition != null) data.writeBlockPosition(blockPosition.notNull()) } }
gpl-3.0
a5e5921c4e172f1022e4078706462d8e
33.333333
83
0.688781
4.362353
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/HistoryKeyListener.kt
6
3286
// 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.console import com.intellij.codeInsight.lookup.LookupManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.project.Project import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import kotlin.math.max import kotlin.math.min class HistoryKeyListener(private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory) : KeyAdapter(), HistoryUpdateListener { private var historyPos = 0 private var prevCaretOffset = -1 private var unfinishedCommand = "" override fun onNewEntry(entry: CommandHistory.Entry) { // reset history positions historyPos = history.size prevCaretOffset = -1 unfinishedCommand = "" } private enum class HistoryMove { UP, DOWN } override fun keyReleased(e: KeyEvent) { when (e.keyCode) { KeyEvent.VK_UP -> moveHistoryCursor(HistoryMove.UP) KeyEvent.VK_DOWN -> moveHistoryCursor(HistoryMove.DOWN) KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT -> prevCaretOffset = consoleEditor.caretModel.offset } } private fun moveHistoryCursor(move: HistoryMove) { if (history.size == 0) return if (LookupManager.getInstance(project).activeLookup != null) return val caret = consoleEditor.caretModel val document = consoleEditor.document val curOffset = caret.offset val curLine = document.getLineNumber(curOffset) val totalLines = document.lineCount val isMultiline = totalLines > 1 when (move) { HistoryMove.UP -> { if (curLine != 0 || (isMultiline && prevCaretOffset != 0)) { prevCaretOffset = curOffset return } if (historyPos == history.size) { unfinishedCommand = document.text } historyPos = max(historyPos - 1, 0) WriteCommandAction.runWriteCommandAction(project) { document.setText(history[historyPos].entryText) EditorUtil.scrollToTheEnd(consoleEditor) prevCaretOffset = 0 caret.moveToOffset(0) } } HistoryMove.DOWN -> { if (historyPos == history.size) return if (curLine != totalLines - 1 || (isMultiline && prevCaretOffset != document.textLength)) { prevCaretOffset = curOffset return } historyPos = min(historyPos + 1, history.size) WriteCommandAction.runWriteCommandAction(project) { document.setText(if (historyPos == history.size) unfinishedCommand else history[historyPos].entryText) prevCaretOffset = document.textLength EditorUtil.scrollToTheEnd(consoleEditor) } } } } }
apache-2.0
1ffb22a7066702ae1e996d1feac844ab
36.352273
158
0.618685
5.224165
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/diagnosticMessage/js/jsCodeErrorHtml.kt
13
273
// !DIAGNOSTICS_NUMBER: 4 // !DIAGNOSTICS: JSCODE_ERROR // !MESSAGE_TYPE: HTML fun box() { val i = "i" val n = 10 js("var = $n;") js("""var a = 10; var = $n; var c = 15;""") js("""for (var $i = )""") js("var = 10;") }
apache-2.0
41ca06bd7deb84944b4939fad0c30227
13.421053
29
0.410256
2.873684
false
false
false
false
ben-manes/gradle-versions-plugin
gradle-versions-plugin/src/main/kotlin/com/github/benmanes/gradle/versions/updates/DependencyUpdatesReporter.kt
1
12722
package com.github.benmanes.gradle.versions.updates import com.github.benmanes.gradle.versions.reporter.HtmlReporter import com.github.benmanes.gradle.versions.reporter.JsonReporter import com.github.benmanes.gradle.versions.reporter.PlainTextReporter import com.github.benmanes.gradle.versions.reporter.Reporter import com.github.benmanes.gradle.versions.reporter.XmlReporter import com.github.benmanes.gradle.versions.reporter.result.DependenciesGroup import com.github.benmanes.gradle.versions.reporter.result.Dependency import com.github.benmanes.gradle.versions.reporter.result.DependencyLatest import com.github.benmanes.gradle.versions.reporter.result.DependencyOutdated import com.github.benmanes.gradle.versions.reporter.result.DependencyUnresolved import com.github.benmanes.gradle.versions.reporter.result.Result import com.github.benmanes.gradle.versions.reporter.result.VersionAvailable import com.github.benmanes.gradle.versions.updates.gradle.GradleReleaseChannel import com.github.benmanes.gradle.versions.updates.gradle.GradleUpdateChecker import com.github.benmanes.gradle.versions.updates.gradle.GradleUpdateResult import com.github.benmanes.gradle.versions.updates.gradle.GradleUpdateResults import org.gradle.api.Project import org.gradle.api.artifacts.ModuleVersionSelector import org.gradle.api.artifacts.UnresolvedDependency import java.io.File import java.io.PrintStream import java.io.PrintWriter import java.io.StringWriter import java.util.TreeSet /** * Sorts and writes the resolved dependency reports. * * @property project The project evaluated against. * @property revision The revision strategy evaluated with. * @property outputFormatterArgument The output formatter strategy evaluated with. * @property outputDir The outputDir for report. * @property reportfileName The filename of the report file. * @property currentVersions The current versions of each dependency declared in the project(s). * @property latestVersions The latest versions of each dependency (as scoped by the revision level). * @property upToDateVersions The dependencies that are up to date (same as latest found). * @property downgradeVersions The dependencies that exceed the latest found (e.g. may not want SNAPSHOTs). * @property upgradeVersions The dependencies where upgrades were found (below latest found). * @property undeclared The dependencies that were declared without version. * @property unresolved The dependencies that could not be resolved. * @property projectUrls Project urls of maven dependencies. * @property gradleUpdateChecker Facade object to access information about running gradle versions * and gradle updates. * @property gradleReleaseChannel The gradle release channel to use for reporting. * */ class DependencyUpdatesReporter( val project: Project, val revision: String, private val outputFormatterArgument: OutputFormatterArgument, val outputDir: String, val reportfileName: String?, val currentVersions: Map<Map<String, String>, Coordinate>, val latestVersions: Map<Map<String, String>, Coordinate>, val upToDateVersions: Map<Map<String, String>, Coordinate>, val downgradeVersions: Map<Map<String, String>, Coordinate>, val upgradeVersions: Map<Map<String, String>, Coordinate>, val undeclared: Set<Coordinate>, val unresolved: Set<UnresolvedDependency>, val projectUrls: Map<Map<String, String>, String>, val gradleUpdateChecker: GradleUpdateChecker, val gradleReleaseChannel: String, ) { @Synchronized fun write() { if (outputFormatterArgument !is OutputFormatterArgument.CustomAction) { val plainTextReporter = PlainTextReporter( project, revision, gradleReleaseChannel ) plainTextReporter.write(System.out, buildBaseObject()) } if (outputFormatterArgument is OutputFormatterArgument.BuiltIn && outputFormatterArgument.formatterNames.isEmpty()) { project.logger.lifecycle("Skip generating report to file (outputFormatter is empty)") return } when (outputFormatterArgument) { is OutputFormatterArgument.BuiltIn -> { for (it in outputFormatterArgument.formatterNames.split(",")) { generateFileReport(getOutputReporter(it)) } } is OutputFormatterArgument.CustomReporter -> { generateFileReport(outputFormatterArgument.reporter) } is OutputFormatterArgument.CustomAction -> { val result = buildBaseObject() outputFormatterArgument.action.execute(result) } } } private fun generateFileReport(reporter: Reporter) { val fileName = File(outputDir, reportfileName + "." + reporter.getFileExtension()) project.file(outputDir).mkdirs() val outputFile = project.file(fileName) val stream = PrintStream(outputFile) val result = buildBaseObject() reporter.write(stream, result) stream.close() project.logger.lifecycle("\nGenerated report file $fileName") } private fun getOutputReporter(formatterOriginal: String): Reporter { return when (formatterOriginal.trim()) { "json" -> JsonReporter(project, revision, gradleReleaseChannel) "xml" -> XmlReporter(project, revision, gradleReleaseChannel) "html" -> HtmlReporter(project, revision, gradleReleaseChannel) else -> PlainTextReporter(project, revision, gradleReleaseChannel) } } private fun buildBaseObject(): Result { val sortedCurrent = buildCurrentGroup() val sortedOutdated = buildOutdatedGroup() val sortedExceeded = buildExceededGroup() val sortedUndeclared = buildUndeclaredGroup() val sortedUnresolved = buildUnresolvedGroup() val count = sortedCurrent.size + sortedOutdated.size + sortedExceeded.size + sortedUndeclared.size + sortedUnresolved.size return buildObject( count = count, currentGroup = buildDependenciesGroup(sortedCurrent), outdatedGroup = buildDependenciesGroup(sortedOutdated), exceededGroup = buildDependenciesGroup(sortedExceeded), undeclaredGroup = buildDependenciesGroup(sortedUndeclared), unresolvedGroup = buildDependenciesGroup(sortedUnresolved), gradleUpdateResults = buildGradleUpdateResults(), ) } /** * Create a [GradleUpdateResults] object from the information provided by the [GradleUpdateChecker] * @return filled out object instance */ private fun buildGradleUpdateResults(): GradleUpdateResults { val enabled = gradleUpdateChecker.enabled return GradleUpdateResults( enabled = enabled, running = GradleUpdateResult( enabled = enabled, running = gradleUpdateChecker.getRunningGradleVersion(), release = gradleUpdateChecker.getRunningGradleVersion(), ), current = GradleUpdateResult( enabled = enabled, running = gradleUpdateChecker.getRunningGradleVersion(), release = gradleUpdateChecker.getCurrentGradleVersion(), ), releaseCandidate = GradleUpdateResult( enabled = enabled && ( gradleReleaseChannel == GradleReleaseChannel.RELEASE_CANDIDATE.id || gradleReleaseChannel == GradleReleaseChannel.NIGHTLY.id ), running = gradleUpdateChecker.getRunningGradleVersion(), release = gradleUpdateChecker.getReleaseCandidateGradleVersion(), ), nightly = GradleUpdateResult( enabled = enabled && (gradleReleaseChannel == GradleReleaseChannel.NIGHTLY.id), running = gradleUpdateChecker.getRunningGradleVersion(), release = gradleUpdateChecker.getNightlyGradleVersion(), ), ) } private fun buildCurrentGroup(): MutableSet<Dependency> { return sortByGroupAndName(upToDateVersions) .map { dep -> updateKey(dep.key as HashMap) buildDependency(dep.value, dep.key) }.toSortedSet() } private fun buildOutdatedGroup(): MutableSet<DependencyOutdated> { return sortByGroupAndName(upgradeVersions) .map { dep -> updateKey(dep.key as HashMap) buildOutdatedDependency(dep.value, dep.key) }.toSortedSet() } private fun buildExceededGroup(): MutableSet<DependencyLatest> { return sortByGroupAndName(downgradeVersions) .map { dep -> updateKey(dep.key as HashMap) buildExceededDependency(dep.value, dep.key) }.toSortedSet() } private fun buildUndeclaredGroup(): MutableSet<Dependency> { return undeclared .map { coordinate -> Dependency(coordinate.groupId, coordinate.artifactId) }.toSortedSet() } private fun buildUnresolvedGroup(): MutableSet<DependencyUnresolved> { return unresolved .sortedWith { a, b -> compareKeys(keyOf(a.selector), keyOf(b.selector)) }.map { dep -> val stringWriter = StringWriter() dep.problem.printStackTrace(PrintWriter(stringWriter)) val message = stringWriter.toString() buildUnresolvedDependency(dep.selector, message) }.toSortedSet() as TreeSet<DependencyUnresolved> } private fun buildDependency( coordinate: Coordinate, key: Map<String, String> ): Dependency { return Dependency( group = key["group"], name = key["name"], version = coordinate.version, projectUrl = projectUrls[key], userReason = coordinate.userReason, ) } private fun buildExceededDependency( coordinate: Coordinate, key: Map<String, String> ): DependencyLatest { return DependencyLatest( group = key["group"], name = key["name"], version = coordinate.version, projectUrl = projectUrls[key], userReason = coordinate.userReason, latest = latestVersions[key]?.version.orEmpty(), ) } private fun buildUnresolvedDependency( selector: ModuleVersionSelector, message: String ): DependencyUnresolved { return DependencyUnresolved( group = selector.group, name = selector.name, version = currentVersions[keyOf(selector)]?.version, projectUrl = latestVersions[keyOf(selector)]?.version, // TODO not sure? userReason = currentVersions[keyOf(selector)]?.userReason, reason = message, ) } private fun buildOutdatedDependency( coordinate: Coordinate, key: Map<String, String> ): DependencyOutdated { val laterVersion = latestVersions[key]?.version val available = when (revision) { "milestone" -> VersionAvailable(milestone = laterVersion) "integration" -> VersionAvailable(integration = laterVersion) else -> VersionAvailable(release = laterVersion) } return DependencyOutdated( group = key["group"], name = key["name"], version = coordinate.version, projectUrl = projectUrls[key], userReason = coordinate.userReason, available = available, ) } companion object { private fun updateKey(existingKey: HashMap<String, String>) { val index = existingKey["name"]?.lastIndexOf("[") ?: -1 if (index == -1) { existingKey["name"] = existingKey["name"].orEmpty() } else { existingKey["name"] = existingKey["name"].orEmpty().substring(0, index) } } private fun buildObject( count: Int, currentGroup: DependenciesGroup<Dependency>, outdatedGroup: DependenciesGroup<DependencyOutdated>, exceededGroup: DependenciesGroup<DependencyLatest>, undeclaredGroup: DependenciesGroup<Dependency>, unresolvedGroup: DependenciesGroup<DependencyUnresolved>, gradleUpdateResults: GradleUpdateResults, ): Result { return Result( count = count, current = currentGroup, outdated = outdatedGroup, exceeded = exceededGroup, undeclared = undeclaredGroup, unresolved = unresolvedGroup, gradle = gradleUpdateResults ) } private fun <T : Dependency> buildDependenciesGroup(dependencies: MutableSet<T>): DependenciesGroup<T> { return DependenciesGroup<T>(dependencies.size, dependencies) } private fun sortByGroupAndName( dependencies: Map<Map<String, String>, Coordinate> ): Map<Map<String, String>, Coordinate> { return dependencies.toSortedMap { a, b -> compareKeys(a, b) } } /** Compares the dependency keys. */ private fun compareKeys(a: Map<String, String>, b: Map<String, String>): Int { return if (a["group"] == b["group"]) { a["name"].orEmpty().compareTo(b["name"].orEmpty()) } else { a["group"].orEmpty().compareTo(b["group"].orEmpty()) } } private fun keyOf(dependency: ModuleVersionSelector): Map<String, String> { return mapOf("group" to dependency.group, "name" to dependency.name) } } }
apache-2.0
ef6988097475ba2ab170b336dd2c80b6
36.528024
121
0.718755
4.957911
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/fcm/SpaceAvailableNotification.kt
1
2308
package se.barsk.park.fcm import android.content.Context import android.os.Handler import android.os.Looper import org.json.JSONObject import se.barsk.park.error.ErrorHandler import se.barsk.park.Injection import se.barsk.park.ParkApp import se.barsk.park.R /** * A space available notification that let's the user know that there is now free space * in the garage. * * Note: The app may or may not be running when this notification is shown. */ class SpaceAvailableNotification(context: Context, data: JSONObject) : Notification(context, data) { override val id = SpaceAvailableNotificationChannel.ID override val timeout: Long = 3 * 60 * 60 * 1000 // 3 hours private val freeSpots = data["free"] private val valid: Boolean init { valid = when (freeSpots) { null -> { ErrorHandler.raiseException("Invalid space available notification, free parameter missing") false } "0" -> { ErrorHandler.raiseException("Invalid space available notification, 0 spaces free") false } else -> true } } override fun show() { if (!valid) { return } val storageManager = Injection.provideStorageManager(context) if (!storageManager.onWaitList()) { // If we're not on the wait list but still get a notification discard it. // This may happen if the user signs out without internet connection while // on the wait list. If this happens we just ignore the notification. return } val title = context.getString(R.string.free_spots_notification_title, freeSpots) val body = context.getString(R.string.free_spots_notification_body) makeNotification(title, body) if (ParkApp.isRunning()) { // Update local wait list state (on the UI thread) if the app is running Handler(Looper.getMainLooper()).post { ParkApp.theUser.isOnWaitList = false } } else { // If the app is not running, update the persistent value instead so we have // the correct state when the app is started the next time. storageManager.setOnWaitList(false) } } }
mit
4f0acd3dab29c25d938019f6fdd547bd
35.078125
107
0.634315
4.681542
false
false
false
false
nick-rakoczy/Conductor
notifications-api/src/test/java/TestPlans.kt
1
1257
import com.google.gson.GsonBuilder import org.apache.logging.log4j.LogManager import org.junit.Test import spark.Spark import urn.conductor.Main import java.util.UUID class TestPlans { data class Notification(var text: String, var value: String) private val logger = LogManager.getLogger() @Test fun test() { val gson = GsonBuilder().create() val user = UUID.randomUUID().toString() val authToken = UUID.randomUUID().toString() val authHeader = com.google.common.net.HttpHeaders.AUTHORIZATION val message = UUID.randomUUID().toString() var callCount = 0 Spark.post("/webhook") { req, _ -> callCount++ val header = req.headers(authHeader) assert(header == "Bearer $authToken") val body = req.body() val note = gson.fromJson(body, Notification::class.java) assert(note.text == "Hello, $user!") assert(note.value == message) logger.info("Received notification [$body] from user-agent ${req.userAgent()}") } val options = arrayOf( "plugins=.", "file=./src/test/resources/webhook-test.xml", "user=$user", "message=$message", "port=${Spark.port()}", "authHeader=$authHeader", "authToken=$authToken" ) Main.Companion.main(options) assert(callCount == 1) Spark.stop() } }
gpl-3.0
1b077a48dfcd4f575c2e1c054a4ea073
23.192308
82
0.68576
3.443836
false
true
false
false
google/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLinesProvider.kt
1
2071
package org.jetbrains.plugins.notebooks.visualization import com.intellij.lang.Language import com.intellij.lang.LanguageExtension import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager private const val ID: String = "org.jetbrains.plugins.notebooks.notebookCellLinesProvider" interface NotebookCellLinesProvider : IntervalsGenerator { fun create(document: Document): NotebookCellLines companion object : LanguageExtension<NotebookCellLinesProvider>(ID) { private val key = Key.create<NotebookCellLinesProvider>(NotebookCellLinesProvider::class.java.name) fun install(editor: Editor): NotebookCellLinesProvider? { get(editor.document)?.let { return it } val language = getLanguage(editor) ?: return null val provider = forLanguage(language) ?: return null key.set(editor.document, provider) return provider } fun get(document: Document): NotebookCellLinesProvider? { return document.getUserData(key) } } } interface IntervalsGenerator { fun makeIntervals(document: Document): List<NotebookCellLines.Interval> } open class NonIncrementalCellLinesProvider protected constructor(private val intervalsGenerator: IntervalsGenerator) : NotebookCellLinesProvider, IntervalsGenerator { override fun create(document: Document): NotebookCellLines = NonIncrementalCellLines.get(document, intervalsGenerator) /* If NotebookCellLines doesn't exist, parse document once and don't create NotebookCellLines instance */ override fun makeIntervals(document: Document): List<NotebookCellLines.Interval> = NonIncrementalCellLines.getOrNull(document)?.intervals ?: intervalsGenerator.makeIntervals(document) } internal fun getLanguage(editor: Editor): Language? = editor .project ?.let(PsiDocumentManager::getInstance) ?.getPsiFile(editor.document) ?.language val Editor.notebookCellLinesProvider: NotebookCellLinesProvider? get() = NotebookCellLinesProvider.install(this)
apache-2.0
71fdc565ccf72e2ecf251e86b7f8944c
38.09434
166
0.791888
5.038929
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt
3
33953
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil import com.intellij.codeInspection.* import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection import com.intellij.codeInspection.ex.EntryPointsManager import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.codeInspection.ex.EntryPointsManagerImpl import com.intellij.openapi.application.invokeLater import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.PsiSearchHelper.SearchCostResult import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.DefinitionsScopedSearch import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.safeDelete.SafeDeleteHandler import com.intellij.util.Processor import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory import org.jetbrains.kotlin.idea.findUsages.handlers.KotlinFindClassUsagesHandler import org.jetbrains.kotlin.idea.intentions.isFinalizeMethod import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction import org.jetbrains.kotlin.idea.isMainFunction import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.search.findScriptsWithUsages import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators import org.jetbrains.kotlin.idea.search.usagesSearch.getClassNameForCompanionObject import org.jetbrains.kotlin.idea.search.usagesSearch.isDataClassProperty import org.jetbrains.kotlin.idea.util.hasActualsFor import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi import org.jetbrains.kotlin.resolve.isInlineClass import org.jetbrains.kotlin.resolve.isInlineClassType import org.jetbrains.kotlin.util.findCallableMemberBySignature import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import javax.swing.JComponent import javax.swing.JPanel import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class UnusedSymbolInspection : AbstractKotlinInspection() { companion object { private val javaInspection = UnusedDeclarationInspection() private val KOTLIN_ADDITIONAL_ANNOTATIONS = listOf("kotlin.test.*", "kotlin.js.JsExport") private fun KtDeclaration.hasKotlinAdditionalAnnotation() = this is KtNamedDeclaration && checkAnnotatedUsingPatterns(this, KOTLIN_ADDITIONAL_ANNOTATIONS) fun isEntryPoint(declaration: KtNamedDeclaration): Boolean = isEntryPoint(declaration, lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) }) private fun isEntryPoint(declaration: KtNamedDeclaration, isCheapEnough: Lazy<SearchCostResult>): Boolean { if (declaration.hasKotlinAdditionalAnnotation()) return true if (declaration is KtClass && declaration.declarations.any { it.hasKotlinAdditionalAnnotation() }) return true // Some of the main-function-cases are covered by 'javaInspection.isEntryPoint(lightElement)' call // but not all of them: light method for parameterless main still points to parameterless name // that is not an actual entry point from Java language point of view if (declaration.isMainFunction()) return true val lightElement: PsiElement = when (declaration) { is KtClassOrObject -> declaration.toLightClass() is KtNamedFunction, is KtSecondaryConstructor -> LightClassUtil.getLightClassMethod(declaration as KtFunction) is KtProperty, is KtParameter -> { if (declaration is KtParameter && !declaration.hasValOrVar()) return false // we may handle only annotation parameters so far if (declaration is KtParameter && isAnnotationParameter(declaration)) { val lightAnnotationMethods = LightClassUtil.getLightClassPropertyMethods(declaration).toList() for (javaParameterPsi in lightAnnotationMethods) { if (javaInspection.isEntryPoint(javaParameterPsi)) { return true } } } // can't rely on light element, check annotation ourselves val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase return checkAnnotatedUsingPatterns( declaration, entryPointsManager.additionalAnnotations + entryPointsManager.ADDITIONAL_ANNOTATIONS ) } else -> return false } ?: return false if (isCheapEnough.value == TOO_MANY_OCCURRENCES) return false return javaInspection.isEntryPoint(lightElement) } private fun isAnnotationParameter(parameter: KtParameter): Boolean { val constructor = parameter.ownerFunction as? KtConstructor<*> ?: return false return constructor.containingClassOrObject?.isAnnotation() ?: false } private fun isCheapEnoughToSearchUsages(declaration: KtNamedDeclaration): SearchCostResult { val project = declaration.project val psiSearchHelper = PsiSearchHelper.getInstance(project) if (!findScriptsWithUsages(declaration) { DefaultScriptingSupport.getInstance(project).isLoadedFromCache(it) }) { // Not all script configuration are loaded; behave like it is used return TOO_MANY_OCCURRENCES } val useScope = psiSearchHelper.getUseScope(declaration) if (useScope is GlobalSearchScope) { var zeroOccurrences = true val list = listOf(declaration.name) + declarationAccessorNames(declaration) + listOfNotNull(declaration.getClassNameForCompanionObject()) for (name in list) { if (name == null) continue when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) { ZERO_OCCURRENCES -> { } // go on, check other names FEW_OCCURRENCES -> zeroOccurrences = false TOO_MANY_OCCURRENCES -> return TOO_MANY_OCCURRENCES // searching usages is too expensive; behave like it is used } } if (zeroOccurrences) return ZERO_OCCURRENCES } return FEW_OCCURRENCES } /** * returns list of declaration accessor names e.g. pair of getter/setter for property declaration * * note: could be more than declaration.getAccessorNames() * as declaration.getAccessorNames() relies on LightClasses and therefore some of them could be not available * (as not accessible outside of class) * * e.g.: private setter w/o body is not visible outside of class and could not be used */ private fun declarationAccessorNames(declaration: KtNamedDeclaration): List<String> = when (declaration) { is KtProperty -> listOfPropertyAccessorNames(declaration) is KtParameter -> listOfParameterAccessorNames(declaration) else -> emptyList() } fun listOfParameterAccessorNames(parameter: KtParameter): List<String> { val accessors = mutableListOf<String>() if (parameter.hasValOrVar()) { parameter.name?.let { accessors.add(JvmAbi.getterName(it)) if (parameter.isVarArg) accessors.add(JvmAbi.setterName(it)) } } return accessors } fun listOfPropertyAccessorNames(property: KtProperty): List<String> { val accessors = mutableListOf<String>() val propertyName = property.name ?: return accessors accessors.add(property.getter?.let { getCustomAccessorName(it) } ?: JvmAbi.getterName(propertyName)) if (property.isVar) accessors.add(property.setter?.let { getCustomAccessorName(it) } ?: JvmAbi.setterName(propertyName)) return accessors } /* If the property has 'JvmName' annotation at accessor it should be used instead */ private fun getCustomAccessorName(method: KtPropertyAccessor?): String? { val customJvmNameAnnotation = method?.annotationEntries?.firstOrNull { it.shortName?.asString() == "JvmName" } ?: return null return customJvmNameAnnotation.findDescendantOfType<KtStringTemplateEntry>()?.text } private fun KtProperty.isSerializationImplicitlyUsedField(): Boolean { val ownerObject = getNonStrictParentOfType<KtClassOrObject>() if (ownerObject is KtObjectDeclaration && ownerObject.isCompanion()) { val lightClass = ownerObject.getNonStrictParentOfType<KtClass>()?.toLightClass() ?: return false return lightClass.fields.any { it.name == name && HighlightUtil.isSerializationImplicitlyUsedField(it) } } return false } private fun KtNamedFunction.isSerializationImplicitlyUsedMethod(): Boolean = toLightMethods().any { JavaHighlightUtil.isSerializationRelatedMethod(it, it.containingClass) } // variation of IDEA's AnnotationUtil.checkAnnotatedUsingPatterns() fun checkAnnotatedUsingPatterns( declaration: KtNamedDeclaration, annotationPatterns: Collection<String> ): Boolean { if (declaration.annotationEntries.isEmpty()) return false val context = declaration.analyze() val annotationsPresent = declaration.annotationEntries.mapNotNull { context[BindingContext.ANNOTATION, it]?.fqName?.asString() } if (annotationsPresent.isEmpty()) return false for (pattern in annotationPatterns) { val hasAnnotation = if (pattern.endsWith(".*")) { annotationsPresent.any { it.startsWith(pattern.dropLast(1)) } } else { pattern in annotationsPresent } if (hasAnnotation) return true } return false } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return namedDeclarationVisitor(fun(declaration) { ProgressManager.checkCanceled() val message = declaration.describe()?.let { KotlinIdeaCompletionBundle.message("inspection.message.never.used", it) } ?: return if (!RootKindFilter.projectSources.matches(declaration)) return // Simple PSI-based checks if (declaration is KtObjectDeclaration && declaration.isCompanion()) return // never mark companion object as unused (there are too many reasons it can be needed for) if (declaration is KtSecondaryConstructor && declaration.containingClass()?.isEnum() == true) return if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return if (declaration is KtProperty && declaration.isLocal) return if (declaration is KtParameter && (declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar()) ) return // More expensive, resolve-based checks val descriptor = declaration.resolveToDescriptorIfAny() ?: return if (declaration.languageVersionSettings.explicitApiEnabled && (descriptor as? DeclarationDescriptorWithVisibility)?.isEffectivelyPublicApi == true) { return } if (descriptor is FunctionDescriptor && descriptor.isOperator) return val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) } if (isEntryPoint(declaration, isCheapEnough)) return if (declaration.isFinalizeMethod(descriptor)) return if (declaration is KtProperty && declaration.isSerializationImplicitlyUsedField()) return if (declaration is KtNamedFunction && declaration.isSerializationImplicitlyUsedMethod()) return // properties can be referred by component1/component2, which is too expensive to search, don't mark them as unused if (declaration is KtParameter && (declaration.isDataClassProperty() || declaration.isInlineClassProperty())) return // experimental annotations if (descriptor is ClassDescriptor && descriptor.kind == ClassKind.ANNOTATION_CLASS) { val fqName = descriptor.fqNameSafe.asString() val languageVersionSettings = declaration.languageVersionSettings if (fqName in languageVersionSettings.getFlag(AnalysisFlags.optIn)) return } // Main checks: finding reference usages && text usages if (hasNonTrivialUsages(declaration, isCheapEnough, descriptor)) return if (declaration is KtClassOrObject && classOrObjectHasTextUsages(declaration)) return val psiElement = declaration.nameIdentifier ?: (declaration as? KtConstructor<*>)?.getConstructorKeyword() ?: return val problemDescriptor = holder.manager.createProblemDescriptor( psiElement, null, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, *createQuickFixes(declaration).toTypedArray() ) holder.registerProblem(problemDescriptor) }) } private fun classOrObjectHasTextUsages(classOrObject: KtClassOrObject): Boolean { var hasTextUsages = false // Finding text usages if (classOrObject.useScope is GlobalSearchScope) { val findClassUsagesHandler = KotlinFindClassUsagesHandler(classOrObject, KotlinFindUsagesHandlerFactory(classOrObject.project)) findClassUsagesHandler.processUsagesInText( classOrObject, { hasTextUsages = true; false }, GlobalSearchScope.projectScope(classOrObject.project) ) } return hasTextUsages } private fun hasNonTrivialUsages(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor? = null): Boolean { val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) } return hasNonTrivialUsages(declaration, isCheapEnough, descriptor) } private fun hasNonTrivialUsages( declaration: KtNamedDeclaration, enoughToSearchUsages: Lazy<SearchCostResult>, descriptor: DeclarationDescriptor? = null ): Boolean { val project = declaration.project val psiSearchHelper = PsiSearchHelper.getInstance(project) val useScope = psiSearchHelper.getUseScope(declaration) val restrictedScope = if (useScope is GlobalSearchScope) { val zeroOccurrences = when (enoughToSearchUsages.value) { ZERO_OCCURRENCES -> true FEW_OCCURRENCES -> false TOO_MANY_OCCURRENCES -> return true // searching usages is too expensive; behave like it is used } if (zeroOccurrences && !declaration.hasActualModifier()) { if (declaration is KtObjectDeclaration && declaration.isCompanion()) { // go on: companion object can be used only in containing class } else { return false } } if (declaration.hasActualModifier()) { KotlinSourceFilterScope.projectSources(project.projectScope(), project) } else { KotlinSourceFilterScope.projectSources(useScope, project) } } else useScope if (declaration is KtTypeParameter) { val containingClass = declaration.containingClass() if (containingClass != null) { val isOpenClass = containingClass.isInterface() || containingClass.hasModifier(KtTokens.ABSTRACT_KEYWORD) || containingClass.hasModifier(KtTokens.SEALED_KEYWORD) || containingClass.hasModifier(KtTokens.OPEN_KEYWORD) if (isOpenClass && hasOverrides(containingClass, restrictedScope)) return true val containingClassSearchScope = GlobalSearchScope.projectScope(project) val isRequiredToCallFunction = ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, containingClassSearchScope)).any { ref -> val userType = ref.element.parent as? KtUserType ?: return@any false val typeArguments = userType.typeArguments if (typeArguments.isEmpty()) return@any false val parameter = userType.getStrictParentOfType<KtParameter>() ?: return@any false val callableDeclaration = parameter.getStrictParentOfType<KtCallableDeclaration>()?.let { if (it !is KtNamedFunction) it.containingClass() else it } ?: return@any false val typeParameters = callableDeclaration.typeParameters.map { it.name } if (typeParameters.isEmpty()) return@any false if (typeArguments.none { it.text in typeParameters }) return@any false ReferencesSearch.search(KotlinReferencesSearchParameters(callableDeclaration, containingClassSearchScope)).any { val callElement = it.element.parent as? KtCallElement callElement != null && callElement.typeArgumentList == null } } if (isRequiredToCallFunction) return true } } return (declaration is KtObjectDeclaration && declaration.isCompanion() && declaration.body?.declarations?.isNotEmpty() == true) || hasReferences(declaration, descriptor, restrictedScope) || hasOverrides(declaration, restrictedScope) || hasFakeOverrides(declaration, restrictedScope) || hasPlatformImplementations(declaration, descriptor) } private fun checkDeclaration(declaration: KtNamedDeclaration, importedDeclaration: KtNamedDeclaration): Boolean = declaration !in importedDeclaration.parentsWithSelf && !hasNonTrivialUsages(importedDeclaration) private val KtNamedDeclaration.isObjectOrEnum: Boolean get() = this is KtObjectDeclaration || this is KtClass && isEnum() private fun checkReference(ref: PsiReference, declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { ProgressManager.checkCanceled() if (declaration.isAncestor(ref.element)) return true // usages inside element's declaration are not counted if (ref.element.parent is KtValueArgumentName) return true // usage of parameter in form of named argument is not counted val import = ref.element.getParentOfType<KtImportDirective>(false) if (import != null) { if (import.aliasName != null && import.aliasName != declaration.name) { return false } // check if we import member(s) from object / nested object / enum and search for their usages val originalDeclaration = (descriptor as? TypeAliasDescriptor)?.classDescriptor?.findPsi() as? KtNamedDeclaration if (declaration is KtClassOrObject || originalDeclaration is KtClassOrObject) { if (import.isAllUnder) { val importedFrom = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtClassOrObject ?: return true return importedFrom.declarations.none { it is KtNamedDeclaration && hasNonTrivialUsages(it) } } else { if (import.importedFqName != declaration.fqName) { val importedDeclaration = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtNamedDeclaration ?: return true if (declaration.isObjectOrEnum || importedDeclaration.containingClassOrObject is KtObjectDeclaration) return checkDeclaration( declaration, importedDeclaration ) if (originalDeclaration?.isObjectOrEnum == true) return checkDeclaration( originalDeclaration, importedDeclaration ) // check type alias if (importedDeclaration.fqName == declaration.fqName) return true } } } return true } return false } private fun hasReferences( declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?, useScope: SearchScope ): Boolean { fun checkReference(ref: PsiReference): Boolean = checkReference(ref, declaration, descriptor) val searchOptions = KotlinReferencesSearchOptions(acceptCallableOverrides = declaration.hasActualModifier()) val searchParameters = KotlinReferencesSearchParameters( declaration, useScope, kotlinOptions = searchOptions ) val referenceUsed: Boolean by lazy { !ReferencesSearch.search(searchParameters).forEach(Processor { checkReference(it) }) } if (descriptor is FunctionDescriptor && DescriptorUtils.findJvmNameAnnotation(descriptor) != null) { if (referenceUsed) return true } if (declaration is KtSecondaryConstructor) { val containingClass = declaration.containingClass() if (containingClass != null && ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, useScope)).any { it.element.getStrictParentOfType<KtTypeAlias>() != null }) return true } if (declaration is KtCallableDeclaration && declaration.canBeHandledByLightMethods(descriptor)) { val lightMethods = declaration.toLightMethods() if (lightMethods.isNotEmpty()) { val lightMethodsUsed = lightMethods.any { method -> !MethodReferencesSearch.search(method).forEach(Processor { checkReference(it) }) } if (lightMethodsUsed) return true if (!declaration.hasActualModifier()) return false } } if (declaration is KtEnumEntry) { val enumClass = declaration.containingClass()?.takeIf { it.isEnum() } if (hasBuiltInEnumFunctionReference(enumClass, useScope)) return true } return referenceUsed || checkPrivateDeclaration(declaration, descriptor) } private fun hasBuiltInEnumFunctionReference(enumClass: KtClass?, useScope: SearchScope): Boolean { if (enumClass == null) return false return enumClass.anyDescendantOfType(KtExpression::isReferenceToBuiltInEnumFunction) || ReferencesSearch.search(KotlinReferencesSearchParameters(enumClass, useScope)).any(::hasBuiltInEnumFunctionReference) } private fun hasBuiltInEnumFunctionReference(reference: PsiReference): Boolean { val parent = reference.element.getParentOfTypes( true, KtTypeReference::class.java, KtQualifiedExpression::class.java, KtCallableReferenceExpression::class.java ) ?: return false return parent.isReferenceToBuiltInEnumFunction() } private fun checkPrivateDeclaration(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { if (descriptor == null || !declaration.isPrivateNestedClassOrObject) return false val set = hashSetOf<KtSimpleNameExpression>() declaration.containingKtFile.importList?.acceptChildren(simpleNameExpressionRecursiveVisitor { set += it }) return set.mapNotNull { it.referenceExpression() } .filter { descriptor in it.resolveMainReferenceToDescriptors() } .any { !checkReference(it.mainReference, declaration, descriptor) } } private fun KtCallableDeclaration.canBeHandledByLightMethods(descriptor: DeclarationDescriptor?): Boolean { return when { descriptor is ConstructorDescriptor -> { val classDescriptor = descriptor.constructedClass !classDescriptor.isInlineClass() && classDescriptor.visibility != DescriptorVisibilities.LOCAL } hasModifier(KtTokens.INTERNAL_KEYWORD) -> false descriptor !is FunctionDescriptor -> true else -> !descriptor.hasInlineClassParameters() } } private fun FunctionDescriptor.hasInlineClassParameters(): Boolean { return when { dispatchReceiverParameter?.type?.isInlineClassType() == true -> true extensionReceiverParameter?.type?.isInlineClassType() == true -> true else -> valueParameters.any { it.type.isInlineClassType() } } } private fun hasOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean = DefinitionsScopedSearch.search(declaration, useScope).findFirst() != null private fun hasFakeOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean { val ownerClass = declaration.containingClassOrObject as? KtClass ?: return false if (!ownerClass.isInheritable()) return false val descriptor = declaration.toDescriptor() as? CallableMemberDescriptor ?: return false if (descriptor.modality == Modality.ABSTRACT) return false val lightMethods = declaration.toLightMethods() return DefinitionsScopedSearch.search(ownerClass, useScope).any { element: PsiElement -> when (element) { is KtLightClass -> { val memberBySignature = (element.kotlinOrigin?.toDescriptor() as? ClassDescriptor)?.findCallableMemberBySignature(descriptor) memberBySignature != null && !memberBySignature.kind.isReal && memberBySignature.overriddenDescriptors.any { it != descriptor } } is PsiClass -> lightMethods.any { lightMethod -> val sameMethods = element.findMethodsBySignature(lightMethod, true) sameMethods.all { it.containingClass != element } && sameMethods.any { it.containingClass != lightMethod.containingClass } } else -> false } } } private fun hasPlatformImplementations(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { if (!declaration.hasExpectModifier()) return false if (descriptor !is MemberDescriptor) return false val commonModuleDescriptor = declaration.containingKtFile.findModuleDescriptor() // TODO: Check if 'allImplementingDescriptors' should be used instead! return commonModuleDescriptor.implementingDescriptors.any { it.hasActualsFor(descriptor) } || commonModuleDescriptor.hasActualsFor(descriptor) } override fun createOptionsPanel(): JComponent = JPanel(GridBagLayout()).apply { add( EntryPointsManagerImpl.createConfigureAnnotationsButton(), GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0) ) } private fun createQuickFixes(declaration: KtNamedDeclaration): List<LocalQuickFix> { val list = ArrayList<LocalQuickFix>() list.add(SafeDeleteFix(declaration)) for (annotationEntry in declaration.annotationEntries) { val resolvedName = annotationEntry.resolveToDescriptorIfAny() ?: continue val fqName = resolvedName.fqName?.asString() ?: continue // checks taken from com.intellij.codeInspection.util.SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes if (fqName.startsWith("kotlin.") || fqName.startsWith("java.") || fqName.startsWith("javax.") || fqName.startsWith("org.jetbrains.annotations.") ) continue val intentionAction = createAddToDependencyInjectionAnnotationsFix(declaration.project, fqName) list.add(IntentionWrapper(intentionAction)) } return list } private fun KtParameter.isInlineClassProperty(): Boolean { if (!hasValOrVar()) return false return containingClassOrObject?.hasModifier(KtTokens.INLINE_KEYWORD) == true || containingClassOrObject?.hasModifier(KtTokens.VALUE_KEYWORD) == true } } class SafeDeleteFix(declaration: KtDeclaration) : LocalQuickFix { @Nls private val name: String = if (declaration is KtConstructor<*>) KotlinBundle.message("safe.delete.constructor") else QuickFixBundle.message("safe.delete.text", declaration.name) override fun getName() = name override fun getFamilyName() = QuickFixBundle.message("safe.delete.family") override fun startInWriteAction(): Boolean = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val declaration = descriptor.psiElement.getStrictParentOfType<KtDeclaration>() ?: return if (!FileModificationService.getInstance().prepareFileForWrite(declaration.containingFile)) return if (declaration is KtParameter && declaration.parent is KtParameterList && declaration.parent?.parent is KtFunction) { RemoveUnusedFunctionParameterFix(declaration).invoke(project, declaration.findExistingEditor(), declaration.containingKtFile) } else { val declarationPointer = declaration.createSmartPointer() invokeLater { declarationPointer.element?.let { safeDelete(project, it) } } } } } private fun safeDelete(project: Project, declaration: PsiElement) { SafeDeleteHandler.invoke(project, arrayOf(declaration), false) }
apache-2.0
d2bfb22399b32ab01c8c3d6990afdc7f
50.443939
178
0.674403
6.066286
false
false
false
false
google/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/When.kt
2
4024
// WITH_STDLIB fun simpleRange(x: Int) = when { x > 10 -> 10 <warning descr="Condition 'x > 15' is always false">x > 15</warning> -> 15 else -> 0 } @OptIn(ExperimentalStdlibApi::class) fun inRange(obj : Int) { when (obj) { in 0..<10 -> {} 10 -> {} <warning descr="'when' branch is never reachable">9</warning> -> {} } when (obj) { in 0 until 10 -> {} 10 -> {} <warning descr="'when' branch is never reachable">9</warning> -> {} } when (obj) { in 0..<10 -> {} !in 0..9 -> {} <warning descr="'when' branch is never reachable">20</warning> -> {} else -> {} } when (obj) { in 0 until 10 -> {} !in 0..9 -> {} <warning descr="'when' branch is never reachable">20</warning> -> {} else -> {} } if (obj > 0) { when (obj) { 3 -> {} 2 -> {} 1 -> {} <warning descr="'when' branch is never reachable">0</warning> -> {} } } } fun whenIs(obj : Any?) { when(obj) { is X -> {} is Y -> {} else -> { if (<warning descr="Condition 'obj is X' is always false">obj is X</warning>) {} } } if (obj is X) { when(obj) { <warning descr="[USELESS_IS_CHECK] Check for instance is always 'false'">is Y</warning> -> {} } } } fun lastBranchTrue(obj : Boolean, obj2 : Any) { when(obj) { true -> {} false -> {} } when(obj2) { is String -> {} is Int -> {} else -> return } when(obj2) { is String -> {} is Int -> {} else -> return } } fun lastBranchTrue2(obj2 : Any) { when(obj2) { is String -> {} is Int -> {} else -> return } when(obj2) { is String -> {} is Int -> {} else -> return } } fun suppressSimilarTests2(a: Boolean, b: Boolean) { when { a && b -> {} a && !b -> {} !a && b -> {} else -> {} } } fun suppressSimilarTests3(a: Boolean, b: Boolean, c: Boolean) { when { a && b && c -> {} a && b && !c -> {} a && !b && c -> {} a && !b && !c -> {} } } fun unboxBoolean(obj : Boolean?) { when(obj) { true -> {} false -> {} null -> {} } } fun unboxAny(obj : Any) { when(obj) { 0 -> {} true -> {} } } fun returnFromWhen(x: Int): Unit { when { x > 10 -> return x < 0 -> return } if (<warning descr="Condition 'x == 11' is always false">x == 11</warning>) {} } fun throwBranch(x: Int) { when(x) { 0 -> {} 1 -> {} 2 -> return 3 -> {} } when(x) { 0 -> {} 1 -> {} <warning descr="'when' branch is never reachable">2</warning> -> throw Exception() 3 -> {} } when { x == 0 -> {} x == 1 -> {} <warning descr="Condition 'x == 2' is always false">x == 2</warning> -> throw Exception() x == 3 -> {} } } class X {} class Y {} fun test3(i: Int): Int { val r = when (i) { 0 -> "0" 1 -> "1" else -> error(0) } val l = when (i) { 0 -> "0" 1 -> "1" <warning descr="'when' branch is never reachable">2</warning> -> "2" else -> error(0) } val l1 = when (i) { 0 -> "0" 1, <warning descr="'when' branch is never reachable">2</warning> -> "1" <warning descr="'when' branch is never reachable">3</warning>, <warning descr="'when' branch is never reachable">4</warning>, <warning descr="'when' branch is never reachable">5</warning> -> "2" else -> error(0) } val l2 = when(1) { <warning descr="'when' branch is never reachable">0</warning> -> "0" 1 -> "1" <warning descr="'when' branch is never reachable">2</warning> -> "2" else -> "3" } return (r + l + l1 + l2).length }
apache-2.0
5bfadf12e3a82566d0bad370d0fdd315
22.816568
202
0.433648
3.505226
false
false
false
false
mikepenz/Storyblok-Android-SDK
library/src/main/java/com/mikepenz/storyblok/model/Entity.kt
1
888
package com.mikepenz.storyblok.model import org.json.JSONObject /** * Created by mikepenz on 14/04/2017. */ open class Entity(story: JSONObject) { var id: Long = 0 private set var name: String? = null private set var uuid: String? = null private set var slug: String? = null private set var isStartpage: Boolean = false private set init { if (story.has("name")) { this.name = story.optString("name") } if (story.has("id")) { this.id = story.optLong("id") } if (story.has("uuid")) { this.uuid = story.optString("uuid") } if (story.has("slug")) { this.slug = story.optString("slug") } if (story.has("is_startpage")) { this.isStartpage = story.optBoolean("is_startpage") } } }
apache-2.0
71d4b1e57b2018e75dbd11b074b62451
22.368421
63
0.525901
3.86087
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/latex/js_interface/ModelViewerInterface.kt
2
1105
package org.stepik.android.view.latex.js_interface import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.webkit.JavascriptInterface import android.widget.Toast import org.stepic.droid.R class ModelViewerInterface(private val context: Context) { companion object { private const val SCENE_VIEWER_BASE_URL = "https://arvr.google.com/scene-viewer/1.0?file=" const val MODEL_VIEWER_INTERFACE = "ModelViewerInterface" } @JavascriptInterface fun handleARModel(url: String) { val sceneViewerIntent = Intent(Intent.ACTION_VIEW) sceneViewerIntent.data = Uri.parse("$SCENE_VIEWER_BASE_URL$url") sceneViewerIntent.setPackage("com.google.android.googlequicksearchbox") sceneViewerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) try { context.startActivity(sceneViewerIntent) } catch (e: ActivityNotFoundException) { Toast.makeText(context, R.string.ar_not_supported_alert, Toast.LENGTH_SHORT).show() } } }
apache-2.0
a92e23d6d9ff61233e19180ac5fb31c0
37.137931
98
0.732127
4.185606
false
false
false
false
neo4j-graphql/neo4j-graphql
src/main/kotlin/org/neo4j/graphql/GraphSchemaScanner.kt
1
6386
package org.neo4j.graphql import org.neo4j.graphdb.Direction import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.graphdb.Label import org.neo4j.graphdb.Node import org.neo4j.helpers.collection.Iterators import org.neo4j.kernel.impl.core.EmbeddedProxySPI import org.neo4j.kernel.impl.core.GraphProperties import org.neo4j.kernel.internal.GraphDatabaseAPI import java.util.* class GraphSchemaScanner { companion object { fun fieldName(type: String) : String = type.split("_").mapIndexed { i, s -> if (i==0) s.toLowerCase() else s.toLowerCase().capitalize() }.joinToString("") internal val allTypes = LinkedHashMap<String, MetaData>() internal var schema : String? = null val IDL_PROPERTY = "graphql.idl" val IDL_UPDATE_PROPERTY = "graphql.idl.update" val DENSE_NODE = 50 @JvmStatic fun from(db: GraphDatabaseService, label: Label): MetaData { val metaData = MetaData(label.name()) inspectIndexes(metaData, db, label) sampleNodes(metaData, db, label) return metaData } fun storeIdl(db: GraphDatabaseService, schema: String) : Map<String, MetaData> { val metaDatas = IDLParser.parse(schema) val tx = db.beginTx() try { graphProperties(db).let { it.setProperty(IDL_PROPERTY, schema) it.setProperty(IDL_UPDATE_PROPERTY, System.currentTimeMillis()) } tx.success() return metaDatas } finally { tx.close() GraphSchema.reset() } } private fun graphProperties(db: GraphDatabaseService): GraphProperties { val nodeManager = (db as (GraphDatabaseAPI)).dependencyResolver.resolveDependency(EmbeddedProxySPI::class.java) val props = nodeManager.newGraphPropertiesProxy() return props } fun deleteIdl(db: GraphDatabaseService) { val tx = db.beginTx() try { val props = graphProperties(db) if (props.hasProperty(IDL_PROPERTY)) { props.removeProperty(IDL_PROPERTY) props.setProperty(IDL_UPDATE_PROPERTY, System.currentTimeMillis()) } tx.success() } finally { tx.close() } } fun readIdlMetadata(db: GraphDatabaseService) = readIdl(db)?.let { IDLParser.parse(it) } fun readIdl(db: GraphDatabaseService) : String? { val tx = db.beginTx() try { val schema = graphProperties(db).getProperty(IDL_PROPERTY, null) as String? tx.success() return schema } finally { tx.close() } } fun readIdlUpdate(db: GraphDatabaseService) : Long { val tx = db.beginTx() try { val update = graphProperties(db).getProperty(IDL_UPDATE_PROPERTY, 0L) as Long tx.success() return update } finally { tx.close() } } fun databaseSchema(db: GraphDatabaseService) { allTypes.clear() schema = readIdl(db) val idlMetaData = readIdlMetadata(db) if (idlMetaData != null) { allTypes.putAll(idlMetaData) } if (allTypes.isEmpty()) { allTypes.putAll(sampleDataBase(db)) } } fun allTypes(): Map<String, MetaData> = allTypes fun allMetaDatas() = allTypes.values fun getMetaData(type: String): MetaData? { return allTypes[type] } private fun inspectIndexes(md: MetaData, db: GraphDatabaseService, label: Label) { for (index in db.schema().getIndexes(label)) { for (s in index.propertyKeys) { if (index.isConstraintIndex) md.addIdProperty(s) md.addIndexedProperty(s) } } } private fun sampleDataBase(db: GraphDatabaseService): Map<String, MetaData> { val tx = db.beginTx() try { val result = db.allLabels.associate { label -> label.name() to from(db,label) } tx.success() return result } finally { tx.close() } } private fun sampleNodes(md: MetaData, db: GraphDatabaseService, label: Label) { var count = 10 val nodes = db.findNodes(label) while (nodes.hasNext() && count-- > 0) { val node = nodes.next() for (l in node.labels) md.addLabel(l.name()) node.allProperties.forEach { k, v -> md.addProperty(k, v.javaClass) } sampleRelationships(md, node) } } private fun sampleRelationships(md: MetaData, node: Node) { val dense = node.degree > DENSE_NODE for (type in node.relationshipTypes) { val itOut = node.getRelationships(Direction.OUTGOING, type).iterator() val out = Iterators.firstOrNull(itOut) val typeName = type.name() val fieldName = fieldName(typeName) // todo handle end-label if (out != null) { if (!dense || node.getDegree(type, Direction.OUTGOING) < DENSE_NODE) { labelsFor(out.endNode) { label -> md.mergeRelationship(typeName, fieldName,label,true,itOut.hasNext(),null,0) } } } val itIn = node.getRelationships(Direction.INCOMING, type).iterator() val `in` = Iterators.firstOrNull(itIn) if (`in` != null) { if (!dense || node.getDegree(type, Direction.INCOMING) < DENSE_NODE) { labelsFor(`in`.startNode) { label -> md.mergeRelationship(typeName, fieldName,label,false,itIn.hasNext(),null,0) } } } } } private fun labelsFor(node: Node, consumer: (String) -> Unit) { for (label in node.labels) { consumer.invoke(label.name()) } } } }
apache-2.0
047972c878d747f3d694324ea6b64486
36.786982
163
0.540871
4.70944
false
false
false
false
fboldog/anko
anko/library/static/commons/src/Async.kt
2
6770
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package org.jetbrains.anko import android.app.Activity import android.app.Fragment import android.content.Context import android.os.Handler import android.os.Looper import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.Future /** * Execute [f] on the application UI thread. */ fun Context.runOnUiThread(f: Context.() -> Unit) { if (ContextHelper.mainThread == Thread.currentThread()) f() else ContextHelper.handler.post { f() } } /** * Execute [f] on the application UI thread. */ inline fun Fragment.runOnUiThread(crossinline f: () -> Unit) { activity?.runOnUiThread { f() } } class AnkoAsyncContext<T>(val weakRef: WeakReference<T>) /** * Execute [f] on the application UI thread. * If the [doAsync] receiver still exists (was not collected by GC), * [f] gets it as a parameter ([f] gets null if the receiver does not exist anymore). */ fun <T> AnkoAsyncContext<T>.onComplete(f: (T?) -> Unit) { val ref = weakRef.get() if (ContextHelper.mainThread == Thread.currentThread()) { f(ref) } else { ContextHelper.handler.post { f(ref) } } } /** * Execute [f] on the application UI thread. * [doAsync] receiver will be passed to [f]. * If the receiver does not exist anymore (it was collected by GC), [f] will not be executed. */ fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit): Boolean { val ref = weakRef.get() ?: return false if (ContextHelper.mainThread == Thread.currentThread()) { f(ref) } else { ContextHelper.handler.post { f(ref) } } return true } /** * Execute [f] on the application UI thread if the underlying [Activity] still exists and is not finished. * The receiver [Activity] will be passed to [f]. * If it is not exist anymore or if it was finished, [f] will not be called. */ fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit): Boolean { val activity = weakRef.get() ?: return false if (activity.isFinishing) return false activity.runOnUiThread { f(activity) } return true } fun <T: Activity> AnkoAsyncContext<T>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean { val activity = weakRef.get() ?: return false if (activity.isFinishing) return false activity.runOnUiThread { activity.f(activity) } return true } @JvmName("activityContextUiThread") fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThread(f: (T) -> Unit): Boolean { val activity = weakRef.get()?.owner ?: return false if (activity.isFinishing) return false activity.runOnUiThread { f(activity) } return true } @JvmName("activityContextUiThreadWithContext") fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean { val activity = weakRef.get()?.owner ?: return false if (activity.isFinishing) return false activity.runOnUiThread { activity.f(activity) } return true } fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit): Boolean { val fragment = weakRef.get() ?: return false if (fragment.isDetached) return false val activity = fragment.activity ?: return false activity.runOnUiThread { f(fragment) } return true } fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThreadWithContext(f: Context.(T) -> Unit): Boolean { val fragment = weakRef.get() ?: return false if (fragment.isDetached) return false val activity = fragment.activity ?: return false activity.runOnUiThread { activity.f(fragment) } return true } private val crashLogger = { throwable : Throwable -> throwable.printStackTrace() } /** * Execute [task] asynchronously. * * @param exceptionHandler optional exception handler. * If defined, any exceptions thrown inside [task] will be passed to it. If not, exceptions will be ignored. * @param task the code to execute asynchronously. */ fun <T> T.doAsync( exceptionHandler: ((Throwable) -> Unit)? = crashLogger, task: AnkoAsyncContext<T>.() -> Unit ): Future<Unit> { val context = AnkoAsyncContext(WeakReference(this)) return BackgroundExecutor.submit { return@submit try { context.task() } catch (thr: Throwable) { val result = exceptionHandler?.invoke(thr) if (result != null) { result } else { Unit } } } } fun <T> T.doAsync( exceptionHandler: ((Throwable) -> Unit)? = crashLogger, executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> Unit ): Future<Unit> { val context = AnkoAsyncContext(WeakReference(this)) return executorService.submit<Unit> { try { context.task() } catch (thr: Throwable) { exceptionHandler?.invoke(thr) } } } fun <T, R> T.doAsyncResult( exceptionHandler: ((Throwable) -> Unit)? = crashLogger, task: AnkoAsyncContext<T>.() -> R ): Future<R> { val context = AnkoAsyncContext(WeakReference(this)) return BackgroundExecutor.submit { try { context.task() } catch (thr: Throwable) { exceptionHandler?.invoke(thr) throw thr } } } fun <T, R> T.doAsyncResult( exceptionHandler: ((Throwable) -> Unit)? = crashLogger, executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> R ): Future<R> { val context = AnkoAsyncContext(WeakReference(this)) return executorService.submit<R> { try { context.task() } catch (thr: Throwable) { exceptionHandler?.invoke(thr) throw thr } } } internal object BackgroundExecutor { var executor: ExecutorService = Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors()) fun <T> submit(task: () -> T): Future<T> { return executor.submit(task) } } private object ContextHelper { val handler = Handler(Looper.getMainLooper()) val mainThread: Thread = Looper.getMainLooper().thread }
apache-2.0
6dbd320b2337516171a509cd6f75a22f
31.085308
113
0.664697
4.186766
false
false
false
false
EGF2/android-client
framework/src/main/kotlin/com/eigengraph/egf2/framework/EGF2AuthApi.kt
1
4355
package com.eigengraph.egf2.framework import android.util.Log import com.eigengraph.egf2.framework.util.HttpHeaderInterceptor import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonObject import retrofit2.Response import rx.Observable import rx.schedulers.Schedulers data class RegisterModel(@JvmField val first_name: String, @JvmField val last_name: String, @JvmField val email: String, @JvmField val date_of_birth: String, @JvmField val password: String) data class LoginModel(@JvmField val email: String, @JvmField val password: String) data class ResetPasswordModel(@JvmField val reset_token: String, @JvmField val new_password: String) data class ChangePasswordModel(@JvmField val old_password: String, @JvmField val new_password: String) data class TokenModel(@JvmField val token: String) internal class EGF2AuthApi : EGF2Api() { private var service: EGF2AuthService init { Log.d("EGF2Api", "EGF2AuthApi init") val restAdapter = getRestAdapterBuilder() val restClient = getRestClientBuilder() restClient.addInterceptor(HttpHeaderInterceptor(baseUrl.replace("https://", "").replace("http://", "").replace("/", ""), { EGF2Api.getHeagers() })) if (EGF2.debugMode) restClient.addInterceptor(interceptor) restAdapter.baseUrl(baseUrl + prefix) restAdapter.client(restClient.build()) service = restAdapter.build().create(EGF2AuthService::class.java) Log.d("EGF2Api", "EGF2AuthApi init") } internal fun register(body: RegisterModel): Observable<String> = service.register(body) .flatMap { if (it.isSuccessful) { val token = it.body().token addHeader("Authorization", "Bearer " + token) Observable.just(token) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun login(body: LoginModel): Observable<String> = service.login(body) .flatMap { if (it.isSuccessful) { val token = it.body().token addHeader("Authorization", "Bearer " + token) Observable.just(token) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun verifyEmail(token: String): Observable<Any> = service.verifyEmail(token) .flatMap { if (it.isSuccessful) { Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun logout(): Observable<Any> = service.logout() .flatMap { if (it.isSuccessful) { removeHeader("Authorization") Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun forgotPassword(email: String): Observable<Any> = service.forgotPassword(email) .flatMap { if (it.isSuccessful) { Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun resetPassword(body: ResetPasswordModel): Observable<Any> = service.resetPassword(body) .flatMap { if (it.isSuccessful) { Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun changePassword(body: ChangePasswordModel): Observable<Any> = service.changePassword(body) .flatMap { if (it.isSuccessful) { Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) internal fun resendEmailVerification(): Observable<Any> = service.resendEmailVerification() .flatMap { if (it.isSuccessful) { Observable.just(it) } else { onError(it) } } .subscribeOn(Schedulers.io()) private fun onError(it: Response<*>): Observable<String>? = if (it.errorBody() != null) { val error: String = it.errorBody().string() val gson: Gson = Gson() val je: JsonElement = gson.fromJson(error, JsonElement::class.java) val jo: JsonObject = je.asJsonObject if (jo.has("code") && jo.has("message")) { Observable.error(Throwable(jo.get("code").asString + ": " + jo.get("message").asString)) } else { Observable.error(Throwable(error)) } } else { Observable.error(Throwable(it.message())) } }
mit
5b62e8760fe3ab76c8e85b05b186d9e2
27.103226
149
0.637658
3.75431
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/ide/customize/WelcomeWizardHelper.kt
1
2095
// 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.ide.customize import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.CodeInsightSettings import com.intellij.ide.WelcomeWizardUtil import com.intellij.ide.projectView.impl.ProjectViewSharedSettings import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.UISettings import com.intellij.lang.Language import com.intellij.openapi.util.registry.Registry internal class WelcomeWizardHelper { init { //Project View settings WelcomeWizardUtil.getAutoScrollToSource()?.let { ProjectViewSharedSettings.instance.autoscrollToSource = it } WelcomeWizardUtil.getManualOrder()?.let { ProjectViewSharedSettings.instance.manualOrder = it } //Debugger settings WelcomeWizardUtil.getDisableBreakpointsOnClick()?.let{ Registry.get("debugger.click.disable.breakpoints").setValue(it) } //Code insight settings WelcomeWizardUtil.getCompletionCaseSensitive()?.let { CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = it } //Code style settings WelcomeWizardUtil.getContinuationIndent()?.let { Language.getRegisteredLanguages() .map { CodeStyle.getDefaultSettings().getIndentOptions(it.associatedFileType) } .filter { it.CONTINUATION_INDENT_SIZE > WelcomeWizardUtil.getContinuationIndent() } .forEach { it.CONTINUATION_INDENT_SIZE = WelcomeWizardUtil.getContinuationIndent() } } //UI settings WelcomeWizardUtil.getTabsPlacement()?.let { UISettings.instance.editorTabPlacement = it } WelcomeWizardUtil.getAppearanceFontSize()?.let { val settings = UISettings.instance settings.overrideLafFonts = true UISettings.instance.fontSize = it } WelcomeWizardUtil.getAppearanceFontFace()?.let { val settings = UISettings.instance settings.overrideLafFonts = true settings.fontFace = it } LafManager.getInstance().updateUI() } }
apache-2.0
a7d0f5aca5e74c98fcbc6ebafd826f78
37.090909
140
0.751313
4.988095
false
false
false
false
bitsydarel/DBWeather
app/src/main/java/com/dbeginc/dbweather/utils/utility/ViewExtensions.kt
1
5686
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweather.utils.utility import android.content.Context import android.databinding.BindingAdapter import android.graphics.Color import android.os.Build import android.support.constraint.ConstraintLayout import android.support.design.widget.Snackbar import android.support.graphics.drawable.VectorDrawableCompat import android.support.v7.view.ContextThemeWrapper import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.dbeginc.dbweather.R import com.dbeginc.dbweather.utils.animations.widgets.RainFallView import com.dbeginc.dbweather.utils.animations.widgets.SnowFallView import com.dbeginc.dbweatherweather.viewmodels.WeatherLocationModel import com.dbeginc.dbweatherweather.viewmodels.toFormattedTime import com.github.clans.fab.FloatingActionButton import org.threeten.bp.Duration import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import java.util.* /** * Created by Darel Bitsy on 26/04/17. * * Custom Binder for my layout * */ fun View.show() { visibility = View.VISIBLE } fun View.remove() { visibility = View.GONE } fun View.hide() { visibility = View.INVISIBLE } fun View.toast(message: String = "", resId: Int = 0, duration: Int = Toast.LENGTH_SHORT) { if (resId == 0) Toast.makeText(context, message, duration).show() else Toast.makeText(context, resId, Toast.LENGTH_SHORT).show() } fun ViewGroup.snack(message: String = "", resId: Int = 0, duration: Int = Snackbar.LENGTH_LONG) { val snackbar = if (resId == 0) Snackbar.make(this, message, duration) else Snackbar.make(this, resId, duration) snackbar.show() } @BindingAdapter("articleTime") fun setArticleTime(textView: TextView, time: Long) { val zoneId = ZoneId.of(TimeZone.getDefault().id) val currentTime = Instant.now().atZone(zoneId) val zonedLastChange = ZonedDateTime.ofInstant( Instant.ofEpochMilli(time), zoneId ) val difference = Duration.between(zonedLastChange, currentTime) val publishDate: String = when { difference.toDays() > 0 -> textView.context.getString(R.string.published_at_days_ago, difference.toDays()) difference.toHours() > 0 -> textView.context.getString(R.string.published_at_hours_ago, difference.toHours()) difference.toMinutes() > 0 -> textView.context.getString(R.string.published_at_minutes_ago, difference.toMinutes()) else -> textView.context.getString(R.string.published_at_seconds_ago, difference.seconds) } textView.text = publishDate } @BindingAdapter("setUpdateTime") fun setWeatherUpdateTime(textView: TextView, time: Long) { textView.text = textView.context.getString(R.string.time_label).format(Locale.getDefault(), time.toFormattedTime(null)) } @BindingAdapter("setImage") fun setImageViewResource(imageView: ImageView, resource: Int) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { imageView.setImageDrawable(VectorDrawableCompat.create(imageView.resources, resource, imageView.context.theme)) } else imageView.setImageResource(resource) } fun ConstraintLayout.showRainingAnimation() { val snowAnimation = findViewById<SnowFallView>(SnowFallView.VIEW_ID) if (snowAnimation != null) removeView(snowAnimation) if (findViewById<RainFallView>(RainFallView.VIEW_ID) == null) addView(RainFallView(context), getLayoutParameter()) } fun ConstraintLayout.showSnowFallAnimation() { val rainAnimation = findViewById<RainFallView>(RainFallView.VIEW_ID) if (rainAnimation != null) removeView(rainAnimation) if (findViewById<SnowFallView>(SnowFallView.VIEW_ID) == null) addView(SnowFallView(context), getLayoutParameter()) } inline fun WeatherLocationModel.asFloatingActionButton(positions: ViewGroup.LayoutParams, context: Context, crossinline onClick: (WeatherLocationModel) -> Unit): FloatingActionButton { return FloatingActionButton(ContextThemeWrapper(context, R.style.AppTheme)).apply { labelText = fullName() colorNormal = Color.WHITE layoutParams = positions setColorPressedResId(R.color.colorSecondaryLight) setColorRippleResId(R.color.colorSecondaryLight) setImageResource(R.drawable.ic_city_location) setOnClickListener { onClick(this@asFloatingActionButton) } } } fun ViewGroup.removeWeatherAnimation() { removeView(findViewById<SnowFallView>(SnowFallView.VIEW_ID)) removeView(findViewById<RainFallView>(RainFallView.VIEW_ID)) } private fun getLayoutParameter(): ConstraintLayout.LayoutParams { val params = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT) params.apply { topToTop = ConstraintLayout.LayoutParams.PARENT_ID startToStart = ConstraintLayout.LayoutParams.PARENT_ID endToEnd = ConstraintLayout.LayoutParams.PARENT_ID bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID } return params }
gpl-3.0
9af2b5973221b3426d585d1750b0c60b
36.169935
184
0.759585
4.317388
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/delegatedProperty/topLevelVar.kt
5
355
import kotlin.reflect.KProperty class Delegate { var inner = 1 operator fun getValue(t: Any?, p: KProperty<*>): Int = inner operator fun setValue(t: Any?, p: KProperty<*>, i: Int) { inner = i } } var prop: Int by Delegate() fun box(): String { if(prop != 1) return "fail get" prop = 2 if (prop != 2) return "fail set" return "OK" }
apache-2.0
7a8fd1851c10fe9910bb56680e71be54
21.1875
73
0.616901
3.287037
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/specialBuiltins/collectionImpl.kt
2
2237
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE class A1 : MutableCollection<String> { override val size: Int get() = 56 override fun isEmpty(): Boolean { throw UnsupportedOperationException() } override fun contains(o: String): Boolean { throw UnsupportedOperationException() } override fun iterator(): MutableIterator<String> { throw UnsupportedOperationException() } override fun containsAll(c: Collection<String>): Boolean { throw UnsupportedOperationException() } override fun add(e: String): Boolean { throw UnsupportedOperationException() } override fun remove(o: String): Boolean { throw UnsupportedOperationException() } override fun addAll(c: Collection<String>): Boolean { throw UnsupportedOperationException() } override fun removeAll(c: Collection<String>): Boolean { throw UnsupportedOperationException() } override fun retainAll(c: Collection<String>): Boolean { throw UnsupportedOperationException() } override fun clear() { throw UnsupportedOperationException() } } class A2 : java.util.AbstractCollection<String>() { override val size: Int get() = 56 override fun iterator(): MutableIterator<String> { throw UnsupportedOperationException() } } class A3 : java.util.ArrayList<String>() { override val size: Int get() = 56 } interface Sized { val size: Int } class A4 : java.util.ArrayList<String>(), Sized { override val size: Int get() = 56 } fun check56(x: Collection<String>) { if (x.size != 56) throw java.lang.RuntimeException("fail ${x.size}") } fun box(): String { val a1 = A1() if (a1.size != 56) return "fail 1: ${a1.size}" check56(a1) val a2 = A2() if (a2.size != 56) return "fail 2: ${a2.size}" check56(a2) val a3 = A3() if (a3.size != 56) return "fail 3: ${a3.size}" check56(a3) val a4 = A4() if (a4.size != 56) return "fail 4: ${a4.size}" check56(a4) val sized: Sized = a4 if (sized.size != 56) return "fail 5: ${a4.size}" return "OK" }
apache-2.0
bdb6d2757667db5bdfe62ded72719c01
22.061856
72
0.625838
4.037906
false
false
false
false
exponent/exponent
packages/expo-dev-launcher/android/src/test/java/expo/modules/devlauncher/helpers/DevLauncherURLHelperTest.kt
2
1915
package expo.modules.devlauncher.helpers import android.net.Uri import com.google.common.truth.Truth import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) internal class DevLauncherURLHelperTest { @Test fun `tests changeUrlScheme`() { val expoUri = Uri.parse("exp://localhost:1999") val httpsUri = Uri.parse("https://google.com") val uriWithPath = Uri.parse("https://expo.io/path") val expoParsedUri = replaceEXPScheme(expoUri, "http") val httpsParsedUri = replaceEXPScheme(httpsUri, "http") val parsedUriWithPath = replaceEXPScheme(uriWithPath, "http") Truth.assertThat(expoParsedUri.scheme).isEqualTo("http") Truth.assertThat(expoParsedUri.host).isEqualTo("localhost") Truth.assertThat(expoParsedUri.port).isEqualTo(1999) Truth.assertThat(httpsParsedUri.scheme).isEqualTo("https") Truth.assertThat(httpsParsedUri.host).isEqualTo("google.com") Truth.assertThat(parsedUriWithPath.scheme).isEqualTo("https") Truth.assertThat(parsedUriWithPath.host).isEqualTo("expo.io") Truth.assertThat(parsedUriWithPath.path).isEqualTo("/path") } @Test fun `tests getAppUrlFromDevLauncherUrl`() { val uriWithCorrectAppUrl = Uri.parse("http://localhost?url=exp://app") val uriWithoutAppUrl = Uri.parse("http://localhost") val appUrl = getAppUrlFromDevLauncherUrl(uriWithCorrectAppUrl) val expectedNull = getAppUrlFromDevLauncherUrl(uriWithoutAppUrl) Truth.assertThat(appUrl).isEqualTo(Uri.parse("exp://app")) Truth.assertThat(expectedNull).isNull() } @Test fun `tests isDevLauncherUrl`() { Truth.assertThat( isDevLauncherUrl( Uri.parse("exp://expo-development-client") ) ).isTrue() Truth.assertThat( isDevLauncherUrl( Uri.parse("exp://not-expo-development-client") ) ).isFalse() } }
bsd-3-clause
9ba34d09efea251efe5b606ce520c20c
31.457627
74
0.730548
4.048626
false
true
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/closure/ImplicitClosureCallPredicateUtil.kt
13
1709
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.closure import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames internal fun PsiType?.isClosureType(): Boolean { return this != null && equalsToText(GroovyCommonClassNames.GROOVY_LANG_CLOSURE) } internal fun PsiElement?.isClosureCallMethod(): Boolean { return this is PsiMethod && name == "call" && containingClass?.qualifiedName == GroovyCommonClassNames.GROOVY_LANG_CLOSURE } internal fun GrCall?.isClosureCall(qualifier: PsiElement): Boolean = this?.resolveMethod()?.isClosureCallMethod() ?: false && this is GrMethodCall && ((this.invokedExpression as? GrReferenceExpression) ?.qualifierExpression ?.reference ?.resolve() == qualifier || this.invokedExpression.reference?.resolve() == qualifier)
apache-2.0
1788a8f6b68a4b386081b604dbc648b4
62.333333
140
0.600936
5.913495
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequests.kt
2
23820
// 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.plugins.github.api import com.intellij.util.ThrowableConvertor import org.jetbrains.plugins.github.api.GithubApiRequest.* import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.api.data.request.* import org.jetbrains.plugins.github.api.util.GHSchemaPreview import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.api.util.GithubApiUrlQueryBuilder import java.awt.Image /** * Collection of factory methods for API requests used in plugin * TODO: improve url building (DSL?) */ object GithubApiRequests { object CurrentUser : Entity("/user") { @JvmStatic fun get(server: GithubServerPath) = get(getUrl(server, urlSuffix)) @JvmStatic fun get(url: String) = Get.json<GithubAuthenticatedUser>(url).withOperationName("get profile information") @JvmStatic fun getAvatar(url: String) = object : Get<Image>(url) { override fun extractResult(response: GithubApiResponse): Image { return response.handleBody(ThrowableConvertor { GithubApiContentHelper.loadImage(it) }) } }.withOperationName("get profile avatar") object Repos : Entity("/repos") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, type, visibility, affiliation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null): GithubApiRequest<GithubResponsePage<GithubRepo>> { if (type != Type.DEFAULT && (visibility != Visibility.DEFAULT || affiliation != Affiliation.DEFAULT)) { throw IllegalArgumentException("Param 'type' should not be used together with 'visibility' or 'affiliation'") } return get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(type.toString(), visibility.toString(), affiliation.toString(), pagination?.toString().orEmpty()))) } @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get user repositories") @JvmStatic fun create(server: GithubServerPath, name: String, description: String, private: Boolean, autoInit: Boolean? = null) = Post.json<GithubRepo>(getUrl(server, CurrentUser.urlSuffix, urlSuffix), GithubRepoRequest(name, description, private, autoInit)) .withOperationName("create user repository") } object Orgs : Entity("/orgs") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) fun get(url: String) = Get.jsonPage<GithubOrg>(url).withOperationName("get user organizations") } object RepoSubs : Entity("/subscriptions") { @JvmStatic fun pages(server: GithubServerPath) = GithubApiPagesLoader.Request(get(server), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get repository subscriptions") } } object Organisations : Entity("/orgs") { object Repos : Entity("/repos") { @JvmStatic fun pages(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, organisation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get organisation repositories") @JvmStatic fun create(server: GithubServerPath, organisation: String, name: String, description: String, private: Boolean) = Post.json<GithubRepo>(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix), GithubRepoRequest(name, description, private, null)) .withOperationName("create organisation repository") } } object Repos : Entity("/repos") { @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String) = Get.Optional.json<GithubRepoDetailed>(getUrl(server, urlSuffix, "/$username/$repoName")) .withOperationName("get information for repository $username/$repoName") @JvmStatic fun get(url: String) = Get.Optional.json<GithubRepoDetailed>(url).withOperationName("get information for repository $url") @JvmStatic fun delete(server: GithubServerPath, username: String, repoName: String) = delete(getUrl(server, urlSuffix, "/$username/$repoName")).withOperationName("delete repository $username/$repoName") @JvmStatic fun delete(url: String) = Delete.json<Unit>(url).withOperationName("delete repository at $url") object Branches : Entity("/branches") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubBranch>(url).withOperationName("get branches") @JvmStatic fun getProtection(repository: GHRepositoryCoordinates, branchName: String): GithubApiRequest<GHBranchProtectionRules> = Get.json(getUrl(repository, urlSuffix, "/$branchName", "/protection"), GHSchemaPreview.BRANCH_PROTECTION.mimeType) } object Commits : Entity("/commits") { @JvmStatic fun compare(repository: GHRepositoryCoordinates, refA: String, refB: String) = Get.json<GHCommitsCompareResult>(getUrl(repository, "/compare/$refA...$refB")).withOperationName("compare refs") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, ref: String) = object : Get<String>(getUrl(repository, urlSuffix, "/$ref"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { it.reader().use { it.readText() } }) } }.withOperationName("get diff for ref") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, refA: String, refB: String) = object : Get<String>(getUrl(repository, "/compare/$refA...$refB"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { it.reader().use { it.readText() } }) } }.withOperationName("get diff between refs") } object Forks : Entity("/forks") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String) = Post.json<GithubRepo>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), Any()) .withOperationName("fork repository $username/$repoName for cuurent user") @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get forks") } object Assignees : Entity("/assignees") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUser>(url).withOperationName("get assignees") } object Labels : Entity("/labels") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueLabel>(url).withOperationName("get assignees") } object Collaborators : Entity("/collaborators") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUserWithPermissions>(url).withOperationName("get collaborators") @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, collaborator: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", collaborator)) } object Issues : Entity("/issues") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, body: String? = null, milestone: Long? = null, labels: List<String>? = null, assignees: List<String>? = null) = Post.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubCreateIssueRequest(title, body, milestone, labels, assignees)) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null) = GithubApiPagesLoader.Request(get(server, username, repoName, state, assignee), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("state", state); param("assignee", assignee); param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssue>(url).withOperationName("get issues in repository") @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, id: String) = Get.Optional.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id)) @JvmStatic fun updateState(server: GithubServerPath, username: String, repoName: String, id: String, open: Boolean) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubChangeIssueStateRequest(if (open) "open" else "closed")) @JvmStatic fun updateAssignees(server: GithubServerPath, username: String, repoName: String, id: String, assignees: Collection<String>) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubAssigneesCollectionRequest(assignees)) object Comments : Entity("/comments") { @JvmStatic fun create(repository: GHRepositoryCoordinates, issueId: Long, body: String) = create(repository.serverPath, repository.repositoryPath.owner, repository.repositoryPath.repository, issueId.toString(), body) @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, issueId: String, body: String) = Post.json<GithubIssueCommentWithHtml>( getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubCreateIssueCommentRequest(body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, issueId: String) = GithubApiPagesLoader.Request(get(server, username, repoName, issueId), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, issueId: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for issue") } object Labels : Entity("/labels") { @JvmStatic fun replace(server: GithubServerPath, username: String, repoName: String, issueId: String, labels: Collection<String>) = Put.jsonList<GithubIssueLabel>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubLabelsCollectionRequest(labels)) } } object PullRequests : Entity("/pulls") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, description: String, head: String, base: String) = Post.json<GithubPullRequestDetailed>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubPullRequestRequest(title, description, head, base)) .withOperationName("create pull request in $username/$repoName") @JvmStatic fun update(serverPath: GithubServerPath, username: String, repoName: String, number: Long, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(getUrl(serverPath, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/$number"), GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request $number") @JvmStatic fun update(url: String, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(url, GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request") @JvmStatic fun merge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.merge)) .withOperationName("merge pull request ${number}") @JvmStatic fun squashMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.squash)) .withOperationName("squash and merge pull request ${number}") @JvmStatic fun rebaseMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRebaseRequest(headSha)) .withOperationName("rebase and merge pull request ${number}") @JvmStatic fun getListETag(server: GithubServerPath, repoPath: GHRepositoryPath) = object : Get<String?>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(GithubRequestPagination(pageSize = 1)) })) { override fun extractResult(response: GithubApiResponse) = response.findHeader("ETag") }.withOperationName("get pull request list ETag") object Reviewers : Entity("/requested_reviewers") { @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Post.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) @JvmStatic fun remove(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Delete.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) } } } object Gists : Entity("/gists") { @JvmStatic fun create(server: GithubServerPath, contents: List<GithubGistRequest.FileContent>, description: String, public: Boolean) = Post.json<GithubGist>(getUrl(server, urlSuffix), GithubGistRequest(contents, description, public)) .withOperationName("create gist") @JvmStatic fun get(server: GithubServerPath, id: String) = Get.Optional.json<GithubGist>(getUrl(server, urlSuffix, "/$id")) .withOperationName("get gist $id") @JvmStatic fun delete(server: GithubServerPath, id: String) = Delete.json<Unit>(getUrl(server, urlSuffix, "/$id")) .withOperationName("delete gist $id") } object Search : Entity("/search") { object Issues : Entity("/issues") { @JvmStatic fun pages(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?) = GithubApiPagesLoader.Request(get(server, repoPath, state, assignee, query), ::get) @JvmStatic fun get(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", GithubApiSearchQueryBuilder.searchQuery { qualifier("repo", repoPath?.toString().orEmpty()) qualifier("state", state) qualifier("assignee", assignee) query(query) }) param(pagination) })) @JvmStatic fun get(server: GithubServerPath, query: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", query) param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonSearchPage<GithubSearchedIssue>(url).withOperationName("search issues in repository") } } object Auth : Entity("/authorizations") { @JvmStatic fun create(server: GithubServerPath, scopes: List<String>, note: String) = Post.json<GithubAuthorization>(getUrl(server, urlSuffix), GithubAuthorizationCreateRequest(scopes, note, null)) .withOperationName("create authorization $note") @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubAuthorization>(url) .withOperationName("get authorizations") @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) } abstract class Entity(val urlSuffix: String) private fun getUrl(server: GithubServerPath, suffix: String) = server.toApiUrl() + suffix private fun getUrl(repository: GHRepositoryCoordinates, vararg suffixes: String) = getUrl(repository.serverPath, Repos.urlSuffix, "/", repository.repositoryPath.toString(), *suffixes) fun getUrl(server: GithubServerPath, vararg suffixes: String) = StringBuilder(server.toApiUrl()).append(*suffixes).toString() private fun getQuery(vararg queryParts: String): String { val builder = StringBuilder() for (part in queryParts) { if (part.isEmpty()) continue if (builder.isEmpty()) builder.append("?") else builder.append("&") builder.append(part) } return builder.toString() } }
apache-2.0
4ca6e12ebf5d7f7e1b676e44a51c51aa
46.929577
140
0.65974
5.173762
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCallableReferenceInLambdaInspection.kt
1
6401
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.intentions.ConvertLambdaToReferenceIntention import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtCallableReferenceExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.ValueArgument import org.jetbrains.kotlin.psi.lambdaExpressionVisitor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.callUtil.getParentCall import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class SuspiciousCallableReferenceInLambdaInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = lambdaExpressionVisitor(fun(lambdaExpression) { val callableReference = lambdaExpression.bodyExpression?.statements?.singleOrNull() as? KtCallableReferenceExpression ?: return val context = lambdaExpression.analyze() val parentResolvedCall = lambdaExpression.getParentResolvedCall(context) if (parentResolvedCall != null) { val expectedType = parentResolvedCall.getParameterForArgument(lambdaExpression.parent as? ValueArgument)?.type if (expectedType?.isBuiltinFunctionalType == true) { val returnType = expectedType.getReturnTypeFromFunctionType() if (returnType.isFunctionOrSuspendFunctionType) return if (parentResolvedCall.call.callElement.getParentCall(context) != null) return } } val quickFix = if (canMove(lambdaExpression, callableReference, context)) IntentionWrapper(MoveIntoParenthesesIntention()) else null holder.registerProblem( lambdaExpression, KotlinBundle.message("suspicious.callable.reference.as.the.only.lambda.element"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, quickFix ) }) private fun canMove( lambdaExpression: KtLambdaExpression, callableReference: KtCallableReferenceExpression, context: BindingContext ): Boolean { val lambdaDescriptor = context[BindingContext.FUNCTION, lambdaExpression.functionLiteral] ?: return false val lambdaParameter = lambdaDescriptor.extensionReceiverParameter ?: lambdaDescriptor.valueParameters.singleOrNull() val functionReceiver = callableReference.receiverExpression?.mainReference?.resolveToDescriptors(context)?.firstOrNull() if (functionReceiver == lambdaParameter) return true val lambdaParameterType = lambdaParameter?.type if (functionReceiver is VariableDescriptor && functionReceiver.type == lambdaParameterType) return true if (functionReceiver is ClassDescriptor && functionReceiver == lambdaParameterType?.constructor?.declarationDescriptor) return true if (lambdaParameterType == null) return false val functionDescriptor = callableReference.callableReference.mainReference.resolveToDescriptors(context).firstOrNull() as? FunctionDescriptor val functionParameterType = functionDescriptor?.valueParameters?.firstOrNull()?.type ?: return false return functionParameterType == lambdaParameterType } class MoveIntoParenthesesIntention : ConvertLambdaToReferenceIntention( KotlinBundle.lazyMessage("move.suspicious.callable.reference.into.parentheses") ) { override fun buildReferenceText(element: KtLambdaExpression): String? { val callableReferenceExpression = element.bodyExpression?.statements?.singleOrNull() as? KtCallableReferenceExpression ?: return null val callableReference = callableReferenceExpression.callableReference val receiverExpression = callableReferenceExpression.receiverExpression val receiver = if (receiverExpression == null) { "" } else { val descriptor = receiverExpression.getCallableDescriptor() val literal = element.functionLiteral if (descriptor == null || descriptor is ValueParameterDescriptor && descriptor.containingDeclaration == literal.resolveToDescriptorIfAny() ) { callableReference.resolveToCall(BodyResolveMode.FULL) ?.let { it.extensionReceiver ?: it.dispatchReceiver } ?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it.type) } ?: "" } else { receiverExpression.text } } return "$receiver::${callableReference.text}" } override fun isApplicableTo(element: KtLambdaExpression) = true } }
apache-2.0
128822023373907d396680cc42db2992
54.66087
158
0.741915
6.208535
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/ReflectionCallClassPatcher.kt
6
15425
// 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.evaluate.compilation import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.impl.compiled.SignatureParsing import com.intellij.psi.impl.compiled.StubBuildingVisitor import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.ClassUtil import com.intellij.util.concurrency.annotations.RequiresReadLock import org.jetbrains.kotlin.idea.debugger.evaluate.variables.EvaluatorValueConverter import org.jetbrains.kotlin.idea.debugger.evaluate.variables.box import org.jetbrains.org.objectweb.asm.* import java.text.StringCharacterIterator object ReflectionCallClassPatcher { var isEnabled: Boolean get() = Registry.`is`("kotlin.debugger.evaluator.enable.reflection.patching") set(newValue) { Registry.get("kotlin.debugger.evaluator.enable.reflection.patching").setValue(newValue) } @RequiresReadLock fun patch(bytes: ByteArray, project: Project, scope: GlobalSearchScope): ByteArray { val reader = ClassReader(bytes) val writer = ClassWriter(reader, ClassWriter.COMPUTE_MAXS) reader.accept(object : ClassVisitor(Opcodes.API_VERSION, writer) { override fun visitMethod( access: Int, name: String?, descriptor: String?, signature: String?, exceptions: Array<out String>? ): MethodVisitor { ProgressManager.checkCanceled() val delegate = super.visitMethod(access, name, descriptor, signature, exceptions) return ReflectionCallMethodVisitor(project, scope, delegate) } }, 0) return writer.toByteArray() } } private class ReflectionCallMethodVisitor( private val project: Project, private val scope: GlobalSearchScope, methodVisitor: MethodVisitor ) : MethodVisitor(Opcodes.API_VERSION, methodVisitor) { private fun boxValue(type: Type, boxedType: Type) { val methodDescriptor = "(" + type.descriptor + ")" + boxedType.descriptor super.visitMethodInsn(Opcodes.INVOKESTATIC, boxedType.internalName, "valueOf", methodDescriptor, false) } private fun unboxValue(type: Type, boxedType: Type) { val boxedClassName = boxedType.internalName val methodName = EvaluatorValueConverter.UNBOXING_METHOD_NAMES[boxedClassName] ?: error("Unexpected boxed type: $boxedType") val methodDescriptor = "()" + type.descriptor super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, boxedClassName, methodName, methodDescriptor, false) } private fun pushClassLiteral(type: Type, resolvedClass: PsiClass? = null) { if (type.sort != Type.OBJECT && type.sort != Type.ARRAY) { throw IllegalStateException("Object or array type expected, got $type") } val internalName = type.internalName val psiClass = resolvedClass ?: findClass(internalName) if (psiClass != null && !psiClass.hasModifierProperty(PsiModifier.PUBLIC)) { super.visitLdcInsn(internalName.replace('/', '.')) super.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false) } else { super.visitLdcInsn(type) } } private fun findClass(internalName: String): PsiClass? { val type = Type.getObjectType(internalName) if (type.sort != Type.OBJECT) { // Array doesn't have any fields (`length` calls is transformed to the ARRAYLENGTH instruction) return null } val iterator = StringCharacterIterator(type.descriptor) val classType = SignatureParsing.parseTypeString(iterator, StubBuildingVisitor.GUESSING_MAPPER) return JavaPsiFacade.getInstance(project).findClass(classType, scope) } private fun fetchReflectionField(owner: String, name: String) { pushClassLiteral(Type.getObjectType(owner)) /// ..., receiverType super.visitLdcInsn(name) /// ..., receiverType, fieldName val methodSignature = "(Ljava/lang/String;)Ljava/lang/reflect/Field;" super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredField", methodSignature, false) /// ..., field super.visitInsn(Opcodes.DUP) /// ..., field, field super.visitLdcInsn(1) /// ..., field, field, 'true' super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Field", "setAccessible", "(Z)V", false) /// ..., field } override fun visitFieldInsn(opcode: Int, owner: String, name: String, descriptor: String) { val field = findClass(owner)?.findFieldByName(name, false) if (field == null || field.hasModifierProperty(PsiModifier.PUBLIC)) { return super.visitFieldInsn(opcode, owner, name, descriptor) } val valueType = Type.getType(descriptor) val boxedValueType = box(valueType) fetchReflectionField(owner, name) // ..., field val isCategory2Type = valueType.size == 2 when (opcode) { Opcodes.GETSTATIC -> { /// field super.visitInsn(Opcodes.ACONST_NULL) /// field, receiver } Opcodes.PUTSTATIC -> { /// value, field super.visitInsn(Opcodes.ACONST_NULL) /// value, field, receiver super.visitInsn(if (isCategory2Type) Opcodes.DUP2_X2 else Opcodes.DUP2_X1) /// field, receiver, value, field, receiver super.visitInsn(Opcodes.POP2) /// field, receiver, value } Opcodes.GETFIELD -> { /// receiver, field super.visitInsn(Opcodes.SWAP) /// field, receiver } Opcodes.PUTFIELD -> { /// receiver, value, field super.visitInsn(if (isCategory2Type) Opcodes.DUP_X2 else Opcodes.DUP_X1) /// receiver, field, value, field super.visitInsn(Opcodes.POP) /// receiver, field, value super.visitInsn(if (isCategory2Type) Opcodes.DUP2_X2 else Opcodes.DUP_X2) /// value, receiver, field, value super.visitInsn(if (isCategory2Type) Opcodes.POP2 else Opcodes.POP) /// value, receiver, field super.visitInsn(Opcodes.SWAP) /// value, field, receiver super.visitInsn(if (isCategory2Type) Opcodes.DUP2_X2 else Opcodes.DUP2_X1) /// field, receiver, value, field, receiver super.visitInsn(Opcodes.POP2) /// field, receiver, value } else -> throw IllegalStateException("Unexpected opcode $opcode") } val isPut = opcode == Opcodes.PUTSTATIC || opcode == Opcodes.PUTFIELD if (isPut && valueType != boxedValueType) { boxValue(valueType, boxedValueType) } val methodName = if (isPut) "set" else "get" val methodSignature = if (isPut) "(Ljava/lang/Object;Ljava/lang/Object;)V" else "(Ljava/lang/Object;)Ljava/lang/Object;" super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Field", methodName, methodSignature, false) if (!isPut) { super.visitTypeInsn(Opcodes.CHECKCAST, boxedValueType.internalName) if (valueType != boxedValueType) { unboxValue(valueType, boxedValueType) } } } private fun findMethod(owner: String, name: String, descriptor: String): PsiMethod? { val declaringClass = findClass(owner) ?: return null val methods = if (name == "<init>") declaringClass.constructors else declaringClass.findMethodsByName(name, true) for (method in methods) { val methodDescriptor = ClassUtil.getAsmMethodSignature(method) if (methodDescriptor == descriptor) { return method } } return null } private class ResolvedMethodCall( val declaringClass: PsiClass, val declaringClassType: Type, val parameterTypes: List<Type>, val boxedParameterTypes: List<Type> ) private fun resolveApplicableMethodCall(opcode: Int, owner: String, name: String, descriptor: String): ResolvedMethodCall? { if (opcode != Opcodes.INVOKEVIRTUAL && opcode != Opcodes.INVOKESTATIC && opcode != Opcodes.INVOKESPECIAL) { return null } if (name.startsWith("<") && name != "<init>") { return null } else if (name == "<init>") { // Constructors are filtered out here as they need to be properly supported // (for instance, we need to deal with the preceding NEW instruction somehow). return null } val method = findMethod(owner, name, descriptor) val declaringClass = method?.containingClass if (method == null || method.hasModifierProperty(PsiModifier.PUBLIC) || declaringClass == null) { return null } val declaringClassType = PsiElementFactory.getInstance(project).createType(declaringClass) val declaringClassTypeDescriptor = ClassUtil.getBinaryPresentation(declaringClassType).takeIf { it.isNotEmpty() } ?: return null val declaringClassAsmType = Type.getType(declaringClassTypeDescriptor) val parameterCount = method.parameterList.parametersCount val parameterTypes = ArrayList<Type>(parameterCount) val boxedParameterTypes = ArrayList<Type>(parameterCount) for (index in 0 until parameterCount) { val parameter = method.parameterList.getParameter(index) ?: return null val parameterTypeDescriptor = ClassUtil.getBinaryPresentation(parameter.type).takeIf { it.isNotEmpty() } ?: return null val parameterType = Type.getType(parameterTypeDescriptor) parameterTypes += parameterType boxedParameterTypes += box(parameterType) } return ResolvedMethodCall(declaringClass, declaringClassAsmType, parameterTypes, boxedParameterTypes) } private fun fetchReflectionMethod(name: String, resolvedCall: ResolvedMethodCall) { val isConstructor = name == "<init>" pushClassLiteral(resolvedCall.declaringClassType, resolvedCall.declaringClass) if (!isConstructor) { super.visitLdcInsn(name) } // Put argument types to an array run { super.visitLdcInsn(resolvedCall.parameterTypes.size) super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class") /// ..., types for (index in 0 until resolvedCall.parameterTypes.size) { val parameterType = resolvedCall.parameterTypes[index] val boxedParameterType = resolvedCall.boxedParameterTypes[index] super.visitInsn(Opcodes.DUP) /// ..., types, types super.visitLdcInsn(index) /// ..., types, types, index if (parameterType != boxedParameterType) { super.visitFieldInsn(Opcodes.GETSTATIC, boxedParameterType.internalName, "TYPE", "Ljava/lang/Class;") } else { pushClassLiteral(parameterType) } /// ..., types, types, index, type super.visitInsn(Opcodes.AASTORE) /// ..., types } } val getMethodName = if (isConstructor) "getDeclaredConstructor" else "getDeclaredMethod" val getMethodSignature = if (isConstructor) "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;" else "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;" super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", getMethodName, getMethodSignature, false) /// ..., method super.visitInsn(Opcodes.DUP) /// ..., method, method super.visitLdcInsn(1) /// ..., method, method, 'true' super.visitMethodInsn( Opcodes.INVOKEVIRTUAL, "java/lang/reflect/AccessibleObject", "setAccessible", "(Z)V", false ) /// ..., method } override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) { val resolvedCall = resolveApplicableMethodCall(opcode, owner, name, descriptor) if (resolvedCall == null) { super.visitMethodInsn(opcode, owner, name, descriptor, isInterface) return } val isConstructor = name == "<init>" val isStatic = opcode == Opcodes.INVOKESTATIC val parameterCount = resolvedCall.parameterTypes.size super.visitLdcInsn(parameterCount) super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object") // Put boxed arguments to an array run { for (index in (parameterCount - 1) downTo 0) { val parameterType = resolvedCall.parameterTypes[index] val boxedParameterType = resolvedCall.boxedParameterTypes[index] /// currentValue, args super.visitInsn(Opcodes.DUP) /// currentValue, args, args super.visitInsn(if (parameterType.size == 2) Opcodes.DUP2_X2 else Opcodes.DUP2_X1) /// args, args, currentValue, args, args super.visitInsn(Opcodes.POP2) /// args, args, currentValue if (parameterType != boxedParameterType) { boxValue(parameterType, boxedParameterType) } super.visitLdcInsn(index) /// args, args, currentValue, index super.visitInsn(Opcodes.SWAP) /// args, args, index, currentValue super.visitInsn(Opcodes.AASTORE) /// args } } if (isStatic) { /// args super.visitInsn(Opcodes.ACONST_NULL) /// args, receiver super.visitInsn(Opcodes.SWAP) /// receiver, args } // Get accessible Method/Constructor instance fetchReflectionMethod(name, resolvedCall) if (isConstructor) { super.visitInsn(Opcodes.SWAP) /// method, args } else { super.visitInsn(Opcodes.DUP_X2) /// method, receiver, args, method super.visitInsn(Opcodes.POP) /// method, receiver, args } val invokeReceiverType = if (isConstructor) "java/lang/reflect/Constructor" else "java/lang/reflect/Method" val invokeMethodName = if (isConstructor) "newInstance" else "invoke" val invokeMethodSignature = if (isConstructor) "([Ljava/lang/Object;)Ljava/lang/Object;" else "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;" /// method, [receiver], args super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, invokeReceiverType, invokeMethodName, invokeMethodSignature, false) val returnType = if (isConstructor) resolvedCall.declaringClassType else Type.getMethodType(descriptor).returnType val boxedReturnType = box(returnType) super.visitTypeInsn(Opcodes.CHECKCAST, boxedReturnType.internalName) if (returnType != boxedReturnType) { unboxValue(returnType, boxedReturnType) } } }
apache-2.0
3356456711717f44f4172ef17719f17e
44.639053
158
0.645575
4.982235
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/models/MessageTest.kt
1
1816
package com.kickstarter.models import com.kickstarter.mock.factories.UserFactory import junit.framework.TestCase import org.joda.time.DateTime import org.junit.Test class MessageTest : TestCase() { @Test fun testDefaultInit() { val dateTime: DateTime = DateTime.now().plusMillis(300) val message = Message.builder().createdAt(dateTime).build() assertTrue(message.id() == 0L) assertTrue(message.body() == "") assertTrue(message.createdAt() == dateTime) assertTrue(message.recipient() == User.builder().build()) assertTrue(message.sender() == User.builder().build()) } @Test fun testMessage_equalFalse() { val message = Message.builder().build() val message2 = Message.builder().body("body2").createdAt(DateTime.now().plusMillis(300)).id(1234L).sender(User.builder().build()).build() val message3 = Message.builder().body("body3").createdAt(DateTime.now().plusDays(1).plusMillis(300)).id(5678L).sender(UserFactory.creator()).build() val message4 = Message.builder().body("body4").createdAt(DateTime.now().plusDays(3).plusMillis(300)).id(1234L).recipient(UserFactory.germanUser()).sender(UserFactory.creator()).build() assertFalse(message == message2) assertFalse(message == message3) assertFalse(message == message4) assertFalse(message3 == message2) assertFalse(message3 == message4) } @Test fun testMessage_equalTrue() { val message1 = Message.builder().body("body2").createdAt(DateTime.now().plusMillis(300)).id(1234L).sender(User.builder().build()).build() val message2 = message1.toBuilder().body("body2").build() assertTrue(message1 == message2) assertTrue(message1.recipient() == message2.recipient()) } }
apache-2.0
b6665f9c9f4684689f169b3b1fe422cf
39.355556
192
0.670705
4.155606
false
true
false
false
fabioCollini/DaggerMock
daggermockTests/src/test/java/it/cosenonjaviste/daggermock/builder/Config.kt
1
1237
package it.cosenonjaviste.daggermock.builder import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Inject class MyService { fun get(): String = "AAA" } class MyService2 { fun get(): String = "AAA" } class MainService @Inject constructor(val myService: MyService) { @Inject lateinit var myService2: MyService2 fun get2(): String = myService.get() + myService2.get() fun get(): String = myService.get() } @Component(modules = [MyModule::class], dependencies = [MyComponent2::class]) interface MyComponent { fun mainService(): MainService @Component.Builder interface Builder { fun myComponent2(component2: MyComponent2): Builder fun myModule(module: MyModule): Builder fun build(): MyComponent } } @Component(modules = [MyModule2::class]) interface MyComponent2 { fun myService2(): MyService2 @Component.Builder interface Builder { fun myModule2(module: MyModule2): Builder fun build(): MyComponent2 } } @Module class MyModule { @Provides fun provideMyService(): MyService = MyService() } @Module class MyModule2 { @Provides fun provideMyService2(): MyService2 = MyService2() }
apache-2.0
b5e01fdfc4b3f94aef4e3f69e8b8fd35
18.967742
77
0.691997
4.265517
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/activities/ThanksActivity.kt
1
6198
package com.kickstarter.ui.activities import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.util.Pair import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kickstarter.R import com.kickstarter.databinding.ThanksLayoutBinding import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.KSString import com.kickstarter.libs.RefTag import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.getProjectIntent import com.kickstarter.models.Project import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.IntentKey import com.kickstarter.ui.adapters.ThanksAdapter import com.kickstarter.ui.extensions.showRatingDialogWidget import com.kickstarter.viewmodels.ThanksViewModel import rx.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit @RequiresActivityViewModel(ThanksViewModel.ViewModel::class) class ThanksActivity : BaseActivity<ThanksViewModel.ViewModel>() { private lateinit var ksString: KSString private lateinit var binding: ThanksLayoutBinding private val projectStarConfirmationString = R.string.project_star_confirmation override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ThanksLayoutBinding.inflate(layoutInflater) setContentView(binding.root) ksString = requireNotNull(environment().ksString()) binding.thanksRecyclerView.layoutManager = LinearLayoutManager(this).apply { orientation = RecyclerView.VERTICAL } val adapter = ThanksAdapter(viewModel.inputs) binding.thanksRecyclerView.adapter = adapter viewModel.outputs.adapterData() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { adapter.takeData(it) } viewModel.outputs.showConfirmGamesNewsletterDialog() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { showConfirmGamesNewsletterDialog() } viewModel.outputs.finish() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { finish() } // I'm not sure why we would attempt to show a dialog after a delay but hopefully this helps viewModel.outputs.showGamesNewsletterDialog() .compose(bindToLifecycle()) .take(1) .delay(700L, TimeUnit.MILLISECONDS) .compose(Transformers.observeForUI()) .subscribe { if (!isFinishing) { showGamesNewsletterDialog() } } viewModel.outputs.showRatingDialog() .compose(bindToLifecycle()) .take(1) .delay(700L, TimeUnit.MILLISECONDS) .compose(Transformers.observeForUI()) .subscribe { if (!isFinishing) { showRatingDialog() } } viewModel.outputs.startDiscoveryActivity() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { startDiscoveryActivity(it) } viewModel.outputs.startProjectActivity() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { startProjectActivity(it) } binding.thanksToolbar.closeButton.setOnClickListener { closeButtonClick() } this.viewModel.outputs.showSavedPrompt() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.showStarToast() } } private fun showStarToast() { ViewUtils.showToastFromTop(this, getString(this.projectStarConfirmationString), 0, resources.getDimensionPixelSize(R.dimen.grid_8)) } override fun onDestroy() { super.onDestroy() binding.thanksRecyclerView.adapter = null } private fun closeButtonClick() = viewModel.inputs.closeButtonClicked() private fun showConfirmGamesNewsletterDialog() { val optInDialogMessageString = ksString.format( getString(R.string.profile_settings_newsletter_opt_in_message), "newsletter", getString(R.string.profile_settings_newsletter_games) ) val builder = AlertDialog.Builder(this) .setMessage(optInDialogMessageString) .setTitle(R.string.profile_settings_newsletter_opt_in_title) .setPositiveButton(R.string.general_alert_buttons_ok) { _: DialogInterface?, _: Int -> } builder.show() } private fun showGamesNewsletterDialog() { val builder = AlertDialog.Builder(this) .setMessage(R.string.project_checkout_games_alert_want_the_coolest_games_delivered_to_your_inbox) .setPositiveButton(R.string.project_checkout_games_alert_yes_please) { _: DialogInterface?, _: Int -> viewModel.inputs.signupToGamesNewsletterClick() } .setNegativeButton(R.string.project_checkout_games_alert_no_thanks) { _: DialogInterface?, _: Int -> } builder.show() } private fun showRatingDialog() = showRatingDialogWidget() private fun startDiscoveryActivity(params: DiscoveryParams) { val intent = Intent(this, DiscoveryActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) .putExtra(IntentKey.DISCOVERY_PARAMS, params) startActivity(intent) } private fun startProjectActivity(projectAndRefTagAndIsFfEnabled: Pair<Project, RefTag>) { val intent = Intent().getProjectIntent(this) .putExtra(IntentKey.PROJECT, projectAndRefTagAndIsFfEnabled.first) .putExtra(IntentKey.REF_TAG, projectAndRefTagAndIsFfEnabled.second) startActivityWithTransition(intent, R.anim.slide_in_right, R.anim.fade_out_slide_out_left) } }
apache-2.0
50814f2dccdc61aaefb503f924241179
40.046358
163
0.696515
5.072013
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt
1
18924
// 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.j2k import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.inspections.* import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.mapToIndex object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { private val myProcessings = ArrayList<J2kPostProcessing>() override val processings: Collection<J2kPostProcessing> get() = myProcessings private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>() override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!! init { myProcessings.add(RemoveExplicitTypeArgumentsProcessing()) myProcessings.add(RemoveRedundantOverrideVisibilityProcessing()) registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection()) myProcessings.add(FixObjectStringConcatenationProcessing()) myProcessings.add(ConvertToStringTemplateProcessing()) myProcessings.add(UsePropertyAccessSyntaxProcessing()) myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(RemoveRedundantSamAdaptersProcessing()) myProcessings.add(RemoveRedundantCastToNullableProcessing()) registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection()) myProcessings.add(UseExpressionBodyProcessing()) registerInspectionBasedProcessing(UnnecessaryVariableInspection()) registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection()) registerIntentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() } registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) { it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments( it ) as KtReturnExpression).returnedExpression.isTrivialStatementBody() } registerInspectionBasedProcessing(IfThenToSafeAccessInspection()) registerInspectionBasedProcessing(IfThenToElvisInspection(true)) registerInspectionBasedProcessing(SimplifyNegatedBinaryExpressionInspection()) registerInspectionBasedProcessing(ReplaceGetOrSetInspection()) registerInspectionBasedProcessing(AddOperatorModifierInspection()) registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention()) registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention()) registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()) registerIntentionBasedProcessing(DestructureIntention()) registerInspectionBasedProcessing(SimplifyAssertNotNullInspection()) registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention()) registerInspectionBasedProcessing(JavaMapForEachInspection()) registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection()) registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ -> val expression = RemoveUselessCastFix.invoke(element) val variable = expression.parent as? KtProperty if (variable != null && expression == variable.initializer && variable.isLocal) { val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull() if (ref != null && ref.element is KtSimpleNameExpression) { ref.element.replace(expression) variable.delete() } } } registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic -> val fix = RemoveModifierFixBase.createRemoveProjectionFactory(true) .asKotlinIntentionActionsFactory() .createActions(diagnostic).single() as RemoveModifierFixBase fix.invoke() } registerDiagnosticBasedProcessingFactory( Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION ) { element: KtSimpleNameExpression, _: Diagnostic -> val property = element.mainReference.resolve() as? KtProperty if (property == null) { null } else { { if (!property.isVar) { property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword()) } } } } registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ -> val exclExclExpr = element.parent as KtUnaryExpression val baseExpression = exclExclExpr.baseExpression!! val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) { exclExclExpr.replace(baseExpression) } } processingsToPriorityMap.putAll(myProcessings.mapToIndex()) } private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing( intention: TIntention, noinline additionalChecker: (TElement) -> Boolean = { true } ) { myProcessings.add(object : J2kPostProcessing { // Intention can either need or not need write action override val writeActionNeeded = intention.startInWriteAction() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (intention.applicabilityRange(tElement) == null) return null if (!additionalChecker(tElement)) return null return { if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change intention.applyTo(element, null) } } } }) } private inline fun <reified TElement : KtElement, TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing( inspection: TInspection, acceptInformationLevel: Boolean = false ) { myProcessings.add(object : J2kPostProcessing { // Inspection can either need or not need write action override val writeActionNeeded = inspection.startFixInWriteAction private fun isApplicable(element: TElement): Boolean { if (!inspection.isApplicable(element)) return false return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION } override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (!isApplicable(tElement)) return null return { if (isApplicable(tElement)) { // check availability of the inspection again because something could change inspection.applyTo(tElement) } } } }) } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fix: (TElement, Diagnostic) -> Unit ) { registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic -> { fix( element, diagnostic ) } } } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)? ) { myProcessings.add(object : J2kPostProcessing { // ??? override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null return fixFactory(element as TElement, diagnostic) } }) } private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo( element, approximateFlexible = true ) ) return null return { if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) { element.delete() } } } } private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val modifier = element.visibilityModifierType() ?: return null return { element.setVisibility(modifier) } } } private class ConvertToStringTemplateProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = ConvertToStringTemplateIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert( element ) ) { return { intention.applyTo(element, null) } } else { return null } } } private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = UsePropertyAccessSyntaxIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val propertyName = intention.detectPropertyNameToUse(element) ?: return null return { intention.applyTo(element, propertyName, reformat = true) } } } private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) if (expressions.isEmpty()) return null return { RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) .forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) } } } } private class UseExpressionBodyProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtPropertyAccessor) return null val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false) if (!inspection.isActiveFor(element)) return null return { if (inspection.isActiveFor(element)) { inspection.simplify(element, false) } } } } private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpressionWithTypeRHS) return null val context = element.analyze() val leftType = context.getType(element.left) ?: return null val rightType = context.get(BindingContext.TYPE, element.right) ?: return null if (!leftType.isMarkedNullable && rightType.isMarkedNullable) { return { val type = element.right?.typeElement as? KtNullableType type?.replace(type.innerType!!) } } return null } } private class FixObjectStringConcatenationProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpression || element.operationToken != KtTokens.PLUS || diagnostics.forElement(element.operationReference).none { it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER || it.factory == Errors.NONE_APPLICABLE } ) return null val bindingContext = element.analyze() val rightType = element.right?.getType(bindingContext) ?: return null if (KotlinBuiltIns.isString(rightType)) { return { val factory = KtPsiFactory(element) element.left!!.replace(factory.buildExpression { appendFixedText("(") appendExpression(element.left) appendFixedText(").toString()") }) } } return null } } private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNINITIALIZED_VARIABLE } ) return null val resolved = element.mainReference.resolve() ?: return null if (resolved.isAncestor(element, strict = true)) { if (resolved is KtVariableDeclaration && resolved.hasInitializer()) { val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } } } return null } } private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNRESOLVED_REFERENCE } ) return null val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null if (variable.nameAsName == element.getReferencedNameAsName() && variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject ) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } return null } } }
apache-2.0
e257ddb5c9a5fa39e9bfbd24cc2c055e
45.844059
158
0.674329
6.356735
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/variables/VariableFinder.kt
1
21193
// 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.evaluate.variables import com.intellij.debugger.engine.JavaValue import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.jdi.LocalVariableProxyImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.sun.jdi.* import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.AsmUtil.getCapturedFieldName import org.jetbrains.kotlin.codegen.AsmUtil.getLabeledThisName import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX import org.jetbrains.kotlin.codegen.inline.INLINE_TRANSFORMATION_SUFFIX import org.jetbrains.kotlin.idea.debugger.* import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.* import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider import org.jetbrains.kotlin.load.java.JvmAbi import kotlin.coroutines.Continuation import org.jetbrains.org.objectweb.asm.Type as AsmType import com.sun.jdi.Type as JdiType class VariableFinder(val context: ExecutionContext) { private val frameProxy = context.frameProxy companion object { private val USE_UNSAFE_FALLBACK: Boolean get() = true private fun getCapturedVariableNameRegex(capturedName: String): Regex { val escapedName = Regex.escape(capturedName) val escapedSuffix = Regex.escape(INLINE_TRANSFORMATION_SUFFIX) return Regex("^$escapedName(?:$escapedSuffix)?$") } } val evaluatorValueConverter = EvaluatorValueConverter(context) val refWrappers: List<RefWrapper> get() = mutableRefWrappers private val mutableRefWrappers = mutableListOf<RefWrapper>() class RefWrapper(val localVariableName: String, val wrapper: Value?) sealed class VariableKind(val asmType: AsmType) { abstract fun capturedNameMatches(name: String): Boolean class Ordinary(val name: String, asmType: AsmType, val isDelegated: Boolean) : VariableKind(asmType) { private val capturedNameRegex = getCapturedVariableNameRegex(getCapturedFieldName(this.name)) override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name) } // TODO Support overloaded local functions class LocalFunction(val name: String, asmType: AsmType) : VariableKind(asmType) { @Suppress("ConvertToStringTemplate") override fun capturedNameMatches(name: String) = name == "$" + name } class UnlabeledThis(asmType: AsmType) : VariableKind(asmType) { override fun capturedNameMatches(name: String) = (name == AsmUtil.CAPTURED_RECEIVER_FIELD || name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD))) } class OuterClassThis(asmType: AsmType) : VariableKind(asmType) { override fun capturedNameMatches(name: String) = false } class FieldVar(val fieldName: String, asmType: AsmType) : VariableKind(asmType) { // Captured 'field' are not supported yet override fun capturedNameMatches(name: String) = false } class ExtensionThis(val label: String, asmType: AsmType) : VariableKind(asmType) { val parameterName = getLabeledThisName(label, AsmUtil.LABELED_THIS_PARAMETER, AsmUtil.RECEIVER_PARAMETER_NAME) val fieldName = getLabeledThisName(label, getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD), AsmUtil.CAPTURED_RECEIVER_FIELD) private val capturedNameRegex = getCapturedVariableNameRegex(fieldName) override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name) } } class Result(val value: Value?) private class NamedEntity(val name: String, val lazyType: Lazy<JdiType?>, val lazyValue: Lazy<Value?>) { val type: JdiType? get() = lazyType.value val value: Value? get() = lazyValue.value companion object { fun of(field: Field, owner: ObjectReference): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { field.safeType() } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { owner.getValue(field) } return NamedEntity(field.name(), type, value) } fun of(variable: LocalVariableProxyImpl, frameProxy: StackFrameProxyImpl): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.safeType() } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { frameProxy.getValue(variable) } return NamedEntity(variable.name(), type, value) } fun of(variable: JavaValue, context: EvaluationContextImpl): NamedEntity { val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.type } val value = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.safeCalcValue(context) } return NamedEntity(variable.name, type, value) } } } fun find(parameter: CodeFragmentParameter, asmType: AsmType): Result? { return when (parameter.kind) { Kind.ORDINARY -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = false)) Kind.DELEGATED -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = true)) Kind.FAKE_JAVA_OUTER_CLASS -> thisObject()?.let { Result(it) } Kind.EXTENSION_RECEIVER -> findExtensionThis(VariableKind.ExtensionThis(parameter.name, asmType)) Kind.LOCAL_FUNCTION -> findLocalFunction(VariableKind.LocalFunction(parameter.name, asmType)) Kind.DISPATCH_RECEIVER -> findDispatchThis(VariableKind.OuterClassThis(asmType)) Kind.COROUTINE_CONTEXT -> findCoroutineContext() Kind.FIELD_VAR -> findFieldVariable(VariableKind.FieldVar(parameter.name, asmType)) Kind.DEBUG_LABEL -> findDebugLabel(parameter.name) } } private fun findOrdinary(kind: VariableKind.Ordinary): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search findLocalVariable(variables, kind, kind.name)?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this return findCapturedVariableInContainingThis(kind) } private fun findFieldVariable(kind: VariableKind.FieldVar): Result? { val thisObject = thisObject() if (thisObject != null) { val field = thisObject.referenceType().fieldByName(kind.fieldName) ?: return null return Result(thisObject.getValue(field)) } else { val containingType = frameProxy.safeLocation()?.declaringType() ?: return null val field = containingType.fieldByName(kind.fieldName) ?: return null return Result(containingType.getValue(field)) } } private fun findLocalFunction(kind: VariableKind.LocalFunction): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search, new convention val newConventionName = AsmUtil.LOCAL_FUNCTION_VARIABLE_PREFIX + kind.name findLocalVariable(variables, kind, newConventionName)?.let { return it } // Local variables – direct search, old convention (before 1.3.30) findLocalVariable(variables, kind, kind.name + "$")?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this return findCapturedVariableInContainingThis(kind) } private fun findCapturedVariableInContainingThis(kind: VariableKind): Result? { if (frameProxy is CoroutineStackFrameProxyImpl && frameProxy.isCoroutineScopeAvailable()) { findCapturedVariable(kind, frameProxy.thisObject())?.let { return it } return findCapturedVariable(kind, frameProxy.continuation) } val containingThis = thisObject() ?: return null return findCapturedVariable(kind, containingThis) } private fun findExtensionThis(kind: VariableKind.ExtensionThis): Result? { val variables = frameProxy.safeVisibleVariables() // Local variables – direct search val namePredicate = fun(name: String) = name == kind.parameterName || name.startsWith(kind.parameterName + '$') findLocalVariable(variables, kind, namePredicate)?.let { return it } // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } // Recursive search in captured this findCapturedVariableInContainingThis(kind)?.let { return it } @Suppress("ConstantConditionIf") if (USE_UNSAFE_FALLBACK) { // Find an unlabeled this with the compatible type findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it } } return null } private fun findDispatchThis(kind: VariableKind.OuterClassThis): Result? { findCapturedVariableInContainingThis(kind)?.let { return it } if (isInsideDefaultImpls()) { val variables = frameProxy.safeVisibleVariables() findLocalVariable(variables, kind, AsmUtil.THIS_IN_DEFAULT_IMPLS)?.let { return it } } val variables = frameProxy.safeVisibleVariables() val inlineDepth = getInlineDepth(variables) if (inlineDepth > 0) { variables.namedEntitySequence() .filter { it.name.matches(INLINED_THIS_REGEX) && getInlineDepth(it.name) == inlineDepth && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } } @Suppress("ConstantConditionIf") if (USE_UNSAFE_FALLBACK) { // Find an unlabeled this with the compatible type findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it } } return null } private fun findDebugLabel(name: String): Result? { val markupMap = DebugLabelPropertyDescriptorProvider.getMarkupMap(context.debugProcess) for ((value, markup) in markupMap) { if (markup.text == name) { return Result(value) } } return null } private fun findUnlabeledThis(kind: VariableKind.UnlabeledThis): Result? { val variables = frameProxy.safeVisibleVariables() // Recursive search in local receiver variables findCapturedVariableInReceiver(variables, kind)?.let { return it } return findCapturedVariableInContainingThis(kind) } private fun findLocalVariable(variables: List<LocalVariableProxyImpl>, kind: VariableKind, name: String): Result? { return findLocalVariable(variables, kind) { it == name } } private fun findLocalVariable( variables: List<LocalVariableProxyImpl>, kind: VariableKind, namePredicate: (String) -> Boolean ): Result? { val inlineDepth = getInlineDepth(variables) findLocalVariable(variables, kind, inlineDepth, namePredicate)?.let { return it } // Try to find variables outside of inline functions as well if (inlineDepth > 0 && USE_UNSAFE_FALLBACK) { findLocalVariable(variables, kind, 0, namePredicate)?.let { return it } } return null } private fun findLocalVariable( variables: List<LocalVariableProxyImpl>, kind: VariableKind, inlineDepth: Int, namePredicate: (String) -> Boolean ): Result? { val actualPredicate: (String) -> Boolean if (inlineDepth > 0) { actualPredicate = fun(name: String): Boolean { var endIndex = name.length var depth = 0 val suffixLen = INLINE_FUN_VAR_SUFFIX.length while (endIndex >= suffixLen) { if (name.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) { break } depth++ endIndex -= suffixLen } return namePredicate(name.take(endIndex)) && getInlineDepth(name) == inlineDepth } } else { actualPredicate = namePredicate } val namedEntities = variables.namedEntitySequence() + getCoroutineStackFrameNamedEntities() for (item in namedEntities) { if (!actualPredicate(item.name) || !kind.typeMatches(item.type)) { continue } val rawValue = item.value val result = evaluatorValueConverter.coerce(getUnwrapDelegate(kind, rawValue), kind.asmType) ?: continue if (!rawValue.isRefType && result.value.isRefType) { // Local variable was wrapped into a Ref instance mutableRefWrappers += RefWrapper(item.name, result.value) } return result } return null } private fun getCoroutineStackFrameNamedEntities() = if (frameProxy is CoroutineStackFrameProxyImpl) { frameProxy.spilledVariables.namedEntitySequence(context.evaluationContext) } else { emptySequence() } private fun isInsideDefaultImpls(): Boolean { val declaringType = frameProxy.safeLocation()?.declaringType() ?: return false return declaringType.name().endsWith(JvmAbi.DEFAULT_IMPLS_SUFFIX) } private fun findCoroutineContext(): Result? { val method = frameProxy.safeLocation()?.safeMethod() ?: return null val result = findCoroutineContextForLambda(method) ?: findCoroutineContextForMethod(method) ?: return null return Result(result) } private fun findCoroutineContextForLambda(method: Method): ObjectReference? { if (method.name() != "invokeSuspend" || method.signature() != "(Ljava/lang/Object;)Ljava/lang/Object;" || frameProxy !is CoroutineStackFrameProxyImpl) { return null } val continuation = frameProxy.continuation ?: return null val continuationType = continuation.referenceType() if (SUSPEND_LAMBDA_CLASSES.none { continuationType.isSubtype(it) }) { return null } return findCoroutineContextForContinuation(continuation) } private fun findCoroutineContextForMethod(method: Method): ObjectReference? { if (CONTINUATION_TYPE.descriptor + ")" !in method.signature()) { return null } val continuationVariable = frameProxy.safeVisibleVariableByName(CONTINUATION_VARIABLE_NAME) ?: frameProxy.safeVisibleVariableByName(SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME) ?: return null val continuation = frameProxy.getValue(continuationVariable) as? ObjectReference ?: return null return findCoroutineContextForContinuation(continuation) } private fun findCoroutineContextForContinuation(continuation: ObjectReference): ObjectReference? { val continuationType = (continuation.referenceType() as? ClassType) ?.allInterfaces()?.firstOrNull { it.name() == Continuation::class.java.name } ?: return null val getContextMethod = continuationType .methodsByName("getContext", "()Lkotlin/coroutines/CoroutineContext;").firstOrNull() ?: return null return context.invokeMethod(continuation, getContextMethod, emptyList()) as? ObjectReference } private fun findCapturedVariableInReceiver(variables: List<LocalVariableProxyImpl>, kind: VariableKind): Result? { fun isReceiverOrPassedThis(name: String) = name.startsWith(AsmUtil.LABELED_THIS_PARAMETER) || name == AsmUtil.RECEIVER_PARAMETER_NAME || name == AsmUtil.THIS_IN_DEFAULT_IMPLS || INLINED_THIS_REGEX.matches(name) if (kind is VariableKind.ExtensionThis) { variables.namedEntitySequence() .filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } } return variables.namedEntitySequence() .filter { isReceiverOrPassedThis(it.name) } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() } private fun findCapturedVariable(kind: VariableKind, parentFactory: () -> Value?): Result? { val parent = getUnwrapDelegate(kind, parentFactory()) return findCapturedVariable(kind, parent) } private fun findCapturedVariable(kind: VariableKind, parent: Value?): Result? { val acceptsParentValue = kind is VariableKind.UnlabeledThis || kind is VariableKind.OuterClassThis if (parent != null && acceptsParentValue && kind.typeMatches(parent.type())) { return Result(parent) } val fields = (parent as? ObjectReference)?.referenceType()?.fields() ?: return null if (kind !is VariableKind.OuterClassThis) { // Captured variables - direct search fields.namedEntitySequence(parent) .filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) } .mapNotNull { it.unwrapAndCheck(kind) } .firstOrNull() ?.let { return it } // Recursive search in captured receivers fields.namedEntitySequence(parent) .filter { isCapturedReceiverFieldName(it.name) } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() ?.let { return it } } // Recursive search in outer and captured this fields.namedEntitySequence(parent) .filter { it.name == AsmUtil.THIS_IN_DEFAULT_IMPLS || it.name == AsmUtil.CAPTURED_THIS_FIELD } .mapNotNull { findCapturedVariable(kind, it.value) } .firstOrNull() ?.let { return it } return null } private fun getUnwrapDelegate(kind: VariableKind, rawValue: Value?): Value? { if (kind !is VariableKind.Ordinary || !kind.isDelegated) { return rawValue } val delegateValue = rawValue as? ObjectReference ?: return rawValue val getValueMethod = delegateValue.referenceType() .methodsByName("getValue", "()Ljava/lang/Object;").firstOrNull() ?: return rawValue return context.invokeMethod(delegateValue, getValueMethod, emptyList()) } private fun isCapturedReceiverFieldName(name: String): Boolean { return name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD)) || name == AsmUtil.CAPTURED_RECEIVER_FIELD } private fun VariableKind.typeMatches(actualType: JdiType?): Boolean { if (this is VariableKind.Ordinary && isDelegated) { // We can't figure out the actual type of the value yet. // No worries: it will be checked again (and more carefully) in `unwrapAndCheck()`. return true } return evaluatorValueConverter.typeMatches(asmType, actualType) } private fun NamedEntity.unwrapAndCheck(kind: VariableKind): Result? { return evaluatorValueConverter.coerce(getUnwrapDelegate(kind, value), kind.asmType) } private fun List<Field>.namedEntitySequence(owner: ObjectReference): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, owner) } } private fun List<LocalVariableProxyImpl>.namedEntitySequence(): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, frameProxy) } } private fun List<JavaValue>.namedEntitySequence(context: EvaluationContextImpl): Sequence<NamedEntity> { return asSequence().map { NamedEntity.of(it, context) } } private fun thisObject(): ObjectReference? { val thisObjectFromEvaluation = context.evaluationContext.computeThisObject() as? ObjectReference if (thisObjectFromEvaluation != null) { return thisObjectFromEvaluation } return frameProxy.thisObject() } }
apache-2.0
4e586d3ce2d72b60820e4bbb7ef98360
41.79798
158
0.665471
5.409857
false
false
false
false
lucasgomes-eti/KotlinAndroidProjects
CollapsedToolbar/app/src/main/java/com/lucas/collapsedtoolbar/MainActivity.kt
1
3223
package com.lucas.collapsedtoolbar import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.content.ContextCompat import android.view.Menu import android.view.WindowManager import kotlinx.android.synthetic.main.activity_main.* import android.transition.TransitionManager import android.widget.FrameLayout import android.widget.LinearLayout class MainActivity : AppCompatActivity() { private var menu: Menu? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) } setSupportActionBar(toolbar) collapsingToolbar.title = getString(R.string.agrosig) collapsingToolbar.setExpandedTitleColor(ContextCompat.getColor(this, android.R.color.white)) collapsingToolbar.setContentScrimColor(ContextCompat.getColor(this, R.color.colorPrimary)) var isShow = false var scrollRange = -1 appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset -> if (scrollRange == -1) { scrollRange = appBarLayout.totalScrollRange } if (scrollRange + verticalOffset == 0) { isShow = true showOption(R.id.action_sincronizar) val layoutParams = FrameLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) layoutParams.topMargin = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { TransitionManager.beginDelayedTransition(tableMenu) } tableMenu.layoutParams = layoutParams } else { isShow = false val layoutParams = FrameLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) layoutParams.topMargin = 32 tableMenu.layoutParams = layoutParams if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { TransitionManager.beginDelayedTransition(tableMenu) } hideOption(R.id.action_sincronizar) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) this.menu = menu hideOption(R.id.action_sincronizar) return true } private fun hideOption(id: Int) { val item = menu?.findItem(id) item?.isVisible = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) } } private fun showOption(id: Int) { val item = menu?.findItem(id) item?.isVisible = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) } } }
cc0-1.0
d550ffcecb582c17c4bcd9627450b3ee
38.304878
103
0.647533
4.973765
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/input/entry/add/AddEntryActivity.kt
1
2189
package io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.api.suggest.SuggestApi import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigator import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity import io.github.feelfreelinux.wykopmobilny.utils.printout import kotlinx.android.synthetic.main.activity_write_comment.* import javax.inject.Inject class AddEntryActivity : BaseInputActivity<AddEntryPresenter>(), AddEntryActivityView { companion object { fun createIntent(context: Activity, receiver: String?, textBody: String? = null) = Intent(context, AddEntryActivity::class.java).apply { putExtra(EXTRA_BODY, textBody) putExtra(EXTRA_RECEIVER, receiver) } } @Inject override lateinit var suggestionApi: SuggestApi @Inject override lateinit var presenter: AddEntryPresenter val navigator by lazy { NewNavigator(this) as NewNavigatorApi } override fun openEntryActivity(id: Int) { navigator.openEntryDetailsActivity(id, false) finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter.subscribe(this) setupSuggestions() supportActionBar?.setTitle(R.string.add_new_entry) if (intent.action == Intent.ACTION_SEND && intent.type != null) { if (intent.type == "text/plain") { val text = intent.getStringExtra(Intent.EXTRA_TEXT) text?.let { textBody = text } } else if (intent!!.type!!.startsWith("image/")) { val imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM) as Uri? imageUri?.let { markupToolbar.photo = imageUri printout(imageUri.toString()) } } } } }
mit
63d558793ccb5c271076416101891855
36.758621
90
0.675651
4.738095
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/MaximizeEditorInSplitAction.kt
2
5726
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.IdeBundle import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.impl.EditorsSplitters import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ComponentUtil import com.intellij.ui.DrawUtil import com.intellij.util.SmartList import com.intellij.util.animation.JBAnimator import com.intellij.util.animation.animation import com.intellij.util.ui.UIUtil import java.awt.Component class MaximizeEditorInSplitAction : DumbAwareAction() { val myActiveAnimators = SmartList<JBAnimator>() init { templatePresentation.text = IdeBundle.message("action.maximize.editor") + "/" +IdeBundle.message("action.normalize.splits") } override fun actionPerformed(e: AnActionEvent) { val project = e.project if (project == null) return myActiveAnimators.forEach { Disposer.dispose(it) } myActiveAnimators.clear() val splittersToMaximize = getSplittersToMaximize(e) if (splittersToMaximize.isNotEmpty()) { splittersToMaximize.forEach { setProportion(project, it.first, if (it.second) it.first.maximumProportion else it.first.minimumProportion) } } else { val splittersToNormalize = getSplittersToNormalize(e) if (splittersToNormalize.isNotEmpty()) { splittersToNormalize.forEach { setProportion(project, it, .5f) } } } } fun setProportion(disposable : Disposable, splitter: Splitter, value: Float) { if (!Registry.`is`("ide.experimental.ui.animations") || DrawUtil.isSimplifiedUI()) { splitter.proportion = value return } val animator = JBAnimator(disposable).also { myActiveAnimators.add(it) } animator.animate( animation(splitter.proportion, value, splitter::setProportion).apply { duration = 350 runWhenExpiredOrCancelled { Disposer.dispose(animator) myActiveAnimators.remove(animator) } } ) } override fun update(event: AnActionEvent) { val presentation = event.presentation presentation.isEnabled = true val splittersToMaximize = getSplittersToMaximize(event) if (splittersToMaximize.isNotEmpty()) { presentation.text = IdeBundle.message("action.maximize.editor") presentation.putClientProperty(CURRENT_STATE_IS_MAXIMIZED_KEY, false) return } val splittersToNormalize = getSplittersToNormalize(event) if (splittersToNormalize.isNotEmpty()) { presentation.text = IdeBundle.message("action.normalize.splits") presentation.putClientProperty(CURRENT_STATE_IS_MAXIMIZED_KEY, true) return } presentation.isEnabled = false } companion object { val CURRENT_STATE_IS_MAXIMIZED_KEY = Key.create<Boolean>("CURRENT_STATE_IS_MAXIMIZED") fun getSplittersToMaximize(project: Project, editorComponent: Component?): Set<Pair<Splitter, Boolean>> { val editorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return emptySet() val set = HashSet<Pair<Splitter, Boolean>>() var comp = editorComponent while (comp != editorManager.mainSplitters && comp != null) { val parent = comp.parent if (parent is Splitter && UIUtil.isClientPropertyTrue(parent, EditorsSplitters.SPLITTER_KEY)) { if (parent.firstComponent == comp) { if (parent.proportion < parent.maximumProportion) { set.add(Pair(parent, true)) } } else { if (parent.proportion > parent.minimumProportion) { set.add(Pair(parent, false)) } } } comp = parent } return set } private fun getEditorComponent(e: AnActionEvent): Component? { with(e.getData(PlatformDataKeys.CONTEXT_COMPONENT)) { return if (ComponentUtil.getParentOfType<Any>(EditorsSplitters::class.java, this) != null) this else null } } fun getSplittersToMaximize(e: AnActionEvent): Set<Pair<Splitter, Boolean>> { val project = e.project val editorComponent = getEditorComponent(e) if (project == null || editorComponent == null) { return emptySet() } return getSplittersToMaximize(project, editorComponent) } fun getSplittersToNormalize(e: AnActionEvent): Set<Splitter> { val project = e.project val editorComponent = getEditorComponent(e) if (project == null || editorComponent == null /*|| !e.isRelatedToSplits()*/) { return emptySet() } val set = HashSet<Splitter>() var splitters = ComponentUtil.getParentOfType(EditorsSplitters::class.java, editorComponent) while (splitters != null) { val candidate = ComponentUtil.getParentOfType(EditorsSplitters::class.java, splitters.parent) splitters = candidate ?: break } if (splitters != null) { val splitterList = UIUtil.findComponentsOfType(splitters, Splitter::class.java) splitterList.removeIf { !UIUtil.isClientPropertyTrue(it, EditorsSplitters.SPLITTER_KEY) } set.addAll(splitterList) } return set } } }
apache-2.0
29bf21668283abb14e88118eb507d721
37.695946
140
0.706252
4.678105
false
false
false
false
jwren/intellij-community
plugins/search-everywhere-ml/test/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereRankingModelTest.kt
1
4448
package com.intellij.ide.actions.searcheverywhere.ml import com.intellij.ide.actions.searcheverywhere.FoundItemDescriptor import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereElementFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereFileFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereModelProvider import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereRankingModel import com.intellij.ide.util.gotoByName.ChooseByNameModel import com.intellij.ide.util.gotoByName.ChooseByNamePopup import com.intellij.ide.util.gotoByName.ChooseByNameViewModel import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.mock.MockProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFileManager internal abstract class SearchEverywhereRankingModelTest : HeavyFeaturesProviderTestCase<SearchEverywhereFileFeaturesProvider>(SearchEverywhereFileFeaturesProvider::class.java) { abstract val tab: SearchEverywhereTabWithMl private val featuresProviders by lazy { SearchEverywhereElementFeaturesProvider.getFeatureProviders() } protected val model by lazy { SearchEverywhereRankingModel(SearchEverywhereModelProvider().getModel(tab.tabId)) } protected val mockProgressIndicator by lazy { MockProgressIndicator() } protected abstract fun filterElements(searchQuery: String): List<FoundItemDescriptor<*>> protected fun performSearchFor(searchQuery: String, featuresProviderCache: Any? = null): RankingAssertion { VirtualFileManager.getInstance().syncRefresh() val rankedElements: List<FoundItemDescriptor<*>> = filterElements(searchQuery) .map { it.withMlWeight(getMlWeight(it, searchQuery, featuresProviderCache)) } .sortedByDescending { it.mlWeight } assert(rankedElements.size > 1) { "Found ${rankedElements.size} which is unsuitable for ranking assertions" } return RankingAssertion(rankedElements) } private fun getMlWeight(item: FoundItemDescriptor<*>, searchQuery: String, featuresProviderCache: Any?) = model.predict(getElementFeatures(item, searchQuery, featuresProviderCache)) private fun getElementFeatures(foundItem: FoundItemDescriptor<*>, searchQuery: String, featuresProviderCache: Any?): Map<String, Any?> { return featuresProviders.map { val features = it.getElementFeatures(foundItem.item, System.currentTimeMillis(), searchQuery, foundItem.weight, featuresProviderCache) val featuresAsMap = hashMapOf<String, Any?>() for (feature in features) { featuresAsMap[feature.field.name] = feature.data } featuresAsMap }.fold(emptyMap()) { acc, value -> acc + value } } private fun FoundItemDescriptor<*>.withMlWeight(mlWeight: Double) = FoundItemDescriptor(this.item, this.weight, mlWeight) protected class RankingAssertion(private val results: List<FoundItemDescriptor<*>>) { fun thenAssertElement(element: FoundItemDescriptor<*>) = ElementAssertion(element) fun findElementAndAssert(predicate: (FoundItemDescriptor<*>) -> Boolean) = ElementAssertion(results.find(predicate)!!) inner class ElementAssertion(private val element: FoundItemDescriptor<*>) { fun isWithinTop(n: Int) { val errorMessage = "The index of the element is actually ${results.indexOf(element)}, it's not within the top $n." val top = n.coerceAtMost(results.size) assertTrue(errorMessage, results.subList(0, top).contains(element)) } fun isAtIndex(index: Int) { val errorMessage = "The index of the element is actually ${results.indexOf(element)}, not ${index} as expected." assertEquals(errorMessage, element, results[index]) } } } protected inner class StubChooseByNameViewModel(private val model: ChooseByNameModel) : ChooseByNameViewModel { override fun getProject(): Project = [email protected] override fun getModel(): ChooseByNameModel = model override fun isSearchInAnyPlace() = model.useMiddleMatching() override fun transformPattern(pattern: String) = ChooseByNamePopup.getTransformedPattern(pattern, model) override fun canShowListForEmptyPattern() = false override fun getMaximumListSizeLimit() = 0 } }
apache-2.0
bdfb2cc873cfefd06c53d224fc50b158
50.732558
140
0.765513
5.166086
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/actions/branch/GitCheckoutFromInputAction.kt
2
1553
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.actions.branch import com.intellij.dvcs.DvcsUtil.disableActionIfAnyRepositoryIsFresh import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import git4idea.branch.GitBrancher import git4idea.i18n.GitBundle import git4idea.ui.branch.GitRefDialog class GitCheckoutFromInputAction : DumbAwareAction(GitBundle.messagePointer("branches.checkout.tag.or.revision")) { override fun update(e: AnActionEvent) { val project = e.project val repositories = e.getData(GitBranchActionsUtil.REPOSITORIES_KEY) e.presentation.isEnabledAndVisible = project != null && !repositories.isNullOrEmpty() disableActionIfAnyRepositoryIsFresh(e, repositories.orEmpty(), GitBundle.message("action.not.possible.in.fresh.repo.checkout")) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val repositories = e.getRequiredData(GitBranchActionsUtil.REPOSITORIES_KEY) // TODO: on type check ref validity, on OK check ref existence. val dialog = GitRefDialog(project, repositories, GitBundle.message("branches.checkout"), GitBundle.message("branches.enter.reference.branch.tag.name.or.commit.hash")) if (dialog.showAndGet()) { val reference = dialog.reference GitBrancher.getInstance(project).checkout(reference, true, repositories, null) } } }
apache-2.0
076fc6785bb463f4868c04c80af54adc
43.4
131
0.752737
4.437143
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/adapters/MyRecyclerViewAdapter.kt
1
12085
package com.simplemobiletools.commons.adapters import android.graphics.Color import android.view.* import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.ActionBar import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.interfaces.MyActionModeCallback import com.simplemobiletools.commons.views.MyRecyclerView abstract class MyRecyclerViewAdapter(val activity: BaseSimpleActivity, val recyclerView: MyRecyclerView, val itemClick: (Any) -> Unit) : RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>() { protected val baseConfig = activity.baseConfig protected val resources = activity.resources!! protected val layoutInflater = activity.layoutInflater protected var textColor = activity.getProperTextColor() protected var backgroundColor = activity.getProperBackgroundColor() protected var properPrimaryColor = activity.getProperPrimaryColor() protected var contrastColor = properPrimaryColor.getContrastColor() protected var actModeCallback: MyActionModeCallback protected var selectedKeys = LinkedHashSet<Int>() protected var positionOffset = 0 protected var actMode: ActionMode? = null private var actBarTextView: TextView? = null private var lastLongPressedItem = -1 abstract fun getActionMenuId(): Int abstract fun prepareActionMode(menu: Menu) abstract fun actionItemPressed(id: Int) abstract fun getSelectableItemCount(): Int abstract fun getIsItemSelectable(position: Int): Boolean abstract fun getItemSelectionKey(position: Int): Int? abstract fun getItemKeyPosition(key: Int): Int abstract fun onActionModeCreated() abstract fun onActionModeDestroyed() protected fun isOneItemSelected() = selectedKeys.size == 1 init { actModeCallback = object : MyActionModeCallback() { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { actionItemPressed(item.itemId) return true } override fun onCreateActionMode(actionMode: ActionMode, menu: Menu?): Boolean { if (getActionMenuId() == 0) { return true } selectedKeys.clear() isSelectable = true actMode = actionMode actBarTextView = layoutInflater.inflate(R.layout.actionbar_title, null) as TextView actBarTextView!!.layoutParams = ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT) actMode!!.customView = actBarTextView actBarTextView!!.setOnClickListener { if (getSelectableItemCount() == selectedKeys.size) { finishActMode() } else { selectAll() } } activity.menuInflater.inflate(getActionMenuId(), menu) val bgColor = if (baseConfig.isUsingSystemTheme) { resources.getColor(R.color.you_contextual_status_bar_color, activity.theme) } else { Color.BLACK } actBarTextView!!.setTextColor(bgColor.getContrastColor()) activity.updateMenuItemColors(menu, baseColor = bgColor) onActionModeCreated() if (baseConfig.isUsingSystemTheme) { actBarTextView?.onGlobalLayout { val backArrow = activity.findViewById<ImageView>(R.id.action_mode_close_button) backArrow?.applyColorFilter(bgColor.getContrastColor()) } } return true } override fun onPrepareActionMode(actionMode: ActionMode, menu: Menu): Boolean { prepareActionMode(menu) return true } override fun onDestroyActionMode(actionMode: ActionMode) { isSelectable = false (selectedKeys.clone() as HashSet<Int>).forEach { val position = getItemKeyPosition(it) if (position != -1) { toggleItemSelection(false, position, false) } } updateTitle() selectedKeys.clear() actBarTextView?.text = "" actMode = null lastLongPressedItem = -1 onActionModeDestroyed() } } } protected fun toggleItemSelection(select: Boolean, pos: Int, updateTitle: Boolean = true) { if (select && !getIsItemSelectable(pos)) { return } val itemKey = getItemSelectionKey(pos) ?: return if ((select && selectedKeys.contains(itemKey)) || (!select && !selectedKeys.contains(itemKey))) { return } if (select) { selectedKeys.add(itemKey) } else { selectedKeys.remove(itemKey) } notifyItemChanged(pos + positionOffset) if (updateTitle) { updateTitle() } if (selectedKeys.isEmpty()) { finishActMode() } } private fun updateTitle() { val selectableItemCount = getSelectableItemCount() val selectedCount = Math.min(selectedKeys.size, selectableItemCount) val oldTitle = actBarTextView?.text val newTitle = "$selectedCount / $selectableItemCount" if (oldTitle != newTitle) { actBarTextView?.text = newTitle actMode?.invalidate() } } fun itemLongClicked(position: Int) { recyclerView.setDragSelectActive(position) lastLongPressedItem = if (lastLongPressedItem == -1) { position } else { val min = Math.min(lastLongPressedItem, position) val max = Math.max(lastLongPressedItem, position) for (i in min..max) { toggleItemSelection(true, i, false) } updateTitle() position } } protected fun getSelectedItemPositions(sortDescending: Boolean = true): ArrayList<Int> { val positions = ArrayList<Int>() val keys = selectedKeys.toList() keys.forEach { val position = getItemKeyPosition(it) if (position != -1) { positions.add(position) } } if (sortDescending) { positions.sortDescending() } return positions } protected fun selectAll() { val cnt = itemCount - positionOffset for (i in 0 until cnt) { toggleItemSelection(true, i, false) } lastLongPressedItem = -1 updateTitle() } protected fun setupDragListener(enable: Boolean) { if (enable) { recyclerView.setupDragListener(object : MyRecyclerView.MyDragListener { override fun selectItem(position: Int) { toggleItemSelection(true, position, true) } override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) { selectItemRange( initialSelection, Math.max(0, lastDraggedIndex - positionOffset), Math.max(0, minReached - positionOffset), maxReached - positionOffset ) if (minReached != maxReached) { lastLongPressedItem = -1 } } }) } else { recyclerView.setupDragListener(null) } } protected fun selectItemRange(from: Int, to: Int, min: Int, max: Int) { if (from == to) { (min..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) } return } if (to < from) { for (i in to..from) { toggleItemSelection(true, i, true) } if (min > -1 && min < to) { (min until to).filter { it != from }.forEach { toggleItemSelection(false, it, true) } } if (max > -1) { for (i in from + 1..max) { toggleItemSelection(false, i, true) } } } else { for (i in from..to) { toggleItemSelection(true, i, true) } if (max > -1 && max > to) { (to + 1..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) } } if (min > -1) { for (i in min until from) { toggleItemSelection(false, i, true) } } } } fun setupZoomListener(zoomListener: MyRecyclerView.MyZoomListener?) { recyclerView.setupZoomListener(zoomListener) } fun addVerticalDividers(add: Boolean) { if (recyclerView.itemDecorationCount > 0) { recyclerView.removeItemDecorationAt(0) } if (add) { DividerItemDecoration(activity, DividerItemDecoration.VERTICAL).apply { setDrawable(resources.getDrawable(R.drawable.divider)) recyclerView.addItemDecoration(this) } } } fun finishActMode() { actMode?.finish() } fun updateTextColor(textColor: Int) { this.textColor = textColor notifyDataSetChanged() } fun updatePrimaryColor() { properPrimaryColor = activity.getProperPrimaryColor() contrastColor = properPrimaryColor.getContrastColor() } fun updateBackgroundColor(backgroundColor: Int) { this.backgroundColor = backgroundColor } protected fun createViewHolder(layoutType: Int, parent: ViewGroup?): ViewHolder { val view = layoutInflater.inflate(layoutType, parent, false) return ViewHolder(view) } protected fun bindViewHolder(holder: ViewHolder) { holder.itemView.tag = holder } protected fun removeSelectedItems(positions: ArrayList<Int>) { positions.forEach { notifyItemRemoved(it) } finishActMode() } open inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bindView(any: Any, allowSingleClick: Boolean, allowLongClick: Boolean, callback: (itemView: View, adapterPosition: Int) -> Unit): View { return itemView.apply { callback(this, adapterPosition) if (allowSingleClick) { setOnClickListener { viewClicked(any) } setOnLongClickListener { if (allowLongClick) viewLongClicked() else viewClicked(any); true } } else { setOnClickListener(null) setOnLongClickListener(null) } } } fun viewClicked(any: Any) { if (actModeCallback.isSelectable) { val currentPosition = adapterPosition - positionOffset val isSelected = selectedKeys.contains(getItemSelectionKey(currentPosition)) toggleItemSelection(!isSelected, currentPosition, true) } else { itemClick.invoke(any) } lastLongPressedItem = -1 } fun viewLongClicked() { val currentPosition = adapterPosition - positionOffset if (!actModeCallback.isSelectable) { activity.startActionMode(actModeCallback) } toggleItemSelection(true, currentPosition, true) itemLongClicked(currentPosition) } } }
gpl-3.0
4873be9790a108c8c1e7cd0e137bb1b9
33.727011
148
0.581134
5.705855
false
false
false
false
androidx/androidx
privacysandbox/tools/tools-core/src/test/java/androidx/privacysandbox/tools/core/validator/ModelValidatorTest.kt
3
15830
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.privacysandbox.tools.core.validator import androidx.privacysandbox.tools.core.model.AnnotatedInterface import androidx.privacysandbox.tools.core.model.AnnotatedValue import androidx.privacysandbox.tools.core.model.Method import androidx.privacysandbox.tools.core.model.Parameter import androidx.privacysandbox.tools.core.model.ParsedApi import androidx.privacysandbox.tools.core.model.Type import androidx.privacysandbox.tools.core.model.Types import androidx.privacysandbox.tools.core.model.ValueProperty import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ModelValidatorTest { @Test fun validModel_ok() { val api = ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "doStuff", parameters = listOf( Parameter( name = "x", type = Types.int ), Parameter( name = "foo", type = Type(packageName = "com.mysdk", simpleName = "Foo") ), Parameter( name = "callback", type = Type( packageName = "com.mysdk", simpleName = "MySdkCallback" ) ), Parameter( name = "myInterface", type = Type( packageName = "com.mysdk", simpleName = "MyInterface" ) ), ), returnType = Types.string, isSuspend = true, ), Method( name = "fireAndForget", parameters = listOf(), returnType = Types.unit, isSuspend = false, ) ) ) ), values = setOf( AnnotatedValue( type = Type(packageName = "com.mysdk", simpleName = "Foo"), properties = listOf( ValueProperty( name = "bar", type = Type(packageName = "com.mysdk", simpleName = "Bar"), ) ), ), AnnotatedValue( type = Type(packageName = "com.mysdk", simpleName = "Bar"), properties = emptyList(), ) ), callbacks = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdkCallback"), methods = listOf( Method( name = "onComplete", parameters = listOf( Parameter( name = "result", type = Types.int ), ), returnType = Types.unit, isSuspend = false, ), ) ) ), interfaces = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MyInterface"), methods = listOf( Method( name = "doStuff", parameters = listOf( Parameter( name = "x", type = Types.int ), Parameter( name = "foo", type = Type(packageName = "com.mysdk", simpleName = "Foo") ), Parameter( name = "callback", type = Type( packageName = "com.mysdk", simpleName = "MySdkCallback" ) ), ), returnType = Types.string, isSuspend = true, ), Method( name = "fireAndForget", parameters = listOf(), returnType = Types.unit, isSuspend = false, ) ) ) ), ) assertThat(ModelValidator.validate(api).isSuccess).isTrue() } @Test fun multipleServices_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface(type = Type(packageName = "com.mysdk", simpleName = "MySdk")), AnnotatedInterface(type = Type(packageName = "com.mysdk", simpleName = "MySdk2")), ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Multiple services are not supported. Found: com.mysdk.MySdk, com.mysdk.MySdk2." ) } @Test fun nonSuspendFunctionReturningValue_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "returnSomethingNow", parameters = listOf(), returnType = Types.string, isSuspend = false, ), Method( name = "returnSomethingElseNow", parameters = listOf(), returnType = Types.int, isSuspend = false, ), Method( name = "returnNothingNow", parameters = listOf(), returnType = Types.unit, isSuspend = false, ), Method( name = "returnSomethingLater", parameters = listOf(), returnType = Types.string, isSuspend = true, ), ), ), ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.MySdk.returnSomethingNow: functions with return values " + "should be suspending functions.", "Error in com.mysdk.MySdk.returnSomethingElseNow: functions with return values " + "should be suspending functions." ) } @Test fun invalidParameterOrReturnType_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "returnFoo", parameters = listOf(), returnType = Type(packageName = "com.mysdk", simpleName = "Foo"), isSuspend = true, ), Method( name = "receiveFoo", parameters = listOf( Parameter( name = "foo", type = Type(packageName = "com.mysdk", simpleName = "Foo") ) ), returnType = Types.unit, isSuspend = true, ), ), ), ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.MySdk.returnFoo: only primitives, lists, data classes annotated " + "with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxInterface are supported as return types.", "Error in com.mysdk.MySdk.receiveFoo: only primitives, lists, data classes " + "annotated with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxCallback or @PrivacySandboxInterface are supported as parameter " + "types." ) } @Test fun nestedList_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "processNestedList", parameters = listOf( Parameter( name = "foo", type = Types.list(Types.list(Types.int)) ) ), returnType = Types.unit, isSuspend = true, ), ), ), ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.MySdk.processNestedList: only primitives, lists, data classes " + "annotated with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxCallback or @PrivacySandboxInterface are supported as " + "parameter types." ) } @Test fun valueWithIllegalProperty_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface(type = Type(packageName = "com.mysdk", simpleName = "MySdk")), ), values = setOf( AnnotatedValue( type = Type(packageName = "com.mysdk", simpleName = "Foo"), properties = listOf( ValueProperty("bar", Type("com.mysdk", "Bar")) ) ) ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.Foo.bar: only primitives, lists, data classes annotated with " + "@PrivacySandboxValue and interfaces annotated with @PrivacySandboxInterface " + "are supported as properties." ) } @Test fun callbackWithNonFireAndForgetMethod_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface(type = Type(packageName = "com.mysdk", simpleName = "MySdk")), ), callbacks = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdkCallback"), methods = listOf( Method( name = "suspendMethod", parameters = listOf(), returnType = Types.unit, isSuspend = true, ), Method( name = "methodWithReturnValue", parameters = listOf(), returnType = Types.int, isSuspend = false, ), ) ) ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.MySdkCallback.suspendMethod: callback methods should be " + "non-suspending and have no return values.", "Error in com.mysdk.MySdkCallback.methodWithReturnValue: callback methods should be " + "non-suspending and have no return values.", ) } @Test fun callbackReceivingCallbacks_throws() { val api = ParsedApi( services = setOf( AnnotatedInterface(type = Type(packageName = "com.mysdk", simpleName = "MySdk")), ), callbacks = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdkCallback"), methods = listOf( Method( name = "foo", parameters = listOf( Parameter("otherCallback", Type("com.mysdk", "MySdkCallback")) ), returnType = Types.unit, isSuspend = false, ), ) ) ) ) val validationResult = ModelValidator.validate(api) assertThat(validationResult.isFailure).isTrue() assertThat(validationResult.errors).containsExactly( "Error in com.mysdk.MySdkCallback.foo: only primitives, lists, data classes " + "annotated with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxInterface are supported as callback parameter types." ) } }
apache-2.0
7e17b02e86513fadbb5d17872bf8764a
41.328877
99
0.433228
6.654056
false
false
false
false
pbreault/adb-idea
src/main/kotlin/com/developerphil/adbidea/adb/command/receiver/GenericReceiver.kt
1
1053
package com.developerphil.adbidea.adb.command.receiver import com.android.ddmlib.MultiLineReceiver import java.util.* import java.util.regex.Pattern class GenericReceiver : MultiLineReceiver() { val adbOutputLines: MutableList<String> = ArrayList() private var errorMessage: String? = null override fun processNewLines(lines: Array<String>) { adbOutputLines.addAll(listOf(*lines)) for (line in lines) { if (line.isNotEmpty()) { errorMessage = if (line.startsWith(SUCCESS_OUTPUT)) { null } else { val m = FAILURE_PATTERN.matcher(line) if (m.matches()) { m.group(1) } else { "Unknown failure" } } } } } override fun isCancelled() = false } private const val SUCCESS_OUTPUT = "Success" //$NON-NLS-1$ private val FAILURE_PATTERN = Pattern.compile("Failure\\s+\\[(.*)\\]") //$NON-NLS-1$
apache-2.0
cba239a520112f1d8941bebf435793b7
29.085714
84
0.547958
4.519313
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertEnumToSealedClassIntention.kt
1
7290
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.util.withExpectedActuals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe /** * Tests: * [org.jetbrains.kotlin.idea.intentions.IntentionTestGenerated.ConvertEnumToSealedClass] */ class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.sealed.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.getClassKeyword() == null) return null val nameIdentifier = element.nameIdentifier ?: return null val enumKeyword = element.modifierList?.getModifier(KtTokens.ENUM_KEYWORD) ?: return null return TextRange(enumKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val name = element.name ?: return if (name.isEmpty()) return val doesSupportDataObjects = element.languageVersionSettings.supportsFeature(LanguageFeature.DataObjects) for (klass in element.withExpectedActuals()) { if (klass !is KtClass) continue val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue val isExpect = classDescriptor.isExpect val isActual = classDescriptor.isActual klass.removeModifier(KtTokens.ENUM_KEYWORD) klass.addModifier(KtTokens.SEALED_KEYWORD) val psiFactory = KtPsiFactory(klass) val objects = mutableListOf<KtObjectDeclaration>() for (member in klass.declarations) { if (member !is KtEnumEntry) continue val obj = psiFactory.createDeclaration<KtObjectDeclaration>( listOfNotNull( "data".takeIf { doesSupportDataObjects }, "object", member.name, ).joinToString(" ") ) val initializers = member.initializerList?.initializers ?: emptyList() if (initializers.isNotEmpty()) { initializers.forEach { obj.addSuperTypeListEntry(psiFactory.createSuperTypeCallEntry("${klass.name}${it.text}")) } } else { val defaultEntry = if (isExpect) psiFactory.createSuperTypeEntry(name) else psiFactory.createSuperTypeCallEntry("$name()") obj.addSuperTypeListEntry(defaultEntry) } if (isActual) { obj.addModifier(KtTokens.ACTUAL_KEYWORD) } member.body?.let { body -> obj.add(body) } obj.addComments(member) member.delete() klass.addDeclaration(obj) objects.add(obj) } if (element.platform.isJvm()) { val enumEntryNames = objects.map { it.nameAsSafeName.asString() } val targetClassName = klass.name if (enumEntryNames.isNotEmpty() && targetClassName != null) { val companionObject = klass.getOrCreateCompanionObject() companionObject.addValuesFunction(targetClassName, enumEntryNames, psiFactory) companionObject.addValueOfFunction(targetClassName, classDescriptor, enumEntryNames, psiFactory) } } klass.body?.let { body -> body.allChildren .takeWhile { it !is KtDeclaration } .firstOrNull { it.node.elementType == KtTokens.SEMICOLON } ?.let { semicolon -> val nonWhiteSibling = semicolon.siblings(forward = true, withItself = false).firstOrNull { it !is PsiWhiteSpace } body.deleteChildRange(semicolon, nonWhiteSibling?.prevSibling ?: semicolon) if (nonWhiteSibling != null) { CodeStyleManager.getInstance(klass.project).reformat(nonWhiteSibling.firstChild ?: nonWhiteSibling) } } } } } private fun KtObjectDeclaration.addValuesFunction(targetClassName: String, enumEntryNames: List<String>, psiFactory: KtPsiFactory) { val functionText = "fun values(): Array<${targetClassName}> { return arrayOf(${enumEntryNames.joinToString()}) }" addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addValueOfFunction( targetClassName: String, classDescriptor: ClassDescriptor, enumEntryNames: List<String>, psiFactory: KtPsiFactory ) { val classFqName = classDescriptor.fqNameSafe.asString() val functionText = buildString { append("fun valueOf(value: String): $targetClassName {") append("return when(value) {") enumEntryNames.forEach { append("\"$it\" -> $it\n") } append("else -> throw IllegalArgumentException(\"No object $classFqName.\$value\")") append("}") append("}") } addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addComments(enumEntry: KtEnumEntry) { val (headComments, tailComments) = enumEntry.allChildren.toList().let { children -> children.takeWhile { it.isCommentOrWhiteSpace() } to children.takeLastWhile { it.isCommentOrWhiteSpace() } } if (headComments.isNotEmpty()) { val anchor = this.allChildren.first() headComments.forEach { addBefore(it, anchor) } } if (tailComments.isNotEmpty()) { val anchor = this.allChildren.last() tailComments.reversed().forEach { addAfter(it, anchor) } } } private fun PsiElement.isCommentOrWhiteSpace() = this is PsiComment || this is PsiWhiteSpace }
apache-2.0
1c668418f0adfb09e554a308ade12bcf
44.279503
158
0.651852
5.464768
false
false
false
false